code
stringlengths
2
1.05M
/** ! * Created by EYHN on 2017/4/17. https://github.com/EYHN * 修改自 sexdevil/LSLoader https://github.com/sexdevil/LSLoader */ (function () { window.lsloader = { jsRunSequence: [], //js 运行队列 {name:代码name,code:代码,status:状态 failed/loading/comboJS,path:线上路径} jsnamemap: {}, //js name map 防fallback 重复请求资源 cssnamemap: {} //css name map 防fallback 重复请求资源 }; /* * 封装localStorage get set remove 方法 * try catch保证ls写满或者不支持本地缓存环境能继续运行js * */ lsloader.removeLS = function (key) { try { localStorage.removeItem(key) } catch (e) { } }; lsloader.setLS = function (key, val) { try { localStorage.setItem(key, val); } catch (e) { } } lsloader.getLS = function (key) { var val = '' try { val = localStorage.getItem(key); } catch (e) { val = ''; } return val } versionString = "/*" + (window.materialVersion || 'unknownVersion') + "*/"; lsloader.clean = function () { try { var keys = []; for (var i = 0; i < localStorage.length; i++) { keys.push(localStorage.key(i)) } keys.forEach(function (key) { var data = lsloader.getLS(key); if (window.oldVersion) { var remove = window.oldVersion.reduce(function(p,c) { return p || data.indexOf('/*' + c + '*/') !== -1 }, false) if (remove) { lsloader.removeLS(key); } } }) } catch (e) { } } lsloader.clean(); /* * load资源 * name 作为key path/分割符/代码值 作为value ,存储资源 * 如果value值中取出的版本号和线上模版的一致,命中缓存用本地, * 否则 调用requestResource 请求资源 * jsname 文件name值,取相对路径,对应存在localStroage里的key * jspath 文件线上路径,带md5版本号,用于加载资源,区分资源版本 * cssonload css加载成功时候调用,用于配合页面展现 * */ lsloader.load = function (jsname, jspath, cssonload, isJs) { if (typeof cssonload === 'boolean') { isJs = cssonload; cssonload = undefined; } isJs = isJs || false; cssonload = cssonload || function () { }; var code; code = this.getLS(jsname); if (code && code.indexOf(versionString) === -1) { //ls 版本 codestartv* 每次换这个版本 所有ls作废 this.removeLS(jsname); this.requestResource(jsname, jspath, cssonload, isJs); return } //取出对应文件名下的code if (code) { var versionNumber = code.split(versionString)[0]; //取出路径版本号 如果要加载的和ls里的不同,清理,重写 if (versionNumber != jspath) { console.log("reload:" + jspath) this.removeLS(jsname); this.requestResource(jsname, jspath, cssonload, isJs); return } code = code.split(versionString)[1]; if (isJs) { this.jsRunSequence.push({ name: jsname, code: code }) this.runjs(jspath, jsname, code); } else { document.getElementById(jsname).appendChild(document.createTextNode(code)); cssonload(); } } else { //null xhr获取资源 this.requestResource(jsname, jspath, cssonload, isJs); } }; /* * load请求资源 * 根据文件名尾部不同加载,js走runjs方法,加入运行队列中 * css 直接加载并且写入对应的<style>标签,根据style的顺序 * 保证css能正确覆盖规则 css 加载成功后调用cssonload 帮助控制 * 异步加载样式造车的dom树渲染错乱问题 * */ lsloader.requestResource = function (name, path, cssonload, isJs) { var that = this if (isJs) { this.iojs(path, name, function (path, name, code) { that.setLS(name, path + versionString + code) that.runjs(path, name, code); }) } else { this.iocss(path, name, function (code) { document.getElementById(name).appendChild(document.createTextNode(code)); that.setLS(name, path + versionString + code) }, cssonload) } }; /* * iojs * 请求js资源,失败后调用jsfallback * */ lsloader.iojs = function (path, jsname, callback) { var that = this; that.jsRunSequence.push({ name: jsname, code: '' }) try { var xhr = new XMLHttpRequest(); xhr.open("get", path, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { if (xhr.response != '') { callback(path, jsname, xhr.response); return; } } that.jsfallback(path, jsname); } }; xhr.send(null); } catch (e) { that.jsfallback(path, jsname); } }; /* * iocss * 请求css资源,失败后调用cssfallback * */ lsloader.iocss = function (path, jsname, callback, cssonload) { var that = this; try { var xhr = new XMLHttpRequest(); xhr.open("get", path, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { if (xhr.response != '') { callback(xhr.response); cssonload(); return; } } that.cssfallback(path, jsname, cssonload); } }; xhr.send(null); } catch (e) { that.cssfallback(path, jsname, cssonload); } }; lsloader.iofonts = function (path, jsname, callback, cssonload) { var that = this; try { var xhr = new XMLHttpRequest(); xhr.open("get", path, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { if (xhr.response != '') { callback(xhr.response); cssonload(); return; } } that.cssfallback(path, jsname, cssonload); } }; xhr.send(null); } catch (e) { that.cssfallback(path, jsname, cssonload); } }; /* * runjs * 运行js主方法 * path js线上路径 * name js相对路径 * code js代码 * */ lsloader.runjs = function (path, name, code) { //如果有 name code ,xhr来的结果,写入ls 否则是script.onload调用 if (!!name && !!code) { for (var k in this.jsRunSequence) { if (this.jsRunSequence[k].name == name) { this.jsRunSequence[k].code = code; } } } if (!!this.jsRunSequence[0] && !!this.jsRunSequence[0].code && this.jsRunSequence[0].status != 'failed') { //每次进入runjs检查jsRunSequence,如果第一项有代码并且状态没被置为failed,执行并剔除队列,回调 var script = document.createElement('script'); script.appendChild(document.createTextNode(this.jsRunSequence[0].code)); script.type = 'text/javascript'; document.getElementsByTagName('head')[0].appendChild(script); this.jsRunSequence.shift(); //如果jsSequence还有排队的 继续运行 if (this.jsRunSequence.length > 0) { this.runjs(); } } else if (!!this.jsRunSequence[0] && this.jsRunSequence[0].status == 'failed') { /*每次进入runjs检查jsRunSequence,如果第一项存在并且状态为failed,用script标签异步加载, * 并且该项status置为loading 其他资源加载调用runjs时候就不会通过这个js项,等候完成 */ var that = this; var script = document.createElement('script'); script.src = this.jsRunSequence[0].path; script.type = 'text/javascript'; this.jsRunSequence[0].status = 'loading' script.onload = function () { that.jsRunSequence.shift(); //如果jsSequence还有排队的 继续运行 if (that.jsRunSequence.length > 0) { that.runjs(); } }; document.body.appendChild(script); } } /* * tagLoad 用script标签加载不支持xhr请求的js资源 * 方法时jsRunSequence队列中添加一项name path为该资源,但是status=failed的项 * runjs调用检查时就会把这个项当作失败取用script标签请求 * */ lsloader.tagLoad = function (path, name) { this.jsRunSequence.push({ name: name, code: '', path: path, status: 'failed' }); this.runjs(); } //js回退加载 this.jsnamemap[name] 存在 证明已经在队列中 放弃 lsloader.jsfallback = function (path, name) { if (!!this.jsnamemap[name]) { return; } else { this.jsnamemap[name] = name; } //jsRunSequence队列中 找到fail的文件,标记他,等到runjs循环用script请求 for (var k in this.jsRunSequence) { if (this.jsRunSequence[k].name == name) { this.jsRunSequence[k].code = ''; this.jsRunSequence[k].status = 'failed'; this.jsRunSequence[k].path = path; } } this.runjs(); }; /*cssfallback 回退加载 * path 同上 * name 同上 * cssonload 同上 * xhr加载css失败的话 使用link标签异步加载样式,成功后调用cssonload */ lsloader.cssfallback = function (path, name, cssonload) { if (!!this.cssnamemap[name]) { return; } else { this.cssnamemap[name] = 1; } var link = document.createElement('link'); link.type = 'text/css'; link.href = path; link.rel = 'stylesheet'; link.onload = link.onerror = cssonload; var root = document.getElementsByTagName('script')[0]; root.parentNode.insertBefore(link, root) } /*runInlineScript 运行行内脚本 * 如果有依赖之前加载的js的内联脚本,用该方法执行, * scriptId js队列中的name值,可选 * codeId 包含内连脚本的textarea容器的id * js队列中添加name code值进入,运行到该项时runjs函数直接把代码append到顶部运行 */ lsloader.runInlineScript = function (scriptId, codeId) { var code = document.getElementById(codeId).innerText; this.jsRunSequence.push({ name: scriptId, code: code }) this.runjs() } /*loadCombo combo加载,顺序执行一系列js * * jslist :[ * { * name:名称, * path:线上路径 * } * ] * 遍历jslist数组,按照顺序加入jsRunSequence * 其中,如果本地缓存成功,直接写入code准备执行 * 否则status值为comboloading code写入null 不会执行 * 所有comboloading的模块拼接成一个url请求线上combo服务 * 成功后执行runcombo方法运行脚本 * 失败的话所有requestingModules请求的js文件都置为failed * runjs会启用script标签加载 */ lsloader.loadCombo = function (jslist) { var updateList = '';// 待更新combo模块列表 var requestingModules = {};//存储本次更新map for (var k in jslist) { var LS = this.getLS(jslist[k].name); if (!!LS) { var version = LS.split(versionString)[0] var code = LS.split(versionString)[1] } else { var version = ''; } if (version == jslist[k].path) { this.jsRunSequence.push({ name: jslist[k].name, code: code, path: jslist[k].path }) // 缓存有效 代码加入runSequence } else { this.jsRunSequence.push({ name: jslist[k].name, code: null, path: jslist[k].path, status: 'comboloading' }) // 缓存无效 代码加入运行队列 状态loading requestingModules[jslist[k].name] = true; updateList += (updateList == '' ? '' : ';') + jslist[k].path; } } var that = this; if (!!updateList) { var xhr = new XMLHttpRequest(); xhr.open("get", combo + updateList, true); xhr.onreadystatechange = function () { if (xhr.readyState == 4) { if ((xhr.status >= 200 && xhr.status < 300) || xhr.status == 304) { if (xhr.response != '') { that.runCombo(xhr.response, requestingModules); return; } } else { for (var i in that.jsRunSequence) { if (requestingModules[that.jsRunSequence[i].name]) { that.jsRunSequence[i].status = 'failed' } } that.runjs(); } } }; xhr.send(null); } this.runjs(); } /*runcombo * comboCode 服务端返回的用/combojs/注释分隔开的js代码 * requestingModules 所有被combo请求的modules map * requestingModules:{ * js文件name : true * } * combo服务返回代码后,用分隔符把所有js模块分隔成数组, * 用requestingModules查找jsRunSequence中该模块对应的项, * 更改该项,code为当前代码,status改为comboJS * 所有combo返回的模块遍历成功后,runjs() * runjs会把所有有代码的项当作成功项执行 */ lsloader.runCombo = function (comboCode, requestingModules) { comboCode = comboCode.split('/*combojs*/'); comboCode.shift();//去除首个空code for (var k in this.jsRunSequence) { if (!!requestingModules[this.jsRunSequence[k].name] && !!comboCode[0]) { this.jsRunSequence[k].status = 'comboJS'; this.jsRunSequence[k].code = comboCode[0]; this.setLS(this.jsRunSequence[k].name, this.jsRunSequence[k].path + versionString + comboCode[0]); comboCode.shift(); } } this.runjs(); } })()
define(function () { var EDITABLE_PADDING = 24; var Statusbar = function (context) { var $document = $(document); var $statusbar = context.layoutInfo.statusbar; var $editable = context.layoutInfo.editable; var options = context.options; this.initialize = function () { if (options.airMode || options.disableResizeEditor) { return; } $statusbar.on('mousedown', function (event) { event.preventDefault(); event.stopPropagation(); var editableTop = $editable.offset().top - $document.scrollTop(); $document.on('mousemove', function (event) { var height = event.clientY - (editableTop + EDITABLE_PADDING); height = (options.minheight > 0) ? Math.max(height, options.minheight) : height; height = (options.maxHeight > 0) ? Math.min(height, options.maxHeight) : height; $editable.height(height); }).one('mouseup', function () { $document.off('mousemove'); }); }); }; this.destroy = function () { $statusbar.off(); }; }; return Statusbar; });
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.echarts = {}))); }(this, (function (exports) { 'use strict'; if (typeof __DEV__ === "undefined") { if (typeof window !== "undefined") { window.__DEV__ = true; } else if (typeof global !== "undefined") { global.__DEV__ = true; } } /** * zrender: 生成唯一id * * @author errorrik (errorrik@gmail.com) */ var idStart = 0x0907; var guid = function () { return idStart++; }; /** * echarts设备环境识别 * * @desc echarts基于Canvas,纯Javascript图表库,提供直观,生动,可交互,可个性化定制的数据统计图表。 * @author firede[firede@firede.us] * @desc thanks zepto. */ var env = {}; if (typeof navigator === 'undefined') { // In node env = { browser: {}, os: {}, node: true, // Assume canvas is supported canvasSupported: true, svgSupported: true }; } else { env = detect(navigator.userAgent); } var env$1 = env; // Zepto.js // (c) 2010-2013 Thomas Fuchs // Zepto.js may be freely distributed under the MIT license. function detect(ua) { var os = {}; var browser = {}; // var webkit = ua.match(/Web[kK]it[\/]{0,1}([\d.]+)/); // var android = ua.match(/(Android);?[\s\/]+([\d.]+)?/); // var ipad = ua.match(/(iPad).*OS\s([\d_]+)/); // var ipod = ua.match(/(iPod)(.*OS\s([\d_]+))?/); // var iphone = !ipad && ua.match(/(iPhone\sOS)\s([\d_]+)/); // var webos = ua.match(/(webOS|hpwOS)[\s\/]([\d.]+)/); // var touchpad = webos && ua.match(/TouchPad/); // var kindle = ua.match(/Kindle\/([\d.]+)/); // var silk = ua.match(/Silk\/([\d._]+)/); // var blackberry = ua.match(/(BlackBerry).*Version\/([\d.]+)/); // var bb10 = ua.match(/(BB10).*Version\/([\d.]+)/); // var rimtabletos = ua.match(/(RIM\sTablet\sOS)\s([\d.]+)/); // var playbook = ua.match(/PlayBook/); // var chrome = ua.match(/Chrome\/([\d.]+)/) || ua.match(/CriOS\/([\d.]+)/); var firefox = ua.match(/Firefox\/([\d.]+)/); // var safari = webkit && ua.match(/Mobile\//) && !chrome; // var webview = ua.match(/(iPhone|iPod|iPad).*AppleWebKit(?!.*Safari)/) && !chrome; var ie = ua.match(/MSIE\s([\d.]+)/) // IE 11 Trident/7.0; rv:11.0 || ua.match(/Trident\/.+?rv:(([\d.]+))/); var edge = ua.match(/Edge\/([\d.]+)/); // IE 12 and 12+ var weChat = (/micromessenger/i).test(ua); // Todo: clean this up with a better OS/browser seperation: // - discern (more) between multiple browsers on android // - decide if kindle fire in silk mode is android or not // - Firefox on Android doesn't specify the Android version // - possibly devide in os, device and browser hashes // if (browser.webkit = !!webkit) browser.version = webkit[1]; // if (android) os.android = true, os.version = android[2]; // if (iphone && !ipod) os.ios = os.iphone = true, os.version = iphone[2].replace(/_/g, '.'); // if (ipad) os.ios = os.ipad = true, os.version = ipad[2].replace(/_/g, '.'); // if (ipod) os.ios = os.ipod = true, os.version = ipod[3] ? ipod[3].replace(/_/g, '.') : null; // if (webos) os.webos = true, os.version = webos[2]; // if (touchpad) os.touchpad = true; // if (blackberry) os.blackberry = true, os.version = blackberry[2]; // if (bb10) os.bb10 = true, os.version = bb10[2]; // if (rimtabletos) os.rimtabletos = true, os.version = rimtabletos[2]; // if (playbook) browser.playbook = true; // if (kindle) os.kindle = true, os.version = kindle[1]; // if (silk) browser.silk = true, browser.version = silk[1]; // if (!silk && os.android && ua.match(/Kindle Fire/)) browser.silk = true; // if (chrome) browser.chrome = true, browser.version = chrome[1]; if (firefox) { browser.firefox = true; browser.version = firefox[1]; } // if (safari && (ua.match(/Safari/) || !!os.ios)) browser.safari = true; // if (webview) browser.webview = true; if (ie) { browser.ie = true; browser.version = ie[1]; } if (edge) { browser.edge = true; browser.version = edge[1]; } // It is difficult to detect WeChat in Win Phone precisely, because ua can // not be set on win phone. So we do not consider Win Phone. if (weChat) { browser.weChat = true; } // os.tablet = !!(ipad || playbook || (android && !ua.match(/Mobile/)) || // (firefox && ua.match(/Tablet/)) || (ie && !ua.match(/Phone/) && ua.match(/Touch/))); // os.phone = !!(!os.tablet && !os.ipod && (android || iphone || webos || // (chrome && ua.match(/Android/)) || (chrome && ua.match(/CriOS\/([\d.]+)/)) || // (firefox && ua.match(/Mobile/)) || (ie && ua.match(/Touch/)))); return { browser: browser, os: os, node: false, // 原生canvas支持,改极端点了 // canvasSupported : !(browser.ie && parseFloat(browser.version) < 9) canvasSupported: !!document.createElement('canvas').getContext, svgSupported: typeof SVGRect !== 'undefined', // @see <http://stackoverflow.com/questions/4817029/whats-the-best-way-to-detect-a-touch-screen-device-using-javascript> // works on most browsers // IE10/11 does not support touch event, and MS Edge supports them but not by // default, so we dont check navigator.maxTouchPoints for them here. touchEventsSupported: 'ontouchstart' in window && !browser.ie && !browser.edge, // <http://caniuse.com/#search=pointer%20event>. pointerEventsSupported: 'onpointerdown' in window // Firefox supports pointer but not by default, only MS browsers are reliable on pointer // events currently. So we dont use that on other browsers unless tested sufficiently. // Although IE 10 supports pointer event, it use old style and is different from the // standard. So we exclude that. (IE 10 is hardly used on touch device) && (browser.edge || (browser.ie && browser.version >= 11)) }; } /** * @module zrender/core/util */ // 用于处理merge时无法遍历Date等对象的问题 var BUILTIN_OBJECT = { '[object Function]': 1, '[object RegExp]': 1, '[object Date]': 1, '[object Error]': 1, '[object CanvasGradient]': 1, '[object CanvasPattern]': 1, // For node-canvas '[object Image]': 1, '[object Canvas]': 1 }; var TYPED_ARRAY = { '[object Int8Array]': 1, '[object Uint8Array]': 1, '[object Uint8ClampedArray]': 1, '[object Int16Array]': 1, '[object Uint16Array]': 1, '[object Int32Array]': 1, '[object Uint32Array]': 1, '[object Float32Array]': 1, '[object Float64Array]': 1 }; var objToString = Object.prototype.toString; var arrayProto = Array.prototype; var nativeForEach = arrayProto.forEach; var nativeFilter = arrayProto.filter; var nativeSlice = arrayProto.slice; var nativeMap = arrayProto.map; var nativeReduce = arrayProto.reduce; /** * Those data types can be cloned: * Plain object, Array, TypedArray, number, string, null, undefined. * Those data types will be assgined using the orginal data: * BUILTIN_OBJECT * Instance of user defined class will be cloned to a plain object, without * properties in prototype. * Other data types is not supported (not sure what will happen). * * Caution: do not support clone Date, for performance consideration. * (There might be a large number of date in `series.data`). * So date should not be modified in and out of echarts. * * @param {*} source * @return {*} new */ function clone(source) { if (source == null || typeof source != 'object') { return source; } var result = source; var typeStr = objToString.call(source); if (typeStr === '[object Array]') { result = []; for (var i = 0, len = source.length; i < len; i++) { result[i] = clone(source[i]); } } else if (TYPED_ARRAY[typeStr]) { var Ctor = source.constructor; if (source.constructor.from) { result = Ctor.from(source); } else { result = new Ctor(source.length); for (var i = 0, len = source.length; i < len; i++) { result[i] = clone(source[i]); } } } else if (!BUILTIN_OBJECT[typeStr] && !isPrimitive(source) && !isDom(source)) { result = {}; for (var key in source) { if (source.hasOwnProperty(key)) { result[key] = clone(source[key]); } } } return result; } /** * @memberOf module:zrender/core/util * @param {*} target * @param {*} source * @param {boolean} [overwrite=false] */ function merge(target, source, overwrite) { // We should escapse that source is string // and enter for ... in ... if (!isObject(source) || !isObject(target)) { return overwrite ? clone(source) : target; } for (var key in source) { if (source.hasOwnProperty(key)) { var targetProp = target[key]; var sourceProp = source[key]; if (isObject(sourceProp) && isObject(targetProp) && !isArray(sourceProp) && !isArray(targetProp) && !isDom(sourceProp) && !isDom(targetProp) && !isBuiltInObject(sourceProp) && !isBuiltInObject(targetProp) && !isPrimitive(sourceProp) && !isPrimitive(targetProp) ) { // 如果需要递归覆盖,就递归调用merge merge(targetProp, sourceProp, overwrite); } else if (overwrite || !(key in target)) { // 否则只处理overwrite为true,或者在目标对象中没有此属性的情况 // NOTE,在 target[key] 不存在的时候也是直接覆盖 target[key] = clone(source[key], true); } } } return target; } /** * @param {Array} targetAndSources The first item is target, and the rests are source. * @param {boolean} [overwrite=false] * @return {*} target */ function mergeAll(targetAndSources, overwrite) { var result = targetAndSources[0]; for (var i = 1, len = targetAndSources.length; i < len; i++) { result = merge(result, targetAndSources[i], overwrite); } return result; } /** * @param {*} target * @param {*} source * @memberOf module:zrender/core/util */ function extend(target, source) { for (var key in source) { if (source.hasOwnProperty(key)) { target[key] = source[key]; } } return target; } /** * @param {*} target * @param {*} source * @param {boolean} [overlay=false] * @memberOf module:zrender/core/util */ function defaults(target, source, overlay) { for (var key in source) { if (source.hasOwnProperty(key) && (overlay ? source[key] != null : target[key] == null) ) { target[key] = source[key]; } } return target; } var createCanvas = function () { return document.createElement('canvas'); }; // FIXME var _ctx; function getContext() { if (!_ctx) { // Use util.createCanvas instead of createCanvas // because createCanvas may be overwritten in different environment _ctx = createCanvas().getContext('2d'); } return _ctx; } /** * 查询数组中元素的index * @memberOf module:zrender/core/util */ function indexOf(array, value) { if (array) { if (array.indexOf) { return array.indexOf(value); } for (var i = 0, len = array.length; i < len; i++) { if (array[i] === value) { return i; } } } return -1; } /** * 构造类继承关系 * * @memberOf module:zrender/core/util * @param {Function} clazz 源类 * @param {Function} baseClazz 基类 */ function inherits(clazz, baseClazz) { var clazzPrototype = clazz.prototype; function F() {} F.prototype = baseClazz.prototype; clazz.prototype = new F(); for (var prop in clazzPrototype) { clazz.prototype[prop] = clazzPrototype[prop]; } clazz.prototype.constructor = clazz; clazz.superClass = baseClazz; } /** * @memberOf module:zrender/core/util * @param {Object|Function} target * @param {Object|Function} sorce * @param {boolean} overlay */ function mixin(target, source, overlay) { target = 'prototype' in target ? target.prototype : target; source = 'prototype' in source ? source.prototype : source; defaults(target, source, overlay); } /** * Consider typed array. * @param {Array|TypedArray} data */ function isArrayLike(data) { if (! data) { return; } if (typeof data == 'string') { return false; } return typeof data.length == 'number'; } /** * 数组或对象遍历 * @memberOf module:zrender/core/util * @param {Object|Array} obj * @param {Function} cb * @param {*} [context] */ function each$1(obj, cb, context) { if (!(obj && cb)) { return; } if (obj.forEach && obj.forEach === nativeForEach) { obj.forEach(cb, context); } else if (obj.length === +obj.length) { for (var i = 0, len = obj.length; i < len; i++) { cb.call(context, obj[i], i, obj); } } else { for (var key in obj) { if (obj.hasOwnProperty(key)) { cb.call(context, obj[key], key, obj); } } } } /** * 数组映射 * @memberOf module:zrender/core/util * @param {Array} obj * @param {Function} cb * @param {*} [context] * @return {Array} */ function map(obj, cb, context) { if (!(obj && cb)) { return; } if (obj.map && obj.map === nativeMap) { return obj.map(cb, context); } else { var result = []; for (var i = 0, len = obj.length; i < len; i++) { result.push(cb.call(context, obj[i], i, obj)); } return result; } } /** * @memberOf module:zrender/core/util * @param {Array} obj * @param {Function} cb * @param {Object} [memo] * @param {*} [context] * @return {Array} */ function reduce(obj, cb, memo, context) { if (!(obj && cb)) { return; } if (obj.reduce && obj.reduce === nativeReduce) { return obj.reduce(cb, memo, context); } else { for (var i = 0, len = obj.length; i < len; i++) { memo = cb.call(context, memo, obj[i], i, obj); } return memo; } } /** * 数组过滤 * @memberOf module:zrender/core/util * @param {Array} obj * @param {Function} cb * @param {*} [context] * @return {Array} */ function filter(obj, cb, context) { if (!(obj && cb)) { return; } if (obj.filter && obj.filter === nativeFilter) { return obj.filter(cb, context); } else { var result = []; for (var i = 0, len = obj.length; i < len; i++) { if (cb.call(context, obj[i], i, obj)) { result.push(obj[i]); } } return result; } } /** * 数组项查找 * @memberOf module:zrender/core/util * @param {Array} obj * @param {Function} cb * @param {*} [context] * @return {*} */ /** * @memberOf module:zrender/core/util * @param {Function} func * @param {*} context * @return {Function} */ function bind(func, context) { var args = nativeSlice.call(arguments, 2); return function () { return func.apply(context, args.concat(nativeSlice.call(arguments))); }; } /** * @memberOf module:zrender/core/util * @param {Function} func * @return {Function} */ function curry(func) { var args = nativeSlice.call(arguments, 1); return function () { return func.apply(this, args.concat(nativeSlice.call(arguments))); }; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isArray(value) { return objToString.call(value) === '[object Array]'; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isFunction(value) { return typeof value === 'function'; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isString(value) { return objToString.call(value) === '[object String]'; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isObject(value) { // Avoid a V8 JIT bug in Chrome 19-20. // See https://code.google.com/p/v8/issues/detail?id=2291 for more details. var type = typeof value; return type === 'function' || (!!value && type == 'object'); } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isBuiltInObject(value) { return !!BUILTIN_OBJECT[objToString.call(value)]; } /** * @memberOf module:zrender/core/util * @param {*} value * @return {boolean} */ function isDom(value) { return typeof value === 'object' && typeof value.nodeType === 'number' && typeof value.ownerDocument === 'object'; } /** * Whether is exactly NaN. Notice isNaN('a') returns true. * @param {*} value * @return {boolean} */ function eqNaN(value) { return value !== value; } /** * If value1 is not null, then return value1, otherwise judget rest of values. * Low performance. * @memberOf module:zrender/core/util * @return {*} Final value */ function retrieve(values) { for (var i = 0, len = arguments.length; i < len; i++) { if (arguments[i] != null) { return arguments[i]; } } } function retrieve2(value0, value1) { return value0 != null ? value0 : value1; } function retrieve3(value0, value1, value2) { return value0 != null ? value0 : value1 != null ? value1 : value2; } /** * @memberOf module:zrender/core/util * @param {Array} arr * @param {number} startIndex * @param {number} endIndex * @return {Array} */ function slice() { return Function.call.apply(nativeSlice, arguments); } /** * Normalize css liked array configuration * e.g. * 3 => [3, 3, 3, 3] * [4, 2] => [4, 2, 4, 2] * [4, 3, 2] => [4, 3, 2, 3] * @param {number|Array.<number>} val * @return {Array.<number>} */ function normalizeCssArray(val) { if (typeof (val) === 'number') { return [val, val, val, val]; } var len = val.length; if (len === 2) { // vertical | horizontal return [val[0], val[1], val[0], val[1]]; } else if (len === 3) { // top | horizontal | bottom return [val[0], val[1], val[2], val[1]]; } return val; } /** * @memberOf module:zrender/core/util * @param {boolean} condition * @param {string} message */ function assert(condition, message) { if (!condition) { throw new Error(message); } } var primitiveKey = '__ec_primitive__'; /** * Set an object as primitive to be ignored traversing children in clone or merge */ function setAsPrimitive(obj) { obj[primitiveKey] = true; } function isPrimitive(obj) { return obj[primitiveKey]; } /** * @constructor * @param {Object} obj Only apply `ownProperty`. */ function HashMap(obj) { obj && each$1(obj, function (value, key) { this.set(key, value); }, this); } // Add prefix to avoid conflict with Object.prototype. var HASH_MAP_PREFIX = '_ec_'; var HASH_MAP_PREFIX_LENGTH = 4; HashMap.prototype = { constructor: HashMap, // Do not provide `has` method to avoid defining what is `has`. // (We usually treat `null` and `undefined` as the same, different // from ES6 Map). get: function (key) { return this[HASH_MAP_PREFIX + key]; }, set: function (key, value) { this[HASH_MAP_PREFIX + key] = value; // Comparing with invocation chaining, `return value` is more commonly // used in this case: `var someVal = map.set('a', genVal());` return value; }, // Although util.each can be performed on this hashMap directly, user // should not use the exposed keys, who are prefixed. each: function (cb, context) { context !== void 0 && (cb = bind(cb, context)); for (var prefixedKey in this) { this.hasOwnProperty(prefixedKey) && cb(this[prefixedKey], prefixedKey.slice(HASH_MAP_PREFIX_LENGTH)); } }, // Do not use this method if performance sensitive. removeKey: function (key) { delete this[HASH_MAP_PREFIX + key]; } }; function createHashMap(obj) { return new HashMap(obj); } function noop() {} var $inject$1 = { createCanvas: function (f) { createCanvas = f; } }; var ArrayCtor = typeof Float32Array === 'undefined' ? Array : Float32Array; /** * 创建一个向量 * @param {number} [x=0] * @param {number} [y=0] * @return {Vector2} */ function create(x, y) { var out = new ArrayCtor(2); if (x == null) { x = 0; } if (y == null) { y = 0; } out[0] = x; out[1] = y; return out; } /** * 复制向量数据 * @param {Vector2} out * @param {Vector2} v * @return {Vector2} */ function copy(out, v) { out[0] = v[0]; out[1] = v[1]; return out; } /** * 克隆一个向量 * @param {Vector2} v * @return {Vector2} */ function clone$1(v) { var out = new ArrayCtor(2); out[0] = v[0]; out[1] = v[1]; return out; } /** * 设置向量的两个项 * @param {Vector2} out * @param {number} a * @param {number} b * @return {Vector2} 结果 */ /** * 向量相加 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function add(out, v1, v2) { out[0] = v1[0] + v2[0]; out[1] = v1[1] + v2[1]; return out; } /** * 向量缩放后相加 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 * @param {number} a */ function scaleAndAdd(out, v1, v2, a) { out[0] = v1[0] + v2[0] * a; out[1] = v1[1] + v2[1] * a; return out; } /** * 向量相减 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function sub(out, v1, v2) { out[0] = v1[0] - v2[0]; out[1] = v1[1] - v2[1]; return out; } /** * 向量长度 * @param {Vector2} v * @return {number} */ function len(v) { return Math.sqrt(lenSquare(v)); } // jshint ignore:line /** * 向量长度平方 * @param {Vector2} v * @return {number} */ function lenSquare(v) { return v[0] * v[0] + v[1] * v[1]; } /** * 向量乘法 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ /** * 向量除法 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ /** * 向量点乘 * @param {Vector2} v1 * @param {Vector2} v2 * @return {number} */ /** * 向量缩放 * @param {Vector2} out * @param {Vector2} v * @param {number} s */ function scale(out, v, s) { out[0] = v[0] * s; out[1] = v[1] * s; return out; } /** * 向量归一化 * @param {Vector2} out * @param {Vector2} v */ function normalize(out, v) { var d = len(v); if (d === 0) { out[0] = 0; out[1] = 0; } else { out[0] = v[0] / d; out[1] = v[1] / d; } return out; } /** * 计算向量间距离 * @param {Vector2} v1 * @param {Vector2} v2 * @return {number} */ function distance(v1, v2) { return Math.sqrt( (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]) ); } var dist = distance; /** * 向量距离平方 * @param {Vector2} v1 * @param {Vector2} v2 * @return {number} */ function distanceSquare(v1, v2) { return (v1[0] - v2[0]) * (v1[0] - v2[0]) + (v1[1] - v2[1]) * (v1[1] - v2[1]); } var distSquare = distanceSquare; /** * 求负向量 * @param {Vector2} out * @param {Vector2} v */ /** * 插值两个点 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 * @param {number} t */ /** * 矩阵左乘向量 * @param {Vector2} out * @param {Vector2} v * @param {Vector2} m */ function applyTransform(out, v, m) { var x = v[0]; var y = v[1]; out[0] = m[0] * x + m[2] * y + m[4]; out[1] = m[1] * x + m[3] * y + m[5]; return out; } /** * 求两个向量最小值 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function min(out, v1, v2) { out[0] = Math.min(v1[0], v2[0]); out[1] = Math.min(v1[1], v2[1]); return out; } /** * 求两个向量最大值 * @param {Vector2} out * @param {Vector2} v1 * @param {Vector2} v2 */ function max(out, v1, v2) { out[0] = Math.max(v1[0], v2[0]); out[1] = Math.max(v1[1], v2[1]); return out; } // TODO Draggable for group // FIXME Draggable on element which has parent rotation or scale function Draggable() { this.on('mousedown', this._dragStart, this); this.on('mousemove', this._drag, this); this.on('mouseup', this._dragEnd, this); this.on('globalout', this._dragEnd, this); // this._dropTarget = null; // this._draggingTarget = null; // this._x = 0; // this._y = 0; } Draggable.prototype = { constructor: Draggable, _dragStart: function (e) { var draggingTarget = e.target; if (draggingTarget && draggingTarget.draggable) { this._draggingTarget = draggingTarget; draggingTarget.dragging = true; this._x = e.offsetX; this._y = e.offsetY; this.dispatchToElement(param(draggingTarget, e), 'dragstart', e.event); } }, _drag: function (e) { var draggingTarget = this._draggingTarget; if (draggingTarget) { var x = e.offsetX; var y = e.offsetY; var dx = x - this._x; var dy = y - this._y; this._x = x; this._y = y; draggingTarget.drift(dx, dy, e); this.dispatchToElement(param(draggingTarget, e), 'drag', e.event); var dropTarget = this.findHover(x, y, draggingTarget).target; var lastDropTarget = this._dropTarget; this._dropTarget = dropTarget; if (draggingTarget !== dropTarget) { if (lastDropTarget && dropTarget !== lastDropTarget) { this.dispatchToElement(param(lastDropTarget, e), 'dragleave', e.event); } if (dropTarget && dropTarget !== lastDropTarget) { this.dispatchToElement(param(dropTarget, e), 'dragenter', e.event); } } } }, _dragEnd: function (e) { var draggingTarget = this._draggingTarget; if (draggingTarget) { draggingTarget.dragging = false; } this.dispatchToElement(param(draggingTarget, e), 'dragend', e.event); if (this._dropTarget) { this.dispatchToElement(param(this._dropTarget, e), 'drop', e.event); } this._draggingTarget = null; this._dropTarget = null; } }; function param(target, e) { return {target: target, topTarget: e && e.topTarget}; } /** * 事件扩展 * @module zrender/mixin/Eventful * @author Kener (@Kener-林峰, kener.linfeng@gmail.com) * pissang (https://www.github.com/pissang) */ var arrySlice = Array.prototype.slice; /** * 事件分发器 * @alias module:zrender/mixin/Eventful * @constructor */ var Eventful = function () { this._$handlers = {}; }; Eventful.prototype = { constructor: Eventful, /** * 单次触发绑定,trigger后销毁 * * @param {string} event 事件名 * @param {Function} handler 响应函数 * @param {Object} context */ one: function (event, handler, context) { var _h = this._$handlers; if (!handler || !event) { return this; } if (!_h[event]) { _h[event] = []; } for (var i = 0; i < _h[event].length; i++) { if (_h[event][i].h === handler) { return this; } } _h[event].push({ h: handler, one: true, ctx: context || this }); return this; }, /** * 绑定事件 * @param {string} event 事件名 * @param {Function} handler 事件处理函数 * @param {Object} [context] */ on: function (event, handler, context) { var _h = this._$handlers; if (!handler || !event) { return this; } if (!_h[event]) { _h[event] = []; } for (var i = 0; i < _h[event].length; i++) { if (_h[event][i].h === handler) { return this; } } _h[event].push({ h: handler, one: false, ctx: context || this }); return this; }, /** * 是否绑定了事件 * @param {string} event * @return {boolean} */ isSilent: function (event) { var _h = this._$handlers; return _h[event] && _h[event].length; }, /** * 解绑事件 * @param {string} event 事件名 * @param {Function} [handler] 事件处理函数 */ off: function (event, handler) { var _h = this._$handlers; if (!event) { this._$handlers = {}; return this; } if (handler) { if (_h[event]) { var newList = []; for (var i = 0, l = _h[event].length; i < l; i++) { if (_h[event][i]['h'] != handler) { newList.push(_h[event][i]); } } _h[event] = newList; } if (_h[event] && _h[event].length === 0) { delete _h[event]; } } else { delete _h[event]; } return this; }, /** * 事件分发 * * @param {string} type 事件类型 */ trigger: function (type) { if (this._$handlers[type]) { var args = arguments; var argLen = args.length; if (argLen > 3) { args = arrySlice.call(args, 1); } var _h = this._$handlers[type]; var len = _h.length; for (var i = 0; i < len;) { // Optimize advise from backbone switch (argLen) { case 1: _h[i]['h'].call(_h[i]['ctx']); break; case 2: _h[i]['h'].call(_h[i]['ctx'], args[1]); break; case 3: _h[i]['h'].call(_h[i]['ctx'], args[1], args[2]); break; default: // have more than 2 given arguments _h[i]['h'].apply(_h[i]['ctx'], args); break; } if (_h[i]['one']) { _h.splice(i, 1); len--; } else { i++; } } } return this; }, /** * 带有context的事件分发, 最后一个参数是事件回调的context * @param {string} type 事件类型 */ triggerWithContext: function (type) { if (this._$handlers[type]) { var args = arguments; var argLen = args.length; if (argLen > 4) { args = arrySlice.call(args, 1, args.length - 1); } var ctx = args[args.length - 1]; var _h = this._$handlers[type]; var len = _h.length; for (var i = 0; i < len;) { // Optimize advise from backbone switch (argLen) { case 1: _h[i]['h'].call(ctx); break; case 2: _h[i]['h'].call(ctx, args[1]); break; case 3: _h[i]['h'].call(ctx, args[1], args[2]); break; default: // have more than 2 given arguments _h[i]['h'].apply(ctx, args); break; } if (_h[i]['one']) { _h.splice(i, 1); len--; } else { i++; } } } return this; } }; /** * Handler * @module zrender/Handler * @author Kener (@Kener-林峰, kener.linfeng@gmail.com) * errorrik (errorrik@gmail.com) * pissang (shenyi.914@gmail.com) */ var SILENT = 'silent'; function makeEventPacket(eveType, targetInfo, event) { return { type: eveType, event: event, // target can only be an element that is not silent. target: targetInfo.target, // topTarget can be a silent element. topTarget: targetInfo.topTarget, cancelBubble: false, offsetX: event.zrX, offsetY: event.zrY, gestureEvent: event.gestureEvent, pinchX: event.pinchX, pinchY: event.pinchY, pinchScale: event.pinchScale, wheelDelta: event.zrDelta, zrByTouch: event.zrByTouch, which: event.which }; } function EmptyProxy () {} EmptyProxy.prototype.dispose = function () {}; var handlerNames = [ 'click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu' ]; /** * @alias module:zrender/Handler * @constructor * @extends module:zrender/mixin/Eventful * @param {module:zrender/Storage} storage Storage instance. * @param {module:zrender/Painter} painter Painter instance. * @param {module:zrender/dom/HandlerProxy} proxy HandlerProxy instance. * @param {HTMLElement} painterRoot painter.root (not painter.getViewportRoot()). */ var Handler = function(storage, painter, proxy, painterRoot) { Eventful.call(this); this.storage = storage; this.painter = painter; this.painterRoot = painterRoot; proxy = proxy || new EmptyProxy(); /** * Proxy of event. can be Dom, WebGLSurface, etc. */ this.proxy = proxy; // Attach handler proxy.handler = this; /** * {target, topTarget, x, y} * @private * @type {Object} */ this._hovered = {}; /** * @private * @type {Date} */ this._lastTouchMoment; /** * @private * @type {number} */ this._lastX; /** * @private * @type {number} */ this._lastY; Draggable.call(this); each$1(handlerNames, function (name) { proxy.on && proxy.on(name, this[name], this); }, this); }; Handler.prototype = { constructor: Handler, mousemove: function (event) { var x = event.zrX; var y = event.zrY; var lastHovered = this._hovered; var lastHoveredTarget = lastHovered.target; // If lastHoveredTarget is removed from zr (detected by '__zr') by some API call // (like 'setOption' or 'dispatchAction') in event handlers, we should find // lastHovered again here. Otherwise 'mouseout' can not be triggered normally. // See #6198. if (lastHoveredTarget && !lastHoveredTarget.__zr) { lastHovered = this.findHover(lastHovered.x, lastHovered.y); lastHoveredTarget = lastHovered.target; } var hovered = this._hovered = this.findHover(x, y); var hoveredTarget = hovered.target; var proxy = this.proxy; proxy.setCursor && proxy.setCursor(hoveredTarget ? hoveredTarget.cursor : 'default'); // Mouse out on previous hovered element if (lastHoveredTarget && hoveredTarget !== lastHoveredTarget) { this.dispatchToElement(lastHovered, 'mouseout', event); } // Mouse moving on one element this.dispatchToElement(hovered, 'mousemove', event); // Mouse over on a new element if (hoveredTarget && hoveredTarget !== lastHoveredTarget) { this.dispatchToElement(hovered, 'mouseover', event); } }, mouseout: function (event) { this.dispatchToElement(this._hovered, 'mouseout', event); // There might be some doms created by upper layer application // at the same level of painter.getViewportRoot() (e.g., tooltip // dom created by echarts), where 'globalout' event should not // be triggered when mouse enters these doms. (But 'mouseout' // should be triggered at the original hovered element as usual). var element = event.toElement || event.relatedTarget; var innerDom; do { element = element && element.parentNode; } while (element && element.nodeType != 9 && !( innerDom = element === this.painterRoot )); !innerDom && this.trigger('globalout', {event: event}); }, /** * Resize */ resize: function (event) { this._hovered = {}; }, /** * Dispatch event * @param {string} eventName * @param {event=} eventArgs */ dispatch: function (eventName, eventArgs) { var handler = this[eventName]; handler && handler.call(this, eventArgs); }, /** * Dispose */ dispose: function () { this.proxy.dispose(); this.storage = this.proxy = this.painter = null; }, /** * 设置默认的cursor style * @param {string} [cursorStyle='default'] 例如 crosshair */ setCursorStyle: function (cursorStyle) { var proxy = this.proxy; proxy.setCursor && proxy.setCursor(cursorStyle); }, /** * 事件分发代理 * * @private * @param {Object} targetInfo {target, topTarget} 目标图形元素 * @param {string} eventName 事件名称 * @param {Object} event 事件对象 */ dispatchToElement: function (targetInfo, eventName, event) { targetInfo = targetInfo || {}; var el = targetInfo.target; if (el && el.silent) { return; } var eventHandler = 'on' + eventName; var eventPacket = makeEventPacket(eventName, targetInfo, event); while (el) { el[eventHandler] && (eventPacket.cancelBubble = el[eventHandler].call(el, eventPacket)); el.trigger(eventName, eventPacket); el = el.parent; if (eventPacket.cancelBubble) { break; } } if (!eventPacket.cancelBubble) { // 冒泡到顶级 zrender 对象 this.trigger(eventName, eventPacket); // 分发事件到用户自定义层 // 用户有可能在全局 click 事件中 dispose,所以需要判断下 painter 是否存在 this.painter && this.painter.eachOtherLayer(function (layer) { if (typeof(layer[eventHandler]) == 'function') { layer[eventHandler].call(layer, eventPacket); } if (layer.trigger) { layer.trigger(eventName, eventPacket); } }); } }, /** * @private * @param {number} x * @param {number} y * @param {module:zrender/graphic/Displayable} exclude * @return {model:zrender/Element} * @method */ findHover: function(x, y, exclude) { var list = this.storage.getDisplayList(); var out = {x: x, y: y}; for (var i = list.length - 1; i >= 0 ; i--) { var hoverCheckResult; if (list[i] !== exclude // getDisplayList may include ignored item in VML mode && !list[i].ignore && (hoverCheckResult = isHover(list[i], x, y)) ) { !out.topTarget && (out.topTarget = list[i]); if (hoverCheckResult !== SILENT) { out.target = list[i]; break; } } } return out; } }; // Common handlers each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) { Handler.prototype[name] = function (event) { // Find hover again to avoid click event is dispatched manually. Or click is triggered without mouseover var hovered = this.findHover(event.zrX, event.zrY); var hoveredTarget = hovered.target; if (name === 'mousedown') { this._downEl = hoveredTarget; this._downPoint = [event.zrX, event.zrY]; // In case click triggered before mouseup this._upEl = hoveredTarget; } else if (name === 'mosueup') { this._upEl = hoveredTarget; } else if (name === 'click') { if (this._downEl !== this._upEl // Original click event is triggered on the whole canvas element, // including the case that `mousedown` - `mousemove` - `mouseup`, // which should be filtered, otherwise it will bring trouble to // pan and zoom. || !this._downPoint // Arbitrary value || dist(this._downPoint, [event.zrX, event.zrY]) > 4 ) { return; } this._downPoint = null; } this.dispatchToElement(hovered, name, event); }; }); function isHover(displayable, x, y) { if (displayable[displayable.rectHover ? 'rectContain' : 'contain'](x, y)) { var el = displayable; var isSilent; while (el) { // If clipped by ancestor. // FIXME: If clipPath has neither stroke nor fill, // el.clipPath.contain(x, y) will always return false. if (el.clipPath && !el.clipPath.contain(x, y)) { return false; } if (el.silent) { isSilent = true; } el = el.parent; } return isSilent ? SILENT : true; } return false; } mixin(Handler, Eventful); mixin(Handler, Draggable); /** * 3x2矩阵操作类 * @exports zrender/tool/matrix */ var ArrayCtor$1 = typeof Float32Array === 'undefined' ? Array : Float32Array; /** * 创建一个单位矩阵 * @return {Float32Array|Array.<number>} */ function create$1() { var out = new ArrayCtor$1(6); identity(out); return out; } /** * 设置矩阵为单位矩阵 * @param {Float32Array|Array.<number>} out */ function identity(out) { out[0] = 1; out[1] = 0; out[2] = 0; out[3] = 1; out[4] = 0; out[5] = 0; return out; } /** * 复制矩阵 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} m */ function copy$1(out, m) { out[0] = m[0]; out[1] = m[1]; out[2] = m[2]; out[3] = m[3]; out[4] = m[4]; out[5] = m[5]; return out; } /** * 矩阵相乘 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} m1 * @param {Float32Array|Array.<number>} m2 */ function mul$1(out, m1, m2) { // Consider matrix.mul(m, m2, m); // where out is the same as m2. // So use temp variable to escape error. var out0 = m1[0] * m2[0] + m1[2] * m2[1]; var out1 = m1[1] * m2[0] + m1[3] * m2[1]; var out2 = m1[0] * m2[2] + m1[2] * m2[3]; var out3 = m1[1] * m2[2] + m1[3] * m2[3]; var out4 = m1[0] * m2[4] + m1[2] * m2[5] + m1[4]; var out5 = m1[1] * m2[4] + m1[3] * m2[5] + m1[5]; out[0] = out0; out[1] = out1; out[2] = out2; out[3] = out3; out[4] = out4; out[5] = out5; return out; } /** * 平移变换 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} a * @param {Float32Array|Array.<number>} v */ function translate(out, a, v) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; out[4] = a[4] + v[0]; out[5] = a[5] + v[1]; return out; } /** * 旋转变换 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} a * @param {number} rad */ function rotate(out, a, rad) { var aa = a[0]; var ac = a[2]; var atx = a[4]; var ab = a[1]; var ad = a[3]; var aty = a[5]; var st = Math.sin(rad); var ct = Math.cos(rad); out[0] = aa * ct + ab * st; out[1] = -aa * st + ab * ct; out[2] = ac * ct + ad * st; out[3] = -ac * st + ct * ad; out[4] = ct * atx + st * aty; out[5] = ct * aty - st * atx; return out; } /** * 缩放变换 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} a * @param {Float32Array|Array.<number>} v */ function scale$1(out, a, v) { var vx = v[0]; var vy = v[1]; out[0] = a[0] * vx; out[1] = a[1] * vy; out[2] = a[2] * vx; out[3] = a[3] * vy; out[4] = a[4] * vx; out[5] = a[5] * vy; return out; } /** * 求逆矩阵 * @param {Float32Array|Array.<number>} out * @param {Float32Array|Array.<number>} a */ function invert(out, a) { var aa = a[0]; var ac = a[2]; var atx = a[4]; var ab = a[1]; var ad = a[3]; var aty = a[5]; var det = aa * ad - ab * ac; if (!det) { return null; } det = 1.0 / det; out[0] = ad * det; out[1] = -ab * det; out[2] = -ac * det; out[3] = aa * det; out[4] = (ac * aty - ad * atx) * det; out[5] = (ab * atx - aa * aty) * det; return out; } /** * 提供变换扩展 * @module zrender/mixin/Transformable * @author pissang (https://www.github.com/pissang) */ var mIdentity = identity; var EPSILON = 5e-5; function isNotAroundZero(val) { return val > EPSILON || val < -EPSILON; } /** * @alias module:zrender/mixin/Transformable * @constructor */ var Transformable = function (opts) { opts = opts || {}; // If there are no given position, rotation, scale if (!opts.position) { /** * 平移 * @type {Array.<number>} * @default [0, 0] */ this.position = [0, 0]; } if (opts.rotation == null) { /** * 旋转 * @type {Array.<number>} * @default 0 */ this.rotation = 0; } if (!opts.scale) { /** * 缩放 * @type {Array.<number>} * @default [1, 1] */ this.scale = [1, 1]; } /** * 旋转和缩放的原点 * @type {Array.<number>} * @default null */ this.origin = this.origin || null; }; var transformableProto = Transformable.prototype; transformableProto.transform = null; /** * 判断是否需要有坐标变换 * 如果有坐标变换, 则从position, rotation, scale以及父节点的transform计算出自身的transform矩阵 */ transformableProto.needLocalTransform = function () { return isNotAroundZero(this.rotation) || isNotAroundZero(this.position[0]) || isNotAroundZero(this.position[1]) || isNotAroundZero(this.scale[0] - 1) || isNotAroundZero(this.scale[1] - 1); }; transformableProto.updateTransform = function () { var parent = this.parent; var parentHasTransform = parent && parent.transform; var needLocalTransform = this.needLocalTransform(); var m = this.transform; if (!(needLocalTransform || parentHasTransform)) { m && mIdentity(m); return; } m = m || create$1(); if (needLocalTransform) { this.getLocalTransform(m); } else { mIdentity(m); } // 应用父节点变换 if (parentHasTransform) { if (needLocalTransform) { mul$1(m, parent.transform, m); } else { copy$1(m, parent.transform); } } // 保存这个变换矩阵 this.transform = m; this.invTransform = this.invTransform || create$1(); invert(this.invTransform, m); }; transformableProto.getLocalTransform = function (m) { return Transformable.getLocalTransform(this, m); }; /** * 将自己的transform应用到context上 * @param {CanvasRenderingContext2D} ctx */ transformableProto.setTransform = function (ctx) { var m = this.transform; var dpr = ctx.dpr || 1; if (m) { ctx.setTransform(dpr * m[0], dpr * m[1], dpr * m[2], dpr * m[3], dpr * m[4], dpr * m[5]); } else { ctx.setTransform(dpr, 0, 0, dpr, 0, 0); } }; transformableProto.restoreTransform = function (ctx) { var dpr = ctx.dpr || 1; ctx.setTransform(dpr, 0, 0, dpr, 0, 0); }; var tmpTransform = []; /** * 分解`transform`矩阵到`position`, `rotation`, `scale` */ transformableProto.decomposeTransform = function () { if (!this.transform) { return; } var parent = this.parent; var m = this.transform; if (parent && parent.transform) { // Get local transform and decompose them to position, scale, rotation mul$1(tmpTransform, parent.invTransform, m); m = tmpTransform; } var sx = m[0] * m[0] + m[1] * m[1]; var sy = m[2] * m[2] + m[3] * m[3]; var position = this.position; var scale$$1 = this.scale; if (isNotAroundZero(sx - 1)) { sx = Math.sqrt(sx); } if (isNotAroundZero(sy - 1)) { sy = Math.sqrt(sy); } if (m[0] < 0) { sx = -sx; } if (m[3] < 0) { sy = -sy; } position[0] = m[4]; position[1] = m[5]; scale$$1[0] = sx; scale$$1[1] = sy; this.rotation = Math.atan2(-m[1] / sy, m[0] / sx); }; /** * Get global scale * @return {Array.<number>} */ transformableProto.getGlobalScale = function () { var m = this.transform; if (!m) { return [1, 1]; } var sx = Math.sqrt(m[0] * m[0] + m[1] * m[1]); var sy = Math.sqrt(m[2] * m[2] + m[3] * m[3]); if (m[0] < 0) { sx = -sx; } if (m[3] < 0) { sy = -sy; } return [sx, sy]; }; /** * 变换坐标位置到 shape 的局部坐标空间 * @method * @param {number} x * @param {number} y * @return {Array.<number>} */ transformableProto.transformCoordToLocal = function (x, y) { var v2 = [x, y]; var invTransform = this.invTransform; if (invTransform) { applyTransform(v2, v2, invTransform); } return v2; }; /** * 变换局部坐标位置到全局坐标空间 * @method * @param {number} x * @param {number} y * @return {Array.<number>} */ transformableProto.transformCoordToGlobal = function (x, y) { var v2 = [x, y]; var transform = this.transform; if (transform) { applyTransform(v2, v2, transform); } return v2; }; /** * @static * @param {Object} target * @param {Array.<number>} target.origin * @param {number} target.rotation * @param {Array.<number>} target.position * @param {Array.<number>} [m] */ Transformable.getLocalTransform = function (target, m) { m = m || []; mIdentity(m); var origin = target.origin; var scale$$1 = target.scale || [1, 1]; var rotation = target.rotation || 0; var position = target.position || [0, 0]; if (origin) { // Translate to origin m[4] -= origin[0]; m[5] -= origin[1]; } scale$1(m, m, scale$$1); if (rotation) { rotate(m, m, rotation); } if (origin) { // Translate back from origin m[4] += origin[0]; m[5] += origin[1]; } m[4] += position[0]; m[5] += position[1]; return m; }; /** * 缓动代码来自 https://github.com/sole/tween.js/blob/master/src/Tween.js * @see http://sole.github.io/tween.js/examples/03_graphs.html * @exports zrender/animation/easing */ var easing = { /** * @param {number} k * @return {number} */ linear: function (k) { return k; }, /** * @param {number} k * @return {number} */ quadraticIn: function (k) { return k * k; }, /** * @param {number} k * @return {number} */ quadraticOut: function (k) { return k * (2 - k); }, /** * @param {number} k * @return {number} */ quadraticInOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k; } return -0.5 * (--k * (k - 2) - 1); }, // 三次方的缓动(t^3) /** * @param {number} k * @return {number} */ cubicIn: function (k) { return k * k * k; }, /** * @param {number} k * @return {number} */ cubicOut: function (k) { return --k * k * k + 1; }, /** * @param {number} k * @return {number} */ cubicInOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k; } return 0.5 * ((k -= 2) * k * k + 2); }, // 四次方的缓动(t^4) /** * @param {number} k * @return {number} */ quarticIn: function (k) { return k * k * k * k; }, /** * @param {number} k * @return {number} */ quarticOut: function (k) { return 1 - (--k * k * k * k); }, /** * @param {number} k * @return {number} */ quarticInOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k; } return -0.5 * ((k -= 2) * k * k * k - 2); }, // 五次方的缓动(t^5) /** * @param {number} k * @return {number} */ quinticIn: function (k) { return k * k * k * k * k; }, /** * @param {number} k * @return {number} */ quinticOut: function (k) { return --k * k * k * k * k + 1; }, /** * @param {number} k * @return {number} */ quinticInOut: function (k) { if ((k *= 2) < 1) { return 0.5 * k * k * k * k * k; } return 0.5 * ((k -= 2) * k * k * k * k + 2); }, // 正弦曲线的缓动(sin(t)) /** * @param {number} k * @return {number} */ sinusoidalIn: function (k) { return 1 - Math.cos(k * Math.PI / 2); }, /** * @param {number} k * @return {number} */ sinusoidalOut: function (k) { return Math.sin(k * Math.PI / 2); }, /** * @param {number} k * @return {number} */ sinusoidalInOut: function (k) { return 0.5 * (1 - Math.cos(Math.PI * k)); }, // 指数曲线的缓动(2^t) /** * @param {number} k * @return {number} */ exponentialIn: function (k) { return k === 0 ? 0 : Math.pow(1024, k - 1); }, /** * @param {number} k * @return {number} */ exponentialOut: function (k) { return k === 1 ? 1 : 1 - Math.pow(2, -10 * k); }, /** * @param {number} k * @return {number} */ exponentialInOut: function (k) { if (k === 0) { return 0; } if (k === 1) { return 1; } if ((k *= 2) < 1) { return 0.5 * Math.pow(1024, k - 1); } return 0.5 * (-Math.pow(2, -10 * (k - 1)) + 2); }, // 圆形曲线的缓动(sqrt(1-t^2)) /** * @param {number} k * @return {number} */ circularIn: function (k) { return 1 - Math.sqrt(1 - k * k); }, /** * @param {number} k * @return {number} */ circularOut: function (k) { return Math.sqrt(1 - (--k * k)); }, /** * @param {number} k * @return {number} */ circularInOut: function (k) { if ((k *= 2) < 1) { return -0.5 * (Math.sqrt(1 - k * k) - 1); } return 0.5 * (Math.sqrt(1 - (k -= 2) * k) + 1); }, // 创建类似于弹簧在停止前来回振荡的动画 /** * @param {number} k * @return {number} */ elasticIn: function (k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } return -(a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); }, /** * @param {number} k * @return {number} */ elasticOut: function (k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } return (a * Math.pow(2, -10 * k) * Math.sin((k - s) * (2 * Math.PI) / p) + 1); }, /** * @param {number} k * @return {number} */ elasticInOut: function (k) { var s; var a = 0.1; var p = 0.4; if (k === 0) { return 0; } if (k === 1) { return 1; } if (!a || a < 1) { a = 1; s = p / 4; } else { s = p * Math.asin(1 / a) / (2 * Math.PI); } if ((k *= 2) < 1) { return -0.5 * (a * Math.pow(2, 10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p)); } return a * Math.pow(2, -10 * (k -= 1)) * Math.sin((k - s) * (2 * Math.PI) / p) * 0.5 + 1; }, // 在某一动画开始沿指示的路径进行动画处理前稍稍收回该动画的移动 /** * @param {number} k * @return {number} */ backIn: function (k) { var s = 1.70158; return k * k * ((s + 1) * k - s); }, /** * @param {number} k * @return {number} */ backOut: function (k) { var s = 1.70158; return --k * k * ((s + 1) * k + s) + 1; }, /** * @param {number} k * @return {number} */ backInOut: function (k) { var s = 1.70158 * 1.525; if ((k *= 2) < 1) { return 0.5 * (k * k * ((s + 1) * k - s)); } return 0.5 * ((k -= 2) * k * ((s + 1) * k + s) + 2); }, // 创建弹跳效果 /** * @param {number} k * @return {number} */ bounceIn: function (k) { return 1 - easing.bounceOut(1 - k); }, /** * @param {number} k * @return {number} */ bounceOut: function (k) { if (k < (1 / 2.75)) { return 7.5625 * k * k; } else if (k < (2 / 2.75)) { return 7.5625 * (k -= (1.5 / 2.75)) * k + 0.75; } else if (k < (2.5 / 2.75)) { return 7.5625 * (k -= (2.25 / 2.75)) * k + 0.9375; } else { return 7.5625 * (k -= (2.625 / 2.75)) * k + 0.984375; } }, /** * @param {number} k * @return {number} */ bounceInOut: function (k) { if (k < 0.5) { return easing.bounceIn(k * 2) * 0.5; } return easing.bounceOut(k * 2 - 1) * 0.5 + 0.5; } }; /** * 动画主控制器 * @config target 动画对象,可以是数组,如果是数组的话会批量分发onframe等事件 * @config life(1000) 动画时长 * @config delay(0) 动画延迟时间 * @config loop(true) * @config gap(0) 循环的间隔时间 * @config onframe * @config easing(optional) * @config ondestroy(optional) * @config onrestart(optional) * * TODO pause */ function Clip(options) { this._target = options.target; // 生命周期 this._life = options.life || 1000; // 延时 this._delay = options.delay || 0; // 开始时间 // this._startTime = new Date().getTime() + this._delay;// 单位毫秒 this._initialized = false; // 是否循环 this.loop = options.loop == null ? false : options.loop; this.gap = options.gap || 0; this.easing = options.easing || 'Linear'; this.onframe = options.onframe; this.ondestroy = options.ondestroy; this.onrestart = options.onrestart; this._pausedTime = 0; this._paused = false; } Clip.prototype = { constructor: Clip, step: function (globalTime, deltaTime) { // Set startTime on first step, or _startTime may has milleseconds different between clips // PENDING if (!this._initialized) { this._startTime = globalTime + this._delay; this._initialized = true; } if (this._paused) { this._pausedTime += deltaTime; return; } var percent = (globalTime - this._startTime - this._pausedTime) / this._life; // 还没开始 if (percent < 0) { return; } percent = Math.min(percent, 1); var easing$$1 = this.easing; var easingFunc = typeof easing$$1 == 'string' ? easing[easing$$1] : easing$$1; var schedule = typeof easingFunc === 'function' ? easingFunc(percent) : percent; this.fire('frame', schedule); // 结束 if (percent == 1) { if (this.loop) { this.restart (globalTime); // 重新开始周期 // 抛出而不是直接调用事件直到 stage.update 后再统一调用这些事件 return 'restart'; } // 动画完成将这个控制器标识为待删除 // 在Animation.update中进行批量删除 this._needsRemove = true; return 'destroy'; } return null; }, restart: function (globalTime) { var remainder = (globalTime - this._startTime - this._pausedTime) % this._life; this._startTime = globalTime - remainder + this.gap; this._pausedTime = 0; this._needsRemove = false; }, fire: function (eventType, arg) { eventType = 'on' + eventType; if (this[eventType]) { this[eventType](this._target, arg); } }, pause: function () { this._paused = true; }, resume: function () { this._paused = false; } }; // Simple LRU cache use doubly linked list // @module zrender/core/LRU /** * Simple double linked list. Compared with array, it has O(1) remove operation. * @constructor */ var LinkedList = function () { /** * @type {module:zrender/core/LRU~Entry} */ this.head = null; /** * @type {module:zrender/core/LRU~Entry} */ this.tail = null; this._len = 0; }; var linkedListProto = LinkedList.prototype; /** * Insert a new value at the tail * @param {} val * @return {module:zrender/core/LRU~Entry} */ linkedListProto.insert = function (val) { var entry = new Entry(val); this.insertEntry(entry); return entry; }; /** * Insert an entry at the tail * @param {module:zrender/core/LRU~Entry} entry */ linkedListProto.insertEntry = function (entry) { if (!this.head) { this.head = this.tail = entry; } else { this.tail.next = entry; entry.prev = this.tail; entry.next = null; this.tail = entry; } this._len++; }; /** * Remove entry. * @param {module:zrender/core/LRU~Entry} entry */ linkedListProto.remove = function (entry) { var prev = entry.prev; var next = entry.next; if (prev) { prev.next = next; } else { // Is head this.head = next; } if (next) { next.prev = prev; } else { // Is tail this.tail = prev; } entry.next = entry.prev = null; this._len--; }; /** * @return {number} */ linkedListProto.len = function () { return this._len; }; /** * Clear list */ linkedListProto.clear = function () { this.head = this.tail = null; this._len = 0; }; /** * @constructor * @param {} val */ var Entry = function (val) { /** * @type {} */ this.value = val; /** * @type {module:zrender/core/LRU~Entry} */ this.next; /** * @type {module:zrender/core/LRU~Entry} */ this.prev; }; /** * LRU Cache * @constructor * @alias module:zrender/core/LRU */ var LRU = function (maxSize) { this._list = new LinkedList(); this._map = {}; this._maxSize = maxSize || 10; this._lastRemovedEntry = null; }; var LRUProto = LRU.prototype; /** * @param {string} key * @param {} value * @return {} Removed value */ LRUProto.put = function (key, value) { var list = this._list; var map = this._map; var removed = null; if (map[key] == null) { var len = list.len(); // Reuse last removed entry var entry = this._lastRemovedEntry; if (len >= this._maxSize && len > 0) { // Remove the least recently used var leastUsedEntry = list.head; list.remove(leastUsedEntry); delete map[leastUsedEntry.key]; removed = leastUsedEntry.value; this._lastRemovedEntry = leastUsedEntry; } if (entry) { entry.value = value; } else { entry = new Entry(value); } entry.key = key; list.insertEntry(entry); map[key] = entry; } return removed; }; /** * @param {string} key * @return {} */ LRUProto.get = function (key) { var entry = this._map[key]; var list = this._list; if (entry != null) { // Put the latest used entry in the tail if (entry !== list.tail) { list.remove(entry); list.insertEntry(entry); } return entry.value; } }; /** * Clear the cache */ LRUProto.clear = function () { this._list.clear(); this._map = {}; }; var kCSSColorTable = { 'transparent': [0,0,0,0], 'aliceblue': [240,248,255,1], 'antiquewhite': [250,235,215,1], 'aqua': [0,255,255,1], 'aquamarine': [127,255,212,1], 'azure': [240,255,255,1], 'beige': [245,245,220,1], 'bisque': [255,228,196,1], 'black': [0,0,0,1], 'blanchedalmond': [255,235,205,1], 'blue': [0,0,255,1], 'blueviolet': [138,43,226,1], 'brown': [165,42,42,1], 'burlywood': [222,184,135,1], 'cadetblue': [95,158,160,1], 'chartreuse': [127,255,0,1], 'chocolate': [210,105,30,1], 'coral': [255,127,80,1], 'cornflowerblue': [100,149,237,1], 'cornsilk': [255,248,220,1], 'crimson': [220,20,60,1], 'cyan': [0,255,255,1], 'darkblue': [0,0,139,1], 'darkcyan': [0,139,139,1], 'darkgoldenrod': [184,134,11,1], 'darkgray': [169,169,169,1], 'darkgreen': [0,100,0,1], 'darkgrey': [169,169,169,1], 'darkkhaki': [189,183,107,1], 'darkmagenta': [139,0,139,1], 'darkolivegreen': [85,107,47,1], 'darkorange': [255,140,0,1], 'darkorchid': [153,50,204,1], 'darkred': [139,0,0,1], 'darksalmon': [233,150,122,1], 'darkseagreen': [143,188,143,1], 'darkslateblue': [72,61,139,1], 'darkslategray': [47,79,79,1], 'darkslategrey': [47,79,79,1], 'darkturquoise': [0,206,209,1], 'darkviolet': [148,0,211,1], 'deeppink': [255,20,147,1], 'deepskyblue': [0,191,255,1], 'dimgray': [105,105,105,1], 'dimgrey': [105,105,105,1], 'dodgerblue': [30,144,255,1], 'firebrick': [178,34,34,1], 'floralwhite': [255,250,240,1], 'forestgreen': [34,139,34,1], 'fuchsia': [255,0,255,1], 'gainsboro': [220,220,220,1], 'ghostwhite': [248,248,255,1], 'gold': [255,215,0,1], 'goldenrod': [218,165,32,1], 'gray': [128,128,128,1], 'green': [0,128,0,1], 'greenyellow': [173,255,47,1], 'grey': [128,128,128,1], 'honeydew': [240,255,240,1], 'hotpink': [255,105,180,1], 'indianred': [205,92,92,1], 'indigo': [75,0,130,1], 'ivory': [255,255,240,1], 'khaki': [240,230,140,1], 'lavender': [230,230,250,1], 'lavenderblush': [255,240,245,1], 'lawngreen': [124,252,0,1], 'lemonchiffon': [255,250,205,1], 'lightblue': [173,216,230,1], 'lightcoral': [240,128,128,1], 'lightcyan': [224,255,255,1], 'lightgoldenrodyellow': [250,250,210,1], 'lightgray': [211,211,211,1], 'lightgreen': [144,238,144,1], 'lightgrey': [211,211,211,1], 'lightpink': [255,182,193,1], 'lightsalmon': [255,160,122,1], 'lightseagreen': [32,178,170,1], 'lightskyblue': [135,206,250,1], 'lightslategray': [119,136,153,1], 'lightslategrey': [119,136,153,1], 'lightsteelblue': [176,196,222,1], 'lightyellow': [255,255,224,1], 'lime': [0,255,0,1], 'limegreen': [50,205,50,1], 'linen': [250,240,230,1], 'magenta': [255,0,255,1], 'maroon': [128,0,0,1], 'mediumaquamarine': [102,205,170,1], 'mediumblue': [0,0,205,1], 'mediumorchid': [186,85,211,1], 'mediumpurple': [147,112,219,1], 'mediumseagreen': [60,179,113,1], 'mediumslateblue': [123,104,238,1], 'mediumspringgreen': [0,250,154,1], 'mediumturquoise': [72,209,204,1], 'mediumvioletred': [199,21,133,1], 'midnightblue': [25,25,112,1], 'mintcream': [245,255,250,1], 'mistyrose': [255,228,225,1], 'moccasin': [255,228,181,1], 'navajowhite': [255,222,173,1], 'navy': [0,0,128,1], 'oldlace': [253,245,230,1], 'olive': [128,128,0,1], 'olivedrab': [107,142,35,1], 'orange': [255,165,0,1], 'orangered': [255,69,0,1], 'orchid': [218,112,214,1], 'palegoldenrod': [238,232,170,1], 'palegreen': [152,251,152,1], 'paleturquoise': [175,238,238,1], 'palevioletred': [219,112,147,1], 'papayawhip': [255,239,213,1], 'peachpuff': [255,218,185,1], 'peru': [205,133,63,1], 'pink': [255,192,203,1], 'plum': [221,160,221,1], 'powderblue': [176,224,230,1], 'purple': [128,0,128,1], 'red': [255,0,0,1], 'rosybrown': [188,143,143,1], 'royalblue': [65,105,225,1], 'saddlebrown': [139,69,19,1], 'salmon': [250,128,114,1], 'sandybrown': [244,164,96,1], 'seagreen': [46,139,87,1], 'seashell': [255,245,238,1], 'sienna': [160,82,45,1], 'silver': [192,192,192,1], 'skyblue': [135,206,235,1], 'slateblue': [106,90,205,1], 'slategray': [112,128,144,1], 'slategrey': [112,128,144,1], 'snow': [255,250,250,1], 'springgreen': [0,255,127,1], 'steelblue': [70,130,180,1], 'tan': [210,180,140,1], 'teal': [0,128,128,1], 'thistle': [216,191,216,1], 'tomato': [255,99,71,1], 'turquoise': [64,224,208,1], 'violet': [238,130,238,1], 'wheat': [245,222,179,1], 'white': [255,255,255,1], 'whitesmoke': [245,245,245,1], 'yellow': [255,255,0,1], 'yellowgreen': [154,205,50,1] }; function clampCssByte(i) { // Clamp to integer 0 .. 255. i = Math.round(i); // Seems to be what Chrome does (vs truncation). return i < 0 ? 0 : i > 255 ? 255 : i; } function clampCssFloat(f) { // Clamp to float 0.0 .. 1.0. return f < 0 ? 0 : f > 1 ? 1 : f; } function parseCssInt(str) { // int or percentage. if (str.length && str.charAt(str.length - 1) === '%') { return clampCssByte(parseFloat(str) / 100 * 255); } return clampCssByte(parseInt(str, 10)); } function parseCssFloat(str) { // float or percentage. if (str.length && str.charAt(str.length - 1) === '%') { return clampCssFloat(parseFloat(str) / 100); } return clampCssFloat(parseFloat(str)); } function cssHueToRgb(m1, m2, h) { if (h < 0) { h += 1; } else if (h > 1) { h -= 1; } if (h * 6 < 1) { return m1 + (m2 - m1) * h * 6; } if (h * 2 < 1) { return m2; } if (h * 3 < 2) { return m1 + (m2 - m1) * (2/3 - h) * 6; } return m1; } function setRgba(out, r, g, b, a) { out[0] = r; out[1] = g; out[2] = b; out[3] = a; return out; } function copyRgba(out, a) { out[0] = a[0]; out[1] = a[1]; out[2] = a[2]; out[3] = a[3]; return out; } var colorCache = new LRU(20); var lastRemovedArr = null; function putToCache(colorStr, rgbaArr) { // Reuse removed array if (lastRemovedArr) { copyRgba(lastRemovedArr, rgbaArr); } lastRemovedArr = colorCache.put(colorStr, lastRemovedArr || (rgbaArr.slice())); } /** * @param {string} colorStr * @param {Array.<number>} out * @return {Array.<number>} * @memberOf module:zrender/util/color */ function parse(colorStr, rgbaArr) { if (!colorStr) { return; } rgbaArr = rgbaArr || []; var cached = colorCache.get(colorStr); if (cached) { return copyRgba(rgbaArr, cached); } // colorStr may be not string colorStr = colorStr + ''; // Remove all whitespace, not compliant, but should just be more accepting. var str = colorStr.replace(/ /g, '').toLowerCase(); // Color keywords (and transparent) lookup. if (str in kCSSColorTable) { copyRgba(rgbaArr, kCSSColorTable[str]); putToCache(colorStr, rgbaArr); return rgbaArr; } // #abc and #abc123 syntax. if (str.charAt(0) === '#') { if (str.length === 4) { var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. if (!(iv >= 0 && iv <= 0xfff)) { setRgba(rgbaArr, 0, 0, 0, 1); return; // Covers NaN. } setRgba(rgbaArr, ((iv & 0xf00) >> 4) | ((iv & 0xf00) >> 8), (iv & 0xf0) | ((iv & 0xf0) >> 4), (iv & 0xf) | ((iv & 0xf) << 4), 1 ); putToCache(colorStr, rgbaArr); return rgbaArr; } else if (str.length === 7) { var iv = parseInt(str.substr(1), 16); // TODO(deanm): Stricter parsing. if (!(iv >= 0 && iv <= 0xffffff)) { setRgba(rgbaArr, 0, 0, 0, 1); return; // Covers NaN. } setRgba(rgbaArr, (iv & 0xff0000) >> 16, (iv & 0xff00) >> 8, iv & 0xff, 1 ); putToCache(colorStr, rgbaArr); return rgbaArr; } return; } var op = str.indexOf('('), ep = str.indexOf(')'); if (op !== -1 && ep + 1 === str.length) { var fname = str.substr(0, op); var params = str.substr(op + 1, ep - (op + 1)).split(','); var alpha = 1; // To allow case fallthrough. switch (fname) { case 'rgba': if (params.length !== 4) { setRgba(rgbaArr, 0, 0, 0, 1); return; } alpha = parseCssFloat(params.pop()); // jshint ignore:line // Fall through. case 'rgb': if (params.length !== 3) { setRgba(rgbaArr, 0, 0, 0, 1); return; } setRgba(rgbaArr, parseCssInt(params[0]), parseCssInt(params[1]), parseCssInt(params[2]), alpha ); putToCache(colorStr, rgbaArr); return rgbaArr; case 'hsla': if (params.length !== 4) { setRgba(rgbaArr, 0, 0, 0, 1); return; } params[3] = parseCssFloat(params[3]); hsla2rgba(params, rgbaArr); putToCache(colorStr, rgbaArr); return rgbaArr; case 'hsl': if (params.length !== 3) { setRgba(rgbaArr, 0, 0, 0, 1); return; } hsla2rgba(params, rgbaArr); putToCache(colorStr, rgbaArr); return rgbaArr; default: return; } } setRgba(rgbaArr, 0, 0, 0, 1); return; } /** * @param {Array.<number>} hsla * @param {Array.<number>} rgba * @return {Array.<number>} rgba */ function hsla2rgba(hsla, rgba) { var h = (((parseFloat(hsla[0]) % 360) + 360) % 360) / 360; // 0 .. 1 // NOTE(deanm): According to the CSS spec s/l should only be // percentages, but we don't bother and let float or percentage. var s = parseCssFloat(hsla[1]); var l = parseCssFloat(hsla[2]); var m2 = l <= 0.5 ? l * (s + 1) : l + s - l * s; var m1 = l * 2 - m2; rgba = rgba || []; setRgba(rgba, clampCssByte(cssHueToRgb(m1, m2, h + 1 / 3) * 255), clampCssByte(cssHueToRgb(m1, m2, h) * 255), clampCssByte(cssHueToRgb(m1, m2, h - 1 / 3) * 255), 1 ); if (hsla.length === 4) { rgba[3] = hsla[3]; } return rgba; } /** * @param {string} color * @param {number} level * @return {string} * @memberOf module:zrender/util/color */ function lift(color, level) { var colorArr = parse(color); if (colorArr) { for (var i = 0; i < 3; i++) { if (level < 0) { colorArr[i] = colorArr[i] * (1 - level) | 0; } else { colorArr[i] = ((255 - colorArr[i]) * level + colorArr[i]) | 0; } } return stringify(colorArr, colorArr.length === 4 ? 'rgba' : 'rgb'); } } /** * @param {string} color * @return {string} * @memberOf module:zrender/util/color */ /** * Map value to color. Faster than lerp methods because color is represented by rgba array. * @param {number} normalizedValue A float between 0 and 1. * @param {Array.<Array.<number>>} colors List of rgba color array * @param {Array.<number>} [out] Mapped gba color array * @return {Array.<number>} will be null/undefined if input illegal. */ /** * @deprecated */ /** * @param {number} normalizedValue A float between 0 and 1. * @param {Array.<string>} colors Color list. * @param {boolean=} fullOutput Default false. * @return {(string|Object)} Result color. If fullOutput, * return {color: ..., leftIndex: ..., rightIndex: ..., value: ...}, * @memberOf module:zrender/util/color */ /** * @deprecated */ /** * @param {string} color * @param {number=} h 0 ~ 360, ignore when null. * @param {number=} s 0 ~ 1, ignore when null. * @param {number=} l 0 ~ 1, ignore when null. * @return {string} Color string in rgba format. * @memberOf module:zrender/util/color */ /** * @param {string} color * @param {number=} alpha 0 ~ 1 * @return {string} Color string in rgba format. * @memberOf module:zrender/util/color */ /** * @param {Array.<number>} arrColor like [12,33,44,0.4] * @param {string} type 'rgba', 'hsva', ... * @return {string} Result color. (If input illegal, return undefined). */ function stringify(arrColor, type) { if (!arrColor || !arrColor.length) { return; } var colorStr = arrColor[0] + ',' + arrColor[1] + ',' + arrColor[2]; if (type === 'rgba' || type === 'hsva' || type === 'hsla') { colorStr += ',' + arrColor[3]; } return type + '(' + colorStr + ')'; } /** * @module echarts/animation/Animator */ var arraySlice = Array.prototype.slice; function defaultGetter(target, key) { return target[key]; } function defaultSetter(target, key, value) { target[key] = value; } /** * @param {number} p0 * @param {number} p1 * @param {number} percent * @return {number} */ function interpolateNumber(p0, p1, percent) { return (p1 - p0) * percent + p0; } /** * @param {string} p0 * @param {string} p1 * @param {number} percent * @return {string} */ function interpolateString(p0, p1, percent) { return percent > 0.5 ? p1 : p0; } /** * @param {Array} p0 * @param {Array} p1 * @param {number} percent * @param {Array} out * @param {number} arrDim */ function interpolateArray(p0, p1, percent, out, arrDim) { var len = p0.length; if (arrDim == 1) { for (var i = 0; i < len; i++) { out[i] = interpolateNumber(p0[i], p1[i], percent); } } else { var len2 = len && p0[0].length; for (var i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { out[i][j] = interpolateNumber( p0[i][j], p1[i][j], percent ); } } } } // arr0 is source array, arr1 is target array. // Do some preprocess to avoid error happened when interpolating from arr0 to arr1 function fillArr(arr0, arr1, arrDim) { var arr0Len = arr0.length; var arr1Len = arr1.length; if (arr0Len !== arr1Len) { // FIXME Not work for TypedArray var isPreviousLarger = arr0Len > arr1Len; if (isPreviousLarger) { // Cut the previous arr0.length = arr1Len; } else { // Fill the previous for (var i = arr0Len; i < arr1Len; i++) { arr0.push( arrDim === 1 ? arr1[i] : arraySlice.call(arr1[i]) ); } } } // Handling NaN value var len2 = arr0[0] && arr0[0].length; for (var i = 0; i < arr0.length; i++) { if (arrDim === 1) { if (isNaN(arr0[i])) { arr0[i] = arr1[i]; } } else { for (var j = 0; j < len2; j++) { if (isNaN(arr0[i][j])) { arr0[i][j] = arr1[i][j]; } } } } } /** * @param {Array} arr0 * @param {Array} arr1 * @param {number} arrDim * @return {boolean} */ function isArraySame(arr0, arr1, arrDim) { if (arr0 === arr1) { return true; } var len = arr0.length; if (len !== arr1.length) { return false; } if (arrDim === 1) { for (var i = 0; i < len; i++) { if (arr0[i] !== arr1[i]) { return false; } } } else { var len2 = arr0[0].length; for (var i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { if (arr0[i][j] !== arr1[i][j]) { return false; } } } } return true; } /** * Catmull Rom interpolate array * @param {Array} p0 * @param {Array} p1 * @param {Array} p2 * @param {Array} p3 * @param {number} t * @param {number} t2 * @param {number} t3 * @param {Array} out * @param {number} arrDim */ function catmullRomInterpolateArray( p0, p1, p2, p3, t, t2, t3, out, arrDim ) { var len = p0.length; if (arrDim == 1) { for (var i = 0; i < len; i++) { out[i] = catmullRomInterpolate( p0[i], p1[i], p2[i], p3[i], t, t2, t3 ); } } else { var len2 = p0[0].length; for (var i = 0; i < len; i++) { for (var j = 0; j < len2; j++) { out[i][j] = catmullRomInterpolate( p0[i][j], p1[i][j], p2[i][j], p3[i][j], t, t2, t3 ); } } } } /** * Catmull Rom interpolate number * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} t * @param {number} t2 * @param {number} t3 * @return {number} */ function catmullRomInterpolate(p0, p1, p2, p3, t, t2, t3) { var v0 = (p2 - p0) * 0.5; var v1 = (p3 - p1) * 0.5; return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1; } function cloneValue(value) { if (isArrayLike(value)) { var len = value.length; if (isArrayLike(value[0])) { var ret = []; for (var i = 0; i < len; i++) { ret.push(arraySlice.call(value[i])); } return ret; } return arraySlice.call(value); } return value; } function rgba2String(rgba) { rgba[0] = Math.floor(rgba[0]); rgba[1] = Math.floor(rgba[1]); rgba[2] = Math.floor(rgba[2]); return 'rgba(' + rgba.join(',') + ')'; } function getArrayDim(keyframes) { var lastValue = keyframes[keyframes.length - 1].value; return isArrayLike(lastValue && lastValue[0]) ? 2 : 1; } function createTrackClip(animator, easing, oneTrackDone, keyframes, propName, forceAnimate) { var getter = animator._getter; var setter = animator._setter; var useSpline = easing === 'spline'; var trackLen = keyframes.length; if (!trackLen) { return; } // Guess data type var firstVal = keyframes[0].value; var isValueArray = isArrayLike(firstVal); var isValueColor = false; var isValueString = false; // For vertices morphing var arrDim = isValueArray ? getArrayDim(keyframes) : 0; var trackMaxTime; // Sort keyframe as ascending keyframes.sort(function(a, b) { return a.time - b.time; }); trackMaxTime = keyframes[trackLen - 1].time; // Percents of each keyframe var kfPercents = []; // Value of each keyframe var kfValues = []; var prevValue = keyframes[0].value; var isAllValueEqual = true; for (var i = 0; i < trackLen; i++) { kfPercents.push(keyframes[i].time / trackMaxTime); // Assume value is a color when it is a string var value = keyframes[i].value; // Check if value is equal, deep check if value is array if (!((isValueArray && isArraySame(value, prevValue, arrDim)) || (!isValueArray && value === prevValue))) { isAllValueEqual = false; } prevValue = value; // Try converting a string to a color array if (typeof value == 'string') { var colorArray = parse(value); if (colorArray) { value = colorArray; isValueColor = true; } else { isValueString = true; } } kfValues.push(value); } if (!forceAnimate && isAllValueEqual) { return; } var lastValue = kfValues[trackLen - 1]; // Polyfill array and NaN value for (var i = 0; i < trackLen - 1; i++) { if (isValueArray) { fillArr(kfValues[i], lastValue, arrDim); } else { if (isNaN(kfValues[i]) && !isNaN(lastValue) && !isValueString && !isValueColor) { kfValues[i] = lastValue; } } } isValueArray && fillArr(getter(animator._target, propName), lastValue, arrDim); // Cache the key of last frame to speed up when // animation playback is sequency var lastFrame = 0; var lastFramePercent = 0; var start; var w; var p0; var p1; var p2; var p3; if (isValueColor) { var rgba = [0, 0, 0, 0]; } var onframe = function (target, percent) { // Find the range keyframes // kf1-----kf2---------current--------kf3 // find kf2 and kf3 and do interpolation var frame; // In the easing function like elasticOut, percent may less than 0 if (percent < 0) { frame = 0; } else if (percent < lastFramePercent) { // Start from next key // PENDING start from lastFrame ? start = Math.min(lastFrame + 1, trackLen - 1); for (frame = start; frame >= 0; frame--) { if (kfPercents[frame] <= percent) { break; } } // PENDING really need to do this ? frame = Math.min(frame, trackLen - 2); } else { for (frame = lastFrame; frame < trackLen; frame++) { if (kfPercents[frame] > percent) { break; } } frame = Math.min(frame - 1, trackLen - 2); } lastFrame = frame; lastFramePercent = percent; var range = (kfPercents[frame + 1] - kfPercents[frame]); if (range === 0) { return; } else { w = (percent - kfPercents[frame]) / range; } if (useSpline) { p1 = kfValues[frame]; p0 = kfValues[frame === 0 ? frame : frame - 1]; p2 = kfValues[frame > trackLen - 2 ? trackLen - 1 : frame + 1]; p3 = kfValues[frame > trackLen - 3 ? trackLen - 1 : frame + 2]; if (isValueArray) { catmullRomInterpolateArray( p0, p1, p2, p3, w, w * w, w * w * w, getter(target, propName), arrDim ); } else { var value; if (isValueColor) { value = catmullRomInterpolateArray( p0, p1, p2, p3, w, w * w, w * w * w, rgba, 1 ); value = rgba2String(rgba); } else if (isValueString) { // String is step(0.5) return interpolateString(p1, p2, w); } else { value = catmullRomInterpolate( p0, p1, p2, p3, w, w * w, w * w * w ); } setter( target, propName, value ); } } else { if (isValueArray) { interpolateArray( kfValues[frame], kfValues[frame + 1], w, getter(target, propName), arrDim ); } else { var value; if (isValueColor) { interpolateArray( kfValues[frame], kfValues[frame + 1], w, rgba, 1 ); value = rgba2String(rgba); } else if (isValueString) { // String is step(0.5) return interpolateString(kfValues[frame], kfValues[frame + 1], w); } else { value = interpolateNumber(kfValues[frame], kfValues[frame + 1], w); } setter( target, propName, value ); } } }; var clip = new Clip({ target: animator._target, life: trackMaxTime, loop: animator._loop, delay: animator._delay, onframe: onframe, ondestroy: oneTrackDone }); if (easing && easing !== 'spline') { clip.easing = easing; } return clip; } /** * @alias module:zrender/animation/Animator * @constructor * @param {Object} target * @param {boolean} loop * @param {Function} getter * @param {Function} setter */ var Animator = function(target, loop, getter, setter) { this._tracks = {}; this._target = target; this._loop = loop || false; this._getter = getter || defaultGetter; this._setter = setter || defaultSetter; this._clipCount = 0; this._delay = 0; this._doneList = []; this._onframeList = []; this._clipList = []; }; Animator.prototype = { /** * 设置动画关键帧 * @param {number} time 关键帧时间,单位是ms * @param {Object} props 关键帧的属性值,key-value表示 * @return {module:zrender/animation/Animator} */ when: function(time /* ms */, props) { var tracks = this._tracks; for (var propName in props) { if (!props.hasOwnProperty(propName)) { continue; } if (!tracks[propName]) { tracks[propName] = []; // Invalid value var value = this._getter(this._target, propName); if (value == null) { // zrLog('Invalid property ' + propName); continue; } // If time is 0 // Then props is given initialize value // Else // Initialize value from current prop value if (time !== 0) { tracks[propName].push({ time: 0, value: cloneValue(value) }); } } tracks[propName].push({ time: time, value: props[propName] }); } return this; }, /** * 添加动画每一帧的回调函数 * @param {Function} callback * @return {module:zrender/animation/Animator} */ during: function (callback) { this._onframeList.push(callback); return this; }, pause: function () { for (var i = 0; i < this._clipList.length; i++) { this._clipList[i].pause(); } this._paused = true; }, resume: function () { for (var i = 0; i < this._clipList.length; i++) { this._clipList[i].resume(); } this._paused = false; }, isPaused: function () { return !!this._paused; }, _doneCallback: function () { // Clear all tracks this._tracks = {}; // Clear all clips this._clipList.length = 0; var doneList = this._doneList; var len = doneList.length; for (var i = 0; i < len; i++) { doneList[i].call(this); } }, /** * 开始执行动画 * @param {string|Function} [easing] * 动画缓动函数,详见{@link module:zrender/animation/easing} * @param {boolean} forceAnimate * @return {module:zrender/animation/Animator} */ start: function (easing, forceAnimate) { var self = this; var clipCount = 0; var oneTrackDone = function() { clipCount--; if (!clipCount) { self._doneCallback(); } }; var lastClip; for (var propName in this._tracks) { if (!this._tracks.hasOwnProperty(propName)) { continue; } var clip = createTrackClip( this, easing, oneTrackDone, this._tracks[propName], propName, forceAnimate ); if (clip) { this._clipList.push(clip); clipCount++; // If start after added to animation if (this.animation) { this.animation.addClip(clip); } lastClip = clip; } } // Add during callback on the last clip if (lastClip) { var oldOnFrame = lastClip.onframe; lastClip.onframe = function (target, percent) { oldOnFrame(target, percent); for (var i = 0; i < self._onframeList.length; i++) { self._onframeList[i](target, percent); } }; } // This optimization will help the case that in the upper application // the view may be refreshed frequently, where animation will be // called repeatly but nothing changed. if (!clipCount) { this._doneCallback(); } return this; }, /** * 停止动画 * @param {boolean} forwardToLast If move to last frame before stop */ stop: function (forwardToLast) { var clipList = this._clipList; var animation = this.animation; for (var i = 0; i < clipList.length; i++) { var clip = clipList[i]; if (forwardToLast) { // Move to last frame before stop clip.onframe(this._target, 1); } animation && animation.removeClip(clip); } clipList.length = 0; }, /** * 设置动画延迟开始的时间 * @param {number} time 单位ms * @return {module:zrender/animation/Animator} */ delay: function (time) { this._delay = time; return this; }, /** * 添加动画结束的回调 * @param {Function} cb * @return {module:zrender/animation/Animator} */ done: function(cb) { if (cb) { this._doneList.push(cb); } return this; }, /** * @return {Array.<module:zrender/animation/Clip>} */ getClips: function () { return this._clipList; } }; var dpr = 1; // If in browser environment if (typeof window !== 'undefined') { dpr = Math.max(window.devicePixelRatio || 1, 1); } /** * config默认配置项 * @exports zrender/config * @author Kener (@Kener-林峰, kener.linfeng@gmail.com) */ /** * debug日志选项:catchBrushException为true下有效 * 0 : 不生成debug数据,发布用 * 1 : 异常抛出,调试用 * 2 : 控制台输出,调试用 */ var debugMode = 0; // retina 屏幕优化 var devicePixelRatio = dpr; var log = function () { }; if (debugMode === 1) { log = function () { for (var k in arguments) { throw new Error(arguments[k]); } }; } else if (debugMode > 1) { log = function () { for (var k in arguments) { console.log(arguments[k]); } }; } var log$1 = log; /** * @alias modue:zrender/mixin/Animatable * @constructor */ var Animatable = function () { /** * @type {Array.<module:zrender/animation/Animator>} * @readOnly */ this.animators = []; }; Animatable.prototype = { constructor: Animatable, /** * 动画 * * @param {string} path The path to fetch value from object, like 'a.b.c'. * @param {boolean} [loop] Whether to loop animation. * @return {module:zrender/animation/Animator} * @example: * el.animate('style', false) * .when(1000, {x: 10} ) * .done(function(){ // Animation done }) * .start() */ animate: function (path, loop) { var target; var animatingShape = false; var el = this; var zr = this.__zr; if (path) { var pathSplitted = path.split('.'); var prop = el; // If animating shape animatingShape = pathSplitted[0] === 'shape'; for (var i = 0, l = pathSplitted.length; i < l; i++) { if (!prop) { continue; } prop = prop[pathSplitted[i]]; } if (prop) { target = prop; } } else { target = el; } if (!target) { log$1( 'Property "' + path + '" is not existed in element ' + el.id ); return; } var animators = el.animators; var animator = new Animator(target, loop); animator.during(function (target) { el.dirty(animatingShape); }) .done(function () { // FIXME Animator will not be removed if use `Animator#stop` to stop animation animators.splice(indexOf(animators, animator), 1); }); animators.push(animator); // If animate after added to the zrender if (zr) { zr.animation.addAnimator(animator); } return animator; }, /** * 停止动画 * @param {boolean} forwardToLast If move to last frame before stop */ stopAnimation: function (forwardToLast) { var animators = this.animators; var len = animators.length; for (var i = 0; i < len; i++) { animators[i].stop(forwardToLast); } animators.length = 0; return this; }, /** * Caution: this method will stop previous animation. * So do not use this method to one element twice before * animation starts, unless you know what you are doing. * @param {Object} target * @param {number} [time=500] Time in ms * @param {string} [easing='linear'] * @param {number} [delay=0] * @param {Function} [callback] * @param {Function} [forceAnimate] Prevent stop animation and callback * immediently when target values are the same as current values. * * @example * // Animate position * el.animateTo({ * position: [10, 10] * }, function () { // done }) * * // Animate shape, style and position in 100ms, delayed 100ms, with cubicOut easing * el.animateTo({ * shape: { * width: 500 * }, * style: { * fill: 'red' * } * position: [10, 10] * }, 100, 100, 'cubicOut', function () { // done }) */ // TODO Return animation key animateTo: function (target, time, delay, easing, callback, forceAnimate) { // animateTo(target, time, easing, callback); if (isString(delay)) { callback = easing; easing = delay; delay = 0; } // animateTo(target, time, delay, callback); else if (isFunction(easing)) { callback = easing; easing = 'linear'; delay = 0; } // animateTo(target, time, callback); else if (isFunction(delay)) { callback = delay; delay = 0; } // animateTo(target, callback) else if (isFunction(time)) { callback = time; time = 500; } // animateTo(target) else if (!time) { time = 500; } // Stop all previous animations this.stopAnimation(); this._animateToShallow('', this, target, time, delay); // Animators may be removed immediately after start // if there is nothing to animate var animators = this.animators.slice(); var count = animators.length; function done() { count--; if (!count) { callback && callback(); } } // No animators. This should be checked before animators[i].start(), // because 'done' may be executed immediately if no need to animate. if (!count) { callback && callback(); } // Start after all animators created // Incase any animator is done immediately when all animation properties are not changed for (var i = 0; i < animators.length; i++) { animators[i] .done(done) .start(easing, forceAnimate); } }, /** * @private * @param {string} path='' * @param {Object} source=this * @param {Object} target * @param {number} [time=500] * @param {number} [delay=0] * * @example * // Animate position * el._animateToShallow({ * position: [10, 10] * }) * * // Animate shape, style and position in 100ms, delayed 100ms * el._animateToShallow({ * shape: { * width: 500 * }, * style: { * fill: 'red' * } * position: [10, 10] * }, 100, 100) */ _animateToShallow: function (path, source, target, time, delay) { var objShallow = {}; var propertyCount = 0; for (var name in target) { if (!target.hasOwnProperty(name)) { continue; } if (source[name] != null) { if (isObject(target[name]) && !isArrayLike(target[name])) { this._animateToShallow( path ? path + '.' + name : name, source[name], target[name], time, delay ); } else { objShallow[name] = target[name]; propertyCount++; } } else if (target[name] != null) { // Attr directly if not has property // FIXME, if some property not needed for element ? if (!path) { this.attr(name, target[name]); } else { // Shape or style var props = {}; props[path] = {}; props[path][name] = target[name]; this.attr(props); } } } if (propertyCount > 0) { this.animate(path, false) .when(time == null ? 500 : time, objShallow) .delay(delay || 0); } return this; } }; /** * @alias module:zrender/Element * @constructor * @extends {module:zrender/mixin/Animatable} * @extends {module:zrender/mixin/Transformable} * @extends {module:zrender/mixin/Eventful} */ var Element = function (opts) { // jshint ignore:line Transformable.call(this, opts); Eventful.call(this, opts); Animatable.call(this, opts); /** * 画布元素ID * @type {string} */ this.id = opts.id || guid(); }; Element.prototype = { /** * 元素类型 * Element type * @type {string} */ type: 'element', /** * 元素名字 * Element name * @type {string} */ name: '', /** * ZRender 实例对象,会在 element 添加到 zrender 实例中后自动赋值 * ZRender instance will be assigned when element is associated with zrender * @name module:/zrender/Element#__zr * @type {module:zrender/ZRender} */ __zr: null, /** * 图形是否忽略,为true时忽略图形的绘制以及事件触发 * If ignore drawing and events of the element object * @name module:/zrender/Element#ignore * @type {boolean} * @default false */ ignore: false, /** * 用于裁剪的路径(shape),所有 Group 内的路径在绘制时都会被这个路径裁剪 * 该路径会继承被裁减对象的变换 * @type {module:zrender/graphic/Path} * @see http://www.w3.org/TR/2dcontext/#clipping-region * @readOnly */ clipPath: null, /** * Drift element * @param {number} dx dx on the global space * @param {number} dy dy on the global space */ drift: function (dx, dy) { switch (this.draggable) { case 'horizontal': dy = 0; break; case 'vertical': dx = 0; break; } var m = this.transform; if (!m) { m = this.transform = [1, 0, 0, 1, 0, 0]; } m[4] += dx; m[5] += dy; this.decomposeTransform(); this.dirty(false); }, /** * Hook before update */ beforeUpdate: function () {}, /** * Hook after update */ afterUpdate: function () {}, /** * Update each frame */ update: function () { this.updateTransform(); }, /** * @param {Function} cb * @param {} context */ traverse: function (cb, context) {}, /** * @protected */ attrKV: function (key, value) { if (key === 'position' || key === 'scale' || key === 'origin') { // Copy the array if (value) { var target = this[key]; if (!target) { target = this[key] = []; } target[0] = value[0]; target[1] = value[1]; } } else { this[key] = value; } }, /** * Hide the element */ hide: function () { this.ignore = true; this.__zr && this.__zr.refresh(); }, /** * Show the element */ show: function () { this.ignore = false; this.__zr && this.__zr.refresh(); }, /** * @param {string|Object} key * @param {*} value */ attr: function (key, value) { if (typeof key === 'string') { this.attrKV(key, value); } else if (isObject(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { this.attrKV(name, key[name]); } } } this.dirty(false); return this; }, /** * @param {module:zrender/graphic/Path} clipPath */ setClipPath: function (clipPath) { var zr = this.__zr; if (zr) { clipPath.addSelfToZr(zr); } // Remove previous clip path if (this.clipPath && this.clipPath !== clipPath) { this.removeClipPath(); } this.clipPath = clipPath; clipPath.__zr = zr; clipPath.__clipTarget = this; this.dirty(false); }, /** */ removeClipPath: function () { var clipPath = this.clipPath; if (clipPath) { if (clipPath.__zr) { clipPath.removeSelfFromZr(clipPath.__zr); } clipPath.__zr = null; clipPath.__clipTarget = null; this.clipPath = null; this.dirty(false); } }, /** * Add self from zrender instance. * Not recursively because it will be invoked when element added to storage. * @param {module:zrender/ZRender} zr */ addSelfToZr: function (zr) { this.__zr = zr; // 添加动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.addAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.addSelfToZr(zr); } }, /** * Remove self from zrender instance. * Not recursively because it will be invoked when element added to storage. * @param {module:zrender/ZRender} zr */ removeSelfFromZr: function (zr) { this.__zr = null; // 移除动画 var animators = this.animators; if (animators) { for (var i = 0; i < animators.length; i++) { zr.animation.removeAnimator(animators[i]); } } if (this.clipPath) { this.clipPath.removeSelfFromZr(zr); } } }; mixin(Element, Animatable); mixin(Element, Transformable); mixin(Element, Eventful); /** * @module echarts/core/BoundingRect */ var v2ApplyTransform = applyTransform; var mathMin = Math.min; var mathMax = Math.max; /** * @alias module:echarts/core/BoundingRect */ function BoundingRect(x, y, width, height) { if (width < 0) { x = x + width; width = -width; } if (height < 0) { y = y + height; height = -height; } /** * @type {number} */ this.x = x; /** * @type {number} */ this.y = y; /** * @type {number} */ this.width = width; /** * @type {number} */ this.height = height; } BoundingRect.prototype = { constructor: BoundingRect, /** * @param {module:echarts/core/BoundingRect} other */ union: function (other) { var x = mathMin(other.x, this.x); var y = mathMin(other.y, this.y); this.width = mathMax( other.x + other.width, this.x + this.width ) - x; this.height = mathMax( other.y + other.height, this.y + this.height ) - y; this.x = x; this.y = y; }, /** * @param {Array.<number>} m * @methods */ applyTransform: (function () { var lt = []; var rb = []; var lb = []; var rt = []; return function (m) { // In case usage like this // el.getBoundingRect().applyTransform(el.transform) // And element has no transform if (!m) { return; } lt[0] = lb[0] = this.x; lt[1] = rt[1] = this.y; rb[0] = rt[0] = this.x + this.width; rb[1] = lb[1] = this.y + this.height; v2ApplyTransform(lt, lt, m); v2ApplyTransform(rb, rb, m); v2ApplyTransform(lb, lb, m); v2ApplyTransform(rt, rt, m); this.x = mathMin(lt[0], rb[0], lb[0], rt[0]); this.y = mathMin(lt[1], rb[1], lb[1], rt[1]); var maxX = mathMax(lt[0], rb[0], lb[0], rt[0]); var maxY = mathMax(lt[1], rb[1], lb[1], rt[1]); this.width = maxX - this.x; this.height = maxY - this.y; }; })(), /** * Calculate matrix of transforming from self to target rect * @param {module:zrender/core/BoundingRect} b * @return {Array.<number>} */ calculateTransform: function (b) { var a = this; var sx = b.width / a.width; var sy = b.height / a.height; var m = create$1(); // 矩阵右乘 translate(m, m, [-a.x, -a.y]); scale$1(m, m, [sx, sy]); translate(m, m, [b.x, b.y]); return m; }, /** * @param {(module:echarts/core/BoundingRect|Object)} b * @return {boolean} */ intersect: function (b) { if (!b) { return false; } if (!(b instanceof BoundingRect)) { // Normalize negative width/height. b = BoundingRect.create(b); } var a = this; var ax0 = a.x; var ax1 = a.x + a.width; var ay0 = a.y; var ay1 = a.y + a.height; var bx0 = b.x; var bx1 = b.x + b.width; var by0 = b.y; var by1 = b.y + b.height; return ! (ax1 < bx0 || bx1 < ax0 || ay1 < by0 || by1 < ay0); }, contain: function (x, y) { var rect = this; return x >= rect.x && x <= (rect.x + rect.width) && y >= rect.y && y <= (rect.y + rect.height); }, /** * @return {module:echarts/core/BoundingRect} */ clone: function () { return new BoundingRect(this.x, this.y, this.width, this.height); }, /** * Copy from another rect */ copy: function (other) { this.x = other.x; this.y = other.y; this.width = other.width; this.height = other.height; }, plain: function () { return { x: this.x, y: this.y, width: this.width, height: this.height }; } }; /** * @param {Object|module:zrender/core/BoundingRect} rect * @param {number} rect.x * @param {number} rect.y * @param {number} rect.width * @param {number} rect.height * @return {module:zrender/core/BoundingRect} */ BoundingRect.create = function (rect) { return new BoundingRect(rect.x, rect.y, rect.width, rect.height); }; /** * Group是一个容器,可以插入子节点,Group的变换也会被应用到子节点上 * @module zrender/graphic/Group * @example * var Group = require('zrender/container/Group'); * var Circle = require('zrender/graphic/shape/Circle'); * var g = new Group(); * g.position[0] = 100; * g.position[1] = 100; * g.add(new Circle({ * style: { * x: 100, * y: 100, * r: 20, * } * })); * zr.add(g); */ /** * @alias module:zrender/graphic/Group * @constructor * @extends module:zrender/mixin/Transformable * @extends module:zrender/mixin/Eventful */ var Group = function (opts) { opts = opts || {}; Element.call(this, opts); for (var key in opts) { if (opts.hasOwnProperty(key)) { this[key] = opts[key]; } } this._children = []; this.__storage = null; this.__dirty = true; }; Group.prototype = { constructor: Group, isGroup: true, /** * @type {string} */ type: 'group', /** * 所有子孙元素是否响应鼠标事件 * @name module:/zrender/container/Group#silent * @type {boolean} * @default false */ silent: false, /** * @return {Array.<module:zrender/Element>} */ children: function () { return this._children.slice(); }, /** * 获取指定 index 的儿子节点 * @param {number} idx * @return {module:zrender/Element} */ childAt: function (idx) { return this._children[idx]; }, /** * 获取指定名字的儿子节点 * @param {string} name * @return {module:zrender/Element} */ childOfName: function (name) { var children = this._children; for (var i = 0; i < children.length; i++) { if (children[i].name === name) { return children[i]; } } }, /** * @return {number} */ childCount: function () { return this._children.length; }, /** * 添加子节点到最后 * @param {module:zrender/Element} child */ add: function (child) { if (child && child !== this && child.parent !== this) { this._children.push(child); this._doAdd(child); } return this; }, /** * 添加子节点在 nextSibling 之前 * @param {module:zrender/Element} child * @param {module:zrender/Element} nextSibling */ addBefore: function (child, nextSibling) { if (child && child !== this && child.parent !== this && nextSibling && nextSibling.parent === this) { var children = this._children; var idx = children.indexOf(nextSibling); if (idx >= 0) { children.splice(idx, 0, child); this._doAdd(child); } } return this; }, _doAdd: function (child) { if (child.parent) { child.parent.remove(child); } child.parent = this; var storage = this.__storage; var zr = this.__zr; if (storage && storage !== child.__storage) { storage.addToStorage(child); if (child instanceof Group) { child.addChildrenToStorage(storage); } } zr && zr.refresh(); }, /** * 移除子节点 * @param {module:zrender/Element} child */ remove: function (child) { var zr = this.__zr; var storage = this.__storage; var children = this._children; var idx = indexOf(children, child); if (idx < 0) { return this; } children.splice(idx, 1); child.parent = null; if (storage) { storage.delFromStorage(child); if (child instanceof Group) { child.delChildrenFromStorage(storage); } } zr && zr.refresh(); return this; }, /** * 移除所有子节点 */ removeAll: function () { var children = this._children; var storage = this.__storage; var child; var i; for (i = 0; i < children.length; i++) { child = children[i]; if (storage) { storage.delFromStorage(child); if (child instanceof Group) { child.delChildrenFromStorage(storage); } } child.parent = null; } children.length = 0; return this; }, /** * 遍历所有子节点 * @param {Function} cb * @param {} context */ eachChild: function (cb, context) { var children = this._children; for (var i = 0; i < children.length; i++) { var child = children[i]; cb.call(context, child, i); } return this; }, /** * 深度优先遍历所有子孙节点 * @param {Function} cb * @param {} context */ traverse: function (cb, context) { for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; cb.call(context, child); if (child.type === 'group') { child.traverse(cb, context); } } return this; }, addChildrenToStorage: function (storage) { for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; storage.addToStorage(child); if (child instanceof Group) { child.addChildrenToStorage(storage); } } }, delChildrenFromStorage: function (storage) { for (var i = 0; i < this._children.length; i++) { var child = this._children[i]; storage.delFromStorage(child); if (child instanceof Group) { child.delChildrenFromStorage(storage); } } }, dirty: function () { this.__dirty = true; this.__zr && this.__zr.refresh(); return this; }, /** * @return {module:zrender/core/BoundingRect} */ getBoundingRect: function (includeChildren) { // TODO Caching var rect = null; var tmpRect = new BoundingRect(0, 0, 0, 0); var children = includeChildren || this._children; var tmpMat = []; for (var i = 0; i < children.length; i++) { var child = children[i]; if (child.ignore || child.invisible) { continue; } var childRect = child.getBoundingRect(); var transform = child.getLocalTransform(tmpMat); // TODO // The boundingRect cacluated by transforming original // rect may be bigger than the actual bundingRect when rotation // is used. (Consider a circle rotated aginst its center, where // the actual boundingRect should be the same as that not be // rotated.) But we can not find better approach to calculate // actual boundingRect yet, considering performance. if (transform) { tmpRect.copy(childRect); tmpRect.applyTransform(transform); rect = rect || tmpRect.clone(); rect.union(tmpRect); } else { rect = rect || childRect.clone(); rect.union(childRect); } } return rect || tmpRect; } }; inherits(Group, Element); // https://github.com/mziccard/node-timsort var DEFAULT_MIN_MERGE = 32; var DEFAULT_MIN_GALLOPING = 7; function minRunLength(n) { var r = 0; while (n >= DEFAULT_MIN_MERGE) { r |= n & 1; n >>= 1; } return n + r; } function makeAscendingRun(array, lo, hi, compare) { var runHi = lo + 1; if (runHi === hi) { return 1; } if (compare(array[runHi++], array[lo]) < 0) { while (runHi < hi && compare(array[runHi], array[runHi - 1]) < 0) { runHi++; } reverseRun(array, lo, runHi); } else { while (runHi < hi && compare(array[runHi], array[runHi - 1]) >= 0) { runHi++; } } return runHi - lo; } function reverseRun(array, lo, hi) { hi--; while (lo < hi) { var t = array[lo]; array[lo++] = array[hi]; array[hi--] = t; } } function binaryInsertionSort(array, lo, hi, start, compare) { if (start === lo) { start++; } for (; start < hi; start++) { var pivot = array[start]; var left = lo; var right = start; var mid; while (left < right) { mid = left + right >>> 1; if (compare(pivot, array[mid]) < 0) { right = mid; } else { left = mid + 1; } } var n = start - left; switch (n) { case 3: array[left + 3] = array[left + 2]; case 2: array[left + 2] = array[left + 1]; case 1: array[left + 1] = array[left]; break; default: while (n > 0) { array[left + n] = array[left + n - 1]; n--; } } array[left] = pivot; } } function gallopLeft(value, array, start, length, hint, compare) { var lastOffset = 0; var maxOffset = 0; var offset = 1; if (compare(value, array[start + hint]) > 0) { maxOffset = length - hint; while (offset < maxOffset && compare(value, array[start + hint + offset]) > 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } lastOffset += hint; offset += hint; } else { maxOffset = hint + 1; while (offset < maxOffset && compare(value, array[start + hint - offset]) <= 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } var tmp = lastOffset; lastOffset = hint - offset; offset = hint - tmp; } lastOffset++; while (lastOffset < offset) { var m = lastOffset + (offset - lastOffset >>> 1); if (compare(value, array[start + m]) > 0) { lastOffset = m + 1; } else { offset = m; } } return offset; } function gallopRight(value, array, start, length, hint, compare) { var lastOffset = 0; var maxOffset = 0; var offset = 1; if (compare(value, array[start + hint]) < 0) { maxOffset = hint + 1; while (offset < maxOffset && compare(value, array[start + hint - offset]) < 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } var tmp = lastOffset; lastOffset = hint - offset; offset = hint - tmp; } else { maxOffset = length - hint; while (offset < maxOffset && compare(value, array[start + hint + offset]) >= 0) { lastOffset = offset; offset = (offset << 1) + 1; if (offset <= 0) { offset = maxOffset; } } if (offset > maxOffset) { offset = maxOffset; } lastOffset += hint; offset += hint; } lastOffset++; while (lastOffset < offset) { var m = lastOffset + (offset - lastOffset >>> 1); if (compare(value, array[start + m]) < 0) { offset = m; } else { lastOffset = m + 1; } } return offset; } function TimSort(array, compare) { var minGallop = DEFAULT_MIN_GALLOPING; var runStart; var runLength; var stackSize = 0; var tmp = []; runStart = []; runLength = []; function pushRun(_runStart, _runLength) { runStart[stackSize] = _runStart; runLength[stackSize] = _runLength; stackSize += 1; } function mergeRuns() { while (stackSize > 1) { var n = stackSize - 2; if (n >= 1 && runLength[n - 1] <= runLength[n] + runLength[n + 1] || n >= 2 && runLength[n - 2] <= runLength[n] + runLength[n - 1]) { if (runLength[n - 1] < runLength[n + 1]) { n--; } } else if (runLength[n] > runLength[n + 1]) { break; } mergeAt(n); } } function forceMergeRuns() { while (stackSize > 1) { var n = stackSize - 2; if (n > 0 && runLength[n - 1] < runLength[n + 1]) { n--; } mergeAt(n); } } function mergeAt(i) { var start1 = runStart[i]; var length1 = runLength[i]; var start2 = runStart[i + 1]; var length2 = runLength[i + 1]; runLength[i] = length1 + length2; if (i === stackSize - 3) { runStart[i + 1] = runStart[i + 2]; runLength[i + 1] = runLength[i + 2]; } stackSize--; var k = gallopRight(array[start2], array, start1, length1, 0, compare); start1 += k; length1 -= k; if (length1 === 0) { return; } length2 = gallopLeft(array[start1 + length1 - 1], array, start2, length2, length2 - 1, compare); if (length2 === 0) { return; } if (length1 <= length2) { mergeLow(start1, length1, start2, length2); } else { mergeHigh(start1, length1, start2, length2); } } function mergeLow(start1, length1, start2, length2) { var i = 0; for (i = 0; i < length1; i++) { tmp[i] = array[start1 + i]; } var cursor1 = 0; var cursor2 = start2; var dest = start1; array[dest++] = array[cursor2++]; if (--length2 === 0) { for (i = 0; i < length1; i++) { array[dest + i] = tmp[cursor1 + i]; } return; } if (length1 === 1) { for (i = 0; i < length2; i++) { array[dest + i] = array[cursor2 + i]; } array[dest + length2] = tmp[cursor1]; return; } var _minGallop = minGallop; var count1, count2, exit; while (1) { count1 = 0; count2 = 0; exit = false; do { if (compare(array[cursor2], tmp[cursor1]) < 0) { array[dest++] = array[cursor2++]; count2++; count1 = 0; if (--length2 === 0) { exit = true; break; } } else { array[dest++] = tmp[cursor1++]; count1++; count2 = 0; if (--length1 === 1) { exit = true; break; } } } while ((count1 | count2) < _minGallop); if (exit) { break; } do { count1 = gallopRight(array[cursor2], tmp, cursor1, length1, 0, compare); if (count1 !== 0) { for (i = 0; i < count1; i++) { array[dest + i] = tmp[cursor1 + i]; } dest += count1; cursor1 += count1; length1 -= count1; if (length1 <= 1) { exit = true; break; } } array[dest++] = array[cursor2++]; if (--length2 === 0) { exit = true; break; } count2 = gallopLeft(tmp[cursor1], array, cursor2, length2, 0, compare); if (count2 !== 0) { for (i = 0; i < count2; i++) { array[dest + i] = array[cursor2 + i]; } dest += count2; cursor2 += count2; length2 -= count2; if (length2 === 0) { exit = true; break; } } array[dest++] = tmp[cursor1++]; if (--length1 === 1) { exit = true; break; } _minGallop--; } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); if (exit) { break; } if (_minGallop < 0) { _minGallop = 0; } _minGallop += 2; } minGallop = _minGallop; minGallop < 1 && (minGallop = 1); if (length1 === 1) { for (i = 0; i < length2; i++) { array[dest + i] = array[cursor2 + i]; } array[dest + length2] = tmp[cursor1]; } else if (length1 === 0) { throw new Error(); // throw new Error('mergeLow preconditions were not respected'); } else { for (i = 0; i < length1; i++) { array[dest + i] = tmp[cursor1 + i]; } } } function mergeHigh (start1, length1, start2, length2) { var i = 0; for (i = 0; i < length2; i++) { tmp[i] = array[start2 + i]; } var cursor1 = start1 + length1 - 1; var cursor2 = length2 - 1; var dest = start2 + length2 - 1; var customCursor = 0; var customDest = 0; array[dest--] = array[cursor1--]; if (--length1 === 0) { customCursor = dest - (length2 - 1); for (i = 0; i < length2; i++) { array[customCursor + i] = tmp[i]; } return; } if (length2 === 1) { dest -= length1; cursor1 -= length1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = length1 - 1; i >= 0; i--) { array[customDest + i] = array[customCursor + i]; } array[dest] = tmp[cursor2]; return; } var _minGallop = minGallop; while (true) { var count1 = 0; var count2 = 0; var exit = false; do { if (compare(tmp[cursor2], array[cursor1]) < 0) { array[dest--] = array[cursor1--]; count1++; count2 = 0; if (--length1 === 0) { exit = true; break; } } else { array[dest--] = tmp[cursor2--]; count2++; count1 = 0; if (--length2 === 1) { exit = true; break; } } } while ((count1 | count2) < _minGallop); if (exit) { break; } do { count1 = length1 - gallopRight(tmp[cursor2], array, start1, length1, length1 - 1, compare); if (count1 !== 0) { dest -= count1; cursor1 -= count1; length1 -= count1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = count1 - 1; i >= 0; i--) { array[customDest + i] = array[customCursor + i]; } if (length1 === 0) { exit = true; break; } } array[dest--] = tmp[cursor2--]; if (--length2 === 1) { exit = true; break; } count2 = length2 - gallopLeft(array[cursor1], tmp, 0, length2, length2 - 1, compare); if (count2 !== 0) { dest -= count2; cursor2 -= count2; length2 -= count2; customDest = dest + 1; customCursor = cursor2 + 1; for (i = 0; i < count2; i++) { array[customDest + i] = tmp[customCursor + i]; } if (length2 <= 1) { exit = true; break; } } array[dest--] = array[cursor1--]; if (--length1 === 0) { exit = true; break; } _minGallop--; } while (count1 >= DEFAULT_MIN_GALLOPING || count2 >= DEFAULT_MIN_GALLOPING); if (exit) { break; } if (_minGallop < 0) { _minGallop = 0; } _minGallop += 2; } minGallop = _minGallop; if (minGallop < 1) { minGallop = 1; } if (length2 === 1) { dest -= length1; cursor1 -= length1; customDest = dest + 1; customCursor = cursor1 + 1; for (i = length1 - 1; i >= 0; i--) { array[customDest + i] = array[customCursor + i]; } array[dest] = tmp[cursor2]; } else if (length2 === 0) { throw new Error(); // throw new Error('mergeHigh preconditions were not respected'); } else { customCursor = dest - (length2 - 1); for (i = 0; i < length2; i++) { array[customCursor + i] = tmp[i]; } } } this.mergeRuns = mergeRuns; this.forceMergeRuns = forceMergeRuns; this.pushRun = pushRun; } function sort(array, compare, lo, hi) { if (!lo) { lo = 0; } if (!hi) { hi = array.length; } var remaining = hi - lo; if (remaining < 2) { return; } var runLength = 0; if (remaining < DEFAULT_MIN_MERGE) { runLength = makeAscendingRun(array, lo, hi, compare); binaryInsertionSort(array, lo, hi, lo + runLength, compare); return; } var ts = new TimSort(array, compare); var minRun = minRunLength(remaining); do { runLength = makeAscendingRun(array, lo, hi, compare); if (runLength < minRun) { var force = remaining; if (force > minRun) { force = minRun; } binaryInsertionSort(array, lo, lo + force, lo + runLength, compare); runLength = force; } ts.pushRun(lo, runLength); ts.mergeRuns(); remaining -= runLength; lo += runLength; } while (remaining !== 0); ts.forceMergeRuns(); } /** * Storage内容仓库模块 * @module zrender/Storage * @author Kener (@Kener-林峰, kener.linfeng@gmail.com) * @author errorrik (errorrik@gmail.com) * @author pissang (https://github.com/pissang/) */ // Use timsort because in most case elements are partially sorted // https://jsfiddle.net/pissang/jr4x7mdm/8/ function shapeCompareFunc(a, b) { if (a.zlevel === b.zlevel) { if (a.z === b.z) { // if (a.z2 === b.z2) { // // FIXME Slow has renderidx compare // // http://stackoverflow.com/questions/20883421/sorting-in-javascript-should-every-compare-function-have-a-return-0-statement // // https://github.com/v8/v8/blob/47cce544a31ed5577ffe2963f67acb4144ee0232/src/js/array.js#L1012 // return a.__renderidx - b.__renderidx; // } return a.z2 - b.z2; } return a.z - b.z; } return a.zlevel - b.zlevel; } /** * 内容仓库 (M) * @alias module:zrender/Storage * @constructor */ var Storage = function () { // jshint ignore:line this._roots = []; this._displayList = []; this._displayListLen = 0; }; Storage.prototype = { constructor: Storage, /** * @param {Function} cb * */ traverse: function (cb, context) { for (var i = 0; i < this._roots.length; i++) { this._roots[i].traverse(cb, context); } }, /** * 返回所有图形的绘制队列 * @param {boolean} [update=false] 是否在返回前更新该数组 * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组, 在 update 为 true 的时候有效 * * 详见{@link module:zrender/graphic/Displayable.prototype.updateDisplayList} * @return {Array.<module:zrender/graphic/Displayable>} */ getDisplayList: function (update, includeIgnore) { includeIgnore = includeIgnore || false; if (update) { this.updateDisplayList(includeIgnore); } return this._displayList; }, /** * 更新图形的绘制队列。 * 每次绘制前都会调用,该方法会先深度优先遍历整个树,更新所有Group和Shape的变换并且把所有可见的Shape保存到数组中, * 最后根据绘制的优先级(zlevel > z > 插入顺序)排序得到绘制队列 * @param {boolean} [includeIgnore=false] 是否包含 ignore 的数组 */ updateDisplayList: function (includeIgnore) { this._displayListLen = 0; var roots = this._roots; var displayList = this._displayList; for (var i = 0, len = roots.length; i < len; i++) { this._updateAndAddDisplayable(roots[i], null, includeIgnore); } displayList.length = this._displayListLen; // for (var i = 0, len = displayList.length; i < len; i++) { // displayList[i].__renderidx = i; // } // displayList.sort(shapeCompareFunc); env$1.canvasSupported && sort(displayList, shapeCompareFunc); }, _updateAndAddDisplayable: function (el, clipPaths, includeIgnore) { if (el.ignore && !includeIgnore) { return; } el.beforeUpdate(); if (el.__dirty) { el.update(); } el.afterUpdate(); var userSetClipPath = el.clipPath; if (userSetClipPath) { // FIXME 效率影响 if (clipPaths) { clipPaths = clipPaths.slice(); } else { clipPaths = []; } var currentClipPath = userSetClipPath; var parentClipPath = el; // Recursively add clip path while (currentClipPath) { // clipPath 的变换是基于使用这个 clipPath 的元素 currentClipPath.parent = parentClipPath; currentClipPath.updateTransform(); clipPaths.push(currentClipPath); parentClipPath = currentClipPath; currentClipPath = currentClipPath.clipPath; } } if (el.isGroup) { var children = el._children; for (var i = 0; i < children.length; i++) { var child = children[i]; // Force to mark as dirty if group is dirty // FIXME __dirtyPath ? if (el.__dirty) { child.__dirty = true; } this._updateAndAddDisplayable(child, clipPaths, includeIgnore); } // Mark group clean here el.__dirty = false; } else { el.__clipPaths = clipPaths; this._displayList[this._displayListLen++] = el; } }, /** * 添加图形(Shape)或者组(Group)到根节点 * @param {module:zrender/Element} el */ addRoot: function (el) { if (el.__storage === this) { return; } if (el instanceof Group) { el.addChildrenToStorage(this); } this.addToStorage(el); this._roots.push(el); }, /** * 删除指定的图形(Shape)或者组(Group) * @param {string|Array.<string>} [el] 如果为空清空整个Storage */ delRoot: function (el) { if (el == null) { // 不指定el清空 for (var i = 0; i < this._roots.length; i++) { var root = this._roots[i]; if (root instanceof Group) { root.delChildrenFromStorage(this); } } this._roots = []; this._displayList = []; this._displayListLen = 0; return; } if (el instanceof Array) { for (var i = 0, l = el.length; i < l; i++) { this.delRoot(el[i]); } return; } var idx = indexOf(this._roots, el); if (idx >= 0) { this.delFromStorage(el); this._roots.splice(idx, 1); if (el instanceof Group) { el.delChildrenFromStorage(this); } } }, addToStorage: function (el) { el.__storage = this; el.dirty(false); return this; }, delFromStorage: function (el) { if (el) { el.__storage = null; } return this; }, /** * 清空并且释放Storage */ dispose: function () { this._renderList = this._roots = null; }, displayableSortFunc: shapeCompareFunc }; var STYLE_COMMON_PROPS = [ ['shadowBlur', 0], ['shadowOffsetX', 0], ['shadowOffsetY', 0], ['shadowColor', '#000'], ['lineCap', 'butt'], ['lineJoin', 'miter'], ['miterLimit', 10] ]; // var SHADOW_PROPS = STYLE_COMMON_PROPS.slice(0, 4); // var LINE_PROPS = STYLE_COMMON_PROPS.slice(4); var Style = function (opts, host) { this.extendFrom(opts, false); this.host = host; }; function createLinearGradient(ctx, obj, rect) { var x = obj.x == null ? 0 : obj.x; var x2 = obj.x2 == null ? 1 : obj.x2; var y = obj.y == null ? 0 : obj.y; var y2 = obj.y2 == null ? 0 : obj.y2; if (!obj.global) { x = x * rect.width + rect.x; x2 = x2 * rect.width + rect.x; y = y * rect.height + rect.y; y2 = y2 * rect.height + rect.y; } var canvasGradient = ctx.createLinearGradient(x, y, x2, y2); return canvasGradient; } function createRadialGradient(ctx, obj, rect) { var width = rect.width; var height = rect.height; var min = Math.min(width, height); var x = obj.x == null ? 0.5 : obj.x; var y = obj.y == null ? 0.5 : obj.y; var r = obj.r == null ? 0.5 : obj.r; if (!obj.global) { x = x * width + rect.x; y = y * height + rect.y; r = r * min; } var canvasGradient = ctx.createRadialGradient(x, y, 0, x, y, r); return canvasGradient; } Style.prototype = { constructor: Style, /** * @type {module:zrender/graphic/Displayable} */ host: null, /** * @type {string} */ fill: '#000', /** * @type {string} */ stroke: null, /** * @type {number} */ opacity: 1, /** * @type {Array.<number>} */ lineDash: null, /** * @type {number} */ lineDashOffset: 0, /** * @type {number} */ shadowBlur: 0, /** * @type {number} */ shadowOffsetX: 0, /** * @type {number} */ shadowOffsetY: 0, /** * @type {number} */ lineWidth: 1, /** * If stroke ignore scale * @type {Boolean} */ strokeNoScale: false, // Bounding rect text configuration // Not affected by element transform /** * @type {string} */ text: null, /** * If `fontSize` or `fontFamily` exists, `font` will be reset by * `fontSize`, `fontStyle`, `fontWeight`, `fontFamily`. * So do not visit it directly in upper application (like echarts), * but use `contain/text#makeFont` instead. * @type {string} */ font: null, /** * The same as font. Use font please. * @deprecated * @type {string} */ textFont: null, /** * It helps merging respectively, rather than parsing an entire font string. * @type {string} */ fontStyle: null, /** * It helps merging respectively, rather than parsing an entire font string. * @type {string} */ fontWeight: null, /** * It helps merging respectively, rather than parsing an entire font string. * Should be 12 but not '12px'. * @type {number} */ fontSize: null, /** * It helps merging respectively, rather than parsing an entire font string. * @type {string} */ fontFamily: null, /** * Reserved for special functinality, like 'hr'. * @type {string} */ textTag: null, /** * @type {string} */ textFill: '#000', /** * @type {string} */ textStroke: null, /** * @type {number} */ textWidth: null, /** * Only for textBackground. * @type {number} */ textHeight: null, /** * textStroke may be set as some color as a default * value in upper applicaion, where the default value * of textStrokeWidth should be 0 to make sure that * user can choose to do not use text stroke. * @type {number} */ textStrokeWidth: 0, /** * @type {number} */ textLineHeight: null, /** * 'inside', 'left', 'right', 'top', 'bottom' * [x, y] * Based on x, y of rect. * @type {string|Array.<number>} * @default 'inside' */ textPosition: 'inside', /** * If not specified, use the boundingRect of a `displayable`. * @type {Object} */ textRect: null, /** * [x, y] * @type {Array.<number>} */ textOffset: null, /** * @type {string} */ textAlign: null, /** * @type {string} */ textVerticalAlign: null, /** * @type {number} */ textDistance: 5, /** * @type {string} */ textShadowColor: 'transparent', /** * @type {number} */ textShadowBlur: 0, /** * @type {number} */ textShadowOffsetX: 0, /** * @type {number} */ textShadowOffsetY: 0, /** * @type {string} */ textBoxShadowColor: 'transparent', /** * @type {number} */ textBoxShadowBlur: 0, /** * @type {number} */ textBoxShadowOffsetX: 0, /** * @type {number} */ textBoxShadowOffsetY: 0, /** * Whether transform text. * Only useful in Path and Image element * @type {boolean} */ transformText: false, /** * Text rotate around position of Path or Image * Only useful in Path and Image element and transformText is false. */ textRotation: 0, /** * Text origin of text rotation, like [10, 40]. * Based on x, y of rect. * Useful in label rotation of circular symbol. * By default, this origin is textPosition. * Can be 'center'. * @type {string|Array.<number>} */ textOrigin: null, /** * @type {string} */ textBackgroundColor: null, /** * @type {string} */ textBorderColor: null, /** * @type {number} */ textBorderWidth: 0, /** * @type {number} */ textBorderRadius: 0, /** * Can be `2` or `[2, 4]` or `[2, 3, 4, 5]` * @type {number|Array.<number>} */ textPadding: null, /** * Text styles for rich text. * @type {Object} */ rich: null, /** * {outerWidth, outerHeight, ellipsis, placeholder} * @type {Object} */ truncate: null, /** * https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation * @type {string} */ blend: null, /** * @param {CanvasRenderingContext2D} ctx */ bind: function (ctx, el, prevEl) { var style = this; var prevStyle = prevEl && prevEl.style; var firstDraw = !prevStyle; for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) { var prop = STYLE_COMMON_PROPS[i]; var styleName = prop[0]; if (firstDraw || style[styleName] !== prevStyle[styleName]) { // FIXME Invalid property value will cause style leak from previous element. ctx[styleName] = style[styleName] || prop[1]; } } if ((firstDraw || style.fill !== prevStyle.fill)) { ctx.fillStyle = style.fill; } if ((firstDraw || style.stroke !== prevStyle.stroke)) { ctx.strokeStyle = style.stroke; } if ((firstDraw || style.opacity !== prevStyle.opacity)) { ctx.globalAlpha = style.opacity == null ? 1 : style.opacity; } if ((firstDraw || style.blend !== prevStyle.blend)) { ctx.globalCompositeOperation = style.blend || 'source-over'; } if (this.hasStroke()) { var lineWidth = style.lineWidth; ctx.lineWidth = lineWidth / ( (this.strokeNoScale && el && el.getLineScale) ? el.getLineScale() : 1 ); } }, hasFill: function () { var fill = this.fill; return fill != null && fill !== 'none'; }, hasStroke: function () { var stroke = this.stroke; return stroke != null && stroke !== 'none' && this.lineWidth > 0; }, /** * Extend from other style * @param {zrender/graphic/Style} otherStyle * @param {boolean} overwrite true: overwrirte any way. * false: overwrite only when !target.hasOwnProperty * others: overwrite when property is not null/undefined. */ extendFrom: function (otherStyle, overwrite) { if (otherStyle) { for (var name in otherStyle) { if (otherStyle.hasOwnProperty(name) && (overwrite === true || ( overwrite === false ? !this.hasOwnProperty(name) : otherStyle[name] != null ) ) ) { this[name] = otherStyle[name]; } } } }, /** * Batch setting style with a given object * @param {Object|string} obj * @param {*} [obj] */ set: function (obj, value) { if (typeof obj === 'string') { this[obj] = value; } else { this.extendFrom(obj, true); } }, /** * Clone * @return {zrender/graphic/Style} [description] */ clone: function () { var newStyle = new this.constructor(); newStyle.extendFrom(this, true); return newStyle; }, getGradient: function (ctx, obj, rect) { var method = obj.type === 'radial' ? createRadialGradient : createLinearGradient; var canvasGradient = method(ctx, obj, rect); var colorStops = obj.colorStops; for (var i = 0; i < colorStops.length; i++) { canvasGradient.addColorStop( colorStops[i].offset, colorStops[i].color ); } return canvasGradient; } }; var styleProto = Style.prototype; for (var i = 0; i < STYLE_COMMON_PROPS.length; i++) { var prop = STYLE_COMMON_PROPS[i]; if (!(prop[0] in styleProto)) { styleProto[prop[0]] = prop[1]; } } // Provide for others Style.getGradient = styleProto.getGradient; var Pattern = function (image, repeat) { // Should do nothing more in this constructor. Because gradient can be // declard by `color: {image: ...}`, where this constructor will not be called. this.image = image; this.repeat = repeat; // Can be cloned this.type = 'pattern'; }; Pattern.prototype.getCanvasPattern = function (ctx) { return ctx.createPattern(this.image, this.repeat || 'repeat'); }; /** * @module zrender/Layer * @author pissang(https://www.github.com/pissang) */ function returnFalse() { return false; } /** * 创建dom * * @inner * @param {string} id dom id 待用 * @param {Painter} painter painter instance * @param {number} number */ function createDom(id, painter, dpr) { var newDom = createCanvas(); var width = painter.getWidth(); var height = painter.getHeight(); var newDomStyle = newDom.style; // 没append呢,请原谅我这样写,清晰~ newDomStyle.position = 'absolute'; newDomStyle.left = 0; newDomStyle.top = 0; newDomStyle.width = width + 'px'; newDomStyle.height = height + 'px'; newDom.width = width * dpr; newDom.height = height * dpr; // id不作为索引用,避免可能造成的重名,定义为私有属性 newDom.setAttribute('data-zr-dom-id', id); return newDom; } /** * @alias module:zrender/Layer * @constructor * @extends module:zrender/mixin/Transformable * @param {string} id * @param {module:zrender/Painter} painter * @param {number} [dpr] */ var Layer = function(id, painter, dpr) { var dom; dpr = dpr || devicePixelRatio; if (typeof id === 'string') { dom = createDom(id, painter, dpr); } // Not using isDom because in node it will return false else if (isObject(id)) { dom = id; id = dom.id; } this.id = id; this.dom = dom; var domStyle = dom.style; if (domStyle) { // Not in node dom.onselectstart = returnFalse; // 避免页面选中的尴尬 domStyle['-webkit-user-select'] = 'none'; domStyle['user-select'] = 'none'; domStyle['-webkit-touch-callout'] = 'none'; domStyle['-webkit-tap-highlight-color'] = 'rgba(0,0,0,0)'; domStyle['padding'] = 0; domStyle['margin'] = 0; domStyle['border-width'] = 0; } this.domBack = null; this.ctxBack = null; this.painter = painter; this.config = null; // Configs /** * 每次清空画布的颜色 * @type {string} * @default 0 */ this.clearColor = 0; /** * 是否开启动态模糊 * @type {boolean} * @default false */ this.motionBlur = false; /** * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显 * @type {number} * @default 0.7 */ this.lastFrameAlpha = 0.7; /** * Layer dpr * @type {number} */ this.dpr = dpr; }; Layer.prototype = { constructor: Layer, elCount: 0, __dirty: true, initContext: function () { this.ctx = this.dom.getContext('2d'); this.ctx.__currentValues = {}; this.ctx.dpr = this.dpr; }, createBackBuffer: function () { var dpr = this.dpr; this.domBack = createDom('back-' + this.id, this.painter, dpr); this.ctxBack = this.domBack.getContext('2d'); this.ctxBack.__currentValues = {}; if (dpr != 1) { this.ctxBack.scale(dpr, dpr); } }, /** * @param {number} width * @param {number} height */ resize: function (width, height) { var dpr = this.dpr; var dom = this.dom; var domStyle = dom.style; var domBack = this.domBack; domStyle.width = width + 'px'; domStyle.height = height + 'px'; dom.width = width * dpr; dom.height = height * dpr; if (domBack) { domBack.width = width * dpr; domBack.height = height * dpr; if (dpr != 1) { this.ctxBack.scale(dpr, dpr); } } }, /** * 清空该层画布 * @param {boolean} clearAll Clear all with out motion blur */ clear: function (clearAll) { var dom = this.dom; var ctx = this.ctx; var width = dom.width; var height = dom.height; var clearColor = this.clearColor; var haveMotionBLur = this.motionBlur && !clearAll; var lastFrameAlpha = this.lastFrameAlpha; var dpr = this.dpr; if (haveMotionBLur) { if (!this.domBack) { this.createBackBuffer(); } this.ctxBack.globalCompositeOperation = 'copy'; this.ctxBack.drawImage( dom, 0, 0, width / dpr, height / dpr ); } ctx.clearRect(0, 0, width, height); if (clearColor) { var clearColorGradientOrPattern; // Gradient if (clearColor.colorStops) { // Cache canvas gradient clearColorGradientOrPattern = clearColor.__canvasGradient || Style.getGradient(ctx, clearColor, { x: 0, y: 0, width: width, height: height }); clearColor.__canvasGradient = clearColorGradientOrPattern; } // Pattern else if (clearColor.image) { clearColorGradientOrPattern = Pattern.prototype.getCanvasPattern.call(clearColor, ctx); } ctx.save(); ctx.fillStyle = clearColorGradientOrPattern || clearColor; ctx.fillRect(0, 0, width, height); ctx.restore(); } if (haveMotionBLur) { var domBack = this.domBack; ctx.save(); ctx.globalAlpha = lastFrameAlpha; ctx.drawImage(domBack, 0, 0, width, height); ctx.restore(); } } }; var requestAnimationFrame = ( typeof window !== 'undefined' && ( (window.requestAnimationFrame && window.requestAnimationFrame.bind(window)) // https://github.com/ecomfe/zrender/issues/189#issuecomment-224919809 || (window.msRequestAnimationFrame && window.msRequestAnimationFrame.bind(window)) || window.mozRequestAnimationFrame || window.webkitRequestAnimationFrame ) ) || function (func) { setTimeout(func, 16); }; var globalImageCache = new LRU(50); /** * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image */ function findExistImage(newImageOrSrc) { if (typeof newImageOrSrc === 'string') { var cachedImgObj = globalImageCache.get(newImageOrSrc); return cachedImgObj && cachedImgObj.image; } else { return newImageOrSrc; } } /** * Caution: User should cache loaded images, but not just count on LRU. * Consider if required images more than LRU size, will dead loop occur? * * @param {string|HTMLImageElement|HTMLCanvasElement|Canvas} newImageOrSrc * @param {HTMLImageElement|HTMLCanvasElement|Canvas} image Existent image. * @param {module:zrender/Element} [hostEl] For calling `dirty`. * @param {Function} [cb] params: (image, cbPayload) * @param {Object} [cbPayload] Payload on cb calling. * @return {HTMLImageElement|HTMLCanvasElement|Canvas} image */ function createOrUpdateImage(newImageOrSrc, image, hostEl, cb, cbPayload) { if (!newImageOrSrc) { return image; } else if (typeof newImageOrSrc === 'string') { // Image should not be loaded repeatly. if ((image && image.__zrImageSrc === newImageOrSrc) || !hostEl) { return image; } // Only when there is no existent image or existent image src // is different, this method is responsible for load. var cachedImgObj = globalImageCache.get(newImageOrSrc); var pendingWrap = {hostEl: hostEl, cb: cb, cbPayload: cbPayload}; if (cachedImgObj) { image = cachedImgObj.image; !isImageReady(image) && cachedImgObj.pending.push(pendingWrap); } else { !image && (image = new Image()); image.onload = imageOnLoad; globalImageCache.put( newImageOrSrc, image.__cachedImgObj = { image: image, pending: [pendingWrap] } ); image.src = image.__zrImageSrc = newImageOrSrc; } return image; } // newImageOrSrc is an HTMLImageElement or HTMLCanvasElement or Canvas else { return newImageOrSrc; } } function imageOnLoad() { var cachedImgObj = this.__cachedImgObj; this.onload = this.__cachedImgObj = null; for (var i = 0; i < cachedImgObj.pending.length; i++) { var pendingWrap = cachedImgObj.pending[i]; var cb = pendingWrap.cb; cb && cb(this, pendingWrap.cbPayload); pendingWrap.hostEl.dirty(); } cachedImgObj.pending.length = 0; } function isImageReady(image) { return image && image.width && image.height; } var textWidthCache = {}; var textWidthCacheCounter = 0; var TEXT_CACHE_MAX = 5000; var STYLE_REG = /\{([a-zA-Z0-9_]+)\|([^}]*)\}/g; var DEFAULT_FONT = '12px sans-serif'; /** * @public * @param {string} text * @param {string} font * @return {number} width */ function getWidth(text, font) { font = font || DEFAULT_FONT; var key = text + ':' + font; if (textWidthCache[key]) { return textWidthCache[key]; } var textLines = (text + '').split('\n'); var width = 0; for (var i = 0, l = textLines.length; i < l; i++) { // textContain.measureText may be overrided in SVG or VML width = Math.max(measureText(textLines[i], font).width, width); } if (textWidthCacheCounter > TEXT_CACHE_MAX) { textWidthCacheCounter = 0; textWidthCache = {}; } textWidthCacheCounter++; textWidthCache[key] = width; return width; } /** * @public * @param {string} text * @param {string} font * @param {string} [textAlign='left'] * @param {string} [textVerticalAlign='top'] * @param {Array.<number>} [textPadding] * @param {Object} [rich] * @param {Object} [truncate] * @return {Object} {x, y, width, height, lineHeight} */ function getBoundingRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) { return rich ? getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) : getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate); } function getPlainTextRect(text, font, textAlign, textVerticalAlign, textPadding, truncate) { var contentBlock = parsePlainText(text, font, textPadding, truncate); var outerWidth = getWidth(text, font); if (textPadding) { outerWidth += textPadding[1] + textPadding[3]; } var outerHeight = contentBlock.outerHeight; var x = adjustTextX(0, outerWidth, textAlign); var y = adjustTextY(0, outerHeight, textVerticalAlign); var rect = new BoundingRect(x, y, outerWidth, outerHeight); rect.lineHeight = contentBlock.lineHeight; return rect; } function getRichTextRect(text, font, textAlign, textVerticalAlign, textPadding, rich, truncate) { var contentBlock = parseRichText(text, { rich: rich, truncate: truncate, font: font, textAlign: textAlign, textPadding: textPadding }); var outerWidth = contentBlock.outerWidth; var outerHeight = contentBlock.outerHeight; var x = adjustTextX(0, outerWidth, textAlign); var y = adjustTextY(0, outerHeight, textVerticalAlign); return new BoundingRect(x, y, outerWidth, outerHeight); } /** * @public * @param {number} x * @param {number} width * @param {string} [textAlign='left'] * @return {number} Adjusted x. */ function adjustTextX(x, width, textAlign) { // FIXME Right to left language if (textAlign === 'right') { x -= width; } else if (textAlign === 'center') { x -= width / 2; } return x; } /** * @public * @param {number} y * @param {number} height * @param {string} [textVerticalAlign='top'] * @return {number} Adjusted y. */ function adjustTextY(y, height, textVerticalAlign) { if (textVerticalAlign === 'middle') { y -= height / 2; } else if (textVerticalAlign === 'bottom') { y -= height; } return y; } /** * @public * @param {stirng} textPosition * @param {Object} rect {x, y, width, height} * @param {number} distance * @return {Object} {x, y, textAlign, textVerticalAlign} */ function adjustTextPositionOnRect(textPosition, rect, distance) { var x = rect.x; var y = rect.y; var height = rect.height; var width = rect.width; var halfHeight = height / 2; var textAlign = 'left'; var textVerticalAlign = 'top'; switch (textPosition) { case 'left': x -= distance; y += halfHeight; textAlign = 'right'; textVerticalAlign = 'middle'; break; case 'right': x += distance + width; y += halfHeight; textVerticalAlign = 'middle'; break; case 'top': x += width / 2; y -= distance; textAlign = 'center'; textVerticalAlign = 'bottom'; break; case 'bottom': x += width / 2; y += height + distance; textAlign = 'center'; break; case 'inside': x += width / 2; y += halfHeight; textAlign = 'center'; textVerticalAlign = 'middle'; break; case 'insideLeft': x += distance; y += halfHeight; textVerticalAlign = 'middle'; break; case 'insideRight': x += width - distance; y += halfHeight; textAlign = 'right'; textVerticalAlign = 'middle'; break; case 'insideTop': x += width / 2; y += distance; textAlign = 'center'; break; case 'insideBottom': x += width / 2; y += height - distance; textAlign = 'center'; textVerticalAlign = 'bottom'; break; case 'insideTopLeft': x += distance; y += distance; break; case 'insideTopRight': x += width - distance; y += distance; textAlign = 'right'; break; case 'insideBottomLeft': x += distance; y += height - distance; textVerticalAlign = 'bottom'; break; case 'insideBottomRight': x += width - distance; y += height - distance; textAlign = 'right'; textVerticalAlign = 'bottom'; break; } return { x: x, y: y, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; } /** * Show ellipsis if overflow. * * @public * @param {string} text * @param {string} containerWidth * @param {string} font * @param {number} [ellipsis='...'] * @param {Object} [options] * @param {number} [options.maxIterations=3] * @param {number} [options.minChar=0] If truncate result are less * then minChar, ellipsis will not show, which is * better for user hint in some cases. * @param {number} [options.placeholder=''] When all truncated, use the placeholder. * @return {string} */ function truncateText(text, containerWidth, font, ellipsis, options) { if (!containerWidth) { return ''; } var textLines = (text + '').split('\n'); options = prepareTruncateOptions(containerWidth, font, ellipsis, options); // FIXME // It is not appropriate that every line has '...' when truncate multiple lines. for (var i = 0, len = textLines.length; i < len; i++) { textLines[i] = truncateSingleLine(textLines[i], options); } return textLines.join('\n'); } function prepareTruncateOptions(containerWidth, font, ellipsis, options) { options = extend({}, options); options.font = font; var ellipsis = retrieve2(ellipsis, '...'); options.maxIterations = retrieve2(options.maxIterations, 2); var minChar = options.minChar = retrieve2(options.minChar, 0); // FIXME // Other languages? options.cnCharWidth = getWidth('国', font); // FIXME // Consider proportional font? var ascCharWidth = options.ascCharWidth = getWidth('a', font); options.placeholder = retrieve2(options.placeholder, ''); // Example 1: minChar: 3, text: 'asdfzxcv', truncate result: 'asdf', but not: 'a...'. // Example 2: minChar: 3, text: '维度', truncate result: '维', but not: '...'. var contentWidth = containerWidth = Math.max(0, containerWidth - 1); // Reserve some gap. for (var i = 0; i < minChar && contentWidth >= ascCharWidth; i++) { contentWidth -= ascCharWidth; } var ellipsisWidth = getWidth(ellipsis); if (ellipsisWidth > contentWidth) { ellipsis = ''; ellipsisWidth = 0; } contentWidth = containerWidth - ellipsisWidth; options.ellipsis = ellipsis; options.ellipsisWidth = ellipsisWidth; options.contentWidth = contentWidth; options.containerWidth = containerWidth; return options; } function truncateSingleLine(textLine, options) { var containerWidth = options.containerWidth; var font = options.font; var contentWidth = options.contentWidth; if (!containerWidth) { return ''; } var lineWidth = getWidth(textLine, font); if (lineWidth <= containerWidth) { return textLine; } for (var j = 0;; j++) { if (lineWidth <= contentWidth || j >= options.maxIterations) { textLine += options.ellipsis; break; } var subLength = j === 0 ? estimateLength(textLine, contentWidth, options.ascCharWidth, options.cnCharWidth) : lineWidth > 0 ? Math.floor(textLine.length * contentWidth / lineWidth) : 0; textLine = textLine.substr(0, subLength); lineWidth = getWidth(textLine, font); } if (textLine === '') { textLine = options.placeholder; } return textLine; } function estimateLength(text, contentWidth, ascCharWidth, cnCharWidth) { var width = 0; var i = 0; for (var len = text.length; i < len && width < contentWidth; i++) { var charCode = text.charCodeAt(i); width += (0 <= charCode && charCode <= 127) ? ascCharWidth : cnCharWidth; } return i; } /** * @public * @param {string} font * @return {number} line height */ function getLineHeight(font) { // FIXME A rough approach. return getWidth('国', font); } /** * @public * @param {string} text * @param {string} font * @return {Object} width */ var measureText = function (text, font) { var ctx = getContext(); ctx.font = font || DEFAULT_FONT; return ctx.measureText(text); }; /** * @public * @param {string} text * @param {string} font * @param {Object} [truncate] * @return {Object} block: {lineHeight, lines, height, outerHeight} * Notice: for performance, do not calculate outerWidth util needed. */ function parsePlainText(text, font, padding, truncate) { text != null && (text += ''); var lineHeight = getLineHeight(font); var lines = text ? text.split('\n') : []; var height = lines.length * lineHeight; var outerHeight = height; if (padding) { outerHeight += padding[0] + padding[2]; } if (text && truncate) { var truncOuterHeight = truncate.outerHeight; var truncOuterWidth = truncate.outerWidth; if (truncOuterHeight != null && outerHeight > truncOuterHeight) { text = ''; lines = []; } else if (truncOuterWidth != null) { var options = prepareTruncateOptions( truncOuterWidth - (padding ? padding[1] + padding[3] : 0), font, truncate.ellipsis, {minChar: truncate.minChar, placeholder: truncate.placeholder} ); // FIXME // It is not appropriate that every line has '...' when truncate multiple lines. for (var i = 0, len = lines.length; i < len; i++) { lines[i] = truncateSingleLine(lines[i], options); } } } return { lines: lines, height: height, outerHeight: outerHeight, lineHeight: lineHeight }; } /** * For example: 'some text {a|some text}other text{b|some text}xxx{c|}xxx' * Also consider 'bbbb{a|xxx\nzzz}xxxx\naaaa'. * * @public * @param {string} text * @param {Object} style * @return {Object} block * { * width, * height, * lines: [{ * lineHeight, * width, * tokens: [[{ * styleName, * text, * width, // include textPadding * height, // include textPadding * textWidth, // pure text width * textHeight, // pure text height * lineHeihgt, * font, * textAlign, * textVerticalAlign * }], [...], ...] * }, ...] * } * If styleName is undefined, it is plain text. */ function parseRichText(text, style) { var contentBlock = {lines: [], width: 0, height: 0}; text != null && (text += ''); if (!text) { return contentBlock; } var lastIndex = STYLE_REG.lastIndex = 0; var result; while ((result = STYLE_REG.exec(text)) != null) { var matchedIndex = result.index; if (matchedIndex > lastIndex) { pushTokens(contentBlock, text.substring(lastIndex, matchedIndex)); } pushTokens(contentBlock, result[2], result[1]); lastIndex = STYLE_REG.lastIndex; } if (lastIndex < text.length) { pushTokens(contentBlock, text.substring(lastIndex, text.length)); } var lines = contentBlock.lines; var contentHeight = 0; var contentWidth = 0; // For `textWidth: 100%` var pendingList = []; var stlPadding = style.textPadding; var truncate = style.truncate; var truncateWidth = truncate && truncate.outerWidth; var truncateHeight = truncate && truncate.outerHeight; if (stlPadding) { truncateWidth != null && (truncateWidth -= stlPadding[1] + stlPadding[3]); truncateHeight != null && (truncateHeight -= stlPadding[0] + stlPadding[2]); } // Calculate layout info of tokens. for (var i = 0; i < lines.length; i++) { var line = lines[i]; var lineHeight = 0; var lineWidth = 0; for (var j = 0; j < line.tokens.length; j++) { var token = line.tokens[j]; var tokenStyle = token.styleName && style.rich[token.styleName] || {}; // textPadding should not inherit from style. var textPadding = token.textPadding = tokenStyle.textPadding; // textFont has been asigned to font by `normalizeStyle`. var font = token.font = tokenStyle.font || style.font; // textHeight can be used when textVerticalAlign is specified in token. var tokenHeight = token.textHeight = retrieve2( // textHeight should not be inherited, consider it can be specified // as box height of the block. tokenStyle.textHeight, getLineHeight(font) ); textPadding && (tokenHeight += textPadding[0] + textPadding[2]); token.height = tokenHeight; token.lineHeight = retrieve3( tokenStyle.textLineHeight, style.textLineHeight, tokenHeight ); token.textAlign = tokenStyle && tokenStyle.textAlign || style.textAlign; token.textVerticalAlign = tokenStyle && tokenStyle.textVerticalAlign || 'middle'; if (truncateHeight != null && contentHeight + token.lineHeight > truncateHeight) { return {lines: [], width: 0, height: 0}; } token.textWidth = getWidth(token.text, font); var tokenWidth = tokenStyle.textWidth; var tokenWidthNotSpecified = tokenWidth == null || tokenWidth === 'auto'; // Percent width, can be `100%`, can be used in drawing separate // line when box width is needed to be auto. if (typeof tokenWidth === 'string' && tokenWidth.charAt(tokenWidth.length - 1) === '%') { token.percentWidth = tokenWidth; pendingList.push(token); tokenWidth = 0; // Do not truncate in this case, because there is no user case // and it is too complicated. } else { if (tokenWidthNotSpecified) { tokenWidth = token.textWidth; // FIXME: If image is not loaded and textWidth is not specified, calling // `getBoundingRect()` will not get correct result. var textBackgroundColor = tokenStyle.textBackgroundColor; var bgImg = textBackgroundColor && textBackgroundColor.image; // Use cases: // (1) If image is not loaded, it will be loaded at render phase and call // `dirty()` and `textBackgroundColor.image` will be replaced with the loaded // image, and then the right size will be calculated here at the next tick. // See `graphic/helper/text.js`. // (2) If image loaded, and `textBackgroundColor.image` is image src string, // use `imageHelper.findExistImage` to find cached image. // `imageHelper.findExistImage` will always be called here before // `imageHelper.createOrUpdateImage` in `graphic/helper/text.js#renderRichText` // which ensures that image will not be rendered before correct size calcualted. if (bgImg) { bgImg = findExistImage(bgImg); if (isImageReady(bgImg)) { tokenWidth = Math.max(tokenWidth, bgImg.width * tokenHeight / bgImg.height); } } } var paddingW = textPadding ? textPadding[1] + textPadding[3] : 0; tokenWidth += paddingW; var remianTruncWidth = truncateWidth != null ? truncateWidth - lineWidth : null; if (remianTruncWidth != null && remianTruncWidth < tokenWidth) { if (!tokenWidthNotSpecified || remianTruncWidth < paddingW) { token.text = ''; token.textWidth = tokenWidth = 0; } else { token.text = truncateText( token.text, remianTruncWidth - paddingW, font, truncate.ellipsis, {minChar: truncate.minChar} ); token.textWidth = getWidth(token.text, font); tokenWidth = token.textWidth + paddingW; } } } lineWidth += (token.width = tokenWidth); tokenStyle && (lineHeight = Math.max(lineHeight, token.lineHeight)); } line.width = lineWidth; line.lineHeight = lineHeight; contentHeight += lineHeight; contentWidth = Math.max(contentWidth, lineWidth); } contentBlock.outerWidth = contentBlock.width = retrieve2(style.textWidth, contentWidth); contentBlock.outerHeight = contentBlock.height = retrieve2(style.textHeight, contentHeight); if (stlPadding) { contentBlock.outerWidth += stlPadding[1] + stlPadding[3]; contentBlock.outerHeight += stlPadding[0] + stlPadding[2]; } for (var i = 0; i < pendingList.length; i++) { var token = pendingList[i]; var percentWidth = token.percentWidth; // Should not base on outerWidth, because token can not be placed out of padding. token.width = parseInt(percentWidth, 10) / 100 * contentWidth; } return contentBlock; } function pushTokens(block, str, styleName) { var isEmptyStr = str === ''; var strs = str.split('\n'); var lines = block.lines; for (var i = 0; i < strs.length; i++) { var text = strs[i]; var token = { styleName: styleName, text: text, isLineHolder: !text && !isEmptyStr }; // The first token should be appended to the last line. if (!i) { var tokens = (lines[lines.length - 1] || (lines[0] = {tokens: []})).tokens; // Consider cases: // (1) ''.split('\n') => ['', '\n', ''], the '' at the first item // (which is a placeholder) should be replaced by new token. // (2) A image backage, where token likes {a|}. // (3) A redundant '' will affect textAlign in line. // (4) tokens with the same tplName should not be merged, because // they should be displayed in different box (with border and padding). var tokensLen = tokens.length; (tokensLen === 1 && tokens[0].isLineHolder) ? (tokens[0] = token) // Consider text is '', only insert when it is the "lineHolder" or // "emptyStr". Otherwise a redundant '' will affect textAlign in line. : ((text || !tokensLen || isEmptyStr) && tokens.push(token)); } // Other tokens always start a new line. else { // If there is '', insert it as a placeholder. lines.push({tokens: [token]}); } } } function makeFont(style) { // FIXME in node-canvas fontWeight is before fontStyle // Use `fontSize` `fontFamily` to check whether font properties are defined. return (style.fontSize || style.fontFamily) && [ style.fontStyle, style.fontWeight, (style.fontSize || 12) + 'px', // If font properties are defined, `fontFamily` should not be ignored. style.fontFamily || 'sans-serif' ].join(' ') || style.textFont || style.font; } function buildPath(ctx, shape) { var x = shape.x; var y = shape.y; var width = shape.width; var height = shape.height; var r = shape.r; var r1; var r2; var r3; var r4; // Convert width and height to positive for better borderRadius if (width < 0) { x = x + width; width = -width; } if (height < 0) { y = y + height; height = -height; } if (typeof r === 'number') { r1 = r2 = r3 = r4 = r; } else if (r instanceof Array) { if (r.length === 1) { r1 = r2 = r3 = r4 = r[0]; } else if (r.length === 2) { r1 = r3 = r[0]; r2 = r4 = r[1]; } else if (r.length === 3) { r1 = r[0]; r2 = r4 = r[1]; r3 = r[2]; } else { r1 = r[0]; r2 = r[1]; r3 = r[2]; r4 = r[3]; } } else { r1 = r2 = r3 = r4 = 0; } var total; if (r1 + r2 > width) { total = r1 + r2; r1 *= width / total; r2 *= width / total; } if (r3 + r4 > width) { total = r3 + r4; r3 *= width / total; r4 *= width / total; } if (r2 + r3 > height) { total = r2 + r3; r2 *= height / total; r3 *= height / total; } if (r1 + r4 > height) { total = r1 + r4; r1 *= height / total; r4 *= height / total; } ctx.moveTo(x + r1, y); ctx.lineTo(x + width - r2, y); r2 !== 0 && ctx.quadraticCurveTo( x + width, y, x + width, y + r2 ); ctx.lineTo(x + width, y + height - r3); r3 !== 0 && ctx.quadraticCurveTo( x + width, y + height, x + width - r3, y + height ); ctx.lineTo(x + r4, y + height); r4 !== 0 && ctx.quadraticCurveTo( x, y + height, x, y + height - r4 ); ctx.lineTo(x, y + r1); r1 !== 0 && ctx.quadraticCurveTo(x, y, x + r1, y); } // TODO: Have not support 'start', 'end' yet. var VALID_TEXT_ALIGN = {left: 1, right: 1, center: 1}; var VALID_TEXT_VERTICAL_ALIGN = {top: 1, bottom: 1, middle: 1}; /** * @param {module:zrender/graphic/Style} style * @return {module:zrender/graphic/Style} The input style. */ function normalizeTextStyle(style) { normalizeStyle(style); each$1(style.rich, normalizeStyle); return style; } function normalizeStyle(style) { if (style) { style.font = makeFont(style); var textAlign = style.textAlign; textAlign === 'middle' && (textAlign = 'center'); style.textAlign = ( textAlign == null || VALID_TEXT_ALIGN[textAlign] ) ? textAlign : 'left'; // Compatible with textBaseline. var textVerticalAlign = style.textVerticalAlign || style.textBaseline; textVerticalAlign === 'center' && (textVerticalAlign = 'middle'); style.textVerticalAlign = ( textVerticalAlign == null || VALID_TEXT_VERTICAL_ALIGN[textVerticalAlign] ) ? textVerticalAlign : 'top'; var textPadding = style.textPadding; if (textPadding) { style.textPadding = normalizeCssArray(style.textPadding); } } } /** * @param {CanvasRenderingContext2D} ctx * @param {string} text * @param {module:zrender/graphic/Style} style * @param {Object|boolean} [rect] {x, y, width, height} * If set false, rect text is not used. */ function renderText(hostEl, ctx, text, style, rect) { style.rich ? renderRichText(hostEl, ctx, text, style, rect) : renderPlainText(hostEl, ctx, text, style, rect); } function renderPlainText(hostEl, ctx, text, style, rect) { var font = setCtx(ctx, 'font', style.font || DEFAULT_FONT); var textPadding = style.textPadding; var contentBlock = hostEl.__textCotentBlock; if (!contentBlock || hostEl.__dirty) { contentBlock = hostEl.__textCotentBlock = parsePlainText( text, font, textPadding, style.truncate ); } var outerHeight = contentBlock.outerHeight; var textLines = contentBlock.lines; var lineHeight = contentBlock.lineHeight; var boxPos = getBoxPosition(outerHeight, style, rect); var baseX = boxPos.baseX; var baseY = boxPos.baseY; var textAlign = boxPos.textAlign; var textVerticalAlign = boxPos.textVerticalAlign; // Origin of textRotation should be the base point of text drawing. applyTextRotation(ctx, style, rect, baseX, baseY); var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign); var textX = baseX; var textY = boxY; var needDrawBg = needDrawBackground(style); if (needDrawBg || textPadding) { // Consider performance, do not call getTextWidth util necessary. var textWidth = getWidth(text, font); var outerWidth = textWidth; textPadding && (outerWidth += textPadding[1] + textPadding[3]); var boxX = adjustTextX(baseX, outerWidth, textAlign); needDrawBg && drawBackground(hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight); if (textPadding) { textX = getTextXForPadding(baseX, textAlign, textPadding); textY += textPadding[0]; } } setCtx(ctx, 'textAlign', textAlign || 'left'); // Force baseline to be "middle". Otherwise, if using "top", the // text will offset downward a little bit in font "Microsoft YaHei". setCtx(ctx, 'textBaseline', 'middle'); // Always set shadowBlur and shadowOffset to avoid leak from displayable. setCtx(ctx, 'shadowBlur', style.textShadowBlur || 0); setCtx(ctx, 'shadowColor', style.textShadowColor || 'transparent'); setCtx(ctx, 'shadowOffsetX', style.textShadowOffsetX || 0); setCtx(ctx, 'shadowOffsetY', style.textShadowOffsetY || 0); // `textBaseline` is set as 'middle'. textY += lineHeight / 2; var textStrokeWidth = style.textStrokeWidth; var textStroke = getStroke(style.textStroke, textStrokeWidth); var textFill = getFill(style.textFill); if (textStroke) { setCtx(ctx, 'lineWidth', textStrokeWidth); setCtx(ctx, 'strokeStyle', textStroke); } if (textFill) { setCtx(ctx, 'fillStyle', textFill); } for (var i = 0; i < textLines.length; i++) { // Fill after stroke so the outline will not cover the main part. textStroke && ctx.strokeText(textLines[i], textX, textY); textFill && ctx.fillText(textLines[i], textX, textY); textY += lineHeight; } } function renderRichText(hostEl, ctx, text, style, rect) { var contentBlock = hostEl.__textCotentBlock; if (!contentBlock || hostEl.__dirty) { contentBlock = hostEl.__textCotentBlock = parseRichText(text, style); } drawRichText(hostEl, ctx, contentBlock, style, rect); } function drawRichText(hostEl, ctx, contentBlock, style, rect) { var contentWidth = contentBlock.width; var outerWidth = contentBlock.outerWidth; var outerHeight = contentBlock.outerHeight; var textPadding = style.textPadding; var boxPos = getBoxPosition(outerHeight, style, rect); var baseX = boxPos.baseX; var baseY = boxPos.baseY; var textAlign = boxPos.textAlign; var textVerticalAlign = boxPos.textVerticalAlign; // Origin of textRotation should be the base point of text drawing. applyTextRotation(ctx, style, rect, baseX, baseY); var boxX = adjustTextX(baseX, outerWidth, textAlign); var boxY = adjustTextY(baseY, outerHeight, textVerticalAlign); var xLeft = boxX; var lineTop = boxY; if (textPadding) { xLeft += textPadding[3]; lineTop += textPadding[0]; } var xRight = xLeft + contentWidth; needDrawBackground(style) && drawBackground( hostEl, ctx, style, boxX, boxY, outerWidth, outerHeight ); for (var i = 0; i < contentBlock.lines.length; i++) { var line = contentBlock.lines[i]; var tokens = line.tokens; var tokenCount = tokens.length; var lineHeight = line.lineHeight; var usedWidth = line.width; var leftIndex = 0; var lineXLeft = xLeft; var lineXRight = xRight; var rightIndex = tokenCount - 1; var token; while ( leftIndex < tokenCount && (token = tokens[leftIndex], !token.textAlign || token.textAlign === 'left') ) { placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft, 'left'); usedWidth -= token.width; lineXLeft += token.width; leftIndex++; } while ( rightIndex >= 0 && (token = tokens[rightIndex], token.textAlign === 'right') ) { placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXRight, 'right'); usedWidth -= token.width; lineXRight -= token.width; rightIndex--; } // The other tokens are placed as textAlign 'center' if there is enough space. lineXLeft += (contentWidth - (lineXLeft - xLeft) - (xRight - lineXRight) - usedWidth) / 2; while (leftIndex <= rightIndex) { token = tokens[leftIndex]; // Consider width specified by user, use 'center' rather than 'left'. placeToken(hostEl, ctx, token, style, lineHeight, lineTop, lineXLeft + token.width / 2, 'center'); lineXLeft += token.width; leftIndex++; } lineTop += lineHeight; } } function applyTextRotation(ctx, style, rect, x, y) { // textRotation only apply in RectText. if (rect && style.textRotation) { var origin = style.textOrigin; if (origin === 'center') { x = rect.width / 2 + rect.x; y = rect.height / 2 + rect.y; } else if (origin) { x = origin[0] + rect.x; y = origin[1] + rect.y; } ctx.translate(x, y); // Positive: anticlockwise ctx.rotate(-style.textRotation); ctx.translate(-x, -y); } } function placeToken(hostEl, ctx, token, style, lineHeight, lineTop, x, textAlign) { var tokenStyle = style.rich[token.styleName] || {}; // 'ctx.textBaseline' is always set as 'middle', for sake of // the bias of "Microsoft YaHei". var textVerticalAlign = token.textVerticalAlign; var y = lineTop + lineHeight / 2; if (textVerticalAlign === 'top') { y = lineTop + token.height / 2; } else if (textVerticalAlign === 'bottom') { y = lineTop + lineHeight - token.height / 2; } !token.isLineHolder && needDrawBackground(tokenStyle) && drawBackground( hostEl, ctx, tokenStyle, textAlign === 'right' ? x - token.width : textAlign === 'center' ? x - token.width / 2 : x, y - token.height / 2, token.width, token.height ); var textPadding = token.textPadding; if (textPadding) { x = getTextXForPadding(x, textAlign, textPadding); y -= token.height / 2 - textPadding[2] - token.textHeight / 2; } setCtx(ctx, 'shadowBlur', retrieve3(tokenStyle.textShadowBlur, style.textShadowBlur, 0)); setCtx(ctx, 'shadowColor', tokenStyle.textShadowColor || style.textShadowColor || 'transparent'); setCtx(ctx, 'shadowOffsetX', retrieve3(tokenStyle.textShadowOffsetX, style.textShadowOffsetX, 0)); setCtx(ctx, 'shadowOffsetY', retrieve3(tokenStyle.textShadowOffsetY, style.textShadowOffsetY, 0)); setCtx(ctx, 'textAlign', textAlign); // Force baseline to be "middle". Otherwise, if using "top", the // text will offset downward a little bit in font "Microsoft YaHei". setCtx(ctx, 'textBaseline', 'middle'); setCtx(ctx, 'font', token.font || DEFAULT_FONT); var textStroke = getStroke(tokenStyle.textStroke || style.textStroke, textStrokeWidth); var textFill = getFill(tokenStyle.textFill || style.textFill); var textStrokeWidth = retrieve2(tokenStyle.textStrokeWidth, style.textStrokeWidth); // Fill after stroke so the outline will not cover the main part. if (textStroke) { setCtx(ctx, 'lineWidth', textStrokeWidth); setCtx(ctx, 'strokeStyle', textStroke); ctx.strokeText(token.text, x, y); } if (textFill) { setCtx(ctx, 'fillStyle', textFill); ctx.fillText(token.text, x, y); } } function needDrawBackground(style) { return style.textBackgroundColor || (style.textBorderWidth && style.textBorderColor); } // style: {textBackgroundColor, textBorderWidth, textBorderColor, textBorderRadius} // shape: {x, y, width, height} function drawBackground(hostEl, ctx, style, x, y, width, height) { var textBackgroundColor = style.textBackgroundColor; var textBorderWidth = style.textBorderWidth; var textBorderColor = style.textBorderColor; var isPlainBg = isString(textBackgroundColor); setCtx(ctx, 'shadowBlur', style.textBoxShadowBlur || 0); setCtx(ctx, 'shadowColor', style.textBoxShadowColor || 'transparent'); setCtx(ctx, 'shadowOffsetX', style.textBoxShadowOffsetX || 0); setCtx(ctx, 'shadowOffsetY', style.textBoxShadowOffsetY || 0); if (isPlainBg || (textBorderWidth && textBorderColor)) { ctx.beginPath(); var textBorderRadius = style.textBorderRadius; if (!textBorderRadius) { ctx.rect(x, y, width, height); } else { buildPath(ctx, { x: x, y: y, width: width, height: height, r: textBorderRadius }); } ctx.closePath(); } if (isPlainBg) { setCtx(ctx, 'fillStyle', textBackgroundColor); ctx.fill(); } else if (isObject(textBackgroundColor)) { var image = textBackgroundColor.image; image = createOrUpdateImage( image, null, hostEl, onBgImageLoaded, textBackgroundColor ); if (image && isImageReady(image)) { ctx.drawImage(image, x, y, width, height); } } if (textBorderWidth && textBorderColor) { setCtx(ctx, 'lineWidth', textBorderWidth); setCtx(ctx, 'strokeStyle', textBorderColor); ctx.stroke(); } } function onBgImageLoaded(image, textBackgroundColor) { // Replace image, so that `contain/text.js#parseRichText` // will get correct result in next tick. textBackgroundColor.image = image; } function getBoxPosition(blockHeiht, style, rect) { var baseX = style.x || 0; var baseY = style.y || 0; var textAlign = style.textAlign; var textVerticalAlign = style.textVerticalAlign; // Text position represented by coord if (rect) { var textPosition = style.textPosition; if (textPosition instanceof Array) { // Percent baseX = rect.x + parsePercent(textPosition[0], rect.width); baseY = rect.y + parsePercent(textPosition[1], rect.height); } else { var res = adjustTextPositionOnRect( textPosition, rect, style.textDistance ); baseX = res.x; baseY = res.y; // Default align and baseline when has textPosition textAlign = textAlign || res.textAlign; textVerticalAlign = textVerticalAlign || res.textVerticalAlign; } // textOffset is only support in RectText, otherwise // we have to adjust boundingRect for textOffset. var textOffset = style.textOffset; if (textOffset) { baseX += textOffset[0]; baseY += textOffset[1]; } } return { baseX: baseX, baseY: baseY, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; } function setCtx(ctx, prop, value) { // FIXME ??? performance try // if (ctx.__currentValues[prop] !== value) { // ctx[prop] = ctx.__currentValues[prop] = value; ctx[prop] = value; // } return ctx[prop]; } /** * @param {string} [stroke] If specified, do not check style.textStroke. * @param {string} [lineWidth] If specified, do not check style.textStroke. * @param {number} style */ function getStroke(stroke, lineWidth) { return (stroke == null || lineWidth <= 0 || stroke === 'transparent' || stroke === 'none') ? null // TODO pattern and gradient? : (stroke.image || stroke.colorStops) ? '#000' : stroke; } function getFill(fill) { return (fill == null || fill === 'none') ? null // TODO pattern and gradient? : (fill.image || fill.colorStops) ? '#000' : fill; } function parsePercent(value, maxValue) { if (typeof value === 'string') { if (value.lastIndexOf('%') >= 0) { return parseFloat(value) / 100 * maxValue; } return parseFloat(value); } return value; } function getTextXForPadding(x, textAlign, textPadding) { return textAlign === 'right' ? (x - textPadding[1]) : textAlign === 'center' ? (x + textPadding[3] / 2 - textPadding[1] / 2) : (x + textPadding[3]); } /** * @param {string} text * @param {module:zrender/Style} style * @return {boolean} */ function needDrawText(text, style) { return text != null && (text || style.textBackgroundColor || (style.textBorderWidth && style.textBorderColor) || style.textPadding ); } /** * Mixin for drawing text in a element bounding rect * @module zrender/mixin/RectText */ var tmpRect$1 = new BoundingRect(); var RectText = function () {}; RectText.prototype = { constructor: RectText, /** * Draw text in a rect with specified position. * @param {CanvasRenderingContext2D} ctx * @param {Object} rect Displayable rect */ drawRectText: function (ctx, rect) { var style = this.style; rect = style.textRect || rect; // Optimize, avoid normalize every time. this.__dirty && normalizeTextStyle(style, true); var text = style.text; // Convert to string text != null && (text += ''); if (!needDrawText(text, style)) { return; } // FIXME ctx.save(); // Transform rect to view space var transform = this.transform; if (!style.transformText) { if (transform) { tmpRect$1.copy(rect); tmpRect$1.applyTransform(transform); rect = tmpRect$1; } } else { this.setTransform(ctx); } // transformText and textRotation can not be used at the same time. renderText(this, ctx, text, style, rect); ctx.restore(); } }; /** * 可绘制的图形基类 * Base class of all displayable graphic objects * @module zrender/graphic/Displayable */ /** * @alias module:zrender/graphic/Displayable * @extends module:zrender/Element * @extends module:zrender/graphic/mixin/RectText */ function Displayable(opts) { opts = opts || {}; Element.call(this, opts); // Extend properties for (var name in opts) { if ( opts.hasOwnProperty(name) && name !== 'style' ) { this[name] = opts[name]; } } /** * @type {module:zrender/graphic/Style} */ this.style = new Style(opts.style, this); this._rect = null; // Shapes for cascade clipping. this.__clipPaths = []; // FIXME Stateful must be mixined after style is setted // Stateful.call(this, opts); } Displayable.prototype = { constructor: Displayable, type: 'displayable', /** * Displayable 是否为脏,Painter 中会根据该标记判断是否需要是否需要重新绘制 * Dirty flag. From which painter will determine if this displayable object needs brush * @name module:zrender/graphic/Displayable#__dirty * @type {boolean} */ __dirty: true, /** * 图形是否可见,为true时不绘制图形,但是仍能触发鼠标事件 * If ignore drawing of the displayable object. Mouse event will still be triggered * @name module:/zrender/graphic/Displayable#invisible * @type {boolean} * @default false */ invisible: false, /** * @name module:/zrender/graphic/Displayable#z * @type {number} * @default 0 */ z: 0, /** * @name module:/zrender/graphic/Displayable#z * @type {number} * @default 0 */ z2: 0, /** * z层level,决定绘画在哪层canvas中 * @name module:/zrender/graphic/Displayable#zlevel * @type {number} * @default 0 */ zlevel: 0, /** * 是否可拖拽 * @name module:/zrender/graphic/Displayable#draggable * @type {boolean} * @default false */ draggable: false, /** * 是否正在拖拽 * @name module:/zrender/graphic/Displayable#draggable * @type {boolean} * @default false */ dragging: false, /** * 是否相应鼠标事件 * @name module:/zrender/graphic/Displayable#silent * @type {boolean} * @default false */ silent: false, /** * If enable culling * @type {boolean} * @default false */ culling: false, /** * Mouse cursor when hovered * @name module:/zrender/graphic/Displayable#cursor * @type {string} */ cursor: 'pointer', /** * If hover area is bounding rect * @name module:/zrender/graphic/Displayable#rectHover * @type {string} */ rectHover: false, /** * Render the element progressively when the value >= 0, * usefull for large data. * @type {number} */ progressive: -1, beforeBrush: function (ctx) {}, afterBrush: function (ctx) {}, /** * 图形绘制方法 * @param {CanvasRenderingContext2D} ctx */ // Interface brush: function (ctx, prevEl) {}, /** * 获取最小包围盒 * @return {module:zrender/core/BoundingRect} */ // Interface getBoundingRect: function () {}, /** * 判断坐标 x, y 是否在图形上 * If displayable element contain coord x, y * @param {number} x * @param {number} y * @return {boolean} */ contain: function (x, y) { return this.rectContain(x, y); }, /** * @param {Function} cb * @param {} context */ traverse: function (cb, context) { cb.call(context, this); }, /** * 判断坐标 x, y 是否在图形的包围盒上 * If bounding rect of element contain coord x, y * @param {number} x * @param {number} y * @return {boolean} */ rectContain: function (x, y) { var coord = this.transformCoordToLocal(x, y); var rect = this.getBoundingRect(); return rect.contain(coord[0], coord[1]); }, /** * 标记图形元素为脏,并且在下一帧重绘 * Mark displayable element dirty and refresh next frame */ dirty: function () { this.__dirty = true; this._rect = null; this.__zr && this.__zr.refresh(); }, /** * 图形是否会触发事件 * If displayable object binded any event * @return {boolean} */ // TODO, 通过 bind 绑定的事件 // isSilent: function () { // return !( // this.hoverable || this.draggable // || this.onmousemove || this.onmouseover || this.onmouseout // || this.onmousedown || this.onmouseup || this.onclick // || this.ondragenter || this.ondragover || this.ondragleave // || this.ondrop // ); // }, /** * Alias for animate('style') * @param {boolean} loop */ animateStyle: function (loop) { return this.animate('style', loop); }, attrKV: function (key, value) { if (key !== 'style') { Element.prototype.attrKV.call(this, key, value); } else { this.style.set(value); } }, /** * @param {Object|string} key * @param {*} value */ setStyle: function (key, value) { this.style.set(key, value); this.dirty(false); return this; }, /** * Use given style object * @param {Object} obj */ useStyle: function (obj) { this.style = new Style(obj, this); this.dirty(false); return this; } }; inherits(Displayable, Element); mixin(Displayable, RectText); /** * @alias zrender/graphic/Image * @extends module:zrender/graphic/Displayable * @constructor * @param {Object} opts */ function ZImage(opts) { Displayable.call(this, opts); } ZImage.prototype = { constructor: ZImage, type: 'image', brush: function (ctx, prevEl) { var style = this.style; var src = style.image; // Must bind each time style.bind(ctx, this, prevEl); var image = this._image = createOrUpdateImage( src, this._image, this, this.onload ); if (!image || !isImageReady(image)) { return; } // 图片已经加载完成 // if (image.nodeName.toUpperCase() == 'IMG') { // if (!image.complete) { // return; // } // } // Else is canvas var x = style.x || 0; var y = style.y || 0; var width = style.width; var height = style.height; var aspect = image.width / image.height; if (width == null && height != null) { // Keep image/height ratio width = height * aspect; } else if (height == null && width != null) { height = width / aspect; } else if (width == null && height == null) { width = image.width; height = image.height; } // 设置transform this.setTransform(ctx); if (style.sWidth && style.sHeight) { var sx = style.sx || 0; var sy = style.sy || 0; ctx.drawImage( image, sx, sy, style.sWidth, style.sHeight, x, y, width, height ); } else if (style.sx && style.sy) { var sx = style.sx; var sy = style.sy; var sWidth = width - sx; var sHeight = height - sy; ctx.drawImage( image, sx, sy, sWidth, sHeight, x, y, width, height ); } else { ctx.drawImage(image, x, y, width, height); } this.restoreTransform(ctx); // Draw rect text if (style.text != null) { this.drawRectText(ctx, this.getBoundingRect()); } }, getBoundingRect: function () { var style = this.style; if (! this._rect) { this._rect = new BoundingRect( style.x || 0, style.y || 0, style.width || 0, style.height || 0 ); } return this._rect; } }; inherits(ZImage, Displayable); /** * Default canvas painter * @module zrender/Painter * @author Kener (@Kener-林峰, kener.linfeng@gmail.com) * errorrik (errorrik@gmail.com) * pissang (https://www.github.com/pissang) */ // PENDIGN // Layer exceeds MAX_PROGRESSIVE_LAYER_NUMBER may have some problem when flush directly second time. // // Maximum progressive layer. When exceeding this number. All elements will be drawed in the last layer. var MAX_PROGRESSIVE_LAYER_NUMBER = 5; function parseInt10(val) { return parseInt(val, 10); } function isLayerValid(layer) { if (!layer) { return false; } if (layer.__builtin__) { return true; } if (typeof(layer.resize) !== 'function' || typeof(layer.refresh) !== 'function' ) { return false; } return true; } function preProcessLayer(layer) { layer.__unusedCount++; } function postProcessLayer(layer) { if (layer.__unusedCount == 1) { layer.clear(); } } var tmpRect = new BoundingRect(0, 0, 0, 0); var viewRect = new BoundingRect(0, 0, 0, 0); function isDisplayableCulled(el, width, height) { tmpRect.copy(el.getBoundingRect()); if (el.transform) { tmpRect.applyTransform(el.transform); } viewRect.width = width; viewRect.height = height; return !tmpRect.intersect(viewRect); } function isClipPathChanged(clipPaths, prevClipPaths) { if (clipPaths == prevClipPaths) { // Can both be null or undefined return false; } if (!clipPaths || !prevClipPaths || (clipPaths.length !== prevClipPaths.length)) { return true; } for (var i = 0; i < clipPaths.length; i++) { if (clipPaths[i] !== prevClipPaths[i]) { return true; } } } function doClip(clipPaths, ctx) { for (var i = 0; i < clipPaths.length; i++) { var clipPath = clipPaths[i]; clipPath.setTransform(ctx); ctx.beginPath(); clipPath.buildPath(ctx, clipPath.shape); ctx.clip(); // Transform back clipPath.restoreTransform(ctx); } } function createRoot(width, height) { var domRoot = document.createElement('div'); // domRoot.onselectstart = returnFalse; // 避免页面选中的尴尬 domRoot.style.cssText = [ 'position:relative', 'overflow:hidden', 'width:' + width + 'px', 'height:' + height + 'px', 'padding:0', 'margin:0', 'border-width:0' ].join(';') + ';'; return domRoot; } /** * @alias module:zrender/Painter * @constructor * @param {HTMLElement} root 绘图容器 * @param {module:zrender/Storage} storage * @param {Object} opts */ var Painter = function (root, storage, opts) { this.type = 'canvas'; // In node environment using node-canvas var singleCanvas = !root.nodeName // In node ? || root.nodeName.toUpperCase() === 'CANVAS'; this._opts = opts = extend({}, opts || {}); /** * @type {number} */ this.dpr = opts.devicePixelRatio || devicePixelRatio; /** * @type {boolean} * @private */ this._singleCanvas = singleCanvas; /** * 绘图容器 * @type {HTMLElement} */ this.root = root; var rootStyle = root.style; if (rootStyle) { rootStyle['-webkit-tap-highlight-color'] = 'transparent'; rootStyle['-webkit-user-select'] = rootStyle['user-select'] = rootStyle['-webkit-touch-callout'] = 'none'; root.innerHTML = ''; } /** * @type {module:zrender/Storage} */ this.storage = storage; /** * @type {Array.<number>} * @private */ var zlevelList = this._zlevelList = []; /** * @type {Object.<string, module:zrender/Layer>} * @private */ var layers = this._layers = {}; /** * @type {Object.<string, Object>} * @type {private} */ this._layerConfig = {}; if (!singleCanvas) { this._width = this._getSize(0); this._height = this._getSize(1); var domRoot = this._domRoot = createRoot( this._width, this._height ); root.appendChild(domRoot); } else { if (opts.width != null) { root.width = opts.width; } if (opts.height != null) { root.height = opts.height; } // Use canvas width and height directly var width = root.width; var height = root.height; this._width = width; this._height = height; // Create layer if only one given canvas // Device pixel ratio is fixed to 1 because given canvas has its specified width and height var mainLayer = new Layer(root, this, 1); mainLayer.initContext(); // FIXME Use canvas width and height // mainLayer.resize(width, height); layers[0] = mainLayer; zlevelList.push(0); this._domRoot = root; } // Layers for progressive rendering this._progressiveLayers = []; /** * @type {module:zrender/Layer} * @private */ this._hoverlayer; this._hoverElements = []; }; Painter.prototype = { constructor: Painter, getType: function () { return 'canvas'; }, /** * If painter use a single canvas * @return {boolean} */ isSingleCanvas: function () { return this._singleCanvas; }, /** * @return {HTMLDivElement} */ getViewportRoot: function () { return this._domRoot; }, getViewportRootOffset: function () { var viewportRoot = this.getViewportRoot(); if (viewportRoot) { return { offsetLeft: viewportRoot.offsetLeft || 0, offsetTop: viewportRoot.offsetTop || 0 }; } }, /** * 刷新 * @param {boolean} [paintAll=false] 强制绘制所有displayable */ refresh: function (paintAll) { var list = this.storage.getDisplayList(true); var zlevelList = this._zlevelList; this._paintList(list, paintAll); // Paint custum layers for (var i = 0; i < zlevelList.length; i++) { var z = zlevelList[i]; var layer = this._layers[z]; if (!layer.__builtin__ && layer.refresh) { layer.refresh(); } } this.refreshHover(); if (this._progressiveLayers.length) { this._startProgessive(); } return this; }, addHover: function (el, hoverStyle) { if (el.__hoverMir) { return; } var elMirror = new el.constructor({ style: el.style, shape: el.shape }); elMirror.__from = el; el.__hoverMir = elMirror; elMirror.setStyle(hoverStyle); this._hoverElements.push(elMirror); }, removeHover: function (el) { var elMirror = el.__hoverMir; var hoverElements = this._hoverElements; var idx = indexOf(hoverElements, elMirror); if (idx >= 0) { hoverElements.splice(idx, 1); } el.__hoverMir = null; }, clearHover: function (el) { var hoverElements = this._hoverElements; for (var i = 0; i < hoverElements.length; i++) { var from = hoverElements[i].__from; if (from) { from.__hoverMir = null; } } hoverElements.length = 0; }, refreshHover: function () { var hoverElements = this._hoverElements; var len = hoverElements.length; var hoverLayer = this._hoverlayer; hoverLayer && hoverLayer.clear(); if (!len) { return; } sort(hoverElements, this.storage.displayableSortFunc); // Use a extream large zlevel // FIXME? if (!hoverLayer) { hoverLayer = this._hoverlayer = this.getLayer(1e5); } var scope = {}; hoverLayer.ctx.save(); for (var i = 0; i < len;) { var el = hoverElements[i]; var originalEl = el.__from; // Original el is removed // PENDING if (!(originalEl && originalEl.__zr)) { hoverElements.splice(i, 1); originalEl.__hoverMir = null; len--; continue; } i++; // Use transform // FIXME style and shape ? if (!originalEl.invisible) { el.transform = originalEl.transform; el.invTransform = originalEl.invTransform; el.__clipPaths = originalEl.__clipPaths; // el. this._doPaintEl(el, hoverLayer, true, scope); } } hoverLayer.ctx.restore(); }, _startProgessive: function () { var self = this; if (!self._furtherProgressive) { return; } // Use a token to stop progress steps triggered by // previous zr.refresh calling. var token = self._progressiveToken = +new Date(); self._progress++; requestAnimationFrame(step); function step() { // In case refreshed or disposed if (token === self._progressiveToken && self.storage) { self._doPaintList(self.storage.getDisplayList()); if (self._furtherProgressive) { self._progress++; requestAnimationFrame(step); } else { self._progressiveToken = -1; } } } }, _clearProgressive: function () { this._progressiveToken = -1; this._progress = 0; each$1(this._progressiveLayers, function (layer) { layer.__dirty && layer.clear(); }); }, _paintList: function (list, paintAll) { if (paintAll == null) { paintAll = false; } this._updateLayerStatus(list); this._clearProgressive(); this.eachBuiltinLayer(preProcessLayer); this._doPaintList(list, paintAll); this.eachBuiltinLayer(postProcessLayer); }, _doPaintList: function (list, paintAll) { var currentLayer; var currentZLevel; var ctx; // var invTransform = []; var scope; var progressiveLayerIdx = 0; var currentProgressiveLayer; var width = this._width; var height = this._height; var layerProgress; var frame = this._progress; function flushProgressiveLayer(layer) { var dpr = ctx.dpr || 1; ctx.save(); ctx.globalAlpha = 1; ctx.shadowBlur = 0; // Avoid layer don't clear in next progressive frame currentLayer.__dirty = true; ctx.setTransform(1, 0, 0, 1, 0, 0); ctx.drawImage(layer.dom, 0, 0, width * dpr, height * dpr); ctx.restore(); } for (var i = 0, l = list.length; i < l; i++) { var el = list[i]; var elZLevel = this._singleCanvas ? 0 : el.zlevel; var elFrame = el.__frame; // Flush at current context // PENDING if (elFrame < 0 && currentProgressiveLayer) { flushProgressiveLayer(currentProgressiveLayer); currentProgressiveLayer = null; } // Change draw layer if (currentZLevel !== elZLevel) { if (ctx) { ctx.restore(); } // Reset scope scope = {}; // Only 0 zlevel if only has one canvas currentZLevel = elZLevel; currentLayer = this.getLayer(currentZLevel); if (!currentLayer.__builtin__) { log$1( 'ZLevel ' + currentZLevel + ' has been used by unkown layer ' + currentLayer.id ); } ctx = currentLayer.ctx; ctx.save(); // Reset the count currentLayer.__unusedCount = 0; if (currentLayer.__dirty || paintAll) { currentLayer.clear(); } } if (!(currentLayer.__dirty || paintAll)) { continue; } if (elFrame >= 0) { // Progressive layer changed if (!currentProgressiveLayer) { currentProgressiveLayer = this._progressiveLayers[ Math.min(progressiveLayerIdx++, MAX_PROGRESSIVE_LAYER_NUMBER - 1) ]; currentProgressiveLayer.ctx.save(); currentProgressiveLayer.renderScope = {}; if (currentProgressiveLayer && (currentProgressiveLayer.__progress > currentProgressiveLayer.__maxProgress) ) { // flushProgressiveLayer(currentProgressiveLayer); // Quick jump all progressive elements // All progressive element are not dirty, jump over and flush directly i = currentProgressiveLayer.__nextIdxNotProg - 1; // currentProgressiveLayer = null; continue; } layerProgress = currentProgressiveLayer.__progress; if (!currentProgressiveLayer.__dirty) { // Keep rendering frame = layerProgress; } currentProgressiveLayer.__progress = frame + 1; } if (elFrame === frame) { this._doPaintEl(el, currentProgressiveLayer, true, currentProgressiveLayer.renderScope); } } else { this._doPaintEl(el, currentLayer, paintAll, scope); } el.__dirty = false; } if (currentProgressiveLayer) { flushProgressiveLayer(currentProgressiveLayer); } // Restore the lastLayer ctx ctx && ctx.restore(); // If still has clipping state // if (scope.prevElClipPaths) { // ctx.restore(); // } this._furtherProgressive = false; each$1(this._progressiveLayers, function (layer) { if (layer.__maxProgress >= layer.__progress) { this._furtherProgressive = true; } }, this); }, _doPaintEl: function (el, currentLayer, forcePaint, scope) { var ctx = currentLayer.ctx; var m = el.transform; if ( (currentLayer.__dirty || forcePaint) // Ignore invisible element && !el.invisible // Ignore transparent element && el.style.opacity !== 0 // Ignore scale 0 element, in some environment like node-canvas // Draw a scale 0 element can cause all following draw wrong // And setTransform with scale 0 will cause set back transform failed. && !(m && !m[0] && !m[3]) // Ignore culled element && !(el.culling && isDisplayableCulled(el, this._width, this._height)) ) { var clipPaths = el.__clipPaths; // Optimize when clipping on group with several elements if (scope.prevClipLayer !== currentLayer || isClipPathChanged(clipPaths, scope.prevElClipPaths) ) { // If has previous clipping state, restore from it if (scope.prevElClipPaths) { scope.prevClipLayer.ctx.restore(); scope.prevClipLayer = scope.prevElClipPaths = null; // Reset prevEl since context has been restored scope.prevEl = null; } // New clipping state if (clipPaths) { ctx.save(); doClip(clipPaths, ctx); scope.prevClipLayer = currentLayer; scope.prevElClipPaths = clipPaths; } } el.beforeBrush && el.beforeBrush(ctx); el.brush(ctx, scope.prevEl || null); scope.prevEl = el; el.afterBrush && el.afterBrush(ctx); } }, /** * 获取 zlevel 所在层,如果不存在则会创建一个新的层 * @param {number} zlevel * @return {module:zrender/Layer} */ getLayer: function (zlevel) { if (this._singleCanvas) { return this._layers[0]; } var layer = this._layers[zlevel]; if (!layer) { // Create a new layer layer = new Layer('zr_' + zlevel, this, this.dpr); layer.__builtin__ = true; if (this._layerConfig[zlevel]) { merge(layer, this._layerConfig[zlevel], true); } this.insertLayer(zlevel, layer); // Context is created after dom inserted to document // Or excanvas will get 0px clientWidth and clientHeight layer.initContext(); } return layer; }, insertLayer: function (zlevel, layer) { var layersMap = this._layers; var zlevelList = this._zlevelList; var len = zlevelList.length; var prevLayer = null; var i = -1; var domRoot = this._domRoot; if (layersMap[zlevel]) { log$1('ZLevel ' + zlevel + ' has been used already'); return; } // Check if is a valid layer if (!isLayerValid(layer)) { log$1('Layer of zlevel ' + zlevel + ' is not valid'); return; } if (len > 0 && zlevel > zlevelList[0]) { for (i = 0; i < len - 1; i++) { if ( zlevelList[i] < zlevel && zlevelList[i + 1] > zlevel ) { break; } } prevLayer = layersMap[zlevelList[i]]; } zlevelList.splice(i + 1, 0, zlevel); layersMap[zlevel] = layer; // Vitual layer will not directly show on the screen. // (It can be a WebGL layer and assigned to a ZImage element) // But it still under management of zrender. if (!layer.virtual) { if (prevLayer) { var prevDom = prevLayer.dom; if (prevDom.nextSibling) { domRoot.insertBefore( layer.dom, prevDom.nextSibling ); } else { domRoot.appendChild(layer.dom); } } else { if (domRoot.firstChild) { domRoot.insertBefore(layer.dom, domRoot.firstChild); } else { domRoot.appendChild(layer.dom); } } } }, // Iterate each layer eachLayer: function (cb, context) { var zlevelList = this._zlevelList; var z; var i; for (i = 0; i < zlevelList.length; i++) { z = zlevelList[i]; cb.call(context, this._layers[z], z); } }, // Iterate each buildin layer eachBuiltinLayer: function (cb, context) { var zlevelList = this._zlevelList; var layer; var z; var i; for (i = 0; i < zlevelList.length; i++) { z = zlevelList[i]; layer = this._layers[z]; if (layer.__builtin__) { cb.call(context, layer, z); } } }, // Iterate each other layer except buildin layer eachOtherLayer: function (cb, context) { var zlevelList = this._zlevelList; var layer; var z; var i; for (i = 0; i < zlevelList.length; i++) { z = zlevelList[i]; layer = this._layers[z]; if (!layer.__builtin__) { cb.call(context, layer, z); } } }, /** * 获取所有已创建的层 * @param {Array.<module:zrender/Layer>} [prevLayer] */ getLayers: function () { return this._layers; }, _updateLayerStatus: function (list) { var layers = this._layers; var progressiveLayers = this._progressiveLayers; var elCountsLastFrame = {}; var progressiveElCountsLastFrame = {}; this.eachBuiltinLayer(function (layer, z) { elCountsLastFrame[z] = layer.elCount; layer.elCount = 0; layer.__dirty = false; }); each$1(progressiveLayers, function (layer, idx) { progressiveElCountsLastFrame[idx] = layer.elCount; layer.elCount = 0; layer.__dirty = false; }); var progressiveLayerCount = 0; var currentProgressiveLayer; var lastProgressiveKey; var frameCount = 0; for (var i = 0, l = list.length; i < l; i++) { var el = list[i]; var zlevel = this._singleCanvas ? 0 : el.zlevel; var layer = layers[zlevel]; var elProgress = el.progressive; if (layer) { layer.elCount++; layer.__dirty = layer.__dirty || el.__dirty; } /////// Update progressive if (elProgress >= 0) { // Fix wrong progressive sequence problem. if (lastProgressiveKey !== elProgress) { lastProgressiveKey = elProgress; frameCount++; } var elFrame = el.__frame = frameCount - 1; if (!currentProgressiveLayer) { var idx = Math.min(progressiveLayerCount, MAX_PROGRESSIVE_LAYER_NUMBER - 1); currentProgressiveLayer = progressiveLayers[idx]; if (!currentProgressiveLayer) { currentProgressiveLayer = progressiveLayers[idx] = new Layer( 'progressive', this, this.dpr ); currentProgressiveLayer.initContext(); } currentProgressiveLayer.__maxProgress = 0; } currentProgressiveLayer.__dirty = currentProgressiveLayer.__dirty || el.__dirty; currentProgressiveLayer.elCount++; currentProgressiveLayer.__maxProgress = Math.max( currentProgressiveLayer.__maxProgress, elFrame ); if (currentProgressiveLayer.__maxProgress >= currentProgressiveLayer.__progress) { // Should keep rendering this layer because progressive rendering is not finished yet layer.__dirty = true; } } else { el.__frame = -1; if (currentProgressiveLayer) { currentProgressiveLayer.__nextIdxNotProg = i; progressiveLayerCount++; currentProgressiveLayer = null; } } } if (currentProgressiveLayer) { progressiveLayerCount++; currentProgressiveLayer.__nextIdxNotProg = i; } // 层中的元素数量有发生变化 this.eachBuiltinLayer(function (layer, z) { if (elCountsLastFrame[z] !== layer.elCount) { layer.__dirty = true; } }); progressiveLayers.length = Math.min(progressiveLayerCount, MAX_PROGRESSIVE_LAYER_NUMBER); each$1(progressiveLayers, function (layer, idx) { if (progressiveElCountsLastFrame[idx] !== layer.elCount) { el.__dirty = true; } if (layer.__dirty) { layer.__progress = 0; } }); }, /** * 清除hover层外所有内容 */ clear: function () { this.eachBuiltinLayer(this._clearLayer); return this; }, _clearLayer: function (layer) { layer.clear(); }, /** * 修改指定zlevel的绘制参数 * * @param {string} zlevel * @param {Object} config 配置对象 * @param {string} [config.clearColor=0] 每次清空画布的颜色 * @param {string} [config.motionBlur=false] 是否开启动态模糊 * @param {number} [config.lastFrameAlpha=0.7] * 在开启动态模糊的时候使用,与上一帧混合的alpha值,值越大尾迹越明显 */ configLayer: function (zlevel, config) { if (config) { var layerConfig = this._layerConfig; if (!layerConfig[zlevel]) { layerConfig[zlevel] = config; } else { merge(layerConfig[zlevel], config, true); } var layer = this._layers[zlevel]; if (layer) { merge(layer, layerConfig[zlevel], true); } } }, /** * 删除指定层 * @param {number} zlevel 层所在的zlevel */ delLayer: function (zlevel) { var layers = this._layers; var zlevelList = this._zlevelList; var layer = layers[zlevel]; if (!layer) { return; } layer.dom.parentNode.removeChild(layer.dom); delete layers[zlevel]; zlevelList.splice(indexOf(zlevelList, zlevel), 1); }, /** * 区域大小变化后重绘 */ resize: function (width, height) { var domRoot = this._domRoot; // FIXME Why ? domRoot.style.display = 'none'; // Save input w/h var opts = this._opts; width != null && (opts.width = width); height != null && (opts.height = height); width = this._getSize(0); height = this._getSize(1); domRoot.style.display = ''; // 优化没有实际改变的resize if (this._width != width || height != this._height) { domRoot.style.width = width + 'px'; domRoot.style.height = height + 'px'; for (var id in this._layers) { if (this._layers.hasOwnProperty(id)) { this._layers[id].resize(width, height); } } each$1(this._progressiveLayers, function (layer) { layer.resize(width, height); }); this.refresh(true); } this._width = width; this._height = height; return this; }, /** * 清除单独的一个层 * @param {number} zlevel */ clearLayer: function (zlevel) { var layer = this._layers[zlevel]; if (layer) { layer.clear(); } }, /** * 释放 */ dispose: function () { this.root.innerHTML = ''; this.root = this.storage = this._domRoot = this._layers = null; }, /** * Get canvas which has all thing rendered * @param {Object} opts * @param {string} [opts.backgroundColor] * @param {number} [opts.pixelRatio] */ getRenderedCanvas: function (opts) { opts = opts || {}; if (this._singleCanvas) { return this._layers[0].dom; } var imageLayer = new Layer('image', this, opts.pixelRatio || this.dpr); imageLayer.initContext(); imageLayer.clearColor = opts.backgroundColor; imageLayer.clear(); var displayList = this.storage.getDisplayList(true); var scope = {}; var zlevel; var self = this; function findAndDrawOtherLayer(smaller, larger) { var zlevelList = self._zlevelList; if (smaller == null) { smaller = -Infinity; } var intermediateLayer; for (var i = 0; i < zlevelList.length; i++) { var z = zlevelList[i]; var layer = self._layers[z]; if (!layer.__builtin__ && z > smaller && z < larger) { intermediateLayer = layer; break; } } if (intermediateLayer && intermediateLayer.renderToCanvas) { imageLayer.ctx.save(); intermediateLayer.renderToCanvas(imageLayer.ctx); imageLayer.ctx.restore(); } } for (var i = 0; i < displayList.length; i++) { var el = displayList[i]; if (el.zlevel !== zlevel) { findAndDrawOtherLayer(zlevel, el.zlevel); zlevel = el.zlevel; } this._doPaintEl(el, imageLayer, true, scope); } findAndDrawOtherLayer(zlevel, Infinity); return imageLayer.dom; }, /** * 获取绘图区域宽度 */ getWidth: function () { return this._width; }, /** * 获取绘图区域高度 */ getHeight: function () { return this._height; }, _getSize: function (whIdx) { var opts = this._opts; var wh = ['width', 'height'][whIdx]; var cwh = ['clientWidth', 'clientHeight'][whIdx]; var plt = ['paddingLeft', 'paddingTop'][whIdx]; var prb = ['paddingRight', 'paddingBottom'][whIdx]; if (opts[wh] != null && opts[wh] !== 'auto') { return parseFloat(opts[wh]); } var root = this.root; // IE8 does not support getComputedStyle, but it use VML. var stl = document.defaultView.getComputedStyle(root); return ( (root[cwh] || parseInt10(stl[wh]) || parseInt10(root.style[wh])) - (parseInt10(stl[plt]) || 0) - (parseInt10(stl[prb]) || 0) ) | 0; }, pathToImage: function (path, dpr) { dpr = dpr || this.dpr; var canvas = document.createElement('canvas'); var ctx = canvas.getContext('2d'); var rect = path.getBoundingRect(); var style = path.style; var shadowBlurSize = style.shadowBlur; var shadowOffsetX = style.shadowOffsetX; var shadowOffsetY = style.shadowOffsetY; var lineWidth = style.hasStroke() ? style.lineWidth : 0; var leftMargin = Math.max(lineWidth / 2, -shadowOffsetX + shadowBlurSize); var rightMargin = Math.max(lineWidth / 2, shadowOffsetX + shadowBlurSize); var topMargin = Math.max(lineWidth / 2, -shadowOffsetY + shadowBlurSize); var bottomMargin = Math.max(lineWidth / 2, shadowOffsetY + shadowBlurSize); var width = rect.width + leftMargin + rightMargin; var height = rect.height + topMargin + bottomMargin; canvas.width = width * dpr; canvas.height = height * dpr; ctx.scale(dpr, dpr); ctx.clearRect(0, 0, width, height); ctx.dpr = dpr; var pathTransform = { position: path.position, rotation: path.rotation, scale: path.scale }; path.position = [leftMargin - rect.x, topMargin - rect.y]; path.rotation = 0; path.scale = [1, 1]; path.updateTransform(); if (path) { path.brush(ctx); } var ImageShape = ZImage; var imgShape = new ImageShape({ style: { x: 0, y: 0, image: canvas } }); if (pathTransform.position != null) { imgShape.position = path.position = pathTransform.position; } if (pathTransform.rotation != null) { imgShape.rotation = path.rotation = pathTransform.rotation; } if (pathTransform.scale != null) { imgShape.scale = path.scale = pathTransform.scale; } return imgShape; } }; /** * 事件辅助类 * @module zrender/core/event * @author Kener (@Kener-林峰, kener.linfeng@gmail.com) */ var isDomLevel2 = (typeof window !== 'undefined') && !!window.addEventListener; var MOUSE_EVENT_REG = /^(?:mouse|pointer|contextmenu|drag|drop)|click/; function getBoundingClientRect(el) { // BlackBerry 5, iOS 3 (original iPhone) don't have getBoundingRect return el.getBoundingClientRect ? el.getBoundingClientRect() : {left: 0, top: 0}; } // `calculate` is optional, default false function clientToLocal(el, e, out, calculate) { out = out || {}; // According to the W3C Working Draft, offsetX and offsetY should be relative // to the padding edge of the target element. The only browser using this convention // is IE. Webkit uses the border edge, Opera uses the content edge, and FireFox does // not support the properties. // (see http://www.jacklmoore.com/notes/mouse-position/) // In zr painter.dom, padding edge equals to border edge. // FIXME // When mousemove event triggered on ec tooltip, target is not zr painter.dom, and // offsetX/Y is relative to e.target, where the calculation of zrX/Y via offsetX/Y // is too complex. So css-transfrom dont support in this case temporarily. if (calculate || !env$1.canvasSupported) { defaultGetZrXY(el, e, out); } // Caution: In FireFox, layerX/layerY Mouse position relative to the closest positioned // ancestor element, so we should make sure el is positioned (e.g., not position:static). // BTW1, Webkit don't return the same results as FF in non-simple cases (like add // zoom-factor, overflow / opacity layers, transforms ...) // BTW2, (ev.offsetY || ev.pageY - $(ev.target).offset().top) is not correct in preserve-3d. // <https://bugs.jquery.com/ticket/8523#comment:14> // BTW3, In ff, offsetX/offsetY is always 0. else if (env$1.browser.firefox && e.layerX != null && e.layerX !== e.offsetX) { out.zrX = e.layerX; out.zrY = e.layerY; } // For IE6+, chrome, safari, opera. (When will ff support offsetX?) else if (e.offsetX != null) { out.zrX = e.offsetX; out.zrY = e.offsetY; } // For some other device, e.g., IOS safari. else { defaultGetZrXY(el, e, out); } return out; } function defaultGetZrXY(el, e, out) { // This well-known method below does not support css transform. var box = getBoundingClientRect(el); out.zrX = e.clientX - box.left; out.zrY = e.clientY - box.top; } /** * 如果存在第三方嵌入的一些dom触发的事件,或touch事件,需要转换一下事件坐标. * `calculate` is optional, default false. */ function normalizeEvent(el, e, calculate) { e = e || window.event; if (e.zrX != null) { return e; } var eventType = e.type; var isTouch = eventType && eventType.indexOf('touch') >= 0; if (!isTouch) { clientToLocal(el, e, e, calculate); e.zrDelta = (e.wheelDelta) ? e.wheelDelta / 120 : -(e.detail || 0) / 3; } else { var touch = eventType != 'touchend' ? e.targetTouches[0] : e.changedTouches[0]; touch && clientToLocal(el, touch, e, calculate); } // Add which for click: 1 === left; 2 === middle; 3 === right; otherwise: 0; // See jQuery: https://github.com/jquery/jquery/blob/master/src/event.js // If e.which has been defined, if may be readonly, // see: https://developer.mozilla.org/en-US/docs/Web/API/MouseEvent/which var button = e.button; if (e.which == null && button !== undefined && MOUSE_EVENT_REG.test(e.type)) { e.which = (button & 1 ? 1 : (button & 2 ? 3 : (button & 4 ? 2 : 0))); } return e; } function addEventListener(el, name, handler) { if (isDomLevel2) { el.addEventListener(name, handler); } else { el.attachEvent('on' + name, handler); } } function removeEventListener(el, name, handler) { if (isDomLevel2) { el.removeEventListener(name, handler); } else { el.detachEvent('on' + name, handler); } } /** * preventDefault and stopPropagation. * Notice: do not do that in zrender. Upper application * do that if necessary. * * @memberOf module:zrender/core/event * @method * @param {Event} e : event对象 */ /** * 动画主类, 调度和管理所有动画控制器 * * @module zrender/animation/Animation * @author pissang(https://github.com/pissang) */ // TODO Additive animation // http://iosoteric.com/additive-animations-animatewithduration-in-ios-8/ // https://developer.apple.com/videos/wwdc2014/#236 /** * @typedef {Object} IZRenderStage * @property {Function} update */ /** * @alias module:zrender/animation/Animation * @constructor * @param {Object} [options] * @param {Function} [options.onframe] * @param {IZRenderStage} [options.stage] * @example * var animation = new Animation(); * var obj = { * x: 100, * y: 100 * }; * animation.animate(node.position) * .when(1000, { * x: 500, * y: 500 * }) * .when(2000, { * x: 100, * y: 100 * }) * .start('spline'); */ var Animation = function (options) { options = options || {}; this.stage = options.stage || {}; this.onframe = options.onframe || function() {}; // private properties this._clips = []; this._running = false; this._time; this._pausedTime; this._pauseStart; this._paused = false; Eventful.call(this); }; Animation.prototype = { constructor: Animation, /** * 添加 clip * @param {module:zrender/animation/Clip} clip */ addClip: function (clip) { this._clips.push(clip); }, /** * 添加 animator * @param {module:zrender/animation/Animator} animator */ addAnimator: function (animator) { animator.animation = this; var clips = animator.getClips(); for (var i = 0; i < clips.length; i++) { this.addClip(clips[i]); } }, /** * 删除动画片段 * @param {module:zrender/animation/Clip} clip */ removeClip: function(clip) { var idx = indexOf(this._clips, clip); if (idx >= 0) { this._clips.splice(idx, 1); } }, /** * 删除动画片段 * @param {module:zrender/animation/Animator} animator */ removeAnimator: function (animator) { var clips = animator.getClips(); for (var i = 0; i < clips.length; i++) { this.removeClip(clips[i]); } animator.animation = null; }, _update: function() { var time = new Date().getTime() - this._pausedTime; var delta = time - this._time; var clips = this._clips; var len = clips.length; var deferredEvents = []; var deferredClips = []; for (var i = 0; i < len; i++) { var clip = clips[i]; var e = clip.step(time, delta); // Throw out the events need to be called after // stage.update, like destroy if (e) { deferredEvents.push(e); deferredClips.push(clip); } } // Remove the finished clip for (var i = 0; i < len;) { if (clips[i]._needsRemove) { clips[i] = clips[len - 1]; clips.pop(); len--; } else { i++; } } len = deferredEvents.length; for (var i = 0; i < len; i++) { deferredClips[i].fire(deferredEvents[i]); } this._time = time; this.onframe(delta); this.trigger('frame', delta); if (this.stage.update) { this.stage.update(); } }, _startLoop: function () { var self = this; this._running = true; function step() { if (self._running) { requestAnimationFrame(step); !self._paused && self._update(); } } requestAnimationFrame(step); }, /** * 开始运行动画 */ start: function () { this._time = new Date().getTime(); this._pausedTime = 0; this._startLoop(); }, /** * 停止运行动画 */ stop: function () { this._running = false; }, /** * Pause */ pause: function () { if (!this._paused) { this._pauseStart = new Date().getTime(); this._paused = true; } }, /** * Resume */ resume: function () { if (this._paused) { this._pausedTime += (new Date().getTime()) - this._pauseStart; this._paused = false; } }, /** * 清除所有动画片段 */ clear: function () { this._clips = []; }, /** * 对一个目标创建一个animator对象,可以指定目标中的属性使用动画 * @param {Object} target * @param {Object} options * @param {boolean} [options.loop=false] 是否循环播放动画 * @param {Function} [options.getter=null] * 如果指定getter函数,会通过getter函数取属性值 * @param {Function} [options.setter=null] * 如果指定setter函数,会通过setter函数设置属性值 * @return {module:zrender/animation/Animation~Animator} */ // TODO Gap animate: function (target, options) { options = options || {}; var animator = new Animator( target, options.loop, options.getter, options.setter ); this.addAnimator(animator); return animator; } }; mixin(Animation, Eventful); /** * Only implements needed gestures for mobile. */ var GestureMgr = function () { /** * @private * @type {Array.<Object>} */ this._track = []; }; GestureMgr.prototype = { constructor: GestureMgr, recognize: function (event, target, root) { this._doTrack(event, target, root); return this._recognize(event); }, clear: function () { this._track.length = 0; return this; }, _doTrack: function (event, target, root) { var touches = event.touches; if (!touches) { return; } var trackItem = { points: [], touches: [], target: target, event: event }; for (var i = 0, len = touches.length; i < len; i++) { var touch = touches[i]; var pos = clientToLocal(root, touch, {}); trackItem.points.push([pos.zrX, pos.zrY]); trackItem.touches.push(touch); } this._track.push(trackItem); }, _recognize: function (event) { for (var eventName in recognizers) { if (recognizers.hasOwnProperty(eventName)) { var gestureInfo = recognizers[eventName](this._track, event); if (gestureInfo) { return gestureInfo; } } } } }; function dist$1(pointPair) { var dx = pointPair[1][0] - pointPair[0][0]; var dy = pointPair[1][1] - pointPair[0][1]; return Math.sqrt(dx * dx + dy * dy); } function center(pointPair) { return [ (pointPair[0][0] + pointPair[1][0]) / 2, (pointPair[0][1] + pointPair[1][1]) / 2 ]; } var recognizers = { pinch: function (track, event) { var trackLen = track.length; if (!trackLen) { return; } var pinchEnd = (track[trackLen - 1] || {}).points; var pinchPre = (track[trackLen - 2] || {}).points || pinchEnd; if (pinchPre && pinchPre.length > 1 && pinchEnd && pinchEnd.length > 1 ) { var pinchScale = dist$1(pinchEnd) / dist$1(pinchPre); !isFinite(pinchScale) && (pinchScale = 1); event.pinchScale = pinchScale; var pinchCenter = center(pinchEnd); event.pinchX = pinchCenter[0]; event.pinchY = pinchCenter[1]; return { type: 'pinch', target: track[0].target, event: event }; } } // Only pinch currently. }; var TOUCH_CLICK_DELAY = 300; var mouseHandlerNames = [ 'click', 'dblclick', 'mousewheel', 'mouseout', 'mouseup', 'mousedown', 'mousemove', 'contextmenu' ]; var touchHandlerNames = [ 'touchstart', 'touchend', 'touchmove' ]; var pointerEventNames = { pointerdown: 1, pointerup: 1, pointermove: 1, pointerout: 1 }; var pointerHandlerNames = map(mouseHandlerNames, function (name) { var nm = name.replace('mouse', 'pointer'); return pointerEventNames[nm] ? nm : name; }); function eventNameFix(name) { return (name === 'mousewheel' && env$1.browser.firefox) ? 'DOMMouseScroll' : name; } function processGesture(proxy, event, stage) { var gestureMgr = proxy._gestureMgr; stage === 'start' && gestureMgr.clear(); var gestureInfo = gestureMgr.recognize( event, proxy.handler.findHover(event.zrX, event.zrY, null).target, proxy.dom ); stage === 'end' && gestureMgr.clear(); // Do not do any preventDefault here. Upper application do that if necessary. if (gestureInfo) { var type = gestureInfo.type; event.gestureEvent = type; proxy.handler.dispatchToElement({target: gestureInfo.target}, type, gestureInfo.event); } } // function onMSGestureChange(proxy, event) { // if (event.translationX || event.translationY) { // // mousemove is carried by MSGesture to reduce the sensitivity. // proxy.handler.dispatchToElement(event.target, 'mousemove', event); // } // if (event.scale !== 1) { // event.pinchX = event.offsetX; // event.pinchY = event.offsetY; // event.pinchScale = event.scale; // proxy.handler.dispatchToElement(event.target, 'pinch', event); // } // } /** * Prevent mouse event from being dispatched after Touch Events action * @see <https://github.com/deltakosh/handjs/blob/master/src/hand.base.js> * 1. Mobile browsers dispatch mouse events 300ms after touchend. * 2. Chrome for Android dispatch mousedown for long-touch about 650ms * Result: Blocking Mouse Events for 700ms. */ function setTouchTimer(instance) { instance._touching = true; clearTimeout(instance._touchTimer); instance._touchTimer = setTimeout(function () { instance._touching = false; }, 700); } var domHandlers = { /** * Mouse move handler * @inner * @param {Event} event */ mousemove: function (event) { event = normalizeEvent(this.dom, event); this.trigger('mousemove', event); }, /** * Mouse out handler * @inner * @param {Event} event */ mouseout: function (event) { event = normalizeEvent(this.dom, event); var element = event.toElement || event.relatedTarget; if (element != this.dom) { while (element && element.nodeType != 9) { // 忽略包含在root中的dom引起的mouseOut if (element === this.dom) { return; } element = element.parentNode; } } this.trigger('mouseout', event); }, /** * Touch开始响应函数 * @inner * @param {Event} event */ touchstart: function (event) { // Default mouse behaviour should not be disabled here. // For example, page may needs to be slided. event = normalizeEvent(this.dom, event); // Mark touch, which is useful in distinguish touch and // mouse event in upper applicatoin. event.zrByTouch = true; this._lastTouchMoment = new Date(); processGesture(this, event, 'start'); // In touch device, trigger `mousemove`(`mouseover`) should // be triggered, and must before `mousedown` triggered. domHandlers.mousemove.call(this, event); domHandlers.mousedown.call(this, event); setTouchTimer(this); }, /** * Touch移动响应函数 * @inner * @param {Event} event */ touchmove: function (event) { event = normalizeEvent(this.dom, event); // Mark touch, which is useful in distinguish touch and // mouse event in upper applicatoin. event.zrByTouch = true; processGesture(this, event, 'change'); // Mouse move should always be triggered no matter whether // there is gestrue event, because mouse move and pinch may // be used at the same time. domHandlers.mousemove.call(this, event); setTouchTimer(this); }, /** * Touch结束响应函数 * @inner * @param {Event} event */ touchend: function (event) { event = normalizeEvent(this.dom, event); // Mark touch, which is useful in distinguish touch and // mouse event in upper applicatoin. event.zrByTouch = true; processGesture(this, event, 'end'); domHandlers.mouseup.call(this, event); // Do not trigger `mouseout` here, in spite of `mousemove`(`mouseover`) is // triggered in `touchstart`. This seems to be illogical, but by this mechanism, // we can conveniently implement "hover style" in both PC and touch device just // by listening to `mouseover` to add "hover style" and listening to `mouseout` // to remove "hover style" on an element, without any additional code for // compatibility. (`mouseout` will not be triggered in `touchend`, so "hover // style" will remain for user view) // click event should always be triggered no matter whether // there is gestrue event. System click can not be prevented. if (+new Date() - this._lastTouchMoment < TOUCH_CLICK_DELAY) { domHandlers.click.call(this, event); } setTouchTimer(this); }, pointerdown: function (event) { domHandlers.mousedown.call(this, event); // if (useMSGuesture(this, event)) { // this._msGesture.addPointer(event.pointerId); // } }, pointermove: function (event) { // FIXME // pointermove is so sensitive that it always triggered when // tap(click) on touch screen, which affect some judgement in // upper application. So, we dont support mousemove on MS touch // device yet. if (!isPointerFromTouch(event)) { domHandlers.mousemove.call(this, event); } }, pointerup: function (event) { domHandlers.mouseup.call(this, event); }, pointerout: function (event) { // pointerout will be triggered when tap on touch screen // (IE11+/Edge on MS Surface) after click event triggered, // which is inconsistent with the mousout behavior we defined // in touchend. So we unify them. // (check domHandlers.touchend for detailed explanation) if (!isPointerFromTouch(event)) { domHandlers.mouseout.call(this, event); } } }; function isPointerFromTouch(event) { var pointerType = event.pointerType; return pointerType === 'pen' || pointerType === 'touch'; } // function useMSGuesture(handlerProxy, event) { // return isPointerFromTouch(event) && !!handlerProxy._msGesture; // } // Common handlers each$1(['click', 'mousedown', 'mouseup', 'mousewheel', 'dblclick', 'contextmenu'], function (name) { domHandlers[name] = function (event) { event = normalizeEvent(this.dom, event); this.trigger(name, event); }; }); /** * 为控制类实例初始化dom 事件处理函数 * * @inner * @param {module:zrender/Handler} instance 控制类实例 */ function initDomHandler(instance) { each$1(touchHandlerNames, function (name) { instance._handlers[name] = bind(domHandlers[name], instance); }); each$1(pointerHandlerNames, function (name) { instance._handlers[name] = bind(domHandlers[name], instance); }); each$1(mouseHandlerNames, function (name) { instance._handlers[name] = makeMouseHandler(domHandlers[name], instance); }); function makeMouseHandler(fn, instance) { return function () { if (instance._touching) { return; } return fn.apply(instance, arguments); }; } } function HandlerDomProxy(dom) { Eventful.call(this); this.dom = dom; /** * @private * @type {boolean} */ this._touching = false; /** * @private * @type {number} */ this._touchTimer; /** * @private * @type {module:zrender/core/GestureMgr} */ this._gestureMgr = new GestureMgr(); this._handlers = {}; initDomHandler(this); if (env$1.pointerEventsSupported) { // Only IE11+/Edge // 1. On devices that both enable touch and mouse (e.g., MS Surface and lenovo X240), // IE11+/Edge do not trigger touch event, but trigger pointer event and mouse event // at the same time. // 2. On MS Surface, it probablely only trigger mousedown but no mouseup when tap on // screen, which do not occurs in pointer event. // So we use pointer event to both detect touch gesture and mouse behavior. mountHandlers(pointerHandlerNames, this); // FIXME // Note: MS Gesture require CSS touch-action set. But touch-action is not reliable, // which does not prevent defuault behavior occasionally (which may cause view port // zoomed in but use can not zoom it back). And event.preventDefault() does not work. // So we have to not to use MSGesture and not to support touchmove and pinch on MS // touch screen. And we only support click behavior on MS touch screen now. // MS Gesture Event is only supported on IE11+/Edge and on Windows 8+. // We dont support touch on IE on win7. // See <https://msdn.microsoft.com/en-us/library/dn433243(v=vs.85).aspx> // if (typeof MSGesture === 'function') { // (this._msGesture = new MSGesture()).target = dom; // jshint ignore:line // dom.addEventListener('MSGestureChange', onMSGestureChange); // } } else { if (env$1.touchEventsSupported) { mountHandlers(touchHandlerNames, this); // Handler of 'mouseout' event is needed in touch mode, which will be mounted below. // addEventListener(root, 'mouseout', this._mouseoutHandler); } // 1. Considering some devices that both enable touch and mouse event (like on MS Surface // and lenovo X240, @see #2350), we make mouse event be always listened, otherwise // mouse event can not be handle in those devices. // 2. On MS Surface, Chrome will trigger both touch event and mouse event. How to prevent // mouseevent after touch event triggered, see `setTouchTimer`. mountHandlers(mouseHandlerNames, this); } function mountHandlers(handlerNames, instance) { each$1(handlerNames, function (name) { addEventListener(dom, eventNameFix(name), instance._handlers[name]); }, instance); } } var handlerDomProxyProto = HandlerDomProxy.prototype; handlerDomProxyProto.dispose = function () { var handlerNames = mouseHandlerNames.concat(touchHandlerNames); for (var i = 0; i < handlerNames.length; i++) { var name = handlerNames[i]; removeEventListener(this.dom, eventNameFix(name), this._handlers[name]); } }; handlerDomProxyProto.setCursor = function (cursorStyle) { this.dom.style.cursor = cursorStyle || 'default'; }; mixin(HandlerDomProxy, Eventful); /*! * ZRender, a high performance 2d drawing library. * * Copyright (c) 2013, Baidu Inc. * All rights reserved. * * LICENSE * https://github.com/ecomfe/zrender/blob/master/LICENSE.txt */ var useVML = !env$1.canvasSupported; var painterCtors = { canvas: Painter }; /** * @type {string} */ var version$1 = '3.7.0'; /** * Initializing a zrender instance * @param {HTMLElement} dom * @param {Object} opts * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg' * @param {number} [opts.devicePixelRatio] * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined) * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined) * @return {module:zrender/ZRender} */ function init$1(dom, opts) { var zr = new ZRender(guid(), dom, opts); return zr; } /** * Dispose zrender instance * @param {module:zrender/ZRender} zr */ /** * Get zrender instance by id * @param {string} id zrender instance id * @return {module:zrender/ZRender} */ /** * @module zrender/ZRender */ /** * @constructor * @alias module:zrender/ZRender * @param {string} id * @param {HTMLElement} dom * @param {Object} opts * @param {string} [opts.renderer='canvas'] 'canvas' or 'svg' * @param {number} [opts.devicePixelRatio] * @param {number} [opts.width] Can be 'auto' (the same as null/undefined) * @param {number} [opts.height] Can be 'auto' (the same as null/undefined) */ var ZRender = function (id, dom, opts) { opts = opts || {}; /** * @type {HTMLDomElement} */ this.dom = dom; /** * @type {string} */ this.id = id; var self = this; var storage = new Storage(); var rendererType = opts.renderer; // TODO WebGL if (useVML) { if (!painterCtors.vml) { throw new Error('You need to require \'zrender/vml/vml\' to support IE8'); } rendererType = 'vml'; } else if (!rendererType || !painterCtors[rendererType]) { rendererType = 'canvas'; } var painter = new painterCtors[rendererType](dom, storage, opts); this.storage = storage; this.painter = painter; var handerProxy = !env$1.node ? new HandlerDomProxy(painter.getViewportRoot()) : null; this.handler = new Handler(storage, painter, handerProxy, painter.root); /** * @type {module:zrender/animation/Animation} */ this.animation = new Animation({ stage: { update: bind(this.flush, this) } }); this.animation.start(); /** * @type {boolean} * @private */ this._needsRefresh; // 修改 storage.delFromStorage, 每次删除元素之前删除动画 // FIXME 有点ugly var oldDelFromStorage = storage.delFromStorage; var oldAddToStorage = storage.addToStorage; storage.delFromStorage = function (el) { oldDelFromStorage.call(storage, el); el && el.removeSelfFromZr(self); }; storage.addToStorage = function (el) { oldAddToStorage.call(storage, el); el.addSelfToZr(self); }; }; ZRender.prototype = { constructor: ZRender, /** * 获取实例唯一标识 * @return {string} */ getId: function () { return this.id; }, /** * 添加元素 * @param {module:zrender/Element} el */ add: function (el) { this.storage.addRoot(el); this._needsRefresh = true; }, /** * 删除元素 * @param {module:zrender/Element} el */ remove: function (el) { this.storage.delRoot(el); this._needsRefresh = true; }, /** * Change configuration of layer * @param {string} zLevel * @param {Object} config * @param {string} [config.clearColor=0] Clear color * @param {string} [config.motionBlur=false] If enable motion blur * @param {number} [config.lastFrameAlpha=0.7] Motion blur factor. Larger value cause longer trailer */ configLayer: function (zLevel, config) { this.painter.configLayer(zLevel, config); this._needsRefresh = true; }, /** * Repaint the canvas immediately */ refreshImmediately: function () { // var start = new Date(); // Clear needsRefresh ahead to avoid something wrong happens in refresh // Or it will cause zrender refreshes again and again. this._needsRefresh = false; this.painter.refresh(); /** * Avoid trigger zr.refresh in Element#beforeUpdate hook */ this._needsRefresh = false; // var end = new Date(); // var log = document.getElementById('log'); // if (log) { // log.innerHTML = log.innerHTML + '<br>' + (end - start); // } }, /** * Mark and repaint the canvas in the next frame of browser */ refresh: function() { this._needsRefresh = true; }, /** * Perform all refresh */ flush: function () { if (this._needsRefresh) { this.refreshImmediately(); } if (this._needsRefreshHover) { this.refreshHoverImmediately(); } }, /** * Add element to hover layer * @param {module:zrender/Element} el * @param {Object} style */ addHover: function (el, style) { if (this.painter.addHover) { this.painter.addHover(el, style); this.refreshHover(); } }, /** * Add element from hover layer * @param {module:zrender/Element} el */ removeHover: function (el) { if (this.painter.removeHover) { this.painter.removeHover(el); this.refreshHover(); } }, /** * Clear all hover elements in hover layer * @param {module:zrender/Element} el */ clearHover: function () { if (this.painter.clearHover) { this.painter.clearHover(); this.refreshHover(); } }, /** * Refresh hover in next frame */ refreshHover: function () { this._needsRefreshHover = true; }, /** * Refresh hover immediately */ refreshHoverImmediately: function () { this._needsRefreshHover = false; this.painter.refreshHover && this.painter.refreshHover(); }, /** * Resize the canvas. * Should be invoked when container size is changed * @param {Object} [opts] * @param {number|string} [opts.width] Can be 'auto' (the same as null/undefined) * @param {number|string} [opts.height] Can be 'auto' (the same as null/undefined) */ resize: function(opts) { opts = opts || {}; this.painter.resize(opts.width, opts.height); this.handler.resize(); }, /** * Stop and clear all animation immediately */ clearAnimation: function () { this.animation.clear(); }, /** * Get container width */ getWidth: function() { return this.painter.getWidth(); }, /** * Get container height */ getHeight: function() { return this.painter.getHeight(); }, /** * Export the canvas as Base64 URL * @param {string} type * @param {string} [backgroundColor='#fff'] * @return {string} Base64 URL */ // toDataURL: function(type, backgroundColor) { // return this.painter.getRenderedCanvas({ // backgroundColor: backgroundColor // }).toDataURL(type); // }, /** * Converting a path to image. * It has much better performance of drawing image rather than drawing a vector path. * @param {module:zrender/graphic/Path} e * @param {number} width * @param {number} height */ pathToImage: function(e, dpr) { return this.painter.pathToImage(e, dpr); }, /** * Set default cursor * @param {string} [cursorStyle='default'] 例如 crosshair */ setCursorStyle: function (cursorStyle) { this.handler.setCursorStyle(cursorStyle); }, /** * Find hovered element * @param {number} x * @param {number} y * @return {Object} {target, topTarget} */ findHover: function (x, y) { return this.handler.findHover(x, y); }, /** * Bind event * * @param {string} eventName Event name * @param {Function} eventHandler Handler function * @param {Object} [context] Context object */ on: function(eventName, eventHandler, context) { this.handler.on(eventName, eventHandler, context); }, /** * Unbind event * @param {string} eventName Event name * @param {Function} [eventHandler] Handler function */ off: function(eventName, eventHandler) { this.handler.off(eventName, eventHandler); }, /** * Trigger event manually * * @param {string} eventName Event name * @param {event=} event Event object */ trigger: function (eventName, event) { this.handler.trigger(eventName, event); }, /** * Clear all objects and the canvas. */ clear: function () { this.storage.delRoot(); this.painter.clear(); }, /** * Dispose self. */ dispose: function () { this.animation.stop(); this.clear(); this.storage.dispose(); this.painter.dispose(); this.handler.dispose(); this.animation = this.storage = this.painter = this.handler = null; } }; var RADIAN_EPSILON = 1e-4; function _trim(str) { return str.replace(/^\s+/, '').replace(/\s+$/, ''); } /** * Linear mapping a value from domain to range * @memberOf module:echarts/util/number * @param {(number|Array.<number>)} val * @param {Array.<number>} domain Domain extent domain[0] can be bigger than domain[1] * @param {Array.<number>} range Range extent range[0] can be bigger than range[1] * @param {boolean} clamp * @return {(number|Array.<number>} */ function linearMap(val, domain, range, clamp) { var subDomain = domain[1] - domain[0]; var subRange = range[1] - range[0]; if (subDomain === 0) { return subRange === 0 ? range[0] : (range[0] + range[1]) / 2; } // Avoid accuracy problem in edge, such as // 146.39 - 62.83 === 83.55999999999999. // See echarts/test/ut/spec/util/number.js#linearMap#accuracyError // It is a little verbose for efficiency considering this method // is a hotspot. if (clamp) { if (subDomain > 0) { if (val <= domain[0]) { return range[0]; } else if (val >= domain[1]) { return range[1]; } } else { if (val >= domain[0]) { return range[0]; } else if (val <= domain[1]) { return range[1]; } } } else { if (val === domain[0]) { return range[0]; } if (val === domain[1]) { return range[1]; } } return (val - domain[0]) / subDomain * subRange + range[0]; } /** * Convert a percent string to absolute number. * Returns NaN if percent is not a valid string or number * @memberOf module:echarts/util/number * @param {string|number} percent * @param {number} all * @return {number} */ function parsePercent$1(percent, all) { switch (percent) { case 'center': case 'middle': percent = '50%'; break; case 'left': case 'top': percent = '0%'; break; case 'right': case 'bottom': percent = '100%'; break; } if (typeof percent === 'string') { if (_trim(percent).match(/%$/)) { return parseFloat(percent) / 100 * all; } return parseFloat(percent); } return percent == null ? NaN : +percent; } /** * (1) Fix rounding error of float numbers. * (2) Support return string to avoid scientific notation like '3.5e-7'. * * @param {number} x * @param {number} [precision] * @param {boolean} [returnStr] * @return {number|string} */ function round(x, precision, returnStr) { if (precision == null) { precision = 10; } // Avoid range error precision = Math.min(Math.max(0, precision), 20); x = (+x).toFixed(precision); return returnStr ? x : +x; } /** * Get precision * @param {number} val */ /** * @param {string|number} val * @return {number} */ function getPrecisionSafe(val) { var str = val.toString(); // Consider scientific notation: '3.4e-12' '3.4e+12' var eIndex = str.indexOf('e'); if (eIndex > 0) { var precision = +str.slice(eIndex + 1); return precision < 0 ? -precision : 0; } else { var dotIndex = str.indexOf('.'); return dotIndex < 0 ? 0 : str.length - 1 - dotIndex; } } /** * Minimal dicernible data precisioin according to a single pixel. * * @param {Array.<number>} dataExtent * @param {Array.<number>} pixelExtent * @return {number} precision */ function getPixelPrecision(dataExtent, pixelExtent) { var log = Math.log; var LN10 = Math.LN10; var dataQuantity = Math.floor(log(dataExtent[1] - dataExtent[0]) / LN10); var sizeQuantity = Math.round(log(Math.abs(pixelExtent[1] - pixelExtent[0])) / LN10); // toFixed() digits argument must be between 0 and 20. var precision = Math.min(Math.max(-dataQuantity + sizeQuantity, 0), 20); return !isFinite(precision) ? 20 : precision; } /** * Get a data of given precision, assuring the sum of percentages * in valueList is 1. * The largest remainer method is used. * https://en.wikipedia.org/wiki/Largest_remainder_method * * @param {Array.<number>} valueList a list of all data * @param {number} idx index of the data to be processed in valueList * @param {number} precision integer number showing digits of precision * @return {number} percent ranging from 0 to 100 */ function getPercentWithPrecision(valueList, idx, precision) { if (!valueList[idx]) { return 0; } var sum = reduce(valueList, function (acc, val) { return acc + (isNaN(val) ? 0 : val); }, 0); if (sum === 0) { return 0; } var digits = Math.pow(10, precision); var votesPerQuota = map(valueList, function (val) { return (isNaN(val) ? 0 : val) / sum * digits * 100; }); var targetSeats = digits * 100; var seats = map(votesPerQuota, function (votes) { // Assign automatic seats. return Math.floor(votes); }); var currentSum = reduce(seats, function (acc, val) { return acc + val; }, 0); var remainder = map(votesPerQuota, function (votes, idx) { return votes - seats[idx]; }); // Has remainding votes. while (currentSum < targetSeats) { // Find next largest remainder. var max = Number.NEGATIVE_INFINITY; var maxId = null; for (var i = 0, len = remainder.length; i < len; ++i) { if (remainder[i] > max) { max = remainder[i]; maxId = i; } } // Add a vote to max remainder. ++seats[maxId]; remainder[maxId] = 0; ++currentSum; } return seats[idx] / digits; } // Number.MAX_SAFE_INTEGER, ie do not support. /** * To 0 - 2 * PI, considering negative radian. * @param {number} radian * @return {number} */ function remRadian(radian) { var pi2 = Math.PI * 2; return (radian % pi2 + pi2) % pi2; } /** * @param {type} radian * @return {boolean} */ function isRadianAroundZero(val) { return val > -RADIAN_EPSILON && val < RADIAN_EPSILON; } var TIME_REG = /^(?:(\d{4})(?:[-\/](\d{1,2})(?:[-\/](\d{1,2})(?:[T ](\d{1,2})(?::(\d\d)(?::(\d\d)(?:[.,](\d+))?)?)?(Z|[\+\-]\d\d:?\d\d)?)?)?)?)?$/; // jshint ignore:line /** * @param {string|Date|number} value These values can be accepted: * + An instance of Date, represent a time in its own time zone. * + Or string in a subset of ISO 8601, only including: * + only year, month, date: '2012-03', '2012-03-01', '2012-03-01 05', '2012-03-01 05:06', * + separated with T or space: '2012-03-01T12:22:33.123', '2012-03-01 12:22:33.123', * + time zone: '2012-03-01T12:22:33Z', '2012-03-01T12:22:33+8000', '2012-03-01T12:22:33-05:00', * all of which will be treated as local time if time zone is not specified * (see <https://momentjs.com/>). * + Or other string format, including (all of which will be treated as loacal time): * '2012', '2012-3-1', '2012/3/1', '2012/03/01', * '2009/6/12 2:00', '2009/6/12 2:05:08', '2009/6/12 2:05:08.123' * + a timestamp, which represent a time in UTC. * @return {Date} date */ function parseDate(value) { if (value instanceof Date) { return value; } else if (typeof value === 'string') { // Different browsers parse date in different way, so we parse it manually. // Some other issues: // new Date('1970-01-01') is UTC, // new Date('1970/01/01') and new Date('1970-1-01') is local. // See issue #3623 var match = TIME_REG.exec(value); if (!match) { // return Invalid Date. return new Date(NaN); } // Use local time when no timezone offset specifed. if (!match[8]) { // match[n] can only be string or undefined. // But take care of '12' + 1 => '121'. return new Date( +match[1], +(match[2] || 1) - 1, +match[3] || 1, +match[4] || 0, +(match[5] || 0), +match[6] || 0, +match[7] || 0 ); } // Timezoneoffset of Javascript Date has considered DST (Daylight Saving Time, // https://tc39.github.io/ecma262/#sec-daylight-saving-time-adjustment). // For example, system timezone is set as "Time Zone: America/Toronto", // then these code will get different result: // `new Date(1478411999999).getTimezoneOffset(); // get 240` // `new Date(1478412000000).getTimezoneOffset(); // get 300` // So we should not use `new Date`, but use `Date.UTC`. else { var hour = +match[4] || 0; if (match[8].toUpperCase() !== 'Z') { hour -= match[8].slice(0, 3); } return new Date(Date.UTC( +match[1], +(match[2] || 1) - 1, +match[3] || 1, hour, +(match[5] || 0), +match[6] || 0, +match[7] || 0 )); } } else if (value == null) { return new Date(NaN); } return new Date(Math.round(value)); } /** * Quantity of a number. e.g. 0.1, 1, 10, 100 * * @param {number} val * @return {number} */ function quantity(val) { return Math.pow(10, quantityExponent(val)); } function quantityExponent(val) { return Math.floor(Math.log(val) / Math.LN10); } /** * find a “nice” number approximately equal to x. Round the number if round = true, * take ceiling if round = false. The primary observation is that the “nicest” * numbers in decimal are 1, 2, and 5, and all power-of-ten multiples of these numbers. * * See "Nice Numbers for Graph Labels" of Graphic Gems. * * @param {number} val Non-negative value. * @param {boolean} round * @return {number} */ function nice(val, round) { var exponent = quantityExponent(val); var exp10 = Math.pow(10, exponent); var f = val / exp10; // 1 <= f < 10 var nf; if (round) { if (f < 1.5) { nf = 1; } else if (f < 2.5) { nf = 2; } else if (f < 4) { nf = 3; } else if (f < 7) { nf = 5; } else { nf = 10; } } else { if (f < 1) { nf = 1; } else if (f < 2) { nf = 2; } else if (f < 3) { nf = 3; } else if (f < 5) { nf = 5; } else { nf = 10; } } val = nf * exp10; // Fix 3 * 0.1 === 0.30000000000000004 issue (see IEEE 754). // 20 is the uppper bound of toFixed. return exponent >= -20 ? +val.toFixed(exponent < 0 ? -exponent : 0) : val; } /** * Order intervals asc, and split them when overlap. * expect(numberUtil.reformIntervals([ * {interval: [18, 62], close: [1, 1]}, * {interval: [-Infinity, -70], close: [0, 0]}, * {interval: [-70, -26], close: [1, 1]}, * {interval: [-26, 18], close: [1, 1]}, * {interval: [62, 150], close: [1, 1]}, * {interval: [106, 150], close: [1, 1]}, * {interval: [150, Infinity], close: [0, 0]} * ])).toEqual([ * {interval: [-Infinity, -70], close: [0, 0]}, * {interval: [-70, -26], close: [1, 1]}, * {interval: [-26, 18], close: [0, 1]}, * {interval: [18, 62], close: [0, 1]}, * {interval: [62, 150], close: [0, 1]}, * {interval: [150, Infinity], close: [0, 0]} * ]); * @param {Array.<Object>} list, where `close` mean open or close * of the interval, and Infinity can be used. * @return {Array.<Object>} The origin list, which has been reformed. */ /** * parseFloat NaNs numeric-cast false positives (null|true|false|"") * ...but misinterprets leading-number strings, particularly hex literals ("0x...") * subtraction forces infinities to NaN * * @param {*} v * @return {boolean} */ /** * 每三位默认加,格式化 * @param {string|number} x * @return {string} */ function addCommas(x) { if (isNaN(x)) { return '-'; } x = (x + '').split('.'); return x[0].replace(/(\d{1,3})(?=(?:\d{3})+(?!\d))/g,'$1,') + (x.length > 1 ? ('.' + x[1]) : ''); } /** * @param {string} str * @param {boolean} [upperCaseFirst=false] * @return {string} str */ var normalizeCssArray$1 = normalizeCssArray; function encodeHTML(source) { return String(source) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/'/g, '&#39;'); } var TPL_VAR_ALIAS = ['a', 'b', 'c', 'd', 'e', 'f', 'g']; var wrapVar = function (varName, seriesIdx) { return '{' + varName + (seriesIdx == null ? '' : seriesIdx) + '}'; }; /** * Template formatter * @param {string} tpl * @param {Array.<Object>|Object} paramsList * @param {boolean} [encode=false] * @return {string} */ function formatTpl(tpl, paramsList, encode) { if (!isArray(paramsList)) { paramsList = [paramsList]; } var seriesLen = paramsList.length; if (!seriesLen) { return ''; } var $vars = paramsList[0].$vars || []; for (var i = 0; i < $vars.length; i++) { var alias = TPL_VAR_ALIAS[i]; var val = wrapVar(alias, 0); tpl = tpl.replace(wrapVar(alias), encode ? encodeHTML(val) : val); } for (var seriesIdx = 0; seriesIdx < seriesLen; seriesIdx++) { for (var k = 0; k < $vars.length; k++) { var val = paramsList[seriesIdx][$vars[k]]; tpl = tpl.replace( wrapVar(TPL_VAR_ALIAS[k], seriesIdx), encode ? encodeHTML(val) : val ); } } return tpl; } /** * simple Template formatter * * @param {string} tpl * @param {Object} param * @param {boolean} [encode=false] * @return {string} */ /** * @param {string} color * @param {string} [extraCssText] * @return {string} */ function getTooltipMarker(color, extraCssText) { return color ? '<span style="display:inline-block;margin-right:5px;' + 'border-radius:10px;width:9px;height:9px;background-color:' + encodeHTML(color) + ';' + (extraCssText || '') + '"></span>' : ''; } /** * @param {string} str * @return {string} * @inner */ var s2d = function (str) { return str < 10 ? ('0' + str) : str; }; /** * ISO Date format * @param {string} tpl * @param {number} value * @param {boolean} [isUTC=false] Default in local time. * see `module:echarts/scale/Time` * and `module:echarts/util/number#parseDate`. * @inner */ function formatTime(tpl, value, isUTC) { if (tpl === 'week' || tpl === 'month' || tpl === 'quarter' || tpl === 'half-year' || tpl === 'year' ) { tpl = 'MM-dd\nyyyy'; } var date = parseDate(value); var utc = isUTC ? 'UTC' : ''; var y = date['get' + utc + 'FullYear'](); var M = date['get' + utc + 'Month']() + 1; var d = date['get' + utc + 'Date'](); var h = date['get' + utc + 'Hours'](); var m = date['get' + utc + 'Minutes'](); var s = date['get' + utc + 'Seconds'](); tpl = tpl.replace('MM', s2d(M)) .replace('M', M) .replace('yyyy', y) .replace('yy', y % 100) .replace('dd', s2d(d)) .replace('d', d) .replace('hh', s2d(h)) .replace('h', h) .replace('mm', s2d(m)) .replace('m', m) .replace('ss', s2d(s)) .replace('s', s); return tpl; } /** * Capital first * @param {string} str * @return {string} */ var truncateText$1 = truncateText; var TYPE_DELIMITER = '.'; var IS_CONTAINER = '___EC__COMPONENT__CONTAINER___'; var MEMBER_PRIFIX = '\0ec_\0'; /** * Hide private class member. * The same behavior as `host[name] = value;` (can be right-value) * @public */ function set$1(host, name, value) { return (host[MEMBER_PRIFIX + name] = value); } /** * Hide private class member. * The same behavior as `host[name];` * @public */ function get(host, name) { return host[MEMBER_PRIFIX + name]; } /** * For hidden private class member. * The same behavior as `host.hasOwnProperty(name);` * @public */ function hasOwn(host, name) { return host.hasOwnProperty(MEMBER_PRIFIX + name); } /** * Notice, parseClassType('') should returns {main: '', sub: ''} * @public */ function parseClassType$1(componentType) { var ret = {main: '', sub: ''}; if (componentType) { componentType = componentType.split(TYPE_DELIMITER); ret.main = componentType[0] || ''; ret.sub = componentType[1] || ''; } return ret; } /** * @public */ function checkClassType(componentType) { assert( /^[a-zA-Z0-9_]+([.][a-zA-Z0-9_]+)?$/.test(componentType), 'componentType "' + componentType + '" illegal' ); } /** * @public */ function enableClassExtend(RootClass, mandatoryMethods) { RootClass.$constructor = RootClass; RootClass.extend = function (proto) { if (__DEV__) { each$1(mandatoryMethods, function (method) { if (!proto[method]) { console.warn( 'Method `' + method + '` should be implemented' + (proto.type ? ' in ' + proto.type : '') + '.' ); } }); } var superClass = this; var ExtendedClass = function () { if (!proto.$constructor) { superClass.apply(this, arguments); } else { proto.$constructor.apply(this, arguments); } }; extend(ExtendedClass.prototype, proto); ExtendedClass.extend = this.extend; ExtendedClass.superCall = superCall; ExtendedClass.superApply = superApply; inherits(ExtendedClass, this); ExtendedClass.superClass = superClass; return ExtendedClass; }; } // superCall should have class info, which can not be fetch from 'this'. // Consider this case: // class A has method f, // class B inherits class A, overrides method f, f call superApply('f'), // class C inherits class B, do not overrides method f, // then when method of class C is called, dead loop occured. function superCall(context, methodName) { var args = slice(arguments, 2); return this.superClass.prototype[methodName].apply(context, args); } function superApply(context, methodName, args) { return this.superClass.prototype[methodName].apply(context, args); } /** * @param {Object} entity * @param {Object} options * @param {boolean} [options.registerWhenExtend] * @public */ function enableClassManagement(entity, options) { options = options || {}; /** * Component model classes * key: componentType, * value: * componentClass, when componentType is 'xxx' * or Object.<subKey, componentClass>, when componentType is 'xxx.yy' * @type {Object} */ var storage = {}; entity.registerClass = function (Clazz, componentType) { if (componentType) { checkClassType(componentType); componentType = parseClassType$1(componentType); if (!componentType.sub) { if (__DEV__) { if (storage[componentType.main]) { console.warn(componentType.main + ' exists.'); } } storage[componentType.main] = Clazz; } else if (componentType.sub !== IS_CONTAINER) { var container = makeContainer(componentType); container[componentType.sub] = Clazz; } } return Clazz; }; entity.getClass = function (componentMainType, subType, throwWhenNotFound) { var Clazz = storage[componentMainType]; if (Clazz && Clazz[IS_CONTAINER]) { Clazz = subType ? Clazz[subType] : null; } if (throwWhenNotFound && !Clazz) { throw new Error( !subType ? componentMainType + '.' + 'type should be specified.' : 'Component ' + componentMainType + '.' + (subType || '') + ' not exists. Load it first.' ); } return Clazz; }; entity.getClassesByMainType = function (componentType) { componentType = parseClassType$1(componentType); var result = []; var obj = storage[componentType.main]; if (obj && obj[IS_CONTAINER]) { each$1(obj, function (o, type) { type !== IS_CONTAINER && result.push(o); }); } else { result.push(obj); } return result; }; entity.hasClass = function (componentType) { // Just consider componentType.main. componentType = parseClassType$1(componentType); return !!storage[componentType.main]; }; /** * @return {Array.<string>} Like ['aa', 'bb'], but can not be ['aa.xx'] */ entity.getAllClassMainTypes = function () { var types = []; each$1(storage, function (obj, type) { types.push(type); }); return types; }; /** * If a main type is container and has sub types * @param {string} mainType * @return {boolean} */ entity.hasSubTypes = function (componentType) { componentType = parseClassType$1(componentType); var obj = storage[componentType.main]; return obj && obj[IS_CONTAINER]; }; entity.parseClassType = parseClassType$1; function makeContainer(componentType) { var container = storage[componentType.main]; if (!container || !container[IS_CONTAINER]) { container = storage[componentType.main] = {}; container[IS_CONTAINER] = true; } return container; } if (options.registerWhenExtend) { var originalExtend = entity.extend; if (originalExtend) { entity.extend = function (proto) { var ExtendedClass = originalExtend.call(this, proto); return entity.registerClass(ExtendedClass, proto.type); }; } } return entity; } /** * @param {string|Array.<string>} properties */ // TODO Parse shadow style // TODO Only shallow path support var makeStyleMapper = function (properties) { // Normalize for (var i = 0; i < properties.length; i++) { if (!properties[i][1]) { properties[i][1] = properties[i][0]; } } return function (model, excludes, includes) { var style = {}; for (var i = 0; i < properties.length; i++) { var propName = properties[i][1]; if ((excludes && indexOf(excludes, propName) >= 0) || (includes && indexOf(includes, propName) < 0) ) { continue; } var val = model.getShallow(propName); if (val != null) { style[properties[i][0]] = val; } } return style; }; }; var getLineStyle = makeStyleMapper( [ ['lineWidth', 'width'], ['stroke', 'color'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] ] ); var lineStyleMixin = { getLineStyle: function (excludes) { var style = getLineStyle(this, excludes); var lineDash = this.getLineDash(style.lineWidth); lineDash && (style.lineDash = lineDash); return style; }, getLineDash: function (lineWidth) { if (lineWidth == null) { lineWidth = 1; } var lineType = this.get('type'); var dotSize = Math.max(lineWidth, 2); var dashSize = lineWidth * 4; return (lineType === 'solid' || lineType == null) ? null : (lineType === 'dashed' ? [dashSize, dashSize] : [dotSize, dotSize]); } }; var getAreaStyle = makeStyleMapper( [ ['fill', 'color'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['opacity'], ['shadowColor'] ] ); var areaStyleMixin = { getAreaStyle: function (excludes, includes) { return getAreaStyle(this, excludes, includes); } }; /** * 曲线辅助模块 * @module zrender/core/curve * @author pissang(https://www.github.com/pissang) */ var mathPow = Math.pow; var mathSqrt$2 = Math.sqrt; var EPSILON$1 = 1e-8; var EPSILON_NUMERIC = 1e-4; var THREE_SQRT = mathSqrt$2(3); var ONE_THIRD = 1 / 3; // 临时变量 var _v0 = create(); var _v1 = create(); var _v2 = create(); function isAroundZero(val) { return val > -EPSILON$1 && val < EPSILON$1; } function isNotAroundZero$1(val) { return val > EPSILON$1 || val < -EPSILON$1; } /** * 计算三次贝塞尔值 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} t * @return {number} */ function cubicAt(p0, p1, p2, p3, t) { var onet = 1 - t; return onet * onet * (onet * p0 + 3 * t * p1) + t * t * (t * p3 + 3 * onet * p2); } /** * 计算三次贝塞尔导数值 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} t * @return {number} */ function cubicDerivativeAt(p0, p1, p2, p3, t) { var onet = 1 - t; return 3 * ( ((p1 - p0) * onet + 2 * (p2 - p1) * t) * onet + (p3 - p2) * t * t ); } /** * 计算三次贝塞尔方程根,使用盛金公式 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} val * @param {Array.<number>} roots * @return {number} 有效根数目 */ function cubicRootAt(p0, p1, p2, p3, val, roots) { // Evaluate roots of cubic functions var a = p3 + 3 * (p1 - p2) - p0; var b = 3 * (p2 - p1 * 2 + p0); var c = 3 * (p1 - p0); var d = p0 - val; var A = b * b - 3 * a * c; var B = b * c - 9 * a * d; var C = c * c - 3 * b * d; var n = 0; if (isAroundZero(A) && isAroundZero(B)) { if (isAroundZero(b)) { roots[0] = 0; } else { var t1 = -c / b; //t1, t2, t3, b is not zero if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } } else { var disc = B * B - 4 * A * C; if (isAroundZero(disc)) { var K = B / A; var t1 = -b / a + K; // t1, a is not zero var t2 = -K / 2; // t2, t3 if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } } else if (disc > 0) { var discSqrt = mathSqrt$2(disc); var Y1 = A * b + 1.5 * a * (-B + discSqrt); var Y2 = A * b + 1.5 * a * (-B - discSqrt); if (Y1 < 0) { Y1 = -mathPow(-Y1, ONE_THIRD); } else { Y1 = mathPow(Y1, ONE_THIRD); } if (Y2 < 0) { Y2 = -mathPow(-Y2, ONE_THIRD); } else { Y2 = mathPow(Y2, ONE_THIRD); } var t1 = (-b - (Y1 + Y2)) / (3 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } else { var T = (2 * A * b - 3 * a * B) / (2 * mathSqrt$2(A * A * A)); var theta = Math.acos(T) / 3; var ASqrt = mathSqrt$2(A); var tmp = Math.cos(theta); var t1 = (-b - 2 * ASqrt * tmp) / (3 * a); var t2 = (-b + ASqrt * (tmp + THREE_SQRT * Math.sin(theta))) / (3 * a); var t3 = (-b + ASqrt * (tmp - THREE_SQRT * Math.sin(theta))) / (3 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } if (t3 >= 0 && t3 <= 1) { roots[n++] = t3; } } } return n; } /** * 计算三次贝塞尔方程极限值的位置 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {Array.<number>} extrema * @return {number} 有效数目 */ function cubicExtrema(p0, p1, p2, p3, extrema) { var b = 6 * p2 - 12 * p1 + 6 * p0; var a = 9 * p1 + 3 * p3 - 3 * p0 - 9 * p2; var c = 3 * p1 - 3 * p0; var n = 0; if (isAroundZero(a)) { if (isNotAroundZero$1(b)) { var t1 = -c / b; if (t1 >= 0 && t1 <=1) { extrema[n++] = t1; } } } else { var disc = b * b - 4 * a * c; if (isAroundZero(disc)) { extrema[0] = -b / (2 * a); } else if (disc > 0) { var discSqrt = mathSqrt$2(disc); var t1 = (-b + discSqrt) / (2 * a); var t2 = (-b - discSqrt) / (2 * a); if (t1 >= 0 && t1 <= 1) { extrema[n++] = t1; } if (t2 >= 0 && t2 <= 1) { extrema[n++] = t2; } } } return n; } /** * 细分三次贝塞尔曲线 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} p3 * @param {number} t * @param {Array.<number>} out */ function cubicSubdivide(p0, p1, p2, p3, t, out) { var p01 = (p1 - p0) * t + p0; var p12 = (p2 - p1) * t + p1; var p23 = (p3 - p2) * t + p2; var p012 = (p12 - p01) * t + p01; var p123 = (p23 - p12) * t + p12; var p0123 = (p123 - p012) * t + p012; // Seg0 out[0] = p0; out[1] = p01; out[2] = p012; out[3] = p0123; // Seg1 out[4] = p0123; out[5] = p123; out[6] = p23; out[7] = p3; } /** * 投射点到三次贝塞尔曲线上,返回投射距离。 * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @param {number} x * @param {number} y * @param {Array.<number>} [out] 投射点 * @return {number} */ function cubicProjectPoint( x0, y0, x1, y1, x2, y2, x3, y3, x, y, out ) { // http://pomax.github.io/bezierinfo/#projections var t; var interval = 0.005; var d = Infinity; var prev; var next; var d1; var d2; _v0[0] = x; _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值 // PENDING for (var _t = 0; _t < 1; _t += 0.05) { _v1[0] = cubicAt(x0, x1, x2, x3, _t); _v1[1] = cubicAt(y0, y1, y2, y3, _t); d1 = distSquare(_v0, _v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; // At most 32 iteration for (var i = 0; i < 32; i++) { if (interval < EPSILON_NUMERIC) { break; } prev = t - interval; next = t + interval; // t - interval _v1[0] = cubicAt(x0, x1, x2, x3, prev); _v1[1] = cubicAt(y0, y1, y2, y3, prev); d1 = distSquare(_v1, _v0); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { // t + interval _v2[0] = cubicAt(x0, x1, x2, x3, next); _v2[1] = cubicAt(y0, y1, y2, y3, next); d2 = distSquare(_v2, _v0); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } // t if (out) { out[0] = cubicAt(x0, x1, x2, x3, t); out[1] = cubicAt(y0, y1, y2, y3, t); } // console.log(interval, i); return mathSqrt$2(d); } /** * 计算二次方贝塞尔值 * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} t * @return {number} */ function quadraticAt(p0, p1, p2, t) { var onet = 1 - t; return onet * (onet * p0 + 2 * t * p1) + t * t * p2; } /** * 计算二次方贝塞尔导数值 * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} t * @return {number} */ function quadraticDerivativeAt(p0, p1, p2, t) { return 2 * ((1 - t) * (p1 - p0) + t * (p2 - p1)); } /** * 计算二次方贝塞尔方程根 * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} t * @param {Array.<number>} roots * @return {number} 有效根数目 */ function quadraticRootAt(p0, p1, p2, val, roots) { var a = p0 - 2 * p1 + p2; var b = 2 * (p1 - p0); var c = p0 - val; var n = 0; if (isAroundZero(a)) { if (isNotAroundZero$1(b)) { var t1 = -c / b; if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } } else { var disc = b * b - 4 * a * c; if (isAroundZero(disc)) { var t1 = -b / (2 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } } else if (disc > 0) { var discSqrt = mathSqrt$2(disc); var t1 = (-b + discSqrt) / (2 * a); var t2 = (-b - discSqrt) / (2 * a); if (t1 >= 0 && t1 <= 1) { roots[n++] = t1; } if (t2 >= 0 && t2 <= 1) { roots[n++] = t2; } } } return n; } /** * 计算二次贝塞尔方程极限值 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @return {number} */ function quadraticExtremum(p0, p1, p2) { var divider = p0 + p2 - 2 * p1; if (divider === 0) { // p1 is center of p0 and p2 return 0.5; } else { return (p0 - p1) / divider; } } /** * 细分二次贝塞尔曲线 * @memberOf module:zrender/core/curve * @param {number} p0 * @param {number} p1 * @param {number} p2 * @param {number} t * @param {Array.<number>} out */ function quadraticSubdivide(p0, p1, p2, t, out) { var p01 = (p1 - p0) * t + p0; var p12 = (p2 - p1) * t + p1; var p012 = (p12 - p01) * t + p01; // Seg0 out[0] = p0; out[1] = p01; out[2] = p012; // Seg1 out[3] = p012; out[4] = p12; out[5] = p2; } /** * 投射点到二次贝塞尔曲线上,返回投射距离。 * 投射点有可能会有一个或者多个,这里只返回其中距离最短的一个。 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x * @param {number} y * @param {Array.<number>} out 投射点 * @return {number} */ function quadraticProjectPoint( x0, y0, x1, y1, x2, y2, x, y, out ) { // http://pomax.github.io/bezierinfo/#projections var t; var interval = 0.005; var d = Infinity; _v0[0] = x; _v0[1] = y; // 先粗略估计一下可能的最小距离的 t 值 // PENDING for (var _t = 0; _t < 1; _t += 0.05) { _v1[0] = quadraticAt(x0, x1, x2, _t); _v1[1] = quadraticAt(y0, y1, y2, _t); var d1 = distSquare(_v0, _v1); if (d1 < d) { t = _t; d = d1; } } d = Infinity; // At most 32 iteration for (var i = 0; i < 32; i++) { if (interval < EPSILON_NUMERIC) { break; } var prev = t - interval; var next = t + interval; // t - interval _v1[0] = quadraticAt(x0, x1, x2, prev); _v1[1] = quadraticAt(y0, y1, y2, prev); var d1 = distSquare(_v1, _v0); if (prev >= 0 && d1 < d) { t = prev; d = d1; } else { // t + interval _v2[0] = quadraticAt(x0, x1, x2, next); _v2[1] = quadraticAt(y0, y1, y2, next); var d2 = distSquare(_v2, _v0); if (next <= 1 && d2 < d) { t = next; d = d2; } else { interval *= 0.5; } } } // t if (out) { out[0] = quadraticAt(x0, x1, x2, t); out[1] = quadraticAt(y0, y1, y2, t); } // console.log(interval, i); return mathSqrt$2(d); } /** * @author Yi Shen(https://github.com/pissang) */ var mathMin$3 = Math.min; var mathMax$3 = Math.max; var mathSin$2 = Math.sin; var mathCos$2 = Math.cos; var PI2 = Math.PI * 2; var start = create(); var end = create(); var extremity = create(); /** * 从顶点数组中计算出最小包围盒,写入`min`和`max`中 * @module zrender/core/bbox * @param {Array<Object>} points 顶点数组 * @param {number} min * @param {number} max */ /** * @memberOf module:zrender/core/bbox * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {Array.<number>} min * @param {Array.<number>} max */ function fromLine(x0, y0, x1, y1, min$$1, max$$1) { min$$1[0] = mathMin$3(x0, x1); min$$1[1] = mathMin$3(y0, y1); max$$1[0] = mathMax$3(x0, x1); max$$1[1] = mathMax$3(y0, y1); } var xDim = []; var yDim = []; /** * 从三阶贝塞尔曲线(p0, p1, p2, p3)中计算出最小包围盒,写入`min`和`max`中 * @memberOf module:zrender/core/bbox * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @param {Array.<number>} min * @param {Array.<number>} max */ function fromCubic( x0, y0, x1, y1, x2, y2, x3, y3, min$$1, max$$1 ) { var cubicExtrema$$1 = cubicExtrema; var cubicAt$$1 = cubicAt; var i; var n = cubicExtrema$$1(x0, x1, x2, x3, xDim); min$$1[0] = Infinity; min$$1[1] = Infinity; max$$1[0] = -Infinity; max$$1[1] = -Infinity; for (i = 0; i < n; i++) { var x = cubicAt$$1(x0, x1, x2, x3, xDim[i]); min$$1[0] = mathMin$3(x, min$$1[0]); max$$1[0] = mathMax$3(x, max$$1[0]); } n = cubicExtrema$$1(y0, y1, y2, y3, yDim); for (i = 0; i < n; i++) { var y = cubicAt$$1(y0, y1, y2, y3, yDim[i]); min$$1[1] = mathMin$3(y, min$$1[1]); max$$1[1] = mathMax$3(y, max$$1[1]); } min$$1[0] = mathMin$3(x0, min$$1[0]); max$$1[0] = mathMax$3(x0, max$$1[0]); min$$1[0] = mathMin$3(x3, min$$1[0]); max$$1[0] = mathMax$3(x3, max$$1[0]); min$$1[1] = mathMin$3(y0, min$$1[1]); max$$1[1] = mathMax$3(y0, max$$1[1]); min$$1[1] = mathMin$3(y3, min$$1[1]); max$$1[1] = mathMax$3(y3, max$$1[1]); } /** * 从二阶贝塞尔曲线(p0, p1, p2)中计算出最小包围盒,写入`min`和`max`中 * @memberOf module:zrender/core/bbox * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {Array.<number>} min * @param {Array.<number>} max */ function fromQuadratic(x0, y0, x1, y1, x2, y2, min$$1, max$$1) { var quadraticExtremum$$1 = quadraticExtremum; var quadraticAt$$1 = quadraticAt; // Find extremities, where derivative in x dim or y dim is zero var tx = mathMax$3( mathMin$3(quadraticExtremum$$1(x0, x1, x2), 1), 0 ); var ty = mathMax$3( mathMin$3(quadraticExtremum$$1(y0, y1, y2), 1), 0 ); var x = quadraticAt$$1(x0, x1, x2, tx); var y = quadraticAt$$1(y0, y1, y2, ty); min$$1[0] = mathMin$3(x0, x2, x); min$$1[1] = mathMin$3(y0, y2, y); max$$1[0] = mathMax$3(x0, x2, x); max$$1[1] = mathMax$3(y0, y2, y); } /** * 从圆弧中计算出最小包围盒,写入`min`和`max`中 * @method * @memberOf module:zrender/core/bbox * @param {number} x * @param {number} y * @param {number} rx * @param {number} ry * @param {number} startAngle * @param {number} endAngle * @param {number} anticlockwise * @param {Array.<number>} min * @param {Array.<number>} max */ function fromArc( x, y, rx, ry, startAngle, endAngle, anticlockwise, min$$1, max$$1 ) { var vec2Min = min; var vec2Max = max; var diff = Math.abs(startAngle - endAngle); if (diff % PI2 < 1e-4 && diff > 1e-4) { // Is a circle min$$1[0] = x - rx; min$$1[1] = y - ry; max$$1[0] = x + rx; max$$1[1] = y + ry; return; } start[0] = mathCos$2(startAngle) * rx + x; start[1] = mathSin$2(startAngle) * ry + y; end[0] = mathCos$2(endAngle) * rx + x; end[1] = mathSin$2(endAngle) * ry + y; vec2Min(min$$1, start, end); vec2Max(max$$1, start, end); // Thresh to [0, Math.PI * 2] startAngle = startAngle % (PI2); if (startAngle < 0) { startAngle = startAngle + PI2; } endAngle = endAngle % (PI2); if (endAngle < 0) { endAngle = endAngle + PI2; } if (startAngle > endAngle && !anticlockwise) { endAngle += PI2; } else if (startAngle < endAngle && anticlockwise) { startAngle += PI2; } if (anticlockwise) { var tmp = endAngle; endAngle = startAngle; startAngle = tmp; } // var number = 0; // var step = (anticlockwise ? -Math.PI : Math.PI) / 2; for (var angle = 0; angle < endAngle; angle += Math.PI / 2) { if (angle > startAngle) { extremity[0] = mathCos$2(angle) * rx + x; extremity[1] = mathSin$2(angle) * ry + y; vec2Min(min$$1, extremity, min$$1); vec2Max(max$$1, extremity, max$$1); } } } /** * Path 代理,可以在`buildPath`中用于替代`ctx`, 会保存每个path操作的命令到pathCommands属性中 * 可以用于 isInsidePath 判断以及获取boundingRect * * @module zrender/core/PathProxy * @author Yi Shen (http://www.github.com/pissang) */ // TODO getTotalLength, getPointAtLength var CMD = { M: 1, L: 2, C: 3, Q: 4, A: 5, Z: 6, // Rect R: 7 }; // var CMD_MEM_SIZE = { // M: 3, // L: 3, // C: 7, // Q: 5, // A: 9, // R: 5, // Z: 1 // }; var min$1 = []; var max$1 = []; var min2 = []; var max2 = []; var mathMin$2 = Math.min; var mathMax$2 = Math.max; var mathCos$1 = Math.cos; var mathSin$1 = Math.sin; var mathSqrt$1 = Math.sqrt; var mathAbs = Math.abs; var hasTypedArray = typeof Float32Array != 'undefined'; /** * @alias module:zrender/core/PathProxy * @constructor */ var PathProxy = function (notSaveData) { this._saveData = !(notSaveData || false); if (this._saveData) { /** * Path data. Stored as flat array * @type {Array.<Object>} */ this.data = []; } this._ctx = null; }; /** * 快速计算Path包围盒(并不是最小包围盒) * @return {Object} */ PathProxy.prototype = { constructor: PathProxy, _xi: 0, _yi: 0, _x0: 0, _y0: 0, // Unit x, Unit y. Provide for avoiding drawing that too short line segment _ux: 0, _uy: 0, _len: 0, _lineDash: null, _dashOffset: 0, _dashIdx: 0, _dashSum: 0, /** * @readOnly */ setScale: function (sx, sy) { this._ux = mathAbs(1 / devicePixelRatio / sx) || 0; this._uy = mathAbs(1 / devicePixelRatio / sy) || 0; }, getContext: function () { return this._ctx; }, /** * @param {CanvasRenderingContext2D} ctx * @return {module:zrender/core/PathProxy} */ beginPath: function (ctx) { this._ctx = ctx; ctx && ctx.beginPath(); ctx && (this.dpr = ctx.dpr); // Reset if (this._saveData) { this._len = 0; } if (this._lineDash) { this._lineDash = null; this._dashOffset = 0; } return this; }, /** * @param {number} x * @param {number} y * @return {module:zrender/core/PathProxy} */ moveTo: function (x, y) { this.addData(CMD.M, x, y); this._ctx && this._ctx.moveTo(x, y); // x0, y0, xi, yi 是记录在 _dashedXXXXTo 方法中使用 // xi, yi 记录当前点, x0, y0 在 closePath 的时候回到起始点。 // 有可能在 beginPath 之后直接调用 lineTo,这时候 x0, y0 需要 // 在 lineTo 方法中记录,这里先不考虑这种情况,dashed line 也只在 IE10- 中不支持 this._x0 = x; this._y0 = y; this._xi = x; this._yi = y; return this; }, /** * @param {number} x * @param {number} y * @return {module:zrender/core/PathProxy} */ lineTo: function (x, y) { var exceedUnit = mathAbs(x - this._xi) > this._ux || mathAbs(y - this._yi) > this._uy // Force draw the first segment || this._len < 5; this.addData(CMD.L, x, y); if (this._ctx && exceedUnit) { this._needsDash() ? this._dashedLineTo(x, y) : this._ctx.lineTo(x, y); } if (exceedUnit) { this._xi = x; this._yi = y; } return this; }, /** * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @return {module:zrender/core/PathProxy} */ bezierCurveTo: function (x1, y1, x2, y2, x3, y3) { this.addData(CMD.C, x1, y1, x2, y2, x3, y3); if (this._ctx) { this._needsDash() ? this._dashedBezierTo(x1, y1, x2, y2, x3, y3) : this._ctx.bezierCurveTo(x1, y1, x2, y2, x3, y3); } this._xi = x3; this._yi = y3; return this; }, /** * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @return {module:zrender/core/PathProxy} */ quadraticCurveTo: function (x1, y1, x2, y2) { this.addData(CMD.Q, x1, y1, x2, y2); if (this._ctx) { this._needsDash() ? this._dashedQuadraticTo(x1, y1, x2, y2) : this._ctx.quadraticCurveTo(x1, y1, x2, y2); } this._xi = x2; this._yi = y2; return this; }, /** * @param {number} cx * @param {number} cy * @param {number} r * @param {number} startAngle * @param {number} endAngle * @param {boolean} anticlockwise * @return {module:zrender/core/PathProxy} */ arc: function (cx, cy, r, startAngle, endAngle, anticlockwise) { this.addData( CMD.A, cx, cy, r, r, startAngle, endAngle - startAngle, 0, anticlockwise ? 0 : 1 ); this._ctx && this._ctx.arc(cx, cy, r, startAngle, endAngle, anticlockwise); this._xi = mathCos$1(endAngle) * r + cx; this._yi = mathSin$1(endAngle) * r + cx; return this; }, // TODO arcTo: function (x1, y1, x2, y2, radius) { if (this._ctx) { this._ctx.arcTo(x1, y1, x2, y2, radius); } return this; }, // TODO rect: function (x, y, w, h) { this._ctx && this._ctx.rect(x, y, w, h); this.addData(CMD.R, x, y, w, h); return this; }, /** * @return {module:zrender/core/PathProxy} */ closePath: function () { this.addData(CMD.Z); var ctx = this._ctx; var x0 = this._x0; var y0 = this._y0; if (ctx) { this._needsDash() && this._dashedLineTo(x0, y0); ctx.closePath(); } this._xi = x0; this._yi = y0; return this; }, /** * Context 从外部传入,因为有可能是 rebuildPath 完之后再 fill。 * stroke 同样 * @param {CanvasRenderingContext2D} ctx * @return {module:zrender/core/PathProxy} */ fill: function (ctx) { ctx && ctx.fill(); this.toStatic(); }, /** * @param {CanvasRenderingContext2D} ctx * @return {module:zrender/core/PathProxy} */ stroke: function (ctx) { ctx && ctx.stroke(); this.toStatic(); }, /** * 必须在其它绘制命令前调用 * Must be invoked before all other path drawing methods * @return {module:zrender/core/PathProxy} */ setLineDash: function (lineDash) { if (lineDash instanceof Array) { this._lineDash = lineDash; this._dashIdx = 0; var lineDashSum = 0; for (var i = 0; i < lineDash.length; i++) { lineDashSum += lineDash[i]; } this._dashSum = lineDashSum; } return this; }, /** * 必须在其它绘制命令前调用 * Must be invoked before all other path drawing methods * @return {module:zrender/core/PathProxy} */ setLineDashOffset: function (offset) { this._dashOffset = offset; return this; }, /** * * @return {boolean} */ len: function () { return this._len; }, /** * 直接设置 Path 数据 */ setData: function (data) { var len$$1 = data.length; if (! (this.data && this.data.length == len$$1) && hasTypedArray) { this.data = new Float32Array(len$$1); } for (var i = 0; i < len$$1; i++) { this.data[i] = data[i]; } this._len = len$$1; }, /** * 添加子路径 * @param {module:zrender/core/PathProxy|Array.<module:zrender/core/PathProxy>} path */ appendPath: function (path) { if (!(path instanceof Array)) { path = [path]; } var len$$1 = path.length; var appendSize = 0; var offset = this._len; for (var i = 0; i < len$$1; i++) { appendSize += path[i].len(); } if (hasTypedArray && (this.data instanceof Float32Array)) { this.data = new Float32Array(offset + appendSize); } for (var i = 0; i < len$$1; i++) { var appendPathData = path[i].data; for (var k = 0; k < appendPathData.length; k++) { this.data[offset++] = appendPathData[k]; } } this._len = offset; }, /** * 填充 Path 数据。 * 尽量复用而不申明新的数组。大部分图形重绘的指令数据长度都是不变的。 */ addData: function (cmd) { if (!this._saveData) { return; } var data = this.data; if (this._len + arguments.length > data.length) { // 因为之前的数组已经转换成静态的 Float32Array // 所以不够用时需要扩展一个新的动态数组 this._expandData(); data = this.data; } for (var i = 0; i < arguments.length; i++) { data[this._len++] = arguments[i]; } this._prevCmd = cmd; }, _expandData: function () { // Only if data is Float32Array if (!(this.data instanceof Array)) { var newData = []; for (var i = 0; i < this._len; i++) { newData[i] = this.data[i]; } this.data = newData; } }, /** * If needs js implemented dashed line * @return {boolean} * @private */ _needsDash: function () { return this._lineDash; }, _dashedLineTo: function (x1, y1) { var dashSum = this._dashSum; var offset = this._dashOffset; var lineDash = this._lineDash; var ctx = this._ctx; var x0 = this._xi; var y0 = this._yi; var dx = x1 - x0; var dy = y1 - y0; var dist$$1 = mathSqrt$1(dx * dx + dy * dy); var x = x0; var y = y0; var dash; var nDash = lineDash.length; var idx; dx /= dist$$1; dy /= dist$$1; if (offset < 0) { // Convert to positive offset offset = dashSum + offset; } offset %= dashSum; x -= offset * dx; y -= offset * dy; while ((dx > 0 && x <= x1) || (dx < 0 && x >= x1) || (dx == 0 && ((dy > 0 && y <= y1) || (dy < 0 && y >= y1)))) { idx = this._dashIdx; dash = lineDash[idx]; x += dx * dash; y += dy * dash; this._dashIdx = (idx + 1) % nDash; // Skip positive offset if ((dx > 0 && x < x0) || (dx < 0 && x > x0) || (dy > 0 && y < y0) || (dy < 0 && y > y0)) { continue; } ctx[idx % 2 ? 'moveTo' : 'lineTo']( dx >= 0 ? mathMin$2(x, x1) : mathMax$2(x, x1), dy >= 0 ? mathMin$2(y, y1) : mathMax$2(y, y1) ); } // Offset for next lineTo dx = x - x1; dy = y - y1; this._dashOffset = -mathSqrt$1(dx * dx + dy * dy); }, // Not accurate dashed line to _dashedBezierTo: function (x1, y1, x2, y2, x3, y3) { var dashSum = this._dashSum; var offset = this._dashOffset; var lineDash = this._lineDash; var ctx = this._ctx; var x0 = this._xi; var y0 = this._yi; var t; var dx; var dy; var cubicAt$$1 = cubicAt; var bezierLen = 0; var idx = this._dashIdx; var nDash = lineDash.length; var x; var y; var tmpLen = 0; if (offset < 0) { // Convert to positive offset offset = dashSum + offset; } offset %= dashSum; // Bezier approx length for (t = 0; t < 1; t += 0.1) { dx = cubicAt$$1(x0, x1, x2, x3, t + 0.1) - cubicAt$$1(x0, x1, x2, x3, t); dy = cubicAt$$1(y0, y1, y2, y3, t + 0.1) - cubicAt$$1(y0, y1, y2, y3, t); bezierLen += mathSqrt$1(dx * dx + dy * dy); } // Find idx after add offset for (; idx < nDash; idx++) { tmpLen += lineDash[idx]; if (tmpLen > offset) { break; } } t = (tmpLen - offset) / bezierLen; while (t <= 1) { x = cubicAt$$1(x0, x1, x2, x3, t); y = cubicAt$$1(y0, y1, y2, y3, t); // Use line to approximate dashed bezier // Bad result if dash is long idx % 2 ? ctx.moveTo(x, y) : ctx.lineTo(x, y); t += lineDash[idx] / bezierLen; idx = (idx + 1) % nDash; } // Finish the last segment and calculate the new offset (idx % 2 !== 0) && ctx.lineTo(x3, y3); dx = x3 - x; dy = y3 - y; this._dashOffset = -mathSqrt$1(dx * dx + dy * dy); }, _dashedQuadraticTo: function (x1, y1, x2, y2) { // Convert quadratic to cubic using degree elevation var x3 = x2; var y3 = y2; x2 = (x2 + 2 * x1) / 3; y2 = (y2 + 2 * y1) / 3; x1 = (this._xi + 2 * x1) / 3; y1 = (this._yi + 2 * y1) / 3; this._dashedBezierTo(x1, y1, x2, y2, x3, y3); }, /** * 转成静态的 Float32Array 减少堆内存占用 * Convert dynamic array to static Float32Array */ toStatic: function () { var data = this.data; if (data instanceof Array) { data.length = this._len; if (hasTypedArray) { this.data = new Float32Array(data); } } }, /** * @return {module:zrender/core/BoundingRect} */ getBoundingRect: function () { min$1[0] = min$1[1] = min2[0] = min2[1] = Number.MAX_VALUE; max$1[0] = max$1[1] = max2[0] = max2[1] = -Number.MAX_VALUE; var data = this.data; var xi = 0; var yi = 0; var x0 = 0; var y0 = 0; for (var i = 0; i < data.length;) { var cmd = data[i++]; if (i == 1) { // 如果第一个命令是 L, C, Q // 则 previous point 同绘制命令的第一个 point // // 第一个命令为 Arc 的情况下会在后面特殊处理 xi = data[i]; yi = data[i + 1]; x0 = xi; y0 = yi; } switch (cmd) { case CMD.M: // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点 // 在 closePath 的时候使用 x0 = data[i++]; y0 = data[i++]; xi = x0; yi = y0; min2[0] = x0; min2[1] = y0; max2[0] = x0; max2[1] = y0; break; case CMD.L: fromLine(xi, yi, data[i], data[i + 1], min2, max2); xi = data[i++]; yi = data[i++]; break; case CMD.C: fromCubic( xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], min2, max2 ); xi = data[i++]; yi = data[i++]; break; case CMD.Q: fromQuadratic( xi, yi, data[i++], data[i++], data[i], data[i + 1], min2, max2 ); xi = data[i++]; yi = data[i++]; break; case CMD.A: // TODO Arc 判断的开销比较大 var cx = data[i++]; var cy = data[i++]; var rx = data[i++]; var ry = data[i++]; var startAngle = data[i++]; var endAngle = data[i++] + startAngle; // TODO Arc 旋转 var psi = data[i++]; var anticlockwise = 1 - data[i++]; if (i == 1) { // 直接使用 arc 命令 // 第一个命令起点还未定义 x0 = mathCos$1(startAngle) * rx + cx; y0 = mathSin$1(startAngle) * ry + cy; } fromArc( cx, cy, rx, ry, startAngle, endAngle, anticlockwise, min2, max2 ); xi = mathCos$1(endAngle) * rx + cx; yi = mathSin$1(endAngle) * ry + cy; break; case CMD.R: x0 = xi = data[i++]; y0 = yi = data[i++]; var width = data[i++]; var height = data[i++]; // Use fromLine fromLine(x0, y0, x0 + width, y0 + height, min2, max2); break; case CMD.Z: xi = x0; yi = y0; break; } // Union min(min$1, min$1, min2); max(max$1, max$1, max2); } // No data if (i === 0) { min$1[0] = min$1[1] = max$1[0] = max$1[1] = 0; } return new BoundingRect( min$1[0], min$1[1], max$1[0] - min$1[0], max$1[1] - min$1[1] ); }, /** * Rebuild path from current data * Rebuild path will not consider javascript implemented line dash. * @param {CanvasRenderingContext2D} ctx */ rebuildPath: function (ctx) { var d = this.data; var x0, y0; var xi, yi; var x, y; var ux = this._ux; var uy = this._uy; var len$$1 = this._len; for (var i = 0; i < len$$1;) { var cmd = d[i++]; if (i == 1) { // 如果第一个命令是 L, C, Q // 则 previous point 同绘制命令的第一个 point // // 第一个命令为 Arc 的情况下会在后面特殊处理 xi = d[i]; yi = d[i + 1]; x0 = xi; y0 = yi; } switch (cmd) { case CMD.M: x0 = xi = d[i++]; y0 = yi = d[i++]; ctx.moveTo(xi, yi); break; case CMD.L: x = d[i++]; y = d[i++]; // Not draw too small seg between if (mathAbs(x - xi) > ux || mathAbs(y - yi) > uy || i === len$$1 - 1) { ctx.lineTo(x, y); xi = x; yi = y; } break; case CMD.C: ctx.bezierCurveTo( d[i++], d[i++], d[i++], d[i++], d[i++], d[i++] ); xi = d[i - 2]; yi = d[i - 1]; break; case CMD.Q: ctx.quadraticCurveTo(d[i++], d[i++], d[i++], d[i++]); xi = d[i - 2]; yi = d[i - 1]; break; case CMD.A: var cx = d[i++]; var cy = d[i++]; var rx = d[i++]; var ry = d[i++]; var theta = d[i++]; var dTheta = d[i++]; var psi = d[i++]; var fs = d[i++]; var r = (rx > ry) ? rx : ry; var scaleX = (rx > ry) ? 1 : rx / ry; var scaleY = (rx > ry) ? ry / rx : 1; var isEllipse = Math.abs(rx - ry) > 1e-3; var endAngle = theta + dTheta; if (isEllipse) { ctx.translate(cx, cy); ctx.rotate(psi); ctx.scale(scaleX, scaleY); ctx.arc(0, 0, r, theta, endAngle, 1 - fs); ctx.scale(1 / scaleX, 1 / scaleY); ctx.rotate(-psi); ctx.translate(-cx, -cy); } else { ctx.arc(cx, cy, r, theta, endAngle, 1 - fs); } if (i == 1) { // 直接使用 arc 命令 // 第一个命令起点还未定义 x0 = mathCos$1(theta) * rx + cx; y0 = mathSin$1(theta) * ry + cy; } xi = mathCos$1(endAngle) * rx + cx; yi = mathSin$1(endAngle) * ry + cy; break; case CMD.R: x0 = xi = d[i]; y0 = yi = d[i + 1]; ctx.rect(d[i++], d[i++], d[i++], d[i++]); break; case CMD.Z: ctx.closePath(); xi = x0; yi = y0; } } } }; PathProxy.CMD = CMD; /** * 线段包含判断 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} lineWidth * @param {number} x * @param {number} y * @return {boolean} */ function containStroke$1(x0, y0, x1, y1, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = lineWidth; var _a = 0; var _b = x0; // Quick reject if ( (y > y0 + _l && y > y1 + _l) || (y < y0 - _l && y < y1 - _l) || (x > x0 + _l && x > x1 + _l) || (x < x0 - _l && x < x1 - _l) ) { return false; } if (x0 !== x1) { _a = (y0 - y1) / (x0 - x1); _b = (x0 * y1 - x1 * y0) / (x0 - x1) ; } else { return Math.abs(x - x0) <= _l / 2; } var tmp = _a * x - y + _b; var _s = tmp * tmp / (_a * _a + 1); return _s <= _l / 2 * _l / 2; } /** * 三次贝塞尔曲线描边包含判断 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} x3 * @param {number} y3 * @param {number} lineWidth * @param {number} x * @param {number} y * @return {boolean} */ function containStroke$2(x0, y0, x1, y1, x2, y2, x3, y3, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = lineWidth; // Quick reject if ( (y > y0 + _l && y > y1 + _l && y > y2 + _l && y > y3 + _l) || (y < y0 - _l && y < y1 - _l && y < y2 - _l && y < y3 - _l) || (x > x0 + _l && x > x1 + _l && x > x2 + _l && x > x3 + _l) || (x < x0 - _l && x < x1 - _l && x < x2 - _l && x < x3 - _l) ) { return false; } var d = cubicProjectPoint( x0, y0, x1, y1, x2, y2, x3, y3, x, y, null ); return d <= _l / 2; } /** * 二次贝塞尔曲线描边包含判断 * @param {number} x0 * @param {number} y0 * @param {number} x1 * @param {number} y1 * @param {number} x2 * @param {number} y2 * @param {number} lineWidth * @param {number} x * @param {number} y * @return {boolean} */ function containStroke$3(x0, y0, x1, y1, x2, y2, lineWidth, x, y) { if (lineWidth === 0) { return false; } var _l = lineWidth; // Quick reject if ( (y > y0 + _l && y > y1 + _l && y > y2 + _l) || (y < y0 - _l && y < y1 - _l && y < y2 - _l) || (x > x0 + _l && x > x1 + _l && x > x2 + _l) || (x < x0 - _l && x < x1 - _l && x < x2 - _l) ) { return false; } var d = quadraticProjectPoint( x0, y0, x1, y1, x2, y2, x, y, null ); return d <= _l / 2; } var PI2$3 = Math.PI * 2; function normalizeRadian(angle) { angle %= PI2$3; if (angle < 0) { angle += PI2$3; } return angle; } var PI2$2 = Math.PI * 2; /** * 圆弧描边包含判断 * @param {number} cx * @param {number} cy * @param {number} r * @param {number} startAngle * @param {number} endAngle * @param {boolean} anticlockwise * @param {number} lineWidth * @param {number} x * @param {number} y * @return {Boolean} */ function containStroke$4( cx, cy, r, startAngle, endAngle, anticlockwise, lineWidth, x, y ) { if (lineWidth === 0) { return false; } var _l = lineWidth; x -= cx; y -= cy; var d = Math.sqrt(x * x + y * y); if ((d - _l > r) || (d + _l < r)) { return false; } if (Math.abs(startAngle - endAngle) % PI2$2 < 1e-4) { // Is a circle return true; } if (anticlockwise) { var tmp = startAngle; startAngle = normalizeRadian(endAngle); endAngle = normalizeRadian(tmp); } else { startAngle = normalizeRadian(startAngle); endAngle = normalizeRadian(endAngle); } if (startAngle > endAngle) { endAngle += PI2$2; } var angle = Math.atan2(y, x); if (angle < 0) { angle += PI2$2; } return (angle >= startAngle && angle <= endAngle) || (angle + PI2$2 >= startAngle && angle + PI2$2 <= endAngle); } function windingLine(x0, y0, x1, y1, x, y) { if ((y > y0 && y > y1) || (y < y0 && y < y1)) { return 0; } // Ignore horizontal line if (y1 === y0) { return 0; } var dir = y1 < y0 ? 1 : -1; var t = (y - y0) / (y1 - y0); // Avoid winding error when intersection point is the connect point of two line of polygon if (t === 1 || t === 0) { dir = y1 < y0 ? 0.5 : -0.5; } var x_ = t * (x1 - x0) + x0; return x_ > x ? dir : 0; } var PI2$1 = Math.PI * 2; var EPSILON$2 = 1e-4; function isAroundEqual(a, b) { return Math.abs(a - b) < EPSILON$2; } // 临时数组 var roots = [-1, -1, -1]; var extrema = [-1, -1]; function swapExtrema() { var tmp = extrema[0]; extrema[0] = extrema[1]; extrema[1] = tmp; } function windingCubic(x0, y0, x1, y1, x2, y2, x3, y3, x, y) { // Quick reject if ( (y > y0 && y > y1 && y > y2 && y > y3) || (y < y0 && y < y1 && y < y2 && y < y3) ) { return 0; } var nRoots = cubicRootAt(y0, y1, y2, y3, y, roots); if (nRoots === 0) { return 0; } else { var w = 0; var nExtrema = -1; var y0_, y1_; for (var i = 0; i < nRoots; i++) { var t = roots[i]; // Avoid winding error when intersection point is the connect point of two line of polygon var unit = (t === 0 || t === 1) ? 0.5 : 1; var x_ = cubicAt(x0, x1, x2, x3, t); if (x_ < x) { // Quick reject continue; } if (nExtrema < 0) { nExtrema = cubicExtrema(y0, y1, y2, y3, extrema); if (extrema[1] < extrema[0] && nExtrema > 1) { swapExtrema(); } y0_ = cubicAt(y0, y1, y2, y3, extrema[0]); if (nExtrema > 1) { y1_ = cubicAt(y0, y1, y2, y3, extrema[1]); } } if (nExtrema == 2) { // 分成三段单调函数 if (t < extrema[0]) { w += y0_ < y0 ? unit : -unit; } else if (t < extrema[1]) { w += y1_ < y0_ ? unit : -unit; } else { w += y3 < y1_ ? unit : -unit; } } else { // 分成两段单调函数 if (t < extrema[0]) { w += y0_ < y0 ? unit : -unit; } else { w += y3 < y0_ ? unit : -unit; } } } return w; } } function windingQuadratic(x0, y0, x1, y1, x2, y2, x, y) { // Quick reject if ( (y > y0 && y > y1 && y > y2) || (y < y0 && y < y1 && y < y2) ) { return 0; } var nRoots = quadraticRootAt(y0, y1, y2, y, roots); if (nRoots === 0) { return 0; } else { var t = quadraticExtremum(y0, y1, y2); if (t >= 0 && t <= 1) { var w = 0; var y_ = quadraticAt(y0, y1, y2, t); for (var i = 0; i < nRoots; i++) { // Remove one endpoint. var unit = (roots[i] === 0 || roots[i] === 1) ? 0.5 : 1; var x_ = quadraticAt(x0, x1, x2, roots[i]); if (x_ < x) { // Quick reject continue; } if (roots[i] < t) { w += y_ < y0 ? unit : -unit; } else { w += y2 < y_ ? unit : -unit; } } return w; } else { // Remove one endpoint. var unit = (roots[0] === 0 || roots[0] === 1) ? 0.5 : 1; var x_ = quadraticAt(x0, x1, x2, roots[0]); if (x_ < x) { // Quick reject return 0; } return y2 < y0 ? unit : -unit; } } } // TODO // Arc 旋转 function windingArc( cx, cy, r, startAngle, endAngle, anticlockwise, x, y ) { y -= cy; if (y > r || y < -r) { return 0; } var tmp = Math.sqrt(r * r - y * y); roots[0] = -tmp; roots[1] = tmp; var diff = Math.abs(startAngle - endAngle); if (diff < 1e-4) { return 0; } if (diff % PI2$1 < 1e-4) { // Is a circle startAngle = 0; endAngle = PI2$1; var dir = anticlockwise ? 1 : -1; if (x >= roots[0] + cx && x <= roots[1] + cx) { return dir; } else { return 0; } } if (anticlockwise) { var tmp = startAngle; startAngle = normalizeRadian(endAngle); endAngle = normalizeRadian(tmp); } else { startAngle = normalizeRadian(startAngle); endAngle = normalizeRadian(endAngle); } if (startAngle > endAngle) { endAngle += PI2$1; } var w = 0; for (var i = 0; i < 2; i++) { var x_ = roots[i]; if (x_ + cx > x) { var angle = Math.atan2(y, x_); var dir = anticlockwise ? 1 : -1; if (angle < 0) { angle = PI2$1 + angle; } if ( (angle >= startAngle && angle <= endAngle) || (angle + PI2$1 >= startAngle && angle + PI2$1 <= endAngle) ) { if (angle > Math.PI / 2 && angle < Math.PI * 1.5) { dir = -dir; } w += dir; } } } return w; } function containPath(data, lineWidth, isStroke, x, y) { var w = 0; var xi = 0; var yi = 0; var x0 = 0; var y0 = 0; for (var i = 0; i < data.length;) { var cmd = data[i++]; // Begin a new subpath if (cmd === CMD.M && i > 1) { // Close previous subpath if (!isStroke) { w += windingLine(xi, yi, x0, y0, x, y); } // 如果被任何一个 subpath 包含 // if (w !== 0) { // return true; // } } if (i == 1) { // 如果第一个命令是 L, C, Q // 则 previous point 同绘制命令的第一个 point // // 第一个命令为 Arc 的情况下会在后面特殊处理 xi = data[i]; yi = data[i + 1]; x0 = xi; y0 = yi; } switch (cmd) { case CMD.M: // moveTo 命令重新创建一个新的 subpath, 并且更新新的起点 // 在 closePath 的时候使用 x0 = data[i++]; y0 = data[i++]; xi = x0; yi = y0; break; case CMD.L: if (isStroke) { if (containStroke$1(xi, yi, data[i], data[i + 1], lineWidth, x, y)) { return true; } } else { // NOTE 在第一个命令为 L, C, Q 的时候会计算出 NaN w += windingLine(xi, yi, data[i], data[i + 1], x, y) || 0; } xi = data[i++]; yi = data[i++]; break; case CMD.C: if (isStroke) { if (containStroke$2(xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y )) { return true; } } else { w += windingCubic( xi, yi, data[i++], data[i++], data[i++], data[i++], data[i], data[i + 1], x, y ) || 0; } xi = data[i++]; yi = data[i++]; break; case CMD.Q: if (isStroke) { if (containStroke$3(xi, yi, data[i++], data[i++], data[i], data[i + 1], lineWidth, x, y )) { return true; } } else { w += windingQuadratic( xi, yi, data[i++], data[i++], data[i], data[i + 1], x, y ) || 0; } xi = data[i++]; yi = data[i++]; break; case CMD.A: // TODO Arc 判断的开销比较大 var cx = data[i++]; var cy = data[i++]; var rx = data[i++]; var ry = data[i++]; var theta = data[i++]; var dTheta = data[i++]; // TODO Arc 旋转 var psi = data[i++]; var anticlockwise = 1 - data[i++]; var x1 = Math.cos(theta) * rx + cx; var y1 = Math.sin(theta) * ry + cy; // 不是直接使用 arc 命令 if (i > 1) { w += windingLine(xi, yi, x1, y1, x, y); } else { // 第一个命令起点还未定义 x0 = x1; y0 = y1; } // zr 使用scale来模拟椭圆, 这里也对x做一定的缩放 var _x = (x - cx) * ry / rx + cx; if (isStroke) { if (containStroke$4( cx, cy, ry, theta, theta + dTheta, anticlockwise, lineWidth, _x, y )) { return true; } } else { w += windingArc( cx, cy, ry, theta, theta + dTheta, anticlockwise, _x, y ); } xi = Math.cos(theta + dTheta) * rx + cx; yi = Math.sin(theta + dTheta) * ry + cy; break; case CMD.R: x0 = xi = data[i++]; y0 = yi = data[i++]; var width = data[i++]; var height = data[i++]; var x1 = x0 + width; var y1 = y0 + height; if (isStroke) { if (containStroke$1(x0, y0, x1, y0, lineWidth, x, y) || containStroke$1(x1, y0, x1, y1, lineWidth, x, y) || containStroke$1(x1, y1, x0, y1, lineWidth, x, y) || containStroke$1(x0, y1, x0, y0, lineWidth, x, y) ) { return true; } } else { // FIXME Clockwise ? w += windingLine(x1, y0, x1, y1, x, y); w += windingLine(x0, y1, x0, y0, x, y); } break; case CMD.Z: if (isStroke) { if (containStroke$1( xi, yi, x0, y0, lineWidth, x, y )) { return true; } } else { // Close a subpath w += windingLine(xi, yi, x0, y0, x, y); // 如果被任何一个 subpath 包含 // FIXME subpaths may overlap // if (w !== 0) { // return true; // } } xi = x0; yi = y0; break; } } if (!isStroke && !isAroundEqual(yi, y0)) { w += windingLine(xi, yi, x0, y0, x, y) || 0; } return w !== 0; } function contain(pathData, x, y) { return containPath(pathData, 0, false, x, y); } function containStroke(pathData, lineWidth, x, y) { return containPath(pathData, lineWidth, true, x, y); } var getCanvasPattern = Pattern.prototype.getCanvasPattern; var abs = Math.abs; var pathProxyForDraw = new PathProxy(true); /** * @alias module:zrender/graphic/Path * @extends module:zrender/graphic/Displayable * @constructor * @param {Object} opts */ function Path(opts) { Displayable.call(this, opts); /** * @type {module:zrender/core/PathProxy} * @readOnly */ this.path = null; } Path.prototype = { constructor: Path, type: 'path', __dirtyPath: true, strokeContainThreshold: 5, brush: function (ctx, prevEl) { var style = this.style; var path = this.path || pathProxyForDraw; var hasStroke = style.hasStroke(); var hasFill = style.hasFill(); var fill = style.fill; var stroke = style.stroke; var hasFillGradient = hasFill && !!(fill.colorStops); var hasStrokeGradient = hasStroke && !!(stroke.colorStops); var hasFillPattern = hasFill && !!(fill.image); var hasStrokePattern = hasStroke && !!(stroke.image); style.bind(ctx, this, prevEl); this.setTransform(ctx); if (this.__dirty) { var rect; // Update gradient because bounding rect may changed if (hasFillGradient) { rect = rect || this.getBoundingRect(); this._fillGradient = style.getGradient(ctx, fill, rect); } if (hasStrokeGradient) { rect = rect || this.getBoundingRect(); this._strokeGradient = style.getGradient(ctx, stroke, rect); } } // Use the gradient or pattern if (hasFillGradient) { // PENDING If may have affect the state ctx.fillStyle = this._fillGradient; } else if (hasFillPattern) { ctx.fillStyle = getCanvasPattern.call(fill, ctx); } if (hasStrokeGradient) { ctx.strokeStyle = this._strokeGradient; } else if (hasStrokePattern) { ctx.strokeStyle = getCanvasPattern.call(stroke, ctx); } var lineDash = style.lineDash; var lineDashOffset = style.lineDashOffset; var ctxLineDash = !!ctx.setLineDash; // Update path sx, sy var scale = this.getGlobalScale(); path.setScale(scale[0], scale[1]); // Proxy context // Rebuild path in following 2 cases // 1. Path is dirty // 2. Path needs javascript implemented lineDash stroking. // In this case, lineDash information will not be saved in PathProxy if (this.__dirtyPath || (lineDash && !ctxLineDash && hasStroke) ) { path.beginPath(ctx); // Setting line dash before build path if (lineDash && !ctxLineDash) { path.setLineDash(lineDash); path.setLineDashOffset(lineDashOffset); } this.buildPath(path, this.shape, false); // Clear path dirty flag if (this.path) { this.__dirtyPath = false; } } else { // Replay path building ctx.beginPath(); this.path.rebuildPath(ctx); } hasFill && path.fill(ctx); if (lineDash && ctxLineDash) { ctx.setLineDash(lineDash); ctx.lineDashOffset = lineDashOffset; } hasStroke && path.stroke(ctx); if (lineDash && ctxLineDash) { // PENDING // Remove lineDash ctx.setLineDash([]); } this.restoreTransform(ctx); // Draw rect text if (style.text != null) { this.drawRectText(ctx, this.getBoundingRect()); } }, // When bundling path, some shape may decide if use moveTo to begin a new subpath or closePath // Like in circle buildPath: function (ctx, shapeCfg, inBundle) {}, createPathProxy: function () { this.path = new PathProxy(); }, getBoundingRect: function () { var rect = this._rect; var style = this.style; var needsUpdateRect = !rect; if (needsUpdateRect) { var path = this.path; if (!path) { // Create path on demand. path = this.path = new PathProxy(); } if (this.__dirtyPath) { path.beginPath(); this.buildPath(path, this.shape, false); } rect = path.getBoundingRect(); } this._rect = rect; if (style.hasStroke()) { // Needs update rect with stroke lineWidth when // 1. Element changes scale or lineWidth // 2. Shape is changed var rectWithStroke = this._rectWithStroke || (this._rectWithStroke = rect.clone()); if (this.__dirty || needsUpdateRect) { rectWithStroke.copy(rect); // FIXME Must after updateTransform var w = style.lineWidth; // PENDING, Min line width is needed when line is horizontal or vertical var lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Only add extra hover lineWidth when there are no fill if (!style.hasFill()) { w = Math.max(w, this.strokeContainThreshold || 4); } // Consider line width // Line scale can't be 0; if (lineScale > 1e-10) { rectWithStroke.width += w / lineScale; rectWithStroke.height += w / lineScale; rectWithStroke.x -= w / lineScale / 2; rectWithStroke.y -= w / lineScale / 2; } } // Return rect with stroke return rectWithStroke; } return rect; }, contain: function (x, y) { var localPos = this.transformCoordToLocal(x, y); var rect = this.getBoundingRect(); var style = this.style; x = localPos[0]; y = localPos[1]; if (rect.contain(x, y)) { var pathData = this.path.data; if (style.hasStroke()) { var lineWidth = style.lineWidth; var lineScale = style.strokeNoScale ? this.getLineScale() : 1; // Line scale can't be 0; if (lineScale > 1e-10) { // Only add extra hover lineWidth when there are no fill if (!style.hasFill()) { lineWidth = Math.max(lineWidth, this.strokeContainThreshold); } if (containStroke( pathData, lineWidth / lineScale, x, y )) { return true; } } } if (style.hasFill()) { return contain(pathData, x, y); } } return false; }, /** * @param {boolean} dirtyPath */ dirty: function (dirtyPath) { if (dirtyPath == null) { dirtyPath = true; } // Only mark dirty, not mark clean if (dirtyPath) { this.__dirtyPath = dirtyPath; this._rect = null; } this.__dirty = true; this.__zr && this.__zr.refresh(); // Used as a clipping path if (this.__clipTarget) { this.__clipTarget.dirty(); } }, /** * Alias for animate('shape') * @param {boolean} loop */ animateShape: function (loop) { return this.animate('shape', loop); }, // Overwrite attrKV attrKV: function (key, value) { // FIXME if (key === 'shape') { this.setShape(value); this.__dirtyPath = true; this._rect = null; } else { Displayable.prototype.attrKV.call(this, key, value); } }, /** * @param {Object|string} key * @param {*} value */ setShape: function (key, value) { var shape = this.shape; // Path from string may not have shape if (shape) { if (isObject(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { shape[name] = key[name]; } } } else { shape[key] = value; } this.dirty(true); } return this; }, getLineScale: function () { var m = this.transform; // Get the line scale. // Determinant of `m` means how much the area is enlarged by the // transformation. So its square root can be used as a scale factor // for width. return m && abs(m[0] - 1) > 1e-10 && abs(m[3] - 1) > 1e-10 ? Math.sqrt(abs(m[0] * m[3] - m[2] * m[1])) : 1; } }; /** * 扩展一个 Path element, 比如星形,圆等。 * Extend a path element * @param {Object} props * @param {string} props.type Path type * @param {Function} props.init Initialize * @param {Function} props.buildPath Overwrite buildPath method * @param {Object} [props.style] Extended default style config * @param {Object} [props.shape] Extended default shape config */ Path.extend = function (defaults$$1) { var Sub = function (opts) { Path.call(this, opts); if (defaults$$1.style) { // Extend default style this.style.extendFrom(defaults$$1.style, false); } // Extend default shape var defaultShape = defaults$$1.shape; if (defaultShape) { this.shape = this.shape || {}; var thisShape = this.shape; for (var name in defaultShape) { if ( ! thisShape.hasOwnProperty(name) && defaultShape.hasOwnProperty(name) ) { thisShape[name] = defaultShape[name]; } } } defaults$$1.init && defaults$$1.init.call(this, opts); }; inherits(Sub, Path); // FIXME 不能 extend position, rotation 等引用对象 for (var name in defaults$$1) { // Extending prototype values and methods if (name !== 'style' && name !== 'shape') { Sub.prototype[name] = defaults$$1[name]; } } return Sub; }; inherits(Path, Displayable); var points = [[], [], []]; var mathSqrt$3 = Math.sqrt; var mathAtan2 = Math.atan2; var transformPath = function (path, m) { var data = path.data; var cmd; var nPoint; var i; var j; var k; var p; var M = CMD.M; var C = CMD.C; var L = CMD.L; var R = CMD.R; var A = CMD.A; var Q = CMD.Q; for (i = 0, j = 0; i < data.length;) { cmd = data[i++]; j = i; nPoint = 0; switch (cmd) { case M: nPoint = 1; break; case L: nPoint = 1; break; case C: nPoint = 3; break; case Q: nPoint = 2; break; case A: var x = m[4]; var y = m[5]; var sx = mathSqrt$3(m[0] * m[0] + m[1] * m[1]); var sy = mathSqrt$3(m[2] * m[2] + m[3] * m[3]); var angle = mathAtan2(-m[1] / sy, m[0] / sx); // cx data[i] *= sx; data[i++] += x; // cy data[i] *= sy; data[i++] += y; // Scale rx and ry // FIXME Assume psi is 0 here data[i++] *= sx; data[i++] *= sy; // Start angle data[i++] += angle; // end angle data[i++] += angle; // FIXME psi i += 2; j = i; break; case R: // x0, y0 p[0] = data[i++]; p[1] = data[i++]; applyTransform(p, p, m); data[j++] = p[0]; data[j++] = p[1]; // x1, y1 p[0] += data[i++]; p[1] += data[i++]; applyTransform(p, p, m); data[j++] = p[0]; data[j++] = p[1]; } for (k = 0; k < nPoint; k++) { var p = points[k]; p[0] = data[i++]; p[1] = data[i++]; applyTransform(p, p, m); // Write back data[j++] = p[0]; data[j++] = p[1]; } } }; // command chars var cc = [ 'm', 'M', 'l', 'L', 'v', 'V', 'h', 'H', 'z', 'Z', 'c', 'C', 'q', 'Q', 't', 'T', 's', 'S', 'a', 'A' ]; var mathSqrt = Math.sqrt; var mathSin = Math.sin; var mathCos = Math.cos; var PI = Math.PI; var vMag = function(v) { return Math.sqrt(v[0] * v[0] + v[1] * v[1]); }; var vRatio = function(u, v) { return (u[0] * v[0] + u[1] * v[1]) / (vMag(u) * vMag(v)); }; var vAngle = function(u, v) { return (u[0] * v[1] < u[1] * v[0] ? -1 : 1) * Math.acos(vRatio(u, v)); }; function processArc(x1, y1, x2, y2, fa, fs, rx, ry, psiDeg, cmd, path) { var psi = psiDeg * (PI / 180.0); var xp = mathCos(psi) * (x1 - x2) / 2.0 + mathSin(psi) * (y1 - y2) / 2.0; var yp = -1 * mathSin(psi) * (x1 - x2) / 2.0 + mathCos(psi) * (y1 - y2) / 2.0; var lambda = (xp * xp) / (rx * rx) + (yp * yp) / (ry * ry); if (lambda > 1) { rx *= mathSqrt(lambda); ry *= mathSqrt(lambda); } var f = (fa === fs ? -1 : 1) * mathSqrt((((rx * rx) * (ry * ry)) - ((rx * rx) * (yp * yp)) - ((ry * ry) * (xp * xp))) / ((rx * rx) * (yp * yp) + (ry * ry) * (xp * xp)) ) || 0; var cxp = f * rx * yp / ry; var cyp = f * -ry * xp / rx; var cx = (x1 + x2) / 2.0 + mathCos(psi) * cxp - mathSin(psi) * cyp; var cy = (y1 + y2) / 2.0 + mathSin(psi) * cxp + mathCos(psi) * cyp; var theta = vAngle([ 1, 0 ], [ (xp - cxp) / rx, (yp - cyp) / ry ]); var u = [ (xp - cxp) / rx, (yp - cyp) / ry ]; var v = [ (-1 * xp - cxp) / rx, (-1 * yp - cyp) / ry ]; var dTheta = vAngle(u, v); if (vRatio(u, v) <= -1) { dTheta = PI; } if (vRatio(u, v) >= 1) { dTheta = 0; } if (fs === 0 && dTheta > 0) { dTheta = dTheta - 2 * PI; } if (fs === 1 && dTheta < 0) { dTheta = dTheta + 2 * PI; } path.addData(cmd, cx, cy, rx, ry, theta, dTheta, psi, fs); } function createPathProxyFromString(data) { if (!data) { return []; } // command string var cs = data.replace(/-/g, ' -') .replace(/ /g, ' ') .replace(/ /g, ',') .replace(/,,/g, ','); var n; // create pipes so that we can split the data for (n = 0; n < cc.length; n++) { cs = cs.replace(new RegExp(cc[n], 'g'), '|' + cc[n]); } // create array var arr = cs.split('|'); // init context point var cpx = 0; var cpy = 0; var path = new PathProxy(); var CMD$$1 = PathProxy.CMD; var prevCmd; for (n = 1; n < arr.length; n++) { var str = arr[n]; var c = str.charAt(0); var off = 0; var p = str.slice(1).replace(/e,-/g, 'e-').split(','); var cmd; if (p.length > 0 && p[0] === '') { p.shift(); } for (var i = 0; i < p.length; i++) { p[i] = parseFloat(p[i]); } while (off < p.length && !isNaN(p[off])) { if (isNaN(p[0])) { break; } var ctlPtx; var ctlPty; var rx; var ry; var psi; var fa; var fs; var x1 = cpx; var y1 = cpy; // convert l, H, h, V, and v to L switch (c) { case 'l': cpx += p[off++]; cpy += p[off++]; cmd = CMD$$1.L; path.addData(cmd, cpx, cpy); break; case 'L': cpx = p[off++]; cpy = p[off++]; cmd = CMD$$1.L; path.addData(cmd, cpx, cpy); break; case 'm': cpx += p[off++]; cpy += p[off++]; cmd = CMD$$1.M; path.addData(cmd, cpx, cpy); c = 'l'; break; case 'M': cpx = p[off++]; cpy = p[off++]; cmd = CMD$$1.M; path.addData(cmd, cpx, cpy); c = 'L'; break; case 'h': cpx += p[off++]; cmd = CMD$$1.L; path.addData(cmd, cpx, cpy); break; case 'H': cpx = p[off++]; cmd = CMD$$1.L; path.addData(cmd, cpx, cpy); break; case 'v': cpy += p[off++]; cmd = CMD$$1.L; path.addData(cmd, cpx, cpy); break; case 'V': cpy = p[off++]; cmd = CMD$$1.L; path.addData(cmd, cpx, cpy); break; case 'C': cmd = CMD$$1.C; path.addData( cmd, p[off++], p[off++], p[off++], p[off++], p[off++], p[off++] ); cpx = p[off - 2]; cpy = p[off - 1]; break; case 'c': cmd = CMD$$1.C; path.addData( cmd, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy, p[off++] + cpx, p[off++] + cpy ); cpx += p[off - 2]; cpy += p[off - 1]; break; case 'S': ctlPtx = cpx; ctlPty = cpy; var len = path.len(); var pathData = path.data; if (prevCmd === CMD$$1.C) { ctlPtx += cpx - pathData[len - 4]; ctlPty += cpy - pathData[len - 3]; } cmd = CMD$$1.C; x1 = p[off++]; y1 = p[off++]; cpx = p[off++]; cpy = p[off++]; path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy); break; case 's': ctlPtx = cpx; ctlPty = cpy; var len = path.len(); var pathData = path.data; if (prevCmd === CMD$$1.C) { ctlPtx += cpx - pathData[len - 4]; ctlPty += cpy - pathData[len - 3]; } cmd = CMD$$1.C; x1 = cpx + p[off++]; y1 = cpy + p[off++]; cpx += p[off++]; cpy += p[off++]; path.addData(cmd, ctlPtx, ctlPty, x1, y1, cpx, cpy); break; case 'Q': x1 = p[off++]; y1 = p[off++]; cpx = p[off++]; cpy = p[off++]; cmd = CMD$$1.Q; path.addData(cmd, x1, y1, cpx, cpy); break; case 'q': x1 = p[off++] + cpx; y1 = p[off++] + cpy; cpx += p[off++]; cpy += p[off++]; cmd = CMD$$1.Q; path.addData(cmd, x1, y1, cpx, cpy); break; case 'T': ctlPtx = cpx; ctlPty = cpy; var len = path.len(); var pathData = path.data; if (prevCmd === CMD$$1.Q) { ctlPtx += cpx - pathData[len - 4]; ctlPty += cpy - pathData[len - 3]; } cpx = p[off++]; cpy = p[off++]; cmd = CMD$$1.Q; path.addData(cmd, ctlPtx, ctlPty, cpx, cpy); break; case 't': ctlPtx = cpx; ctlPty = cpy; var len = path.len(); var pathData = path.data; if (prevCmd === CMD$$1.Q) { ctlPtx += cpx - pathData[len - 4]; ctlPty += cpy - pathData[len - 3]; } cpx += p[off++]; cpy += p[off++]; cmd = CMD$$1.Q; path.addData(cmd, ctlPtx, ctlPty, cpx, cpy); break; case 'A': rx = p[off++]; ry = p[off++]; psi = p[off++]; fa = p[off++]; fs = p[off++]; x1 = cpx, y1 = cpy; cpx = p[off++]; cpy = p[off++]; cmd = CMD$$1.A; processArc( x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path ); break; case 'a': rx = p[off++]; ry = p[off++]; psi = p[off++]; fa = p[off++]; fs = p[off++]; x1 = cpx, y1 = cpy; cpx += p[off++]; cpy += p[off++]; cmd = CMD$$1.A; processArc( x1, y1, cpx, cpy, fa, fs, rx, ry, psi, cmd, path ); break; } } if (c === 'z' || c === 'Z') { cmd = CMD$$1.Z; path.addData(cmd); } prevCmd = cmd; } path.toStatic(); return path; } // TODO Optimize double memory cost problem function createPathOptions(str, opts) { var pathProxy = createPathProxyFromString(str); opts = opts || {}; opts.buildPath = function (path) { if (path.setData) { path.setData(pathProxy.data); // Svg and vml renderer don't have context var ctx = path.getContext(); if (ctx) { path.rebuildPath(ctx); } } else { var ctx = path; pathProxy.rebuildPath(ctx); } }; opts.applyTransform = function (m) { transformPath(pathProxy, m); this.dirty(true); }; return opts; } /** * Create a Path object from path string data * http://www.w3.org/TR/SVG/paths.html#PathData * @param {Object} opts Other options */ function createFromString(str, opts) { return new Path(createPathOptions(str, opts)); } /** * Create a Path class from path string data * @param {string} str * @param {Object} opts Other options */ function extendFromString(str, opts) { return Path.extend(createPathOptions(str, opts)); } /** * Merge multiple paths */ // TODO Apply transform // TODO stroke dash // TODO Optimize double memory cost problem function mergePath$1(pathEls, opts) { var pathList = []; var len = pathEls.length; for (var i = 0; i < len; i++) { var pathEl = pathEls[i]; if (!pathEl.path) { pathEl.createPathProxy(); } if (pathEl.__dirtyPath) { pathEl.buildPath(pathEl.path, pathEl.shape, true); } pathList.push(pathEl.path); } var pathBundle = new Path(opts); // Need path proxy. pathBundle.createPathProxy(); pathBundle.buildPath = function (path) { path.appendPath(pathList); // Svg and vml renderer don't have context var ctx = path.getContext(); if (ctx) { path.rebuildPath(ctx); } }; return pathBundle; } /** * @alias zrender/graphic/Text * @extends module:zrender/graphic/Displayable * @constructor * @param {Object} opts */ var Text = function (opts) { // jshint ignore:line Displayable.call(this, opts); }; Text.prototype = { constructor: Text, type: 'text', brush: function (ctx, prevEl) { var style = this.style; // Optimize, avoid normalize every time. this.__dirty && normalizeTextStyle(style, true); // Use props with prefix 'text'. style.fill = style.stroke = style.shadowBlur = style.shadowColor = style.shadowOffsetX = style.shadowOffsetY = null; var text = style.text; // Convert to string text != null && (text += ''); // Always bind style style.bind(ctx, this, prevEl); if (!needDrawText(text, style)) { return; } this.setTransform(ctx); renderText(this, ctx, text, style); this.restoreTransform(ctx); }, getBoundingRect: function () { var style = this.style; // Optimize, avoid normalize every time. this.__dirty && normalizeTextStyle(style, true); if (!this._rect) { var text = style.text; text != null ? (text += '') : (text = ''); var rect = getBoundingRect( style.text + '', style.font, style.textAlign, style.textVerticalAlign, style.textPadding, style.rich ); rect.x += style.x || 0; rect.y += style.y || 0; if (getStroke(style.textStroke, style.textStrokeWidth)) { var w = style.textStrokeWidth; rect.x -= w / 2; rect.y -= w / 2; rect.width += w; rect.height += w; } this._rect = rect; } return this._rect; } }; inherits(Text, Displayable); /** * 圆形 * @module zrender/shape/Circle */ var Circle = Path.extend({ type: 'circle', shape: { cx: 0, cy: 0, r: 0 }, buildPath : function (ctx, shape, inBundle) { // Better stroking in ShapeBundle // Always do it may have performence issue ( fill may be 2x more cost) if (inBundle) { ctx.moveTo(shape.cx + shape.r, shape.cy); } // else { // if (ctx.allocate && !ctx.data.length) { // ctx.allocate(ctx.CMD_MEM_SIZE.A); // } // } // Better stroking in ShapeBundle // ctx.moveTo(shape.cx + shape.r, shape.cy); ctx.arc(shape.cx, shape.cy, shape.r, 0, Math.PI * 2, true); } }); // Fix weird bug in some version of IE11 (like 11.0.9600.178**), // where exception "unexpected call to method or property access" // might be thrown when calling ctx.fill or ctx.stroke after a path // whose area size is zero is drawn and ctx.clip() is called and // shadowBlur is set. See #4572, #3112, #5777. // (e.g., // ctx.moveTo(10, 10); // ctx.lineTo(20, 10); // ctx.closePath(); // ctx.clip(); // ctx.shadowBlur = 10; // ... // ctx.fill(); // ) var shadowTemp = [ ['shadowBlur', 0], ['shadowColor', '#000'], ['shadowOffsetX', 0], ['shadowOffsetY', 0] ]; var fixClipWithShadow = function (orignalBrush) { // version string can be: '11.0' return (env$1.browser.ie && env$1.browser.version >= 11) ? function () { var clipPaths = this.__clipPaths; var style = this.style; var modified; if (clipPaths) { for (var i = 0; i < clipPaths.length; i++) { var clipPath = clipPaths[i]; var shape = clipPath && clipPath.shape; var type = clipPath && clipPath.type; if (shape && ( (type === 'sector' && shape.startAngle === shape.endAngle) || (type === 'rect' && (!shape.width || !shape.height)) )) { for (var j = 0; j < shadowTemp.length; j++) { // It is save to put shadowTemp static, because shadowTemp // will be all modified each item brush called. shadowTemp[j][2] = style[shadowTemp[j][0]]; style[shadowTemp[j][0]] = shadowTemp[j][1]; } modified = true; break; } } } orignalBrush.apply(this, arguments); if (modified) { for (var j = 0; j < shadowTemp.length; j++) { style[shadowTemp[j][0]] = shadowTemp[j][2]; } } } : orignalBrush; }; /** * 扇形 * @module zrender/graphic/shape/Sector */ var Sector = Path.extend({ type: 'sector', shape: { cx: 0, cy: 0, r0: 0, r: 0, startAngle: 0, endAngle: Math.PI * 2, clockwise: true }, brush: fixClipWithShadow(Path.prototype.brush), buildPath: function (ctx, shape) { var x = shape.cx; var y = shape.cy; var r0 = Math.max(shape.r0 || 0, 0); var r = Math.max(shape.r, 0); var startAngle = shape.startAngle; var endAngle = shape.endAngle; var clockwise = shape.clockwise; var unitX = Math.cos(startAngle); var unitY = Math.sin(startAngle); ctx.moveTo(unitX * r0 + x, unitY * r0 + y); ctx.lineTo(unitX * r + x, unitY * r + y); ctx.arc(x, y, r, startAngle, endAngle, !clockwise); ctx.lineTo( Math.cos(endAngle) * r0 + x, Math.sin(endAngle) * r0 + y ); if (r0 !== 0) { ctx.arc(x, y, r0, endAngle, startAngle, clockwise); } ctx.closePath(); } }); /** * 圆环 * @module zrender/graphic/shape/Ring */ var Ring = Path.extend({ type: 'ring', shape: { cx: 0, cy: 0, r: 0, r0: 0 }, buildPath: function (ctx, shape) { var x = shape.cx; var y = shape.cy; var PI2 = Math.PI * 2; ctx.moveTo(x + shape.r, y); ctx.arc(x, y, shape.r, 0, PI2, false); ctx.moveTo(x + shape.r0, y); ctx.arc(x, y, shape.r0, 0, PI2, true); } }); /** * Catmull-Rom spline 插值折线 * @module zrender/shape/util/smoothSpline * @author pissang (https://www.github.com/pissang) * Kener (@Kener-林峰, kener.linfeng@gmail.com) * errorrik (errorrik@gmail.com) */ /** * @inner */ function interpolate(p0, p1, p2, p3, t, t2, t3) { var v0 = (p2 - p0) * 0.5; var v1 = (p3 - p1) * 0.5; return (2 * (p1 - p2) + v0 + v1) * t3 + (-3 * (p1 - p2) - 2 * v0 - v1) * t2 + v0 * t + p1; } /** * @alias module:zrender/shape/util/smoothSpline * @param {Array} points 线段顶点数组 * @param {boolean} isLoop * @return {Array} */ var smoothSpline = function (points, isLoop) { var len$$1 = points.length; var ret = []; var distance$$1 = 0; for (var i = 1; i < len$$1; i++) { distance$$1 += distance(points[i - 1], points[i]); } var segs = distance$$1 / 2; segs = segs < len$$1 ? len$$1 : segs; for (var i = 0; i < segs; i++) { var pos = i / (segs - 1) * (isLoop ? len$$1 : len$$1 - 1); var idx = Math.floor(pos); var w = pos - idx; var p0; var p1 = points[idx % len$$1]; var p2; var p3; if (!isLoop) { p0 = points[idx === 0 ? idx : idx - 1]; p2 = points[idx > len$$1 - 2 ? len$$1 - 1 : idx + 1]; p3 = points[idx > len$$1 - 3 ? len$$1 - 1 : idx + 2]; } else { p0 = points[(idx - 1 + len$$1) % len$$1]; p2 = points[(idx + 1) % len$$1]; p3 = points[(idx + 2) % len$$1]; } var w2 = w * w; var w3 = w * w2; ret.push([ interpolate(p0[0], p1[0], p2[0], p3[0], w, w2, w3), interpolate(p0[1], p1[1], p2[1], p3[1], w, w2, w3) ]); } return ret; }; /** * 贝塞尔平滑曲线 * @module zrender/shape/util/smoothBezier * @author pissang (https://www.github.com/pissang) * Kener (@Kener-林峰, kener.linfeng@gmail.com) * errorrik (errorrik@gmail.com) */ /** * 贝塞尔平滑曲线 * @alias module:zrender/shape/util/smoothBezier * @param {Array} points 线段顶点数组 * @param {number} smooth 平滑等级, 0-1 * @param {boolean} isLoop * @param {Array} constraint 将计算出来的控制点约束在一个包围盒内 * 比如 [[0, 0], [100, 100]], 这个包围盒会与 * 整个折线的包围盒做一个并集用来约束控制点。 * @param {Array} 计算出来的控制点数组 */ var smoothBezier = function (points, smooth, isLoop, constraint) { var cps = []; var v = []; var v1 = []; var v2 = []; var prevPoint; var nextPoint; var min$$1, max$$1; if (constraint) { min$$1 = [Infinity, Infinity]; max$$1 = [-Infinity, -Infinity]; for (var i = 0, len$$1 = points.length; i < len$$1; i++) { min(min$$1, min$$1, points[i]); max(max$$1, max$$1, points[i]); } // 与指定的包围盒做并集 min(min$$1, min$$1, constraint[0]); max(max$$1, max$$1, constraint[1]); } for (var i = 0, len$$1 = points.length; i < len$$1; i++) { var point = points[i]; if (isLoop) { prevPoint = points[i ? i - 1 : len$$1 - 1]; nextPoint = points[(i + 1) % len$$1]; } else { if (i === 0 || i === len$$1 - 1) { cps.push(clone$1(points[i])); continue; } else { prevPoint = points[i - 1]; nextPoint = points[i + 1]; } } sub(v, nextPoint, prevPoint); // use degree to scale the handle length scale(v, v, smooth); var d0 = distance(point, prevPoint); var d1 = distance(point, nextPoint); var sum = d0 + d1; if (sum !== 0) { d0 /= sum; d1 /= sum; } scale(v1, v, -d0); scale(v2, v, d1); var cp0 = add([], point, v1); var cp1 = add([], point, v2); if (constraint) { max(cp0, cp0, min$$1); min(cp0, cp0, max$$1); max(cp1, cp1, min$$1); min(cp1, cp1, max$$1); } cps.push(cp0); cps.push(cp1); } if (isLoop) { cps.push(cps.shift()); } return cps; }; function buildPath$1(ctx, shape, closePath) { var points = shape.points; var smooth = shape.smooth; if (points && points.length >= 2) { if (smooth && smooth !== 'spline') { var controlPoints = smoothBezier( points, smooth, closePath, shape.smoothConstraint ); ctx.moveTo(points[0][0], points[0][1]); var len = points.length; for (var i = 0; i < (closePath ? len : len - 1); i++) { var cp1 = controlPoints[i * 2]; var cp2 = controlPoints[i * 2 + 1]; var p = points[(i + 1) % len]; ctx.bezierCurveTo( cp1[0], cp1[1], cp2[0], cp2[1], p[0], p[1] ); } } else { if (smooth === 'spline') { points = smoothSpline(points, closePath); } ctx.moveTo(points[0][0], points[0][1]); for (var i = 1, l = points.length; i < l; i++) { ctx.lineTo(points[i][0], points[i][1]); } } closePath && ctx.closePath(); } } /** * 多边形 * @module zrender/shape/Polygon */ var Polygon = Path.extend({ type: 'polygon', shape: { points: null, smooth: false, smoothConstraint: null }, buildPath: function (ctx, shape) { buildPath$1(ctx, shape, true); } }); /** * @module zrender/graphic/shape/Polyline */ var Polyline = Path.extend({ type: 'polyline', shape: { points: null, smooth: false, smoothConstraint: null }, style: { stroke: '#000', fill: null }, buildPath: function (ctx, shape) { buildPath$1(ctx, shape, false); } }); /** * 矩形 * @module zrender/graphic/shape/Rect */ var Rect = Path.extend({ type: 'rect', shape: { // 左上、右上、右下、左下角的半径依次为r1、r2、r3、r4 // r缩写为1 相当于 [1, 1, 1, 1] // r缩写为[1] 相当于 [1, 1, 1, 1] // r缩写为[1, 2] 相当于 [1, 2, 1, 2] // r缩写为[1, 2, 3] 相当于 [1, 2, 3, 2] r: 0, x: 0, y: 0, width: 0, height: 0 }, buildPath: function (ctx, shape) { var x = shape.x; var y = shape.y; var width = shape.width; var height = shape.height; if (!shape.r) { ctx.rect(x, y, width, height); } else { buildPath(ctx, shape); } ctx.closePath(); return; } }); /** * 直线 * @module zrender/graphic/shape/Line */ var Line = Path.extend({ type: 'line', shape: { // Start point x1: 0, y1: 0, // End point x2: 0, y2: 0, percent: 1 }, style: { stroke: '#000', fill: null }, buildPath: function (ctx, shape) { var x1 = shape.x1; var y1 = shape.y1; var x2 = shape.x2; var y2 = shape.y2; var percent = shape.percent; if (percent === 0) { return; } ctx.moveTo(x1, y1); if (percent < 1) { x2 = x1 * (1 - percent) + x2 * percent; y2 = y1 * (1 - percent) + y2 * percent; } ctx.lineTo(x2, y2); }, /** * Get point at percent * @param {number} percent * @return {Array.<number>} */ pointAt: function (p) { var shape = this.shape; return [ shape.x1 * (1 - p) + shape.x2 * p, shape.y1 * (1 - p) + shape.y2 * p ]; } }); /** * 贝塞尔曲线 * @module zrender/shape/BezierCurve */ var out = []; function someVectorAt(shape, t, isTangent) { var cpx2 = shape.cpx2; var cpy2 = shape.cpy2; if (cpx2 === null || cpy2 === null) { return [ (isTangent ? cubicDerivativeAt : cubicAt)(shape.x1, shape.cpx1, shape.cpx2, shape.x2, t), (isTangent ? cubicDerivativeAt : cubicAt)(shape.y1, shape.cpy1, shape.cpy2, shape.y2, t) ]; } else { return [ (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.x1, shape.cpx1, shape.x2, t), (isTangent ? quadraticDerivativeAt : quadraticAt)(shape.y1, shape.cpy1, shape.y2, t) ]; } } var BezierCurve = Path.extend({ type: 'bezier-curve', shape: { x1: 0, y1: 0, x2: 0, y2: 0, cpx1: 0, cpy1: 0, // cpx2: 0, // cpy2: 0 // Curve show percent, for animating percent: 1 }, style: { stroke: '#000', fill: null }, buildPath: function (ctx, shape) { var x1 = shape.x1; var y1 = shape.y1; var x2 = shape.x2; var y2 = shape.y2; var cpx1 = shape.cpx1; var cpy1 = shape.cpy1; var cpx2 = shape.cpx2; var cpy2 = shape.cpy2; var percent = shape.percent; if (percent === 0) { return; } ctx.moveTo(x1, y1); if (cpx2 == null || cpy2 == null) { if (percent < 1) { quadraticSubdivide( x1, cpx1, x2, percent, out ); cpx1 = out[1]; x2 = out[2]; quadraticSubdivide( y1, cpy1, y2, percent, out ); cpy1 = out[1]; y2 = out[2]; } ctx.quadraticCurveTo( cpx1, cpy1, x2, y2 ); } else { if (percent < 1) { cubicSubdivide( x1, cpx1, cpx2, x2, percent, out ); cpx1 = out[1]; cpx2 = out[2]; x2 = out[3]; cubicSubdivide( y1, cpy1, cpy2, y2, percent, out ); cpy1 = out[1]; cpy2 = out[2]; y2 = out[3]; } ctx.bezierCurveTo( cpx1, cpy1, cpx2, cpy2, x2, y2 ); } }, /** * Get point at percent * @param {number} t * @return {Array.<number>} */ pointAt: function (t) { return someVectorAt(this.shape, t, false); }, /** * Get tangent at percent * @param {number} t * @return {Array.<number>} */ tangentAt: function (t) { var p = someVectorAt(this.shape, t, true); return normalize(p, p); } }); /** * 圆弧 * @module zrender/graphic/shape/Arc */ var Arc = Path.extend({ type: 'arc', shape: { cx: 0, cy: 0, r: 0, startAngle: 0, endAngle: Math.PI * 2, clockwise: true }, style: { stroke: '#000', fill: null }, buildPath: function (ctx, shape) { var x = shape.cx; var y = shape.cy; var r = Math.max(shape.r, 0); var startAngle = shape.startAngle; var endAngle = shape.endAngle; var clockwise = shape.clockwise; var unitX = Math.cos(startAngle); var unitY = Math.sin(startAngle); ctx.moveTo(unitX * r + x, unitY * r + y); ctx.arc(x, y, r, startAngle, endAngle, !clockwise); } }); // CompoundPath to improve performance var CompoundPath = Path.extend({ type: 'compound', shape: { paths: null }, _updatePathDirty: function () { var dirtyPath = this.__dirtyPath; var paths = this.shape.paths; for (var i = 0; i < paths.length; i++) { // Mark as dirty if any subpath is dirty dirtyPath = dirtyPath || paths[i].__dirtyPath; } this.__dirtyPath = dirtyPath; this.__dirty = this.__dirty || dirtyPath; }, beforeBrush: function () { this._updatePathDirty(); var paths = this.shape.paths || []; var scale = this.getGlobalScale(); // Update path scale for (var i = 0; i < paths.length; i++) { if (!paths[i].path) { paths[i].createPathProxy(); } paths[i].path.setScale(scale[0], scale[1]); } }, buildPath: function (ctx, shape) { var paths = shape.paths || []; for (var i = 0; i < paths.length; i++) { paths[i].buildPath(ctx, paths[i].shape, true); } }, afterBrush: function () { var paths = this.shape.paths || []; for (var i = 0; i < paths.length; i++) { paths[i].__dirtyPath = false; } }, getBoundingRect: function () { this._updatePathDirty(); return Path.prototype.getBoundingRect.call(this); } }); /** * @param {Array.<Object>} colorStops */ var Gradient = function (colorStops) { this.colorStops = colorStops || []; }; Gradient.prototype = { constructor: Gradient, addColorStop: function (offset, color) { this.colorStops.push({ offset: offset, color: color }); } }; /** * x, y, x2, y2 are all percent from 0 to 1 * @param {number} [x=0] * @param {number} [y=0] * @param {number} [x2=1] * @param {number} [y2=0] * @param {Array.<Object>} colorStops * @param {boolean} [globalCoord=false] */ var LinearGradient = function (x, y, x2, y2, colorStops, globalCoord) { // Should do nothing more in this constructor. Because gradient can be // declard by `color: {type: 'linear', colorStops: ...}`, where // this constructor will not be called. this.x = x == null ? 0 : x; this.y = y == null ? 0 : y; this.x2 = x2 == null ? 1 : x2; this.y2 = y2 == null ? 0 : y2; // Can be cloned this.type = 'linear'; // If use global coord this.global = globalCoord || false; Gradient.call(this, colorStops); }; LinearGradient.prototype = { constructor: LinearGradient }; inherits(LinearGradient, Gradient); /** * x, y, r are all percent from 0 to 1 * @param {number} [x=0.5] * @param {number} [y=0.5] * @param {number} [r=0.5] * @param {Array.<Object>} [colorStops] * @param {boolean} [globalCoord=false] */ var RadialGradient = function (x, y, r, colorStops, globalCoord) { // Should do nothing more in this constructor. Because gradient can be // declard by `color: {type: 'radial', colorStops: ...}`, where // this constructor will not be called. this.x = x == null ? 0.5 : x; this.y = y == null ? 0.5 : y; this.r = r == null ? 0.5 : r; // Can be cloned this.type = 'radial'; // If use global coord this.global = globalCoord || false; Gradient.call(this, colorStops); }; RadialGradient.prototype = { constructor: RadialGradient }; inherits(RadialGradient, Gradient); var round$1 = Math.round; var mathMax$1 = Math.max; var mathMin$1 = Math.min; var EMPTY_OBJ = {}; /** * Extend shape with parameters */ function extendShape(opts) { return Path.extend(opts); } /** * Extend path */ function extendPath(pathData, opts) { return extendFromString(pathData, opts); } /** * Create a path element from path data string * @param {string} pathData * @param {Object} opts * @param {module:zrender/core/BoundingRect} rect * @param {string} [layout=cover] 'center' or 'cover' */ function makePath(pathData, opts, rect, layout) { var path = createFromString(pathData, opts); var boundingRect = path.getBoundingRect(); if (rect) { if (layout === 'center') { rect = centerGraphic(rect, boundingRect); } resizePath(path, rect); } return path; } /** * Create a image element from image url * @param {string} imageUrl image url * @param {Object} opts options * @param {module:zrender/core/BoundingRect} rect constrain rect * @param {string} [layout=cover] 'center' or 'cover' */ function makeImage(imageUrl, rect, layout) { var path = new ZImage({ style: { image: imageUrl, x: rect.x, y: rect.y, width: rect.width, height: rect.height }, onload: function (img) { if (layout === 'center') { var boundingRect = { width: img.width, height: img.height }; path.setStyle(centerGraphic(rect, boundingRect)); } } }); return path; } /** * Get position of centered element in bounding box. * * @param {Object} rect element local bounding box * @param {Object} boundingRect constraint bounding box * @return {Object} element position containing x, y, width, and height */ function centerGraphic(rect, boundingRect) { // Set rect to center, keep width / height ratio. var aspect = boundingRect.width / boundingRect.height; var width = rect.height * aspect; var height; if (width <= rect.width) { height = rect.height; } else { width = rect.width; height = width / aspect; } var cx = rect.x + rect.width / 2; var cy = rect.y + rect.height / 2; return { x: cx - width / 2, y: cy - height / 2, width: width, height: height }; } var mergePath = mergePath$1; /** * Resize a path to fit the rect * @param {module:zrender/graphic/Path} path * @param {Object} rect */ function resizePath(path, rect) { if (!path.applyTransform) { return; } var pathRect = path.getBoundingRect(); var m = pathRect.calculateTransform(rect); path.applyTransform(m); } /** * Sub pixel optimize line for canvas * * @param {Object} param * @param {Object} [param.shape] * @param {number} [param.shape.x1] * @param {number} [param.shape.y1] * @param {number} [param.shape.x2] * @param {number} [param.shape.y2] * @param {Object} [param.style] * @param {number} [param.style.lineWidth] * @return {Object} Modified param */ function subPixelOptimizeLine(param) { var shape = param.shape; var lineWidth = param.style.lineWidth; if (round$1(shape.x1 * 2) === round$1(shape.x2 * 2)) { shape.x1 = shape.x2 = subPixelOptimize(shape.x1, lineWidth, true); } if (round$1(shape.y1 * 2) === round$1(shape.y2 * 2)) { shape.y1 = shape.y2 = subPixelOptimize(shape.y1, lineWidth, true); } return param; } /** * Sub pixel optimize rect for canvas * * @param {Object} param * @param {Object} [param.shape] * @param {number} [param.shape.x] * @param {number} [param.shape.y] * @param {number} [param.shape.width] * @param {number} [param.shape.height] * @param {Object} [param.style] * @param {number} [param.style.lineWidth] * @return {Object} Modified param */ function subPixelOptimizeRect(param) { var shape = param.shape; var lineWidth = param.style.lineWidth; var originX = shape.x; var originY = shape.y; var originWidth = shape.width; var originHeight = shape.height; shape.x = subPixelOptimize(shape.x, lineWidth, true); shape.y = subPixelOptimize(shape.y, lineWidth, true); shape.width = Math.max( subPixelOptimize(originX + originWidth, lineWidth, false) - shape.x, originWidth === 0 ? 0 : 1 ); shape.height = Math.max( subPixelOptimize(originY + originHeight, lineWidth, false) - shape.y, originHeight === 0 ? 0 : 1 ); return param; } /** * Sub pixel optimize for canvas * * @param {number} position Coordinate, such as x, y * @param {number} lineWidth Should be nonnegative integer. * @param {boolean=} positiveOrNegative Default false (negative). * @return {number} Optimized position. */ function subPixelOptimize(position, lineWidth, positiveOrNegative) { // Assure that (position + lineWidth / 2) is near integer edge, // otherwise line will be fuzzy in canvas. var doubledPosition = round$1(position * 2); return (doubledPosition + round$1(lineWidth)) % 2 === 0 ? doubledPosition / 2 : (doubledPosition + (positiveOrNegative ? 1 : -1)) / 2; } function hasFillOrStroke(fillOrStroke) { return fillOrStroke != null && fillOrStroke != 'none'; } function liftColor(color) { return typeof color === 'string' ? lift(color, -0.1) : color; } /** * @private */ function cacheElementStl(el) { if (el.__hoverStlDirty) { var stroke = el.style.stroke; var fill = el.style.fill; // Create hoverStyle on mouseover var hoverStyle = el.__hoverStl; hoverStyle.fill = hoverStyle.fill || (hasFillOrStroke(fill) ? liftColor(fill) : null); hoverStyle.stroke = hoverStyle.stroke || (hasFillOrStroke(stroke) ? liftColor(stroke) : null); var normalStyle = {}; for (var name in hoverStyle) { // See comment in `doSingleEnterHover`. if (hoverStyle[name] != null) { normalStyle[name] = el.style[name]; } } el.__normalStl = normalStyle; el.__hoverStlDirty = false; } } /** * @private */ function doSingleEnterHover(el) { if (el.__isHover) { return; } cacheElementStl(el); if (el.useHoverLayer) { el.__zr && el.__zr.addHover(el, el.__hoverStl); } else { var style = el.style; var insideRollbackOpt = style.insideRollbackOpt; // Consider case: only `position: 'top'` is set on emphasis, then text // color should be returned to `autoColor`, rather than remain '#fff'. // So we should rollback then apply again after style merging. insideRollbackOpt && rollbackInsideStyle(style); // styles can be: // { // label: { // normal: { // show: false, // position: 'outside', // fontSize: 18 // }, // emphasis: { // show: true // } // } // }, // where properties of `emphasis` may not appear in `normal`. We previously use // module:echarts/util/model#defaultEmphasis to merge `normal` to `emphasis`. // But consider rich text and setOption in merge mode, it is impossible to cover // all properties in merge. So we use merge mode when setting style here, where // only properties that is not `null/undefined` can be set. The disadventage: // null/undefined can not be used to remove style any more in `emphasis`. style.extendFrom(el.__hoverStl); // Do not save `insideRollback`. if (insideRollbackOpt) { applyInsideStyle(style, style.insideOriginalTextPosition, insideRollbackOpt); // textFill may be rollbacked to null. if (style.textFill == null) { style.textFill = insideRollbackOpt.autoColor; } } el.dirty(false); el.z2 += 1; } el.__isHover = true; } /** * @inner */ function doSingleLeaveHover(el) { if (!el.__isHover) { return; } var normalStl = el.__normalStl; if (el.useHoverLayer) { el.__zr && el.__zr.removeHover(el); } else { // Consider null/undefined value, should use // `setStyle` but not `extendFrom(stl, true)`. normalStl && el.setStyle(normalStl); el.z2 -= 1; } el.__isHover = false; } /** * @inner */ function doEnterHover(el) { el.type === 'group' ? el.traverse(function (child) { if (child.type !== 'group') { doSingleEnterHover(child); } }) : doSingleEnterHover(el); } function doLeaveHover(el) { el.type === 'group' ? el.traverse(function (child) { if (child.type !== 'group') { doSingleLeaveHover(child); } }) : doSingleLeaveHover(el); } /** * @inner */ function setElementHoverStl(el, hoverStl) { // If element has sepcified hoverStyle, then use it instead of given hoverStyle // Often used when item group has a label element and it's hoverStyle is different el.__hoverStl = el.hoverStyle || hoverStl || {}; el.__hoverStlDirty = true; if (el.__isHover) { cacheElementStl(el); } } /** * @inner */ function onElementMouseOver(e) { if (this.__hoverSilentOnTouch && e.zrByTouch) { return; } // Only if element is not in emphasis status !this.__isEmphasis && doEnterHover(this); } /** * @inner */ function onElementMouseOut(e) { if (this.__hoverSilentOnTouch && e.zrByTouch) { return; } // Only if element is not in emphasis status !this.__isEmphasis && doLeaveHover(this); } /** * @inner */ function enterEmphasis() { this.__isEmphasis = true; doEnterHover(this); } /** * @inner */ function leaveEmphasis() { this.__isEmphasis = false; doLeaveHover(this); } /** * Set hover style of element. * This method can be called repeatly without side-effects. * @param {module:zrender/Element} el * @param {Object} [hoverStyle] * @param {Object} [opt] * @param {boolean} [opt.hoverSilentOnTouch=false] * In touch device, mouseover event will be trigger on touchstart event * (see module:zrender/dom/HandlerProxy). By this mechanism, we can * conviniently use hoverStyle when tap on touch screen without additional * code for compatibility. * But if the chart/component has select feature, which usually also use * hoverStyle, there might be conflict between 'select-highlight' and * 'hover-highlight' especially when roam is enabled (see geo for example). * In this case, hoverSilentOnTouch should be used to disable hover-highlight * on touch device. */ function setHoverStyle(el, hoverStyle, opt) { el.__hoverSilentOnTouch = opt && opt.hoverSilentOnTouch; el.type === 'group' ? el.traverse(function (child) { if (child.type !== 'group') { setElementHoverStl(child, hoverStyle); } }) : setElementHoverStl(el, hoverStyle); // Duplicated function will be auto-ignored, see Eventful.js. el.on('mouseover', onElementMouseOver) .on('mouseout', onElementMouseOut); // Emphasis, normal can be triggered manually el.on('emphasis', enterEmphasis) .on('normal', leaveEmphasis); } /** * @param {Object|module:zrender/graphic/Style} normalStyle * @param {Object} emphasisStyle * @param {module:echarts/model/Model} normalModel * @param {module:echarts/model/Model} emphasisModel * @param {Object} opt Check `opt` of `setTextStyleCommon` to find other props. * @param {Object} [opt.defaultText] * @param {module:echarts/model/Model} [opt.labelFetcher] Fetch text by * `opt.labelFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)` * @param {module:echarts/model/Model} [opt.labelDataIndex] Fetch text by * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)` * @param {module:echarts/model/Model} [opt.labelDimIndex] Fetch text by * `opt.textFetcher.getFormattedLabel(opt.labelDataIndex, 'normal'/'emphasis', null, opt.labelDimIndex)` * @param {Object} [normalSpecified] * @param {Object} [emphasisSpecified] */ function setLabelStyle( normalStyle, emphasisStyle, normalModel, emphasisModel, opt, normalSpecified, emphasisSpecified ) { opt = opt || EMPTY_OBJ; var labelFetcher = opt.labelFetcher; var labelDataIndex = opt.labelDataIndex; var labelDimIndex = opt.labelDimIndex; // This scenario, `label.normal.show = true; label.emphasis.show = false`, // is not supported util someone requests. var showNormal = normalModel.getShallow('show'); var showEmphasis = emphasisModel.getShallow('show'); // Consider performance, only fetch label when necessary. // If `normal.show` is `false` and `emphasis.show` is `true` and `emphasis.formatter` is not set, // label should be displayed, where text is fetched by `normal.formatter` or `opt.defaultText`. var baseText = (showNormal || showEmphasis) ? retrieve2( labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, 'normal', null, labelDimIndex) : null, opt.defaultText ) : null; var normalStyleText = showNormal ? baseText : null; var emphasisStyleText = showEmphasis ? retrieve2( labelFetcher ? labelFetcher.getFormattedLabel(labelDataIndex, 'emphasis', null, labelDimIndex) : null, baseText ) : null; // Optimize: If style.text is null, text will not be drawn. if (normalStyleText != null || emphasisStyleText != null) { // Always set `textStyle` even if `normalStyle.text` is null, because default // values have to be set on `normalStyle`. // If we set default values on `emphasisStyle`, consider case: // Firstly, `setOption(... label: {normal: {text: null}, emphasis: {show: true}} ...);` // Secondly, `setOption(... label: {noraml: {show: true, text: 'abc', color: 'red'} ...);` // Then the 'red' will not work on emphasis. setTextStyle(normalStyle, normalModel, normalSpecified, opt); setTextStyle(emphasisStyle, emphasisModel, emphasisSpecified, opt, true); } normalStyle.text = normalStyleText; emphasisStyle.text = emphasisStyleText; } /** * Set basic textStyle properties. * @param {Object|module:zrender/graphic/Style} textStyle * @param {module:echarts/model/Model} model * @param {Object} [specifiedTextStyle] Can be overrided by settings in model. * @param {Object} [opt] See `opt` of `setTextStyleCommon`. * @param {boolean} [isEmphasis] */ function setTextStyle( textStyle, textStyleModel, specifiedTextStyle, opt, isEmphasis ) { setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis); specifiedTextStyle && extend(textStyle, specifiedTextStyle); textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false); return textStyle; } /** * Set text option in the style. * @deprecated * @param {Object} textStyle * @param {module:echarts/model/Model} labelModel * @param {string|boolean} defaultColor Default text color. * If set as false, it will be processed as a emphasis style. */ function setText(textStyle, labelModel, defaultColor) { var opt = {isRectText: true}; var isEmphasis; if (defaultColor === false) { isEmphasis = true; } else { // Support setting color as 'auto' to get visual color. opt.autoColor = defaultColor; } setTextStyleCommon(textStyle, labelModel, opt, isEmphasis); textStyle.host && textStyle.host.dirty && textStyle.host.dirty(false); } /** * { * disableBox: boolean, Whether diable drawing box of block (outer most). * isRectText: boolean, * autoColor: string, specify a color when color is 'auto', * for textFill, textStroke, textBackgroundColor, and textBorderColor. * If autoColor specified, it is used as default textFill. * useInsideStyle: * `true`: Use inside style (textFill, textStroke, textStrokeWidth) * if `textFill` is not specified. * `false`: Do not use inside style. * `null/undefined`: use inside style if `isRectText` is true and * `textFill` is not specified and textPosition contains `'inside'`. * forceRich: boolean * } */ function setTextStyleCommon(textStyle, textStyleModel, opt, isEmphasis) { // Consider there will be abnormal when merge hover style to normal style if given default value. opt = opt || EMPTY_OBJ; if (opt.isRectText) { var textPosition = textStyleModel.getShallow('position') || (isEmphasis ? null : 'inside'); // 'outside' is not a valid zr textPostion value, but used // in bar series, and magric type should be considered. textPosition === 'outside' && (textPosition = 'top'); textStyle.textPosition = textPosition; textStyle.textOffset = textStyleModel.getShallow('offset'); var labelRotate = textStyleModel.getShallow('rotate'); labelRotate != null && (labelRotate *= Math.PI / 180); textStyle.textRotation = labelRotate; textStyle.textDistance = retrieve2( textStyleModel.getShallow('distance'), isEmphasis ? null : 5 ); } var ecModel = textStyleModel.ecModel; var globalTextStyle = ecModel && ecModel.option.textStyle; // Consider case: // { // data: [{ // value: 12, // label: { // normal: { // rich: { // // no 'a' here but using parent 'a'. // } // } // } // }], // rich: { // a: { ... } // } // } var richItemNames = getRichItemNames(textStyleModel); var richResult; if (richItemNames) { richResult = {}; for (var name in richItemNames) { if (richItemNames.hasOwnProperty(name)) { // Cascade is supported in rich. var richTextStyle = textStyleModel.getModel(['rich', name]); // In rich, never `disableBox`. setTokenTextStyle(richResult[name] = {}, richTextStyle, globalTextStyle, opt, isEmphasis); } } } textStyle.rich = richResult; setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, true); if (opt.forceRich && !opt.textStyle) { opt.textStyle = {}; } return textStyle; } // Consider case: // { // data: [{ // value: 12, // label: { // normal: { // rich: { // // no 'a' here but using parent 'a'. // } // } // } // }], // rich: { // a: { ... } // } // } function getRichItemNames(textStyleModel) { // Use object to remove duplicated names. var richItemNameMap; while (textStyleModel && textStyleModel !== textStyleModel.ecModel) { var rich = (textStyleModel.option || EMPTY_OBJ).rich; if (rich) { richItemNameMap = richItemNameMap || {}; for (var name in rich) { if (rich.hasOwnProperty(name)) { richItemNameMap[name] = 1; } } } textStyleModel = textStyleModel.parentModel; } return richItemNameMap; } function setTokenTextStyle(textStyle, textStyleModel, globalTextStyle, opt, isEmphasis, isBlock) { // In merge mode, default value should not be given. globalTextStyle = !isEmphasis && globalTextStyle || EMPTY_OBJ; textStyle.textFill = getAutoColor(textStyleModel.getShallow('color'), opt) || globalTextStyle.color; textStyle.textStroke = getAutoColor(textStyleModel.getShallow('textBorderColor'), opt) || globalTextStyle.textBorderColor; textStyle.textStrokeWidth = retrieve2( textStyleModel.getShallow('textBorderWidth'), globalTextStyle.textBorderWidth ); if (!isEmphasis) { if (isBlock) { // Always set `insideRollback`, for clearing previous. var originalTextPosition = textStyle.textPosition; textStyle.insideRollback = applyInsideStyle(textStyle, originalTextPosition, opt); // Save original textPosition, because style.textPosition will be repalced by // real location (like [10, 30]) in zrender. textStyle.insideOriginalTextPosition = originalTextPosition; textStyle.insideRollbackOpt = opt; } // Set default finally. if (textStyle.textFill == null) { textStyle.textFill = opt.autoColor; } } // Do not use `getFont` here, because merge should be supported, where // part of these properties may be changed in emphasis style, and the // others should remain their original value got from normal style. textStyle.fontStyle = textStyleModel.getShallow('fontStyle') || globalTextStyle.fontStyle; textStyle.fontWeight = textStyleModel.getShallow('fontWeight') || globalTextStyle.fontWeight; textStyle.fontSize = textStyleModel.getShallow('fontSize') || globalTextStyle.fontSize; textStyle.fontFamily = textStyleModel.getShallow('fontFamily') || globalTextStyle.fontFamily; textStyle.textAlign = textStyleModel.getShallow('align'); textStyle.textVerticalAlign = textStyleModel.getShallow('verticalAlign') || textStyleModel.getShallow('baseline'); textStyle.textLineHeight = textStyleModel.getShallow('lineHeight'); textStyle.textWidth = textStyleModel.getShallow('width'); textStyle.textHeight = textStyleModel.getShallow('height'); textStyle.textTag = textStyleModel.getShallow('tag'); if (!isBlock || !opt.disableBox) { textStyle.textBackgroundColor = getAutoColor(textStyleModel.getShallow('backgroundColor'), opt); textStyle.textPadding = textStyleModel.getShallow('padding'); textStyle.textBorderColor = getAutoColor(textStyleModel.getShallow('borderColor'), opt); textStyle.textBorderWidth = textStyleModel.getShallow('borderWidth'); textStyle.textBorderRadius = textStyleModel.getShallow('borderRadius'); textStyle.textBoxShadowColor = textStyleModel.getShallow('shadowColor'); textStyle.textBoxShadowBlur = textStyleModel.getShallow('shadowBlur'); textStyle.textBoxShadowOffsetX = textStyleModel.getShallow('shadowOffsetX'); textStyle.textBoxShadowOffsetY = textStyleModel.getShallow('shadowOffsetY'); } textStyle.textShadowColor = textStyleModel.getShallow('textShadowColor') || globalTextStyle.textShadowColor; textStyle.textShadowBlur = textStyleModel.getShallow('textShadowBlur') || globalTextStyle.textShadowBlur; textStyle.textShadowOffsetX = textStyleModel.getShallow('textShadowOffsetX') || globalTextStyle.textShadowOffsetX; textStyle.textShadowOffsetY = textStyleModel.getShallow('textShadowOffsetY') || globalTextStyle.textShadowOffsetY; } function getAutoColor(color, opt) { return color !== 'auto' ? color : (opt && opt.autoColor) ? opt.autoColor : null; } function applyInsideStyle(textStyle, textPosition, opt) { var useInsideStyle = opt.useInsideStyle; var insideRollback; if (textStyle.textFill == null && useInsideStyle !== false && (useInsideStyle === true || (opt.isRectText && textPosition // textPosition can be [10, 30] && typeof textPosition === 'string' && textPosition.indexOf('inside') >= 0 ) ) ) { insideRollback = { textFill: null, textStroke: textStyle.textStroke, textStrokeWidth: textStyle.textStrokeWidth }; textStyle.textFill = '#fff'; // Consider text with #fff overflow its container. if (textStyle.textStroke == null) { textStyle.textStroke = opt.autoColor; textStyle.textStrokeWidth == null && (textStyle.textStrokeWidth = 2); } } return insideRollback; } function rollbackInsideStyle(style) { var insideRollback = style.insideRollback; if (insideRollback) { style.textFill = insideRollback.textFill; style.textStroke = insideRollback.textStroke; style.textStrokeWidth = insideRollback.textStrokeWidth; } } function getFont(opt, ecModel) { // ecModel or default text style model. var gTextStyleModel = ecModel || ecModel.getModel('textStyle'); return [ // FIXME in node-canvas fontWeight is before fontStyle opt.fontStyle || gTextStyleModel && gTextStyleModel.getShallow('fontStyle') || '', opt.fontWeight || gTextStyleModel && gTextStyleModel.getShallow('fontWeight') || '', (opt.fontSize || gTextStyleModel && gTextStyleModel.getShallow('fontSize') || 12) + 'px', opt.fontFamily || gTextStyleModel && gTextStyleModel.getShallow('fontFamily') || 'sans-serif' ].join(' '); } function animateOrSetProps(isUpdate, el, props, animatableModel, dataIndex, cb) { if (typeof dataIndex === 'function') { cb = dataIndex; dataIndex = null; } // Do not check 'animation' property directly here. Consider this case: // animation model is an `itemModel`, whose does not have `isAnimationEnabled` // but its parent model (`seriesModel`) does. var animationEnabled = animatableModel && animatableModel.isAnimationEnabled(); if (animationEnabled) { var postfix = isUpdate ? 'Update' : ''; var duration = animatableModel.getShallow('animationDuration' + postfix); var animationEasing = animatableModel.getShallow('animationEasing' + postfix); var animationDelay = animatableModel.getShallow('animationDelay' + postfix); if (typeof animationDelay === 'function') { animationDelay = animationDelay( dataIndex, animatableModel.getAnimationDelayParams ? animatableModel.getAnimationDelayParams(el, dataIndex) : null ); } if (typeof duration === 'function') { duration = duration(dataIndex); } duration > 0 ? el.animateTo(props, duration, animationDelay || 0, animationEasing, cb, !!cb) : (el.stopAnimation(), el.attr(props), cb && cb()); } else { el.stopAnimation(); el.attr(props); cb && cb(); } } /** * Update graphic element properties with or without animation according to the * configuration in series. * * Caution: this method will stop previous animation. * So if do not use this method to one element twice before * animation starts, unless you know what you are doing. * * @param {module:zrender/Element} el * @param {Object} props * @param {module:echarts/model/Model} [animatableModel] * @param {number} [dataIndex] * @param {Function} [cb] * @example * graphic.updateProps(el, { * position: [100, 100] * }, seriesModel, dataIndex, function () { console.log('Animation done!'); }); * // Or * graphic.updateProps(el, { * position: [100, 100] * }, seriesModel, function () { console.log('Animation done!'); }); */ function updateProps(el, props, animatableModel, dataIndex, cb) { animateOrSetProps(true, el, props, animatableModel, dataIndex, cb); } /** * Init graphic element properties with or without animation according to the * configuration in series. * * Caution: this method will stop previous animation. * So if do not use this method to one element twice before * animation starts, unless you know what you are doing. * * @param {module:zrender/Element} el * @param {Object} props * @param {module:echarts/model/Model} [animatableModel] * @param {number} [dataIndex] * @param {Function} cb */ function initProps(el, props, animatableModel, dataIndex, cb) { animateOrSetProps(false, el, props, animatableModel, dataIndex, cb); } /** * Get transform matrix of target (param target), * in coordinate of its ancestor (param ancestor) * * @param {module:zrender/mixin/Transformable} target * @param {module:zrender/mixin/Transformable} [ancestor] */ function getTransform(target, ancestor) { var mat = identity([]); while (target && target !== ancestor) { mul$1(mat, target.getLocalTransform(), mat); target = target.parent; } return mat; } /** * Apply transform to an vertex. * @param {Array.<number>} target [x, y] * @param {Array.<number>|TypedArray.<number>|Object} transform Can be: * + Transform matrix: like [1, 0, 0, 1, 0, 0] * + {position, rotation, scale}, the same as `zrender/Transformable`. * @param {boolean=} invert Whether use invert matrix. * @return {Array.<number>} [x, y] */ function applyTransform$1(target, transform, invert$$1) { if (transform && !isArrayLike(transform)) { transform = Transformable.getLocalTransform(transform); } if (invert$$1) { transform = invert([], transform); } return applyTransform([], target, transform); } /** * @param {string} direction 'left' 'right' 'top' 'bottom' * @param {Array.<number>} transform Transform matrix: like [1, 0, 0, 1, 0, 0] * @param {boolean=} invert Whether use invert matrix. * @return {string} Transformed direction. 'left' 'right' 'top' 'bottom' */ function transformDirection(direction, transform, invert$$1) { // Pick a base, ensure that transform result will not be (0, 0). var hBase = (transform[4] === 0 || transform[5] === 0 || transform[0] === 0) ? 1 : Math.abs(2 * transform[4] / transform[0]); var vBase = (transform[4] === 0 || transform[5] === 0 || transform[2] === 0) ? 1 : Math.abs(2 * transform[4] / transform[2]); var vertex = [ direction === 'left' ? -hBase : direction === 'right' ? hBase : 0, direction === 'top' ? -vBase : direction === 'bottom' ? vBase : 0 ]; vertex = applyTransform$1(vertex, transform, invert$$1); return Math.abs(vertex[0]) > Math.abs(vertex[1]) ? (vertex[0] > 0 ? 'right' : 'left') : (vertex[1] > 0 ? 'bottom' : 'top'); } /** * Apply group transition animation from g1 to g2. * If no animatableModel, no animation. */ function groupTransition(g1, g2, animatableModel, cb) { if (!g1 || !g2) { return; } function getElMap(g) { var elMap = {}; g.traverse(function (el) { if (!el.isGroup && el.anid) { elMap[el.anid] = el; } }); return elMap; } function getAnimatableProps(el) { var obj = { position: clone$1(el.position), rotation: el.rotation }; if (el.shape) { obj.shape = extend({}, el.shape); } return obj; } var elMap1 = getElMap(g1); g2.traverse(function (el) { if (!el.isGroup && el.anid) { var oldEl = elMap1[el.anid]; if (oldEl) { var newProp = getAnimatableProps(el); el.attr(getAnimatableProps(oldEl)); updateProps(el, newProp, animatableModel, el.dataIndex); } // else { // if (el.previousProps) { // graphic.updateProps // } // } } }); } /** * @param {Array.<Array.<number>>} points Like: [[23, 44], [53, 66], ...] * @param {Object} rect {x, y, width, height} * @return {Array.<Array.<number>>} A new clipped points. */ function clipPointsByRect(points, rect) { return map(points, function (point) { var x = point[0]; x = mathMax$1(x, rect.x); x = mathMin$1(x, rect.x + rect.width); var y = point[1]; y = mathMax$1(y, rect.y); y = mathMin$1(y, rect.y + rect.height); return [x, y]; }); } /** * @param {Object} targetRect {x, y, width, height} * @param {Object} rect {x, y, width, height} * @return {Object} A new clipped rect. If rect size are negative, return undefined. */ function clipRectByRect(targetRect, rect) { var x = mathMax$1(targetRect.x, rect.x); var x2 = mathMin$1(targetRect.x + targetRect.width, rect.x + rect.width); var y = mathMax$1(targetRect.y, rect.y); var y2 = mathMin$1(targetRect.y + targetRect.height, rect.y + rect.height); if (x2 >= x && y2 >= y) { return { x: x, y: y, width: x2 - x, height: y2 - y }; } } /** * @param {string} iconStr Support 'image://' or 'path://' or direct svg path. * @param {Object} [opt] Properties of `module:zrender/Element`, except `style`. * @param {Object} [rect] {x, y, width, height} * @return {module:zrender/Element} Icon path or image element. */ function createIcon(iconStr, opt, rect) { opt = extend({rectHover: true}, opt); var style = opt.style = {strokeNoScale: true}; rect = rect || {x: -1, y: -1, width: 2, height: 2}; if (iconStr) { return iconStr.indexOf('image://') === 0 ? ( style.image = iconStr.slice(8), defaults(style, rect), new ZImage(opt) ) : ( makePath( iconStr.replace('path://', ''), opt, rect, 'center' ) ); } } var graphic = (Object.freeze || Object)({ extendShape: extendShape, extendPath: extendPath, makePath: makePath, makeImage: makeImage, mergePath: mergePath, resizePath: resizePath, subPixelOptimizeLine: subPixelOptimizeLine, subPixelOptimizeRect: subPixelOptimizeRect, subPixelOptimize: subPixelOptimize, setHoverStyle: setHoverStyle, setLabelStyle: setLabelStyle, setTextStyle: setTextStyle, setText: setText, getFont: getFont, updateProps: updateProps, initProps: initProps, getTransform: getTransform, applyTransform: applyTransform$1, transformDirection: transformDirection, groupTransition: groupTransition, clipPointsByRect: clipPointsByRect, clipRectByRect: clipRectByRect, createIcon: createIcon, Group: Group, Image: ZImage, Text: Text, Circle: Circle, Sector: Sector, Ring: Ring, Polygon: Polygon, Polyline: Polyline, Rect: Rect, Line: Line, BezierCurve: BezierCurve, Arc: Arc, CompoundPath: CompoundPath, LinearGradient: LinearGradient, RadialGradient: RadialGradient, BoundingRect: BoundingRect }); var PATH_COLOR = ['textStyle', 'color']; var textStyleMixin = { /** * Get color property or get color from option.textStyle.color * @param {boolean} [isEmphasis] * @return {string} */ getTextColor: function (isEmphasis) { var ecModel = this.ecModel; return this.getShallow('color') || ( (!isEmphasis && ecModel) ? ecModel.get(PATH_COLOR) : null ); }, /** * Create font string from fontStyle, fontWeight, fontSize, fontFamily * @return {string} */ getFont: function () { return getFont({ fontStyle: this.getShallow('fontStyle'), fontWeight: this.getShallow('fontWeight'), fontSize: this.getShallow('fontSize'), fontFamily: this.getShallow('fontFamily') }, this.ecModel); }, getTextRect: function (text) { return getBoundingRect( text, this.getFont(), this.getShallow('align'), this.getShallow('verticalAlign') || this.getShallow('baseline'), this.getShallow('padding'), this.getShallow('rich'), this.getShallow('truncateText') ); } }; var getItemStyle = makeStyleMapper( [ ['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'], ['textPosition'], ['textAlign'] ] ); var itemStyleMixin = { getItemStyle: function (excludes, includes) { var style = getItemStyle(this, excludes, includes); var lineDash = this.getBorderLineDash(); lineDash && (style.lineDash = lineDash); return style; }, getBorderLineDash: function () { var lineType = this.get('borderType'); return (lineType === 'solid' || lineType == null) ? null : (lineType === 'dashed' ? [5, 5] : [1, 1]); } }; /** * @module echarts/model/Model */ var mixin$1 = mixin; /** * @alias module:echarts/model/Model * @constructor * @param {Object} option * @param {module:echarts/model/Model} [parentModel] * @param {module:echarts/model/Global} [ecModel] */ function Model(option, parentModel, ecModel) { /** * @type {module:echarts/model/Model} * @readOnly */ this.parentModel = parentModel; /** * @type {module:echarts/model/Global} * @readOnly */ this.ecModel = ecModel; /** * @type {Object} * @protected */ this.option = option; // Simple optimization // if (this.init) { // if (arguments.length <= 4) { // this.init(option, parentModel, ecModel, extraOpt); // } // else { // this.init.apply(this, arguments); // } // } } Model.prototype = { constructor: Model, /** * Model 的初始化函数 * @param {Object} option */ init: null, /** * 从新的 Option merge */ mergeOption: function (option) { merge(this.option, option, true); }, /** * @param {string|Array.<string>} path * @param {boolean} [ignoreParent=false] * @return {*} */ get: function (path, ignoreParent) { if (path == null) { return this.option; } return doGet( this.option, this.parsePath(path), !ignoreParent && getParent(this, path) ); }, /** * @param {string} key * @param {boolean} [ignoreParent=false] * @return {*} */ getShallow: function (key, ignoreParent) { var option = this.option; var val = option == null ? option : option[key]; var parentModel = !ignoreParent && getParent(this, key); if (val == null && parentModel) { val = parentModel.getShallow(key); } return val; }, /** * @param {string|Array.<string>} [path] * @param {module:echarts/model/Model} [parentModel] * @return {module:echarts/model/Model} */ getModel: function (path, parentModel) { var obj = path == null ? this.option : doGet(this.option, path = this.parsePath(path)); var thisParentModel; parentModel = parentModel || ( (thisParentModel = getParent(this, path)) && thisParentModel.getModel(path) ); return new Model(obj, parentModel, this.ecModel); }, /** * If model has option */ isEmpty: function () { return this.option == null; }, restoreData: function () {}, // Pending clone: function () { var Ctor = this.constructor; return new Ctor(clone(this.option)); }, setReadOnly: function (properties) { }, // If path is null/undefined, return null/undefined. parsePath: function(path) { if (typeof path === 'string') { path = path.split('.'); } return path; }, /** * @param {Function} getParentMethod * param {Array.<string>|string} path * return {module:echarts/model/Model} */ customizeGetParent: function (getParentMethod) { set$1(this, 'getParent', getParentMethod); }, isAnimationEnabled: function () { if (!env$1.node) { if (this.option.animation != null) { return !!this.option.animation; } else if (this.parentModel) { return this.parentModel.isAnimationEnabled(); } } } }; function doGet(obj, pathArr, parentModel) { for (var i = 0; i < pathArr.length; i++) { // Ignore empty if (!pathArr[i]) { continue; } // obj could be number/string/... (like 0) obj = (obj && typeof obj === 'object') ? obj[pathArr[i]] : null; if (obj == null) { break; } } if (obj == null && parentModel) { obj = parentModel.get(pathArr); } return obj; } // `path` can be null/undefined function getParent(model, path) { var getParentMethod = get(model, 'getParent'); return getParentMethod ? getParentMethod.call(model, path) : model.parentModel; } // Enable Model.extend. enableClassExtend(Model); mixin$1(Model, lineStyleMixin); mixin$1(Model, areaStyleMixin); mixin$1(Model, textStyleMixin); mixin$1(Model, itemStyleMixin); var each$3 = each$1; var isObject$2 = isObject; /** * If value is not array, then translate it to array. * @param {*} value * @return {Array} [value] or value */ function normalizeToArray(value) { return value instanceof Array ? value : value == null ? [] : [value]; } /** * Sync default option between normal and emphasis like `position` and `show` * In case some one will write code like * label: { * normal: { * show: false, * position: 'outside', * fontSize: 18 * }, * emphasis: { * show: true * } * } * @param {Object} opt * @param {Array.<string>} subOpts */ function defaultEmphasis(opt, subOpts) { if (opt) { var emphasisOpt = opt.emphasis = opt.emphasis || {}; var normalOpt = opt.normal = opt.normal || {}; // Default emphasis option from normal for (var i = 0, len = subOpts.length; i < len; i++) { var subOptName = subOpts[i]; if (!emphasisOpt.hasOwnProperty(subOptName) && normalOpt.hasOwnProperty(subOptName) ) { emphasisOpt[subOptName] = normalOpt[subOptName]; } } } } var TEXT_STYLE_OPTIONS = [ 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily', 'rich', 'tag', 'color', 'textBorderColor', 'textBorderWidth', 'width', 'height', 'lineHeight', 'align', 'verticalAlign', 'baseline', 'shadowColor', 'shadowBlur', 'shadowOffsetX', 'shadowOffsetY', 'textShadowColor', 'textShadowBlur', 'textShadowOffsetX', 'textShadowOffsetY', 'backgroundColor', 'borderColor', 'borderWidth', 'borderRadius', 'padding' ]; // modelUtil.LABEL_OPTIONS = modelUtil.TEXT_STYLE_OPTIONS.concat([ // 'position', 'offset', 'rotate', 'origin', 'show', 'distance', 'formatter', // 'fontStyle', 'fontWeight', 'fontSize', 'fontFamily', // // FIXME: deprecated, check and remove it. // 'textStyle' // ]); /** * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}] * This helper method retieves value from data. * @param {string|number|Date|Array|Object} dataItem * @return {number|string|Date|Array.<number|string|Date>} */ function getDataItemValue(dataItem) { // Performance sensitive. return dataItem && (dataItem.value == null ? dataItem : dataItem.value); } /** * data could be [12, 2323, {value: 223}, [1221, 23], {value: [2, 23]}] * This helper method determine if dataItem has extra option besides value * @param {string|number|Date|Array|Object} dataItem */ function isDataItemOption(dataItem) { return isObject$2(dataItem) && !(dataItem instanceof Array); // // markLine data can be array // && !(dataItem[0] && isObject(dataItem[0]) && !(dataItem[0] instanceof Array)); } /** * This helper method convert value in data. * @param {string|number|Date} value * @param {Object|string} [dimInfo] If string (like 'x'), dimType defaults 'number'. */ function converDataValue(value, dimInfo) { // Performance sensitive. var dimType = dimInfo && dimInfo.type; if (dimType === 'ordinal') { return value; } if (dimType === 'time' // spead up when using timestamp && typeof value !== 'number' && value != null && value !== '-' ) { value = +parseDate(value); } // dimType defaults 'number'. // If dimType is not ordinal and value is null or undefined or NaN or '-', // parse to NaN. return (value == null || value === '') ? NaN : +value; // If string (like '-'), using '+' parse to NaN } /** * Create a model proxy to be used in tooltip for edge data, markLine data, markPoint data. * @param {module:echarts/data/List} data * @param {Object} opt * @param {string} [opt.seriesIndex] * @param {Object} [opt.name] * @param {Object} [opt.mainType] * @param {Object} [opt.subType] */ // PENDING A little ugly var dataFormatMixin = { /** * Get params for formatter * @param {number} dataIndex * @param {string} [dataType] * @return {Object} */ getDataParams: function (dataIndex, dataType) { var data = this.getData(dataType); var rawValue = this.getRawValue(dataIndex, dataType); var rawDataIndex = data.getRawIndex(dataIndex); var name = data.getName(dataIndex, true); var itemOpt = data.getRawDataItem(dataIndex); var color = data.getItemVisual(dataIndex, 'color'); return { componentType: this.mainType, componentSubType: this.subType, seriesType: this.mainType === 'series' ? this.subType : null, seriesIndex: this.seriesIndex, seriesId: this.id, seriesName: this.name, name: name, dataIndex: rawDataIndex, data: itemOpt, dataType: dataType, value: rawValue, color: color, marker: getTooltipMarker(color), // Param name list for mapping `a`, `b`, `c`, `d`, `e` $vars: ['seriesName', 'name', 'value'] }; }, /** * Format label * @param {number} dataIndex * @param {string} [status='normal'] 'normal' or 'emphasis' * @param {string} [dataType] * @param {number} [dimIndex] * @param {string} [labelProp='label'] * @return {string} */ getFormattedLabel: function (dataIndex, status, dataType, dimIndex, labelProp) { status = status || 'normal'; var data = this.getData(dataType); var itemModel = data.getItemModel(dataIndex); var params = this.getDataParams(dataIndex, dataType); if (dimIndex != null && (params.value instanceof Array)) { params.value = params.value[dimIndex]; } var formatter = itemModel.get([labelProp || 'label', status, 'formatter']); if (typeof formatter === 'function') { params.status = status; return formatter(params); } else if (typeof formatter === 'string') { return formatTpl(formatter, params); } }, /** * Get raw value in option * @param {number} idx * @param {string} [dataType] * @return {Object} */ getRawValue: function (idx, dataType) { var data = this.getData(dataType); var dataItem = data.getRawDataItem(idx); if (dataItem != null) { return (isObject$2(dataItem) && !(dataItem instanceof Array)) ? dataItem.value : dataItem; } }, /** * Should be implemented. * @param {number} dataIndex * @param {boolean} [multipleSeries=false] * @param {number} [dataType] * @return {string} tooltip string */ formatTooltip: noop }; /** * Mapping to exists for merge. * * @public * @param {Array.<Object>|Array.<module:echarts/model/Component>} exists * @param {Object|Array.<Object>} newCptOptions * @return {Array.<Object>} Result, like [{exist: ..., option: ...}, {}], * index of which is the same as exists. */ function mappingToExists(exists, newCptOptions) { // Mapping by the order by original option (but not order of // new option) in merge mode. Because we should ensure // some specified index (like xAxisIndex) is consistent with // original option, which is easy to understand, espatially in // media query. And in most case, merge option is used to // update partial option but not be expected to change order. newCptOptions = (newCptOptions || []).slice(); var result = map(exists || [], function (obj, index) { return {exist: obj}; }); // Mapping by id or name if specified. each$3(newCptOptions, function (cptOption, index) { if (!isObject$2(cptOption)) { return; } // id has highest priority. for (var i = 0; i < result.length; i++) { if (!result[i].option // Consider name: two map to one. && cptOption.id != null && result[i].exist.id === cptOption.id + '' ) { result[i].option = cptOption; newCptOptions[index] = null; return; } } for (var i = 0; i < result.length; i++) { var exist = result[i].exist; if (!result[i].option // Consider name: two map to one. // Can not match when both ids exist but different. && (exist.id == null || cptOption.id == null) && cptOption.name != null && !isIdInner(cptOption) && !isIdInner(exist) && exist.name === cptOption.name + '' ) { result[i].option = cptOption; newCptOptions[index] = null; return; } } }); // Otherwise mapping by index. each$3(newCptOptions, function (cptOption, index) { if (!isObject$2(cptOption)) { return; } var i = 0; for (; i < result.length; i++) { var exist = result[i].exist; if (!result[i].option // Existing model that already has id should be able to // mapped to (because after mapping performed model may // be assigned with a id, whish should not affect next // mapping), except those has inner id. && !isIdInner(exist) // Caution: // Do not overwrite id. But name can be overwritten, // because axis use name as 'show label text'. // 'exist' always has id and name and we dont // need to check it. && cptOption.id == null ) { result[i].option = cptOption; break; } } if (i >= result.length) { result.push({option: cptOption}); } }); return result; } /** * Make id and name for mapping result (result of mappingToExists) * into `keyInfo` field. * * @public * @param {Array.<Object>} Result, like [{exist: ..., option: ...}, {}], * which order is the same as exists. * @return {Array.<Object>} The input. */ function makeIdAndName(mapResult) { // We use this id to hash component models and view instances // in echarts. id can be specified by user, or auto generated. // The id generation rule ensures new view instance are able // to mapped to old instance when setOption are called in // no-merge mode. So we generate model id by name and plus // type in view id. // name can be duplicated among components, which is convenient // to specify multi components (like series) by one name. // Ensure that each id is distinct. var idMap = createHashMap(); each$3(mapResult, function (item, index) { var existCpt = item.exist; existCpt && idMap.set(existCpt.id, item); }); each$3(mapResult, function (item, index) { var opt = item.option; assert( !opt || opt.id == null || !idMap.get(opt.id) || idMap.get(opt.id) === item, 'id duplicates: ' + (opt && opt.id) ); opt && opt.id != null && idMap.set(opt.id, item); !item.keyInfo && (item.keyInfo = {}); }); // Make name and id. each$3(mapResult, function (item, index) { var existCpt = item.exist; var opt = item.option; var keyInfo = item.keyInfo; if (!isObject$2(opt)) { return; } // name can be overwitten. Consider case: axis.name = '20km'. // But id generated by name will not be changed, which affect // only in that case: setOption with 'not merge mode' and view // instance will be recreated, which can be accepted. keyInfo.name = opt.name != null ? opt.name + '' : existCpt ? existCpt.name : '\0-'; // name may be displayed on screen, so use '-'. if (existCpt) { keyInfo.id = existCpt.id; } else if (opt.id != null) { keyInfo.id = opt.id + ''; } else { // Consider this situatoin: // optionA: [{name: 'a'}, {name: 'a'}, {..}] // optionB [{..}, {name: 'a'}, {name: 'a'}] // Series with the same name between optionA and optionB // should be mapped. var idNum = 0; do { keyInfo.id = '\0' + keyInfo.name + '\0' + idNum++; } while (idMap.get(keyInfo.id)); } idMap.set(keyInfo.id, item); }); } /** * @public * @param {Object} cptOption * @return {boolean} */ function isIdInner(cptOption) { return isObject$2(cptOption) && cptOption.id && (cptOption.id + '').indexOf('\0_ec_\0') === 0; } /** * A helper for removing duplicate items between batchA and batchB, * and in themselves, and categorize by series. * * @param {Array.<Object>} batchA Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...] * @param {Array.<Object>} batchB Like: [{seriesId: 2, dataIndex: [32, 4, 5]}, ...] * @return {Array.<Array.<Object>, Array.<Object>>} result: [resultBatchA, resultBatchB] */ /** * @param {module:echarts/data/List} data * @param {Object} payload Contains dataIndex (means rawIndex) / dataIndexInside / name * each of which can be Array or primary type. * @return {number|Array.<number>} dataIndex If not found, return undefined/null. */ function queryDataIndex(data, payload) { if (payload.dataIndexInside != null) { return payload.dataIndexInside; } else if (payload.dataIndex != null) { return isArray(payload.dataIndex) ? map(payload.dataIndex, function (value) { return data.indexOfRawIndex(value); }) : data.indexOfRawIndex(payload.dataIndex); } else if (payload.name != null) { return isArray(payload.name) ? map(payload.name, function (value) { return data.indexOfName(value); }) : data.indexOfName(payload.name); } } /** * Enable property storage to any host object. * Notice: Serialization is not supported. * * For example: * var get = modelUitl.makeGetter(); * * function some(hostObj) { * get(hostObj)._someProperty = 1212; * ... * } * * @return {Function} */ /** * @param {module:echarts/model/Global} ecModel * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex, seriesId, seriesName, * geoIndex, geoId, geoName, * bmapIndex, bmapId, bmapName, * xAxisIndex, xAxisId, xAxisName, * yAxisIndex, yAxisId, yAxisName, * gridIndex, gridId, gridName, * ... (can be extended) * } * Each properties can be number|string|Array.<number>|Array.<string> * For example, a finder could be * { * seriesIndex: 3, * geoId: ['aa', 'cc'], * gridName: ['xx', 'rr'] * } * xxxIndex can be set as 'all' (means all xxx) or 'none' (means not specify) * If nothing or null/undefined specified, return nothing. * @param {Object} [opt] * @param {string} [opt.defaultMainType] * @param {Array.<string>} [opt.includeMainTypes] * @return {Object} result like: * { * seriesModels: [seriesModel1, seriesModel2], * seriesModel: seriesModel1, // The first model * geoModels: [geoModel1, geoModel2], * geoModel: geoModel1, // The first model * ... * } */ function parseFinder(ecModel, finder, opt) { if (isString(finder)) { var obj = {}; obj[finder + 'Index'] = 0; finder = obj; } var defaultMainType = opt && opt.defaultMainType; if (defaultMainType && !has(finder, defaultMainType + 'Index') && !has(finder, defaultMainType + 'Id') && !has(finder, defaultMainType + 'Name') ) { finder[defaultMainType + 'Index'] = 0; } var result = {}; each$3(finder, function (value, key) { var value = finder[key]; // Exclude 'dataIndex' and other illgal keys. if (key === 'dataIndex' || key === 'dataIndexInside') { result[key] = value; return; } var parsedKey = key.match(/^(\w+)(Index|Id|Name)$/) || []; var mainType = parsedKey[1]; var queryType = (parsedKey[2] || '').toLowerCase(); if (!mainType || !queryType || value == null || (queryType === 'index' && value === 'none') || (opt && opt.includeMainTypes && indexOf(opt.includeMainTypes, mainType) < 0) ) { return; } var queryParam = {mainType: mainType}; if (queryType !== 'index' || value !== 'all') { queryParam[queryType] = value; } var models = ecModel.queryComponents(queryParam); result[mainType + 'Models'] = models; result[mainType + 'Model'] = models[0]; }); return result; } /** * @see {module:echarts/data/helper/completeDimensions} * @param {module:echarts/data/List} data * @param {string|number} dataDim * @return {string} */ function dataDimToCoordDim(data, dataDim) { var dimensions = data.dimensions; dataDim = data.getDimension(dataDim); for (var i = 0; i < dimensions.length; i++) { var dimItem = data.getDimensionInfo(dimensions[i]); if (dimItem.name === dataDim) { return dimItem.coordDim; } } } /** * @see {module:echarts/data/helper/completeDimensions} * @param {module:echarts/data/List} data * @param {string} coordDim * @return {Array.<string>} data dimensions on the coordDim. */ function coordDimToDataDim(data, coordDim) { var dataDim = []; each$3(data.dimensions, function (dimName) { var dimItem = data.getDimensionInfo(dimName); if (dimItem.coordDim === coordDim) { dataDim[dimItem.coordDimIndex] = dimItem.name; } }); return dataDim; } /** * @see {module:echarts/data/helper/completeDimensions} * @param {module:echarts/data/List} data * @param {string} otherDim Can be `otherDims` * like 'label' or 'tooltip'. * @return {Array.<string>} data dimensions on the otherDim. */ function otherDimToDataDim(data, otherDim) { var dataDim = []; each$3(data.dimensions, function (dimName) { var dimItem = data.getDimensionInfo(dimName); var otherDims = dimItem.otherDims; var dimIndex = otherDims[otherDim]; if (dimIndex != null && dimIndex !== false) { dataDim[dimIndex] = dimItem.name; } }); return dataDim; } function has(obj, prop) { return obj && obj.hasOwnProperty(prop); } var base = 0; var DELIMITER = '_'; /** * @public * @param {string} type * @return {string} */ function getUID(type) { // Considering the case of crossing js context, // use Math.random to make id as unique as possible. return [(type || ''), base++, Math.random()].join(DELIMITER); } /** * @inner */ function enableSubTypeDefaulter(entity) { var subTypeDefaulters = {}; entity.registerSubTypeDefaulter = function (componentType, defaulter) { componentType = parseClassType$1(componentType); subTypeDefaulters[componentType.main] = defaulter; }; entity.determineSubType = function (componentType, option) { var type = option.type; if (!type) { var componentTypeMain = parseClassType$1(componentType).main; if (entity.hasSubTypes(componentType) && subTypeDefaulters[componentTypeMain]) { type = subTypeDefaulters[componentTypeMain](option); } } return type; }; return entity; } /** * Topological travel on Activity Network (Activity On Vertices). * Dependencies is defined in Model.prototype.dependencies, like ['xAxis', 'yAxis']. * * If 'xAxis' or 'yAxis' is absent in componentTypeList, just ignore it in topology. * * If there is circle dependencey, Error will be thrown. * */ function enableTopologicalTravel(entity, dependencyGetter) { /** * @public * @param {Array.<string>} targetNameList Target Component type list. * Can be ['aa', 'bb', 'aa.xx'] * @param {Array.<string>} fullNameList By which we can build dependency graph. * @param {Function} callback Params: componentType, dependencies. * @param {Object} context Scope of callback. */ entity.topologicalTravel = function (targetNameList, fullNameList, callback, context) { if (!targetNameList.length) { return; } var result = makeDepndencyGraph(fullNameList); var graph = result.graph; var stack = result.noEntryList; var targetNameSet = {}; each$1(targetNameList, function (name) { targetNameSet[name] = true; }); while (stack.length) { var currComponentType = stack.pop(); var currVertex = graph[currComponentType]; var isInTargetNameSet = !!targetNameSet[currComponentType]; if (isInTargetNameSet) { callback.call(context, currComponentType, currVertex.originalDeps.slice()); delete targetNameSet[currComponentType]; } each$1( currVertex.successor, isInTargetNameSet ? removeEdgeAndAdd : removeEdge ); } each$1(targetNameSet, function () { throw new Error('Circle dependency may exists'); }); function removeEdge(succComponentType) { graph[succComponentType].entryCount--; if (graph[succComponentType].entryCount === 0) { stack.push(succComponentType); } } // Consider this case: legend depends on series, and we call // chart.setOption({series: [...]}), where only series is in option. // If we do not have 'removeEdgeAndAdd', legendModel.mergeOption will // not be called, but only sereis.mergeOption is called. Thus legend // have no chance to update its local record about series (like which // name of series is available in legend). function removeEdgeAndAdd(succComponentType) { targetNameSet[succComponentType] = true; removeEdge(succComponentType); } }; /** * DepndencyGraph: {Object} * key: conponentType, * value: { * successor: [conponentTypes...], * originalDeps: [conponentTypes...], * entryCount: {number} * } */ function makeDepndencyGraph(fullNameList) { var graph = {}; var noEntryList = []; each$1(fullNameList, function (name) { var thisItem = createDependencyGraphItem(graph, name); var originalDeps = thisItem.originalDeps = dependencyGetter(name); var availableDeps = getAvailableDependencies(originalDeps, fullNameList); thisItem.entryCount = availableDeps.length; if (thisItem.entryCount === 0) { noEntryList.push(name); } each$1(availableDeps, function (dependentName) { if (indexOf(thisItem.predecessor, dependentName) < 0) { thisItem.predecessor.push(dependentName); } var thatItem = createDependencyGraphItem(graph, dependentName); if (indexOf(thatItem.successor, dependentName) < 0) { thatItem.successor.push(name); } }); }); return {graph: graph, noEntryList: noEntryList}; } function createDependencyGraphItem(graph, name) { if (!graph[name]) { graph[name] = {predecessor: [], successor: []}; } return graph[name]; } function getAvailableDependencies(originalDeps, fullNameList) { var availableDeps = []; each$1(originalDeps, function (dep) { indexOf(fullNameList, dep) >= 0 && availableDeps.push(dep); }); return availableDeps; } } // Layout helpers for each component positioning var each$4 = each$1; /** * @public */ var LOCATION_PARAMS = [ 'left', 'right', 'top', 'bottom', 'width', 'height' ]; /** * @public */ var HV_NAMES = [ ['width', 'left', 'right'], ['height', 'top', 'bottom'] ]; function boxLayout(orient, group, gap, maxWidth, maxHeight) { var x = 0; var y = 0; if (maxWidth == null) { maxWidth = Infinity; } if (maxHeight == null) { maxHeight = Infinity; } var currentLineMaxSize = 0; group.eachChild(function (child, idx) { var position = child.position; var rect = child.getBoundingRect(); var nextChild = group.childAt(idx + 1); var nextChildRect = nextChild && nextChild.getBoundingRect(); var nextX; var nextY; if (orient === 'horizontal') { var moveX = rect.width + (nextChildRect ? (-nextChildRect.x + rect.x) : 0); nextX = x + moveX; // Wrap when width exceeds maxWidth or meet a `newline` group // FIXME compare before adding gap? if (nextX > maxWidth || child.newline) { x = 0; nextX = moveX; y += currentLineMaxSize + gap; currentLineMaxSize = rect.height; } else { // FIXME: consider rect.y is not `0`? currentLineMaxSize = Math.max(currentLineMaxSize, rect.height); } } else { var moveY = rect.height + (nextChildRect ? (-nextChildRect.y + rect.y) : 0); nextY = y + moveY; // Wrap when width exceeds maxHeight or meet a `newline` group if (nextY > maxHeight || child.newline) { x += currentLineMaxSize + gap; y = 0; nextY = moveY; currentLineMaxSize = rect.width; } else { currentLineMaxSize = Math.max(currentLineMaxSize, rect.width); } } if (child.newline) { return; } position[0] = x; position[1] = y; orient === 'horizontal' ? (x = nextX + gap) : (y = nextY + gap); }); } /** * VBox or HBox layouting * @param {string} orient * @param {module:zrender/container/Group} group * @param {number} gap * @param {number} [width=Infinity] * @param {number} [height=Infinity] */ /** * VBox layouting * @param {module:zrender/container/Group} group * @param {number} gap * @param {number} [width=Infinity] * @param {number} [height=Infinity] */ var vbox = curry(boxLayout, 'vertical'); /** * HBox layouting * @param {module:zrender/container/Group} group * @param {number} gap * @param {number} [width=Infinity] * @param {number} [height=Infinity] */ var hbox = curry(boxLayout, 'horizontal'); /** * If x or x2 is not specified or 'center' 'left' 'right', * the width would be as long as possible. * If y or y2 is not specified or 'middle' 'top' 'bottom', * the height would be as long as possible. * * @param {Object} positionInfo * @param {number|string} [positionInfo.x] * @param {number|string} [positionInfo.y] * @param {number|string} [positionInfo.x2] * @param {number|string} [positionInfo.y2] * @param {Object} containerRect {width, height} * @param {string|number} margin * @return {Object} {width, height} */ /** * Parse position info. * * @param {Object} positionInfo * @param {number|string} [positionInfo.left] * @param {number|string} [positionInfo.top] * @param {number|string} [positionInfo.right] * @param {number|string} [positionInfo.bottom] * @param {number|string} [positionInfo.width] * @param {number|string} [positionInfo.height] * @param {number|string} [positionInfo.aspect] Aspect is width / height * @param {Object} containerRect * @param {string|number} [margin] * * @return {module:zrender/core/BoundingRect} */ function getLayoutRect( positionInfo, containerRect, margin ) { margin = normalizeCssArray$1(margin || 0); var containerWidth = containerRect.width; var containerHeight = containerRect.height; var left = parsePercent$1(positionInfo.left, containerWidth); var top = parsePercent$1(positionInfo.top, containerHeight); var right = parsePercent$1(positionInfo.right, containerWidth); var bottom = parsePercent$1(positionInfo.bottom, containerHeight); var width = parsePercent$1(positionInfo.width, containerWidth); var height = parsePercent$1(positionInfo.height, containerHeight); var verticalMargin = margin[2] + margin[0]; var horizontalMargin = margin[1] + margin[3]; var aspect = positionInfo.aspect; // If width is not specified, calculate width from left and right if (isNaN(width)) { width = containerWidth - right - horizontalMargin - left; } if (isNaN(height)) { height = containerHeight - bottom - verticalMargin - top; } if (aspect != null) { // If width and height are not given // 1. Graph should not exceeds the container // 2. Aspect must be keeped // 3. Graph should take the space as more as possible // FIXME // Margin is not considered, because there is no case that both // using margin and aspect so far. if (isNaN(width) && isNaN(height)) { if (aspect > containerWidth / containerHeight) { width = containerWidth * 0.8; } else { height = containerHeight * 0.8; } } // Calculate width or height with given aspect if (isNaN(width)) { width = aspect * height; } if (isNaN(height)) { height = width / aspect; } } // If left is not specified, calculate left from right and width if (isNaN(left)) { left = containerWidth - right - width - horizontalMargin; } if (isNaN(top)) { top = containerHeight - bottom - height - verticalMargin; } // Align left and top switch (positionInfo.left || positionInfo.right) { case 'center': left = containerWidth / 2 - width / 2 - margin[3]; break; case 'right': left = containerWidth - width - horizontalMargin; break; } switch (positionInfo.top || positionInfo.bottom) { case 'middle': case 'center': top = containerHeight / 2 - height / 2 - margin[0]; break; case 'bottom': top = containerHeight - height - verticalMargin; break; } // If something is wrong and left, top, width, height are calculated as NaN left = left || 0; top = top || 0; if (isNaN(width)) { // Width may be NaN if only one value is given except width width = containerWidth - horizontalMargin - left - (right || 0); } if (isNaN(height)) { // Height may be NaN if only one value is given except height height = containerHeight - verticalMargin - top - (bottom || 0); } var rect = new BoundingRect(left + margin[3], top + margin[0], width, height); rect.margin = margin; return rect; } /** * Position a zr element in viewport * Group position is specified by either * {left, top}, {right, bottom} * If all properties exists, right and bottom will be igonred. * * Logic: * 1. Scale (against origin point in parent coord) * 2. Rotate (against origin point in parent coord) * 3. Traslate (with el.position by this method) * So this method only fixes the last step 'Traslate', which does not affect * scaling and rotating. * * If be called repeatly with the same input el, the same result will be gotten. * * @param {module:zrender/Element} el Should have `getBoundingRect` method. * @param {Object} positionInfo * @param {number|string} [positionInfo.left] * @param {number|string} [positionInfo.top] * @param {number|string} [positionInfo.right] * @param {number|string} [positionInfo.bottom] * @param {number|string} [positionInfo.width] Only for opt.boundingModel: 'raw' * @param {number|string} [positionInfo.height] Only for opt.boundingModel: 'raw' * @param {Object} containerRect * @param {string|number} margin * @param {Object} [opt] * @param {Array.<number>} [opt.hv=[1,1]] Only horizontal or only vertical. * @param {Array.<number>} [opt.boundingMode='all'] * Specify how to calculate boundingRect when locating. * 'all': Position the boundingRect that is transformed and uioned * both itself and its descendants. * This mode simplies confine the elements in the bounding * of their container (e.g., using 'right: 0'). * 'raw': Position the boundingRect that is not transformed and only itself. * This mode is useful when you want a element can overflow its * container. (Consider a rotated circle needs to be located in a corner.) * In this mode positionInfo.width/height can only be number. */ /** * @param {Object} option Contains some of the properties in HV_NAMES. * @param {number} hvIdx 0: horizontal; 1: vertical. */ /** * Consider Case: * When defulat option has {left: 0, width: 100}, and we set {right: 0} * through setOption or media query, using normal zrUtil.merge will cause * {right: 0} does not take effect. * * @example * ComponentModel.extend({ * init: function () { * ... * var inputPositionParams = layout.getLayoutParams(option); * this.mergeOption(inputPositionParams); * }, * mergeOption: function (newOption) { * newOption && zrUtil.merge(thisOption, newOption, true); * layout.mergeLayoutParam(thisOption, newOption); * } * }); * * @param {Object} targetOption * @param {Object} newOption * @param {Object|string} [opt] * @param {boolean|Array.<boolean>} [opt.ignoreSize=false] Used for the components * that width (or height) should not be calculated by left and right (or top and bottom). */ function mergeLayoutParam(targetOption, newOption, opt) { !isObject(opt) && (opt = {}); var ignoreSize = opt.ignoreSize; !isArray(ignoreSize) && (ignoreSize = [ignoreSize, ignoreSize]); var hResult = merge$$1(HV_NAMES[0], 0); var vResult = merge$$1(HV_NAMES[1], 1); copy(HV_NAMES[0], targetOption, hResult); copy(HV_NAMES[1], targetOption, vResult); function merge$$1(names, hvIdx) { var newParams = {}; var newValueCount = 0; var merged = {}; var mergedValueCount = 0; var enoughParamNumber = 2; each$4(names, function (name) { merged[name] = targetOption[name]; }); each$4(names, function (name) { // Consider case: newOption.width is null, which is // set by user for removing width setting. hasProp(newOption, name) && (newParams[name] = merged[name] = newOption[name]); hasValue(newParams, name) && newValueCount++; hasValue(merged, name) && mergedValueCount++; }); if (ignoreSize[hvIdx]) { // Only one of left/right is premitted to exist. if (hasValue(newOption, names[1])) { merged[names[2]] = null; } else if (hasValue(newOption, names[2])) { merged[names[1]] = null; } return merged; } // Case: newOption: {width: ..., right: ...}, // or targetOption: {right: ...} and newOption: {width: ...}, // There is no conflict when merged only has params count // little than enoughParamNumber. if (mergedValueCount === enoughParamNumber || !newValueCount) { return merged; } // Case: newOption: {width: ..., right: ...}, // Than we can make sure user only want those two, and ignore // all origin params in targetOption. else if (newValueCount >= enoughParamNumber) { return newParams; } else { // Chose another param from targetOption by priority. for (var i = 0; i < names.length; i++) { var name = names[i]; if (!hasProp(newParams, name) && hasProp(targetOption, name)) { newParams[name] = targetOption[name]; break; } } return newParams; } } function hasProp(obj, name) { return obj.hasOwnProperty(name); } function hasValue(obj, name) { return obj[name] != null && obj[name] !== 'auto'; } function copy(names, target, source) { each$4(names, function (name) { target[name] = source[name]; }); } } /** * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object. * @param {Object} source * @return {Object} Result contains those props. */ function getLayoutParams(source) { return copyLayoutParams({}, source); } /** * Retrieve 'left', 'right', 'top', 'bottom', 'width', 'height' from object. * @param {Object} source * @return {Object} Result contains those props. */ function copyLayoutParams(target, source) { source && target && each$4(LOCATION_PARAMS, function (name) { source.hasOwnProperty(name) && (target[name] = source[name]); }); return target; } var boxLayoutMixin = { getBoxLayoutParams: function () { return { left: this.get('left'), top: this.get('top'), right: this.get('right'), bottom: this.get('bottom'), width: this.get('width'), height: this.get('height') }; } }; /** * Component model * * @module echarts/model/Component */ var arrayPush = Array.prototype.push; /** * @alias module:echarts/model/Component * @constructor * @param {Object} option * @param {module:echarts/model/Model} parentModel * @param {module:echarts/model/Model} ecModel */ var ComponentModel = Model.extend({ type: 'component', /** * @readOnly * @type {string} */ id: '', /** * @readOnly */ name: '', /** * @readOnly * @type {string} */ mainType: '', /** * @readOnly * @type {string} */ subType: '', /** * @readOnly * @type {number} */ componentIndex: 0, /** * @type {Object} * @protected */ defaultOption: null, /** * @type {module:echarts/model/Global} * @readOnly */ ecModel: null, /** * key: componentType * value: Component model list, can not be null. * @type {Object.<string, Array.<module:echarts/model/Model>>} * @readOnly */ dependentModels: [], /** * @type {string} * @readOnly */ uid: null, /** * Support merge layout params. * Only support 'box' now (left/right/top/bottom/width/height). * @type {string|Object} Object can be {ignoreSize: true} * @readOnly */ layoutMode: null, $constructor: function (option, parentModel, ecModel, extraOpt) { Model.call(this, option, parentModel, ecModel, extraOpt); this.uid = getUID('componentModel'); }, init: function (option, parentModel, ecModel, extraOpt) { this.mergeDefaultAndTheme(option, ecModel); }, mergeDefaultAndTheme: function (option, ecModel) { var layoutMode = this.layoutMode; var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; var themeModel = ecModel.getTheme(); merge(option, themeModel.get(this.mainType)); merge(option, this.getDefaultOption()); if (layoutMode) { mergeLayoutParam(option, inputPositionParams, layoutMode); } }, mergeOption: function (option, extraOpt) { merge(this.option, option, true); var layoutMode = this.layoutMode; if (layoutMode) { mergeLayoutParam(this.option, option, layoutMode); } }, // Hooker after init or mergeOption optionUpdated: function (newCptOption, isInit) {}, getDefaultOption: function () { if (!hasOwn(this, '__defaultOption')) { var optList = []; var Class = this.constructor; while (Class) { var opt = Class.prototype.defaultOption; opt && optList.push(opt); Class = Class.superClass; } var defaultOption = {}; for (var i = optList.length - 1; i >= 0; i--) { defaultOption = merge(defaultOption, optList[i], true); } set$1(this, '__defaultOption', defaultOption); } return get(this, '__defaultOption'); }, getReferringComponents: function (mainType) { return this.ecModel.queryComponents({ mainType: mainType, index: this.get(mainType + 'Index', true), id: this.get(mainType + 'Id', true) }); } }); // Reset ComponentModel.extend, add preConstruct. // clazzUtil.enableClassExtend( // ComponentModel, // function (option, parentModel, ecModel, extraOpt) { // // Set dependentModels, componentIndex, name, id, mainType, subType. // zrUtil.extend(this, extraOpt); // this.uid = componentUtil.getUID('componentModel'); // // this.setReadOnly([ // // 'type', 'id', 'uid', 'name', 'mainType', 'subType', // // 'dependentModels', 'componentIndex' // // ]); // } // ); // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on. enableClassManagement( ComponentModel, {registerWhenExtend: true} ); enableSubTypeDefaulter(ComponentModel); // Add capability of ComponentModel.topologicalTravel. enableTopologicalTravel(ComponentModel, getDependencies); function getDependencies(componentType) { var deps = []; each$1(ComponentModel.getClassesByMainType(componentType), function (Clazz) { arrayPush.apply(deps, Clazz.prototype.dependencies || []); }); // Ensure main type return map(deps, function (type) { return parseClassType$1(type).main; }); } mixin(ComponentModel, boxLayoutMixin); var platform = ''; // Navigator not exists in node if (typeof navigator !== 'undefined') { platform = navigator.platform || ''; } var globalDefault = { // 全图默认背景 // backgroundColor: 'rgba(0,0,0,0)', // https://dribbble.com/shots/1065960-Infographic-Pie-chart-visualization // color: ['#5793f3', '#d14a61', '#fd9c35', '#675bba', '#fec42c', '#dd4444', '#d4df5a', '#cd4870'], // 浅色 // color: ['#bcd3bb', '#e88f70', '#edc1a5', '#9dc5c8', '#e1e8c8', '#7b7c68', '#e5b5b5', '#f0b489', '#928ea8', '#bda29a'], // color: ['#cc5664', '#9bd6ec', '#ea946e', '#8acaaa', '#f1ec64', '#ee8686', '#a48dc1', '#5da6bc', '#b9dcae'], // 深色 color: ['#c23531','#2f4554', '#61a0a8', '#d48265', '#91c7ae','#749f83', '#ca8622', '#bda29a','#6e7074', '#546570', '#c4ccd3'], // 默认需要 Grid 配置项 // grid: {}, // 主题,主题 textStyle: { // color: '#000', // decoration: 'none', // PENDING fontFamily: platform.match(/^Win/) ? 'Microsoft YaHei' : 'sans-serif', // fontFamily: 'Arial, Verdana, sans-serif', fontSize: 12, fontStyle: 'normal', fontWeight: 'normal' }, // http://blogs.adobe.com/webplatform/2014/02/24/using-blend-modes-in-html-canvas/ // https://developer.mozilla.org/en-US/docs/Web/API/CanvasRenderingContext2D/globalCompositeOperation // Default is source-over blendMode: null, animation: 'auto', animationDuration: 1000, animationDurationUpdate: 300, animationEasing: 'exponentialOut', animationEasingUpdate: 'cubicOut', animationThreshold: 2000, // Configuration for progressive/incremental rendering progressiveThreshold: 3000, progressive: 400, // Threshold of if use single hover layer to optimize. // It is recommended that `hoverLayerThreshold` is equivalent to or less than // `progressiveThreshold`, otherwise hover will cause restart of progressive, // which is unexpected. // see example <echarts/test/heatmap-large.html>. hoverLayerThreshold: 3000, // See: module:echarts/scale/Time useUTC: false }; var colorPaletteMixin = { clearColorPalette: function () { set$1(this, 'colorIdx', 0); set$1(this, 'colorNameMap', {}); }, getColorFromPalette: function (name, scope) { scope = scope || this; var colorIdx = get(scope, 'colorIdx') || 0; var colorNameMap = get(scope, 'colorNameMap') || set$1(scope, 'colorNameMap', {}); // Use `hasOwnProperty` to avoid conflict with Object.prototype. if (colorNameMap.hasOwnProperty(name)) { return colorNameMap[name]; } var colorPalette = this.get('color', true) || []; if (!colorPalette.length) { return; } var color = colorPalette[colorIdx]; if (name) { colorNameMap[name] = color; } set$1(scope, 'colorIdx', (colorIdx + 1) % colorPalette.length); return color; } }; /** * ECharts global model * * @module {echarts/model/Global} */ /** * Caution: If the mechanism should be changed some day, these cases * should be considered: * * (1) In `merge option` mode, if using the same option to call `setOption` * many times, the result should be the same (try our best to ensure that). * (2) In `merge option` mode, if a component has no id/name specified, it * will be merged by index, and the result sequence of the components is * consistent to the original sequence. * (3) `reset` feature (in toolbox). Find detailed info in comments about * `mergeOption` in module:echarts/model/OptionManager. */ var each$2 = each$1; var filter$1 = filter; var map$1 = map; var isArray$1 = isArray; var indexOf$1 = indexOf; var isObject$1 = isObject; var OPTION_INNER_KEY = '\0_ec_inner'; /** * @alias module:echarts/model/Global * * @param {Object} option * @param {module:echarts/model/Model} parentModel * @param {Object} theme */ var GlobalModel = Model.extend({ constructor: GlobalModel, init: function (option, parentModel, theme, optionManager) { theme = theme || {}; this.option = null; // Mark as not initialized. /** * @type {module:echarts/model/Model} * @private */ this._theme = new Model(theme); /** * @type {module:echarts/model/OptionManager} */ this._optionManager = optionManager; }, setOption: function (option, optionPreprocessorFuncs) { assert( !(OPTION_INNER_KEY in option), 'please use chart.getOption()' ); this._optionManager.setOption(option, optionPreprocessorFuncs); this.resetOption(null); }, /** * @param {string} type null/undefined: reset all. * 'recreate': force recreate all. * 'timeline': only reset timeline option * 'media': only reset media query option * @return {boolean} Whether option changed. */ resetOption: function (type) { var optionChanged = false; var optionManager = this._optionManager; if (!type || type === 'recreate') { var baseOption = optionManager.mountOption(type === 'recreate'); if (!this.option || type === 'recreate') { initBase.call(this, baseOption); } else { this.restoreData(); this.mergeOption(baseOption); } optionChanged = true; } if (type === 'timeline' || type === 'media') { this.restoreData(); } if (!type || type === 'recreate' || type === 'timeline') { var timelineOption = optionManager.getTimelineOption(this); timelineOption && (this.mergeOption(timelineOption), optionChanged = true); } if (!type || type === 'recreate' || type === 'media') { var mediaOptions = optionManager.getMediaOption(this, this._api); if (mediaOptions.length) { each$2(mediaOptions, function (mediaOption) { this.mergeOption(mediaOption, optionChanged = true); }, this); } } return optionChanged; }, /** * @protected */ mergeOption: function (newOption) { var option = this.option; var componentsMap = this._componentsMap; var newCptTypes = []; // 如果不存在对应的 component model 则直接 merge each$2(newOption, function (componentOption, mainType) { if (componentOption == null) { return; } if (!ComponentModel.hasClass(mainType)) { option[mainType] = option[mainType] == null ? clone(componentOption) : merge(option[mainType], componentOption, true); } else { newCptTypes.push(mainType); } }); // FIXME OPTION 同步是否要改回原来的 ComponentModel.topologicalTravel( newCptTypes, ComponentModel.getAllClassMainTypes(), visitComponent, this ); this._seriesIndices = this._seriesIndices || []; function visitComponent(mainType, dependencies) { var newCptOptionList = normalizeToArray(newOption[mainType]); var mapResult = mappingToExists( componentsMap.get(mainType), newCptOptionList ); makeIdAndName(mapResult); // Set mainType and complete subType. each$2(mapResult, function (item, index) { var opt = item.option; if (isObject$1(opt)) { item.keyInfo.mainType = mainType; item.keyInfo.subType = determineSubType(mainType, opt, item.exist); } }); var dependentModels = getComponentsByTypes( componentsMap, dependencies ); option[mainType] = []; componentsMap.set(mainType, []); each$2(mapResult, function (resultItem, index) { var componentModel = resultItem.exist; var newCptOption = resultItem.option; assert( isObject$1(newCptOption) || componentModel, 'Empty component definition' ); // Consider where is no new option and should be merged using {}, // see removeEdgeAndAdd in topologicalTravel and // ComponentModel.getAllClassMainTypes. if (!newCptOption) { componentModel.mergeOption({}, this); componentModel.optionUpdated({}, false); } else { var ComponentModelClass = ComponentModel.getClass( mainType, resultItem.keyInfo.subType, true ); if (componentModel && componentModel instanceof ComponentModelClass) { componentModel.name = resultItem.keyInfo.name; componentModel.mergeOption(newCptOption, this); componentModel.optionUpdated(newCptOption, false); } else { // PENDING Global as parent ? var extraOpt = extend( { dependentModels: dependentModels, componentIndex: index }, resultItem.keyInfo ); componentModel = new ComponentModelClass( newCptOption, this, this, extraOpt ); extend(componentModel, extraOpt); componentModel.init(newCptOption, this, this, extraOpt); // Call optionUpdated after init. // newCptOption has been used as componentModel.option // and may be merged with theme and default, so pass null // to avoid confusion. componentModel.optionUpdated(null, true); } } componentsMap.get(mainType)[index] = componentModel; option[mainType][index] = componentModel.option; }, this); // Backup series for filtering. if (mainType === 'series') { this._seriesIndices = createSeriesIndices(componentsMap.get('series')); } } }, /** * Get option for output (cloned option and inner info removed) * @public * @return {Object} */ getOption: function () { var option = clone(this.option); each$2(option, function (opts, mainType) { if (ComponentModel.hasClass(mainType)) { var opts = normalizeToArray(opts); for (var i = opts.length - 1; i >= 0; i--) { // Remove options with inner id. if (isIdInner(opts[i])) { opts.splice(i, 1); } } option[mainType] = opts; } }); delete option[OPTION_INNER_KEY]; return option; }, /** * @return {module:echarts/model/Model} */ getTheme: function () { return this._theme; }, /** * @param {string} mainType * @param {number} [idx=0] * @return {module:echarts/model/Component} */ getComponent: function (mainType, idx) { var list = this._componentsMap.get(mainType); if (list) { return list[idx || 0]; } }, /** * If none of index and id and name used, return all components with mainType. * @param {Object} condition * @param {string} condition.mainType * @param {string} [condition.subType] If ignore, only query by mainType * @param {number|Array.<number>} [condition.index] Either input index or id or name. * @param {string|Array.<string>} [condition.id] Either input index or id or name. * @param {string|Array.<string>} [condition.name] Either input index or id or name. * @return {Array.<module:echarts/model/Component>} */ queryComponents: function (condition) { var mainType = condition.mainType; if (!mainType) { return []; } var index = condition.index; var id = condition.id; var name = condition.name; var cpts = this._componentsMap.get(mainType); if (!cpts || !cpts.length) { return []; } var result; if (index != null) { if (!isArray$1(index)) { index = [index]; } result = filter$1(map$1(index, function (idx) { return cpts[idx]; }), function (val) { return !!val; }); } else if (id != null) { var isIdArray = isArray$1(id); result = filter$1(cpts, function (cpt) { return (isIdArray && indexOf$1(id, cpt.id) >= 0) || (!isIdArray && cpt.id === id); }); } else if (name != null) { var isNameArray = isArray$1(name); result = filter$1(cpts, function (cpt) { return (isNameArray && indexOf$1(name, cpt.name) >= 0) || (!isNameArray && cpt.name === name); }); } else { // Return all components with mainType result = cpts.slice(); } return filterBySubType(result, condition); }, /** * The interface is different from queryComponents, * which is convenient for inner usage. * * @usage * var result = findComponents( * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}} * ); * var result = findComponents( * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}} * ); * var result = findComponents( * {mainType: 'series'}, * function (model, index) {...} * ); * // result like [component0, componnet1, ...] * * @param {Object} condition * @param {string} condition.mainType Mandatory. * @param {string} [condition.subType] Optional. * @param {Object} [condition.query] like {xxxIndex, xxxId, xxxName}, * where xxx is mainType. * If query attribute is null/undefined or has no index/id/name, * do not filtering by query conditions, which is convenient for * no-payload situations or when target of action is global. * @param {Function} [condition.filter] parameter: component, return boolean. * @return {Array.<module:echarts/model/Component>} */ findComponents: function (condition) { var query = condition.query; var mainType = condition.mainType; var queryCond = getQueryCond(query); var result = queryCond ? this.queryComponents(queryCond) : this._componentsMap.get(mainType); return doFilter(filterBySubType(result, condition)); function getQueryCond(q) { var indexAttr = mainType + 'Index'; var idAttr = mainType + 'Id'; var nameAttr = mainType + 'Name'; return q && ( q[indexAttr] != null || q[idAttr] != null || q[nameAttr] != null ) ? { mainType: mainType, // subType will be filtered finally. index: q[indexAttr], id: q[idAttr], name: q[nameAttr] } : null; } function doFilter(res) { return condition.filter ? filter$1(res, condition.filter) : res; } }, /** * @usage * eachComponent('legend', function (legendModel, index) { * ... * }); * eachComponent(function (componentType, model, index) { * // componentType does not include subType * // (componentType is 'xxx' but not 'xxx.aa') * }); * eachComponent( * {mainType: 'dataZoom', query: {dataZoomId: 'abc'}}, * function (model, index) {...} * ); * eachComponent( * {mainType: 'series', subType: 'pie', query: {seriesName: 'uio'}}, * function (model, index) {...} * ); * * @param {string|Object=} mainType When mainType is object, the definition * is the same as the method 'findComponents'. * @param {Function} cb * @param {*} context */ eachComponent: function (mainType, cb, context) { var componentsMap = this._componentsMap; if (typeof mainType === 'function') { context = cb; cb = mainType; componentsMap.each(function (components, componentType) { each$2(components, function (component, index) { cb.call(context, componentType, component, index); }); }); } else if (isString(mainType)) { each$2(componentsMap.get(mainType), cb, context); } else if (isObject$1(mainType)) { var queryResult = this.findComponents(mainType); each$2(queryResult, cb, context); } }, /** * @param {string} name * @return {Array.<module:echarts/model/Series>} */ getSeriesByName: function (name) { var series = this._componentsMap.get('series'); return filter$1(series, function (oneSeries) { return oneSeries.name === name; }); }, /** * @param {number} seriesIndex * @return {module:echarts/model/Series} */ getSeriesByIndex: function (seriesIndex) { return this._componentsMap.get('series')[seriesIndex]; }, /** * @param {string} subType * @return {Array.<module:echarts/model/Series>} */ getSeriesByType: function (subType) { var series = this._componentsMap.get('series'); return filter$1(series, function (oneSeries) { return oneSeries.subType === subType; }); }, /** * @return {Array.<module:echarts/model/Series>} */ getSeries: function () { return this._componentsMap.get('series').slice(); }, /** * After filtering, series may be different * frome raw series. * * @param {Function} cb * @param {*} context */ eachSeries: function (cb, context) { assertSeriesInitialized(this); each$2(this._seriesIndices, function (rawSeriesIndex) { var series = this._componentsMap.get('series')[rawSeriesIndex]; cb.call(context, series, rawSeriesIndex); }, this); }, /** * Iterate raw series before filtered. * * @param {Function} cb * @param {*} context */ eachRawSeries: function (cb, context) { each$2(this._componentsMap.get('series'), cb, context); }, /** * After filtering, series may be different. * frome raw series. * * @parma {string} subType * @param {Function} cb * @param {*} context */ eachSeriesByType: function (subType, cb, context) { assertSeriesInitialized(this); each$2(this._seriesIndices, function (rawSeriesIndex) { var series = this._componentsMap.get('series')[rawSeriesIndex]; if (series.subType === subType) { cb.call(context, series, rawSeriesIndex); } }, this); }, /** * Iterate raw series before filtered of given type. * * @parma {string} subType * @param {Function} cb * @param {*} context */ eachRawSeriesByType: function (subType, cb, context) { return each$2(this.getSeriesByType(subType), cb, context); }, /** * @param {module:echarts/model/Series} seriesModel */ isSeriesFiltered: function (seriesModel) { assertSeriesInitialized(this); return indexOf(this._seriesIndices, seriesModel.componentIndex) < 0; }, /** * @return {Array.<number>} */ getCurrentSeriesIndices: function () { return (this._seriesIndices || []).slice(); }, /** * @param {Function} cb * @param {*} context */ filterSeries: function (cb, context) { assertSeriesInitialized(this); var filteredSeries = filter$1( this._componentsMap.get('series'), cb, context ); this._seriesIndices = createSeriesIndices(filteredSeries); }, restoreData: function () { var componentsMap = this._componentsMap; this._seriesIndices = createSeriesIndices(componentsMap.get('series')); var componentTypes = []; componentsMap.each(function (components, componentType) { componentTypes.push(componentType); }); ComponentModel.topologicalTravel( componentTypes, ComponentModel.getAllClassMainTypes(), function (componentType, dependencies) { each$2(componentsMap.get(componentType), function (component) { component.restoreData(); }); } ); } }); /** * @inner */ function mergeTheme(option, theme) { each$1(theme, function (themeItem, name) { // 如果有 component model 则把具体的 merge 逻辑交给该 model 处理 if (!ComponentModel.hasClass(name)) { if (typeof themeItem === 'object') { option[name] = !option[name] ? clone(themeItem) : merge(option[name], themeItem, false); } else { if (option[name] == null) { option[name] = themeItem; } } } }); } function initBase(baseOption) { baseOption = baseOption; // Using OPTION_INNER_KEY to mark that this option can not be used outside, // i.e. `chart.setOption(chart.getModel().option);` is forbiden. this.option = {}; this.option[OPTION_INNER_KEY] = 1; /** * Init with series: [], in case of calling findSeries method * before series initialized. * @type {Object.<string, Array.<module:echarts/model/Model>>} * @private */ this._componentsMap = createHashMap({series: []}); /** * Mapping between filtered series list and raw series list. * key: filtered series indices, value: raw series indices. * @type {Array.<nubmer>} * @private */ this._seriesIndices = null; mergeTheme(baseOption, this._theme.option); // TODO Needs clone when merging to the unexisted property merge(baseOption, globalDefault, false); this.mergeOption(baseOption); } /** * @inner * @param {Array.<string>|string} types model types * @return {Object} key: {string} type, value: {Array.<Object>} models */ function getComponentsByTypes(componentsMap, types) { if (!isArray(types)) { types = types ? [types] : []; } var ret = {}; each$2(types, function (type) { ret[type] = (componentsMap.get(type) || []).slice(); }); return ret; } /** * @inner */ function determineSubType(mainType, newCptOption, existComponent) { var subType = newCptOption.type ? newCptOption.type : existComponent ? existComponent.subType // Use determineSubType only when there is no existComponent. : ComponentModel.determineSubType(mainType, newCptOption); // tooltip, markline, markpoint may always has no subType return subType; } /** * @inner */ function createSeriesIndices(seriesModels) { return map$1(seriesModels, function (series) { return series.componentIndex; }) || []; } /** * @inner */ function filterBySubType(components, condition) { // Using hasOwnProperty for restrict. Consider // subType is undefined in user payload. return condition.hasOwnProperty('subType') ? filter$1(components, function (cpt) { return cpt.subType === condition.subType; }) : components; } /** * @inner */ function assertSeriesInitialized(ecModel) { // Components that use _seriesIndices should depends on series component, // which make sure that their initialization is after series. if (__DEV__) { if (!ecModel._seriesIndices) { throw new Error('Option should contains series.'); } } } mixin(GlobalModel, colorPaletteMixin); var echartsAPIList = [ 'getDom', 'getZr', 'getWidth', 'getHeight', 'getDevicePixelRatio', 'dispatchAction', 'isDisposed', 'on', 'off', 'getDataURL', 'getConnectedDataURL', 'getModel', 'getOption', 'getViewOfComponentModel', 'getViewOfSeriesModel' ]; // And `getCoordinateSystems` and `getComponentByElement` will be injected in echarts.js function ExtensionAPI(chartInstance) { each$1(echartsAPIList, function (name) { this[name] = bind(chartInstance[name], chartInstance); }, this); } var coordinateSystemCreators = {}; function CoordinateSystemManager() { this._coordinateSystems = []; } CoordinateSystemManager.prototype = { constructor: CoordinateSystemManager, create: function (ecModel, api) { var coordinateSystems = []; each$1(coordinateSystemCreators, function (creater, type) { var list = creater.create(ecModel, api); coordinateSystems = coordinateSystems.concat(list || []); }); this._coordinateSystems = coordinateSystems; }, update: function (ecModel, api) { each$1(this._coordinateSystems, function (coordSys) { // FIXME MUST have coordSys.update && coordSys.update(ecModel, api); }); }, getCoordinateSystems: function () { return this._coordinateSystems.slice(); } }; CoordinateSystemManager.register = function (type, coordinateSystemCreator) { coordinateSystemCreators[type] = coordinateSystemCreator; }; CoordinateSystemManager.get = function (type) { return coordinateSystemCreators[type]; }; /** * ECharts option manager * * @module {echarts/model/OptionManager} */ var each$5 = each$1; var clone$2 = clone; var map$2 = map; var merge$1 = merge; var QUERY_REG = /^(min|max)?(.+)$/; /** * TERM EXPLANATIONS: * * [option]: * * An object that contains definitions of components. For example: * var option = { * title: {...}, * legend: {...}, * visualMap: {...}, * series: [ * {data: [...]}, * {data: [...]}, * ... * ] * }; * * [rawOption]: * * An object input to echarts.setOption. 'rawOption' may be an * 'option', or may be an object contains multi-options. For example: * var option = { * baseOption: { * title: {...}, * legend: {...}, * series: [ * {data: [...]}, * {data: [...]}, * ... * ] * }, * timeline: {...}, * options: [ * {title: {...}, series: {data: [...]}}, * {title: {...}, series: {data: [...]}}, * ... * ], * media: [ * { * query: {maxWidth: 320}, * option: {series: {x: 20}, visualMap: {show: false}} * }, * { * query: {minWidth: 320, maxWidth: 720}, * option: {series: {x: 500}, visualMap: {show: true}} * }, * { * option: {series: {x: 1200}, visualMap: {show: true}} * } * ] * }; * * @alias module:echarts/model/OptionManager * @param {module:echarts/ExtensionAPI} api */ function OptionManager(api) { /** * @private * @type {module:echarts/ExtensionAPI} */ this._api = api; /** * @private * @type {Array.<number>} */ this._timelineOptions = []; /** * @private * @type {Array.<Object>} */ this._mediaList = []; /** * @private * @type {Object} */ this._mediaDefault; /** * -1, means default. * empty means no media. * @private * @type {Array.<number>} */ this._currentMediaIndices = []; /** * @private * @type {Object} */ this._optionBackup; /** * @private * @type {Object} */ this._newBaseOption; } // timeline.notMerge is not supported in ec3. Firstly there is rearly // case that notMerge is needed. Secondly supporting 'notMerge' requires // rawOption cloned and backuped when timeline changed, which does no // good to performance. What's more, that both timeline and setOption // method supply 'notMerge' brings complex and some problems. // Consider this case: // (step1) chart.setOption({timeline: {notMerge: false}, ...}, false); // (step2) chart.setOption({timeline: {notMerge: true}, ...}, false); OptionManager.prototype = { constructor: OptionManager, /** * @public * @param {Object} rawOption Raw option. * @param {module:echarts/model/Global} ecModel * @param {Array.<Function>} optionPreprocessorFuncs * @return {Object} Init option */ setOption: function (rawOption, optionPreprocessorFuncs) { rawOption = clone$2(rawOption, true); // FIXME // 如果 timeline options 或者 media 中设置了某个属性,而baseOption中没有设置,则进行警告。 var oldOptionBackup = this._optionBackup; var newParsedOption = parseRawOption.call( this, rawOption, optionPreprocessorFuncs, !oldOptionBackup ); this._newBaseOption = newParsedOption.baseOption; // For setOption at second time (using merge mode); if (oldOptionBackup) { // Only baseOption can be merged. mergeOption(oldOptionBackup.baseOption, newParsedOption.baseOption); // For simplicity, timeline options and media options do not support merge, // that is, if you `setOption` twice and both has timeline options, the latter // timeline opitons will not be merged to the formers, but just substitude them. if (newParsedOption.timelineOptions.length) { oldOptionBackup.timelineOptions = newParsedOption.timelineOptions; } if (newParsedOption.mediaList.length) { oldOptionBackup.mediaList = newParsedOption.mediaList; } if (newParsedOption.mediaDefault) { oldOptionBackup.mediaDefault = newParsedOption.mediaDefault; } } else { this._optionBackup = newParsedOption; } }, /** * @param {boolean} isRecreate * @return {Object} */ mountOption: function (isRecreate) { var optionBackup = this._optionBackup; // TODO // 如果没有reset功能则不clone。 this._timelineOptions = map$2(optionBackup.timelineOptions, clone$2); this._mediaList = map$2(optionBackup.mediaList, clone$2); this._mediaDefault = clone$2(optionBackup.mediaDefault); this._currentMediaIndices = []; return clone$2(isRecreate // this._optionBackup.baseOption, which is created at the first `setOption` // called, and is merged into every new option by inner method `mergeOption` // each time `setOption` called, can be only used in `isRecreate`, because // its reliability is under suspicion. In other cases option merge is // performed by `model.mergeOption`. ? optionBackup.baseOption : this._newBaseOption ); }, /** * @param {module:echarts/model/Global} ecModel * @return {Object} */ getTimelineOption: function (ecModel) { var option; var timelineOptions = this._timelineOptions; if (timelineOptions.length) { // getTimelineOption can only be called after ecModel inited, // so we can get currentIndex from timelineModel. var timelineModel = ecModel.getComponent('timeline'); if (timelineModel) { option = clone$2( timelineOptions[timelineModel.getCurrentIndex()], true ); } } return option; }, /** * @param {module:echarts/model/Global} ecModel * @return {Array.<Object>} */ getMediaOption: function (ecModel) { var ecWidth = this._api.getWidth(); var ecHeight = this._api.getHeight(); var mediaList = this._mediaList; var mediaDefault = this._mediaDefault; var indices = []; var result = []; // No media defined. if (!mediaList.length && !mediaDefault) { return result; } // Multi media may be applied, the latter defined media has higher priority. for (var i = 0, len = mediaList.length; i < len; i++) { if (applyMediaQuery(mediaList[i].query, ecWidth, ecHeight)) { indices.push(i); } } // FIXME // 是否mediaDefault应该强制用户设置,否则可能修改不能回归。 if (!indices.length && mediaDefault) { indices = [-1]; } if (indices.length && !indicesEquals(indices, this._currentMediaIndices)) { result = map$2(indices, function (index) { return clone$2( index === -1 ? mediaDefault.option : mediaList[index].option ); }); } // Otherwise return nothing. this._currentMediaIndices = indices; return result; } }; function parseRawOption(rawOption, optionPreprocessorFuncs, isNew) { var timelineOptions = []; var mediaList = []; var mediaDefault; var baseOption; // Compatible with ec2. var timelineOpt = rawOption.timeline; if (rawOption.baseOption) { baseOption = rawOption.baseOption; } // For timeline if (timelineOpt || rawOption.options) { baseOption = baseOption || {}; timelineOptions = (rawOption.options || []).slice(); } // For media query if (rawOption.media) { baseOption = baseOption || {}; var media = rawOption.media; each$5(media, function (singleMedia) { if (singleMedia && singleMedia.option) { if (singleMedia.query) { mediaList.push(singleMedia); } else if (!mediaDefault) { // Use the first media default. mediaDefault = singleMedia; } } }); } // For normal option if (!baseOption) { baseOption = rawOption; } // Set timelineOpt to baseOption in ec3, // which is convenient for merge option. if (!baseOption.timeline) { baseOption.timeline = timelineOpt; } // Preprocess. each$5([baseOption].concat(timelineOptions) .concat(map(mediaList, function (media) { return media.option; })), function (option) { each$5(optionPreprocessorFuncs, function (preProcess) { preProcess(option, isNew); }); } ); return { baseOption: baseOption, timelineOptions: timelineOptions, mediaDefault: mediaDefault, mediaList: mediaList }; } /** * @see <http://www.w3.org/TR/css3-mediaqueries/#media1> * Support: width, height, aspectRatio * Can use max or min as prefix. */ function applyMediaQuery(query, ecWidth, ecHeight) { var realMap = { width: ecWidth, height: ecHeight, aspectratio: ecWidth / ecHeight // lowser case for convenientce. }; var applicatable = true; each$1(query, function (value, attr) { var matched = attr.match(QUERY_REG); if (!matched || !matched[1] || !matched[2]) { return; } var operator = matched[1]; var realAttr = matched[2].toLowerCase(); if (!compare(realMap[realAttr], value, operator)) { applicatable = false; } }); return applicatable; } function compare(real, expect, operator) { if (operator === 'min') { return real >= expect; } else if (operator === 'max') { return real <= expect; } else { // Equals return real === expect; } } function indicesEquals(indices1, indices2) { // indices is always order by asc and has only finite number. return indices1.join(',') === indices2.join(','); } /** * Consider case: * `chart.setOption(opt1);` * Then user do some interaction like dataZoom, dataView changing. * `chart.setOption(opt2);` * Then user press 'reset button' in toolbox. * * After doing that all of the interaction effects should be reset, the * chart should be the same as the result of invoke * `chart.setOption(opt1); chart.setOption(opt2);`. * * Although it is not able ensure that * `chart.setOption(opt1); chart.setOption(opt2);` is equivalents to * `chart.setOption(merge(opt1, opt2));` exactly, * this might be the only simple way to implement that feature. * * MEMO: We've considered some other approaches: * 1. Each model handle its self restoration but not uniform treatment. * (Too complex in logic and error-prone) * 2. Use a shadow ecModel. (Performace expensive) */ function mergeOption(oldOption, newOption) { newOption = newOption || {}; each$5(newOption, function (newCptOpt, mainType) { if (newCptOpt == null) { return; } var oldCptOpt = oldOption[mainType]; if (!ComponentModel.hasClass(mainType)) { oldOption[mainType] = merge$1(oldCptOpt, newCptOpt, true); } else { newCptOpt = normalizeToArray(newCptOpt); oldCptOpt = normalizeToArray(oldCptOpt); var mapResult = mappingToExists(oldCptOpt, newCptOpt); oldOption[mainType] = map$2(mapResult, function (item) { return (item.option && item.exist) ? merge$1(item.exist, item.option, true) : (item.exist || item.option); }); } }); } var each$6 = each$1; var isObject$3 = isObject; var POSSIBLE_STYLES = [ 'areaStyle', 'lineStyle', 'nodeStyle', 'linkStyle', 'chordStyle', 'label', 'labelLine' ]; function compatItemStyle(opt) { var itemStyleOpt = opt && opt.itemStyle; if (!itemStyleOpt) { return; } for (var i = 0, len = POSSIBLE_STYLES.length; i < len; i++) { var styleName = POSSIBLE_STYLES[i]; var normalItemStyleOpt = itemStyleOpt.normal; var emphasisItemStyleOpt = itemStyleOpt.emphasis; if (normalItemStyleOpt && normalItemStyleOpt[styleName]) { opt[styleName] = opt[styleName] || {}; if (!opt[styleName].normal) { opt[styleName].normal = normalItemStyleOpt[styleName]; } else { merge(opt[styleName].normal, normalItemStyleOpt[styleName]); } normalItemStyleOpt[styleName] = null; } if (emphasisItemStyleOpt && emphasisItemStyleOpt[styleName]) { opt[styleName] = opt[styleName] || {}; if (!opt[styleName].emphasis) { opt[styleName].emphasis = emphasisItemStyleOpt[styleName]; } else { merge(opt[styleName].emphasis, emphasisItemStyleOpt[styleName]); } emphasisItemStyleOpt[styleName] = null; } } } function compatTextStyle(opt, propName) { var labelOptSingle = isObject$3(opt) && opt[propName]; var textStyle = isObject$3(labelOptSingle) && labelOptSingle.textStyle; if (textStyle) { for (var i = 0, len = TEXT_STYLE_OPTIONS.length; i < len; i++) { var propName = TEXT_STYLE_OPTIONS[i]; if (textStyle.hasOwnProperty(propName)) { labelOptSingle[propName] = textStyle[propName]; } } } } function compatLabelTextStyle(labelOpt) { if (isObject$3(labelOpt)) { compatTextStyle(labelOpt, 'normal'); compatTextStyle(labelOpt, 'emphasis'); } } function processSeries(seriesOpt) { if (!isObject$3(seriesOpt)) { return; } compatItemStyle(seriesOpt); compatLabelTextStyle(seriesOpt.label); // treemap compatLabelTextStyle(seriesOpt.upperLabel); // graph compatLabelTextStyle(seriesOpt.edgeLabel); var markPoint = seriesOpt.markPoint; compatItemStyle(markPoint); compatLabelTextStyle(markPoint && markPoint.label); var markLine = seriesOpt.markLine; compatItemStyle(seriesOpt.markLine); compatLabelTextStyle(markLine && markLine.label); var markArea = seriesOpt.markArea; compatLabelTextStyle(markArea && markArea.label); // For gauge compatTextStyle(seriesOpt, 'axisLabel'); compatTextStyle(seriesOpt, 'title'); compatTextStyle(seriesOpt, 'detail'); var data = seriesOpt.data; if (data) { for (var i = 0; i < data.length; i++) { compatItemStyle(data[i]); compatLabelTextStyle(data[i] && data[i].label); } } // mark point data var markPoint = seriesOpt.markPoint; if (markPoint && markPoint.data) { var mpData = markPoint.data; for (var i = 0; i < mpData.length; i++) { compatItemStyle(mpData[i]); compatLabelTextStyle(mpData[i] && mpData[i].label); } } // mark line data var markLine = seriesOpt.markLine; if (markLine && markLine.data) { var mlData = markLine.data; for (var i = 0; i < mlData.length; i++) { if (isArray(mlData[i])) { compatItemStyle(mlData[i][0]); compatLabelTextStyle(mlData[i][0] && mlData[i][0].label); compatItemStyle(mlData[i][1]); compatLabelTextStyle(mlData[i][1] && mlData[i][1].label); } else { compatItemStyle(mlData[i]); compatLabelTextStyle(mlData[i] && mlData[i].label); } } } } function toArr(o) { return isArray(o) ? o : o ? [o] : []; } function toObj(o) { return (isArray(o) ? o[0] : o) || {}; } var compatStyle = function (option, isTheme) { each$6(toArr(option.series), function (seriesOpt) { isObject$3(seriesOpt) && processSeries(seriesOpt); }); var axes = ['xAxis', 'yAxis', 'radiusAxis', 'angleAxis', 'singleAxis', 'parallelAxis', 'radar']; isTheme && axes.push('valueAxis', 'categoryAxis', 'logAxis', 'timeAxis'); each$6( axes, function (axisName) { each$6(toArr(option[axisName]), function (axisOpt) { if (axisOpt) { compatTextStyle(axisOpt, 'axisLabel'); compatTextStyle(axisOpt.axisPointer, 'label'); } }); } ); each$6(toArr(option.parallel), function (parallelOpt) { var parallelAxisDefault = parallelOpt && parallelOpt.parallelAxisDefault; compatTextStyle(parallelAxisDefault, 'axisLabel'); compatTextStyle(parallelAxisDefault && parallelAxisDefault.axisPointer, 'label'); }); each$6(toArr(option.calendar), function (calendarOpt) { compatTextStyle(calendarOpt, 'dayLabel'); compatTextStyle(calendarOpt, 'monthLabel'); compatTextStyle(calendarOpt, 'yearLabel'); }); // radar.name.textStyle each$6(toArr(option.radar), function (radarOpt) { compatTextStyle(radarOpt, 'name'); }); each$6(toArr(option.geo), function (geoOpt) { if (isObject$3(geoOpt)) { compatLabelTextStyle(geoOpt.label); each$6(toArr(geoOpt.regions), function (regionObj) { compatLabelTextStyle(regionObj.label); }); } }); compatLabelTextStyle(toObj(option.timeline).label); compatTextStyle(toObj(option.axisPointer), 'label'); compatTextStyle(toObj(option.tooltip).axisPointer, 'label'); }; // Compatitable with 2.0 function get$1(opt, path) { path = path.split(','); var obj = opt; for (var i = 0; i < path.length; i++) { obj = obj && obj[path[i]]; if (obj == null) { break; } } return obj; } function set$2(opt, path, val, overwrite) { path = path.split(','); var obj = opt; var key; for (var i = 0; i < path.length - 1; i++) { key = path[i]; if (obj[key] == null) { obj[key] = {}; } obj = obj[key]; } if (overwrite || obj[path[i]] == null) { obj[path[i]] = val; } } function compatLayoutProperties(option) { each$1(LAYOUT_PROPERTIES, function (prop) { if (prop[0] in option && !(prop[1] in option)) { option[prop[1]] = option[prop[0]]; } }); } var LAYOUT_PROPERTIES = [ ['x', 'left'], ['y', 'top'], ['x2', 'right'], ['y2', 'bottom'] ]; var COMPATITABLE_COMPONENTS = [ 'grid', 'geo', 'parallel', 'legend', 'toolbox', 'title', 'visualMap', 'dataZoom', 'timeline' ]; var COMPATITABLE_SERIES = [ 'bar', 'boxplot', 'candlestick', 'chord', 'effectScatter', 'funnel', 'gauge', 'lines', 'graph', 'heatmap', 'line', 'map', 'parallel', 'pie', 'radar', 'sankey', 'scatter', 'treemap' ]; var backwardCompat = function (option, isTheme) { compatStyle(option, isTheme); // Make sure series array for model initialization. option.series = normalizeToArray(option.series); each$1(option.series, function (seriesOpt) { if (!isObject(seriesOpt)) { return; } var seriesType = seriesOpt.type; if (seriesType === 'pie' || seriesType === 'gauge') { if (seriesOpt.clockWise != null) { seriesOpt.clockwise = seriesOpt.clockWise; } } if (seriesType === 'gauge') { var pointerColor = get$1(seriesOpt, 'pointer.color'); pointerColor != null && set$2(seriesOpt, 'itemStyle.normal.color', pointerColor); } for (var i = 0; i < COMPATITABLE_SERIES.length; i++) { if (COMPATITABLE_SERIES[i] === seriesOpt.type) { compatLayoutProperties(seriesOpt); break; } } }); // dataRange has changed to visualMap if (option.dataRange) { option.visualMap = option.dataRange; } each$1(COMPATITABLE_COMPONENTS, function (componentName) { var options = option[componentName]; if (options) { if (!isArray(options)) { options = [options]; } each$1(options, function (option) { compatLayoutProperties(option); }); } }); }; var SeriesModel = ComponentModel.extend({ type: 'series.__base__', /** * @readOnly */ seriesIndex: 0, // coodinateSystem will be injected in the echarts/CoordinateSystem coordinateSystem: null, /** * @type {Object} * @protected */ defaultOption: null, /** * Data provided for legend * @type {Function} */ // PENDING legendDataProvider: null, /** * Access path of color for visual */ visualColorAccessPath: 'itemStyle.normal.color', /** * Support merge layout params. * Only support 'box' now (left/right/top/bottom/width/height). * @type {string|Object} Object can be {ignoreSize: true} * @readOnly */ layoutMode: null, init: function (option, parentModel, ecModel, extraOpt) { /** * @type {number} * @readOnly */ this.seriesIndex = this.componentIndex; this.mergeDefaultAndTheme(option, ecModel); var data = this.getInitialData(option, ecModel); if (__DEV__) { assert(data, 'getInitialData returned invalid data.'); } /** * @type {module:echarts/data/List|module:echarts/data/Tree|module:echarts/data/Graph} * @private */ set$1(this, 'dataBeforeProcessed', data); // If we reverse the order (make data firstly, and then make // dataBeforeProcessed by cloneShallow), cloneShallow will // cause data.graph.data !== data when using // module:echarts/data/Graph or module:echarts/data/Tree. // See module:echarts/data/helper/linkList this.restoreData(); }, /** * Util for merge default and theme to option * @param {Object} option * @param {module:echarts/model/Global} ecModel */ mergeDefaultAndTheme: function (option, ecModel) { var layoutMode = this.layoutMode; var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; // Backward compat: using subType on theme. // But if name duplicate between series subType // (for example: parallel) add component mainType, // add suffix 'Series'. var themeSubType = this.subType; if (ComponentModel.hasClass(themeSubType)) { themeSubType += 'Series'; } merge( option, ecModel.getTheme().get(this.subType) ); merge(option, this.getDefaultOption()); // Default label emphasis `show` defaultEmphasis(option.label, ['show']); this.fillDataTextStyle(option.data); if (layoutMode) { mergeLayoutParam(option, inputPositionParams, layoutMode); } }, mergeOption: function (newSeriesOption, ecModel) { newSeriesOption = merge(this.option, newSeriesOption, true); this.fillDataTextStyle(newSeriesOption.data); var layoutMode = this.layoutMode; if (layoutMode) { mergeLayoutParam(this.option, newSeriesOption, layoutMode); } var data = this.getInitialData(newSeriesOption, ecModel); // TODO Merge data? if (data) { set$1(this, 'data', data); set$1(this, 'dataBeforeProcessed', data.cloneShallow()); } }, fillDataTextStyle: function (data) { // Default data label emphasis `show` // FIXME Tree structure data ? // FIXME Performance ? if (data) { var props = ['show']; for (var i = 0; i < data.length; i++) { if (data[i] && data[i].label) { defaultEmphasis(data[i].label, props); } } } }, /** * Init a data structure from data related option in series * Must be overwritten */ getInitialData: function () {}, /** * @param {string} [dataType] * @return {module:echarts/data/List} */ getData: function (dataType) { var data = get(this, 'data'); return dataType == null ? data : data.getLinkedData(dataType); }, /** * @param {module:echarts/data/List} data */ setData: function (data) { set$1(this, 'data', data); }, /** * Get data before processed * @return {module:echarts/data/List} */ getRawData: function () { return get(this, 'dataBeforeProcessed'); }, /** * Coord dimension to data dimension. * * By default the result is the same as dimensions of series data. * But in some series data dimensions are different from coord dimensions (i.e. * candlestick and boxplot). Override this method to handle those cases. * * Coord dimension to data dimension can be one-to-many * * @param {string} coordDim * @return {Array.<string>} dimensions on the axis. */ coordDimToDataDim: function (coordDim) { return coordDimToDataDim(this.getData(), coordDim); }, /** * Convert data dimension to coord dimension. * * @param {string|number} dataDim * @return {string} */ dataDimToCoordDim: function (dataDim) { return dataDimToCoordDim(this.getData(), dataDim); }, /** * Get base axis if has coordinate system and has axis. * By default use coordSys.getBaseAxis(); * Can be overrided for some chart. * @return {type} description */ getBaseAxis: function () { var coordSys = this.coordinateSystem; return coordSys && coordSys.getBaseAxis && coordSys.getBaseAxis(); }, // FIXME /** * Default tooltip formatter * * @param {number} dataIndex * @param {boolean} [multipleSeries=false] * @param {number} [dataType] */ formatTooltip: function (dataIndex, multipleSeries, dataType) { function formatArrayValue(value) { var vertially = reduce(value, function (vertially, val, idx) { var dimItem = data.getDimensionInfo(idx); return vertially |= dimItem && dimItem.tooltip !== false && dimItem.tooltipName != null; }, 0); var result = []; var tooltipDims = otherDimToDataDim(data, 'tooltip'); tooltipDims.length ? each$1(tooltipDims, function (dimIdx) { setEachItem(data.get(dimIdx, dataIndex), dimIdx); }) // By default, all dims is used on tooltip. : each$1(value, setEachItem); function setEachItem(val, dimIdx) { var dimInfo = data.getDimensionInfo(dimIdx); // If `dimInfo.tooltip` is not set, show tooltip. if (!dimInfo || dimInfo.otherDims.tooltip === false) { return; } var dimType = dimInfo.type; var valStr = (vertially ? '- ' + (dimInfo.tooltipName || dimInfo.name) + ': ' : '') + (dimType === 'ordinal' ? val + '' : dimType === 'time' ? (multipleSeries ? '' : formatTime('yyyy/MM/dd hh:mm:ss', val)) : addCommas(val) ); valStr && result.push(encodeHTML(valStr)); } return (vertially ? '<br/>' : '') + result.join(vertially ? '<br/>' : ', '); } var data = get(this, 'data'); var value = this.getRawValue(dataIndex); var formattedValue = isArray(value) ? formatArrayValue(value) : encodeHTML(addCommas(value)); var name = data.getName(dataIndex); var color = data.getItemVisual(dataIndex, 'color'); if (isObject(color) && color.colorStops) { color = (color.colorStops[0] || {}).color; } color = color || 'transparent'; var colorEl = getTooltipMarker(color); var seriesName = this.name; // FIXME if (seriesName === '\0-') { // Not show '-' seriesName = ''; } seriesName = seriesName ? encodeHTML(seriesName) + (!multipleSeries ? '<br/>' : ': ') : ''; return !multipleSeries ? seriesName + colorEl + (name ? encodeHTML(name) + ': ' + formattedValue : formattedValue ) : colorEl + seriesName + formattedValue; }, /** * @return {boolean} */ isAnimationEnabled: function () { if (env$1.node) { return false; } var animationEnabled = this.getShallow('animation'); if (animationEnabled) { if (this.getData().count() > this.getShallow('animationThreshold')) { animationEnabled = false; } } return animationEnabled; }, restoreData: function () { set$1(this, 'data', get(this, 'dataBeforeProcessed').cloneShallow()); }, getColorFromPalette: function (name, scope) { var ecModel = this.ecModel; // PENDING var color = colorPaletteMixin.getColorFromPalette.call(this, name, scope); if (!color) { color = ecModel.getColorFromPalette(name, scope); } return color; }, /** * Get data indices for show tooltip content. See tooltip. * @abstract * @param {Array.<string>|string} dim * @param {Array.<number>} value * @param {module:echarts/coord/single/SingleAxis} baseAxis * @return {Object} {dataIndices, nestestValue}. */ getAxisTooltipData: null, /** * See tooltip. * @abstract * @param {number} dataIndex * @return {Array.<number>} Point of tooltip. null/undefined can be returned. */ getTooltipPosition: null }); mixin(SeriesModel, dataFormatMixin); mixin(SeriesModel, colorPaletteMixin); var Component = function () { /** * @type {module:zrender/container/Group} * @readOnly */ this.group = new Group(); /** * @type {string} * @readOnly */ this.uid = getUID('viewComponent'); }; Component.prototype = { constructor: Component, init: function (ecModel, api) {}, render: function (componentModel, ecModel, api, payload) {}, dispose: function () {} }; var componentProto = Component.prototype; componentProto.updateView = componentProto.updateLayout = componentProto.updateVisual = function (seriesModel, ecModel, api, payload) { // Do nothing; }; // Enable Component.extend. enableClassExtend(Component); // Enable capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on. enableClassManagement(Component, {registerWhenExtend: true}); function Chart() { /** * @type {module:zrender/container/Group} * @readOnly */ this.group = new Group(); /** * @type {string} * @readOnly */ this.uid = getUID('viewChart'); } Chart.prototype = { type: 'chart', /** * Init the chart * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api */ init: function (ecModel, api) {}, /** * Render the chart * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ render: function (seriesModel, ecModel, api, payload) {}, /** * Highlight series or specified data item * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ highlight: function (seriesModel, ecModel, api, payload) { toggleHighlight(seriesModel.getData(), payload, 'emphasis'); }, /** * Downplay series or specified data item * @param {module:echarts/model/Series} seriesModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ downplay: function (seriesModel, ecModel, api, payload) { toggleHighlight(seriesModel.getData(), payload, 'normal'); }, /** * Remove self * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api */ remove: function (ecModel, api) { this.group.removeAll(); }, /** * Dispose self * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api */ dispose: function () {} /** * The view contains the given point. * @interface * @param {Array.<number>} point * @return {boolean} */ // containPoint: function () {} }; var chartProto = Chart.prototype; chartProto.updateView = chartProto.updateLayout = chartProto.updateVisual = function (seriesModel, ecModel, api, payload) { this.render(seriesModel, ecModel, api, payload); }; /** * Set state of single element * @param {module:zrender/Element} el * @param {string} state */ function elSetState(el, state) { if (el) { el.trigger(state); if (el.type === 'group') { for (var i = 0; i < el.childCount(); i++) { elSetState(el.childAt(i), state); } } } } /** * @param {module:echarts/data/List} data * @param {Object} payload * @param {string} state 'normal'|'emphasis' * @inner */ function toggleHighlight(data, payload, state) { var dataIndex = queryDataIndex(data, payload); if (dataIndex != null) { each$1(normalizeToArray(dataIndex), function (dataIdx) { elSetState(data.getItemGraphicEl(dataIdx), state); }); } else { data.eachItemGraphicEl(function (el) { elSetState(el, state); }); } } // Enable Chart.extend. enableClassExtend(Chart, ['dispose']); // Add capability of registerClass, getClass, hasClass, registerSubTypeDefaulter and so on. enableClassManagement(Chart, {registerWhenExtend: true}); /** * @public * @param {(Function)} fn * @param {number} [delay=0] Unit: ms. * @param {boolean} [debounce=false] * true: If call interval less than `delay`, only the last call works. * false: If call interval less than `delay, call works on fixed rate. * @return {(Function)} throttled fn. */ function throttle(fn, delay, debounce) { var currCall; var lastCall = 0; var lastExec = 0; var timer = null; var diff; var scope; var args; var debounceNextCall; delay = delay || 0; function exec() { lastExec = (new Date()).getTime(); timer = null; fn.apply(scope, args || []); } var cb = function () { currCall = (new Date()).getTime(); scope = this; args = arguments; var thisDelay = debounceNextCall || delay; var thisDebounce = debounceNextCall || debounce; debounceNextCall = null; diff = currCall - (thisDebounce ? lastCall : lastExec) - thisDelay; clearTimeout(timer); if (thisDebounce) { timer = setTimeout(exec, thisDelay); } else { if (diff >= 0) { exec(); } else { timer = setTimeout(exec, -diff); } } lastCall = currCall; }; /** * Clear throttle. * @public */ cb.clear = function () { if (timer) { clearTimeout(timer); timer = null; } }; /** * Enable debounce once. */ cb.debounceNextCall = function (debounceDelay) { debounceNextCall = debounceDelay; }; return cb; } /** * Create throttle method or update throttle rate. * * @example * ComponentView.prototype.render = function () { * ... * throttle.createOrUpdate( * this, * '_dispatchAction', * this.model.get('throttle'), * 'fixRate' * ); * }; * ComponentView.prototype.remove = function () { * throttle.clear(this, '_dispatchAction'); * }; * ComponentView.prototype.dispose = function () { * throttle.clear(this, '_dispatchAction'); * }; * * @public * @param {Object} obj * @param {string} fnAttr * @param {number} [rate] * @param {string} [throttleType='fixRate'] 'fixRate' or 'debounce' * @return {Function} throttled function. */ /** * Clear throttle. Example see throttle.createOrUpdate. * * @public * @param {Object} obj * @param {string} fnAttr */ var seriesColor = function (ecModel) { function encodeColor(seriesModel) { var colorAccessPath = (seriesModel.visualColorAccessPath || 'itemStyle.normal.color').split('.'); var data = seriesModel.getData(); var color = seriesModel.get(colorAccessPath) // Set in itemStyle || seriesModel.getColorFromPalette(seriesModel.get('name')); // Default color // FIXME Set color function or use the platte color data.setVisual('color', color); // Only visible series has each data be visual encoded if (!ecModel.isSeriesFiltered(seriesModel)) { if (typeof color === 'function' && !(color instanceof Gradient)) { data.each(function (idx) { data.setItemVisual( idx, 'color', color(seriesModel.getDataParams(idx)) ); }); } // itemStyle in each data item data.each(function (idx) { var itemModel = data.getItemModel(idx); var color = itemModel.get(colorAccessPath, true); if (color != null) { data.setItemVisual(idx, 'color', color); } }); } } ecModel.eachRawSeries(encodeColor); }; var PI$1 = Math.PI; /** * @param {module:echarts/ExtensionAPI} api * @param {Object} [opts] * @param {string} [opts.text] * @param {string} [opts.color] * @param {string} [opts.textColor] * @return {module:zrender/Element} */ var loadingDefault = function (api, opts) { opts = opts || {}; defaults(opts, { text: 'loading', color: '#c23531', textColor: '#000', maskColor: 'rgba(255, 255, 255, 0.8)', zlevel: 0 }); var mask = new Rect({ style: { fill: opts.maskColor }, zlevel: opts.zlevel, z: 10000 }); var arc = new Arc({ shape: { startAngle: -PI$1 / 2, endAngle: -PI$1 / 2 + 0.1, r: 10 }, style: { stroke: opts.color, lineCap: 'round', lineWidth: 5 }, zlevel: opts.zlevel, z: 10001 }); var labelRect = new Rect({ style: { fill: 'none', text: opts.text, textPosition: 'right', textDistance: 10, textFill: opts.textColor }, zlevel: opts.zlevel, z: 10001 }); arc.animateShape(true) .when(1000, { endAngle: PI$1 * 3 / 2 }) .start('circularInOut'); arc.animateShape(true) .when(1000, { startAngle: PI$1 * 3 / 2 }) .delay(300) .start('circularInOut'); var group = new Group(); group.add(arc); group.add(labelRect); group.add(mask); // Inject resize group.resize = function () { var cx = api.getWidth() / 2; var cy = api.getHeight() / 2; arc.setShape({ cx: cx, cy: cy }); var r = arc.shape.r; labelRect.setShape({ x: cx - r, y: cy - r, width: r * 2, height: r * 2 }); mask.setShape({ x: 0, y: 0, width: api.getWidth(), height: api.getHeight() }); }; group.resize(); return group; }; /*! * ECharts, a javascript interactive chart library. * * Copyright (c) 2015, Baidu Inc. * All rights reserved. * * LICENSE * https://github.com/ecomfe/echarts/blob/master/LICENSE.txt */ var each = each$1; var parseClassType = ComponentModel.parseClassType; var version = '3.8.0'; var dependencies = { zrender: '3.7.0' }; var PRIORITY_PROCESSOR_FILTER = 1000; var PRIORITY_PROCESSOR_STATISTIC = 5000; var PRIORITY_VISUAL_LAYOUT = 1000; var PRIORITY_VISUAL_GLOBAL = 2000; var PRIORITY_VISUAL_CHART = 3000; var PRIORITY_VISUAL_COMPONENT = 4000; // FIXME // necessary? var PRIORITY_VISUAL_BRUSH = 5000; var PRIORITY = { PROCESSOR: { FILTER: PRIORITY_PROCESSOR_FILTER, STATISTIC: PRIORITY_PROCESSOR_STATISTIC }, VISUAL: { LAYOUT: PRIORITY_VISUAL_LAYOUT, GLOBAL: PRIORITY_VISUAL_GLOBAL, CHART: PRIORITY_VISUAL_CHART, COMPONENT: PRIORITY_VISUAL_COMPONENT, BRUSH: PRIORITY_VISUAL_BRUSH } }; // Main process have three entries: `setOption`, `dispatchAction` and `resize`, // where they must not be invoked nestedly, except the only case: invoke // dispatchAction with updateMethod "none" in main process. // This flag is used to carry out this rule. // All events will be triggered out side main process (i.e. when !this[IN_MAIN_PROCESS]). var IN_MAIN_PROCESS = '__flagInMainProcess'; var HAS_GRADIENT_OR_PATTERN_BG = '__hasGradientOrPatternBg'; var OPTION_UPDATED = '__optionUpdated'; var ACTION_REG = /^[a-zA-Z0-9_]+$/; function createRegisterEventWithLowercaseName(method) { return function (eventName, handler, context) { // Event name is all lowercase eventName = eventName && eventName.toLowerCase(); Eventful.prototype[method].call(this, eventName, handler, context); }; } /** * @module echarts~MessageCenter */ function MessageCenter() { Eventful.call(this); } MessageCenter.prototype.on = createRegisterEventWithLowercaseName('on'); MessageCenter.prototype.off = createRegisterEventWithLowercaseName('off'); MessageCenter.prototype.one = createRegisterEventWithLowercaseName('one'); mixin(MessageCenter, Eventful); /** * @module echarts~ECharts */ function ECharts(dom, theme, opts) { opts = opts || {}; // Get theme by name if (typeof theme === 'string') { theme = themeStorage[theme]; } /** * @type {string} */ this.id; /** * Group id * @type {string} */ this.group; /** * @type {HTMLElement} * @private */ this._dom = dom; var defaultRenderer = 'canvas'; if (__DEV__) { defaultRenderer = ( typeof window === 'undefined' ? global : window ).__ECHARTS__DEFAULT__RENDERER__ || defaultRenderer; } /** * @type {module:zrender/ZRender} * @private */ var zr = this._zr = init$1(dom, { renderer: opts.renderer || defaultRenderer, devicePixelRatio: opts.devicePixelRatio, width: opts.width, height: opts.height }); /** * Expect 60 pfs. * @type {Function} * @private */ this._throttledZrFlush = throttle(bind(zr.flush, zr), 17); var theme = clone(theme); theme && backwardCompat(theme, true); /** * @type {Object} * @private */ this._theme = theme; /** * @type {Array.<module:echarts/view/Chart>} * @private */ this._chartsViews = []; /** * @type {Object.<string, module:echarts/view/Chart>} * @private */ this._chartsMap = {}; /** * @type {Array.<module:echarts/view/Component>} * @private */ this._componentsViews = []; /** * @type {Object.<string, module:echarts/view/Component>} * @private */ this._componentsMap = {}; /** * @type {module:echarts/CoordinateSystem} * @private */ this._coordSysMgr = new CoordinateSystemManager(); /** * @type {module:echarts/ExtensionAPI} * @private */ this._api = createExtensionAPI(this); Eventful.call(this); /** * @type {module:echarts~MessageCenter} * @private */ this._messageCenter = new MessageCenter(); // Init mouse events this._initEvents(); // In case some people write `window.onresize = chart.resize` this.resize = bind(this.resize, this); // Can't dispatch action during rendering procedure this._pendingActions = []; // Sort on demand function prioritySortFunc(a, b) { return a.prio - b.prio; } sort(visualFuncs, prioritySortFunc); sort(dataProcessorFuncs, prioritySortFunc); zr.animation.on('frame', this._onframe, this); // ECharts instance can be used as value. setAsPrimitive(this); } var echartsProto = ECharts.prototype; echartsProto._onframe = function () { // Lazy update if (this[OPTION_UPDATED]) { var silent = this[OPTION_UPDATED].silent; this[IN_MAIN_PROCESS] = true; updateMethods.prepareAndUpdate.call(this); this[IN_MAIN_PROCESS] = false; this[OPTION_UPDATED] = false; flushPendingActions.call(this, silent); triggerUpdatedEvent.call(this, silent); } }; /** * @return {HTMLElement} */ echartsProto.getDom = function () { return this._dom; }; /** * @return {module:zrender~ZRender} */ echartsProto.getZr = function () { return this._zr; }; /** * Usage: * chart.setOption(option, notMerge, lazyUpdate); * chart.setOption(option, { * notMerge: ..., * lazyUpdate: ..., * silent: ... * }); * * @param {Object} option * @param {Object|boolean} [opts] opts or notMerge. * @param {boolean} [opts.notMerge=false] * @param {boolean} [opts.lazyUpdate=false] Useful when setOption frequently. */ echartsProto.setOption = function (option, notMerge, lazyUpdate) { if (__DEV__) { assert(!this[IN_MAIN_PROCESS], '`setOption` should not be called during main process.'); } var silent; if (isObject(notMerge)) { lazyUpdate = notMerge.lazyUpdate; silent = notMerge.silent; notMerge = notMerge.notMerge; } this[IN_MAIN_PROCESS] = true; if (!this._model || notMerge) { var optionManager = new OptionManager(this._api); var theme = this._theme; var ecModel = this._model = new GlobalModel(null, null, theme, optionManager); ecModel.init(null, null, theme, optionManager); } this._model.setOption(option, optionPreprocessorFuncs); if (lazyUpdate) { this[OPTION_UPDATED] = {silent: silent}; this[IN_MAIN_PROCESS] = false; } else { updateMethods.prepareAndUpdate.call(this); // Ensure zr refresh sychronously, and then pixel in canvas can be // fetched after `setOption`. this._zr.flush(); this[OPTION_UPDATED] = false; this[IN_MAIN_PROCESS] = false; flushPendingActions.call(this, silent); triggerUpdatedEvent.call(this, silent); } }; /** * @DEPRECATED */ echartsProto.setTheme = function () { console.log('ECharts#setTheme() is DEPRECATED in ECharts 3.0'); }; /** * @return {module:echarts/model/Global} */ echartsProto.getModel = function () { return this._model; }; /** * @return {Object} */ echartsProto.getOption = function () { return this._model && this._model.getOption(); }; /** * @return {number} */ echartsProto.getWidth = function () { return this._zr.getWidth(); }; /** * @return {number} */ echartsProto.getHeight = function () { return this._zr.getHeight(); }; /** * @return {number} */ echartsProto.getDevicePixelRatio = function () { return this._zr.painter.dpr || window.devicePixelRatio || 1; }; /** * Get canvas which has all thing rendered * @param {Object} opts * @param {string} [opts.backgroundColor] * @return {string} */ echartsProto.getRenderedCanvas = function (opts) { if (!env$1.canvasSupported) { return; } opts = opts || {}; opts.pixelRatio = opts.pixelRatio || 1; opts.backgroundColor = opts.backgroundColor || this._model.get('backgroundColor'); var zr = this._zr; var list = zr.storage.getDisplayList(); // Stop animations each$1(list, function (el) { el.stopAnimation(true); }); return zr.painter.getRenderedCanvas(opts); }; /** * Get svg data url * @return {string} */ echartsProto.getSvgDataUrl = function () { if (!env$1.svgSupported) { return; } var zr = this._zr; var list = zr.storage.getDisplayList(); // Stop animations each$1(list, function (el) { el.stopAnimation(true); }); return zr.painter.pathToSvg(); }; /** * @return {string} * @param {Object} opts * @param {string} [opts.type='png'] * @param {string} [opts.pixelRatio=1] * @param {string} [opts.backgroundColor] * @param {string} [opts.excludeComponents] */ echartsProto.getDataURL = function (opts) { opts = opts || {}; var excludeComponents = opts.excludeComponents; var ecModel = this._model; var excludesComponentViews = []; var self = this; each(excludeComponents, function (componentType) { ecModel.eachComponent({ mainType: componentType }, function (component) { var view = self._componentsMap[component.__viewId]; if (!view.group.ignore) { excludesComponentViews.push(view); view.group.ignore = true; } }); }); var url = this._zr.painter.getType() === 'svg' ? this.getSvgDataUrl() : this.getRenderedCanvas(opts).toDataURL( 'image/' + (opts && opts.type || 'png') ); each(excludesComponentViews, function (view) { view.group.ignore = false; }); return url; }; /** * @return {string} * @param {Object} opts * @param {string} [opts.type='png'] * @param {string} [opts.pixelRatio=1] * @param {string} [opts.backgroundColor] */ echartsProto.getConnectedDataURL = function (opts) { if (!env$1.canvasSupported) { return; } var groupId = this.group; var mathMin = Math.min; var mathMax = Math.max; var MAX_NUMBER = Infinity; if (connectedGroups[groupId]) { var left = MAX_NUMBER; var top = MAX_NUMBER; var right = -MAX_NUMBER; var bottom = -MAX_NUMBER; var canvasList = []; var dpr = (opts && opts.pixelRatio) || 1; each$1(instances, function (chart, id) { if (chart.group === groupId) { var canvas = chart.getRenderedCanvas( clone(opts) ); var boundingRect = chart.getDom().getBoundingClientRect(); left = mathMin(boundingRect.left, left); top = mathMin(boundingRect.top, top); right = mathMax(boundingRect.right, right); bottom = mathMax(boundingRect.bottom, bottom); canvasList.push({ dom: canvas, left: boundingRect.left, top: boundingRect.top }); } }); left *= dpr; top *= dpr; right *= dpr; bottom *= dpr; var width = right - left; var height = bottom - top; var targetCanvas = createCanvas(); targetCanvas.width = width; targetCanvas.height = height; var zr = init$1(targetCanvas); each(canvasList, function (item) { var img = new ZImage({ style: { x: item.left * dpr - left, y: item.top * dpr - top, image: item.dom } }); zr.add(img); }); zr.refreshImmediately(); return targetCanvas.toDataURL('image/' + (opts && opts.type || 'png')); } else { return this.getDataURL(opts); } }; /** * Convert from logical coordinate system to pixel coordinate system. * See CoordinateSystem#convertToPixel. * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * geoIndex / geoId, geoName, * bmapIndex / bmapId / bmapName, * xAxisIndex / xAxisId / xAxisName, * yAxisIndex / yAxisId / yAxisName, * gridIndex / gridId / gridName, * ... (can be extended) * } * @param {Array|number} value * @return {Array|number} result */ echartsProto.convertToPixel = curry(doConvertPixel, 'convertToPixel'); /** * Convert from pixel coordinate system to logical coordinate system. * See CoordinateSystem#convertFromPixel. * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * geoIndex / geoId / geoName, * bmapIndex / bmapId / bmapName, * xAxisIndex / xAxisId / xAxisName, * yAxisIndex / yAxisId / yAxisName * gridIndex / gridId / gridName, * ... (can be extended) * } * @param {Array|number} value * @return {Array|number} result */ echartsProto.convertFromPixel = curry(doConvertPixel, 'convertFromPixel'); function doConvertPixel(methodName, finder, value) { var ecModel = this._model; var coordSysList = this._coordSysMgr.getCoordinateSystems(); var result; finder = parseFinder(ecModel, finder); for (var i = 0; i < coordSysList.length; i++) { var coordSys = coordSysList[i]; if (coordSys[methodName] && (result = coordSys[methodName](ecModel, finder, value)) != null ) { return result; } } if (__DEV__) { console.warn( 'No coordinate system that supports ' + methodName + ' found by the given finder.' ); } } /** * Is the specified coordinate systems or components contain the given pixel point. * @param {string|Object} finder * If string, e.g., 'geo', means {geoIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * geoIndex / geoId / geoName, * bmapIndex / bmapId / bmapName, * xAxisIndex / xAxisId / xAxisName, * yAxisIndex / yAxisId / yAxisName, * gridIndex / gridId / gridName, * ... (can be extended) * } * @param {Array|number} value * @return {boolean} result */ echartsProto.containPixel = function (finder, value) { var ecModel = this._model; var result; finder = parseFinder(ecModel, finder); each$1(finder, function (models, key) { key.indexOf('Models') >= 0 && each$1(models, function (model) { var coordSys = model.coordinateSystem; if (coordSys && coordSys.containPoint) { result |= !!coordSys.containPoint(value); } else if (key === 'seriesModels') { var view = this._chartsMap[model.__viewId]; if (view && view.containPoint) { result |= view.containPoint(value, model); } else { if (__DEV__) { console.warn(key + ': ' + (view ? 'The found component do not support containPoint.' : 'No view mapping to the found component.' )); } } } else { if (__DEV__) { console.warn(key + ': containPoint is not supported'); } } }, this); }, this); return !!result; }; /** * Get visual from series or data. * @param {string|Object} finder * If string, e.g., 'series', means {seriesIndex: 0}. * If Object, could contain some of these properties below: * { * seriesIndex / seriesId / seriesName, * dataIndex / dataIndexInside * } * If dataIndex is not specified, series visual will be fetched, * but not data item visual. * If all of seriesIndex, seriesId, seriesName are not specified, * visual will be fetched from first series. * @param {string} visualType 'color', 'symbol', 'symbolSize' */ echartsProto.getVisual = function (finder, visualType) { var ecModel = this._model; finder = parseFinder(ecModel, finder, {defaultMainType: 'series'}); var seriesModel = finder.seriesModel; if (__DEV__) { if (!seriesModel) { console.warn('There is no specified seires model'); } } var data = seriesModel.getData(); var dataIndexInside = finder.hasOwnProperty('dataIndexInside') ? finder.dataIndexInside : finder.hasOwnProperty('dataIndex') ? data.indexOfRawIndex(finder.dataIndex) : null; return dataIndexInside != null ? data.getItemVisual(dataIndexInside, visualType) : data.getVisual(visualType); }; /** * Get view of corresponding component model * @param {module:echarts/model/Component} componentModel * @return {module:echarts/view/Component} */ echartsProto.getViewOfComponentModel = function (componentModel) { return this._componentsMap[componentModel.__viewId]; }; /** * Get view of corresponding series model * @param {module:echarts/model/Series} seriesModel * @return {module:echarts/view/Chart} */ echartsProto.getViewOfSeriesModel = function (seriesModel) { return this._chartsMap[seriesModel.__viewId]; }; var updateMethods = { /** * @param {Object} payload * @private */ update: function (payload) { // console.profile && console.profile('update'); var ecModel = this._model; var api = this._api; var coordSysMgr = this._coordSysMgr; var zr = this._zr; // update before setOption if (!ecModel) { return; } // Fixme First time update ? ecModel.restoreData(); // TODO // Save total ecModel here for undo/redo (after restoring data and before processing data). // Undo (restoration of total ecModel) can be carried out in 'action' or outside API call. // Create new coordinate system each update // In LineView may save the old coordinate system and use it to get the orignal point coordSysMgr.create(this._model, this._api); processData.call(this, ecModel, api); stackSeriesData.call(this, ecModel); coordSysMgr.update(ecModel, api); doVisualEncoding.call(this, ecModel, payload); doRender.call(this, ecModel, payload); // Set background var backgroundColor = ecModel.get('backgroundColor') || 'transparent'; var painter = zr.painter; // TODO all use clearColor ? if (painter.isSingleCanvas && painter.isSingleCanvas()) { zr.configLayer(0, { clearColor: backgroundColor }); } else { // In IE8 if (!env$1.canvasSupported) { var colorArr = parse(backgroundColor); backgroundColor = stringify(colorArr, 'rgb'); if (colorArr[3] === 0) { backgroundColor = 'transparent'; } } if (backgroundColor.colorStops || backgroundColor.image) { // Gradient background // FIXME Fixed layer? zr.configLayer(0, { clearColor: backgroundColor }); this[HAS_GRADIENT_OR_PATTERN_BG] = true; this._dom.style.background = 'transparent'; } else { if (this[HAS_GRADIENT_OR_PATTERN_BG]) { zr.configLayer(0, { clearColor: null }); } this[HAS_GRADIENT_OR_PATTERN_BG] = false; this._dom.style.background = backgroundColor; } } each(postUpdateFuncs, function (func) { func(ecModel, api); }); // console.profile && console.profileEnd('update'); }, /** * @param {Object} payload * @private */ updateView: function (payload) { var ecModel = this._model; // update before setOption if (!ecModel) { return; } ecModel.eachSeries(function (seriesModel) { seriesModel.getData().clearAllVisual(); }); doVisualEncoding.call(this, ecModel, payload); invokeUpdateMethod.call(this, 'updateView', ecModel, payload); }, /** * @param {Object} payload * @private */ updateVisual: function (payload) { var ecModel = this._model; // update before setOption if (!ecModel) { return; } ecModel.eachSeries(function (seriesModel) { seriesModel.getData().clearAllVisual(); }); doVisualEncoding.call(this, ecModel, payload, true); invokeUpdateMethod.call(this, 'updateVisual', ecModel, payload); }, /** * @param {Object} payload * @private */ updateLayout: function (payload) { var ecModel = this._model; // update before setOption if (!ecModel) { return; } doLayout.call(this, ecModel, payload); invokeUpdateMethod.call(this, 'updateLayout', ecModel, payload); }, /** * @param {Object} payload * @private */ prepareAndUpdate: function (payload) { var ecModel = this._model; prepareView.call(this, 'component', ecModel); prepareView.call(this, 'chart', ecModel); updateMethods.update.call(this, payload); } }; /** * @private */ function updateDirectly(ecIns, method, payload, mainType, subType) { var ecModel = ecIns._model; // broadcast if (!mainType) { each(ecIns._componentsViews.concat(ecIns._chartsViews), callView); return; } var query = {}; query[mainType + 'Id'] = payload[mainType + 'Id']; query[mainType + 'Index'] = payload[mainType + 'Index']; query[mainType + 'Name'] = payload[mainType + 'Name']; var condition = {mainType: mainType, query: query}; subType && (condition.subType = subType); // subType may be '' by parseClassType; // If dispatchAction before setOption, do nothing. ecModel && ecModel.eachComponent(condition, function (model, index) { callView(ecIns[ mainType === 'series' ? '_chartsMap' : '_componentsMap' ][model.__viewId]); }, ecIns); function callView(view) { view && view.__alive && view[method] && view[method]( view.__model, ecModel, ecIns._api, payload ); } } /** * Resize the chart * @param {Object} opts * @param {number} [opts.width] Can be 'auto' (the same as null/undefined) * @param {number} [opts.height] Can be 'auto' (the same as null/undefined) * @param {boolean} [opts.silent=false] */ echartsProto.resize = function (opts) { if (__DEV__) { assert(!this[IN_MAIN_PROCESS], '`resize` should not be called during main process.'); } this[IN_MAIN_PROCESS] = true; this._zr.resize(opts); var optionChanged = this._model && this._model.resetOption('media'); var updateMethod = optionChanged ? 'prepareAndUpdate' : 'update'; updateMethods[updateMethod].call(this); // Resize loading effect this._loadingFX && this._loadingFX.resize(); this[IN_MAIN_PROCESS] = false; var silent = opts && opts.silent; flushPendingActions.call(this, silent); triggerUpdatedEvent.call(this, silent); }; /** * Show loading effect * @param {string} [name='default'] * @param {Object} [cfg] */ echartsProto.showLoading = function (name, cfg) { if (isObject(name)) { cfg = name; name = ''; } name = name || 'default'; this.hideLoading(); if (!loadingEffects[name]) { if (__DEV__) { console.warn('Loading effects ' + name + ' not exists.'); } return; } var el = loadingEffects[name](this._api, cfg); var zr = this._zr; this._loadingFX = el; zr.add(el); }; /** * Hide loading effect */ echartsProto.hideLoading = function () { this._loadingFX && this._zr.remove(this._loadingFX); this._loadingFX = null; }; /** * @param {Object} eventObj * @return {Object} */ echartsProto.makeActionFromEvent = function (eventObj) { var payload = extend({}, eventObj); payload.type = eventActionMap[eventObj.type]; return payload; }; /** * @pubilc * @param {Object} payload * @param {string} [payload.type] Action type * @param {Object|boolean} [opt] If pass boolean, means opt.silent * @param {boolean} [opt.silent=false] Whether trigger events. * @param {boolean} [opt.flush=undefined] * true: Flush immediately, and then pixel in canvas can be fetched * immediately. Caution: it might affect performance. * false: Not not flush. * undefined: Auto decide whether perform flush. */ echartsProto.dispatchAction = function (payload, opt) { if (!isObject(opt)) { opt = {silent: !!opt}; } if (!actions[payload.type]) { return; } // Avoid dispatch action before setOption. Especially in `connect`. if (!this._model) { return; } // May dispatchAction in rendering procedure if (this[IN_MAIN_PROCESS]) { this._pendingActions.push(payload); return; } doDispatchAction.call(this, payload, opt.silent); if (opt.flush) { this._zr.flush(true); } else if (opt.flush !== false && env$1.browser.weChat) { // In WeChat embeded browser, `requestAnimationFrame` and `setInterval` // hang when sliding page (on touch event), which cause that zr does not // refresh util user interaction finished, which is not expected. // But `dispatchAction` may be called too frequently when pan on touch // screen, which impacts performance if do not throttle them. this._throttledZrFlush(); } flushPendingActions.call(this, opt.silent); triggerUpdatedEvent.call(this, opt.silent); }; function doDispatchAction(payload, silent) { var payloadType = payload.type; var escapeConnect = payload.escapeConnect; var actionWrap = actions[payloadType]; var actionInfo = actionWrap.actionInfo; var cptType = (actionInfo.update || 'update').split(':'); var updateMethod = cptType.pop(); cptType = cptType[0] != null && parseClassType(cptType[0]); this[IN_MAIN_PROCESS] = true; var payloads = [payload]; var batched = false; // Batch action if (payload.batch) { batched = true; payloads = map(payload.batch, function (item) { item = defaults(extend({}, item), payload); item.batch = null; return item; }); } var eventObjBatch = []; var eventObj; var isHighDown = payloadType === 'highlight' || payloadType === 'downplay'; each(payloads, function (batchItem) { // Action can specify the event by return it. eventObj = actionWrap.action(batchItem, this._model, this._api); // Emit event outside eventObj = eventObj || extend({}, batchItem); // Convert type to eventType eventObj.type = actionInfo.event || eventObj.type; eventObjBatch.push(eventObj); // light update does not perform data process, layout and visual. if (isHighDown) { // method, payload, mainType, subType updateDirectly(this, updateMethod, batchItem, 'series'); } else if (cptType) { updateDirectly(this, updateMethod, batchItem, cptType.main, cptType.sub); } }, this); if (updateMethod !== 'none' && !isHighDown && !cptType) { // Still dirty if (this[OPTION_UPDATED]) { // FIXME Pass payload ? updateMethods.prepareAndUpdate.call(this, payload); this[OPTION_UPDATED] = false; } else { updateMethods[updateMethod].call(this, payload); } } // Follow the rule of action batch if (batched) { eventObj = { type: actionInfo.event || payloadType, escapeConnect: escapeConnect, batch: eventObjBatch }; } else { eventObj = eventObjBatch[0]; } this[IN_MAIN_PROCESS] = false; !silent && this._messageCenter.trigger(eventObj.type, eventObj); } function flushPendingActions(silent) { var pendingActions = this._pendingActions; while (pendingActions.length) { var payload = pendingActions.shift(); doDispatchAction.call(this, payload, silent); } } function triggerUpdatedEvent(silent) { !silent && this.trigger('updated'); } /** * Register event * @method */ echartsProto.on = createRegisterEventWithLowercaseName('on'); echartsProto.off = createRegisterEventWithLowercaseName('off'); echartsProto.one = createRegisterEventWithLowercaseName('one'); /** * @param {string} methodName * @private */ function invokeUpdateMethod(methodName, ecModel, payload) { var api = this._api; // Update all components each(this._componentsViews, function (component) { var componentModel = component.__model; component[methodName](componentModel, ecModel, api, payload); updateZ(componentModel, component); }, this); // Upate all charts ecModel.eachSeries(function (seriesModel, idx) { var chart = this._chartsMap[seriesModel.__viewId]; chart[methodName](seriesModel, ecModel, api, payload); updateZ(seriesModel, chart); updateProgressiveAndBlend(seriesModel, chart); }, this); // If use hover layer updateHoverLayerStatus(this._zr, ecModel); // Post render each(postUpdateFuncs, function (func) { func(ecModel, api); }); } /** * Prepare view instances of charts and components * @param {module:echarts/model/Global} ecModel * @private */ function prepareView(type, ecModel) { var isComponent = type === 'component'; var viewList = isComponent ? this._componentsViews : this._chartsViews; var viewMap = isComponent ? this._componentsMap : this._chartsMap; var zr = this._zr; for (var i = 0; i < viewList.length; i++) { viewList[i].__alive = false; } ecModel[isComponent ? 'eachComponent' : 'eachSeries'](function (componentType, model) { if (isComponent) { if (componentType === 'series') { return; } } else { model = componentType; } // Consider: id same and type changed. var viewId = '_ec_' + model.id + '_' + model.type; var view = viewMap[viewId]; if (!view) { var classType = parseClassType(model.type); var Clazz = isComponent ? Component.getClass(classType.main, classType.sub) : Chart.getClass(classType.sub); if (Clazz) { view = new Clazz(); view.init(ecModel, this._api); viewMap[viewId] = view; viewList.push(view); zr.add(view.group); } else { // Error return; } } model.__viewId = view.__id = viewId; view.__alive = true; view.__model = model; view.group.__ecComponentInfo = { mainType: model.mainType, index: model.componentIndex }; }, this); for (var i = 0; i < viewList.length;) { var view = viewList[i]; if (!view.__alive) { zr.remove(view.group); view.dispose(ecModel, this._api); viewList.splice(i, 1); delete viewMap[view.__id]; view.__id = view.group.__ecComponentInfo = null; } else { i++; } } } /** * Processor data in each series * * @param {module:echarts/model/Global} ecModel * @private */ function processData(ecModel, api) { each(dataProcessorFuncs, function (process) { process.func(ecModel, api); }); } /** * @private */ function stackSeriesData(ecModel) { var stackedDataMap = {}; ecModel.eachSeries(function (series) { var stack = series.get('stack'); var data = series.getData(); if (stack && data.type === 'list') { var previousStack = stackedDataMap[stack]; // Avoid conflict with Object.prototype if (stackedDataMap.hasOwnProperty(stack) && previousStack) { data.stackedOn = previousStack; } stackedDataMap[stack] = data; } }); } /** * Layout before each chart render there series, special visual encoding stage * * @param {module:echarts/model/Global} ecModel * @private */ function doLayout(ecModel, payload) { var api = this._api; each(visualFuncs, function (visual) { if (visual.isLayout) { visual.func(ecModel, api, payload); } }); } /** * Encode visual infomation from data after data processing * * @param {module:echarts/model/Global} ecModel * @param {object} layout * @param {boolean} [excludesLayout] * @private */ function doVisualEncoding(ecModel, payload, excludesLayout) { var api = this._api; ecModel.clearColorPalette(); ecModel.eachSeries(function (seriesModel) { seriesModel.clearColorPalette(); }); each(visualFuncs, function (visual) { (!excludesLayout || !visual.isLayout) && visual.func(ecModel, api, payload); }); } /** * Render each chart and component * @private */ function doRender(ecModel, payload) { var api = this._api; // Render all components each(this._componentsViews, function (componentView) { var componentModel = componentView.__model; componentView.render(componentModel, ecModel, api, payload); updateZ(componentModel, componentView); }, this); each(this._chartsViews, function (chart) { chart.__alive = false; }, this); // Render all charts ecModel.eachSeries(function (seriesModel, idx) { var chartView = this._chartsMap[seriesModel.__viewId]; chartView.__alive = true; chartView.render(seriesModel, ecModel, api, payload); chartView.group.silent = !!seriesModel.get('silent'); updateZ(seriesModel, chartView); updateProgressiveAndBlend(seriesModel, chartView); }, this); // If use hover layer updateHoverLayerStatus(this._zr, ecModel); // Remove groups of unrendered charts each(this._chartsViews, function (chart) { if (!chart.__alive) { chart.remove(ecModel, api); } }, this); } var MOUSE_EVENT_NAMES = [ 'click', 'dblclick', 'mouseover', 'mouseout', 'mousemove', 'mousedown', 'mouseup', 'globalout', 'contextmenu' ]; /** * @private */ echartsProto._initEvents = function () { each(MOUSE_EVENT_NAMES, function (eveName) { this._zr.on(eveName, function (e) { var ecModel = this.getModel(); var el = e.target; var params; // no e.target when 'globalout'. if (eveName === 'globalout') { params = {}; } else if (el && el.dataIndex != null) { var dataModel = el.dataModel || ecModel.getSeriesByIndex(el.seriesIndex); params = dataModel && dataModel.getDataParams(el.dataIndex, el.dataType) || {}; } // If element has custom eventData of components else if (el && el.eventData) { params = extend({}, el.eventData); } if (params) { params.event = e; params.type = eveName; this.trigger(eveName, params); } }, this); }, this); each(eventActionMap, function (actionType, eventType) { this._messageCenter.on(eventType, function (event) { this.trigger(eventType, event); }, this); }, this); }; /** * @return {boolean} */ echartsProto.isDisposed = function () { return this._disposed; }; /** * Clear */ echartsProto.clear = function () { this.setOption({ series: [] }, true); }; /** * Dispose instance */ echartsProto.dispose = function () { if (this._disposed) { if (__DEV__) { console.warn('Instance ' + this.id + ' has been disposed'); } return; } this._disposed = true; var api = this._api; var ecModel = this._model; each(this._componentsViews, function (component) { component.dispose(ecModel, api); }); each(this._chartsViews, function (chart) { chart.dispose(ecModel, api); }); // Dispose after all views disposed this._zr.dispose(); delete instances[this.id]; }; mixin(ECharts, Eventful); function updateHoverLayerStatus(zr, ecModel) { var storage = zr.storage; var elCount = 0; storage.traverse(function (el) { if (!el.isGroup) { elCount++; } }); if (elCount > ecModel.get('hoverLayerThreshold') && !env$1.node) { storage.traverse(function (el) { if (!el.isGroup) { el.useHoverLayer = true; } }); } } /** * Update chart progressive and blend. * @param {module:echarts/model/Series|module:echarts/model/Component} model * @param {module:echarts/view/Component|module:echarts/view/Chart} view */ function updateProgressiveAndBlend(seriesModel, chartView) { // Progressive configuration var elCount = 0; chartView.group.traverse(function (el) { if (el.type !== 'group' && !el.ignore) { elCount++; } }); var frameDrawNum = +seriesModel.get('progressive'); var needProgressive = elCount > seriesModel.get('progressiveThreshold') && frameDrawNum && !env$1.node; if (needProgressive) { chartView.group.traverse(function (el) { // FIXME marker and other components if (!el.isGroup) { el.progressive = needProgressive ? Math.floor(elCount++ / frameDrawNum) : -1; if (needProgressive) { el.stopAnimation(true); } } }); } // Blend configration var blendMode = seriesModel.get('blendMode') || null; if (__DEV__) { if (!env$1.canvasSupported && blendMode && blendMode !== 'source-over') { console.warn('Only canvas support blendMode'); } } chartView.group.traverse(function (el) { // FIXME marker and other components if (!el.isGroup) { el.setStyle('blend', blendMode); } }); } /** * @param {module:echarts/model/Series|module:echarts/model/Component} model * @param {module:echarts/view/Component|module:echarts/view/Chart} view */ function updateZ(model, view) { var z = model.get('z'); var zlevel = model.get('zlevel'); // Set z and zlevel view.group.traverse(function (el) { if (el.type !== 'group') { z != null && (el.z = z); zlevel != null && (el.zlevel = zlevel); } }); } function createExtensionAPI(ecInstance) { var coordSysMgr = ecInstance._coordSysMgr; return extend(new ExtensionAPI(ecInstance), { // Inject methods getCoordinateSystems: bind( coordSysMgr.getCoordinateSystems, coordSysMgr ), getComponentByElement: function (el) { while (el) { var modelInfo = el.__ecComponentInfo; if (modelInfo != null) { return ecInstance._model.getComponent(modelInfo.mainType, modelInfo.index); } el = el.parent; } } }); } /** * @type {Object} key: actionType. * @inner */ var actions = {}; /** * Map eventType to actionType * @type {Object} */ var eventActionMap = {}; /** * Data processor functions of each stage * @type {Array.<Object.<string, Function>>} * @inner */ var dataProcessorFuncs = []; /** * @type {Array.<Function>} * @inner */ var optionPreprocessorFuncs = []; /** * @type {Array.<Function>} * @inner */ var postUpdateFuncs = []; /** * Visual encoding functions of each stage * @type {Array.<Object.<string, Function>>} * @inner */ var visualFuncs = []; /** * Theme storage * @type {Object.<key, Object>} */ var themeStorage = {}; /** * Loading effects */ var loadingEffects = {}; var instances = {}; var connectedGroups = {}; var idBase = new Date() - 0; var groupIdBase = new Date() - 0; var DOM_ATTRIBUTE_KEY = '_echarts_instance_'; function enableConnect(chart) { var STATUS_PENDING = 0; var STATUS_UPDATING = 1; var STATUS_UPDATED = 2; var STATUS_KEY = '__connectUpdateStatus'; function updateConnectedChartsStatus(charts, status) { for (var i = 0; i < charts.length; i++) { var otherChart = charts[i]; otherChart[STATUS_KEY] = status; } } each$1(eventActionMap, function (actionType, eventType) { chart._messageCenter.on(eventType, function (event) { if (connectedGroups[chart.group] && chart[STATUS_KEY] !== STATUS_PENDING) { if (event && event.escapeConnect) { return; } var action = chart.makeActionFromEvent(event); var otherCharts = []; each$1(instances, function (otherChart) { if (otherChart !== chart && otherChart.group === chart.group) { otherCharts.push(otherChart); } }); updateConnectedChartsStatus(otherCharts, STATUS_PENDING); each(otherCharts, function (otherChart) { if (otherChart[STATUS_KEY] !== STATUS_UPDATING) { otherChart.dispatchAction(action); } }); updateConnectedChartsStatus(otherCharts, STATUS_UPDATED); } }); }); } /** * @param {HTMLElement} dom * @param {Object} [theme] * @param {Object} opts * @param {number} [opts.devicePixelRatio] Use window.devicePixelRatio by default * @param {string} [opts.renderer] Currently only 'canvas' is supported. * @param {number} [opts.width] Use clientWidth of the input `dom` by default. * Can be 'auto' (the same as null/undefined) * @param {number} [opts.height] Use clientHeight of the input `dom` by default. * Can be 'auto' (the same as null/undefined) */ function init(dom, theme, opts) { if (__DEV__) { // Check version if ((version$1.replace('.', '') - 0) < (dependencies.zrender.replace('.', '') - 0)) { throw new Error( 'zrender/src ' + version$1 + ' is too old for ECharts ' + version + '. Current version need ZRender ' + dependencies.zrender + '+' ); } if (!dom) { throw new Error('Initialize failed: invalid dom.'); } } var existInstance = getInstanceByDom(dom); if (existInstance) { if (__DEV__) { console.warn('There is a chart instance already initialized on the dom.'); } return existInstance; } if (__DEV__) { if (isDom(dom) && dom.nodeName.toUpperCase() !== 'CANVAS' && ( (!dom.clientWidth && (!opts || opts.width == null)) || (!dom.clientHeight && (!opts || opts.height == null)) ) ) { console.warn('Can\'t get dom width or height'); } } var chart = new ECharts(dom, theme, opts); chart.id = 'ec_' + idBase++; instances[chart.id] = chart; if (dom.setAttribute) { dom.setAttribute(DOM_ATTRIBUTE_KEY, chart.id); } else { dom[DOM_ATTRIBUTE_KEY] = chart.id; } enableConnect(chart); return chart; } /** * @return {string|Array.<module:echarts~ECharts>} groupId */ function connect(groupId) { // Is array of charts if (isArray(groupId)) { var charts = groupId; groupId = null; // If any chart has group each$1(charts, function (chart) { if (chart.group != null) { groupId = chart.group; } }); groupId = groupId || ('g_' + groupIdBase++); each$1(charts, function (chart) { chart.group = groupId; }); } connectedGroups[groupId] = true; return groupId; } /** * @DEPRECATED * @return {string} groupId */ function disConnect(groupId) { connectedGroups[groupId] = false; } /** * @return {string} groupId */ var disconnect = disConnect; /** * Dispose a chart instance * @param {module:echarts~ECharts|HTMLDomElement|string} chart */ function dispose(chart) { if (typeof chart === 'string') { chart = instances[chart]; } else if (!(chart instanceof ECharts)){ // Try to treat as dom chart = getInstanceByDom(chart); } if ((chart instanceof ECharts) && !chart.isDisposed()) { chart.dispose(); } } /** * @param {HTMLElement} dom * @return {echarts~ECharts} */ function getInstanceByDom(dom) { var key; if (dom.getAttribute) { key = dom.getAttribute(DOM_ATTRIBUTE_KEY); } else { key = dom[DOM_ATTRIBUTE_KEY]; } return instances[key]; } /** * @param {string} key * @return {echarts~ECharts} */ function getInstanceById(key) { return instances[key]; } /** * Register theme */ function registerTheme(name, theme) { themeStorage[name] = theme; } /** * Register option preprocessor * @param {Function} preprocessorFunc */ function registerPreprocessor(preprocessorFunc) { optionPreprocessorFuncs.push(preprocessorFunc); } /** * @param {number} [priority=1000] * @param {Function} processorFunc */ function registerProcessor(priority, processorFunc) { if (typeof priority === 'function') { processorFunc = priority; priority = PRIORITY_PROCESSOR_FILTER; } if (__DEV__) { if (isNaN(priority)) { throw new Error('Unkown processor priority'); } } dataProcessorFuncs.push({ prio: priority, func: processorFunc }); } /** * Register postUpdater * @param {Function} postUpdateFunc */ function registerPostUpdate(postUpdateFunc) { postUpdateFuncs.push(postUpdateFunc); } /** * Usage: * registerAction('someAction', 'someEvent', function () { ... }); * registerAction('someAction', function () { ... }); * registerAction( * {type: 'someAction', event: 'someEvent', update: 'updateView'}, * function () { ... } * ); * * @param {(string|Object)} actionInfo * @param {string} actionInfo.type * @param {string} [actionInfo.event] * @param {string} [actionInfo.update] * @param {string} [eventName] * @param {Function} action */ function registerAction(actionInfo, eventName, action) { if (typeof eventName === 'function') { action = eventName; eventName = ''; } var actionType = isObject(actionInfo) ? actionInfo.type : ([actionInfo, actionInfo = { event: eventName }][0]); // Event name is all lowercase actionInfo.event = (actionInfo.event || actionType).toLowerCase(); eventName = actionInfo.event; // Validate action type and event name. assert(ACTION_REG.test(actionType) && ACTION_REG.test(eventName)); if (!actions[actionType]) { actions[actionType] = {action: action, actionInfo: actionInfo}; } eventActionMap[eventName] = actionType; } /** * @param {string} type * @param {*} CoordinateSystem */ function registerCoordinateSystem(type, CoordinateSystem$$1) { CoordinateSystemManager.register(type, CoordinateSystem$$1); } /** * Get dimensions of specified coordinate system. * @param {string} type * @return {Array.<string|Object>} */ function getCoordinateSystemDimensions(type) { var coordSysCreator = CoordinateSystemManager.get(type); if (coordSysCreator) { return coordSysCreator.getDimensionsInfo ? coordSysCreator.getDimensionsInfo() : coordSysCreator.dimensions.slice(); } } /** * Layout is a special stage of visual encoding * Most visual encoding like color are common for different chart * But each chart has it's own layout algorithm * * @param {number} [priority=1000] * @param {Function} layoutFunc */ function registerLayout(priority, layoutFunc) { if (typeof priority === 'function') { layoutFunc = priority; priority = PRIORITY_VISUAL_LAYOUT; } if (__DEV__) { if (isNaN(priority)) { throw new Error('Unkown layout priority'); } } visualFuncs.push({ prio: priority, func: layoutFunc, isLayout: true }); } /** * @param {number} [priority=3000] * @param {Function} visualFunc */ function registerVisual(priority, visualFunc) { if (typeof priority === 'function') { visualFunc = priority; priority = PRIORITY_VISUAL_CHART; } if (__DEV__) { if (isNaN(priority)) { throw new Error('Unkown visual priority'); } } visualFuncs.push({ prio: priority, func: visualFunc }); } /** * @param {string} name */ function registerLoading(name, loadingFx) { loadingEffects[name] = loadingFx; } /** * @param {Object} opts * @param {string} [superClass] */ function extendComponentModel(opts/*, superClass*/) { // var Clazz = ComponentModel; // if (superClass) { // var classType = parseClassType(superClass); // Clazz = ComponentModel.getClass(classType.main, classType.sub, true); // } return ComponentModel.extend(opts); } /** * @param {Object} opts * @param {string} [superClass] */ function extendComponentView(opts/*, superClass*/) { // var Clazz = ComponentView; // if (superClass) { // var classType = parseClassType(superClass); // Clazz = ComponentView.getClass(classType.main, classType.sub, true); // } return Component.extend(opts); } /** * @param {Object} opts * @param {string} [superClass] */ function extendSeriesModel(opts/*, superClass*/) { // var Clazz = SeriesModel; // if (superClass) { // superClass = 'series.' + superClass.replace('series.', ''); // var classType = parseClassType(superClass); // Clazz = ComponentModel.getClass(classType.main, classType.sub, true); // } return SeriesModel.extend(opts); } /** * @param {Object} opts * @param {string} [superClass] */ function extendChartView(opts/*, superClass*/) { // var Clazz = ChartView; // if (superClass) { // superClass = superClass.replace('series.', ''); // var classType = parseClassType(superClass); // Clazz = ChartView.getClass(classType.main, true); // } return Chart.extend(opts); } /** * ZRender need a canvas context to do measureText. * But in node environment canvas may be created by node-canvas. * So we need to specify how to create a canvas instead of using document.createElement('canvas') * * Be careful of using it in the browser. * * @param {Function} creator * @example * var Canvas = require('canvas'); * var echarts = require('echarts'); * echarts.setCanvasCreator(function () { * // Small size is enough. * return new Canvas(32, 32); * }); */ function setCanvasCreator(creator) { $inject$1.createCanvas(creator); } registerVisual(PRIORITY_VISUAL_GLOBAL, seriesColor); registerPreprocessor(backwardCompat); registerLoading('default', loadingDefault); // Default actions registerAction({ type: 'highlight', event: 'highlight', update: 'highlight' }, noop); registerAction({ type: 'downplay', event: 'downplay', update: 'downplay' }, noop); // -------- // Exports // -------- var $inject = { registerMap: function (f) { exports.registerMap = f; }, getMap: function (f) { exports.getMap = f; }, parseGeoJSON: function (f) { exports.parseGeoJSON = f; } }; function defaultKeyGetter(item) { return item; } /** * @param {Array} oldArr * @param {Array} newArr * @param {Function} oldKeyGetter * @param {Function} newKeyGetter * @param {Object} [context] Can be visited by this.context in callback. */ function DataDiffer(oldArr, newArr, oldKeyGetter, newKeyGetter, context) { this._old = oldArr; this._new = newArr; this._oldKeyGetter = oldKeyGetter || defaultKeyGetter; this._newKeyGetter = newKeyGetter || defaultKeyGetter; this.context = context; } DataDiffer.prototype = { constructor: DataDiffer, /** * Callback function when add a data */ add: function (func) { this._add = func; return this; }, /** * Callback function when update a data */ update: function (func) { this._update = func; return this; }, /** * Callback function when remove a data */ remove: function (func) { this._remove = func; return this; }, execute: function () { var oldArr = this._old; var newArr = this._new; var oldDataIndexMap = {}; var newDataIndexMap = {}; var oldDataKeyArr = []; var newDataKeyArr = []; var i; initIndexMap(oldArr, oldDataIndexMap, oldDataKeyArr, '_oldKeyGetter', this); initIndexMap(newArr, newDataIndexMap, newDataKeyArr, '_newKeyGetter', this); // Travel by inverted order to make sure order consistency // when duplicate keys exists (consider newDataIndex.pop() below). // For performance consideration, these code below do not look neat. for (i = 0; i < oldArr.length; i++) { var key = oldDataKeyArr[i]; var idx = newDataIndexMap[key]; // idx can never be empty array here. see 'set null' logic below. if (idx != null) { // Consider there is duplicate key (for example, use dataItem.name as key). // We should make sure every item in newArr and oldArr can be visited. var len = idx.length; if (len) { len === 1 && (newDataIndexMap[key] = null); idx = idx.unshift(); } else { newDataIndexMap[key] = null; } this._update && this._update(idx, i); } else { this._remove && this._remove(i); } } for (var i = 0; i < newDataKeyArr.length; i++) { var key = newDataKeyArr[i]; if (newDataIndexMap.hasOwnProperty(key)) { var idx = newDataIndexMap[key]; if (idx == null) { continue; } // idx can never be empty array here. see 'set null' logic above. if (!idx.length) { this._add && this._add(idx); } else { for (var j = 0, len = idx.length; j < len; j++) { this._add && this._add(idx[j]); } } } } } }; function initIndexMap(arr, map, keyArr, keyGetterName, dataDiffer) { for (var i = 0; i < arr.length; i++) { // Add prefix to avoid conflict with Object.prototype. var key = '_ec_' + dataDiffer[keyGetterName](arr[i], i); var existence = map[key]; if (existence == null) { keyArr.push(key); map[key] = i; } else { if (!existence.length) { map[key] = existence = [existence]; } existence.push(i); } } } /** * List for data storage * @module echarts/data/List */ var isObject$4 = isObject; var UNDEFINED = 'undefined'; var globalObj = typeof window === UNDEFINED ? global : window; var dataCtors = { 'float': typeof globalObj.Float64Array === UNDEFINED ? Array : globalObj.Float64Array, 'int': typeof globalObj.Int32Array === UNDEFINED ? Array : globalObj.Int32Array, // Ordinal data type can be string or int 'ordinal': Array, 'number': Array, 'time': Array }; var TRANSFERABLE_PROPERTIES = [ 'stackedOn', 'hasItemOption', '_nameList', '_idList', '_rawData' ]; function transferProperties(a, b) { each$1(TRANSFERABLE_PROPERTIES.concat(b.__wrappedMethods || []), function (propName) { if (b.hasOwnProperty(propName)) { a[propName] = b[propName]; } }); a.__wrappedMethods = b.__wrappedMethods; } function DefaultDataProvider(dataArray) { this._array = dataArray || []; } DefaultDataProvider.prototype.pure = false; DefaultDataProvider.prototype.count = function () { return this._array.length; }; DefaultDataProvider.prototype.getItem = function (idx) { return this._array[idx]; }; /** * @constructor * @alias module:echarts/data/List * * @param {Array.<string|Object>} dimensions * For example, ['someDimName', {name: 'someDimName', type: 'someDimType'}, ...]. * Dimensions should be concrete names like x, y, z, lng, lat, angle, radius * @param {module:echarts/model/Model} hostModel */ var List = function (dimensions, hostModel) { dimensions = dimensions || ['x', 'y']; var dimensionInfos = {}; var dimensionNames = []; for (var i = 0; i < dimensions.length; i++) { var dimensionName; var dimensionInfo = {}; if (typeof dimensions[i] === 'string') { dimensionName = dimensions[i]; dimensionInfo = { name: dimensionName, coordDim: dimensionName, coordDimIndex: 0, stackable: false, // Type can be 'float', 'int', 'number' // Default is number, Precision of float may not enough type: 'number' }; } else { dimensionInfo = dimensions[i]; dimensionName = dimensionInfo.name; dimensionInfo.type = dimensionInfo.type || 'number'; if (!dimensionInfo.coordDim) { dimensionInfo.coordDim = dimensionName; dimensionInfo.coordDimIndex = 0; } } dimensionInfo.otherDims = dimensionInfo.otherDims || {}; dimensionNames.push(dimensionName); dimensionInfos[dimensionName] = dimensionInfo; } /** * @readOnly * @type {Array.<string>} */ this.dimensions = dimensionNames; /** * Infomation of each data dimension, like data type. * @type {Object} */ this._dimensionInfos = dimensionInfos; /** * @type {module:echarts/model/Model} */ this.hostModel = hostModel; /** * @type {module:echarts/model/Model} */ this.dataType; /** * Indices stores the indices of data subset after filtered. * This data subset will be used in chart. * @type {Array.<number>} * @readOnly */ this.indices = []; /** * Data storage * @type {Object.<key, TypedArray|Array>} * @private */ this._storage = {}; /** * @type {Array.<string>} */ this._nameList = []; /** * @type {Array.<string>} */ this._idList = []; /** * Models of data option is stored sparse for optimizing memory cost * @type {Array.<module:echarts/model/Model>} * @private */ this._optionModels = []; /** * @param {module:echarts/data/List} */ this.stackedOn = null; /** * Global visual properties after visual coding * @type {Object} * @private */ this._visual = {}; /** * Globel layout properties. * @type {Object} * @private */ this._layout = {}; /** * Item visual properties after visual coding * @type {Array.<Object>} * @private */ this._itemVisuals = []; /** * Item layout properties after layout * @type {Array.<Object>} * @private */ this._itemLayouts = []; /** * Graphic elemnents * @type {Array.<module:zrender/Element>} * @private */ this._graphicEls = []; /** * @type {Array.<Array|Object>} * @private */ this._rawData; /** * @type {Object} * @private */ this._extent; }; var listProto = List.prototype; listProto.type = 'list'; /** * If each data item has it's own option * @type {boolean} */ listProto.hasItemOption = true; /** * Get dimension name * @param {string|number} dim * Dimension can be concrete names like x, y, z, lng, lat, angle, radius * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius' * @return {string} Concrete dim name. */ listProto.getDimension = function (dim) { if (!isNaN(dim)) { dim = this.dimensions[dim] || dim; } return dim; }; /** * Get type and stackable info of particular dimension * @param {string|number} dim * Dimension can be concrete names like x, y, z, lng, lat, angle, radius * Or a ordinal number. For example getDimensionInfo(0) will return 'x' or 'lng' or 'radius' */ listProto.getDimensionInfo = function (dim) { return clone(this._dimensionInfos[this.getDimension(dim)]); }; /** * Initialize from data * @param {Array.<Object|number|Array>} data * @param {Array.<string>} [nameList] * @param {Function} [dimValueGetter] (dataItem, dimName, dataIndex, dimIndex) => number */ listProto.initData = function (data, nameList, dimValueGetter) { data = data || []; var isDataArray = isArray(data); if (isDataArray) { data = new DefaultDataProvider(data); } if (__DEV__) { if (!isDataArray && (typeof data.getItem != 'function' || typeof data.count != 'function')) { throw new Error('Inavlid data provider.'); } } this._rawData = data; // Clear var storage = this._storage = {}; var indices = this.indices = []; var dimensions = this.dimensions; var dimensionInfoMap = this._dimensionInfos; var size = data.count(); var idList = []; var nameRepeatCount = {}; var nameDimIdx; nameList = nameList || []; // Init storage for (var i = 0; i < dimensions.length; i++) { var dimInfo = dimensionInfoMap[dimensions[i]]; dimInfo.otherDims.itemName === 0 && (nameDimIdx = i); var DataCtor = dataCtors[dimInfo.type]; storage[dimensions[i]] = new DataCtor(size); } var self = this; if (!dimValueGetter) { self.hasItemOption = false; } // Default dim value getter dimValueGetter = dimValueGetter || function (dataItem, dimName, dataIndex, dimIndex) { var value = getDataItemValue(dataItem); // If any dataItem is like { value: 10 } if (isDataItemOption(dataItem)) { self.hasItemOption = true; } return converDataValue( (value instanceof Array) ? value[dimIndex] // If value is a single number or something else not array. : value, dimensionInfoMap[dimName] ); }; for (var i = 0; i < size; i++) { // NOTICE: Try not to write things into dataItem var dataItem = data.getItem(i); // Each data item is value // [1, 2] // 2 // Bar chart, line chart which uses category axis // only gives the 'y' value. 'x' value is the indices of cateogry // Use a tempValue to normalize the value to be a (x, y) value // Store the data by dimensions for (var k = 0; k < dimensions.length; k++) { var dim = dimensions[k]; var dimStorage = storage[dim]; // PENDING NULL is empty or zero dimStorage[i] = dimValueGetter(dataItem, dim, i, k); } indices.push(i); } // Use the name in option and create id for (var i = 0; i < size; i++) { var dataItem = data.getItem(i); if (!nameList[i] && dataItem) { if (dataItem.name != null) { nameList[i] = dataItem.name; } else if (nameDimIdx != null) { nameList[i] = storage[dimensions[nameDimIdx]][i]; } } var name = nameList[i] || ''; // Try using the id in option var id = dataItem && dataItem.id; if (!id && name) { // Use name as id and add counter to avoid same name nameRepeatCount[name] = nameRepeatCount[name] || 0; id = name; if (nameRepeatCount[name] > 0) { id += '__ec__' + nameRepeatCount[name]; } nameRepeatCount[name]++; } id && (idList[i] = id); } this._nameList = nameList; this._idList = idList; }; /** * @return {number} */ listProto.count = function () { return this.indices.length; }; /** * Get value. Return NaN if idx is out of range. * @param {string} dim Dim must be concrete name. * @param {number} idx * @param {boolean} stack * @return {number} */ listProto.get = function (dim, idx, stack) { var storage = this._storage; var dataIndex = this.indices[idx]; // If value not exists if (dataIndex == null || !storage[dim]) { return NaN; } var value = storage[dim][dataIndex]; // FIXME ordinal data type is not stackable if (stack) { var dimensionInfo = this._dimensionInfos[dim]; if (dimensionInfo && dimensionInfo.stackable) { var stackedOn = this.stackedOn; while (stackedOn) { // Get no stacked data of stacked on var stackedValue = stackedOn.get(dim, idx); // Considering positive stack, negative stack and empty data if ((value >= 0 && stackedValue > 0) // Positive stack || (value <= 0 && stackedValue < 0) // Negative stack ) { value += stackedValue; } stackedOn = stackedOn.stackedOn; } } } return value; }; /** * Get value for multi dimensions. * @param {Array.<string>} [dimensions] If ignored, using all dimensions. * @param {number} idx * @param {boolean} stack * @return {number} */ listProto.getValues = function (dimensions, idx, stack) { var values = []; if (!isArray(dimensions)) { stack = idx; idx = dimensions; dimensions = this.dimensions; } for (var i = 0, len = dimensions.length; i < len; i++) { values.push(this.get(dimensions[i], idx, stack)); } return values; }; /** * If value is NaN. Inlcuding '-' * @param {string} dim * @param {number} idx * @return {number} */ listProto.hasValue = function (idx) { var dimensions = this.dimensions; var dimensionInfos = this._dimensionInfos; for (var i = 0, len = dimensions.length; i < len; i++) { if ( // Ordinal type can be string or number dimensionInfos[dimensions[i]].type !== 'ordinal' && isNaN(this.get(dimensions[i], idx)) ) { return false; } } return true; }; /** * Get extent of data in one dimension * @param {string} dim * @param {boolean} stack * @param {Function} filter */ listProto.getDataExtent = function (dim, stack, filter$$1) { dim = this.getDimension(dim); var dimData = this._storage[dim]; var dimInfo = this.getDimensionInfo(dim); stack = (dimInfo && dimInfo.stackable) && stack; var dimExtent = (this._extent || (this._extent = {}))[dim + (!!stack)]; var value; if (dimExtent) { return dimExtent; } // var dimInfo = this._dimensionInfos[dim]; if (dimData) { var min = Infinity; var max = -Infinity; // var isOrdinal = dimInfo.type === 'ordinal'; for (var i = 0, len = this.count(); i < len; i++) { value = this.get(dim, i, stack); // FIXME // if (isOrdinal && typeof value === 'string') { // value = zrUtil.indexOf(dimData, value); // } if (!filter$$1 || filter$$1(value, dim, i)) { value < min && (min = value); value > max && (max = value); } } return (this._extent[dim + !!stack] = [min, max]); } else { return [Infinity, -Infinity]; } }; /** * Get sum of data in one dimension * @param {string} dim * @param {boolean} stack */ listProto.getSum = function (dim, stack) { var dimData = this._storage[dim]; var sum = 0; if (dimData) { for (var i = 0, len = this.count(); i < len; i++) { var value = this.get(dim, i, stack); if (!isNaN(value)) { sum += value; } } } return sum; }; /** * Retreive the index with given value * @param {number} idx * @param {number} value * @return {number} */ // FIXME Precision of float value listProto.indexOf = function (dim, value) { var storage = this._storage; var dimData = storage[dim]; var indices = this.indices; if (dimData) { for (var i = 0, len = indices.length; i < len; i++) { var rawIndex = indices[i]; if (dimData[rawIndex] === value) { return i; } } } return -1; }; /** * Retreive the index with given name * @param {number} idx * @param {number} name * @return {number} */ listProto.indexOfName = function (name) { var indices = this.indices; var nameList = this._nameList; for (var i = 0, len = indices.length; i < len; i++) { var rawIndex = indices[i]; if (nameList[rawIndex] === name) { return i; } } return -1; }; /** * Retreive the index with given raw data index * @param {number} idx * @param {number} name * @return {number} */ listProto.indexOfRawIndex = function (rawIndex) { // Indices are ascending var indices = this.indices; // If rawIndex === dataIndex var rawDataIndex = indices[rawIndex]; if (rawDataIndex != null && rawDataIndex === rawIndex) { return rawIndex; } var left = 0; var right = indices.length - 1; while (left <= right) { var mid = (left + right) / 2 | 0; if (indices[mid] < rawIndex) { left = mid + 1; } else if (indices[mid] > rawIndex) { right = mid - 1; } else { return mid; } } return -1; }; /** * Retreive the index of nearest value * @param {string} dim * @param {number} value * @param {boolean} stack If given value is after stacked * @param {number} [maxDistance=Infinity] * @return {Array.<number>} Considere multiple points has the same value. */ listProto.indicesOfNearest = function (dim, value, stack, maxDistance) { var storage = this._storage; var dimData = storage[dim]; var nearestIndices = []; if (!dimData) { return nearestIndices; } if (maxDistance == null) { maxDistance = Infinity; } var minDist = Number.MAX_VALUE; var minDiff = -1; for (var i = 0, len = this.count(); i < len; i++) { var diff = value - this.get(dim, i, stack); var dist = Math.abs(diff); if (diff <= maxDistance && dist <= minDist) { // For the case of two data are same on xAxis, which has sequence data. // Show the nearest index // https://github.com/ecomfe/echarts/issues/2869 if (dist < minDist || (diff >= 0 && minDiff < 0)) { minDist = dist; minDiff = diff; nearestIndices.length = 0; } nearestIndices.push(i); } } return nearestIndices; }; /** * Get raw data index * @param {number} idx * @return {number} */ listProto.getRawIndex = function (idx) { var rawIdx = this.indices[idx]; return rawIdx == null ? -1 : rawIdx; }; /** * Get raw data item * @param {number} idx * @return {number} */ listProto.getRawDataItem = function (idx) { return this._rawData.getItem(this.getRawIndex(idx)); }; /** * @param {number} idx * @param {boolean} [notDefaultIdx=false] * @return {string} */ listProto.getName = function (idx) { return this._nameList[this.indices[idx]] || ''; }; /** * @param {number} idx * @param {boolean} [notDefaultIdx=false] * @return {string} */ listProto.getId = function (idx) { return this._idList[this.indices[idx]] || (this.getRawIndex(idx) + ''); }; function normalizeDimensions(dimensions) { if (!isArray(dimensions)) { dimensions = [dimensions]; } return dimensions; } /** * Data iteration * @param {string|Array.<string>} * @param {Function} cb * @param {boolean} [stack=false] * @param {*} [context=this] * * @example * list.each('x', function (x, idx) {}); * list.each(['x', 'y'], function (x, y, idx) {}); * list.each(function (idx) {}) */ listProto.each = function (dims, cb, stack, context) { if (typeof dims === 'function') { context = stack; stack = cb; cb = dims; dims = []; } dims = map(normalizeDimensions(dims), this.getDimension, this); var value = []; var dimSize = dims.length; var indices = this.indices; context = context || this; for (var i = 0; i < indices.length; i++) { // Simple optimization switch (dimSize) { case 0: cb.call(context, i); break; case 1: cb.call(context, this.get(dims[0], i, stack), i); break; case 2: cb.call(context, this.get(dims[0], i, stack), this.get(dims[1], i, stack), i); break; default: for (var k = 0; k < dimSize; k++) { value[k] = this.get(dims[k], i, stack); } // Index value[k] = i; cb.apply(context, value); } } }; /** * Data filter * @param {string|Array.<string>} * @param {Function} cb * @param {boolean} [stack=false] * @param {*} [context=this] */ listProto.filterSelf = function (dimensions, cb, stack, context) { if (typeof dimensions === 'function') { context = stack; stack = cb; cb = dimensions; dimensions = []; } dimensions = map( normalizeDimensions(dimensions), this.getDimension, this ); var newIndices = []; var value = []; var dimSize = dimensions.length; var indices = this.indices; context = context || this; for (var i = 0; i < indices.length; i++) { var keep; // Simple optimization if (!dimSize) { keep = cb.call(context, i); } else if (dimSize === 1) { keep = cb.call( context, this.get(dimensions[0], i, stack), i ); } else { for (var k = 0; k < dimSize; k++) { value[k] = this.get(dimensions[k], i, stack); } value[k] = i; keep = cb.apply(context, value); } if (keep) { newIndices.push(indices[i]); } } this.indices = newIndices; // Reset data extent this._extent = {}; return this; }; /** * Data mapping to a plain array * @param {string|Array.<string>} [dimensions] * @param {Function} cb * @param {boolean} [stack=false] * @param {*} [context=this] * @return {Array} */ listProto.mapArray = function (dimensions, cb, stack, context) { if (typeof dimensions === 'function') { context = stack; stack = cb; cb = dimensions; dimensions = []; } var result = []; this.each(dimensions, function () { result.push(cb && cb.apply(this, arguments)); }, stack, context); return result; }; function cloneListForMapAndSample(original, excludeDimensions) { var allDimensions = original.dimensions; var list = new List( map(allDimensions, original.getDimensionInfo, original), original.hostModel ); // FIXME If needs stackedOn, value may already been stacked transferProperties(list, original); var storage = list._storage = {}; var originalStorage = original._storage; // Init storage for (var i = 0; i < allDimensions.length; i++) { var dim = allDimensions[i]; var dimStore = originalStorage[dim]; if (indexOf(excludeDimensions, dim) >= 0) { storage[dim] = new dimStore.constructor( originalStorage[dim].length ); } else { // Direct reference for other dimensions storage[dim] = originalStorage[dim]; } } return list; } /** * Data mapping to a new List with given dimensions * @param {string|Array.<string>} dimensions * @param {Function} cb * @param {boolean} [stack=false] * @param {*} [context=this] * @return {Array} */ listProto.map = function (dimensions, cb, stack, context) { dimensions = map( normalizeDimensions(dimensions), this.getDimension, this ); var list = cloneListForMapAndSample(this, dimensions); // Following properties are all immutable. // So we can reference to the same value var indices = list.indices = this.indices; var storage = list._storage; var tmpRetValue = []; this.each(dimensions, function () { var idx = arguments[arguments.length - 1]; var retValue = cb && cb.apply(this, arguments); if (retValue != null) { // a number if (typeof retValue === 'number') { tmpRetValue[0] = retValue; retValue = tmpRetValue; } for (var i = 0; i < retValue.length; i++) { var dim = dimensions[i]; var dimStore = storage[dim]; var rawIdx = indices[idx]; if (dimStore) { dimStore[rawIdx] = retValue[i]; } } } }, stack, context); return list; }; /** * Large data down sampling on given dimension * @param {string} dimension * @param {number} rate * @param {Function} sampleValue * @param {Function} sampleIndex Sample index for name and id */ listProto.downSample = function (dimension, rate, sampleValue, sampleIndex) { var list = cloneListForMapAndSample(this, [dimension]); var storage = this._storage; var targetStorage = list._storage; var originalIndices = this.indices; var indices = list.indices = []; var frameValues = []; var frameIndices = []; var frameSize = Math.floor(1 / rate); var dimStore = targetStorage[dimension]; var len = this.count(); // Copy data from original data for (var i = 0; i < storage[dimension].length; i++) { targetStorage[dimension][i] = storage[dimension][i]; } for (var i = 0; i < len; i += frameSize) { // Last frame if (frameSize > len - i) { frameSize = len - i; frameValues.length = frameSize; } for (var k = 0; k < frameSize; k++) { var idx = originalIndices[i + k]; frameValues[k] = dimStore[idx]; frameIndices[k] = idx; } var value = sampleValue(frameValues); var idx = frameIndices[sampleIndex(frameValues, value) || 0]; // Only write value on the filtered data dimStore[idx] = value; indices.push(idx); } return list; }; /** * Get model of one data item. * * @param {number} idx */ // FIXME Model proxy ? listProto.getItemModel = function (idx) { var hostModel = this.hostModel; idx = this.indices[idx]; return new Model(this._rawData.getItem(idx), hostModel, hostModel && hostModel.ecModel); }; /** * Create a data differ * @param {module:echarts/data/List} otherList * @return {module:echarts/data/DataDiffer} */ listProto.diff = function (otherList) { var idList = this._idList; var otherIdList = otherList && otherList._idList; var val; // Use prefix to avoid index to be the same as otherIdList[idx], // which will cause weird udpate animation. var prefix = 'e\0\0'; return new DataDiffer( otherList ? otherList.indices : [], this.indices, function (idx) { return (val = otherIdList[idx]) != null ? val : prefix + idx; }, function (idx) { return (val = idList[idx]) != null ? val : prefix + idx; } ); }; /** * Get visual property. * @param {string} key */ listProto.getVisual = function (key) { var visual = this._visual; return visual && visual[key]; }; /** * Set visual property * @param {string|Object} key * @param {*} [value] * * @example * setVisual('color', color); * setVisual({ * 'color': color * }); */ listProto.setVisual = function (key, val) { if (isObject$4(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { this.setVisual(name, key[name]); } } return; } this._visual = this._visual || {}; this._visual[key] = val; }; /** * Set layout property. * @param {string|Object} key * @param {*} [val] */ listProto.setLayout = function (key, val) { if (isObject$4(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { this.setLayout(name, key[name]); } } return; } this._layout[key] = val; }; /** * Get layout property. * @param {string} key. * @return {*} */ listProto.getLayout = function (key) { return this._layout[key]; }; /** * Get layout of single data item * @param {number} idx */ listProto.getItemLayout = function (idx) { return this._itemLayouts[idx]; }; /** * Set layout of single data item * @param {number} idx * @param {Object} layout * @param {boolean=} [merge=false] */ listProto.setItemLayout = function (idx, layout, merge$$1) { this._itemLayouts[idx] = merge$$1 ? extend(this._itemLayouts[idx] || {}, layout) : layout; }; /** * Clear all layout of single data item */ listProto.clearItemLayouts = function () { this._itemLayouts.length = 0; }; /** * Get visual property of single data item * @param {number} idx * @param {string} key * @param {boolean} [ignoreParent=false] */ listProto.getItemVisual = function (idx, key, ignoreParent) { var itemVisual = this._itemVisuals[idx]; var val = itemVisual && itemVisual[key]; if (val == null && !ignoreParent) { // Use global visual property return this.getVisual(key); } return val; }; /** * Set visual property of single data item * * @param {number} idx * @param {string|Object} key * @param {*} [value] * * @example * setItemVisual(0, 'color', color); * setItemVisual(0, { * 'color': color * }); */ listProto.setItemVisual = function (idx, key, value) { var itemVisual = this._itemVisuals[idx] || {}; this._itemVisuals[idx] = itemVisual; if (isObject$4(key)) { for (var name in key) { if (key.hasOwnProperty(name)) { itemVisual[name] = key[name]; } } return; } itemVisual[key] = value; }; /** * Clear itemVisuals and list visual. */ listProto.clearAllVisual = function () { this._visual = {}; this._itemVisuals = []; }; var setItemDataAndSeriesIndex = function (child) { child.seriesIndex = this.seriesIndex; child.dataIndex = this.dataIndex; child.dataType = this.dataType; }; /** * Set graphic element relative to data. It can be set as null * @param {number} idx * @param {module:zrender/Element} [el] */ listProto.setItemGraphicEl = function (idx, el) { var hostModel = this.hostModel; if (el) { // Add data index and series index for indexing the data by element // Useful in tooltip el.dataIndex = idx; el.dataType = this.dataType; el.seriesIndex = hostModel && hostModel.seriesIndex; if (el.type === 'group') { el.traverse(setItemDataAndSeriesIndex, el); } } this._graphicEls[idx] = el; }; /** * @param {number} idx * @return {module:zrender/Element} */ listProto.getItemGraphicEl = function (idx) { return this._graphicEls[idx]; }; /** * @param {Function} cb * @param {*} context */ listProto.eachItemGraphicEl = function (cb, context) { each$1(this._graphicEls, function (el, idx) { if (el) { cb && cb.call(context, el, idx); } }); }; /** * Shallow clone a new list except visual and layout properties, and graph elements. * New list only change the indices. */ listProto.cloneShallow = function () { var dimensionInfoList = map(this.dimensions, this.getDimensionInfo, this); var list = new List(dimensionInfoList, this.hostModel); // FIXME list._storage = this._storage; transferProperties(list, this); // Clone will not change the data extent and indices list.indices = this.indices.slice(); if (this._extent) { list._extent = extend({}, this._extent); } return list; }; /** * Wrap some method to add more feature * @param {string} methodName * @param {Function} injectFunction */ listProto.wrapMethod = function (methodName, injectFunction) { var originalMethod = this[methodName]; if (typeof originalMethod !== 'function') { return; } this.__wrappedMethods = this.__wrappedMethods || []; this.__wrappedMethods.push(methodName); this[methodName] = function () { var res = originalMethod.apply(this, arguments); return injectFunction.apply(this, [res].concat(slice(arguments))); }; }; // Methods that create a new list based on this list should be listed here. // Notice that those method should `RETURN` the new list. listProto.TRANSFERABLE_METHODS = ['cloneShallow', 'downSample', 'map']; // Methods that change indices of this list should be listed here. listProto.CHANGABLE_METHODS = ['filterSelf']; /** * Complete dimensions by data (guess dimension). */ var each$7 = each$1; var isString$1 = isString; var defaults$1 = defaults; var OTHER_DIMS = {tooltip: 1, label: 1, itemName: 1}; /** * Complete the dimensions array, by user defined `dimension` and `encode`, * and guessing from the data structure. * If no 'value' dimension specified, the first no-named dimension will be * named as 'value'. * * @param {Array.<string>} sysDims Necessary dimensions, like ['x', 'y'], which * provides not only dim template, but also default order. * `name` of each item provides default coord name. * [{dimsDef: []}, ...] can be specified to give names. * @param {Array} data Data list. [[1, 2, 3], [2, 3, 4]]. * @param {Object} [opt] * @param {Array.<Object|string>} [opt.dimsDef] option.series.dimensions User defined dimensions * For example: ['asdf', {name, type}, ...]. * @param {Object} [opt.encodeDef] option.series.encode {x: 2, y: [3, 1], tooltip: [1, 2], label: 3} * @param {string} [opt.extraPrefix] Prefix of name when filling the left dimensions. * @param {string} [opt.extraFromZero] If specified, extra dim names will be: * extraPrefix + 0, extraPrefix + extraBaseIndex + 1 ... * If not specified, extra dim names will be: * extraPrefix, extraPrefix + 0, extraPrefix + 1 ... * @param {number} [opt.dimCount] If not specified, guess by the first data item. * @return {Array.<Object>} [{ * name: string mandatory, * coordDim: string mandatory, * coordDimIndex: number mandatory, * type: string optional, * tooltipName: string optional, * otherDims: { * tooltip: number optional, * label: number optional * }, * isExtraCoord: boolean true or undefined. * other props ... * }] */ function completeDimensions(sysDims, data, opt) { data = data || []; opt = opt || {}; sysDims = (sysDims || []).slice(); var dimsDef = (opt.dimsDef || []).slice(); var encodeDef = createHashMap(opt.encodeDef); var dataDimNameMap = createHashMap(); var coordDimNameMap = createHashMap(); // var valueCandidate; var result = []; var dimCount = opt.dimCount; if (dimCount == null) { var value0 = retrieveValue(data[0]); dimCount = Math.max( isArray(value0) && value0.length || 1, sysDims.length, dimsDef.length ); each$7(sysDims, function (sysDimItem) { var sysDimItemDimsDef = sysDimItem.dimsDef; sysDimItemDimsDef && (dimCount = Math.max(dimCount, sysDimItemDimsDef.length)); }); } // Apply user defined dims (`name` and `type`) and init result. for (var i = 0; i < dimCount; i++) { var dimDefItem = isString$1(dimsDef[i]) ? {name: dimsDef[i]} : (dimsDef[i] || {}); var userDimName = dimDefItem.name; var resultItem = result[i] = {otherDims: {}}; // Name will be applied later for avoiding duplication. if (userDimName != null && dataDimNameMap.get(userDimName) == null) { // Only if `series.dimensions` is defined in option, tooltipName // will be set, and dimension will be diplayed vertically in // tooltip by default. resultItem.name = resultItem.tooltipName = userDimName; dataDimNameMap.set(userDimName, i); } dimDefItem.type != null && (resultItem.type = dimDefItem.type); } // Set `coordDim` and `coordDimIndex` by `encodeDef` and normalize `encodeDef`. encodeDef.each(function (dataDims, coordDim) { dataDims = encodeDef.set(coordDim, normalizeToArray(dataDims).slice()); each$7(dataDims, function (resultDimIdx, coordDimIndex) { // The input resultDimIdx can be dim name or index. isString$1(resultDimIdx) && (resultDimIdx = dataDimNameMap.get(resultDimIdx)); if (resultDimIdx != null && resultDimIdx < dimCount) { dataDims[coordDimIndex] = resultDimIdx; applyDim(result[resultDimIdx], coordDim, coordDimIndex); } }); }); // Apply templetes and default order from `sysDims`. var availDimIdx = 0; each$7(sysDims, function (sysDimItem, sysDimIndex) { var coordDim; var sysDimItem; var sysDimItemDimsDef; var sysDimItemOtherDims; if (isString$1(sysDimItem)) { coordDim = sysDimItem; sysDimItem = {}; } else { coordDim = sysDimItem.name; sysDimItem = clone(sysDimItem); // `coordDimIndex` should not be set directly. sysDimItemDimsDef = sysDimItem.dimsDef; sysDimItemOtherDims = sysDimItem.otherDims; sysDimItem.name = sysDimItem.coordDim = sysDimItem.coordDimIndex = sysDimItem.dimsDef = sysDimItem.otherDims = null; } var dataDims = normalizeToArray(encodeDef.get(coordDim)); // dimensions provides default dim sequences. if (!dataDims.length) { for (var i = 0; i < (sysDimItemDimsDef && sysDimItemDimsDef.length || 1); i++) { while (availDimIdx < result.length && result[availDimIdx].coordDim != null) { availDimIdx++; } availDimIdx < result.length && dataDims.push(availDimIdx++); } } // Apply templates. each$7(dataDims, function (resultDimIdx, coordDimIndex) { var resultItem = result[resultDimIdx]; applyDim(defaults$1(resultItem, sysDimItem), coordDim, coordDimIndex); if (resultItem.name == null && sysDimItemDimsDef) { resultItem.name = resultItem.tooltipName = sysDimItemDimsDef[coordDimIndex]; } sysDimItemOtherDims && defaults$1(resultItem.otherDims, sysDimItemOtherDims); }); }); // Make sure the first extra dim is 'value'. var extra = opt.extraPrefix || 'value'; // Set dim `name` and other `coordDim` and other props. for (var resultDimIdx = 0; resultDimIdx < dimCount; resultDimIdx++) { var resultItem = result[resultDimIdx] = result[resultDimIdx] || {}; var coordDim = resultItem.coordDim; coordDim == null && ( resultItem.coordDim = genName(extra, coordDimNameMap, opt.extraFromZero), resultItem.coordDimIndex = 0, resultItem.isExtraCoord = true ); resultItem.name == null && (resultItem.name = genName( resultItem.coordDim, dataDimNameMap )); resultItem.type == null && guessOrdinal(data, resultDimIdx) && (resultItem.type = 'ordinal'); } return result; function applyDim(resultItem, coordDim, coordDimIndex) { if (OTHER_DIMS[coordDim]) { resultItem.otherDims[coordDim] = coordDimIndex; } else { resultItem.coordDim = coordDim; resultItem.coordDimIndex = coordDimIndex; coordDimNameMap.set(coordDim, true); } } function genName(name, map$$1, fromZero) { if (fromZero || map$$1.get(name) != null) { var i = 0; while (map$$1.get(name + i) != null) { i++; } name += i; } map$$1.set(name, true); return name; } } // The rule should not be complex, otherwise user might not // be able to known where the data is wrong. var guessOrdinal = completeDimensions.guessOrdinal = function (data, dimIndex) { for (var i = 0, len = data.length; i < len; i++) { var value = retrieveValue(data[i]); if (!isArray(value)) { return false; } var value = value[dimIndex]; // Consider usage convenience, '1', '2' will be treated as "number". // `isFinit('')` get `true`. if (value != null && isFinite(value) && value !== '') { return false; } else if (isString$1(value) && value !== '-') { return true; } } return false; }; function retrieveValue(o) { return isArray(o) ? o : isObject(o) ? o.value: o; } function firstDataNotNull(data) { var i = 0; while (i < data.length && data[i] == null) { i++; } return data[i]; } function ifNeedCompleteOrdinalData(data) { var sampleItem = firstDataNotNull(data); return sampleItem != null && !isArray(getDataItemValue(sampleItem)); } /** * Helper function to create a list from option data */ function createListFromArray(data, seriesModel, ecModel) { // If data is undefined data = data || []; if (__DEV__) { if (!isArray(data)) { throw new Error('Invalid data.'); } } var coordSysName = seriesModel.get('coordinateSystem'); var creator = creators[coordSysName]; var registeredCoordSys = CoordinateSystemManager.get(coordSysName); var completeDimOpt = { encodeDef: seriesModel.get('encode'), dimsDef: seriesModel.get('dimensions') }; // FIXME var axesInfo = creator && creator(data, seriesModel, ecModel, completeDimOpt); var dimensions = axesInfo && axesInfo.dimensions; if (!dimensions) { // Get dimensions from registered coordinate system dimensions = (registeredCoordSys && ( registeredCoordSys.getDimensionsInfo ? registeredCoordSys.getDimensionsInfo() : registeredCoordSys.dimensions.slice() )) || ['x', 'y']; dimensions = completeDimensions(dimensions, data, completeDimOpt); } var categoryIndex = axesInfo ? axesInfo.categoryIndex : -1; var list = new List(dimensions, seriesModel); var nameList = createNameList(axesInfo, data); var categories = {}; var dimValueGetter = (categoryIndex >= 0 && ifNeedCompleteOrdinalData(data)) ? function (itemOpt, dimName, dataIndex, dimIndex) { // If any dataItem is like { value: 10 } if (isDataItemOption(itemOpt)) { list.hasItemOption = true; } // Use dataIndex as ordinal value in categoryAxis return dimIndex === categoryIndex ? dataIndex : converDataValue(getDataItemValue(itemOpt), dimensions[dimIndex]); } : function (itemOpt, dimName, dataIndex, dimIndex) { var value = getDataItemValue(itemOpt); var val = converDataValue(value && value[dimIndex], dimensions[dimIndex]); // If any dataItem is like { value: 10 } if (isDataItemOption(itemOpt)) { list.hasItemOption = true; } var categoryAxesModels = axesInfo && axesInfo.categoryAxesModels; if (categoryAxesModels && categoryAxesModels[dimName]) { // If given value is a category string if (typeof val === 'string') { // Lazy get categories categories[dimName] = categories[dimName] || categoryAxesModels[dimName].getCategories(); val = indexOf(categories[dimName], val); if (val < 0 && !isNaN(val)) { // In case some one write '1', '2' istead of 1, 2 val = +val; } } } return val; }; list.hasItemOption = false; list.initData(data, nameList, dimValueGetter); return list; } function isStackable(axisType) { return axisType !== 'category' && axisType !== 'time'; } function getDimTypeByAxis(axisType) { return axisType === 'category' ? 'ordinal' : axisType === 'time' ? 'time' : 'float'; } /** * Creaters for each coord system. */ var creators = { cartesian2d: function (data, seriesModel, ecModel, completeDimOpt) { var axesModels = map(['xAxis', 'yAxis'], function (name) { return ecModel.queryComponents({ mainType: name, index: seriesModel.get(name + 'Index'), id: seriesModel.get(name + 'Id') })[0]; }); var xAxisModel = axesModels[0]; var yAxisModel = axesModels[1]; if (__DEV__) { if (!xAxisModel) { throw new Error('xAxis "' + retrieve( seriesModel.get('xAxisIndex'), seriesModel.get('xAxisId'), 0 ) + '" not found'); } if (!yAxisModel) { throw new Error('yAxis "' + retrieve( seriesModel.get('xAxisIndex'), seriesModel.get('yAxisId'), 0 ) + '" not found'); } } var xAxisType = xAxisModel.get('type'); var yAxisType = yAxisModel.get('type'); var dimensions = [ { name: 'x', type: getDimTypeByAxis(xAxisType), stackable: isStackable(xAxisType) }, { name: 'y', // If two category axes type: getDimTypeByAxis(yAxisType), stackable: isStackable(yAxisType) } ]; var isXAxisCateogry = xAxisType === 'category'; var isYAxisCategory = yAxisType === 'category'; dimensions = completeDimensions(dimensions, data, completeDimOpt); var categoryAxesModels = {}; if (isXAxisCateogry) { categoryAxesModels.x = xAxisModel; } if (isYAxisCategory) { categoryAxesModels.y = yAxisModel; } return { dimensions: dimensions, categoryIndex: isXAxisCateogry ? 0 : (isYAxisCategory ? 1 : -1), categoryAxesModels: categoryAxesModels }; }, singleAxis: function (data, seriesModel, ecModel, completeDimOpt) { var singleAxisModel = ecModel.queryComponents({ mainType: 'singleAxis', index: seriesModel.get('singleAxisIndex'), id: seriesModel.get('singleAxisId') })[0]; if (__DEV__) { if (!singleAxisModel) { throw new Error('singleAxis should be specified.'); } } var singleAxisType = singleAxisModel.get('type'); var isCategory = singleAxisType === 'category'; var dimensions = [{ name: 'single', type: getDimTypeByAxis(singleAxisType), stackable: isStackable(singleAxisType) }]; dimensions = completeDimensions(dimensions, data, completeDimOpt); var categoryAxesModels = {}; if (isCategory) { categoryAxesModels.single = singleAxisModel; } return { dimensions: dimensions, categoryIndex: isCategory ? 0 : -1, categoryAxesModels: categoryAxesModels }; }, polar: function (data, seriesModel, ecModel, completeDimOpt) { var polarModel = ecModel.queryComponents({ mainType: 'polar', index: seriesModel.get('polarIndex'), id: seriesModel.get('polarId') })[0]; var angleAxisModel = polarModel.findAxisModel('angleAxis'); var radiusAxisModel = polarModel.findAxisModel('radiusAxis'); if (__DEV__) { if (!angleAxisModel) { throw new Error('angleAxis option not found'); } if (!radiusAxisModel) { throw new Error('radiusAxis option not found'); } } var radiusAxisType = radiusAxisModel.get('type'); var angleAxisType = angleAxisModel.get('type'); var dimensions = [ { name: 'radius', type: getDimTypeByAxis(radiusAxisType), stackable: isStackable(radiusAxisType) }, { name: 'angle', type: getDimTypeByAxis(angleAxisType), stackable: isStackable(angleAxisType) } ]; var isAngleAxisCateogry = angleAxisType === 'category'; var isRadiusAxisCateogry = radiusAxisType === 'category'; dimensions = completeDimensions(dimensions, data, completeDimOpt); var categoryAxesModels = {}; if (isRadiusAxisCateogry) { categoryAxesModels.radius = radiusAxisModel; } if (isAngleAxisCateogry) { categoryAxesModels.angle = angleAxisModel; } return { dimensions: dimensions, categoryIndex: isAngleAxisCateogry ? 1 : (isRadiusAxisCateogry ? 0 : -1), categoryAxesModels: categoryAxesModels }; }, geo: function (data, seriesModel, ecModel, completeDimOpt) { // TODO Region // 多个散点图系列在同一个地区的时候 return { dimensions: completeDimensions([ {name: 'lng'}, {name: 'lat'} ], data, completeDimOpt) }; } }; function createNameList(result, data) { var nameList = []; var categoryDim = result && result.dimensions[result.categoryIndex]; var categoryAxisModel; if (categoryDim) { categoryAxisModel = result.categoryAxesModels[categoryDim.name]; } if (categoryAxisModel) { // FIXME Two category axis var categories = categoryAxisModel.getCategories(); if (categories) { var dataLen = data.length; // Ordered data is given explicitly like // [[3, 0.2], [1, 0.3], [2, 0.15]] // or given scatter data, // pick the category if (isArray(data[0]) && data[0].length > 1) { nameList = []; for (var i = 0; i < dataLen; i++) { nameList[i] = categories[data[i][result.categoryIndex || 0]]; } } else { nameList = categories.slice(0); } } } return nameList; } SeriesModel.extend({ type: 'series.line', dependencies: ['grid', 'polar'], getInitialData: function (option, ecModel) { if (__DEV__) { var coordSys = option.coordinateSystem; if (coordSys !== 'polar' && coordSys !== 'cartesian2d') { throw new Error('Line not support coordinateSystem besides cartesian and polar'); } } return createListFromArray(option.data, this, ecModel); }, defaultOption: { zlevel: 0, // 一级层叠 z: 2, // 二级层叠 coordinateSystem: 'cartesian2d', legendHoverLink: true, hoverAnimation: true, // stack: null // xAxisIndex: 0, // yAxisIndex: 0, // polarIndex: 0, // If clip the overflow value clipOverflow: true, // cursor: null, label: { normal: { position: 'top' } }, // itemStyle: { // normal: {}, // emphasis: {} // }, lineStyle: { normal: { width: 2, type: 'solid' } }, // areaStyle: {}, // false, 'start', 'end', 'middle' step: false, // Disabled if step is true smooth: false, smoothMonotone: null, // 拐点图形类型 symbol: 'emptyCircle', // 拐点图形大小 symbolSize: 4, // 拐点图形旋转控制 symbolRotate: null, // 是否显示 symbol, 只有在 tooltip hover 的时候显示 showSymbol: true, // 标志图形默认只有主轴显示(随主轴标签间隔隐藏策略) showAllSymbol: false, // 是否连接断点 connectNulls: false, // 数据过滤,'average', 'max', 'min', 'sum' sampling: 'none', animationEasing: 'linear', // Disable progressive progressive: 0, hoverLayerThreshold: Infinity } }); // Symbol factory /** * Triangle shape * @inner */ var Triangle = extendShape({ type: 'triangle', shape: { cx: 0, cy: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var cx = shape.cx; var cy = shape.cy; var width = shape.width / 2; var height = shape.height / 2; path.moveTo(cx, cy - height); path.lineTo(cx + width, cy + height); path.lineTo(cx - width, cy + height); path.closePath(); } }); /** * Diamond shape * @inner */ var Diamond = extendShape({ type: 'diamond', shape: { cx: 0, cy: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var cx = shape.cx; var cy = shape.cy; var width = shape.width / 2; var height = shape.height / 2; path.moveTo(cx, cy - height); path.lineTo(cx + width, cy); path.lineTo(cx, cy + height); path.lineTo(cx - width, cy); path.closePath(); } }); /** * Pin shape * @inner */ var Pin = extendShape({ type: 'pin', shape: { // x, y on the cusp x: 0, y: 0, width: 0, height: 0 }, buildPath: function (path, shape) { var x = shape.x; var y = shape.y; var w = shape.width / 5 * 3; // Height must be larger than width var h = Math.max(w, shape.height); var r = w / 2; // Dist on y with tangent point and circle center var dy = r * r / (h - r); var cy = y - h + r + dy; var angle = Math.asin(dy / r); // Dist on x with tangent point and circle center var dx = Math.cos(angle) * r; var tanX = Math.sin(angle); var tanY = Math.cos(angle); var cpLen = r * 0.6; var cpLen2 = r * 0.7; path.moveTo(x - dx, cy + dy); path.arc( x, cy, r, Math.PI - angle, Math.PI * 2 + angle ); path.bezierCurveTo( x + dx - tanX * cpLen, cy + dy + tanY * cpLen, x, y - cpLen2, x, y ); path.bezierCurveTo( x, y - cpLen2, x - dx + tanX * cpLen, cy + dy + tanY * cpLen, x - dx, cy + dy ); path.closePath(); } }); /** * Arrow shape * @inner */ var Arrow = extendShape({ type: 'arrow', shape: { x: 0, y: 0, width: 0, height: 0 }, buildPath: function (ctx, shape) { var height = shape.height; var width = shape.width; var x = shape.x; var y = shape.y; var dx = width / 3 * 2; ctx.moveTo(x, y); ctx.lineTo(x + dx, y + height); ctx.lineTo(x, y + height / 4 * 3); ctx.lineTo(x - dx, y + height); ctx.lineTo(x, y); ctx.closePath(); } }); /** * Map of path contructors * @type {Object.<string, module:zrender/graphic/Path>} */ var symbolCtors = { line: Line, rect: Rect, roundRect: Rect, square: Rect, circle: Circle, diamond: Diamond, pin: Pin, arrow: Arrow, triangle: Triangle }; var symbolShapeMakers = { line: function (x, y, w, h, shape) { // FIXME shape.x1 = x; shape.y1 = y + h / 2; shape.x2 = x + w; shape.y2 = y + h / 2; }, rect: function (x, y, w, h, shape) { shape.x = x; shape.y = y; shape.width = w; shape.height = h; }, roundRect: function (x, y, w, h, shape) { shape.x = x; shape.y = y; shape.width = w; shape.height = h; shape.r = Math.min(w, h) / 4; }, square: function (x, y, w, h, shape) { var size = Math.min(w, h); shape.x = x; shape.y = y; shape.width = size; shape.height = size; }, circle: function (x, y, w, h, shape) { // Put circle in the center of square shape.cx = x + w / 2; shape.cy = y + h / 2; shape.r = Math.min(w, h) / 2; }, diamond: function (x, y, w, h, shape) { shape.cx = x + w / 2; shape.cy = y + h / 2; shape.width = w; shape.height = h; }, pin: function (x, y, w, h, shape) { shape.x = x + w / 2; shape.y = y + h / 2; shape.width = w; shape.height = h; }, arrow: function (x, y, w, h, shape) { shape.x = x + w / 2; shape.y = y + h / 2; shape.width = w; shape.height = h; }, triangle: function (x, y, w, h, shape) { shape.cx = x + w / 2; shape.cy = y + h / 2; shape.width = w; shape.height = h; } }; var symbolBuildProxies = {}; each$1(symbolCtors, function (Ctor, name) { symbolBuildProxies[name] = new Ctor(); }); var SymbolClz$2 = extendShape({ type: 'symbol', shape: { symbolType: '', x: 0, y: 0, width: 0, height: 0 }, beforeBrush: function () { var style = this.style; var shape = this.shape; // FIXME if (shape.symbolType === 'pin' && style.textPosition === 'inside') { style.textPosition = ['50%', '40%']; style.textAlign = 'center'; style.textVerticalAlign = 'middle'; } }, buildPath: function (ctx, shape, inBundle) { var symbolType = shape.symbolType; var proxySymbol = symbolBuildProxies[symbolType]; if (shape.symbolType !== 'none') { if (!proxySymbol) { // Default rect symbolType = 'rect'; proxySymbol = symbolBuildProxies[symbolType]; } symbolShapeMakers[symbolType]( shape.x, shape.y, shape.width, shape.height, proxySymbol.shape ); proxySymbol.buildPath(ctx, proxySymbol.shape, inBundle); } } }); // Provide setColor helper method to avoid determine if set the fill or stroke outside function symbolPathSetColor(color, innerColor) { if (this.type !== 'image') { var symbolStyle = this.style; var symbolShape = this.shape; if (symbolShape && symbolShape.symbolType === 'line') { symbolStyle.stroke = color; } else if (this.__isEmptyBrush) { symbolStyle.stroke = color; symbolStyle.fill = innerColor || '#fff'; } else { // FIXME 判断图形默认是填充还是描边,使用 onlyStroke ? symbolStyle.fill && (symbolStyle.fill = color); symbolStyle.stroke && (symbolStyle.stroke = color); } this.dirty(false); } } /** * Create a symbol element with given symbol configuration: shape, x, y, width, height, color * @param {string} symbolType * @param {number} x * @param {number} y * @param {number} w * @param {number} h * @param {string} color * @param {boolean} [keepAspect=false] whether to keep the ratio of w/h, * for path and image only. */ function createSymbol(symbolType, x, y, w, h, color, keepAspect) { // TODO Support image object, DynamicImage. var isEmpty = symbolType.indexOf('empty') === 0; if (isEmpty) { symbolType = symbolType.substr(5, 1).toLowerCase() + symbolType.substr(6); } var symbolPath; if (symbolType.indexOf('image://') === 0) { symbolPath = makeImage( symbolType.slice(8), new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover' ); } else if (symbolType.indexOf('path://') === 0) { symbolPath = makePath( symbolType.slice(7), {}, new BoundingRect(x, y, w, h), keepAspect ? 'center' : 'cover' ); } else { symbolPath = new SymbolClz$2({ shape: { symbolType: symbolType, x: x, y: y, width: w, height: h } }); } symbolPath.__isEmptyBrush = isEmpty; symbolPath.setColor = symbolPathSetColor; symbolPath.setColor(color); return symbolPath; } /** * @module echarts/chart/helper/Symbol */ function findLabelValueDim(data) { var valueDim; var labelDims = otherDimToDataDim(data, 'label'); if (labelDims.length) { valueDim = labelDims[0]; } else { // Get last value dim var dimensions = data.dimensions.slice(); var dataType; while (dimensions.length && ( valueDim = dimensions.pop(), dataType = data.getDimensionInfo(valueDim).type, dataType === 'ordinal' || dataType === 'time' )) {} // jshint ignore:line } return valueDim; } /** * @module echarts/chart/helper/Symbol */ function getSymbolSize(data, idx) { var symbolSize = data.getItemVisual(idx, 'symbolSize'); return symbolSize instanceof Array ? symbolSize.slice() : [+symbolSize, +symbolSize]; } function getScale(symbolSize) { return [symbolSize[0] / 2, symbolSize[1] / 2]; } /** * @constructor * @alias {module:echarts/chart/helper/Symbol} * @param {module:echarts/data/List} data * @param {number} idx * @extends {module:zrender/graphic/Group} */ function SymbolClz(data, idx, seriesScope) { Group.call(this); this.updateData(data, idx, seriesScope); } var symbolProto = SymbolClz.prototype; function driftSymbol(dx, dy) { this.parent.drift(dx, dy); } symbolProto._createSymbol = function (symbolType, data, idx, symbolSize) { // Remove paths created before this.removeAll(); var color = data.getItemVisual(idx, 'color'); // var symbolPath = createSymbol( // symbolType, -0.5, -0.5, 1, 1, color // ); // If width/height are set too small (e.g., set to 1) on ios10 // and macOS Sierra, a circle stroke become a rect, no matter what // the scale is set. So we set width/height as 2. See #4150. var symbolPath = createSymbol( symbolType, -1, -1, 2, 2, color ); symbolPath.attr({ z2: 100, culling: true, scale: getScale(symbolSize) }); // Rewrite drift method symbolPath.drift = driftSymbol; this._symbolType = symbolType; this.add(symbolPath); }; /** * Stop animation * @param {boolean} toLastFrame */ symbolProto.stopSymbolAnimation = function (toLastFrame) { this.childAt(0).stopAnimation(toLastFrame); }; /** * FIXME: * Caution: This method breaks the encapsulation of this module, * but it indeed brings convenience. So do not use the method * unless you detailedly know all the implements of `Symbol`, * especially animation. * * Get symbol path element. */ symbolProto.getSymbolPath = function () { return this.childAt(0); }; /** * Get scale(aka, current symbol size). * Including the change caused by animation */ symbolProto.getScale = function () { return this.childAt(0).scale; }; /** * Highlight symbol */ symbolProto.highlight = function () { this.childAt(0).trigger('emphasis'); }; /** * Downplay symbol */ symbolProto.downplay = function () { this.childAt(0).trigger('normal'); }; /** * @param {number} zlevel * @param {number} z */ symbolProto.setZ = function (zlevel, z) { var symbolPath = this.childAt(0); symbolPath.zlevel = zlevel; symbolPath.z = z; }; symbolProto.setDraggable = function (draggable) { var symbolPath = this.childAt(0); symbolPath.draggable = draggable; symbolPath.cursor = draggable ? 'move' : 'pointer'; }; /** * Update symbol properties * @param {module:echarts/data/List} data * @param {number} idx * @param {Object} [seriesScope] * @param {Object} [seriesScope.itemStyle] * @param {Object} [seriesScope.hoverItemStyle] * @param {Object} [seriesScope.symbolRotate] * @param {Object} [seriesScope.symbolOffset] * @param {module:echarts/model/Model} [seriesScope.labelModel] * @param {module:echarts/model/Model} [seriesScope.hoverLabelModel] * @param {boolean} [seriesScope.hoverAnimation] * @param {Object} [seriesScope.cursorStyle] * @param {module:echarts/model/Model} [seriesScope.itemModel] * @param {string} [seriesScope.symbolInnerColor] * @param {Object} [seriesScope.fadeIn=false] */ symbolProto.updateData = function (data, idx, seriesScope) { this.silent = false; var symbolType = data.getItemVisual(idx, 'symbol') || 'circle'; var seriesModel = data.hostModel; var symbolSize = getSymbolSize(data, idx); var isInit = symbolType !== this._symbolType; if (isInit) { this._createSymbol(symbolType, data, idx, symbolSize); } else { var symbolPath = this.childAt(0); symbolPath.silent = false; updateProps(symbolPath, { scale: getScale(symbolSize) }, seriesModel, idx); } this._updateCommon(data, idx, symbolSize, seriesScope); if (isInit) { var symbolPath = this.childAt(0); var fadeIn = seriesScope && seriesScope.fadeIn; var target = {scale: symbolPath.scale.slice()}; fadeIn && (target.style = {opacity: symbolPath.style.opacity}); symbolPath.scale = [0, 0]; fadeIn && (symbolPath.style.opacity = 0); initProps(symbolPath, target, seriesModel, idx); } this._seriesModel = seriesModel; }; // Update common properties var normalStyleAccessPath = ['itemStyle', 'normal']; var emphasisStyleAccessPath = ['itemStyle', 'emphasis']; var normalLabelAccessPath = ['label', 'normal']; var emphasisLabelAccessPath = ['label', 'emphasis']; /** * @param {module:echarts/data/List} data * @param {number} idx * @param {Array.<number>} symbolSize * @param {Object} [seriesScope] */ symbolProto._updateCommon = function (data, idx, symbolSize, seriesScope) { var symbolPath = this.childAt(0); var seriesModel = data.hostModel; var color = data.getItemVisual(idx, 'color'); // Reset style if (symbolPath.type !== 'image') { symbolPath.useStyle({ strokeNoScale: true }); } var itemStyle = seriesScope && seriesScope.itemStyle; var hoverItemStyle = seriesScope && seriesScope.hoverItemStyle; var symbolRotate = seriesScope && seriesScope.symbolRotate; var symbolOffset = seriesScope && seriesScope.symbolOffset; var labelModel = seriesScope && seriesScope.labelModel; var hoverLabelModel = seriesScope && seriesScope.hoverLabelModel; var hoverAnimation = seriesScope && seriesScope.hoverAnimation; var cursorStyle = seriesScope && seriesScope.cursorStyle; if (!seriesScope || data.hasItemOption) { var itemModel = (seriesScope && seriesScope.itemModel) ? seriesScope.itemModel : data.getItemModel(idx); // Color must be excluded. // Because symbol provide setColor individually to set fill and stroke itemStyle = itemModel.getModel(normalStyleAccessPath).getItemStyle(['color']); hoverItemStyle = itemModel.getModel(emphasisStyleAccessPath).getItemStyle(); symbolRotate = itemModel.getShallow('symbolRotate'); symbolOffset = itemModel.getShallow('symbolOffset'); labelModel = itemModel.getModel(normalLabelAccessPath); hoverLabelModel = itemModel.getModel(emphasisLabelAccessPath); hoverAnimation = itemModel.getShallow('hoverAnimation'); cursorStyle = itemModel.getShallow('cursor'); } else { hoverItemStyle = extend({}, hoverItemStyle); } var elStyle = symbolPath.style; symbolPath.attr('rotation', (symbolRotate || 0) * Math.PI / 180 || 0); if (symbolOffset) { symbolPath.attr('position', [ parsePercent$1(symbolOffset[0], symbolSize[0]), parsePercent$1(symbolOffset[1], symbolSize[1]) ]); } cursorStyle && symbolPath.attr('cursor', cursorStyle); // PENDING setColor before setStyle!!! symbolPath.setColor(color, seriesScope && seriesScope.symbolInnerColor); symbolPath.setStyle(itemStyle); var opacity = data.getItemVisual(idx, 'opacity'); if (opacity != null) { elStyle.opacity = opacity; } var useNameLabel = seriesScope && seriesScope.useNameLabel; var valueDim = !useNameLabel && findLabelValueDim(data); if (useNameLabel || valueDim != null) { setLabelStyle( elStyle, hoverItemStyle, labelModel, hoverLabelModel, { labelFetcher: seriesModel, labelDataIndex: idx, defaultText: useNameLabel ? data.getName(idx) : data.get(valueDim, idx), isRectText: true, autoColor: color } ); } symbolPath.off('mouseover') .off('mouseout') .off('emphasis') .off('normal'); symbolPath.hoverStyle = hoverItemStyle; // FIXME // Do not use symbol.trigger('emphasis'), but use symbol.highlight() instead. setHoverStyle(symbolPath); var scale = getScale(symbolSize); if (hoverAnimation && seriesModel.isAnimationEnabled()) { var onEmphasis = function() { var ratio = scale[1] / scale[0]; this.animateTo({ scale: [ Math.max(scale[0] * 1.1, scale[0] + 3), Math.max(scale[1] * 1.1, scale[1] + 3 * ratio) ] }, 400, 'elasticOut'); }; var onNormal = function() { this.animateTo({ scale: scale }, 400, 'elasticOut'); }; symbolPath.on('mouseover', onEmphasis) .on('mouseout', onNormal) .on('emphasis', onEmphasis) .on('normal', onNormal); } }; /** * @param {Function} cb * @param {Object} [opt] * @param {Object} [opt.keepLabel=true] */ symbolProto.fadeOut = function (cb, opt) { var symbolPath = this.childAt(0); // Avoid mistaken hover when fading out this.silent = symbolPath.silent = true; // Not show text when animating !(opt && opt.keepLabel) && (symbolPath.style.text = null); updateProps( symbolPath, { style: {opacity: 0}, scale: [0, 0] }, this._seriesModel, this.dataIndex, cb ); }; inherits(SymbolClz, Group); /** * @module echarts/chart/helper/SymbolDraw */ /** * @constructor * @alias module:echarts/chart/helper/SymbolDraw * @param {module:zrender/graphic/Group} [symbolCtor] */ function SymbolDraw(symbolCtor) { this.group = new Group(); this._symbolCtor = symbolCtor || SymbolClz; } var symbolDrawProto = SymbolDraw.prototype; function symbolNeedsDraw(data, idx, isIgnore) { var point = data.getItemLayout(idx); // Is an object // if (point && point.hasOwnProperty('point')) { // point = point.point; // } return point && !isNaN(point[0]) && !isNaN(point[1]) && !(isIgnore && isIgnore(idx)) && data.getItemVisual(idx, 'symbol') !== 'none'; } /** * Update symbols draw by new data * @param {module:echarts/data/List} data * @param {Array.<boolean>} [isIgnore] */ symbolDrawProto.updateData = function (data, isIgnore) { var group = this.group; var seriesModel = data.hostModel; var oldData = this._data; var SymbolCtor = this._symbolCtor; var seriesScope = { itemStyle: seriesModel.getModel('itemStyle.normal').getItemStyle(['color']), hoverItemStyle: seriesModel.getModel('itemStyle.emphasis').getItemStyle(), symbolRotate: seriesModel.get('symbolRotate'), symbolOffset: seriesModel.get('symbolOffset'), hoverAnimation: seriesModel.get('hoverAnimation'), labelModel: seriesModel.getModel('label.normal'), hoverLabelModel: seriesModel.getModel('label.emphasis'), cursorStyle: seriesModel.get('cursor') }; data.diff(oldData) .add(function (newIdx) { var point = data.getItemLayout(newIdx); if (symbolNeedsDraw(data, newIdx, isIgnore)) { var symbolEl = new SymbolCtor(data, newIdx, seriesScope); symbolEl.attr('position', point); data.setItemGraphicEl(newIdx, symbolEl); group.add(symbolEl); } }) .update(function (newIdx, oldIdx) { var symbolEl = oldData.getItemGraphicEl(oldIdx); var point = data.getItemLayout(newIdx); if (!symbolNeedsDraw(data, newIdx, isIgnore)) { group.remove(symbolEl); return; } if (!symbolEl) { symbolEl = new SymbolCtor(data, newIdx); symbolEl.attr('position', point); } else { symbolEl.updateData(data, newIdx, seriesScope); updateProps(symbolEl, { position: point }, seriesModel); } // Add back group.add(symbolEl); data.setItemGraphicEl(newIdx, symbolEl); }) .remove(function (oldIdx) { var el = oldData.getItemGraphicEl(oldIdx); el && el.fadeOut(function () { group.remove(el); }); }) .execute(); this._data = data; }; symbolDrawProto.updateLayout = function () { var data = this._data; if (data) { // Not use animation data.eachItemGraphicEl(function (el, idx) { var point = data.getItemLayout(idx); el.attr('position', point); }); } }; symbolDrawProto.remove = function (enableAnimation) { var group = this.group; var data = this._data; if (data) { if (enableAnimation) { data.eachItemGraphicEl(function (el) { el.fadeOut(function () { group.remove(el); }); }); } else { group.removeAll(); } } }; // var arrayDiff = require('zrender/src/core/arrayDiff'); // 'zrender/src/core/arrayDiff' has been used before, but it did // not do well in performance when roam with fixed dataZoom window. function sign$1(val) { return val >= 0 ? 1 : -1; } function getStackedOnPoint(coordSys, data, idx) { var baseAxis = coordSys.getBaseAxis(); var valueAxis = coordSys.getOtherAxis(baseAxis); var valueStart = baseAxis.onZero ? 0 : valueAxis.scale.getExtent()[0]; var valueDim = valueAxis.dim; var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0; var stackedOnSameSign; var stackedOn = data.stackedOn; var val = data.get(valueDim, idx); // Find first stacked value with same sign while (stackedOn && sign$1(stackedOn.get(valueDim, idx)) === sign$1(val) ) { stackedOnSameSign = stackedOn; break; } var stackedData = []; stackedData[baseDataOffset] = data.get(baseAxis.dim, idx); stackedData[1 - baseDataOffset] = stackedOnSameSign ? stackedOnSameSign.get(valueDim, idx, true) : valueStart; return coordSys.dataToPoint(stackedData); } // function convertToIntId(newIdList, oldIdList) { // // Generate int id instead of string id. // // Compare string maybe slow in score function of arrDiff // // Assume id in idList are all unique // var idIndicesMap = {}; // var idx = 0; // for (var i = 0; i < newIdList.length; i++) { // idIndicesMap[newIdList[i]] = idx; // newIdList[i] = idx++; // } // for (var i = 0; i < oldIdList.length; i++) { // var oldId = oldIdList[i]; // // Same with newIdList // if (idIndicesMap[oldId]) { // oldIdList[i] = idIndicesMap[oldId]; // } // else { // oldIdList[i] = idx++; // } // } // } function diffData(oldData, newData) { var diffResult = []; newData.diff(oldData) .add(function (idx) { diffResult.push({cmd: '+', idx: idx}); }) .update(function (newIdx, oldIdx) { diffResult.push({cmd: '=', idx: oldIdx, idx1: newIdx}); }) .remove(function (idx) { diffResult.push({cmd: '-', idx: idx}); }) .execute(); return diffResult; } var lineAnimationDiff = function ( oldData, newData, oldStackedOnPoints, newStackedOnPoints, oldCoordSys, newCoordSys ) { var diff = diffData(oldData, newData); // var newIdList = newData.mapArray(newData.getId); // var oldIdList = oldData.mapArray(oldData.getId); // convertToIntId(newIdList, oldIdList); // // FIXME One data ? // diff = arrayDiff(oldIdList, newIdList); var currPoints = []; var nextPoints = []; // Points for stacking base line var currStackedPoints = []; var nextStackedPoints = []; var status = []; var sortedIndices = []; var rawIndices = []; var dims = newCoordSys.dimensions; for (var i = 0; i < diff.length; i++) { var diffItem = diff[i]; var pointAdded = true; // FIXME, animation is not so perfect when dataZoom window moves fast // Which is in case remvoing or add more than one data in the tail or head switch (diffItem.cmd) { case '=': var currentPt = oldData.getItemLayout(diffItem.idx); var nextPt = newData.getItemLayout(diffItem.idx1); // If previous data is NaN, use next point directly if (isNaN(currentPt[0]) || isNaN(currentPt[1])) { currentPt = nextPt.slice(); } currPoints.push(currentPt); nextPoints.push(nextPt); currStackedPoints.push(oldStackedOnPoints[diffItem.idx]); nextStackedPoints.push(newStackedOnPoints[diffItem.idx1]); rawIndices.push(newData.getRawIndex(diffItem.idx1)); break; case '+': var idx = diffItem.idx; currPoints.push( oldCoordSys.dataToPoint([ newData.get(dims[0], idx, true), newData.get(dims[1], idx, true) ]) ); nextPoints.push(newData.getItemLayout(idx).slice()); currStackedPoints.push( getStackedOnPoint(oldCoordSys, newData, idx) ); nextStackedPoints.push(newStackedOnPoints[idx]); rawIndices.push(newData.getRawIndex(idx)); break; case '-': var idx = diffItem.idx; var rawIndex = oldData.getRawIndex(idx); // Data is replaced. In the case of dynamic data queue // FIXME FIXME FIXME if (rawIndex !== idx) { currPoints.push(oldData.getItemLayout(idx)); nextPoints.push(newCoordSys.dataToPoint([ oldData.get(dims[0], idx, true), oldData.get(dims[1], idx, true) ])); currStackedPoints.push(oldStackedOnPoints[idx]); nextStackedPoints.push( getStackedOnPoint( newCoordSys, oldData, idx ) ); rawIndices.push(rawIndex); } else { pointAdded = false; } } // Original indices if (pointAdded) { status.push(diffItem); sortedIndices.push(sortedIndices.length); } } // Diff result may be crossed if all items are changed // Sort by data index sortedIndices.sort(function (a, b) { return rawIndices[a] - rawIndices[b]; }); var sortedCurrPoints = []; var sortedNextPoints = []; var sortedCurrStackedPoints = []; var sortedNextStackedPoints = []; var sortedStatus = []; for (var i = 0; i < sortedIndices.length; i++) { var idx = sortedIndices[i]; sortedCurrPoints[i] = currPoints[idx]; sortedNextPoints[i] = nextPoints[idx]; sortedCurrStackedPoints[i] = currStackedPoints[idx]; sortedNextStackedPoints[i] = nextStackedPoints[idx]; sortedStatus[i] = status[idx]; } return { current: sortedCurrPoints, next: sortedNextPoints, stackedOnCurrent: sortedCurrStackedPoints, stackedOnNext: sortedNextStackedPoints, status: sortedStatus }; }; // Poly path support NaN point var vec2Min = min; var vec2Max = max; var scaleAndAdd$1 = scaleAndAdd; var v2Copy = copy; // Temporary variable var v = []; var cp0 = []; var cp1 = []; function isPointNull(p) { return isNaN(p[0]) || isNaN(p[1]); } function drawSegment( ctx, points, start, segLen, allLen, dir, smoothMin, smoothMax, smooth, smoothMonotone, connectNulls ) { var prevIdx = 0; var idx = start; for (var k = 0; k < segLen; k++) { var p = points[idx]; if (idx >= allLen || idx < 0) { break; } if (isPointNull(p)) { if (connectNulls) { idx += dir; continue; } break; } if (idx === start) { ctx[dir > 0 ? 'moveTo' : 'lineTo'](p[0], p[1]); v2Copy(cp0, p); } else { if (smooth > 0) { var nextIdx = idx + dir; var nextP = points[nextIdx]; if (connectNulls) { // Find next point not null while (nextP && isPointNull(points[nextIdx])) { nextIdx += dir; nextP = points[nextIdx]; } } var ratioNextSeg = 0.5; var prevP = points[prevIdx]; var nextP = points[nextIdx]; // Last point if (!nextP || isPointNull(nextP)) { v2Copy(cp1, p); } else { // If next data is null in not connect case if (isPointNull(nextP) && !connectNulls) { nextP = p; } sub(v, nextP, prevP); var lenPrevSeg; var lenNextSeg; if (smoothMonotone === 'x' || smoothMonotone === 'y') { var dim = smoothMonotone === 'x' ? 0 : 1; lenPrevSeg = Math.abs(p[dim] - prevP[dim]); lenNextSeg = Math.abs(p[dim] - nextP[dim]); } else { lenPrevSeg = dist(p, prevP); lenNextSeg = dist(p, nextP); } // Use ratio of seg length ratioNextSeg = lenNextSeg / (lenNextSeg + lenPrevSeg); scaleAndAdd$1(cp1, p, v, -smooth * (1 - ratioNextSeg)); } // Smooth constraint vec2Min(cp0, cp0, smoothMax); vec2Max(cp0, cp0, smoothMin); vec2Min(cp1, cp1, smoothMax); vec2Max(cp1, cp1, smoothMin); ctx.bezierCurveTo( cp0[0], cp0[1], cp1[0], cp1[1], p[0], p[1] ); // cp0 of next segment scaleAndAdd$1(cp0, p, v, smooth * ratioNextSeg); } else { ctx.lineTo(p[0], p[1]); } } prevIdx = idx; idx += dir; } return k; } function getBoundingBox(points, smoothConstraint) { var ptMin = [Infinity, Infinity]; var ptMax = [-Infinity, -Infinity]; if (smoothConstraint) { for (var i = 0; i < points.length; i++) { var pt = points[i]; if (pt[0] < ptMin[0]) { ptMin[0] = pt[0]; } if (pt[1] < ptMin[1]) { ptMin[1] = pt[1]; } if (pt[0] > ptMax[0]) { ptMax[0] = pt[0]; } if (pt[1] > ptMax[1]) { ptMax[1] = pt[1]; } } } return { min: smoothConstraint ? ptMin : ptMax, max: smoothConstraint ? ptMax : ptMin }; } var Polyline$1 = Path.extend({ type: 'ec-polyline', shape: { points: [], smooth: 0, smoothConstraint: true, smoothMonotone: null, connectNulls: false }, style: { fill: null, stroke: '#000' }, brush: fixClipWithShadow(Path.prototype.brush), buildPath: function (ctx, shape) { var points = shape.points; var i = 0; var len$$1 = points.length; var result = getBoundingBox(points, shape.smoothConstraint); if (shape.connectNulls) { // Must remove first and last null values avoid draw error in polygon for (; len$$1 > 0; len$$1--) { if (!isPointNull(points[len$$1 - 1])) { break; } } for (; i < len$$1; i++) { if (!isPointNull(points[i])) { break; } } } while (i < len$$1) { i += drawSegment( ctx, points, i, len$$1, len$$1, 1, result.min, result.max, shape.smooth, shape.smoothMonotone, shape.connectNulls ) + 1; } } }); var Polygon$1 = Path.extend({ type: 'ec-polygon', shape: { points: [], // Offset between stacked base points and points stackedOnPoints: [], smooth: 0, stackedOnSmooth: 0, smoothConstraint: true, smoothMonotone: null, connectNulls: false }, brush: fixClipWithShadow(Path.prototype.brush), buildPath: function (ctx, shape) { var points = shape.points; var stackedOnPoints = shape.stackedOnPoints; var i = 0; var len$$1 = points.length; var smoothMonotone = shape.smoothMonotone; var bbox = getBoundingBox(points, shape.smoothConstraint); var stackedOnBBox = getBoundingBox(stackedOnPoints, shape.smoothConstraint); if (shape.connectNulls) { // Must remove first and last null values avoid draw error in polygon for (; len$$1 > 0; len$$1--) { if (!isPointNull(points[len$$1 - 1])) { break; } } for (; i < len$$1; i++) { if (!isPointNull(points[i])) { break; } } } while (i < len$$1) { var k = drawSegment( ctx, points, i, len$$1, len$$1, 1, bbox.min, bbox.max, shape.smooth, smoothMonotone, shape.connectNulls ); drawSegment( ctx, stackedOnPoints, i + k - 1, k, len$$1, -1, stackedOnBBox.min, stackedOnBBox.max, shape.stackedOnSmooth, smoothMonotone, shape.connectNulls ); i += k + 1; ctx.closePath(); } } }); // FIXME step not support polar function isPointsSame(points1, points2) { if (points1.length !== points2.length) { return; } for (var i = 0; i < points1.length; i++) { var p1 = points1[i]; var p2 = points2[i]; if (p1[0] !== p2[0] || p1[1] !== p2[1]) { return; } } return true; } function getSmooth(smooth) { return typeof (smooth) === 'number' ? smooth : (smooth ? 0.3 : 0); } function getAxisExtentWithGap(axis) { var extent = axis.getGlobalExtent(); if (axis.onBand) { // Remove extra 1px to avoid line miter in clipped edge var halfBandWidth = axis.getBandWidth() / 2 - 1; var dir = extent[1] > extent[0] ? 1 : -1; extent[0] += dir * halfBandWidth; extent[1] -= dir * halfBandWidth; } return extent; } function sign(val) { return val >= 0 ? 1 : -1; } /** * @param {module:echarts/coord/cartesian/Cartesian2D|module:echarts/coord/polar/Polar} coordSys * @param {module:echarts/data/List} data * @param {Array.<Array.<number>>} points * @private */ function getStackedOnPoints(coordSys, data) { var baseAxis = coordSys.getBaseAxis(); var valueAxis = coordSys.getOtherAxis(baseAxis); var valueStart = 0; if (!baseAxis.onZero) { var extent = valueAxis.scale.getExtent(); if (extent[0] > 0) { // Both positive valueStart = extent[0]; } else if (extent[1] < 0) { // Both negative valueStart = extent[1]; } // If is one positive, and one negative, onZero shall be true } var valueDim = valueAxis.dim; var baseDataOffset = valueDim === 'x' || valueDim === 'radius' ? 1 : 0; return data.mapArray([valueDim], function (val, idx) { var stackedOnSameSign; var stackedOn = data.stackedOn; // Find first stacked value with same sign while (stackedOn && sign(stackedOn.get(valueDim, idx)) === sign(val) ) { stackedOnSameSign = stackedOn; break; } var stackedData = []; stackedData[baseDataOffset] = data.get(baseAxis.dim, idx); stackedData[1 - baseDataOffset] = stackedOnSameSign ? stackedOnSameSign.get(valueDim, idx, true) : valueStart; return coordSys.dataToPoint(stackedData); }, true); } function createGridClipShape(cartesian, hasAnimation, seriesModel) { var xExtent = getAxisExtentWithGap(cartesian.getAxis('x')); var yExtent = getAxisExtentWithGap(cartesian.getAxis('y')); var isHorizontal = cartesian.getBaseAxis().isHorizontal(); var x = Math.min(xExtent[0], xExtent[1]); var y = Math.min(yExtent[0], yExtent[1]); var width = Math.max(xExtent[0], xExtent[1]) - x; var height = Math.max(yExtent[0], yExtent[1]) - y; var lineWidth = seriesModel.get('lineStyle.normal.width') || 2; // Expand clip shape to avoid clipping when line value exceeds axis var expandSize = seriesModel.get('clipOverflow') ? lineWidth / 2 : Math.max(width, height); if (isHorizontal) { y -= expandSize; height += expandSize * 2; } else { x -= expandSize; width += expandSize * 2; } var clipPath = new Rect({ shape: { x: x, y: y, width: width, height: height } }); if (hasAnimation) { clipPath.shape[isHorizontal ? 'width' : 'height'] = 0; initProps(clipPath, { shape: { width: width, height: height } }, seriesModel); } return clipPath; } function createPolarClipShape(polar, hasAnimation, seriesModel) { var angleAxis = polar.getAngleAxis(); var radiusAxis = polar.getRadiusAxis(); var radiusExtent = radiusAxis.getExtent(); var angleExtent = angleAxis.getExtent(); var RADIAN = Math.PI / 180; var clipPath = new Sector({ shape: { cx: polar.cx, cy: polar.cy, r0: radiusExtent[0], r: radiusExtent[1], startAngle: -angleExtent[0] * RADIAN, endAngle: -angleExtent[1] * RADIAN, clockwise: angleAxis.inverse } }); if (hasAnimation) { clipPath.shape.endAngle = -angleExtent[0] * RADIAN; initProps(clipPath, { shape: { endAngle: -angleExtent[1] * RADIAN } }, seriesModel); } return clipPath; } function createClipShape(coordSys, hasAnimation, seriesModel) { return coordSys.type === 'polar' ? createPolarClipShape(coordSys, hasAnimation, seriesModel) : createGridClipShape(coordSys, hasAnimation, seriesModel); } function turnPointsIntoStep(points, coordSys, stepTurnAt) { var baseAxis = coordSys.getBaseAxis(); var baseIndex = baseAxis.dim === 'x' || baseAxis.dim === 'radius' ? 0 : 1; var stepPoints = []; for (var i = 0; i < points.length - 1; i++) { var nextPt = points[i + 1]; var pt = points[i]; stepPoints.push(pt); var stepPt = []; switch (stepTurnAt) { case 'end': stepPt[baseIndex] = nextPt[baseIndex]; stepPt[1 - baseIndex] = pt[1 - baseIndex]; // default is start stepPoints.push(stepPt); break; case 'middle': // default is start var middle = (pt[baseIndex] + nextPt[baseIndex]) / 2; var stepPt2 = []; stepPt[baseIndex] = stepPt2[baseIndex] = middle; stepPt[1 - baseIndex] = pt[1 - baseIndex]; stepPt2[1 - baseIndex] = nextPt[1 - baseIndex]; stepPoints.push(stepPt); stepPoints.push(stepPt2); break; default: stepPt[baseIndex] = pt[baseIndex]; stepPt[1 - baseIndex] = nextPt[1 - baseIndex]; // default is start stepPoints.push(stepPt); } } // Last points points[i] && stepPoints.push(points[i]); return stepPoints; } function getVisualGradient(data, coordSys) { var visualMetaList = data.getVisual('visualMeta'); if (!visualMetaList || !visualMetaList.length || !data.count()) { // When data.count() is 0, gradient range can not be calculated. return; } var visualMeta; for (var i = visualMetaList.length - 1; i >= 0; i--) { // Can only be x or y if (visualMetaList[i].dimension < 2) { visualMeta = visualMetaList[i]; break; } } if (!visualMeta || coordSys.type !== 'cartesian2d') { if (__DEV__) { console.warn('Visual map on line style only support x or y dimension.'); } return; } // If the area to be rendered is bigger than area defined by LinearGradient, // the canvas spec prescribes that the color of the first stop and the last // stop should be used. But if two stops are added at offset 0, in effect // browsers use the color of the second stop to render area outside // LinearGradient. So we can only infinitesimally extend area defined in // LinearGradient to render `outerColors`. var dimension = visualMeta.dimension; var dimName = data.dimensions[dimension]; var axis = coordSys.getAxis(dimName); // dataToCoor mapping may not be linear, but must be monotonic. var colorStops = map(visualMeta.stops, function (stop) { return { coord: axis.toGlobalCoord(axis.dataToCoord(stop.value)), color: stop.color }; }); var stopLen = colorStops.length; var outerColors = visualMeta.outerColors.slice(); if (stopLen && colorStops[0].coord > colorStops[stopLen - 1].coord) { colorStops.reverse(); outerColors.reverse(); } var tinyExtent = 10; // Arbitrary value: 10px var minCoord = colorStops[0].coord - tinyExtent; var maxCoord = colorStops[stopLen - 1].coord + tinyExtent; var coordSpan = maxCoord - minCoord; if (coordSpan < 1e-3) { return 'transparent'; } each$1(colorStops, function (stop) { stop.offset = (stop.coord - minCoord) / coordSpan; }); colorStops.push({ offset: stopLen ? colorStops[stopLen - 1].offset : 0.5, color: outerColors[1] || 'transparent' }); colorStops.unshift({ // notice colorStops.length have been changed. offset: stopLen ? colorStops[0].offset : 0.5, color: outerColors[0] || 'transparent' }); // zrUtil.each(colorStops, function (colorStop) { // // Make sure each offset has rounded px to avoid not sharp edge // colorStop.offset = (Math.round(colorStop.offset * (end - start) + start) - start) / (end - start); // }); var gradient = new LinearGradient(0, 0, 0, 0, colorStops, true); gradient[dimName] = minCoord; gradient[dimName + '2'] = maxCoord; return gradient; } Chart.extend({ type: 'line', init: function () { var lineGroup = new Group(); var symbolDraw = new SymbolDraw(); this.group.add(symbolDraw.group); this._symbolDraw = symbolDraw; this._lineGroup = lineGroup; }, render: function (seriesModel, ecModel, api) { var coordSys = seriesModel.coordinateSystem; var group = this.group; var data = seriesModel.getData(); var lineStyleModel = seriesModel.getModel('lineStyle.normal'); var areaStyleModel = seriesModel.getModel('areaStyle.normal'); var points = data.mapArray(data.getItemLayout, true); var isCoordSysPolar = coordSys.type === 'polar'; var prevCoordSys = this._coordSys; var symbolDraw = this._symbolDraw; var polyline = this._polyline; var polygon = this._polygon; var lineGroup = this._lineGroup; var hasAnimation = seriesModel.get('animation'); var isAreaChart = !areaStyleModel.isEmpty(); var stackedOnPoints = getStackedOnPoints(coordSys, data); var showSymbol = seriesModel.get('showSymbol'); var isSymbolIgnore = showSymbol && !isCoordSysPolar && !seriesModel.get('showAllSymbol') && this._getSymbolIgnoreFunc(data, coordSys); // Remove temporary symbols var oldData = this._data; oldData && oldData.eachItemGraphicEl(function (el, idx) { if (el.__temp) { group.remove(el); oldData.setItemGraphicEl(idx, null); } }); // Remove previous created symbols if showSymbol changed to false if (!showSymbol) { symbolDraw.remove(); } group.add(lineGroup); // FIXME step not support polar var step = !isCoordSysPolar && seriesModel.get('step'); // Initialization animation or coordinate system changed if ( !(polyline && prevCoordSys.type === coordSys.type && step === this._step) ) { showSymbol && symbolDraw.updateData(data, isSymbolIgnore); if (step) { // TODO If stacked series is not step points = turnPointsIntoStep(points, coordSys, step); stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step); } polyline = this._newPolyline(points, coordSys, hasAnimation); if (isAreaChart) { polygon = this._newPolygon( points, stackedOnPoints, coordSys, hasAnimation ); } lineGroup.setClipPath(createClipShape(coordSys, true, seriesModel)); } else { if (isAreaChart && !polygon) { // If areaStyle is added polygon = this._newPolygon( points, stackedOnPoints, coordSys, hasAnimation ); } else if (polygon && !isAreaChart) { // If areaStyle is removed lineGroup.remove(polygon); polygon = this._polygon = null; } // Update clipPath lineGroup.setClipPath(createClipShape(coordSys, false, seriesModel)); // Always update, or it is wrong in the case turning on legend // because points are not changed showSymbol && symbolDraw.updateData(data, isSymbolIgnore); // Stop symbol animation and sync with line points // FIXME performance? data.eachItemGraphicEl(function (el) { el.stopAnimation(true); }); // In the case data zoom triggerred refreshing frequently // Data may not change if line has a category axis. So it should animate nothing if (!isPointsSame(this._stackedOnPoints, stackedOnPoints) || !isPointsSame(this._points, points) ) { if (hasAnimation) { this._updateAnimation( data, stackedOnPoints, coordSys, api, step ); } else { // Not do it in update with animation if (step) { // TODO If stacked series is not step points = turnPointsIntoStep(points, coordSys, step); stackedOnPoints = turnPointsIntoStep(stackedOnPoints, coordSys, step); } polyline.setShape({ points: points }); polygon && polygon.setShape({ points: points, stackedOnPoints: stackedOnPoints }); } } } var visualColor = getVisualGradient(data, coordSys) || data.getVisual('color'); polyline.useStyle(defaults( // Use color in lineStyle first lineStyleModel.getLineStyle(), { fill: 'none', stroke: visualColor, lineJoin: 'bevel' } )); var smooth = seriesModel.get('smooth'); smooth = getSmooth(seriesModel.get('smooth')); polyline.setShape({ smooth: smooth, smoothMonotone: seriesModel.get('smoothMonotone'), connectNulls: seriesModel.get('connectNulls') }); if (polygon) { var stackedOn = data.stackedOn; var stackedOnSmooth = 0; polygon.useStyle(defaults( areaStyleModel.getAreaStyle(), { fill: visualColor, opacity: 0.7, lineJoin: 'bevel' } )); if (stackedOn) { var stackedOnSeries = stackedOn.hostModel; stackedOnSmooth = getSmooth(stackedOnSeries.get('smooth')); } polygon.setShape({ smooth: smooth, stackedOnSmooth: stackedOnSmooth, smoothMonotone: seriesModel.get('smoothMonotone'), connectNulls: seriesModel.get('connectNulls') }); } this._data = data; // Save the coordinate system for transition animation when data changed this._coordSys = coordSys; this._stackedOnPoints = stackedOnPoints; this._points = points; this._step = step; }, dispose: function () {}, highlight: function (seriesModel, ecModel, api, payload) { var data = seriesModel.getData(); var dataIndex = queryDataIndex(data, payload); if (!(dataIndex instanceof Array) && dataIndex != null && dataIndex >= 0) { var symbol = data.getItemGraphicEl(dataIndex); if (!symbol) { // Create a temporary symbol if it is not exists var pt = data.getItemLayout(dataIndex); if (!pt) { // Null data return; } symbol = new SymbolClz(data, dataIndex); symbol.position = pt; symbol.setZ( seriesModel.get('zlevel'), seriesModel.get('z') ); symbol.ignore = isNaN(pt[0]) || isNaN(pt[1]); symbol.__temp = true; data.setItemGraphicEl(dataIndex, symbol); // Stop scale animation symbol.stopSymbolAnimation(true); this.group.add(symbol); } symbol.highlight(); } else { // Highlight whole series Chart.prototype.highlight.call( this, seriesModel, ecModel, api, payload ); } }, downplay: function (seriesModel, ecModel, api, payload) { var data = seriesModel.getData(); var dataIndex = queryDataIndex(data, payload); if (dataIndex != null && dataIndex >= 0) { var symbol = data.getItemGraphicEl(dataIndex); if (symbol) { if (symbol.__temp) { data.setItemGraphicEl(dataIndex, null); this.group.remove(symbol); } else { symbol.downplay(); } } } else { // FIXME // can not downplay completely. // Downplay whole series Chart.prototype.downplay.call( this, seriesModel, ecModel, api, payload ); } }, /** * @param {module:zrender/container/Group} group * @param {Array.<Array.<number>>} points * @private */ _newPolyline: function (points) { var polyline = this._polyline; // Remove previous created polyline if (polyline) { this._lineGroup.remove(polyline); } polyline = new Polyline$1({ shape: { points: points }, silent: true, z2: 10 }); this._lineGroup.add(polyline); this._polyline = polyline; return polyline; }, /** * @param {module:zrender/container/Group} group * @param {Array.<Array.<number>>} stackedOnPoints * @param {Array.<Array.<number>>} points * @private */ _newPolygon: function (points, stackedOnPoints) { var polygon = this._polygon; // Remove previous created polygon if (polygon) { this._lineGroup.remove(polygon); } polygon = new Polygon$1({ shape: { points: points, stackedOnPoints: stackedOnPoints }, silent: true }); this._lineGroup.add(polygon); this._polygon = polygon; return polygon; }, /** * @private */ _getSymbolIgnoreFunc: function (data, coordSys) { var categoryAxis = coordSys.getAxesByScale('ordinal')[0]; // `getLabelInterval` is provided by echarts/component/axis if (categoryAxis && categoryAxis.isLabelIgnored) { return bind(categoryAxis.isLabelIgnored, categoryAxis); } }, /** * @private */ // FIXME Two value axis _updateAnimation: function (data, stackedOnPoints, coordSys, api, step) { var polyline = this._polyline; var polygon = this._polygon; var seriesModel = data.hostModel; var diff = lineAnimationDiff( this._data, data, this._stackedOnPoints, stackedOnPoints, this._coordSys, coordSys ); var current = diff.current; var stackedOnCurrent = diff.stackedOnCurrent; var next = diff.next; var stackedOnNext = diff.stackedOnNext; if (step) { // TODO If stacked series is not step current = turnPointsIntoStep(diff.current, coordSys, step); stackedOnCurrent = turnPointsIntoStep(diff.stackedOnCurrent, coordSys, step); next = turnPointsIntoStep(diff.next, coordSys, step); stackedOnNext = turnPointsIntoStep(diff.stackedOnNext, coordSys, step); } // `diff.current` is subset of `current` (which should be ensured by // turnPointsIntoStep), so points in `__points` can be updated when // points in `current` are update during animation. polyline.shape.__points = diff.current; polyline.shape.points = current; updateProps(polyline, { shape: { points: next } }, seriesModel); if (polygon) { polygon.setShape({ points: current, stackedOnPoints: stackedOnCurrent }); updateProps(polygon, { shape: { points: next, stackedOnPoints: stackedOnNext } }, seriesModel); } var updatedDataInfo = []; var diffStatus = diff.status; for (var i = 0; i < diffStatus.length; i++) { var cmd = diffStatus[i].cmd; if (cmd === '=') { var el = data.getItemGraphicEl(diffStatus[i].idx1); if (el) { updatedDataInfo.push({ el: el, ptIdx: i // Index of points }); } } } if (polyline.animators && polyline.animators.length) { polyline.animators[0].during(function () { for (var i = 0; i < updatedDataInfo.length; i++) { var el = updatedDataInfo[i].el; el.attr('position', polyline.shape.__points[updatedDataInfo[i].ptIdx]); } }); } }, remove: function (ecModel) { var group = this.group; var oldData = this._data; this._lineGroup.removeAll(); this._symbolDraw.remove(true); // Remove temporary created elements when highlighting oldData && oldData.eachItemGraphicEl(function (el, idx) { if (el.__temp) { group.remove(el); oldData.setItemGraphicEl(idx, null); } }); this._polyline = this._polygon = this._coordSys = this._points = this._stackedOnPoints = this._data = null; } }); var visualSymbol = function (seriesType, defaultSymbolType, legendSymbol, ecModel, api) { // Encoding visual for all series include which is filtered for legend drawing ecModel.eachRawSeriesByType(seriesType, function (seriesModel) { var data = seriesModel.getData(); var symbolType = seriesModel.get('symbol') || defaultSymbolType; var symbolSize = seriesModel.get('symbolSize'); data.setVisual({ legendSymbol: legendSymbol || symbolType, symbol: symbolType, symbolSize: symbolSize }); // Only visible series has each data be visual encoded if (!ecModel.isSeriesFiltered(seriesModel)) { if (typeof symbolSize === 'function') { data.each(function (idx) { var rawValue = seriesModel.getRawValue(idx); // FIXME var params = seriesModel.getDataParams(idx); data.setItemVisual(idx, 'symbolSize', symbolSize(rawValue, params)); }); } data.each(function (idx) { var itemModel = data.getItemModel(idx); var itemSymbolType = itemModel.getShallow('symbol', true); var itemSymbolSize = itemModel.getShallow('symbolSize', true); // If has item symbol if (itemSymbolType != null) { data.setItemVisual(idx, 'symbol', itemSymbolType); } if (itemSymbolSize != null) { // PENDING Transform symbolSize ? data.setItemVisual(idx, 'symbolSize', itemSymbolSize); } }); } }); }; var layoutPoints = function (seriesType, ecModel) { ecModel.eachSeriesByType(seriesType, function (seriesModel) { var data = seriesModel.getData(); var coordSys = seriesModel.coordinateSystem; if (!coordSys) { return; } var dims = []; var coordDims = coordSys.dimensions; for (var i = 0; i < coordDims.length; i++) { dims.push(seriesModel.coordDimToDataDim(coordSys.dimensions[i])[0]); } if (dims.length === 1) { data.each(dims[0], function (x, idx) { // Also {Array.<number>}, not undefined to avoid if...else... statement data.setItemLayout(idx, isNaN(x) ? [NaN, NaN] : coordSys.dataToPoint(x)); }); } else if (dims.length === 2) { data.each(dims, function (x, y, idx) { // Also {Array.<number>}, not undefined to avoid if...else... statement data.setItemLayout( idx, (isNaN(x) || isNaN(y)) ? [NaN, NaN] : coordSys.dataToPoint([x, y]) ); }, true); } }); }; var samplers = { average: function (frame) { var sum = 0; var count = 0; for (var i = 0; i < frame.length; i++) { if (!isNaN(frame[i])) { sum += frame[i]; count++; } } // Return NaN if count is 0 return count === 0 ? NaN : sum / count; }, sum: function (frame) { var sum = 0; for (var i = 0; i < frame.length; i++) { // Ignore NaN sum += frame[i] || 0; } return sum; }, max: function (frame) { var max = -Infinity; for (var i = 0; i < frame.length; i++) { frame[i] > max && (max = frame[i]); } return max; }, min: function (frame) { var min = Infinity; for (var i = 0; i < frame.length; i++) { frame[i] < min && (min = frame[i]); } return min; }, // TODO // Median nearest: function (frame) { return frame[0]; } }; var indexSampler = function (frame, value) { return Math.round(frame.length / 2); }; var dataSample = function (seriesType, ecModel, api) { ecModel.eachSeriesByType(seriesType, function (seriesModel) { var data = seriesModel.getData(); var sampling = seriesModel.get('sampling'); var coordSys = seriesModel.coordinateSystem; // Only cartesian2d support down sampling if (coordSys.type === 'cartesian2d' && sampling) { var baseAxis = coordSys.getBaseAxis(); var valueAxis = coordSys.getOtherAxis(baseAxis); var extent = baseAxis.getExtent(); // Coordinste system has been resized var size = extent[1] - extent[0]; var rate = Math.round(data.count() / size); if (rate > 1) { var sampler; if (typeof sampling === 'string') { sampler = samplers[sampling]; } else if (typeof sampling === 'function') { sampler = sampling; } if (sampler) { data = data.downSample( valueAxis.dim, 1 / rate, sampler, indexSampler ); seriesModel.setData(data); } } } }, this); }; /** * // Scale class management * @module echarts/scale/Scale */ /** * @param {Object} [setting] */ function Scale(setting) { this._setting = setting || {}; /** * Extent * @type {Array.<number>} * @protected */ this._extent = [Infinity, -Infinity]; /** * Step is calculated in adjustExtent * @type {Array.<number>} * @protected */ this._interval = 0; this.init && this.init.apply(this, arguments); } var scaleProto$1 = Scale.prototype; /** * Parse input val to valid inner number. * @param {*} val * @return {number} */ scaleProto$1.parse = function (val) { // Notice: This would be a trap here, If the implementation // of this method depends on extent, and this method is used // before extent set (like in dataZoom), it would be wrong. // Nevertheless, parse does not depend on extent generally. return val; }; scaleProto$1.getSetting = function (name) { return this._setting[name]; }; scaleProto$1.contain = function (val) { var extent = this._extent; return val >= extent[0] && val <= extent[1]; }; /** * Normalize value to linear [0, 1], return 0.5 if extent span is 0 * @param {number} val * @return {number} */ scaleProto$1.normalize = function (val) { var extent = this._extent; if (extent[1] === extent[0]) { return 0.5; } return (val - extent[0]) / (extent[1] - extent[0]); }; /** * Scale normalized value * @param {number} val * @return {number} */ scaleProto$1.scale = function (val) { var extent = this._extent; return val * (extent[1] - extent[0]) + extent[0]; }; /** * Set extent from data * @param {Array.<number>} other */ scaleProto$1.unionExtent = function (other) { var extent = this._extent; other[0] < extent[0] && (extent[0] = other[0]); other[1] > extent[1] && (extent[1] = other[1]); // not setExtent because in log axis it may transformed to power // this.setExtent(extent[0], extent[1]); }; /** * Set extent from data * @param {module:echarts/data/List} data * @param {string} dim */ scaleProto$1.unionExtentFromData = function (data, dim) { this.unionExtent(data.getDataExtent(dim, true)); }; /** * Get extent * @return {Array.<number>} */ scaleProto$1.getExtent = function () { return this._extent.slice(); }; /** * Set extent * @param {number} start * @param {number} end */ scaleProto$1.setExtent = function (start, end) { var thisExtent = this._extent; if (!isNaN(start)) { thisExtent[0] = start; } if (!isNaN(end)) { thisExtent[1] = end; } }; /** * @return {Array.<string>} */ scaleProto$1.getTicksLabels = function () { var labels = []; var ticks = this.getTicks(); for (var i = 0; i < ticks.length; i++) { labels.push(this.getLabel(ticks[i])); } return labels; }; /** * When axis extent depends on data and no data exists, * axis ticks should not be drawn, which is named 'blank'. */ scaleProto$1.isBlank = function () { return this._isBlank; }, /** * When axis extent depends on data and no data exists, * axis ticks should not be drawn, which is named 'blank'. */ scaleProto$1.setBlank = function (isBlank) { this._isBlank = isBlank; }; enableClassExtend(Scale); enableClassManagement(Scale, { registerWhenExtend: true }); /** * Linear continuous scale * @module echarts/coord/scale/Ordinal * * http://en.wikipedia.org/wiki/Level_of_measurement */ // FIXME only one data var scaleProto = Scale.prototype; var OrdinalScale = Scale.extend({ type: 'ordinal', init: function (data, extent) { this._data = data; this._extent = extent || [0, data.length - 1]; }, parse: function (val) { return typeof val === 'string' ? indexOf(this._data, val) // val might be float. : Math.round(val); }, contain: function (rank) { rank = this.parse(rank); return scaleProto.contain.call(this, rank) && this._data[rank] != null; }, /** * Normalize given rank or name to linear [0, 1] * @param {number|string} [val] * @return {number} */ normalize: function (val) { return scaleProto.normalize.call(this, this.parse(val)); }, scale: function (val) { return Math.round(scaleProto.scale.call(this, val)); }, /** * @return {Array} */ getTicks: function () { var ticks = []; var extent = this._extent; var rank = extent[0]; while (rank <= extent[1]) { ticks.push(rank); rank++; } return ticks; }, /** * Get item on rank n * @param {number} n * @return {string} */ getLabel: function (n) { return this._data[n]; }, /** * @return {number} */ count: function () { return this._extent[1] - this._extent[0] + 1; }, /** * @override */ unionExtentFromData: function (data, dim) { this.unionExtent(data.getDataExtent(dim, false)); }, niceTicks: noop, niceExtent: noop }); /** * @return {module:echarts/scale/Time} */ OrdinalScale.create = function () { return new OrdinalScale(); }; /** * For testable. */ var roundNumber$1 = round; /** * @param {Array.<number>} extent Both extent[0] and extent[1] should be valid number. * Should be extent[0] < extent[1]. * @param {number} splitNumber splitNumber should be >= 1. * @param {number} [minInterval] * @param {number} [maxInterval] * @return {Object} {interval, intervalPrecision, niceTickExtent} */ function intervalScaleNiceTicks(extent, splitNumber, minInterval, maxInterval) { var result = {}; var span = extent[1] - extent[0]; var interval = result.interval = nice(span / splitNumber, true); if (minInterval != null && interval < minInterval) { interval = result.interval = minInterval; } if (maxInterval != null && interval > maxInterval) { interval = result.interval = maxInterval; } // Tow more digital for tick. var precision = result.intervalPrecision = getIntervalPrecision(interval); // Niced extent inside original extent var niceTickExtent = result.niceTickExtent = [ roundNumber$1(Math.ceil(extent[0] / interval) * interval, precision), roundNumber$1(Math.floor(extent[1] / interval) * interval, precision) ]; fixExtent(niceTickExtent, extent); return result; } /** * @param {number} interval * @return {number} interval precision */ function getIntervalPrecision(interval) { // Tow more digital for tick. return getPrecisionSafe(interval) + 2; } function clamp(niceTickExtent, idx, extent) { niceTickExtent[idx] = Math.max(Math.min(niceTickExtent[idx], extent[1]), extent[0]); } // In some cases (e.g., splitNumber is 1), niceTickExtent may be out of extent. function fixExtent(niceTickExtent, extent) { !isFinite(niceTickExtent[0]) && (niceTickExtent[0] = extent[0]); !isFinite(niceTickExtent[1]) && (niceTickExtent[1] = extent[1]); clamp(niceTickExtent, 0, extent); clamp(niceTickExtent, 1, extent); if (niceTickExtent[0] > niceTickExtent[1]) { niceTickExtent[0] = niceTickExtent[1]; } } function intervalScaleGetTicks(interval, extent, niceTickExtent, intervalPrecision) { var ticks = []; // If interval is 0, return []; if (!interval) { return ticks; } // Consider this case: using dataZoom toolbox, zoom and zoom. var safeLimit = 10000; if (extent[0] < niceTickExtent[0]) { ticks.push(extent[0]); } var tick = niceTickExtent[0]; while (tick <= niceTickExtent[1]) { ticks.push(tick); // Avoid rounding error tick = roundNumber$1(tick + interval, intervalPrecision); if (tick === ticks[ticks.length - 1]) { // Consider out of safe float point, e.g., // -3711126.9907707 + 2e-10 === -3711126.9907707 break; } if (ticks.length > safeLimit) { return []; } } // Consider this case: the last item of ticks is smaller // than niceTickExtent[1] and niceTickExtent[1] === extent[1]. if (extent[1] > (ticks.length ? ticks[ticks.length - 1] : niceTickExtent[1])) { ticks.push(extent[1]); } return ticks; } /** * Interval scale * @module echarts/scale/Interval */ var roundNumber = round; /** * @alias module:echarts/coord/scale/Interval * @constructor */ var IntervalScale = Scale.extend({ type: 'interval', _interval: 0, _intervalPrecision: 2, setExtent: function (start, end) { var thisExtent = this._extent; //start,end may be a Number like '25',so... if (!isNaN(start)) { thisExtent[0] = parseFloat(start); } if (!isNaN(end)) { thisExtent[1] = parseFloat(end); } }, unionExtent: function (other) { var extent = this._extent; other[0] < extent[0] && (extent[0] = other[0]); other[1] > extent[1] && (extent[1] = other[1]); // unionExtent may called by it's sub classes IntervalScale.prototype.setExtent.call(this, extent[0], extent[1]); }, /** * Get interval */ getInterval: function () { return this._interval; }, /** * Set interval */ setInterval: function (interval) { this._interval = interval; // Dropped auto calculated niceExtent and use user setted extent // We assume user wan't to set both interval, min, max to get a better result this._niceExtent = this._extent.slice(); this._intervalPrecision = getIntervalPrecision(interval); }, /** * @return {Array.<number>} */ getTicks: function () { return intervalScaleGetTicks( this._interval, this._extent, this._niceExtent, this._intervalPrecision ); }, /** * @return {Array.<string>} */ getTicksLabels: function () { var labels = []; var ticks = this.getTicks(); for (var i = 0; i < ticks.length; i++) { labels.push(this.getLabel(ticks[i])); } return labels; }, /** * @param {number} data * @param {Object} [opt] * @param {number|string} [opt.precision] If 'auto', use nice presision. * @param {boolean} [opt.pad] returns 1.50 but not 1.5 if precision is 2. * @return {string} */ getLabel: function (data, opt) { if (data == null) { return ''; } var precision = opt && opt.precision; if (precision == null) { precision = getPrecisionSafe(data) || 0; } else if (precision === 'auto') { // Should be more precise then tick. precision = this._intervalPrecision; } // (1) If `precision` is set, 12.005 should be display as '12.00500'. // (2) Use roundNumber (toFixed) to avoid scientific notation like '3.5e-7'. data = roundNumber(data, precision, true); return addCommas(data); }, /** * Update interval and extent of intervals for nice ticks * * @param {number} [splitNumber = 5] Desired number of ticks * @param {number} [minInterval] * @param {number} [maxInterval] */ niceTicks: function (splitNumber, minInterval, maxInterval) { splitNumber = splitNumber || 5; var extent = this._extent; var span = extent[1] - extent[0]; if (!isFinite(span)) { return; } // User may set axis min 0 and data are all negative // FIXME If it needs to reverse ? if (span < 0) { span = -span; extent.reverse(); } var result = intervalScaleNiceTicks( extent, splitNumber, minInterval, maxInterval ); this._intervalPrecision = result.intervalPrecision; this._interval = result.interval; this._niceExtent = result.niceTickExtent; }, /** * Nice extent. * @param {Object} opt * @param {number} [opt.splitNumber = 5] Given approx tick number * @param {boolean} [opt.fixMin=false] * @param {boolean} [opt.fixMax=false] * @param {boolean} [opt.minInterval] * @param {boolean} [opt.maxInterval] */ niceExtent: function (opt) { var extent = this._extent; // If extent start and end are same, expand them if (extent[0] === extent[1]) { if (extent[0] !== 0) { // Expand extent var expandSize = extent[0]; // In the fowllowing case // Axis has been fixed max 100 // Plus data are all 100 and axis extent are [100, 100]. // Extend to the both side will cause expanded max is larger than fixed max. // So only expand to the smaller side. if (!opt.fixMax) { extent[1] += expandSize / 2; extent[0] -= expandSize / 2; } else { extent[0] -= expandSize / 2; } } else { extent[1] = 1; } } var span = extent[1] - extent[0]; // If there are no data and extent are [Infinity, -Infinity] if (!isFinite(span)) { extent[0] = 0; extent[1] = 1; } this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // var extent = this._extent; var interval = this._interval; if (!opt.fixMin) { extent[0] = roundNumber(Math.floor(extent[0] / interval) * interval); } if (!opt.fixMax) { extent[1] = roundNumber(Math.ceil(extent[1] / interval) * interval); } } }); /** * @return {module:echarts/scale/Time} */ IntervalScale.create = function () { return new IntervalScale(); }; // [About UTC and local time zone]: // In most cases, `number.parseDate` will treat input data string as local time // (except time zone is specified in time string). And `format.formateTime` returns // local time by default. option.useUTC is false by default. This design have // concidered these common case: // (1) Time that is persistent in server is in UTC, but it is needed to be diplayed // in local time by default. // (2) By default, the input data string (e.g., '2011-01-02') should be displayed // as its original time, without any time difference. var intervalScaleProto = IntervalScale.prototype; var mathCeil = Math.ceil; var mathFloor = Math.floor; var ONE_SECOND = 1000; var ONE_MINUTE = ONE_SECOND * 60; var ONE_HOUR = ONE_MINUTE * 60; var ONE_DAY = ONE_HOUR * 24; // FIXME 公用? var bisect = function (a, x, lo, hi) { while (lo < hi) { var mid = lo + hi >>> 1; if (a[mid][1] < x) { lo = mid + 1; } else { hi = mid; } } return lo; }; /** * @alias module:echarts/coord/scale/Time * @constructor */ var TimeScale = IntervalScale.extend({ type: 'time', /** * @override */ getLabel: function (val) { var stepLvl = this._stepLvl; var date = new Date(val); return formatTime(stepLvl[0], date, this.getSetting('useUTC')); }, /** * @override */ niceExtent: function (opt) { var extent = this._extent; // If extent start and end are same, expand them if (extent[0] === extent[1]) { // Expand extent extent[0] -= ONE_DAY; extent[1] += ONE_DAY; } // If there are no data and extent are [Infinity, -Infinity] if (extent[1] === -Infinity && extent[0] === Infinity) { var d = new Date(); extent[1] = +new Date(d.getFullYear(), d.getMonth(), d.getDate()); extent[0] = extent[1] - ONE_DAY; } this.niceTicks(opt.splitNumber, opt.minInterval, opt.maxInterval); // var extent = this._extent; var interval = this._interval; if (!opt.fixMin) { extent[0] = round(mathFloor(extent[0] / interval) * interval); } if (!opt.fixMax) { extent[1] = round(mathCeil(extent[1] / interval) * interval); } }, /** * @override */ niceTicks: function (approxTickNum, minInterval, maxInterval) { approxTickNum = approxTickNum || 10; var extent = this._extent; var span = extent[1] - extent[0]; var approxInterval = span / approxTickNum; if (minInterval != null && approxInterval < minInterval) { approxInterval = minInterval; } if (maxInterval != null && approxInterval > maxInterval) { approxInterval = maxInterval; } var scaleLevelsLen = scaleLevels.length; var idx = bisect(scaleLevels, approxInterval, 0, scaleLevelsLen); var level = scaleLevels[Math.min(idx, scaleLevelsLen - 1)]; var interval = level[1]; // Same with interval scale if span is much larger than 1 year if (level[0] === 'year') { var yearSpan = span / interval; // From "Nice Numbers for Graph Labels" of Graphic Gems // var niceYearSpan = numberUtil.nice(yearSpan, false); var yearStep = nice(yearSpan / approxTickNum, true); interval *= yearStep; } var timezoneOffset = this.getSetting('useUTC') ? 0 : (new Date(+extent[0] || +extent[1])).getTimezoneOffset() * 60 * 1000; var niceExtent = [ Math.round(mathCeil((extent[0] - timezoneOffset) / interval) * interval + timezoneOffset), Math.round(mathFloor((extent[1] - timezoneOffset) / interval) * interval + timezoneOffset) ]; fixExtent(niceExtent, extent); this._stepLvl = level; // Interval will be used in getTicks this._interval = interval; this._niceExtent = niceExtent; }, parse: function (val) { // val might be float. return +parseDate(val); } }); each$1(['contain', 'normalize'], function (methodName) { TimeScale.prototype[methodName] = function (val) { return intervalScaleProto[methodName].call(this, this.parse(val)); }; }); // Steps from d3 var scaleLevels = [ // Format interval ['hh:mm:ss', ONE_SECOND], // 1s ['hh:mm:ss', ONE_SECOND * 5], // 5s ['hh:mm:ss', ONE_SECOND * 10], // 10s ['hh:mm:ss', ONE_SECOND * 15], // 15s ['hh:mm:ss', ONE_SECOND * 30], // 30s ['hh:mm\nMM-dd', ONE_MINUTE], // 1m ['hh:mm\nMM-dd', ONE_MINUTE * 5], // 5m ['hh:mm\nMM-dd', ONE_MINUTE * 10], // 10m ['hh:mm\nMM-dd', ONE_MINUTE * 15], // 15m ['hh:mm\nMM-dd', ONE_MINUTE * 30], // 30m ['hh:mm\nMM-dd', ONE_HOUR], // 1h ['hh:mm\nMM-dd', ONE_HOUR * 2], // 2h ['hh:mm\nMM-dd', ONE_HOUR * 6], // 6h ['hh:mm\nMM-dd', ONE_HOUR * 12], // 12h ['MM-dd\nyyyy', ONE_DAY], // 1d ['MM-dd\nyyyy', ONE_DAY * 2], // 2d ['MM-dd\nyyyy', ONE_DAY * 3], // 3d ['MM-dd\nyyyy', ONE_DAY * 4], // 4d ['MM-dd\nyyyy', ONE_DAY * 5], // 5d ['MM-dd\nyyyy', ONE_DAY * 6], // 6d ['week', ONE_DAY * 7], // 7d ['MM-dd\nyyyy', ONE_DAY * 10], // 10d ['week', ONE_DAY * 14], // 2w ['week', ONE_DAY * 21], // 3w ['month', ONE_DAY * 31], // 1M ['week', ONE_DAY * 42], // 6w ['month', ONE_DAY * 62], // 2M ['week', ONE_DAY * 42], // 10w ['quarter', ONE_DAY * 380 / 4], // 3M ['month', ONE_DAY * 31 * 4], // 4M ['month', ONE_DAY * 31 * 5], // 5M ['half-year', ONE_DAY * 380 / 2], // 6M ['month', ONE_DAY * 31 * 8], // 8M ['month', ONE_DAY * 31 * 10], // 10M ['year', ONE_DAY * 380] // 1Y ]; /** * @param {module:echarts/model/Model} * @return {module:echarts/scale/Time} */ TimeScale.create = function (model) { return new TimeScale({useUTC: model.ecModel.get('useUTC')}); }; /** * Log scale * @module echarts/scale/Log */ // Use some method of IntervalScale var scaleProto$2 = Scale.prototype; var intervalScaleProto$1 = IntervalScale.prototype; var getPrecisionSafe$1 = getPrecisionSafe; var roundingErrorFix = round; var mathFloor$1 = Math.floor; var mathCeil$1 = Math.ceil; var mathPow$1 = Math.pow; var mathLog = Math.log; var LogScale = Scale.extend({ type: 'log', base: 10, $constructor: function () { Scale.apply(this, arguments); this._originalScale = new IntervalScale(); }, /** * @return {Array.<number>} */ getTicks: function () { var originalScale = this._originalScale; var extent = this._extent; var originalExtent = originalScale.getExtent(); return map(intervalScaleProto$1.getTicks.call(this), function (val) { var powVal = round(mathPow$1(this.base, val)); // Fix #4158 powVal = (val === extent[0] && originalScale.__fixMin) ? fixRoundingError(powVal, originalExtent[0]) : powVal; powVal = (val === extent[1] && originalScale.__fixMax) ? fixRoundingError(powVal, originalExtent[1]) : powVal; return powVal; }, this); }, /** * @param {number} val * @return {string} */ getLabel: intervalScaleProto$1.getLabel, /** * @param {number} val * @return {number} */ scale: function (val) { val = scaleProto$2.scale.call(this, val); return mathPow$1(this.base, val); }, /** * @param {number} start * @param {number} end */ setExtent: function (start, end) { var base = this.base; start = mathLog(start) / mathLog(base); end = mathLog(end) / mathLog(base); intervalScaleProto$1.setExtent.call(this, start, end); }, /** * @return {number} end */ getExtent: function () { var base = this.base; var extent = scaleProto$2.getExtent.call(this); extent[0] = mathPow$1(base, extent[0]); extent[1] = mathPow$1(base, extent[1]); // Fix #4158 var originalScale = this._originalScale; var originalExtent = originalScale.getExtent(); originalScale.__fixMin && (extent[0] = fixRoundingError(extent[0], originalExtent[0])); originalScale.__fixMax && (extent[1] = fixRoundingError(extent[1], originalExtent[1])); return extent; }, /** * @param {Array.<number>} extent */ unionExtent: function (extent) { this._originalScale.unionExtent(extent); var base = this.base; extent[0] = mathLog(extent[0]) / mathLog(base); extent[1] = mathLog(extent[1]) / mathLog(base); scaleProto$2.unionExtent.call(this, extent); }, /** * @override */ unionExtentFromData: function (data, dim) { this.unionExtent(data.getDataExtent(dim, true, function (val) { return val > 0; })); }, /** * Update interval and extent of intervals for nice ticks * @param {number} [approxTickNum = 10] Given approx tick number */ niceTicks: function (approxTickNum) { approxTickNum = approxTickNum || 10; var extent = this._extent; var span = extent[1] - extent[0]; if (span === Infinity || span <= 0) { return; } var interval = quantity(span); var err = approxTickNum / span * interval; // Filter ticks to get closer to the desired count. if (err <= 0.5) { interval *= 10; } // Interval should be integer while (!isNaN(interval) && Math.abs(interval) < 1 && Math.abs(interval) > 0) { interval *= 10; } var niceExtent = [ round(mathCeil$1(extent[0] / interval) * interval), round(mathFloor$1(extent[1] / interval) * interval) ]; this._interval = interval; this._niceExtent = niceExtent; }, /** * Nice extent. * @override */ niceExtent: function (opt) { intervalScaleProto$1.niceExtent.call(this, opt); var originalScale = this._originalScale; originalScale.__fixMin = opt.fixMin; originalScale.__fixMax = opt.fixMax; } }); each$1(['contain', 'normalize'], function (methodName) { LogScale.prototype[methodName] = function (val) { val = mathLog(val) / mathLog(this.base); return scaleProto$2[methodName].call(this, val); }; }); LogScale.create = function () { return new LogScale(); }; function fixRoundingError(val, originalVal) { return roundingErrorFix(val, getPrecisionSafe$1(originalVal)); } /** * Get axis scale extent before niced. * Item of returned array can only be number (including Infinity and NaN). */ function getScaleExtent(scale, model) { var scaleType = scale.type; var min = model.getMin(); var max = model.getMax(); var fixMin = min != null; var fixMax = max != null; var originalExtent = scale.getExtent(); var axisDataLen; var boundaryGap; var span; if (scaleType === 'ordinal') { axisDataLen = (model.get('data') || []).length; } else { boundaryGap = model.get('boundaryGap'); if (!isArray(boundaryGap)) { boundaryGap = [boundaryGap || 0, boundaryGap || 0]; } if (typeof boundaryGap[0] === 'boolean') { if (__DEV__) { console.warn('Boolean type for boundaryGap is only ' + 'allowed for ordinal axis. Please use string in ' + 'percentage instead, e.g., "20%". Currently, ' + 'boundaryGap is set to be 0.'); } boundaryGap = [0, 0]; } boundaryGap[0] = parsePercent$1(boundaryGap[0], 1); boundaryGap[1] = parsePercent$1(boundaryGap[1], 1); span = (originalExtent[1] - originalExtent[0]) || Math.abs(originalExtent[0]); } // Notice: When min/max is not set (that is, when there are null/undefined, // which is the most common case), these cases should be ensured: // (1) For 'ordinal', show all axis.data. // (2) For others: // + `boundaryGap` is applied (if min/max set, boundaryGap is // disabled). // + If `needCrossZero`, min/max should be zero, otherwise, min/max should // be the result that originalExtent enlarged by boundaryGap. // (3) If no data, it should be ensured that `scale.setBlank` is set. // FIXME // (1) When min/max is 'dataMin' or 'dataMax', should boundaryGap be able to used? // (2) When `needCrossZero` and all data is positive/negative, should it be ensured // that the results processed by boundaryGap are positive/negative? if (min == null) { min = scaleType === 'ordinal' ? (axisDataLen ? 0 : NaN) : originalExtent[0] - boundaryGap[0] * span; } if (max == null) { max = scaleType === 'ordinal' ? (axisDataLen ? axisDataLen - 1 : NaN) : originalExtent[1] + boundaryGap[1] * span; } if (min === 'dataMin') { min = originalExtent[0]; } else if (typeof min === 'function') { min = min({ min: originalExtent[0], max: originalExtent[1] }); } if (max === 'dataMax') { max = originalExtent[1]; } else if (typeof max === 'function') { max = max({ min: originalExtent[0], max: originalExtent[1] }); } (min == null || !isFinite(min)) && (min = NaN); (max == null || !isFinite(max)) && (max = NaN); scale.setBlank(eqNaN(min) || eqNaN(max)); // Evaluate if axis needs cross zero if (model.getNeedCrossZero()) { // Axis is over zero and min is not set if (min > 0 && max > 0 && !fixMin) { min = 0; } // Axis is under zero and max is not set if (min < 0 && max < 0 && !fixMax) { max = 0; } } return [min, max]; } function niceScaleExtent$1(scale, model) { var extent = getScaleExtent(scale, model); var fixMin = model.getMin() != null; var fixMax = model.getMax() != null; var splitNumber = model.get('splitNumber'); if (scale.type === 'log') { scale.base = model.get('logBase'); } var scaleType = scale.type; scale.setExtent(extent[0], extent[1]); scale.niceExtent({ splitNumber: splitNumber, fixMin: fixMin, fixMax: fixMax, minInterval: (scaleType === 'interval' || scaleType === 'time') ? model.get('minInterval') : null, maxInterval: (scaleType === 'interval' || scaleType === 'time') ? model.get('maxInterval') : null }); // If some one specified the min, max. And the default calculated interval // is not good enough. He can specify the interval. It is often appeared // in angle axis with angle 0 - 360. Interval calculated in interval scale is hard // to be 60. // FIXME var interval = model.get('interval'); if (interval != null) { scale.setInterval && scale.setInterval(interval); } } /** * @param {module:echarts/model/Model} model * @param {string} [axisType] Default retrieve from model.type * @return {module:echarts/scale/*} */ function createScaleByModel(model, axisType) { axisType = axisType || model.get('type'); if (axisType) { switch (axisType) { // Buildin scale case 'category': return new OrdinalScale( model.getCategories(), [Infinity, -Infinity] ); case 'value': return new IntervalScale(); // Extended scale, like time and log default: return (Scale.getClass(axisType) || IntervalScale).create(model); } } } /** * Check if the axis corss 0 */ function ifAxisCrossZero$1(axis) { var dataExtent = axis.scale.getExtent(); var min = dataExtent[0]; var max = dataExtent[1]; return !((min > 0 && max > 0) || (min < 0 && max < 0)); } /** * @param {Array.<number>} tickCoords In axis self coordinate. * @param {Array.<string>} labels * @param {string} font * @param {number} axisRotate 0: towards right horizontally, clock-wise is negative. * @param {number} [labelRotate=0] 0: towards right horizontally, clock-wise is negative. * @return {number} */ function getAxisLabelInterval(tickCoords, labels, font, axisRotate, labelRotate) { var textSpaceTakenRect; var autoLabelInterval = 0; var accumulatedLabelInterval = 0; var rotation = (axisRotate - labelRotate) / 180 * Math.PI; var step = 1; if (labels.length > 40) { // Simple optimization for large amount of labels step = Math.floor(labels.length / 40); } for (var i = 0; i < tickCoords.length; i += step) { var tickCoord = tickCoords[i]; // Not precise, do not consider align and vertical align // and each distance from axis line yet. var rect = getBoundingRect( labels[i], font, 'center', 'top' ); rect.x += tickCoord * Math.cos(rotation); rect.y += tickCoord * Math.sin(rotation); // Magic number rect.width *= 1.3; rect.height *= 1.3; if (!textSpaceTakenRect) { textSpaceTakenRect = rect.clone(); } // There is no space for current label; else if (textSpaceTakenRect.intersect(rect)) { accumulatedLabelInterval++; autoLabelInterval = Math.max(autoLabelInterval, accumulatedLabelInterval); } else { textSpaceTakenRect.union(rect); // Reset accumulatedLabelInterval = 0; } } if (autoLabelInterval === 0 && step > 1) { return step; } return (autoLabelInterval + 1) * step - 1; } /** * @param {Object} axis * @param {Function} labelFormatter * @return {Array.<string>} */ function getFormattedLabels(axis, labelFormatter) { var scale = axis.scale; var labels = scale.getTicksLabels(); var ticks = scale.getTicks(); if (typeof labelFormatter === 'string') { labelFormatter = (function (tpl) { return function (val) { return tpl.replace('{value}', val != null ? val : ''); }; })(labelFormatter); // Consider empty array return map(labels, labelFormatter); } else if (typeof labelFormatter === 'function') { return map(ticks, function (tick, idx) { return labelFormatter( getAxisRawValue(axis, tick), idx ); }, this); } else { return labels; } } function getAxisRawValue(axis, value) { // In category axis with data zoom, tick is not the original // index of axis.data. So tick should not be exposed to user // in category axis. return axis.type === 'category' ? axis.scale.getLabel(value) : value; } /** * Cartesian coordinate system * @module echarts/coord/Cartesian * */ function dimAxisMapper(dim) { return this._axes[dim]; } /** * @alias module:echarts/coord/Cartesian * @constructor */ var Cartesian = function (name) { this._axes = {}; this._dimList = []; /** * @type {string} */ this.name = name || ''; }; Cartesian.prototype = { constructor: Cartesian, type: 'cartesian', /** * Get axis * @param {number|string} dim * @return {module:echarts/coord/Cartesian~Axis} */ getAxis: function (dim) { return this._axes[dim]; }, /** * Get axes list * @return {Array.<module:echarts/coord/Cartesian~Axis>} */ getAxes: function () { return map(this._dimList, dimAxisMapper, this); }, /** * Get axes list by given scale type */ getAxesByScale: function (scaleType) { scaleType = scaleType.toLowerCase(); return filter( this.getAxes(), function (axis) { return axis.scale.type === scaleType; } ); }, /** * Add axis * @param {module:echarts/coord/Cartesian.Axis} */ addAxis: function (axis) { var dim = axis.dim; this._axes[dim] = axis; this._dimList.push(dim); }, /** * Convert data to coord in nd space * @param {Array.<number>|Object.<string, number>} val * @return {Array.<number>|Object.<string, number>} */ dataToCoord: function (val) { return this._dataCoordConvert(val, 'dataToCoord'); }, /** * Convert coord in nd space to data * @param {Array.<number>|Object.<string, number>} val * @return {Array.<number>|Object.<string, number>} */ coordToData: function (val) { return this._dataCoordConvert(val, 'coordToData'); }, _dataCoordConvert: function (input, method) { var dimList = this._dimList; var output = input instanceof Array ? [] : {}; for (var i = 0; i < dimList.length; i++) { var dim = dimList[i]; var axis = this._axes[dim]; output[dim] = axis[method](input[dim]); } return output; } }; function Cartesian2D(name) { Cartesian.call(this, name); } Cartesian2D.prototype = { constructor: Cartesian2D, type: 'cartesian2d', /** * @type {Array.<string>} * @readOnly */ dimensions: ['x', 'y'], /** * Base axis will be used on stacking. * * @return {module:echarts/coord/cartesian/Axis2D} */ getBaseAxis: function () { return this.getAxesByScale('ordinal')[0] || this.getAxesByScale('time')[0] || this.getAxis('x'); }, /** * If contain point * @param {Array.<number>} point * @return {boolean} */ containPoint: function (point) { var axisX = this.getAxis('x'); var axisY = this.getAxis('y'); return axisX.contain(axisX.toLocalCoord(point[0])) && axisY.contain(axisY.toLocalCoord(point[1])); }, /** * If contain data * @param {Array.<number>} data * @return {boolean} */ containData: function (data) { return this.getAxis('x').containData(data[0]) && this.getAxis('y').containData(data[1]); }, /** * @param {Array.<number>} data * @param {boolean} [clamp=false] * @return {Array.<number>} */ dataToPoint: function (data, clamp) { var xAxis = this.getAxis('x'); var yAxis = this.getAxis('y'); return [ xAxis.toGlobalCoord(xAxis.dataToCoord(data[0], clamp)), yAxis.toGlobalCoord(yAxis.dataToCoord(data[1], clamp)) ]; }, /** * @param {Array.<number>} point * @param {boolean} [clamp=false] * @return {Array.<number>} */ pointToData: function (point, clamp) { var xAxis = this.getAxis('x'); var yAxis = this.getAxis('y'); return [ xAxis.coordToData(xAxis.toLocalCoord(point[0]), clamp), yAxis.coordToData(yAxis.toLocalCoord(point[1]), clamp) ]; }, /** * Get other axis * @param {module:echarts/coord/cartesian/Axis2D} axis */ getOtherAxis: function (axis) { return this.getAxis(axis.dim === 'x' ? 'y' : 'x'); } }; inherits(Cartesian2D, Cartesian); var linearMap$1 = linearMap; function fixExtentWithBands(extent, nTick) { var size = extent[1] - extent[0]; var len = nTick; var margin = size / len / 2; extent[0] += margin; extent[1] -= margin; } var normalizedExtent = [0, 1]; /** * @name module:echarts/coord/CartesianAxis * @constructor */ var Axis = function (dim, scale, extent) { /** * Axis dimension. Such as 'x', 'y', 'z', 'angle', 'radius' * @type {string} */ this.dim = dim; /** * Axis scale * @type {module:echarts/coord/scale/*} */ this.scale = scale; /** * @type {Array.<number>} * @private */ this._extent = extent || [0, 0]; /** * @type {boolean} */ this.inverse = false; /** * Usually true when axis has a ordinal scale * @type {boolean} */ this.onBand = false; /** * @private * @type {number} */ this._labelInterval; }; Axis.prototype = { constructor: Axis, /** * If axis extent contain given coord * @param {number} coord * @return {boolean} */ contain: function (coord) { var extent = this._extent; var min = Math.min(extent[0], extent[1]); var max = Math.max(extent[0], extent[1]); return coord >= min && coord <= max; }, /** * If axis extent contain given data * @param {number} data * @return {boolean} */ containData: function (data) { return this.contain(this.dataToCoord(data)); }, /** * Get coord extent. * @return {Array.<number>} */ getExtent: function () { return this._extent.slice(); }, /** * Get precision used for formatting * @param {Array.<number>} [dataExtent] * @return {number} */ getPixelPrecision: function (dataExtent) { return getPixelPrecision( dataExtent || this.scale.getExtent(), this._extent ); }, /** * Set coord extent * @param {number} start * @param {number} end */ setExtent: function (start, end) { var extent = this._extent; extent[0] = start; extent[1] = end; }, /** * Convert data to coord. Data is the rank if it has a ordinal scale * @param {number} data * @param {boolean} clamp * @return {number} */ dataToCoord: function (data, clamp) { var extent = this._extent; var scale = this.scale; data = scale.normalize(data); if (this.onBand && scale.type === 'ordinal') { extent = extent.slice(); fixExtentWithBands(extent, scale.count()); } return linearMap$1(data, normalizedExtent, extent, clamp); }, /** * Convert coord to data. Data is the rank if it has a ordinal scale * @param {number} coord * @param {boolean} clamp * @return {number} */ coordToData: function (coord, clamp) { var extent = this._extent; var scale = this.scale; if (this.onBand && scale.type === 'ordinal') { extent = extent.slice(); fixExtentWithBands(extent, scale.count()); } var t = linearMap$1(coord, extent, normalizedExtent, clamp); return this.scale.scale(t); }, /** * Convert pixel point to data in axis * @param {Array.<number>} point * @param {boolean} clamp * @return {number} data */ pointToData: function (point, clamp) { // Should be implemented in derived class if necessary. }, /** * @return {Array.<number>} */ getTicksCoords: function (alignWithLabel) { if (this.onBand && !alignWithLabel) { var bands = this.getBands(); var coords = []; for (var i = 0; i < bands.length; i++) { coords.push(bands[i][0]); } if (bands[i - 1]) { coords.push(bands[i - 1][1]); } return coords; } else { return map(this.scale.getTicks(), this.dataToCoord, this); } }, /** * Coords of labels are on the ticks or on the middle of bands * @return {Array.<number>} */ getLabelsCoords: function () { return map(this.scale.getTicks(), this.dataToCoord, this); }, /** * Get bands. * * If axis has labels [1, 2, 3, 4]. Bands on the axis are * |---1---|---2---|---3---|---4---|. * * @return {Array} */ // FIXME Situation when labels is on ticks getBands: function () { var extent = this.getExtent(); var bands = []; var len = this.scale.count(); var start = extent[0]; var end = extent[1]; var span = end - start; for (var i = 0; i < len; i++) { bands.push([ span * i / len + start, span * (i + 1) / len + start ]); } return bands; }, /** * Get width of band * @return {number} */ getBandWidth: function () { var axisExtent = this._extent; var dataExtent = this.scale.getExtent(); var len = dataExtent[1] - dataExtent[0] + (this.onBand ? 1 : 0); // Fix #2728, avoid NaN when only one data. len === 0 && (len = 1); var size = Math.abs(axisExtent[1] - axisExtent[0]); return Math.abs(size) / len; }, /** * @abstract * @return {boolean} Is horizontal */ isHorizontal: null, /** * @abstract * @return {number} Get axis rotate, by degree. */ getRotate: null, /** * Get interval of the axis label. * To get precise result, at least one of `getRotate` and `isHorizontal` * should be implemented. * @return {number} */ getLabelInterval: function () { var labelInterval = this._labelInterval; if (!labelInterval) { var axisModel = this.model; var labelModel = axisModel.getModel('axisLabel'); labelInterval = labelModel.get('interval'); if (this.type === 'category' && (labelInterval == null || labelInterval === 'auto') ) { labelInterval = getAxisLabelInterval( map(this.scale.getTicks(), this.dataToCoord, this), axisModel.getFormattedLabels(), labelModel.getFont(), this.getRotate ? this.getRotate() : (this.isHorizontal && !this.isHorizontal()) ? 90 : 0, labelModel.get('rotate') ); } this._labelInterval = labelInterval; } return labelInterval; } }; /** * Extend axis 2d * @constructor module:echarts/coord/cartesian/Axis2D * @extends {module:echarts/coord/cartesian/Axis} * @param {string} dim * @param {*} scale * @param {Array.<number>} coordExtent * @param {string} axisType * @param {string} position */ var Axis2D = function (dim, scale, coordExtent, axisType, position) { Axis.call(this, dim, scale, coordExtent); /** * Axis type * - 'category' * - 'value' * - 'time' * - 'log' * @type {string} */ this.type = axisType || 'value'; /** * Axis position * - 'top' * - 'bottom' * - 'left' * - 'right' */ this.position = position || 'bottom'; }; Axis2D.prototype = { constructor: Axis2D, /** * Index of axis, can be used as key */ index: 0, /** * If axis is on the zero position of the other axis * @type {boolean} */ onZero: false, /** * Axis model * @param {module:echarts/coord/cartesian/AxisModel} */ model: null, isHorizontal: function () { var position = this.position; return position === 'top' || position === 'bottom'; }, /** * Each item cooresponds to this.getExtent(), which * means globalExtent[0] may greater than globalExtent[1], * unless `asc` is input. * * @param {boolean} [asc] * @return {Array.<number>} */ getGlobalExtent: function (asc) { var ret = this.getExtent(); ret[0] = this.toGlobalCoord(ret[0]); ret[1] = this.toGlobalCoord(ret[1]); asc && ret[0] > ret[1] && ret.reverse(); return ret; }, getOtherAxis: function () { this.grid.getOtherAxis(); }, /** * If label is ignored. * Automatically used when axis is category and label can not be all shown * @param {number} idx * @return {boolean} */ isLabelIgnored: function (idx) { if (this.type === 'category') { var labelInterval = this.getLabelInterval(); return ((typeof labelInterval === 'function') && !labelInterval(idx, this.scale.getLabel(idx))) || idx % (labelInterval + 1); } }, /** * @override */ pointToData: function (point, clamp) { return this.coordToData(this.toLocalCoord(point[this.dim === 'x' ? 0 : 1]), clamp); }, /** * Transform global coord to local coord, * i.e. var localCoord = axis.toLocalCoord(80); * designate by module:echarts/coord/cartesian/Grid. * @type {Function} */ toLocalCoord: null, /** * Transform global coord to local coord, * i.e. var globalCoord = axis.toLocalCoord(40); * designate by module:echarts/coord/cartesian/Grid. * @type {Function} */ toGlobalCoord: null }; inherits(Axis2D, Axis); var defaultOption = { show: true, zlevel: 0, // 一级层叠 z: 0, // 二级层叠 // 反向坐标轴 inverse: false, // 坐标轴名字,默认为空 name: '', // 坐标轴名字位置,支持'start' | 'middle' | 'end' nameLocation: 'end', // 坐标轴名字旋转,degree。 nameRotate: null, // Adapt to axis rotate, when nameLocation is 'middle'. nameTruncate: { maxWidth: null, ellipsis: '...', placeholder: '.' }, // 坐标轴文字样式,默认取全局样式 nameTextStyle: {}, // 文字与轴线距离 nameGap: 15, silent: false, // Default false to support tooltip. triggerEvent: false, // Default false to avoid legacy user event listener fail. tooltip: { show: false }, axisPointer: {}, // 坐标轴线 axisLine: { // 默认显示,属性show控制显示与否 show: true, onZero: true, onZeroAxisIndex: null, // 属性lineStyle控制线条样式 lineStyle: { color: '#333', width: 1, type: 'solid' }, // 坐标轴两端的箭头 symbol: ['none', 'none'], symbolSize: [10, 15] }, // 坐标轴小标记 axisTick: { // 属性show控制显示与否,默认显示 show: true, // 控制小标记是否在grid里 inside: false, // 属性length控制线长 length: 5, // 属性lineStyle控制线条样式 lineStyle: { width: 1 } }, // 坐标轴文本标签,详见axis.axisLabel axisLabel: { show: true, // 控制文本标签是否在grid里 inside: false, rotate: 0, showMinLabel: null, // true | false | null (auto) showMaxLabel: null, // true | false | null (auto) margin: 8, // formatter: null, // 其余属性默认使用全局文本样式,详见TEXTSTYLE fontSize: 12 }, // 分隔线 splitLine: { // 默认显示,属性show控制显示与否 show: true, // 属性lineStyle(详见lineStyle)控制线条样式 lineStyle: { color: ['#ccc'], width: 1, type: 'solid' } }, // 分隔区域 splitArea: { // 默认不显示,属性show控制显示与否 show: false, // 属性areaStyle(详见areaStyle)控制区域样式 areaStyle: { color: ['rgba(250,250,250,0.3)','rgba(200,200,200,0.3)'] } } }; var axisDefault = {}; axisDefault.categoryAxis = merge({ // 类目起始和结束两端空白策略 boundaryGap: true, // splitArea: { // show: false // }, splitLine: { show: false }, // 坐标轴小标记 axisTick: { // If tick is align with label when boundaryGap is true alignWithLabel: false, interval: 'auto' }, // 坐标轴文本标签,详见axis.axisLabel axisLabel: { interval: 'auto' } }, defaultOption); axisDefault.valueAxis = merge({ // 数值起始和结束两端空白策略 boundaryGap: [0, 0], // 最小值, 设置成 'dataMin' 则从数据中计算最小值 // min: null, // 最大值,设置成 'dataMax' 则从数据中计算最大值 // max: null, // Readonly prop, specifies start value of the range when using data zoom. // rangeStart: null // Readonly prop, specifies end value of the range when using data zoom. // rangeEnd: null // 脱离0值比例,放大聚焦到最终_min,_max区间 // scale: false, // 分割段数,默认为5 splitNumber: 5 // Minimum interval // minInterval: null // maxInterval: null }, defaultOption); // FIXME axisDefault.timeAxis = defaults({ scale: true, min: 'dataMin', max: 'dataMax' }, axisDefault.valueAxis); axisDefault.logAxis = defaults({ scale: true, logBase: 10 }, axisDefault.valueAxis); // FIXME axisType is fixed ? var AXIS_TYPES = ['value', 'category', 'time', 'log']; /** * Generate sub axis model class * @param {string} axisName 'x' 'y' 'radius' 'angle' 'parallel' * @param {module:echarts/model/Component} BaseAxisModelClass * @param {Function} axisTypeDefaulter * @param {Object} [extraDefaultOption] */ var axisModelCreator = function (axisName, BaseAxisModelClass, axisTypeDefaulter, extraDefaultOption) { each$1(AXIS_TYPES, function (axisType) { BaseAxisModelClass.extend({ type: axisName + 'Axis.' + axisType, mergeDefaultAndTheme: function (option, ecModel) { var layoutMode = this.layoutMode; var inputPositionParams = layoutMode ? getLayoutParams(option) : {}; var themeModel = ecModel.getTheme(); merge(option, themeModel.get(axisType + 'Axis')); merge(option, this.getDefaultOption()); option.type = axisTypeDefaulter(axisName, option); if (layoutMode) { mergeLayoutParam(option, inputPositionParams, layoutMode); } }, defaultOption: mergeAll( [ {}, axisDefault[axisType + 'Axis'], extraDefaultOption ], true ) }); }); ComponentModel.registerSubTypeDefaulter( axisName + 'Axis', curry(axisTypeDefaulter, axisName) ); }; function getName(obj) { if (isObject(obj) && obj.value != null) { return obj.value; } else { return obj + ''; } } var axisModelCommonMixin = { /** * Format labels * @return {Array.<string>} */ getFormattedLabels: function () { return getFormattedLabels( this.axis, this.get('axisLabel.formatter') ); }, /** * Get categories */ getCategories: function () { return this.get('type') === 'category' && map(this.get('data'), getName); }, /** * @param {boolean} origin * @return {number|string} min value or 'dataMin' or null/undefined (means auto) or NaN */ getMin: function (origin) { var option = this.option; var min = (!origin && option.rangeStart != null) ? option.rangeStart : option.min; if (this.axis && min != null && min !== 'dataMin' && typeof min !== 'function' && !eqNaN(min) ) { min = this.axis.scale.parse(min); } return min; }, /** * @param {boolean} origin * @return {number|string} max value or 'dataMax' or null/undefined (means auto) or NaN */ getMax: function (origin) { var option = this.option; var max = (!origin && option.rangeEnd != null) ? option.rangeEnd : option.max; if (this.axis && max != null && max !== 'dataMax' && typeof max !== 'function' && !eqNaN(max) ) { max = this.axis.scale.parse(max); } return max; }, /** * @return {boolean} */ getNeedCrossZero: function () { var option = this.option; return (option.rangeStart != null || option.rangeEnd != null) ? false : !option.scale; }, /** * Should be implemented by each axis model if necessary. * @return {module:echarts/model/Component} coordinate system model */ getCoordSysModel: noop, /** * @param {number} rangeStart Can only be finite number or null/undefined or NaN. * @param {number} rangeEnd Can only be finite number or null/undefined or NaN. */ setRange: function (rangeStart, rangeEnd) { this.option.rangeStart = rangeStart; this.option.rangeEnd = rangeEnd; }, /** * Reset range */ resetRange: function () { // rangeStart and rangeEnd is readonly. this.option.rangeStart = this.option.rangeEnd = null; } }; var AxisModel = ComponentModel.extend({ type: 'cartesian2dAxis', /** * @type {module:echarts/coord/cartesian/Axis2D} */ axis: null, /** * @override */ init: function () { AxisModel.superApply(this, 'init', arguments); this.resetRange(); }, /** * @override */ mergeOption: function () { AxisModel.superApply(this, 'mergeOption', arguments); this.resetRange(); }, /** * @override */ restoreData: function () { AxisModel.superApply(this, 'restoreData', arguments); this.resetRange(); }, /** * @override * @return {module:echarts/model/Component} */ getCoordSysModel: function () { return this.ecModel.queryComponents({ mainType: 'grid', index: this.option.gridIndex, id: this.option.gridId })[0]; } }); function getAxisType(axisDim, option) { // Default axis with data is category axis return option.type || (option.data ? 'category' : 'value'); } merge(AxisModel.prototype, axisModelCommonMixin); var extraOption = { // gridIndex: 0, // gridId: '', // Offset is for multiple axis on the same position offset: 0 }; axisModelCreator('x', AxisModel, getAxisType, extraOption); axisModelCreator('y', AxisModel, getAxisType, extraOption); // Grid 是在有直角坐标系的时候必须要存在的 // 所以这里也要被 Cartesian2D 依赖 ComponentModel.extend({ type: 'grid', dependencies: ['xAxis', 'yAxis'], layoutMode: 'box', /** * @type {module:echarts/coord/cartesian/Grid} */ coordinateSystem: null, defaultOption: { show: false, zlevel: 0, z: 0, left: '10%', top: 60, right: '10%', bottom: 60, // If grid size contain label containLabel: false, // width: {totalWidth} - left - right, // height: {totalHeight} - top - bottom, backgroundColor: 'rgba(0,0,0,0)', borderWidth: 1, borderColor: '#ccc' } }); /** * Grid is a region which contains at most 4 cartesian systems * * TODO Default cartesian */ // Depends on GridModel, AxisModel, which performs preprocess. var each$8 = each$1; var ifAxisCrossZero = ifAxisCrossZero$1; var niceScaleExtent = niceScaleExtent$1; /** * Check if the axis is used in the specified grid * @inner */ function isAxisUsedInTheGrid(axisModel, gridModel, ecModel) { return axisModel.getCoordSysModel() === gridModel; } function rotateTextRect(textRect, rotate) { var rotateRadians = rotate * Math.PI / 180; var boundingBox = textRect.plain(); var beforeWidth = boundingBox.width; var beforeHeight = boundingBox.height; var afterWidth = beforeWidth * Math.cos(rotateRadians) + beforeHeight * Math.sin(rotateRadians); var afterHeight = beforeWidth * Math.sin(rotateRadians) + beforeHeight * Math.cos(rotateRadians); var rotatedRect = new BoundingRect(boundingBox.x, boundingBox.y, afterWidth, afterHeight); return rotatedRect; } function getLabelUnionRect(axis) { var axisModel = axis.model; var labels = axisModel.getFormattedLabels(); var axisLabelModel = axisModel.getModel('axisLabel'); var rect; var step = 1; var labelCount = labels.length; if (labelCount > 40) { // Simple optimization for large amount of labels step = Math.ceil(labelCount / 40); } for (var i = 0; i < labelCount; i += step) { if (!axis.isLabelIgnored(i)) { var unrotatedSingleRect = axisLabelModel.getTextRect(labels[i]); var singleRect = rotateTextRect(unrotatedSingleRect, axisLabelModel.get('rotate') || 0); rect ? rect.union(singleRect) : (rect = singleRect); } } return rect; } function Grid(gridModel, ecModel, api) { /** * @type {Object.<string, module:echarts/coord/cartesian/Cartesian2D>} * @private */ this._coordsMap = {}; /** * @type {Array.<module:echarts/coord/cartesian/Cartesian>} * @private */ this._coordsList = []; /** * @type {Object.<string, module:echarts/coord/cartesian/Axis2D>} * @private */ this._axesMap = {}; /** * @type {Array.<module:echarts/coord/cartesian/Axis2D>} * @private */ this._axesList = []; this._initCartesian(gridModel, ecModel, api); this.model = gridModel; } var gridProto = Grid.prototype; gridProto.type = 'grid'; gridProto.axisPointerEnabled = true; gridProto.getRect = function () { return this._rect; }; gridProto.update = function (ecModel, api) { var axesMap = this._axesMap; this._updateScale(ecModel, this.model); each$8(axesMap.x, function (xAxis) { niceScaleExtent(xAxis.scale, xAxis.model); }); each$8(axesMap.y, function (yAxis) { niceScaleExtent(yAxis.scale, yAxis.model); }); each$8(axesMap.x, function (xAxis) { fixAxisOnZero(axesMap, 'y', xAxis); }); each$8(axesMap.y, function (yAxis) { fixAxisOnZero(axesMap, 'x', yAxis); }); // Resize again if containLabel is enabled // FIXME It may cause getting wrong grid size in data processing stage this.resize(this.model, api); }; function fixAxisOnZero(axesMap, otherAxisDim, axis) { // onZero can not be enabled in these two situations: // 1. When any other axis is a category axis. // 2. When no axis is cross 0 point. var axes = axesMap[otherAxisDim]; if (!axis.onZero) { return; } var onZeroAxisIndex = axis.onZeroAxisIndex; // If target axis is specified. if (onZeroAxisIndex != null) { var otherAxis = axes[onZeroAxisIndex]; if (otherAxis && canNotOnZeroToAxis(otherAxis)) { axis.onZero = false; } return; } for (var idx in axes) { if (axes.hasOwnProperty(idx)) { var otherAxis = axes[idx]; if (otherAxis && !canNotOnZeroToAxis(otherAxis)) { onZeroAxisIndex = +idx; break; } } } if (onZeroAxisIndex == null) { axis.onZero = false; } axis.onZeroAxisIndex = onZeroAxisIndex; } function canNotOnZeroToAxis(axis) { return axis.type === 'category' || axis.type === 'time' || !ifAxisCrossZero(axis); } /** * Resize the grid * @param {module:echarts/coord/cartesian/GridModel} gridModel * @param {module:echarts/ExtensionAPI} api */ gridProto.resize = function (gridModel, api, ignoreContainLabel) { var gridRect = getLayoutRect( gridModel.getBoxLayoutParams(), { width: api.getWidth(), height: api.getHeight() }); this._rect = gridRect; var axesList = this._axesList; adjustAxes(); // Minus label size if (!ignoreContainLabel && gridModel.get('containLabel')) { each$8(axesList, function (axis) { if (!axis.model.get('axisLabel.inside')) { var labelUnionRect = getLabelUnionRect(axis); if (labelUnionRect) { var dim = axis.isHorizontal() ? 'height' : 'width'; var margin = axis.model.get('axisLabel.margin'); gridRect[dim] -= labelUnionRect[dim] + margin; if (axis.position === 'top') { gridRect.y += labelUnionRect.height + margin; } else if (axis.position === 'left') { gridRect.x += labelUnionRect.width + margin; } } } }); adjustAxes(); } function adjustAxes() { each$8(axesList, function (axis) { var isHorizontal = axis.isHorizontal(); var extent = isHorizontal ? [0, gridRect.width] : [0, gridRect.height]; var idx = axis.inverse ? 1 : 0; axis.setExtent(extent[idx], extent[1 - idx]); updateAxisTransfrom(axis, isHorizontal ? gridRect.x : gridRect.y); }); } }; /** * @param {string} axisType * @param {number} [axisIndex] */ gridProto.getAxis = function (axisType, axisIndex) { var axesMapOnDim = this._axesMap[axisType]; if (axesMapOnDim != null) { if (axisIndex == null) { // Find first axis for (var name in axesMapOnDim) { if (axesMapOnDim.hasOwnProperty(name)) { return axesMapOnDim[name]; } } } return axesMapOnDim[axisIndex]; } }; /** * @return {Array.<module:echarts/coord/Axis>} */ gridProto.getAxes = function () { return this._axesList.slice(); }; /** * Usage: * grid.getCartesian(xAxisIndex, yAxisIndex); * grid.getCartesian(xAxisIndex); * grid.getCartesian(null, yAxisIndex); * grid.getCartesian({xAxisIndex: ..., yAxisIndex: ...}); * * @param {number|Object} [xAxisIndex] * @param {number} [yAxisIndex] */ gridProto.getCartesian = function (xAxisIndex, yAxisIndex) { if (xAxisIndex != null && yAxisIndex != null) { var key = 'x' + xAxisIndex + 'y' + yAxisIndex; return this._coordsMap[key]; } if (isObject(xAxisIndex)) { yAxisIndex = xAxisIndex.yAxisIndex; xAxisIndex = xAxisIndex.xAxisIndex; } // When only xAxisIndex or yAxisIndex given, find its first cartesian. for (var i = 0, coordList = this._coordsList; i < coordList.length; i++) { if (coordList[i].getAxis('x').index === xAxisIndex || coordList[i].getAxis('y').index === yAxisIndex ) { return coordList[i]; } } }; gridProto.getCartesians = function () { return this._coordsList.slice(); }; /** * @implements * see {module:echarts/CoodinateSystem} */ gridProto.convertToPixel = function (ecModel, finder, value) { var target = this._findConvertTarget(ecModel, finder); return target.cartesian ? target.cartesian.dataToPoint(value) : target.axis ? target.axis.toGlobalCoord(target.axis.dataToCoord(value)) : null; }; /** * @implements * see {module:echarts/CoodinateSystem} */ gridProto.convertFromPixel = function (ecModel, finder, value) { var target = this._findConvertTarget(ecModel, finder); return target.cartesian ? target.cartesian.pointToData(value) : target.axis ? target.axis.coordToData(target.axis.toLocalCoord(value)) : null; }; /** * @inner */ gridProto._findConvertTarget = function (ecModel, finder) { var seriesModel = finder.seriesModel; var xAxisModel = finder.xAxisModel || (seriesModel && seriesModel.getReferringComponents('xAxis')[0]); var yAxisModel = finder.yAxisModel || (seriesModel && seriesModel.getReferringComponents('yAxis')[0]); var gridModel = finder.gridModel; var coordsList = this._coordsList; var cartesian; var axis; if (seriesModel) { cartesian = seriesModel.coordinateSystem; indexOf(coordsList, cartesian) < 0 && (cartesian = null); } else if (xAxisModel && yAxisModel) { cartesian = this.getCartesian(xAxisModel.componentIndex, yAxisModel.componentIndex); } else if (xAxisModel) { axis = this.getAxis('x', xAxisModel.componentIndex); } else if (yAxisModel) { axis = this.getAxis('y', yAxisModel.componentIndex); } // Lowest priority. else if (gridModel) { var grid = gridModel.coordinateSystem; if (grid === this) { cartesian = this._coordsList[0]; } } return {cartesian: cartesian, axis: axis}; }; /** * @implements * see {module:echarts/CoodinateSystem} */ gridProto.containPoint = function (point) { var coord = this._coordsList[0]; if (coord) { return coord.containPoint(point); } }; /** * Initialize cartesian coordinate systems * @private */ gridProto._initCartesian = function (gridModel, ecModel, api) { var axisPositionUsed = { left: false, right: false, top: false, bottom: false }; var axesMap = { x: {}, y: {} }; var axesCount = { x: 0, y: 0 }; /// Create axis ecModel.eachComponent('xAxis', createAxisCreator('x'), this); ecModel.eachComponent('yAxis', createAxisCreator('y'), this); if (!axesCount.x || !axesCount.y) { // Roll back when there no either x or y axis this._axesMap = {}; this._axesList = []; return; } this._axesMap = axesMap; /// Create cartesian2d each$8(axesMap.x, function (xAxis, xAxisIndex) { each$8(axesMap.y, function (yAxis, yAxisIndex) { var key = 'x' + xAxisIndex + 'y' + yAxisIndex; var cartesian = new Cartesian2D(key); cartesian.grid = this; cartesian.model = gridModel; this._coordsMap[key] = cartesian; this._coordsList.push(cartesian); cartesian.addAxis(xAxis); cartesian.addAxis(yAxis); }, this); }, this); function createAxisCreator(axisType) { return function (axisModel, idx) { if (!isAxisUsedInTheGrid(axisModel, gridModel, ecModel)) { return; } var axisPosition = axisModel.get('position'); if (axisType === 'x') { // Fix position if (axisPosition !== 'top' && axisPosition !== 'bottom') { // Default bottom of X axisPosition = 'bottom'; if (axisPositionUsed[axisPosition]) { axisPosition = axisPosition === 'top' ? 'bottom' : 'top'; } } } else { // Fix position if (axisPosition !== 'left' && axisPosition !== 'right') { // Default left of Y axisPosition = 'left'; if (axisPositionUsed[axisPosition]) { axisPosition = axisPosition === 'left' ? 'right' : 'left'; } } } axisPositionUsed[axisPosition] = true; var axis = new Axis2D( axisType, createScaleByModel(axisModel), [0, 0], axisModel.get('type'), axisPosition ); var isCategory = axis.type === 'category'; axis.onBand = isCategory && axisModel.get('boundaryGap'); axis.inverse = axisModel.get('inverse'); axis.onZero = axisModel.get('axisLine.onZero'); axis.onZeroAxisIndex = axisModel.get('axisLine.onZeroAxisIndex'); // Inject axis into axisModel axisModel.axis = axis; // Inject axisModel into axis axis.model = axisModel; // Inject grid info axis axis.grid = this; // Index of axis, can be used as key axis.index = idx; this._axesList.push(axis); axesMap[axisType][idx] = axis; axesCount[axisType]++; }; } }; /** * Update cartesian properties from series * @param {module:echarts/model/Option} option * @private */ gridProto._updateScale = function (ecModel, gridModel) { // Reset scale each$1(this._axesList, function (axis) { axis.scale.setExtent(Infinity, -Infinity); }); ecModel.eachSeries(function (seriesModel) { if (isCartesian2D(seriesModel)) { var axesModels = findAxesModels(seriesModel, ecModel); var xAxisModel = axesModels[0]; var yAxisModel = axesModels[1]; if (!isAxisUsedInTheGrid(xAxisModel, gridModel, ecModel) || !isAxisUsedInTheGrid(yAxisModel, gridModel, ecModel) ) { return; } var cartesian = this.getCartesian( xAxisModel.componentIndex, yAxisModel.componentIndex ); var data = seriesModel.getData(); var xAxis = cartesian.getAxis('x'); var yAxis = cartesian.getAxis('y'); if (data.type === 'list') { unionExtent(data, xAxis, seriesModel); unionExtent(data, yAxis, seriesModel); } } }, this); function unionExtent(data, axis, seriesModel) { each$8(seriesModel.coordDimToDataDim(axis.dim), function (dim) { axis.scale.unionExtentFromData(data, dim); }); } }; /** * @param {string} [dim] 'x' or 'y' or 'auto' or null/undefined * @return {Object} {baseAxes: [], otherAxes: []} */ gridProto.getTooltipAxes = function (dim) { var baseAxes = []; var otherAxes = []; each$8(this.getCartesians(), function (cartesian) { var baseAxis = (dim != null && dim !== 'auto') ? cartesian.getAxis(dim) : cartesian.getBaseAxis(); var otherAxis = cartesian.getOtherAxis(baseAxis); indexOf(baseAxes, baseAxis) < 0 && baseAxes.push(baseAxis); indexOf(otherAxes, otherAxis) < 0 && otherAxes.push(otherAxis); }); return {baseAxes: baseAxes, otherAxes: otherAxes}; }; /** * @inner */ function updateAxisTransfrom(axis, coordBase) { var axisExtent = axis.getExtent(); var axisExtentSum = axisExtent[0] + axisExtent[1]; // Fast transform axis.toGlobalCoord = axis.dim === 'x' ? function (coord) { return coord + coordBase; } : function (coord) { return axisExtentSum - coord + coordBase; }; axis.toLocalCoord = axis.dim === 'x' ? function (coord) { return coord - coordBase; } : function (coord) { return axisExtentSum - coord + coordBase; }; } var axesTypes = ['xAxis', 'yAxis']; /** * @inner */ function findAxesModels(seriesModel, ecModel) { return map(axesTypes, function (axisType) { var axisModel = seriesModel.getReferringComponents(axisType)[0]; if (__DEV__) { if (!axisModel) { throw new Error(axisType + ' "' + retrieve( seriesModel.get(axisType + 'Index'), seriesModel.get(axisType + 'Id'), 0 ) + '" not found'); } } return axisModel; }); } /** * @inner */ function isCartesian2D(seriesModel) { return seriesModel.get('coordinateSystem') === 'cartesian2d'; } Grid.create = function (ecModel, api) { var grids = []; ecModel.eachComponent('grid', function (gridModel, idx) { var grid = new Grid(gridModel, ecModel, api); grid.name = 'grid_' + idx; // dataSampling requires axis extent, so resize // should be performed in create stage. grid.resize(gridModel, api, true); gridModel.coordinateSystem = grid; grids.push(grid); }); // Inject the coordinateSystems into seriesModel ecModel.eachSeries(function (seriesModel) { if (!isCartesian2D(seriesModel)) { return; } var axesModels = findAxesModels(seriesModel, ecModel); var xAxisModel = axesModels[0]; var yAxisModel = axesModels[1]; var gridModel = xAxisModel.getCoordSysModel(); if (__DEV__) { if (!gridModel) { throw new Error( 'Grid "' + retrieve( xAxisModel.get('gridIndex'), xAxisModel.get('gridId'), 0 ) + '" not found' ); } if (xAxisModel.getCoordSysModel() !== yAxisModel.getCoordSysModel()) { throw new Error('xAxis and yAxis must use the same grid'); } } var grid = gridModel.coordinateSystem; seriesModel.coordinateSystem = grid.getCartesian( xAxisModel.componentIndex, yAxisModel.componentIndex ); }); return grids; }; // For deciding which dimensions to use when creating list data Grid.dimensions = Grid.prototype.dimensions = Cartesian2D.prototype.dimensions; CoordinateSystemManager.register('cartesian2d', Grid); var PI$2 = Math.PI; function makeAxisEventDataBase(axisModel) { var eventData = { componentType: axisModel.mainType }; eventData[axisModel.mainType + 'Index'] = axisModel.componentIndex; return eventData; } /** * A final axis is translated and rotated from a "standard axis". * So opt.position and opt.rotation is required. * * A standard axis is and axis from [0, 0] to [0, axisExtent[1]], * for example: (0, 0) ------------> (0, 50) * * nameDirection or tickDirection or labelDirection is 1 means tick * or label is below the standard axis, whereas is -1 means above * the standard axis. labelOffset means offset between label and axis, * which is useful when 'onZero', where axisLabel is in the grid and * label in outside grid. * * Tips: like always, * positive rotation represents anticlockwise, and negative rotation * represents clockwise. * The direction of position coordinate is the same as the direction * of screen coordinate. * * Do not need to consider axis 'inverse', which is auto processed by * axis extent. * * @param {module:zrender/container/Group} group * @param {Object} axisModel * @param {Object} opt Standard axis parameters. * @param {Array.<number>} opt.position [x, y] * @param {number} opt.rotation by radian * @param {number} [opt.nameDirection=1] 1 or -1 Used when nameLocation is 'middle' or 'center'. * @param {number} [opt.tickDirection=1] 1 or -1 * @param {number} [opt.labelDirection=1] 1 or -1 * @param {number} [opt.labelOffset=0] Usefull when onZero. * @param {string} [opt.axisLabelShow] default get from axisModel. * @param {string} [opt.axisName] default get from axisModel. * @param {number} [opt.axisNameAvailableWidth] * @param {number} [opt.labelRotate] by degree, default get from axisModel. * @param {number} [opt.labelInterval] Default label interval when label * interval from model is null or 'auto'. * @param {number} [opt.strokeContainThreshold] Default label interval when label * @param {number} [opt.nameTruncateMaxWidth] */ var AxisBuilder = function (axisModel, opt) { /** * @readOnly */ this.opt = opt; /** * @readOnly */ this.axisModel = axisModel; // Default value defaults( opt, { labelOffset: 0, nameDirection: 1, tickDirection: 1, labelDirection: 1, silent: true } ); /** * @readOnly */ this.group = new Group(); // FIXME Not use a seperate text group? var dumbGroup = new Group({ position: opt.position.slice(), rotation: opt.rotation }); // this.group.add(dumbGroup); // this._dumbGroup = dumbGroup; dumbGroup.updateTransform(); this._transform = dumbGroup.transform; this._dumbGroup = dumbGroup; }; AxisBuilder.prototype = { constructor: AxisBuilder, hasBuilder: function (name) { return !!builders[name]; }, add: function (name) { builders[name].call(this); }, getGroup: function () { return this.group; } }; var builders = { /** * @private */ axisLine: function () { var opt = this.opt; var axisModel = this.axisModel; if (!axisModel.get('axisLine.show')) { return; } var extent = this.axisModel.axis.getExtent(); var matrix = this._transform; var pt1 = [extent[0], 0]; var pt2 = [extent[1], 0]; if (matrix) { applyTransform(pt1, pt1, matrix); applyTransform(pt2, pt2, matrix); } var lineStyle = extend( { lineCap: 'round' }, axisModel.getModel('axisLine.lineStyle').getLineStyle() ); this.group.add(new Line(subPixelOptimizeLine({ // Id for animation anid: 'line', shape: { x1: pt1[0], y1: pt1[1], x2: pt2[0], y2: pt2[1] }, style: lineStyle, strokeContainThreshold: opt.strokeContainThreshold || 5, silent: true, z2: 1 }))); var arrows = axisModel.get('axisLine.symbol'); var arrowSize = axisModel.get('axisLine.symbolSize'); if (arrows != null) { if (typeof arrows === 'string') { // Use the same arrow for start and end point arrows = [arrows, arrows]; } if (typeof arrowSize === 'string' || typeof arrowSize === 'number' ) { // Use the same size for width and height arrowSize = [arrowSize, arrowSize]; } var symbolWidth = arrowSize[0]; var symbolHeight = arrowSize[1]; each$1([ [opt.rotation + Math.PI / 2, pt1], [opt.rotation - Math.PI / 2, pt2] ], function (item, index) { if (arrows[index] !== 'none' && arrows[index] != null) { var symbol = createSymbol( arrows[index], -symbolWidth / 2, -symbolHeight / 2, symbolWidth, symbolHeight, lineStyle.stroke, true ); symbol.attr({ rotation: item[0], position: item[1], silent: true }); this.group.add(symbol); } }, this); } }, /** * @private */ axisTickLabel: function () { var axisModel = this.axisModel; var opt = this.opt; var tickEls = buildAxisTick(this, axisModel, opt); var labelEls = buildAxisLabel(this, axisModel, opt); fixMinMaxLabelShow(axisModel, labelEls, tickEls); }, /** * @private */ axisName: function () { var opt = this.opt; var axisModel = this.axisModel; var name = retrieve(opt.axisName, axisModel.get('name')); if (!name) { return; } var nameLocation = axisModel.get('nameLocation'); var nameDirection = opt.nameDirection; var textStyleModel = axisModel.getModel('nameTextStyle'); var gap = axisModel.get('nameGap') || 0; var extent = this.axisModel.axis.getExtent(); var gapSignal = extent[0] > extent[1] ? -1 : 1; var pos = [ nameLocation === 'start' ? extent[0] - gapSignal * gap : nameLocation === 'end' ? extent[1] + gapSignal * gap : (extent[0] + extent[1]) / 2, // 'middle' // Reuse labelOffset. isNameLocationCenter(nameLocation) ? opt.labelOffset + nameDirection * gap : 0 ]; var labelLayout; var nameRotation = axisModel.get('nameRotate'); if (nameRotation != null) { nameRotation = nameRotation * PI$2 / 180; // To radian. } var axisNameAvailableWidth; if (isNameLocationCenter(nameLocation)) { labelLayout = innerTextLayout( opt.rotation, nameRotation != null ? nameRotation : opt.rotation, // Adapt to axis. nameDirection ); } else { labelLayout = endTextLayout( opt, nameLocation, nameRotation || 0, extent ); axisNameAvailableWidth = opt.axisNameAvailableWidth; if (axisNameAvailableWidth != null) { axisNameAvailableWidth = Math.abs( axisNameAvailableWidth / Math.sin(labelLayout.rotation) ); !isFinite(axisNameAvailableWidth) && (axisNameAvailableWidth = null); } } var textFont = textStyleModel.getFont(); var truncateOpt = axisModel.get('nameTruncate', true) || {}; var ellipsis = truncateOpt.ellipsis; var maxWidth = retrieve( opt.nameTruncateMaxWidth, truncateOpt.maxWidth, axisNameAvailableWidth ); // FIXME // truncate rich text? (consider performance) var truncatedText = (ellipsis != null && maxWidth != null) ? truncateText$1( name, maxWidth, textFont, ellipsis, {minChar: 2, placeholder: truncateOpt.placeholder} ) : name; var tooltipOpt = axisModel.get('tooltip', true); var mainType = axisModel.mainType; var formatterParams = { componentType: mainType, name: name, $vars: ['name'] }; formatterParams[mainType + 'Index'] = axisModel.componentIndex; var textEl = new Text({ // Id for animation anid: 'name', __fullText: name, __truncatedText: truncatedText, position: pos, rotation: labelLayout.rotation, silent: isSilent(axisModel), z2: 1, tooltip: (tooltipOpt && tooltipOpt.show) ? extend({ content: name, formatter: function () { return name; }, formatterParams: formatterParams }, tooltipOpt) : null }); setTextStyle(textEl.style, textStyleModel, { text: truncatedText, textFont: textFont, textFill: textStyleModel.getTextColor() || axisModel.get('axisLine.lineStyle.color'), textAlign: labelLayout.textAlign, textVerticalAlign: labelLayout.textVerticalAlign }); if (axisModel.get('triggerEvent')) { textEl.eventData = makeAxisEventDataBase(axisModel); textEl.eventData.targetType = 'axisName'; textEl.eventData.name = name; } // FIXME this._dumbGroup.add(textEl); textEl.updateTransform(); this.group.add(textEl); textEl.decomposeTransform(); } }; /** * @public * @static * @param {Object} opt * @param {number} axisRotation in radian * @param {number} textRotation in radian * @param {number} direction * @return {Object} { * rotation, // according to axis * textAlign, * textVerticalAlign * } */ var innerTextLayout = AxisBuilder.innerTextLayout = function (axisRotation, textRotation, direction) { var rotationDiff = remRadian(textRotation - axisRotation); var textAlign; var textVerticalAlign; if (isRadianAroundZero(rotationDiff)) { // Label is parallel with axis line. textVerticalAlign = direction > 0 ? 'top' : 'bottom'; textAlign = 'center'; } else if (isRadianAroundZero(rotationDiff - PI$2)) { // Label is inverse parallel with axis line. textVerticalAlign = direction > 0 ? 'bottom' : 'top'; textAlign = 'center'; } else { textVerticalAlign = 'middle'; if (rotationDiff > 0 && rotationDiff < PI$2) { textAlign = direction > 0 ? 'right' : 'left'; } else { textAlign = direction > 0 ? 'left' : 'right'; } } return { rotation: rotationDiff, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; }; function endTextLayout(opt, textPosition, textRotate, extent) { var rotationDiff = remRadian(textRotate - opt.rotation); var textAlign; var textVerticalAlign; var inverse = extent[0] > extent[1]; var onLeft = (textPosition === 'start' && !inverse) || (textPosition !== 'start' && inverse); if (isRadianAroundZero(rotationDiff - PI$2 / 2)) { textVerticalAlign = onLeft ? 'bottom' : 'top'; textAlign = 'center'; } else if (isRadianAroundZero(rotationDiff - PI$2 * 1.5)) { textVerticalAlign = onLeft ? 'top' : 'bottom'; textAlign = 'center'; } else { textVerticalAlign = 'middle'; if (rotationDiff < PI$2 * 1.5 && rotationDiff > PI$2 / 2) { textAlign = onLeft ? 'left' : 'right'; } else { textAlign = onLeft ? 'right' : 'left'; } } return { rotation: rotationDiff, textAlign: textAlign, textVerticalAlign: textVerticalAlign }; } function isSilent(axisModel) { var tooltipOpt = axisModel.get('tooltip'); return axisModel.get('silent') // Consider mouse cursor, add these restrictions. || !( axisModel.get('triggerEvent') || (tooltipOpt && tooltipOpt.show) ); } function fixMinMaxLabelShow(axisModel, labelEls, tickEls) { // If min or max are user set, we need to check // If the tick on min(max) are overlap on their neighbour tick // If they are overlapped, we need to hide the min(max) tick label var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); // FIXME // Have not consider onBand yet, where tick els is more than label els. labelEls = labelEls || []; tickEls = tickEls || []; var firstLabel = labelEls[0]; var nextLabel = labelEls[1]; var lastLabel = labelEls[labelEls.length - 1]; var prevLabel = labelEls[labelEls.length - 2]; var firstTick = tickEls[0]; var nextTick = tickEls[1]; var lastTick = tickEls[tickEls.length - 1]; var prevTick = tickEls[tickEls.length - 2]; if (showMinLabel === false) { ignoreEl(firstLabel); ignoreEl(firstTick); } else if (isTwoLabelOverlapped(firstLabel, nextLabel)) { if (showMinLabel) { ignoreEl(nextLabel); ignoreEl(nextTick); } else { ignoreEl(firstLabel); ignoreEl(firstTick); } } if (showMaxLabel === false) { ignoreEl(lastLabel); ignoreEl(lastTick); } else if (isTwoLabelOverlapped(prevLabel, lastLabel)) { if (showMaxLabel) { ignoreEl(prevLabel); ignoreEl(prevTick); } else { ignoreEl(lastLabel); ignoreEl(lastTick); } } } function ignoreEl(el) { el && (el.ignore = true); } function isTwoLabelOverlapped(current, next, labelLayout) { // current and next has the same rotation. var firstRect = current && current.getBoundingRect().clone(); var nextRect = next && next.getBoundingRect().clone(); if (!firstRect || !nextRect) { return; } // When checking intersect of two rotated labels, we use mRotationBack // to avoid that boundingRect is enlarge when using `boundingRect.applyTransform`. var mRotationBack = identity([]); rotate(mRotationBack, mRotationBack, -current.rotation); firstRect.applyTransform(mul$1([], mRotationBack, current.getLocalTransform())); nextRect.applyTransform(mul$1([], mRotationBack, next.getLocalTransform())); return firstRect.intersect(nextRect); } function isNameLocationCenter(nameLocation) { return nameLocation === 'middle' || nameLocation === 'center'; } /** * @static */ var ifIgnoreOnTick$1 = AxisBuilder.ifIgnoreOnTick = function ( axis, i, interval, ticksCnt, showMinLabel, showMaxLabel ) { if (i === 0 && showMinLabel || i === ticksCnt - 1 && showMaxLabel) { return false; } // FIXME // Have not consider label overlap (if label is too long) yet. var rawTick; var scale$$1 = axis.scale; return scale$$1.type === 'ordinal' && ( typeof interval === 'function' ? ( rawTick = scale$$1.getTicks()[i], !interval(rawTick, scale$$1.getLabel(rawTick)) ) : i % (interval + 1) ); }; /** * @static */ var getInterval$1 = AxisBuilder.getInterval = function (model, labelInterval) { var interval = model.get('interval'); if (interval == null || interval == 'auto') { interval = labelInterval; } return interval; }; function buildAxisTick(axisBuilder, axisModel, opt) { var axis = axisModel.axis; if (!axisModel.get('axisTick.show') || axis.scale.isBlank()) { return; } var tickModel = axisModel.getModel('axisTick'); var lineStyleModel = tickModel.getModel('lineStyle'); var tickLen = tickModel.get('length'); var tickInterval = getInterval$1(tickModel, opt.labelInterval); var ticksCoords = axis.getTicksCoords(tickModel.get('alignWithLabel')); // FIXME // Corresponds to ticksCoords ? var ticks = axis.scale.getTicks(); var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); var pt1 = []; var pt2 = []; var matrix = axisBuilder._transform; var tickEls = []; var ticksCnt = ticksCoords.length; for (var i = 0; i < ticksCnt; i++) { // Only ordinal scale support tick interval if (ifIgnoreOnTick$1( axis, i, tickInterval, ticksCnt, showMinLabel, showMaxLabel )) { continue; } var tickCoord = ticksCoords[i]; pt1[0] = tickCoord; pt1[1] = 0; pt2[0] = tickCoord; pt2[1] = opt.tickDirection * tickLen; if (matrix) { applyTransform(pt1, pt1, matrix); applyTransform(pt2, pt2, matrix); } // Tick line, Not use group transform to have better line draw var tickEl = new Line(subPixelOptimizeLine({ // Id for animation anid: 'tick_' + ticks[i], shape: { x1: pt1[0], y1: pt1[1], x2: pt2[0], y2: pt2[1] }, style: defaults( lineStyleModel.getLineStyle(), { stroke: axisModel.get('axisLine.lineStyle.color') } ), z2: 2, silent: true })); axisBuilder.group.add(tickEl); tickEls.push(tickEl); } return tickEls; } function buildAxisLabel(axisBuilder, axisModel, opt) { var axis = axisModel.axis; var show = retrieve(opt.axisLabelShow, axisModel.get('axisLabel.show')); if (!show || axis.scale.isBlank()) { return; } var labelModel = axisModel.getModel('axisLabel'); var labelMargin = labelModel.get('margin'); var ticks = axis.scale.getTicks(); var labels = axisModel.getFormattedLabels(); // Special label rotate. var labelRotation = ( retrieve(opt.labelRotate, labelModel.get('rotate')) || 0 ) * PI$2 / 180; var labelLayout = innerTextLayout(opt.rotation, labelRotation, opt.labelDirection); var categoryData = axisModel.get('data'); var labelEls = []; var silent = isSilent(axisModel); var triggerEvent = axisModel.get('triggerEvent'); var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); each$1(ticks, function (tickVal, index) { if (ifIgnoreOnTick$1( axis, index, opt.labelInterval, ticks.length, showMinLabel, showMaxLabel )) { return; } var itemLabelModel = labelModel; if (categoryData && categoryData[tickVal] && categoryData[tickVal].textStyle) { itemLabelModel = new Model( categoryData[tickVal].textStyle, labelModel, axisModel.ecModel ); } var textColor = itemLabelModel.getTextColor() || axisModel.get('axisLine.lineStyle.color'); var tickCoord = axis.dataToCoord(tickVal); var pos = [ tickCoord, opt.labelOffset + opt.labelDirection * labelMargin ]; var labelStr = axis.scale.getLabel(tickVal); var textEl = new Text({ // Id for animation anid: 'label_' + tickVal, position: pos, rotation: labelLayout.rotation, silent: silent, z2: 10 }); setTextStyle(textEl.style, itemLabelModel, { text: labels[index], textAlign: itemLabelModel.getShallow('align', true) || labelLayout.textAlign, textVerticalAlign: itemLabelModel.getShallow('verticalAlign', true) || itemLabelModel.getShallow('baseline', true) || labelLayout.textVerticalAlign, textFill: typeof textColor === 'function' ? textColor( // (1) In category axis with data zoom, tick is not the original // index of axis.data. So tick should not be exposed to user // in category axis. // (2) Compatible with previous version, which always returns labelStr. // But in interval scale labelStr is like '223,445', which maked // user repalce ','. So we modify it to return original val but remain // it as 'string' to avoid error in replacing. axis.type === 'category' ? labelStr : axis.type === 'value' ? tickVal + '' : tickVal, index ) : textColor }); // Pack data for mouse event if (triggerEvent) { textEl.eventData = makeAxisEventDataBase(axisModel); textEl.eventData.targetType = 'axisLabel'; textEl.eventData.value = labelStr; } // FIXME axisBuilder._dumbGroup.add(textEl); textEl.updateTransform(); labelEls.push(textEl); axisBuilder.group.add(textEl); textEl.decomposeTransform(); }); return labelEls; } // Build axisPointerModel, mergin tooltip.axisPointer model for each axis. // allAxesInfo should be updated when setOption performed. function fixValue(axisModel) { var axisInfo = getAxisInfo(axisModel); if (!axisInfo) { return; } var axisPointerModel = axisInfo.axisPointerModel; var scale = axisInfo.axis.scale; var option = axisPointerModel.option; var status = axisPointerModel.get('status'); var value = axisPointerModel.get('value'); // Parse init value for category and time axis. if (value != null) { value = scale.parse(value); } var useHandle = isHandleTrigger(axisPointerModel); // If `handle` used, `axisPointer` will always be displayed, so value // and status should be initialized. if (status == null) { option.status = useHandle ? 'show' : 'hide'; } var extent = scale.getExtent().slice(); extent[0] > extent[1] && extent.reverse(); if (// Pick a value on axis when initializing. value == null // If both `handle` and `dataZoom` are used, value may be out of axis extent, // where we should re-pick a value to keep `handle` displaying normally. || value > extent[1] ) { // Make handle displayed on the end of the axis when init, which looks better. value = extent[1]; } if (value < extent[0]) { value = extent[0]; } option.value = value; if (useHandle) { option.status = axisInfo.axis.scale.isBlank() ? 'hide' : 'show'; } } function getAxisInfo(axisModel) { var coordSysAxesInfo = (axisModel.ecModel.getComponent('axisPointer') || {}).coordSysAxesInfo; return coordSysAxesInfo && coordSysAxesInfo.axesInfo[makeKey(axisModel)]; } function getAxisPointerModel(axisModel) { var axisInfo = getAxisInfo(axisModel); return axisInfo && axisInfo.axisPointerModel; } function isHandleTrigger(axisPointerModel) { return !!axisPointerModel.get('handle.show'); } /** * @param {module:echarts/model/Model} model * @return {string} unique key */ function makeKey(model) { return model.type + '||' + model.id; } /** * Base class of AxisView. */ var AxisView = extendComponentView({ type: 'axis', /** * @private */ _axisPointer: null, /** * @protected * @type {string} */ axisPointerClass: null, /** * @override */ render: function (axisModel, ecModel, api, payload) { // FIXME // This process should proformed after coordinate systems updated // (axis scale updated), and should be performed each time update. // So put it here temporarily, although it is not appropriate to // put a model-writing procedure in `view`. this.axisPointerClass && fixValue(axisModel); AxisView.superApply(this, 'render', arguments); updateAxisPointer(this, axisModel, ecModel, api, payload, true); }, /** * Action handler. * @public * @param {module:echarts/coord/cartesian/AxisModel} axisModel * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api * @param {Object} payload */ updateAxisPointer: function (axisModel, ecModel, api, payload, force) { updateAxisPointer(this, axisModel, ecModel, api, payload, false); }, /** * @override */ remove: function (ecModel, api) { var axisPointer = this._axisPointer; axisPointer && axisPointer.remove(api); AxisView.superApply(this, 'remove', arguments); }, /** * @override */ dispose: function (ecModel, api) { disposeAxisPointer(this, api); AxisView.superApply(this, 'dispose', arguments); } }); function updateAxisPointer(axisView, axisModel, ecModel, api, payload, forceRender) { var Clazz = AxisView.getAxisPointerClass(axisView.axisPointerClass); if (!Clazz) { return; } var axisPointerModel = getAxisPointerModel(axisModel); axisPointerModel ? (axisView._axisPointer || (axisView._axisPointer = new Clazz())) .render(axisModel, axisPointerModel, api, forceRender) : disposeAxisPointer(axisView, api); } function disposeAxisPointer(axisView, ecModel, api) { var axisPointer = axisView._axisPointer; axisPointer && axisPointer.dispose(ecModel, api); axisView._axisPointer = null; } var axisPointerClazz = []; AxisView.registerAxisPointerClass = function (type, clazz) { if (__DEV__) { if (axisPointerClazz[type]) { throw new Error('axisPointer ' + type + ' exists'); } } axisPointerClazz[type] = clazz; }; AxisView.getAxisPointerClass = function (type) { return type && axisPointerClazz[type]; }; /** * @param {Object} opt {labelInside} * @return {Object} { * position, rotation, labelDirection, labelOffset, * tickDirection, labelRotate, labelInterval, z2 * } */ function layout(gridModel, axisModel, opt) { opt = opt || {}; var grid = gridModel.coordinateSystem; var axis = axisModel.axis; var layout = {}; var rawAxisPosition = axis.position; var axisPosition = axis.onZero ? 'onZero' : rawAxisPosition; var axisDim = axis.dim; var rect = grid.getRect(); var rectBound = [rect.x, rect.x + rect.width, rect.y, rect.y + rect.height]; var idx = {left: 0, right: 1, top: 0, bottom: 1, onZero: 2}; var axisOffset = axisModel.get('offset') || 0; var posBound = axisDim === 'x' ? [rectBound[2] - axisOffset, rectBound[3] + axisOffset] : [rectBound[0] - axisOffset, rectBound[1] + axisOffset]; if (axis.onZero) { var otherAxis = grid.getAxis(axisDim === 'x' ? 'y' : 'x', axis.onZeroAxisIndex); var onZeroCoord = otherAxis.toGlobalCoord(otherAxis.dataToCoord(0)); posBound[idx['onZero']] = Math.max(Math.min(onZeroCoord, posBound[1]), posBound[0]); } // Axis position layout.position = [ axisDim === 'y' ? posBound[idx[axisPosition]] : rectBound[0], axisDim === 'x' ? posBound[idx[axisPosition]] : rectBound[3] ]; // Axis rotation layout.rotation = Math.PI / 2 * (axisDim === 'x' ? 0 : 1); // Tick and label direction, x y is axisDim var dirMap = {top: -1, bottom: 1, left: -1, right: 1}; layout.labelDirection = layout.tickDirection = layout.nameDirection = dirMap[rawAxisPosition]; layout.labelOffset = axis.onZero ? posBound[idx[rawAxisPosition]] - posBound[idx['onZero']] : 0; if (axisModel.get('axisTick.inside')) { layout.tickDirection = -layout.tickDirection; } if (retrieve(opt.labelInside, axisModel.get('axisLabel.inside'))) { layout.labelDirection = -layout.labelDirection; } // Special label rotation var labelRotate = axisModel.get('axisLabel.rotate'); layout.labelRotate = axisPosition === 'top' ? -labelRotate : labelRotate; // label interval when auto mode. layout.labelInterval = axis.getLabelInterval(); // Over splitLine and splitArea layout.z2 = 1; return layout; } var ifIgnoreOnTick = AxisBuilder.ifIgnoreOnTick; var getInterval = AxisBuilder.getInterval; var axisBuilderAttrs = [ 'axisLine', 'axisTickLabel', 'axisName' ]; var selfBuilderAttrs = [ 'splitArea', 'splitLine' ]; // function getAlignWithLabel(model, axisModel) { // var alignWithLabel = model.get('alignWithLabel'); // if (alignWithLabel === 'auto') { // alignWithLabel = axisModel.get('axisTick.alignWithLabel'); // } // return alignWithLabel; // } var CartesianAxisView = AxisView.extend({ type: 'cartesianAxis', axisPointerClass: 'CartesianAxisPointer', /** * @override */ render: function (axisModel, ecModel, api, payload) { this.group.removeAll(); var oldAxisGroup = this._axisGroup; this._axisGroup = new Group(); this.group.add(this._axisGroup); if (!axisModel.get('show')) { return; } var gridModel = axisModel.getCoordSysModel(); var layout$$1 = layout(gridModel, axisModel); var axisBuilder = new AxisBuilder(axisModel, layout$$1); each$1(axisBuilderAttrs, axisBuilder.add, axisBuilder); this._axisGroup.add(axisBuilder.getGroup()); each$1(selfBuilderAttrs, function (name) { if (axisModel.get(name + '.show')) { this['_' + name](axisModel, gridModel, layout$$1.labelInterval); } }, this); groupTransition(oldAxisGroup, this._axisGroup, axisModel); CartesianAxisView.superCall(this, 'render', axisModel, ecModel, api, payload); }, /** * @param {module:echarts/coord/cartesian/AxisModel} axisModel * @param {module:echarts/coord/cartesian/GridModel} gridModel * @param {number|Function} labelInterval * @private */ _splitLine: function (axisModel, gridModel, labelInterval) { var axis = axisModel.axis; if (axis.scale.isBlank()) { return; } var splitLineModel = axisModel.getModel('splitLine'); var lineStyleModel = splitLineModel.getModel('lineStyle'); var lineColors = lineStyleModel.get('color'); var lineInterval = getInterval(splitLineModel, labelInterval); lineColors = isArray(lineColors) ? lineColors : [lineColors]; var gridRect = gridModel.coordinateSystem.getRect(); var isHorizontal = axis.isHorizontal(); var lineCount = 0; var ticksCoords = axis.getTicksCoords( // splitLineModel.get('alignWithLabel') ); var ticks = axis.scale.getTicks(); var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); var p1 = []; var p2 = []; // Simple optimization // Batching the lines if color are the same var lineStyle = lineStyleModel.getLineStyle(); for (var i = 0; i < ticksCoords.length; i++) { if (ifIgnoreOnTick( axis, i, lineInterval, ticksCoords.length, showMinLabel, showMaxLabel )) { continue; } var tickCoord = axis.toGlobalCoord(ticksCoords[i]); if (isHorizontal) { p1[0] = tickCoord; p1[1] = gridRect.y; p2[0] = tickCoord; p2[1] = gridRect.y + gridRect.height; } else { p1[0] = gridRect.x; p1[1] = tickCoord; p2[0] = gridRect.x + gridRect.width; p2[1] = tickCoord; } var colorIndex = (lineCount++) % lineColors.length; this._axisGroup.add(new Line(subPixelOptimizeLine({ anid: 'line_' + ticks[i], shape: { x1: p1[0], y1: p1[1], x2: p2[0], y2: p2[1] }, style: defaults({ stroke: lineColors[colorIndex] }, lineStyle), silent: true }))); } }, /** * @param {module:echarts/coord/cartesian/AxisModel} axisModel * @param {module:echarts/coord/cartesian/GridModel} gridModel * @param {number|Function} labelInterval * @private */ _splitArea: function (axisModel, gridModel, labelInterval) { var axis = axisModel.axis; if (axis.scale.isBlank()) { return; } var splitAreaModel = axisModel.getModel('splitArea'); var areaStyleModel = splitAreaModel.getModel('areaStyle'); var areaColors = areaStyleModel.get('color'); var gridRect = gridModel.coordinateSystem.getRect(); var ticksCoords = axis.getTicksCoords( // splitAreaModel.get('alignWithLabel') ); var ticks = axis.scale.getTicks(); var prevX = axis.toGlobalCoord(ticksCoords[0]); var prevY = axis.toGlobalCoord(ticksCoords[0]); var count = 0; var areaInterval = getInterval(splitAreaModel, labelInterval); var areaStyle = areaStyleModel.getAreaStyle(); areaColors = isArray(areaColors) ? areaColors : [areaColors]; var showMinLabel = axisModel.get('axisLabel.showMinLabel'); var showMaxLabel = axisModel.get('axisLabel.showMaxLabel'); for (var i = 1; i < ticksCoords.length; i++) { if (ifIgnoreOnTick( axis, i, areaInterval, ticksCoords.length, showMinLabel, showMaxLabel )) { continue; } var tickCoord = axis.toGlobalCoord(ticksCoords[i]); var x; var y; var width; var height; if (axis.isHorizontal()) { x = prevX; y = gridRect.y; width = tickCoord - x; height = gridRect.height; } else { x = gridRect.x; y = prevY; width = gridRect.width; height = tickCoord - y; } var colorIndex = (count++) % areaColors.length; this._axisGroup.add(new Rect({ anid: 'area_' + ticks[i], shape: { x: x, y: y, width: width, height: height }, style: defaults({ fill: areaColors[colorIndex] }, areaStyle), silent: true })); prevX = x + width; prevY = y + height; } } }); CartesianAxisView.extend({ type: 'xAxis' }); CartesianAxisView.extend({ type: 'yAxis' }); // Grid view extendComponentView({ type: 'grid', render: function (gridModel, ecModel) { this.group.removeAll(); if (gridModel.get('show')) { this.group.add(new Rect({ shape: gridModel.coordinateSystem.getRect(), style: defaults({ fill: gridModel.get('backgroundColor') }, gridModel.getItemStyle()), silent: true, z2: -1 })); } } }); registerPreprocessor(function (option) { // Only create grid when need if (option.xAxis && option.yAxis && !option.grid) { option.grid = {}; } }); // In case developer forget to include grid component registerVisual(curry( visualSymbol, 'line', 'circle', 'line' )); registerLayout(curry( layoutPoints, 'line' )); // Down sample after filter registerProcessor(PRIORITY.PROCESSOR.STATISTIC, curry( dataSample, 'line' )); var STACK_PREFIX = '__ec_stack_'; function getSeriesStackId(seriesModel) { return seriesModel.get('stack') || STACK_PREFIX + seriesModel.seriesIndex; } function getAxisKey(axis) { return axis.dim + axis.index; } /** * @param {Object} opt * @param {module:echarts/coord/Axis} opt.axis Only support category axis currently. * @param {number} opt.count Positive interger. * @param {number} [opt.barWidth] * @param {number} [opt.barMaxWidth] * @param {number} [opt.barGap] * @param {number} [opt.barCategoryGap] * @return {Object} {width, offset, offsetCenter} If axis.type is not 'category', return undefined. */ function getLayoutOnAxis(opt, api) { var params = []; var baseAxis = opt.axis; var axisKey = 'axis0'; if (baseAxis.type !== 'category') { return; } var bandWidth = baseAxis.getBandWidth(); for (var i = 0; i < opt.count || 0; i++) { params.push(defaults({ bandWidth: bandWidth, axisKey: axisKey, stackId: STACK_PREFIX + i }, opt)); } var widthAndOffsets = doCalBarWidthAndOffset(params, api); var result = []; for (var i = 0; i < opt.count; i++) { var item = widthAndOffsets[axisKey][STACK_PREFIX + i]; item.offsetCenter = item.offset + item.width / 2; result.push(item); } return result; } function calBarWidthAndOffset(barSeries, api) { var seriesInfoList = map(barSeries, function (seriesModel) { var data = seriesModel.getData(); var cartesian = seriesModel.coordinateSystem; var baseAxis = cartesian.getBaseAxis(); var axisExtent = baseAxis.getExtent(); var bandWidth = baseAxis.type === 'category' ? baseAxis.getBandWidth() : (Math.abs(axisExtent[1] - axisExtent[0]) / data.count()); var barWidth = parsePercent$1( seriesModel.get('barWidth'), bandWidth ); var barMaxWidth = parsePercent$1( seriesModel.get('barMaxWidth'), bandWidth ); var barGap = seriesModel.get('barGap'); var barCategoryGap = seriesModel.get('barCategoryGap'); return { bandWidth: bandWidth, barWidth: barWidth, barMaxWidth: barMaxWidth, barGap: barGap, barCategoryGap: barCategoryGap, axisKey: getAxisKey(baseAxis), stackId: getSeriesStackId(seriesModel) }; }); return doCalBarWidthAndOffset(seriesInfoList, api); } function doCalBarWidthAndOffset(seriesInfoList, api) { // Columns info on each category axis. Key is cartesian name var columnsMap = {}; each$1(seriesInfoList, function (seriesInfo, idx) { var axisKey = seriesInfo.axisKey; var bandWidth = seriesInfo.bandWidth; var columnsOnAxis = columnsMap[axisKey] || { bandWidth: bandWidth, remainedWidth: bandWidth, autoWidthCount: 0, categoryGap: '20%', gap: '30%', stacks: {} }; var stacks = columnsOnAxis.stacks; columnsMap[axisKey] = columnsOnAxis; var stackId = seriesInfo.stackId; if (!stacks[stackId]) { columnsOnAxis.autoWidthCount++; } stacks[stackId] = stacks[stackId] || { width: 0, maxWidth: 0 }; // Caution: In a single coordinate system, these barGrid attributes // will be shared by series. Consider that they have default values, // only the attributes set on the last series will work. // Do not change this fact unless there will be a break change. // TODO var barWidth = seriesInfo.barWidth; if (barWidth && !stacks[stackId].width) { // See #6312, do not restrict width. stacks[stackId].width = barWidth; barWidth = Math.min(columnsOnAxis.remainedWidth, barWidth); columnsOnAxis.remainedWidth -= barWidth; } var barMaxWidth = seriesInfo.barMaxWidth; barMaxWidth && (stacks[stackId].maxWidth = barMaxWidth); var barGap = seriesInfo.barGap; (barGap != null) && (columnsOnAxis.gap = barGap); var barCategoryGap = seriesInfo.barCategoryGap; (barCategoryGap != null) && (columnsOnAxis.categoryGap = barCategoryGap); }); var result = {}; each$1(columnsMap, function (columnsOnAxis, coordSysName) { result[coordSysName] = {}; var stacks = columnsOnAxis.stacks; var bandWidth = columnsOnAxis.bandWidth; var categoryGap = parsePercent$1(columnsOnAxis.categoryGap, bandWidth); var barGapPercent = parsePercent$1(columnsOnAxis.gap, 1); var remainedWidth = columnsOnAxis.remainedWidth; var autoWidthCount = columnsOnAxis.autoWidthCount; var autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent); autoWidth = Math.max(autoWidth, 0); // Find if any auto calculated bar exceeded maxBarWidth each$1(stacks, function (column, stack) { var maxWidth = column.maxWidth; if (maxWidth && maxWidth < autoWidth) { maxWidth = Math.min(maxWidth, remainedWidth); if (column.width) { maxWidth = Math.min(maxWidth, column.width); } remainedWidth -= maxWidth; column.width = maxWidth; autoWidthCount--; } }); // Recalculate width again autoWidth = (remainedWidth - categoryGap) / (autoWidthCount + (autoWidthCount - 1) * barGapPercent); autoWidth = Math.max(autoWidth, 0); var widthSum = 0; var lastColumn; each$1(stacks, function (column, idx) { if (!column.width) { column.width = autoWidth; } lastColumn = column; widthSum += column.width * (1 + barGapPercent); }); if (lastColumn) { widthSum -= lastColumn.width * barGapPercent; } var offset = -widthSum / 2; each$1(stacks, function (column, stackId) { result[coordSysName][stackId] = result[coordSysName][stackId] || { offset: offset, width: column.width }; offset += column.width * (1 + barGapPercent); }); }); return result; } /** * @param {string} seriesType * @param {module:echarts/model/Global} ecModel * @param {module:echarts/ExtensionAPI} api */ function barLayoutGrid(seriesType, ecModel, api) { var barWidthAndOffset = calBarWidthAndOffset( filter( ecModel.getSeriesByType(seriesType), function (seriesModel) { return !ecModel.isSeriesFiltered(seriesModel) && seriesModel.coordinateSystem && seriesModel.coordinateSystem.type === 'cartesian2d'; } ) ); var lastStackCoords = {}; var lastStackCoordsOrigin = {}; ecModel.eachSeriesByType(seriesType, function (seriesModel) { // Check series coordinate, do layout for cartesian2d only if (seriesModel.coordinateSystem.type !== 'cartesian2d') { return; } var data = seriesModel.getData(); var cartesian = seriesModel.coordinateSystem; var baseAxis = cartesian.getBaseAxis(); var stackId = getSeriesStackId(seriesModel); var columnLayoutInfo = barWidthAndOffset[getAxisKey(baseAxis)][stackId]; var columnOffset = columnLayoutInfo.offset; var columnWidth = columnLayoutInfo.width; var valueAxis = cartesian.getOtherAxis(baseAxis); var barMinHeight = seriesModel.get('barMinHeight') || 0; var valueAxisStart = baseAxis.onZero ? valueAxis.toGlobalCoord(valueAxis.dataToCoord(0)) : valueAxis.getGlobalExtent()[0]; var coordDims = [ seriesModel.coordDimToDataDim('x')[0], seriesModel.coordDimToDataDim('y')[0] ]; var coords = data.mapArray(coordDims, function (x, y) { return cartesian.dataToPoint([x, y]); }, true); lastStackCoords[stackId] = lastStackCoords[stackId] || []; lastStackCoordsOrigin[stackId] = lastStackCoordsOrigin[stackId] || []; // Fix #4243 data.setLayout({ offset: columnOffset, size: columnWidth }); data.each(seriesModel.coordDimToDataDim(valueAxis.dim)[0], function (value, idx) { if (isNaN(value)) { return; } if (!lastStackCoords[stackId][idx]) { lastStackCoords[stackId][idx] = { p: valueAxisStart, // Positive stack n: valueAxisStart // Negative stack }; lastStackCoordsOrigin[stackId][idx] = { p: valueAxisStart, // Positive stack n: valueAxisStart // Negative stack }; } var sign = value >= 0 ? 'p' : 'n'; var coord = coords[idx]; var lastCoord = lastStackCoords[stackId][idx][sign]; var lastCoordOrigin = lastStackCoordsOrigin[stackId][idx][sign]; var x; var y; var width; var height; if (valueAxis.isHorizontal()) { x = lastCoord; y = coord[1] + columnOffset; width = coord[0] - lastCoordOrigin; height = columnWidth; lastStackCoordsOrigin[stackId][idx][sign] += width; if (Math.abs(width) < barMinHeight) { width = (width < 0 ? -1 : 1) * barMinHeight; } lastStackCoords[stackId][idx][sign] += width; } else { x = coord[0] + columnOffset; y = lastCoord; width = columnWidth; height = coord[1] - lastCoordOrigin; lastStackCoordsOrigin[stackId][idx][sign] += height; if (Math.abs(height) < barMinHeight) { // Include zero to has a positive bar height = (height <= 0 ? -1 : 1) * barMinHeight; } lastStackCoords[stackId][idx][sign] += height; } data.setItemLayout(idx, { x: x, y: y, width: width, height: height }); }, true); }, this); } barLayoutGrid.getLayoutOnAxis = getLayoutOnAxis; var BaseBarSeries = SeriesModel.extend({ type: 'series.__base_bar__', getInitialData: function (option, ecModel) { return createListFromArray(option.data, this, ecModel); }, getMarkerPosition: function (value) { var coordSys = this.coordinateSystem; if (coordSys) { // PENDING if clamp ? var pt = coordSys.dataToPoint(value, true); var data = this.getData(); var offset = data.getLayout('offset'); var size = data.getLayout('size'); var offsetIndex = coordSys.getBaseAxis().isHorizontal() ? 0 : 1; pt[offsetIndex] += offset + size / 2; return pt; } return [NaN, NaN]; }, defaultOption: { zlevel: 0, // 一级层叠 z: 2, // 二级层叠 coordinateSystem: 'cartesian2d', legendHoverLink: true, // stack: null // Cartesian coordinate system // xAxisIndex: 0, // yAxisIndex: 0, // 最小高度改为0 barMinHeight: 0, // 最小角度为0,仅对极坐标系下的柱状图有效 barMinAngle: 0, // cursor: null, // barMaxWidth: null, // 默认自适应 // barWidth: null, // 柱间距离,默认为柱形宽度的30%,可设固定值 // barGap: '30%', // 类目间柱形距离,默认为类目间距的20%,可设固定值 // barCategoryGap: '20%', // label: { // normal: { // show: false // } // }, itemStyle: { // normal: { // color: '各异' // }, // emphasis: {} } } }); BaseBarSeries.extend({ type: 'series.bar', dependencies: ['grid', 'polar'], brushSelector: 'rect' }); function setLabel( normalStyle, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside ) { var labelModel = itemModel.getModel('label.normal'); var hoverLabelModel = itemModel.getModel('label.emphasis'); setLabelStyle( normalStyle, hoverStyle, labelModel, hoverLabelModel, { labelFetcher: seriesModel, labelDataIndex: dataIndex, defaultText: seriesModel.getRawValue(dataIndex), isRectText: true, autoColor: color } ); fixPosition(normalStyle); fixPosition(hoverStyle); } function fixPosition(style, labelPositionOutside) { if (style.textPosition === 'outside') { style.textPosition = labelPositionOutside; } } var getBarItemStyle = makeStyleMapper( [ ['fill', 'color'], ['stroke', 'borderColor'], ['lineWidth', 'borderWidth'], // Compatitable with 2 ['stroke', 'barBorderColor'], ['lineWidth', 'barBorderWidth'], ['opacity'], ['shadowBlur'], ['shadowOffsetX'], ['shadowOffsetY'], ['shadowColor'] ] ); var barItemStyle = { getBarItemStyle: function (excludes) { var style = getBarItemStyle(this, excludes); if (this.getBorderLineDash) { var lineDash = this.getBorderLineDash(); lineDash && (style.lineDash = lineDash); } return style; } }; var BAR_BORDER_WIDTH_QUERY = ['itemStyle', 'normal', 'barBorderWidth']; // FIXME // Just for compatible with ec2. extend(Model.prototype, barItemStyle); extendChartView({ type: 'bar', render: function (seriesModel, ecModel, api) { var coordinateSystemType = seriesModel.get('coordinateSystem'); if (coordinateSystemType === 'cartesian2d' || coordinateSystemType === 'polar' ) { this._render(seriesModel, ecModel, api); } else if (__DEV__) { console.warn('Only cartesian2d and polar supported for bar.'); } return this.group; }, dispose: noop, _render: function (seriesModel, ecModel, api) { var group = this.group; var data = seriesModel.getData(); var oldData = this._data; var coord = seriesModel.coordinateSystem; var baseAxis = coord.getBaseAxis(); var isHorizontalOrRadial; if (coord.type === 'cartesian2d') { isHorizontalOrRadial = baseAxis.isHorizontal(); } else if (coord.type === 'polar') { isHorizontalOrRadial = baseAxis.dim === 'angle'; } var animationModel = seriesModel.isAnimationEnabled() ? seriesModel : null; data.diff(oldData) .add(function (dataIndex) { if (!data.hasValue(dataIndex)) { return; } var itemModel = data.getItemModel(dataIndex); var layout = getLayout[coord.type](data, dataIndex, itemModel); var el = elementCreator[coord.type]( data, dataIndex, itemModel, layout, isHorizontalOrRadial, animationModel ); data.setItemGraphicEl(dataIndex, el); group.add(el); updateStyle( el, data, dataIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar' ); }) .update(function (newIndex, oldIndex) { var el = oldData.getItemGraphicEl(oldIndex); if (!data.hasValue(newIndex)) { group.remove(el); return; } var itemModel = data.getItemModel(newIndex); var layout = getLayout[coord.type](data, newIndex, itemModel); if (el) { updateProps(el, {shape: layout}, animationModel, newIndex); } else { el = elementCreator[coord.type]( data, newIndex, itemModel, layout, isHorizontalOrRadial, animationModel, true ); } data.setItemGraphicEl(newIndex, el); // Add back group.add(el); updateStyle( el, data, newIndex, itemModel, layout, seriesModel, isHorizontalOrRadial, coord.type === 'polar' ); }) .remove(function (dataIndex) { var el = oldData.getItemGraphicEl(dataIndex); if (coord.type === 'cartesian2d') { el && removeRect(dataIndex, animationModel, el); } else { el && removeSector(dataIndex, animationModel, el); } }) .execute(); this._data = data; }, remove: function (ecModel, api) { var group = this.group; var data = this._data; if (ecModel.get('animation')) { if (data) { data.eachItemGraphicEl(function (el) { if (el.type === 'sector') { removeSector(el.dataIndex, ecModel, el); } else { removeRect(el.dataIndex, ecModel, el); } }); } } else { group.removeAll(); } } }); var elementCreator = { cartesian2d: function ( data, dataIndex, itemModel, layout, isHorizontal, animationModel, isUpdate ) { var rect = new Rect({shape: extend({}, layout)}); // Animation if (animationModel) { var rectShape = rect.shape; var animateProperty = isHorizontal ? 'height' : 'width'; var animateTarget = {}; rectShape[animateProperty] = 0; animateTarget[animateProperty] = layout[animateProperty]; graphic[isUpdate ? 'updateProps' : 'initProps'](rect, { shape: animateTarget }, animationModel, dataIndex); } return rect; }, polar: function ( data, dataIndex, itemModel, layout, isRadial, animationModel, isUpdate ) { var sector = new Sector({shape: extend({}, layout)}); // Animation if (animationModel) { var sectorShape = sector.shape; var animateProperty = isRadial ? 'r' : 'endAngle'; var animateTarget = {}; sectorShape[animateProperty] = isRadial ? 0 : layout.startAngle; animateTarget[animateProperty] = layout[animateProperty]; graphic[isUpdate ? 'updateProps' : 'initProps'](sector, { shape: animateTarget }, animationModel, dataIndex); } return sector; } }; function removeRect(dataIndex, animationModel, el) { // Not show text when animating el.style.text = null; updateProps(el, { shape: { width: 0 } }, animationModel, dataIndex, function () { el.parent && el.parent.remove(el); }); } function removeSector(dataIndex, animationModel, el) { // Not show text when animating el.style.text = null; updateProps(el, { shape: { r: el.shape.r0 } }, animationModel, dataIndex, function () { el.parent && el.parent.remove(el); }); } var getLayout = { cartesian2d: function (data, dataIndex, itemModel) { var layout = data.getItemLayout(dataIndex); var fixedLineWidth = getLineWidth(itemModel, layout); // fix layout with lineWidth var signX = layout.width > 0 ? 1 : -1; var signY = layout.height > 0 ? 1 : -1; return { x: layout.x + signX * fixedLineWidth / 2, y: layout.y + signY * fixedLineWidth / 2, width: layout.width - signX * fixedLineWidth, height: layout.height - signY * fixedLineWidth }; }, polar: function (data, dataIndex, itemModel) { var layout = data.getItemLayout(dataIndex); return { cx: layout.cx, cy: layout.cy, r0: layout.r0, r: layout.r, startAngle: layout.startAngle, endAngle: layout.endAngle }; } }; function updateStyle( el, data, dataIndex, itemModel, layout, seriesModel, isHorizontal, isPolar ) { var color = data.getItemVisual(dataIndex, 'color'); var opacity = data.getItemVisual(dataIndex, 'opacity'); var itemStyleModel = itemModel.getModel('itemStyle.normal'); var hoverStyle = itemModel.getModel('itemStyle.emphasis').getBarItemStyle(); if (!isPolar) { el.setShape('r', itemStyleModel.get('barBorderRadius') || 0); } el.useStyle(defaults( { fill: color, opacity: opacity }, itemStyleModel.getBarItemStyle() )); var cursorStyle = itemModel.getShallow('cursor'); cursorStyle && el.attr('cursor', cursorStyle); var labelPositionOutside = isHorizontal ? (layout.height > 0 ? 'bottom' : 'top') : (layout.width > 0 ? 'left' : 'right'); if (!isPolar) { setLabel( el.style, hoverStyle, itemModel, color, seriesModel, dataIndex, labelPositionOutside ); } setHoverStyle(el, hoverStyle); } // In case width or height are too small. function getLineWidth(itemModel, rawLayout) { var lineWidth = itemModel.get(BAR_BORDER_WIDTH_QUERY) || 0; return Math.min(lineWidth, Math.abs(rawLayout.width), Math.abs(rawLayout.height)); } // In case developer forget to include grid component registerLayout(curry(barLayoutGrid, 'bar')); // Visual coding for legend registerVisual(function (ecModel) { ecModel.eachSeriesByType('bar', function (seriesModel) { var data = seriesModel.getData(); data.setVisual('legendSymbol', 'roundRect'); }); }); /** * Data selectable mixin for chart series. * To eanble data select, option of series must have `selectedMode`. * And each data item will use `selected` to toggle itself selected status */ var dataSelectableMixin = { updateSelectedMap: function (targetList) { this._targetList = targetList.slice(); this._selectTargetMap = reduce(targetList || [], function (targetMap, target) { targetMap.set(target.name, target); return targetMap; }, createHashMap()); }, /** * Either name or id should be passed as input here. * If both of them are defined, id is used. * * @param {string|undefined} name name of data * @param {number|undefined} id dataIndex of data */ // PENGING If selectedMode is null ? select: function (name, id) { var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); var selectedMode = this.get('selectedMode'); if (selectedMode === 'single') { this._selectTargetMap.each(function (target) { target.selected = false; }); } target && (target.selected = true); }, /** * Either name or id should be passed as input here. * If both of them are defined, id is used. * * @param {string|undefined} name name of data * @param {number|undefined} id dataIndex of data */ unSelect: function (name, id) { var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); // var selectedMode = this.get('selectedMode'); // selectedMode !== 'single' && target && (target.selected = false); target && (target.selected = false); }, /** * Either name or id should be passed as input here. * If both of them are defined, id is used. * * @param {string|undefined} name name of data * @param {number|undefined} id dataIndex of data */ toggleSelected: function (name, id) { var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); if (target != null) { this[target.selected ? 'unSelect' : 'select'](name, id); return target.selected; } }, /** * Either name or id should be passed as input here. * If both of them are defined, id is used. * * @param {string|undefined} name name of data * @param {number|undefined} id dataIndex of data */ isSelected: function (name, id) { var target = id != null ? this._targetList[id] : this._selectTargetMap.get(name); return target && target.selected; } }; var PieSeries = extendSeriesModel({ type: 'series.pie', // Overwrite init: function (option) { PieSeries.superApply(this, 'init', arguments); // Enable legend selection for each data item // Use a function instead of direct access because data reference may changed this.legendDataProvider = function () { return this.getRawData(); }; this.updateSelectedMap(option.data); this._defaultLabelLine(option); }, // Overwrite mergeOption: function (newOption) { PieSeries.superCall(this, 'mergeOption', newOption); this.updateSelectedMap(this.option.data); }, getInitialData: function (option, ecModel) { var dimensions = completeDimensions(['value'], option.data); var list = new List(dimensions, this); list.initData(option.data); return list; }, // Overwrite getDataParams: function (dataIndex) { var data = this.getData(); var params = PieSeries.superCall(this, 'getDataParams', dataIndex); // FIXME toFixed? var valueList = []; data.each('value', function (value) { valueList.push(value); }); params.percent = getPercentWithPrecision( valueList, dataIndex, data.hostModel.get('percentPrecision') ); params.$vars.push('percent'); return params; }, _defaultLabelLine: function (option) { // Extend labelLine emphasis defaultEmphasis(option.labelLine, ['show']); var labelLineNormalOpt = option.labelLine.normal; var labelLineEmphasisOpt = option.labelLine.emphasis; // Not show label line if `label.normal.show = false` labelLineNormalOpt.show = labelLineNormalOpt.show && option.label.normal.show; labelLineEmphasisOpt.show = labelLineEmphasisOpt.show && option.label.emphasis.show; }, defaultOption: { zlevel: 0, z: 2, legendHoverLink: true, hoverAnimation: true, // 默认全局居中 center: ['50%', '50%'], radius: [0, '75%'], // 默认顺时针 clockwise: true, startAngle: 90, // 最小角度改为0 minAngle: 0, // 选中时扇区偏移量 selectedOffset: 10, // 高亮扇区偏移量 hoverOffset: 10, // If use strategy to avoid label overlapping avoidLabelOverlap: true, // 选择模式,默认关闭,可选single,multiple // selectedMode: false, // 南丁格尔玫瑰图模式,'radius'(半径) | 'area'(面积) // roseType: null, percentPrecision: 2, // If still show when all data zero. stillShowZeroSum: true, // cursor: null, label: { normal: { // If rotate around circle rotate: false, show: true, // 'outer', 'inside', 'center' position: 'outer' // formatter: 标签文本格式器,同Tooltip.formatter,不支持异步回调 // 默认使用全局文本样式,详见TEXTSTYLE // distance: 当position为inner时有效,为label位置到圆心的距离与圆半径(环状图为内外半径和)的比例系数 }, emphasis: {} }, // Enabled when label.normal.position is 'outer' labelLine: { normal: { show: true, // 引导线两段中的第一段长度 length: 15, // 引导线两段中的第二段长度 length2: 15, smooth: false, lineStyle: { // color: 各异, width: 1, type: 'solid' } } }, itemStyle: { normal: { borderWidth: 1 }, emphasis: {} }, // Animation type canbe expansion, scale animationType: 'expansion', animationEasing: 'cubicOut', data: [] } }); mixin(PieSeries, dataSelectableMixin); /** * @param {module:echarts/model/Series} seriesModel * @param {boolean} hasAnimation * @inner */ function updateDataSelected(uid, seriesModel, hasAnimation, api) { var data = seriesModel.getData(); var dataIndex = this.dataIndex; var name = data.getName(dataIndex); var selectedOffset = seriesModel.get('selectedOffset'); api.dispatchAction({ type: 'pieToggleSelect', from: uid, name: name, seriesId: seriesModel.id }); data.each(function (idx) { toggleItemSelected( data.getItemGraphicEl(idx), data.getItemLayout(idx), seriesModel.isSelected(data.getName(idx)), selectedOffset, hasAnimation ); }); } /** * @param {module:zrender/graphic/Sector} el * @param {Object} layout * @param {boolean} isSelected * @param {number} selectedOffset * @param {boolean} hasAnimation * @inner */ function toggleItemSelected(el, layout, isSelected, selectedOffset, hasAnimation) { var midAngle = (layout.startAngle + layout.endAngle) / 2; var dx = Math.cos(midAngle); var dy = Math.sin(midAngle); var offset = isSelected ? selectedOffset : 0; var position = [dx * offset, dy * offset]; hasAnimation // animateTo will stop revious animation like update transition ? el.animate() .when(200, { position: position }) .start('bounceOut') : el.attr('position', position); } /** * Piece of pie including Sector, Label, LabelLine * @constructor * @extends {module:zrender/graphic/Group} */ function PiePiece(data, idx) { Group.call(this); var sector = new Sector({ z2: 2 }); var polyline = new Polyline(); var text = new Text(); this.add(sector); this.add(polyline); this.add(text); this.updateData(data, idx, true); // Hover to change label and labelLine function onEmphasis() { polyline.ignore = polyline.hoverIgnore; text.ignore = text.hoverIgnore; } function onNormal() { polyline.ignore = polyline.normalIgnore; text.ignore = text.normalIgnore; } this.on('emphasis', onEmphasis) .on('normal', onNormal) .on('mouseover', onEmphasis) .on('mouseout', onNormal); } var piePieceProto = PiePiece.prototype; piePieceProto.updateData = function (data, idx, firstCreate) { var sector = this.childAt(0); var seriesModel = data.hostModel; var itemModel = data.getItemModel(idx); var layout = data.getItemLayout(idx); var sectorShape = extend({}, layout); sectorShape.label = null; if (firstCreate) { sector.setShape(sectorShape); var animationType = seriesModel.getShallow('animationType'); if (animationType === 'scale') { sector.shape.r = layout.r0; initProps(sector, { shape: { r: layout.r } }, seriesModel, idx); } // Expansion else { sector.shape.endAngle = layout.startAngle; updateProps(sector, { shape: { endAngle: layout.endAngle } }, seriesModel, idx); } } else { updateProps(sector, { shape: sectorShape }, seriesModel, idx); } // Update common style var itemStyleModel = itemModel.getModel('itemStyle'); var visualColor = data.getItemVisual(idx, 'color'); sector.useStyle( defaults( { lineJoin: 'bevel', fill: visualColor }, itemStyleModel.getModel('normal').getItemStyle() ) ); sector.hoverStyle = itemStyleModel.getModel('emphasis').getItemStyle(); var cursorStyle = itemModel.getShallow('cursor'); cursorStyle && sector.attr('cursor', cursorStyle); // Toggle selected toggleItemSelected( this, data.getItemLayout(idx), itemModel.get('selected'), seriesModel.get('selectedOffset'), seriesModel.get('animation') ); function onEmphasis() { // Sector may has animation of updating data. Force to move to the last frame // Or it may stopped on the wrong shape sector.stopAnimation(true); sector.animateTo({ shape: { r: layout.r + seriesModel.get('hoverOffset') } }, 300, 'elasticOut'); } function onNormal() { sector.stopAnimation(true); sector.animateTo({ shape: { r: layout.r } }, 300, 'elasticOut'); } sector.off('mouseover').off('mouseout').off('emphasis').off('normal'); if (itemModel.get('hoverAnimation') && seriesModel.isAnimationEnabled()) { sector .on('mouseover', onEmphasis) .on('mouseout', onNormal) .on('emphasis', onEmphasis) .on('normal', onNormal); } this._updateLabel(data, idx); setHoverStyle(this); }; piePieceProto._updateLabel = function (data, idx) { var labelLine = this.childAt(1); var labelText = this.childAt(2); var seriesModel = data.hostModel; var itemModel = data.getItemModel(idx); var layout = data.getItemLayout(idx); var labelLayout = layout.label; var visualColor = data.getItemVisual(idx, 'color'); updateProps(labelLine, { shape: { points: labelLayout.linePoints || [ [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y], [labelLayout.x, labelLayout.y] ] } }, seriesModel, idx); updateProps(labelText, { style: { x: labelLayout.x, y: labelLayout.y } }, seriesModel, idx); labelText.attr({ rotation: labelLayout.rotation, origin: [labelLayout.x, labelLayout.y], z2: 10 }); var labelModel = itemModel.getModel('label.normal'); var labelHoverModel = itemModel.getModel('label.emphasis'); var labelLineModel = itemModel.getModel('labelLine.normal'); var labelLineHoverModel = itemModel.getModel('labelLine.emphasis'); var visualColor = data.getItemVisual(idx, 'color'); setLabelStyle( labelText.style, labelText.hoverStyle = {}, labelModel, labelHoverModel, { labelFetcher: data.hostModel, labelDataIndex: idx, defaultText: data.getName(idx), autoColor: visualColor, useInsideStyle: !!labelLayout.inside }, { textAlign: labelLayout.textAlign, textVerticalAlign: labelLayout.verticalAlign, opacity: data.getItemVisual(idx, 'opacity') } ); labelText.ignore = labelText.normalIgnore = !labelModel.get('show'); labelText.hoverIgnore = !labelHoverModel.get('show'); labelLine.ignore = labelLine.normalIgnore = !labelLineModel.get('show'); labelLine.hoverIgnore = !labelLineHoverModel.get('show'); // Default use item visual color labelLine.setStyle({ stroke: visualColor, opacity: data.getItemVisual(idx, 'opacity') }); labelLine.setStyle(labelLineModel.getModel('lineStyle').getLineStyle()); labelLine.hoverStyle = labelLineHoverModel.getModel('lineStyle').getLineStyle(); var smooth = labelLineModel.get('smooth'); if (smooth && smooth === true) { smooth = 0.4; } labelLine.setShape({ smooth: smooth }); }; inherits(PiePiece, Group); // Pie view var PieView = Chart.extend({ type: 'pie', init: function () { var sectorGroup = new Group(); this._sectorGroup = sectorGroup; }, render: function (seriesModel, ecModel, api, payload) { if (payload && (payload.from === this.uid)) { return; } var data = seriesModel.getData(); var oldData = this._data; var group = this.group; var hasAnimation = ecModel.get('animation'); var isFirstRender = !oldData; var animationType = seriesModel.get('animationType'); var onSectorClick = curry( updateDataSelected, this.uid, seriesModel, hasAnimation, api ); var selectedMode = seriesModel.get('selectedMode'); data.diff(oldData) .add(function (idx) { var piePiece = new PiePiece(data, idx); // Default expansion animation if (isFirstRender && animationType !== 'scale') { piePiece.eachChild(function (child) { child.stopAnimation(true); }); } selectedMode && piePiece.on('click', onSectorClick); data.setItemGraphicEl(idx, piePiece); group.add(piePiece); }) .update(function (newIdx, oldIdx) { var piePiece = oldData.getItemGraphicEl(oldIdx); piePiece.updateData(data, newIdx); piePiece.off('click'); selectedMode && piePiece.on('click', onSectorClick); group.add(piePiece); data.setItemGraphicEl(newIdx, piePiece); }) .remove(function (idx) { var piePiece = oldData.getItemGraphicEl(idx); group.remove(piePiece); }) .execute(); if ( hasAnimation && isFirstRender && data.count() > 0 // Default expansion animation && animationType !== 'scale' ) { var shape = data.getItemLayout(0); var r = Math.max(api.getWidth(), api.getHeight()) / 2; var removeClipPath = bind(group.removeClipPath, group); group.setClipPath(this._createClipPath( shape.cx, shape.cy, r, shape.startAngle, shape.clockwise, removeClipPath, seriesModel )); } this._data = data; }, dispose: function () {}, _createClipPath: function ( cx, cy, r, startAngle, clockwise, cb, seriesModel ) { var clipPath = new Sector({ shape: { cx: cx, cy: cy, r0: 0, r: r, startAngle: startAngle, endAngle: startAngle, clockwise: clockwise } }); initProps(clipPath, { shape: { endAngle: startAngle + (clockwise ? 1 : -1) * Math.PI * 2 } }, seriesModel, cb); return clipPath; }, /** * @implement */ containPoint: function (point, seriesModel) { var data = seriesModel.getData(); var itemLayout = data.getItemLayout(0); if (itemLayout) { var dx = point[0] - itemLayout.cx; var dy = point[1] - itemLayout.cy; var radius = Math.sqrt(dx * dx + dy * dy); return radius <= itemLayout.r && radius >= itemLayout.r0; } } }); var createDataSelectAction = function (seriesType, actionInfos) { each$1(actionInfos, function (actionInfo) { actionInfo.update = 'updateView'; /** * @payload * @property {string} seriesName * @property {string} name */ registerAction(actionInfo, function (payload, ecModel) { var selected = {}; ecModel.eachComponent( {mainType: 'series', subType: seriesType, query: payload}, function (seriesModel) { if (seriesModel[actionInfo.method]) { seriesModel[actionInfo.method]( payload.name, payload.dataIndex ); } var data = seriesModel.getData(); // Create selected map data.each(function (idx) { var name = data.getName(idx); selected[name] = seriesModel.isSelected(name) || false; }); } ); return { name: payload.name, selected: selected }; }); }); }; // Pick color from palette for each data item. // Applicable for charts that require applying color palette // in data level (like pie, funnel, chord). var dataColor = function (seriesType, ecModel) { // Pie and funnel may use diferrent scope var paletteScope = {}; ecModel.eachRawSeriesByType(seriesType, function (seriesModel) { var dataAll = seriesModel.getRawData(); var idxMap = {}; if (!ecModel.isSeriesFiltered(seriesModel)) { var data = seriesModel.getData(); data.each(function (idx) { var rawIdx = data.getRawIndex(idx); idxMap[rawIdx] = idx; }); dataAll.each(function (rawIdx) { var filteredIdx = idxMap[rawIdx]; // If series.itemStyle.normal.color is a function. itemVisual may be encoded var singleDataColor = filteredIdx != null && data.getItemVisual(filteredIdx, 'color', true); if (!singleDataColor) { // FIXME Performance var itemModel = dataAll.getItemModel(rawIdx); var color = itemModel.get('itemStyle.normal.color') || seriesModel.getColorFromPalette(dataAll.getName(rawIdx), paletteScope); // Legend may use the visual info in data before processed dataAll.setItemVisual(rawIdx, 'color', color); // Data is not filtered if (filteredIdx != null) { data.setItemVisual(filteredIdx, 'color', color); } } else { // Set data all color for legend dataAll.setItemVisual(rawIdx, 'color', singleDataColor); } }); } }); }; // FIXME emphasis label position is not same with normal label position function adjustSingleSide(list, cx, cy, r, dir, viewWidth, viewHeight) { list.sort(function (a, b) { return a.y - b.y; }); // 压 function shiftDown(start, end, delta, dir) { for (var j = start; j < end; j++) { list[j].y += delta; if (j > start && j + 1 < end && list[j + 1].y > list[j].y + list[j].height ) { shiftUp(j, delta / 2); return; } } shiftUp(end - 1, delta / 2); } // 弹 function shiftUp(end, delta) { for (var j = end; j >= 0; j--) { list[j].y -= delta; if (j > 0 && list[j].y > list[j - 1].y + list[j - 1].height ) { break; } } } function changeX(list, isDownList, cx, cy, r, dir) { var lastDeltaX = dir > 0 ? isDownList // 右侧 ? Number.MAX_VALUE // 下 : 0 // 上 : isDownList // 左侧 ? Number.MAX_VALUE // 下 : 0; // 上 for (var i = 0, l = list.length; i < l; i++) { // Not change x for center label if (list[i].position === 'center') { continue; } var deltaY = Math.abs(list[i].y - cy); var length = list[i].len; var length2 = list[i].len2; var deltaX = (deltaY < r + length) ? Math.sqrt( (r + length + length2) * (r + length + length2) - deltaY * deltaY ) : Math.abs(list[i].x - cx); if (isDownList && deltaX >= lastDeltaX) { // 右下,左下 deltaX = lastDeltaX - 10; } if (!isDownList && deltaX <= lastDeltaX) { // 右上,左上 deltaX = lastDeltaX + 10; } list[i].x = cx + deltaX * dir; lastDeltaX = deltaX; } } var lastY = 0; var delta; var len = list.length; var upList = []; var downList = []; for (var i = 0; i < len; i++) { delta = list[i].y - lastY; if (delta < 0) { shiftDown(i, len, -delta, dir); } lastY = list[i].y + list[i].height; } if (viewHeight - lastY < 0) { shiftUp(len - 1, lastY - viewHeight); } for (var i = 0; i < len; i++) { if (list[i].y >= cy) { downList.push(list[i]); } else { upList.push(list[i]); } } changeX(upList, false, cx, cy, r, dir); changeX(downList, true, cx, cy, r, dir); } function avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight) { var leftList = []; var rightList = []; for (var i = 0; i < labelLayoutList.length; i++) { if (labelLayoutList[i].x < cx) { leftList.push(labelLayoutList[i]); } else { rightList.push(labelLayoutList[i]); } } adjustSingleSide(rightList, cx, cy, r, 1, viewWidth, viewHeight); adjustSingleSide(leftList, cx, cy, r, -1, viewWidth, viewHeight); for (var i = 0; i < labelLayoutList.length; i++) { var linePoints = labelLayoutList[i].linePoints; if (linePoints) { var dist = linePoints[1][0] - linePoints[2][0]; if (labelLayoutList[i].x < cx) { linePoints[2][0] = labelLayoutList[i].x + 3; } else { linePoints[2][0] = labelLayoutList[i].x - 3; } linePoints[1][1] = linePoints[2][1] = labelLayoutList[i].y; linePoints[1][0] = linePoints[2][0] + dist; } } } var labelLayout = function (seriesModel, r, viewWidth, viewHeight) { var data = seriesModel.getData(); var labelLayoutList = []; var cx; var cy; var hasLabelRotate = false; data.each(function (idx) { var layout = data.getItemLayout(idx); var itemModel = data.getItemModel(idx); var labelModel = itemModel.getModel('label.normal'); // Use position in normal or emphasis var labelPosition = labelModel.get('position') || itemModel.get('label.emphasis.position'); var labelLineModel = itemModel.getModel('labelLine.normal'); var labelLineLen = labelLineModel.get('length'); var labelLineLen2 = labelLineModel.get('length2'); var midAngle = (layout.startAngle + layout.endAngle) / 2; var dx = Math.cos(midAngle); var dy = Math.sin(midAngle); var textX; var textY; var linePoints; var textAlign; cx = layout.cx; cy = layout.cy; var isLabelInside = labelPosition === 'inside' || labelPosition === 'inner'; if (labelPosition === 'center') { textX = layout.cx; textY = layout.cy; textAlign = 'center'; } else { var x1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dx : layout.r * dx) + cx; var y1 = (isLabelInside ? (layout.r + layout.r0) / 2 * dy : layout.r * dy) + cy; textX = x1 + dx * 3; textY = y1 + dy * 3; if (!isLabelInside) { // For roseType var x2 = x1 + dx * (labelLineLen + r - layout.r); var y2 = y1 + dy * (labelLineLen + r - layout.r); var x3 = x2 + ((dx < 0 ? -1 : 1) * labelLineLen2); var y3 = y2; textX = x3 + (dx < 0 ? -5 : 5); textY = y3; linePoints = [[x1, y1], [x2, y2], [x3, y3]]; } textAlign = isLabelInside ? 'center' : (dx > 0 ? 'left' : 'right'); } var font = labelModel.getFont(); var labelRotate = labelModel.get('rotate') ? (dx < 0 ? -midAngle + Math.PI : -midAngle) : 0; var text = seriesModel.getFormattedLabel(idx, 'normal') || data.getName(idx); var textRect = getBoundingRect( text, font, textAlign, 'top' ); hasLabelRotate = !!labelRotate; layout.label = { x: textX, y: textY, position: labelPosition, height: textRect.height, len: labelLineLen, len2: labelLineLen2, linePoints: linePoints, textAlign: textAlign, verticalAlign: 'middle', rotation: labelRotate, inside: isLabelInside }; // Not layout the inside label if (!isLabelInside) { labelLayoutList.push(layout.label); } }); if (!hasLabelRotate && seriesModel.get('avoidLabelOverlap')) { avoidOverlap(labelLayoutList, cx, cy, r, viewWidth, viewHeight); } }; var PI2$4 = Math.PI * 2; var RADIAN = Math.PI / 180; var pieLayout = function (seriesType, ecModel, api, payload) { ecModel.eachSeriesByType(seriesType, function (seriesModel) { var center = seriesModel.get('center'); var radius = seriesModel.get('radius'); if (!isArray(radius)) { radius = [0, radius]; } if (!isArray(center)) { center = [center, center]; } var width = api.getWidth(); var height = api.getHeight(); var size = Math.min(width, height); var cx = parsePercent$1(center[0], width); var cy = parsePercent$1(center[1], height); var r0 = parsePercent$1(radius[0], size / 2); var r = parsePercent$1(radius[1], size / 2); var data = seriesModel.getData(); var startAngle = -seriesModel.get('startAngle') * RADIAN; var minAngle = seriesModel.get('minAngle') * RADIAN; var validDataCount = 0; data.each('value', function (value) { !isNaN(value) && validDataCount++; }); var sum = data.getSum('value'); // Sum may be 0 var unitRadian = Math.PI / (sum || validDataCount) * 2; var clockwise = seriesModel.get('clockwise'); var roseType = seriesModel.get('roseType'); var stillShowZeroSum = seriesModel.get('stillShowZeroSum'); // [0...max] var extent = data.getDataExtent('value'); extent[0] = 0; // In the case some sector angle is smaller than minAngle var restAngle = PI2$4; var valueSumLargerThanMinAngle = 0; var currentAngle = startAngle; var dir = clockwise ? 1 : -1; data.each('value', function (value, idx) { var angle; if (isNaN(value)) { data.setItemLayout(idx, { angle: NaN, startAngle: NaN, endAngle: NaN, clockwise: clockwise, cx: cx, cy: cy, r0: r0, r: roseType ? NaN : r }); return; } // FIXME 兼容 2.0 但是 roseType 是 area 的时候才是这样? if (roseType !== 'area') { angle = (sum === 0 && stillShowZeroSum) ? unitRadian : (value * unitRadian); } else { angle = PI2$4 / validDataCount; } if (angle < minAngle) { angle = minAngle; restAngle -= minAngle; } else { valueSumLargerThanMinAngle += value; } var endAngle = currentAngle + dir * angle; data.setItemLayout(idx, { angle: angle, startAngle: currentAngle, endAngle: endAngle, clockwise: clockwise, cx: cx, cy: cy, r0: r0, r: roseType ? linearMap(value, extent, [r0, r]) : r }); currentAngle = endAngle; }, true); // Some sector is constrained by minAngle // Rest sectors needs recalculate angle if (restAngle < PI2$4 && validDataCount) { // Average the angle if rest angle is not enough after all angles is // Constrained by minAngle if (restAngle <= 1e-3) { var angle = PI2$4 / validDataCount; data.each('value', function (value, idx) { if (!isNaN(value)) { var layout = data.getItemLayout(idx); layout.angle = angle; layout.startAngle = startAngle + dir * idx * angle; layout.endAngle = startAngle + dir * (idx + 1) * angle; } }); } else { unitRadian = restAngle / valueSumLargerThanMinAngle; currentAngle = startAngle; data.each('value', function (value, idx) { if (!isNaN(value)) { var layout = data.getItemLayout(idx); var angle = layout.angle === minAngle ? minAngle : value * unitRadian; layout.startAngle = currentAngle; layout.endAngle = currentAngle + dir * angle; currentAngle += dir * angle; } }); } } labelLayout(seriesModel, r, width, height); }); }; var dataFilter = function (seriesType, ecModel) { var legendModels = ecModel.findComponents({ mainType: 'legend' }); if (!legendModels || !legendModels.length) { return; } ecModel.eachSeriesByType(seriesType, function (series) { var data = series.getData(); data.filterSelf(function (idx) { var name = data.getName(idx); // If in any legend component the status is not selected. for (var i = 0; i < legendModels.length; i++) { if (!legendModels[i].isSelected(name)) { return false; } } return true; }, this); }, this); }; createDataSelectAction('pie', [{ type: 'pieToggleSelect', event: 'pieselectchanged', method: 'toggleSelected' }, { type: 'pieSelect', event: 'pieselected', method: 'select' }, { type: 'pieUnSelect', event: 'pieunselected', method: 'unSelect' }]); registerVisual(curry(dataColor, 'pie')); registerLayout(curry(pieLayout, 'pie')); registerProcessor(curry(dataFilter, 'pie')); exports.version = version; exports.dependencies = dependencies; exports.PRIORITY = PRIORITY; exports.init = init; exports.connect = connect; exports.disConnect = disConnect; exports.disconnect = disconnect; exports.dispose = dispose; exports.getInstanceByDom = getInstanceByDom; exports.getInstanceById = getInstanceById; exports.registerTheme = registerTheme; exports.registerPreprocessor = registerPreprocessor; exports.registerProcessor = registerProcessor; exports.registerPostUpdate = registerPostUpdate; exports.registerAction = registerAction; exports.registerCoordinateSystem = registerCoordinateSystem; exports.getCoordinateSystemDimensions = getCoordinateSystemDimensions; exports.registerLayout = registerLayout; exports.registerVisual = registerVisual; exports.registerLoading = registerLoading; exports.extendComponentModel = extendComponentModel; exports.extendComponentView = extendComponentView; exports.extendSeriesModel = extendSeriesModel; exports.extendChartView = extendChartView; exports.setCanvasCreator = setCanvasCreator; exports.$inject = $inject; })));
/** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory() : typeof define === 'function' && define.amd ? define(factory) : (factory()); }(this, (function () { 'use strict'; /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var Zone$1 = (function (global) { var FUNCTION = 'function'; var performance = global['performance']; function mark(name) { performance && performance['mark'] && performance['mark'](name); } function performanceMeasure(name, label) { performance && performance['measure'] && performance['measure'](name, label); } mark('Zone'); if (global['Zone']) { throw new Error('Zone already loaded.'); } var Zone = /** @class */ (function () { function Zone(parent, zoneSpec) { this._properties = null; this._parent = parent; this._name = zoneSpec ? zoneSpec.name || 'unnamed' : '<root>'; this._properties = zoneSpec && zoneSpec.properties || {}; this._zoneDelegate = new ZoneDelegate(this, this._parent && this._parent._zoneDelegate, zoneSpec); } Zone.assertZonePatched = function () { if (global['Promise'] !== patches['ZoneAwarePromise']) { throw new Error('Zone.js has detected that ZoneAwarePromise `(window|global).Promise` ' + 'has been overwritten.\n' + 'Most likely cause is that a Promise polyfill has been loaded ' + 'after Zone.js (Polyfilling Promise api is not necessary when zone.js is loaded. ' + 'If you must load one, do so before loading zone.js.)'); } }; Object.defineProperty(Zone, "root", { get: function () { var zone = Zone.current; while (zone.parent) { zone = zone.parent; } return zone; }, enumerable: true, configurable: true }); Object.defineProperty(Zone, "current", { get: function () { return _currentZoneFrame.zone; }, enumerable: true, configurable: true }); Object.defineProperty(Zone, "currentTask", { get: function () { return _currentTask; }, enumerable: true, configurable: true }); Zone.__load_patch = function (name, fn) { if (patches.hasOwnProperty(name)) { throw Error('Already loaded patch: ' + name); } else if (!global['__Zone_disable_' + name]) { var perfName = 'Zone:' + name; mark(perfName); patches[name] = fn(global, Zone, _api); performanceMeasure(perfName, perfName); } }; Object.defineProperty(Zone.prototype, "parent", { get: function () { return this._parent; }, enumerable: true, configurable: true }); Object.defineProperty(Zone.prototype, "name", { get: function () { return this._name; }, enumerable: true, configurable: true }); Zone.prototype.get = function (key) { var zone = this.getZoneWith(key); if (zone) return zone._properties[key]; }; Zone.prototype.getZoneWith = function (key) { var current = this; while (current) { if (current._properties.hasOwnProperty(key)) { return current; } current = current._parent; } return null; }; Zone.prototype.fork = function (zoneSpec) { if (!zoneSpec) throw new Error('ZoneSpec required!'); return this._zoneDelegate.fork(this, zoneSpec); }; Zone.prototype.wrap = function (callback, source) { if (typeof callback !== FUNCTION) { throw new Error('Expecting function got: ' + callback); } var _callback = this._zoneDelegate.intercept(this, callback, source); var zone = this; return function () { return zone.runGuarded(_callback, this, arguments, source); }; }; Zone.prototype.run = function (callback, applyThis, applyArgs, source) { if (applyThis === void 0) { applyThis = undefined; } if (applyArgs === void 0) { applyArgs = null; } if (source === void 0) { source = null; } _currentZoneFrame = { parent: _currentZoneFrame, zone: this }; try { return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source); } finally { _currentZoneFrame = _currentZoneFrame.parent; } }; Zone.prototype.runGuarded = function (callback, applyThis, applyArgs, source) { if (applyThis === void 0) { applyThis = null; } if (applyArgs === void 0) { applyArgs = null; } if (source === void 0) { source = null; } _currentZoneFrame = { parent: _currentZoneFrame, zone: this }; try { try { return this._zoneDelegate.invoke(this, callback, applyThis, applyArgs, source); } catch (error) { if (this._zoneDelegate.handleError(this, error)) { throw error; } } } finally { _currentZoneFrame = _currentZoneFrame.parent; } }; Zone.prototype.runTask = function (task, applyThis, applyArgs) { if (task.zone != this) { throw new Error('A task can only be run in the zone of creation! (Creation: ' + (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')'); } // https://github.com/angular/zone.js/issues/778, sometimes eventTask // will run in notScheduled(canceled) state, we should not try to // run such kind of task but just return // we have to define an variable here, if not // typescript compiler will complain below var isNotScheduled = task.state === notScheduled; if (isNotScheduled && task.type === eventTask) { return; } var reEntryGuard = task.state != running; reEntryGuard && task._transitionTo(running, scheduled); task.runCount++; var previousTask = _currentTask; _currentTask = task; _currentZoneFrame = { parent: _currentZoneFrame, zone: this }; try { if (task.type == macroTask && task.data && !task.data.isPeriodic) { task.cancelFn = null; } try { return this._zoneDelegate.invokeTask(this, task, applyThis, applyArgs); } catch (error) { if (this._zoneDelegate.handleError(this, error)) { throw error; } } } finally { // if the task's state is notScheduled or unknown, then it has already been cancelled // we should not reset the state to scheduled if (task.state !== notScheduled && task.state !== unknown) { if (task.type == eventTask || (task.data && task.data.isPeriodic)) { reEntryGuard && task._transitionTo(scheduled, running); } else { task.runCount = 0; this._updateTaskCount(task, -1); reEntryGuard && task._transitionTo(notScheduled, running, notScheduled); } } _currentZoneFrame = _currentZoneFrame.parent; _currentTask = previousTask; } }; Zone.prototype.scheduleTask = function (task) { if (task.zone && task.zone !== this) { // check if the task was rescheduled, the newZone // should not be the children of the original zone var newZone = this; while (newZone) { if (newZone === task.zone) { throw Error("can not reschedule task to " + this .name + " which is descendants of the original zone " + task.zone.name); } newZone = newZone.parent; } } task._transitionTo(scheduling, notScheduled); var zoneDelegates = []; task._zoneDelegates = zoneDelegates; task._zone = this; try { task = this._zoneDelegate.scheduleTask(this, task); } catch (err) { // should set task's state to unknown when scheduleTask throw error // because the err may from reschedule, so the fromState maybe notScheduled task._transitionTo(unknown, scheduling, notScheduled); // TODO: @JiaLiPassion, should we check the result from handleError? this._zoneDelegate.handleError(this, err); throw err; } if (task._zoneDelegates === zoneDelegates) { // we have to check because internally the delegate can reschedule the task. this._updateTaskCount(task, 1); } if (task.state == scheduling) { task._transitionTo(scheduled, scheduling); } return task; }; Zone.prototype.scheduleMicroTask = function (source, callback, data, customSchedule) { return this.scheduleTask(new ZoneTask(microTask, source, callback, data, customSchedule, null)); }; Zone.prototype.scheduleMacroTask = function (source, callback, data, customSchedule, customCancel) { return this.scheduleTask(new ZoneTask(macroTask, source, callback, data, customSchedule, customCancel)); }; Zone.prototype.scheduleEventTask = function (source, callback, data, customSchedule, customCancel) { return this.scheduleTask(new ZoneTask(eventTask, source, callback, data, customSchedule, customCancel)); }; Zone.prototype.cancelTask = function (task) { if (task.zone != this) throw new Error('A task can only be cancelled in the zone of creation! (Creation: ' + (task.zone || NO_ZONE).name + '; Execution: ' + this.name + ')'); task._transitionTo(canceling, scheduled, running); try { this._zoneDelegate.cancelTask(this, task); } catch (err) { // if error occurs when cancelTask, transit the state to unknown task._transitionTo(unknown, canceling); this._zoneDelegate.handleError(this, err); throw err; } this._updateTaskCount(task, -1); task._transitionTo(notScheduled, canceling); task.runCount = 0; return task; }; Zone.prototype._updateTaskCount = function (task, count) { var zoneDelegates = task._zoneDelegates; if (count == -1) { task._zoneDelegates = null; } for (var i = 0; i < zoneDelegates.length; i++) { zoneDelegates[i]._updateTaskCount(task.type, count); } }; Zone.__symbol__ = __symbol__; return Zone; }()); var DELEGATE_ZS = { name: '', onHasTask: function (delegate, _, target, hasTaskState) { return delegate.hasTask(target, hasTaskState); }, onScheduleTask: function (delegate, _, target, task) { return delegate.scheduleTask(target, task); }, onInvokeTask: function (delegate, _, target, task, applyThis, applyArgs) { return delegate.invokeTask(target, task, applyThis, applyArgs); }, onCancelTask: function (delegate, _, target, task) { return delegate.cancelTask(target, task); } }; var ZoneDelegate = /** @class */ (function () { function ZoneDelegate(zone, parentDelegate, zoneSpec) { this._taskCounts = { 'microTask': 0, 'macroTask': 0, 'eventTask': 0 }; this.zone = zone; this._parentDelegate = parentDelegate; this._forkZS = zoneSpec && (zoneSpec && zoneSpec.onFork ? zoneSpec : parentDelegate._forkZS); this._forkDlgt = zoneSpec && (zoneSpec.onFork ? parentDelegate : parentDelegate._forkDlgt); this._forkCurrZone = zoneSpec && (zoneSpec.onFork ? this.zone : parentDelegate.zone); this._interceptZS = zoneSpec && (zoneSpec.onIntercept ? zoneSpec : parentDelegate._interceptZS); this._interceptDlgt = zoneSpec && (zoneSpec.onIntercept ? parentDelegate : parentDelegate._interceptDlgt); this._interceptCurrZone = zoneSpec && (zoneSpec.onIntercept ? this.zone : parentDelegate.zone); this._invokeZS = zoneSpec && (zoneSpec.onInvoke ? zoneSpec : parentDelegate._invokeZS); this._invokeDlgt = zoneSpec && (zoneSpec.onInvoke ? parentDelegate : parentDelegate._invokeDlgt); this._invokeCurrZone = zoneSpec && (zoneSpec.onInvoke ? this.zone : parentDelegate.zone); this._handleErrorZS = zoneSpec && (zoneSpec.onHandleError ? zoneSpec : parentDelegate._handleErrorZS); this._handleErrorDlgt = zoneSpec && (zoneSpec.onHandleError ? parentDelegate : parentDelegate._handleErrorDlgt); this._handleErrorCurrZone = zoneSpec && (zoneSpec.onHandleError ? this.zone : parentDelegate.zone); this._scheduleTaskZS = zoneSpec && (zoneSpec.onScheduleTask ? zoneSpec : parentDelegate._scheduleTaskZS); this._scheduleTaskDlgt = zoneSpec && (zoneSpec.onScheduleTask ? parentDelegate : parentDelegate._scheduleTaskDlgt); this._scheduleTaskCurrZone = zoneSpec && (zoneSpec.onScheduleTask ? this.zone : parentDelegate.zone); this._invokeTaskZS = zoneSpec && (zoneSpec.onInvokeTask ? zoneSpec : parentDelegate._invokeTaskZS); this._invokeTaskDlgt = zoneSpec && (zoneSpec.onInvokeTask ? parentDelegate : parentDelegate._invokeTaskDlgt); this._invokeTaskCurrZone = zoneSpec && (zoneSpec.onInvokeTask ? this.zone : parentDelegate.zone); this._cancelTaskZS = zoneSpec && (zoneSpec.onCancelTask ? zoneSpec : parentDelegate._cancelTaskZS); this._cancelTaskDlgt = zoneSpec && (zoneSpec.onCancelTask ? parentDelegate : parentDelegate._cancelTaskDlgt); this._cancelTaskCurrZone = zoneSpec && (zoneSpec.onCancelTask ? this.zone : parentDelegate.zone); this._hasTaskZS = null; this._hasTaskDlgt = null; this._hasTaskDlgtOwner = null; this._hasTaskCurrZone = null; var zoneSpecHasTask = zoneSpec && zoneSpec.onHasTask; var parentHasTask = parentDelegate && parentDelegate._hasTaskZS; if (zoneSpecHasTask || parentHasTask) { // If we need to report hasTask, than this ZS needs to do ref counting on tasks. In such // a case all task related interceptors must go through this ZD. We can't short circuit it. this._hasTaskZS = zoneSpecHasTask ? zoneSpec : DELEGATE_ZS; this._hasTaskDlgt = parentDelegate; this._hasTaskDlgtOwner = this; this._hasTaskCurrZone = zone; if (!zoneSpec.onScheduleTask) { this._scheduleTaskZS = DELEGATE_ZS; this._scheduleTaskDlgt = parentDelegate; this._scheduleTaskCurrZone = this.zone; } if (!zoneSpec.onInvokeTask) { this._invokeTaskZS = DELEGATE_ZS; this._invokeTaskDlgt = parentDelegate; this._invokeTaskCurrZone = this.zone; } if (!zoneSpec.onCancelTask) { this._cancelTaskZS = DELEGATE_ZS; this._cancelTaskDlgt = parentDelegate; this._cancelTaskCurrZone = this.zone; } } } ZoneDelegate.prototype.fork = function (targetZone, zoneSpec) { return this._forkZS ? this._forkZS.onFork(this._forkDlgt, this.zone, targetZone, zoneSpec) : new Zone(targetZone, zoneSpec); }; ZoneDelegate.prototype.intercept = function (targetZone, callback, source) { return this._interceptZS ? this._interceptZS.onIntercept(this._interceptDlgt, this._interceptCurrZone, targetZone, callback, source) : callback; }; ZoneDelegate.prototype.invoke = function (targetZone, callback, applyThis, applyArgs, source) { return this._invokeZS ? this._invokeZS.onInvoke(this._invokeDlgt, this._invokeCurrZone, targetZone, callback, applyThis, applyArgs, source) : callback.apply(applyThis, applyArgs); }; ZoneDelegate.prototype.handleError = function (targetZone, error) { return this._handleErrorZS ? this._handleErrorZS.onHandleError(this._handleErrorDlgt, this._handleErrorCurrZone, targetZone, error) : true; }; ZoneDelegate.prototype.scheduleTask = function (targetZone, task) { var returnTask = task; if (this._scheduleTaskZS) { if (this._hasTaskZS) { returnTask._zoneDelegates.push(this._hasTaskDlgtOwner); } returnTask = this._scheduleTaskZS.onScheduleTask(this._scheduleTaskDlgt, this._scheduleTaskCurrZone, targetZone, task); if (!returnTask) returnTask = task; } else { if (task.scheduleFn) { task.scheduleFn(task); } else if (task.type == microTask) { scheduleMicroTask(task); } else { throw new Error('Task is missing scheduleFn.'); } } return returnTask; }; ZoneDelegate.prototype.invokeTask = function (targetZone, task, applyThis, applyArgs) { return this._invokeTaskZS ? this._invokeTaskZS.onInvokeTask(this._invokeTaskDlgt, this._invokeTaskCurrZone, targetZone, task, applyThis, applyArgs) : task.callback.apply(applyThis, applyArgs); }; ZoneDelegate.prototype.cancelTask = function (targetZone, task) { var value; if (this._cancelTaskZS) { value = this._cancelTaskZS.onCancelTask(this._cancelTaskDlgt, this._cancelTaskCurrZone, targetZone, task); } else { if (!task.cancelFn) { throw Error('Task is not cancelable'); } value = task.cancelFn(task); } return value; }; ZoneDelegate.prototype.hasTask = function (targetZone, isEmpty) { // hasTask should not throw error so other ZoneDelegate // can still trigger hasTask callback try { return this._hasTaskZS && this._hasTaskZS.onHasTask(this._hasTaskDlgt, this._hasTaskCurrZone, targetZone, isEmpty); } catch (err) { this.handleError(targetZone, err); } }; ZoneDelegate.prototype._updateTaskCount = function (type, count) { var counts = this._taskCounts; var prev = counts[type]; var next = counts[type] = prev + count; if (next < 0) { throw new Error('More tasks executed then were scheduled.'); } if (prev == 0 || next == 0) { var isEmpty = { microTask: counts['microTask'] > 0, macroTask: counts['macroTask'] > 0, eventTask: counts['eventTask'] > 0, change: type }; this.hasTask(this.zone, isEmpty); } }; return ZoneDelegate; }()); var ZoneTask = /** @class */ (function () { function ZoneTask(type, source, callback, options, scheduleFn, cancelFn) { this._zone = null; this.runCount = 0; this._zoneDelegates = null; this._state = 'notScheduled'; this.type = type; this.source = source; this.data = options; this.scheduleFn = scheduleFn; this.cancelFn = cancelFn; this.callback = callback; var self = this; // TODO: @JiaLiPassion options should have interface if (type === eventTask && options && options.useG) { this.invoke = ZoneTask.invokeTask; } else { this.invoke = function () { return ZoneTask.invokeTask.call(global, self, this, arguments); }; } } ZoneTask.invokeTask = function (task, target, args) { if (!task) { task = this; } _numberOfNestedTaskFrames++; try { task.runCount++; return task.zone.runTask(task, target, args); } finally { if (_numberOfNestedTaskFrames == 1) { drainMicroTaskQueue(); } _numberOfNestedTaskFrames--; } }; Object.defineProperty(ZoneTask.prototype, "zone", { get: function () { return this._zone; }, enumerable: true, configurable: true }); Object.defineProperty(ZoneTask.prototype, "state", { get: function () { return this._state; }, enumerable: true, configurable: true }); ZoneTask.prototype.cancelScheduleRequest = function () { this._transitionTo(notScheduled, scheduling); }; ZoneTask.prototype._transitionTo = function (toState, fromState1, fromState2) { if (this._state === fromState1 || this._state === fromState2) { this._state = toState; if (toState == notScheduled) { this._zoneDelegates = null; } } else { throw new Error(this.type + " '" + this.source + "': can not transition to '" + toState + "', expecting state '" + fromState1 + "'" + (fromState2 ? ' or \'' + fromState2 + '\'' : '') + ", was '" + this._state + "'."); } }; ZoneTask.prototype.toString = function () { if (this.data && typeof this.data.handleId !== 'undefined') { return this.data.handleId; } else { return Object.prototype.toString.call(this); } }; // add toJSON method to prevent cyclic error when // call JSON.stringify(zoneTask) ZoneTask.prototype.toJSON = function () { return { type: this.type, state: this.state, source: this.source, zone: this.zone.name, runCount: this.runCount }; }; return ZoneTask; }()); ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// /// MICROTASK QUEUE ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// var symbolSetTimeout = __symbol__('setTimeout'); var symbolPromise = __symbol__('Promise'); var symbolThen = __symbol__('then'); var _microTaskQueue = []; var _isDrainingMicrotaskQueue = false; var nativeMicroTaskQueuePromise; function scheduleMicroTask(task) { // if we are not running in any task, and there has not been anything scheduled // we must bootstrap the initial task creation by manually scheduling the drain if (_numberOfNestedTaskFrames === 0 && _microTaskQueue.length === 0) { // We are not running in Task, so we need to kickstart the microtask queue. if (!nativeMicroTaskQueuePromise) { if (global[symbolPromise]) { nativeMicroTaskQueuePromise = global[symbolPromise].resolve(0); } } if (nativeMicroTaskQueuePromise) { nativeMicroTaskQueuePromise[symbolThen](drainMicroTaskQueue); } else { global[symbolSetTimeout](drainMicroTaskQueue, 0); } } task && _microTaskQueue.push(task); } function drainMicroTaskQueue() { if (!_isDrainingMicrotaskQueue) { _isDrainingMicrotaskQueue = true; while (_microTaskQueue.length) { var queue = _microTaskQueue; _microTaskQueue = []; for (var i = 0; i < queue.length; i++) { var task = queue[i]; try { task.zone.runTask(task, null, null); } catch (error) { _api.onUnhandledError(error); } } } _api.microtaskDrainDone(); _isDrainingMicrotaskQueue = false; } } ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// /// BOOTSTRAP ////////////////////////////////////////////////////// ////////////////////////////////////////////////////// var NO_ZONE = { name: 'NO ZONE' }; var notScheduled = 'notScheduled', scheduling = 'scheduling', scheduled = 'scheduled', running = 'running', canceling = 'canceling', unknown = 'unknown'; var microTask = 'microTask', macroTask = 'macroTask', eventTask = 'eventTask'; var patches = {}; var _api = { symbol: __symbol__, currentZoneFrame: function () { return _currentZoneFrame; }, onUnhandledError: noop, microtaskDrainDone: noop, scheduleMicroTask: scheduleMicroTask, showUncaughtError: function () { return !Zone[__symbol__('ignoreConsoleErrorUncaughtError')]; }, patchEventTarget: function () { return []; }, patchOnProperties: noop, patchMethod: function () { return noop; }, bindArguments: function () { return null; }, setNativePromise: function (NativePromise) { // sometimes NativePromise.resolve static function // is not ready yet, (such as core-js/es6.promise) // so we need to check here. if (NativePromise && typeof NativePromise.resolve === FUNCTION) { nativeMicroTaskQueuePromise = NativePromise.resolve(0); } }, }; var _currentZoneFrame = { parent: null, zone: new Zone(null, null) }; var _currentTask = null; var _numberOfNestedTaskFrames = 0; function noop() { } function __symbol__(name) { return '__zone_symbol__' + name; } performanceMeasure('Zone', 'Zone'); return global['Zone'] = Zone; })(typeof window !== 'undefined' && window || typeof self !== 'undefined' && self || global); var __values = (undefined && undefined.__values) || function (o) { var m = typeof Symbol === "function" && o[Symbol.iterator], i = 0; if (m) return m.call(o); return { next: function () { if (o && i >= o.length) o = void 0; return { value: o && o[i++], done: !o }; } }; }; Zone.__load_patch('ZoneAwarePromise', function (global, Zone, api) { var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; var ObjectDefineProperty = Object.defineProperty; function readableObjectToString(obj) { if (obj && obj.toString === Object.prototype.toString) { var className = obj.constructor && obj.constructor.name; return (className ? className : '') + ': ' + JSON.stringify(obj); } return obj ? obj.toString() : Object.prototype.toString.call(obj); } var __symbol__ = api.symbol; var _uncaughtPromiseErrors = []; var symbolPromise = __symbol__('Promise'); var symbolThen = __symbol__('then'); var creationTrace = '__creationTrace__'; api.onUnhandledError = function (e) { if (api.showUncaughtError()) { var rejection = e && e.rejection; if (rejection) { console.error('Unhandled Promise rejection:', rejection instanceof Error ? rejection.message : rejection, '; Zone:', e.zone.name, '; Task:', e.task && e.task.source, '; Value:', rejection, rejection instanceof Error ? rejection.stack : undefined); } else { console.error(e); } } }; api.microtaskDrainDone = function () { while (_uncaughtPromiseErrors.length) { var _loop_1 = function () { var uncaughtPromiseError = _uncaughtPromiseErrors.shift(); try { uncaughtPromiseError.zone.runGuarded(function () { throw uncaughtPromiseError; }); } catch (error) { handleUnhandledRejection(error); } }; while (_uncaughtPromiseErrors.length) { _loop_1(); } } }; var UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL = __symbol__('unhandledPromiseRejectionHandler'); function handleUnhandledRejection(e) { api.onUnhandledError(e); try { var handler = Zone[UNHANDLED_PROMISE_REJECTION_HANDLER_SYMBOL]; if (handler && typeof handler === 'function') { handler.call(this, e); } } catch (err) { } } function isThenable(value) { return value && value.then; } function forwardResolution(value) { return value; } function forwardRejection(rejection) { return ZoneAwarePromise.reject(rejection); } var symbolState = __symbol__('state'); var symbolValue = __symbol__('value'); var symbolFinally = __symbol__('finally'); var symbolParentPromiseValue = __symbol__('parentPromiseValue'); var symbolParentPromiseState = __symbol__('parentPromiseState'); var source = 'Promise.then'; var UNRESOLVED = null; var RESOLVED = true; var REJECTED = false; var REJECTED_NO_CATCH = 0; function makeResolver(promise, state) { return function (v) { try { resolvePromise(promise, state, v); } catch (err) { resolvePromise(promise, false, err); } // Do not return value or you will break the Promise spec. }; } var once = function () { var wasCalled = false; return function wrapper(wrappedFunction) { return function () { if (wasCalled) { return; } wasCalled = true; wrappedFunction.apply(null, arguments); }; }; }; var TYPE_ERROR = 'Promise resolved with itself'; var CURRENT_TASK_TRACE_SYMBOL = __symbol__('currentTaskTrace'); // Promise Resolution function resolvePromise(promise, state, value) { var onceWrapper = once(); if (promise === value) { throw new TypeError(TYPE_ERROR); } if (promise[symbolState] === UNRESOLVED) { // should only get value.then once based on promise spec. var then = null; try { if (typeof value === 'object' || typeof value === 'function') { then = value && value.then; } } catch (err) { onceWrapper(function () { resolvePromise(promise, false, err); })(); return promise; } // if (value instanceof ZoneAwarePromise) { if (state !== REJECTED && value instanceof ZoneAwarePromise && value.hasOwnProperty(symbolState) && value.hasOwnProperty(symbolValue) && value[symbolState] !== UNRESOLVED) { clearRejectedNoCatch(value); resolvePromise(promise, value[symbolState], value[symbolValue]); } else if (state !== REJECTED && typeof then === 'function') { try { then.call(value, onceWrapper(makeResolver(promise, state)), onceWrapper(makeResolver(promise, false))); } catch (err) { onceWrapper(function () { resolvePromise(promise, false, err); })(); } } else { promise[symbolState] = state; var queue = promise[symbolValue]; promise[symbolValue] = value; if (promise[symbolFinally] === symbolFinally) { // the promise is generated by Promise.prototype.finally if (state === RESOLVED) { // the state is resolved, should ignore the value // and use parent promise value promise[symbolState] = promise[symbolParentPromiseState]; promise[symbolValue] = promise[symbolParentPromiseValue]; } } // record task information in value when error occurs, so we can // do some additional work such as render longStackTrace if (state === REJECTED && value instanceof Error) { // check if longStackTraceZone is here var trace = Zone.currentTask && Zone.currentTask.data && Zone.currentTask.data[creationTrace]; if (trace) { // only keep the long stack trace into error when in longStackTraceZone ObjectDefineProperty(value, CURRENT_TASK_TRACE_SYMBOL, { configurable: true, enumerable: false, writable: true, value: trace }); } } for (var i = 0; i < queue.length;) { scheduleResolveOrReject(promise, queue[i++], queue[i++], queue[i++], queue[i++]); } if (queue.length == 0 && state == REJECTED) { promise[symbolState] = REJECTED_NO_CATCH; try { // try to print more readable error log throw new Error('Uncaught (in promise): ' + readableObjectToString(value) + (value && value.stack ? '\n' + value.stack : '')); } catch (err) { var error_1 = err; error_1.rejection = value; error_1.promise = promise; error_1.zone = Zone.current; error_1.task = Zone.currentTask; _uncaughtPromiseErrors.push(error_1); api.scheduleMicroTask(); // to make sure that it is running } } } } // Resolving an already resolved promise is a noop. return promise; } var REJECTION_HANDLED_HANDLER = __symbol__('rejectionHandledHandler'); function clearRejectedNoCatch(promise) { if (promise[symbolState] === REJECTED_NO_CATCH) { // if the promise is rejected no catch status // and queue.length > 0, means there is a error handler // here to handle the rejected promise, we should trigger // windows.rejectionhandled eventHandler or nodejs rejectionHandled // eventHandler try { var handler = Zone[REJECTION_HANDLED_HANDLER]; if (handler && typeof handler === 'function') { handler.call(this, { rejection: promise[symbolValue], promise: promise }); } } catch (err) { } promise[symbolState] = REJECTED; for (var i = 0; i < _uncaughtPromiseErrors.length; i++) { if (promise === _uncaughtPromiseErrors[i].promise) { _uncaughtPromiseErrors.splice(i, 1); } } } } function scheduleResolveOrReject(promise, zone, chainPromise, onFulfilled, onRejected) { clearRejectedNoCatch(promise); var promiseState = promise[symbolState]; var delegate = promiseState ? (typeof onFulfilled === 'function') ? onFulfilled : forwardResolution : (typeof onRejected === 'function') ? onRejected : forwardRejection; zone.scheduleMicroTask(source, function () { try { var parentPromiseValue = promise[symbolValue]; var isFinallyPromise = chainPromise && symbolFinally === chainPromise[symbolFinally]; if (isFinallyPromise) { // if the promise is generated from finally call, keep parent promise's state and value chainPromise[symbolParentPromiseValue] = parentPromiseValue; chainPromise[symbolParentPromiseState] = promiseState; } // should not pass value to finally callback var value = zone.run(delegate, undefined, isFinallyPromise && delegate !== forwardRejection && delegate !== forwardResolution ? [] : [parentPromiseValue]); resolvePromise(chainPromise, true, value); } catch (error) { // if error occurs, should always return this error resolvePromise(chainPromise, false, error); } }, chainPromise); } var ZONE_AWARE_PROMISE_TO_STRING = 'function ZoneAwarePromise() { [native code] }'; var ZoneAwarePromise = /** @class */ (function () { function ZoneAwarePromise(executor) { var promise = this; if (!(promise instanceof ZoneAwarePromise)) { throw new Error('Must be an instanceof Promise.'); } promise[symbolState] = UNRESOLVED; promise[symbolValue] = []; // queue; try { executor && executor(makeResolver(promise, RESOLVED), makeResolver(promise, REJECTED)); } catch (error) { resolvePromise(promise, false, error); } } ZoneAwarePromise.toString = function () { return ZONE_AWARE_PROMISE_TO_STRING; }; ZoneAwarePromise.resolve = function (value) { return resolvePromise(new this(null), RESOLVED, value); }; ZoneAwarePromise.reject = function (error) { return resolvePromise(new this(null), REJECTED, error); }; ZoneAwarePromise.race = function (values) { var resolve; var reject; var promise = new this(function (res, rej) { resolve = res; reject = rej; }); function onResolve(value) { promise && (promise = null || resolve(value)); } function onReject(error) { promise && (promise = null || reject(error)); } try { for (var values_1 = __values(values), values_1_1 = values_1.next(); !values_1_1.done; values_1_1 = values_1.next()) { var value = values_1_1.value; if (!isThenable(value)) { value = this.resolve(value); } value.then(onResolve, onReject); } } catch (e_1_1) { e_1 = { error: e_1_1 }; } finally { try { if (values_1_1 && !values_1_1.done && (_a = values_1.return)) _a.call(values_1); } finally { if (e_1) throw e_1.error; } } return promise; var e_1, _a; }; ZoneAwarePromise.all = function (values) { var resolve; var reject; var promise = new this(function (res, rej) { resolve = res; reject = rej; }); var count = 0; var resolvedValues = []; try { for (var values_2 = __values(values), values_2_1 = values_2.next(); !values_2_1.done; values_2_1 = values_2.next()) { var value = values_2_1.value; if (!isThenable(value)) { value = this.resolve(value); } value.then((function (index) { return function (value) { resolvedValues[index] = value; count--; if (!count) { resolve(resolvedValues); } }; })(count), reject); count++; } } catch (e_2_1) { e_2 = { error: e_2_1 }; } finally { try { if (values_2_1 && !values_2_1.done && (_a = values_2.return)) _a.call(values_2); } finally { if (e_2) throw e_2.error; } } if (!count) resolve(resolvedValues); return promise; var e_2, _a; }; ZoneAwarePromise.prototype.then = function (onFulfilled, onRejected) { var chainPromise = new this.constructor(null); var zone = Zone.current; if (this[symbolState] == UNRESOLVED) { this[symbolValue].push(zone, chainPromise, onFulfilled, onRejected); } else { scheduleResolveOrReject(this, zone, chainPromise, onFulfilled, onRejected); } return chainPromise; }; ZoneAwarePromise.prototype.catch = function (onRejected) { return this.then(null, onRejected); }; ZoneAwarePromise.prototype.finally = function (onFinally) { var chainPromise = new this.constructor(null); chainPromise[symbolFinally] = symbolFinally; var zone = Zone.current; if (this[symbolState] == UNRESOLVED) { this[symbolValue].push(zone, chainPromise, onFinally, onFinally); } else { scheduleResolveOrReject(this, zone, chainPromise, onFinally, onFinally); } return chainPromise; }; return ZoneAwarePromise; }()); // Protect against aggressive optimizers dropping seemingly unused properties. // E.g. Closure Compiler in advanced mode. ZoneAwarePromise['resolve'] = ZoneAwarePromise.resolve; ZoneAwarePromise['reject'] = ZoneAwarePromise.reject; ZoneAwarePromise['race'] = ZoneAwarePromise.race; ZoneAwarePromise['all'] = ZoneAwarePromise.all; var NativePromise = global[symbolPromise] = global['Promise']; var ZONE_AWARE_PROMISE = Zone.__symbol__('ZoneAwarePromise'); var desc = ObjectGetOwnPropertyDescriptor(global, 'Promise'); if (!desc || desc.configurable) { desc && delete desc.writable; desc && delete desc.value; if (!desc) { desc = { configurable: true, enumerable: true }; } desc.get = function () { // if we already set ZoneAwarePromise, use patched one // otherwise return native one. return global[ZONE_AWARE_PROMISE] ? global[ZONE_AWARE_PROMISE] : global[symbolPromise]; }; desc.set = function (NewNativePromise) { if (NewNativePromise === ZoneAwarePromise) { // if the NewNativePromise is ZoneAwarePromise // save to global global[ZONE_AWARE_PROMISE] = NewNativePromise; } else { // if the NewNativePromise is not ZoneAwarePromise // for example: after load zone.js, some library just // set es6-promise to global, if we set it to global // directly, assertZonePatched will fail and angular // will not loaded, so we just set the NewNativePromise // to global[symbolPromise], so the result is just like // we load ES6 Promise before zone.js global[symbolPromise] = NewNativePromise; if (!NewNativePromise.prototype[symbolThen]) { patchThen(NewNativePromise); } api.setNativePromise(NewNativePromise); } }; ObjectDefineProperty(global, 'Promise', desc); } global['Promise'] = ZoneAwarePromise; var symbolThenPatched = __symbol__('thenPatched'); function patchThen(Ctor) { var proto = Ctor.prototype; var prop = ObjectGetOwnPropertyDescriptor(proto, 'then'); if (prop && (prop.writable === false || !prop.configurable)) { // check Ctor.prototype.then propertyDescriptor is writable or not // in meteor env, writable is false, we should ignore such case return; } var originalThen = proto.then; // Keep a reference to the original method. proto[symbolThen] = originalThen; Ctor.prototype.then = function (onResolve, onReject) { var _this = this; var wrapped = new ZoneAwarePromise(function (resolve, reject) { originalThen.call(_this, resolve, reject); }); return wrapped.then(onResolve, onReject); }; Ctor[symbolThenPatched] = true; } function zoneify(fn) { return function () { var resultPromise = fn.apply(this, arguments); if (resultPromise instanceof ZoneAwarePromise) { return resultPromise; } var ctor = resultPromise.constructor; if (!ctor[symbolThenPatched]) { patchThen(ctor); } return resultPromise; }; } if (NativePromise) { patchThen(NativePromise); var fetch_1 = global['fetch']; if (typeof fetch_1 == 'function') { global['fetch'] = zoneify(fetch_1); } } // This is not part of public API, but it is useful for tests, so we expose it. Promise[Zone.__symbol__('uncaughtPromiseErrors')] = _uncaughtPromiseErrors; return ZoneAwarePromise; }); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * Suppress closure compiler errors about unknown 'Zone' variable * @fileoverview * @suppress {undefinedVars,globalThis,missingRequire} */ // issue #989, to reduce bundle size, use short name /** Object.getOwnPropertyDescriptor */ var ObjectGetOwnPropertyDescriptor = Object.getOwnPropertyDescriptor; /** Object.defineProperty */ var ObjectDefineProperty = Object.defineProperty; /** Object.getPrototypeOf */ var ObjectGetPrototypeOf = Object.getPrototypeOf; /** Object.create */ var ObjectCreate = Object.create; /** Array.prototype.slice */ var ArraySlice = Array.prototype.slice; /** addEventListener string const */ var ADD_EVENT_LISTENER_STR = 'addEventListener'; /** removeEventListener string const */ var REMOVE_EVENT_LISTENER_STR = 'removeEventListener'; /** zoneSymbol addEventListener */ var ZONE_SYMBOL_ADD_EVENT_LISTENER = Zone.__symbol__(ADD_EVENT_LISTENER_STR); /** zoneSymbol removeEventListener */ var ZONE_SYMBOL_REMOVE_EVENT_LISTENER = Zone.__symbol__(REMOVE_EVENT_LISTENER_STR); /** true string const */ var TRUE_STR = 'true'; /** false string const */ var FALSE_STR = 'false'; /** __zone_symbol__ string const */ var ZONE_SYMBOL_PREFIX = '__zone_symbol__'; function wrapWithCurrentZone(callback, source) { return Zone.current.wrap(callback, source); } function scheduleMacroTaskWithCurrentZone(source, callback, data, customSchedule, customCancel) { return Zone.current.scheduleMacroTask(source, callback, data, customSchedule, customCancel); } var zoneSymbol = Zone.__symbol__; var isWindowExists = typeof window !== 'undefined'; var internalWindow = isWindowExists ? window : undefined; var _global = isWindowExists && internalWindow || typeof self === 'object' && self || global; var REMOVE_ATTRIBUTE = 'removeAttribute'; var NULL_ON_PROP_VALUE = [null]; function bindArguments(args, source) { for (var i = args.length - 1; i >= 0; i--) { if (typeof args[i] === 'function') { args[i] = wrapWithCurrentZone(args[i], source + '_' + i); } } return args; } function patchPrototype(prototype, fnNames) { var source = prototype.constructor['name']; var _loop_1 = function (i) { var name_1 = fnNames[i]; var delegate = prototype[name_1]; if (delegate) { var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, name_1); if (!isPropertyWritable(prototypeDesc)) { return "continue"; } prototype[name_1] = (function (delegate) { var patched = function () { return delegate.apply(this, bindArguments(arguments, source + '.' + name_1)); }; attachOriginToPatched(patched, delegate); return patched; })(delegate); } }; for (var i = 0; i < fnNames.length; i++) { _loop_1(i); } } function isPropertyWritable(propertyDesc) { if (!propertyDesc) { return true; } if (propertyDesc.writable === false) { return false; } return !(typeof propertyDesc.get === 'function' && typeof propertyDesc.set === 'undefined'); } var isWebWorker = (typeof WorkerGlobalScope !== 'undefined' && self instanceof WorkerGlobalScope); // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify // this code. var isNode = (!('nw' in _global) && typeof _global.process !== 'undefined' && {}.toString.call(_global.process) === '[object process]'); var isBrowser = !isNode && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']); // we are in electron of nw, so we are both browser and nodejs // Make sure to access `process` through `_global` so that WebPack does not accidentally browserify // this code. var isMix = typeof _global.process !== 'undefined' && {}.toString.call(_global.process) === '[object process]' && !isWebWorker && !!(isWindowExists && internalWindow['HTMLElement']); var zoneSymbolEventNames = {}; var wrapFn = function (event) { // https://github.com/angular/zone.js/issues/911, in IE, sometimes // event will be undefined, so we need to use window.event event = event || _global.event; if (!event) { return; } var eventNameSymbol = zoneSymbolEventNames[event.type]; if (!eventNameSymbol) { eventNameSymbol = zoneSymbolEventNames[event.type] = zoneSymbol('ON_PROPERTY' + event.type); } var target = this || event.target || _global; var listener = target[eventNameSymbol]; var result = listener && listener.apply(this, arguments); if (result != undefined && !result) { event.preventDefault(); } return result; }; function patchProperty(obj, prop, prototype) { var desc = ObjectGetOwnPropertyDescriptor(obj, prop); if (!desc && prototype) { // when patch window object, use prototype to check prop exist or not var prototypeDesc = ObjectGetOwnPropertyDescriptor(prototype, prop); if (prototypeDesc) { desc = { enumerable: true, configurable: true }; } } // if the descriptor not exists or is not configurable // just return if (!desc || !desc.configurable) { return; } // A property descriptor cannot have getter/setter and be writable // deleting the writable and value properties avoids this error: // // TypeError: property descriptors must not specify a value or be writable when a // getter or setter has been specified delete desc.writable; delete desc.value; var originalDescGet = desc.get; var originalDescSet = desc.set; // substr(2) cuz 'onclick' -> 'click', etc var eventName = prop.substr(2); var eventNameSymbol = zoneSymbolEventNames[eventName]; if (!eventNameSymbol) { eventNameSymbol = zoneSymbolEventNames[eventName] = zoneSymbol('ON_PROPERTY' + eventName); } desc.set = function (newValue) { // in some of windows's onproperty callback, this is undefined // so we need to check it var target = this; if (!target && obj === _global) { target = _global; } if (!target) { return; } var previousValue = target[eventNameSymbol]; if (previousValue) { target.removeEventListener(eventName, wrapFn); } // issue #978, when onload handler was added before loading zone.js // we should remove it with originalDescSet if (originalDescSet) { originalDescSet.apply(target, NULL_ON_PROP_VALUE); } if (typeof newValue === 'function') { target[eventNameSymbol] = newValue; target.addEventListener(eventName, wrapFn, false); } else { target[eventNameSymbol] = null; } }; // The getter would return undefined for unassigned properties but the default value of an // unassigned property is null desc.get = function () { // in some of windows's onproperty callback, this is undefined // so we need to check it var target = this; if (!target && obj === _global) { target = _global; } if (!target) { return null; } var listener = target[eventNameSymbol]; if (listener) { return listener; } else if (originalDescGet) { // result will be null when use inline event attribute, // such as <button onclick="func();">OK</button> // because the onclick function is internal raw uncompiled handler // the onclick will be evaluated when first time event was triggered or // the property is accessed, https://github.com/angular/zone.js/issues/525 // so we should use original native get to retrieve the handler var value = originalDescGet && originalDescGet.call(this); if (value) { desc.set.call(this, value); if (typeof target[REMOVE_ATTRIBUTE] === 'function') { target.removeAttribute(prop); } return value; } } return null; }; ObjectDefineProperty(obj, prop, desc); } function patchOnProperties(obj, properties, prototype) { if (properties) { for (var i = 0; i < properties.length; i++) { patchProperty(obj, 'on' + properties[i], prototype); } } else { var onProperties = []; for (var prop in obj) { if (prop.substr(0, 2) == 'on') { onProperties.push(prop); } } for (var j = 0; j < onProperties.length; j++) { patchProperty(obj, onProperties[j], prototype); } } } var originalInstanceKey = zoneSymbol('originalInstance'); // wrap some native API on `window` function patchClass(className) { var OriginalClass = _global[className]; if (!OriginalClass) return; // keep original class in global _global[zoneSymbol(className)] = OriginalClass; _global[className] = function () { var a = bindArguments(arguments, className); switch (a.length) { case 0: this[originalInstanceKey] = new OriginalClass(); break; case 1: this[originalInstanceKey] = new OriginalClass(a[0]); break; case 2: this[originalInstanceKey] = new OriginalClass(a[0], a[1]); break; case 3: this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2]); break; case 4: this[originalInstanceKey] = new OriginalClass(a[0], a[1], a[2], a[3]); break; default: throw new Error('Arg list too long.'); } }; // attach original delegate to patched function attachOriginToPatched(_global[className], OriginalClass); var instance = new OriginalClass(function () { }); var prop; for (prop in instance) { // https://bugs.webkit.org/show_bug.cgi?id=44721 if (className === 'XMLHttpRequest' && prop === 'responseBlob') continue; (function (prop) { if (typeof instance[prop] === 'function') { _global[className].prototype[prop] = function () { return this[originalInstanceKey][prop].apply(this[originalInstanceKey], arguments); }; } else { ObjectDefineProperty(_global[className].prototype, prop, { set: function (fn) { if (typeof fn === 'function') { this[originalInstanceKey][prop] = wrapWithCurrentZone(fn, className + '.' + prop); // keep callback in wrapped function so we can // use it in Function.prototype.toString to return // the native one. attachOriginToPatched(this[originalInstanceKey][prop], fn); } else { this[originalInstanceKey][prop] = fn; } }, get: function () { return this[originalInstanceKey][prop]; } }); } }(prop)); } for (prop in OriginalClass) { if (prop !== 'prototype' && OriginalClass.hasOwnProperty(prop)) { _global[className][prop] = OriginalClass[prop]; } } } function patchMethod(target, name, patchFn) { var proto = target; while (proto && !proto.hasOwnProperty(name)) { proto = ObjectGetPrototypeOf(proto); } if (!proto && target[name]) { // somehow we did not find it, but we can see it. This happens on IE for Window properties. proto = target; } var delegateName = zoneSymbol(name); var delegate; if (proto && !(delegate = proto[delegateName])) { delegate = proto[delegateName] = proto[name]; // check whether proto[name] is writable // some property is readonly in safari, such as HtmlCanvasElement.prototype.toBlob var desc = proto && ObjectGetOwnPropertyDescriptor(proto, name); if (isPropertyWritable(desc)) { var patchDelegate_1 = patchFn(delegate, delegateName, name); proto[name] = function () { return patchDelegate_1(this, arguments); }; attachOriginToPatched(proto[name], delegate); } } return delegate; } // TODO: @JiaLiPassion, support cancel task later if necessary function patchMacroTask(obj, funcName, metaCreator) { var setNative = null; function scheduleTask(task) { var data = task.data; data.args[data.cbIdx] = function () { task.invoke.apply(this, arguments); }; setNative.apply(data.target, data.args); return task; } setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) { var meta = metaCreator(self, args); if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') { return scheduleMacroTaskWithCurrentZone(meta.name, args[meta.cbIdx], meta, scheduleTask, null); } else { // cause an error by calling it directly. return delegate.apply(self, args); } }; }); } function patchMicroTask(obj, funcName, metaCreator) { var setNative = null; function scheduleTask(task) { var data = task.data; data.args[data.cbIdx] = function () { task.invoke.apply(this, arguments); }; setNative.apply(data.target, data.args); return task; } setNative = patchMethod(obj, funcName, function (delegate) { return function (self, args) { var meta = metaCreator(self, args); if (meta.cbIdx >= 0 && typeof args[meta.cbIdx] === 'function') { return Zone.current.scheduleMicroTask(meta.name, args[meta.cbIdx], meta, scheduleTask); } else { // cause an error by calling it directly. return delegate.apply(self, args); } }; }); } function attachOriginToPatched(patched, original) { patched[zoneSymbol('OriginalDelegate')] = original; } var isDetectedIEOrEdge = false; var ieOrEdge = false; function isIEOrEdge() { if (isDetectedIEOrEdge) { return ieOrEdge; } isDetectedIEOrEdge = true; try { var ua = internalWindow.navigator.userAgent; if (ua.indexOf('MSIE ') !== -1 || ua.indexOf('Trident/') !== -1 || ua.indexOf('Edge/') !== -1) { ieOrEdge = true; } return ieOrEdge; } catch (error) { } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // override Function.prototype.toString to make zone.js patched function // look like native function Zone.__load_patch('toString', function (global) { // patch Func.prototype.toString to let them look like native var originalFunctionToString = Function.prototype.toString; var ORIGINAL_DELEGATE_SYMBOL = zoneSymbol('OriginalDelegate'); var PROMISE_SYMBOL = zoneSymbol('Promise'); var ERROR_SYMBOL = zoneSymbol('Error'); var newFunctionToString = function toString() { if (typeof this === 'function') { var originalDelegate = this[ORIGINAL_DELEGATE_SYMBOL]; if (originalDelegate) { if (typeof originalDelegate === 'function') { return originalFunctionToString.apply(this[ORIGINAL_DELEGATE_SYMBOL], arguments); } else { return Object.prototype.toString.call(originalDelegate); } } if (this === Promise) { var nativePromise = global[PROMISE_SYMBOL]; if (nativePromise) { return originalFunctionToString.apply(nativePromise, arguments); } } if (this === Error) { var nativeError = global[ERROR_SYMBOL]; if (nativeError) { return originalFunctionToString.apply(nativeError, arguments); } } } return originalFunctionToString.apply(this, arguments); }; newFunctionToString[ORIGINAL_DELEGATE_SYMBOL] = originalFunctionToString; Function.prototype.toString = newFunctionToString; // patch Object.prototype.toString to let them look like native var originalObjectToString = Object.prototype.toString; var PROMISE_OBJECT_TO_STRING = '[object Promise]'; Object.prototype.toString = function () { if (this instanceof Promise) { return PROMISE_OBJECT_TO_STRING; } return originalObjectToString.apply(this, arguments); }; }); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @fileoverview * @suppress {missingRequire} */ // an identifier to tell ZoneTask do not create a new invoke closure var OPTIMIZED_ZONE_EVENT_TASK_DATA = { useG: true }; var zoneSymbolEventNames$1 = {}; var globalSources = {}; var EVENT_NAME_SYMBOL_REGX = /^__zone_symbol__(\w+)(true|false)$/; var IMMEDIATE_PROPAGATION_SYMBOL = ('__zone_symbol__propagationStopped'); function patchEventTarget(_global, apis, patchOptions) { var ADD_EVENT_LISTENER = (patchOptions && patchOptions.add) || ADD_EVENT_LISTENER_STR; var REMOVE_EVENT_LISTENER = (patchOptions && patchOptions.rm) || REMOVE_EVENT_LISTENER_STR; var LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.listeners) || 'eventListeners'; var REMOVE_ALL_LISTENERS_EVENT_LISTENER = (patchOptions && patchOptions.rmAll) || 'removeAllListeners'; var zoneSymbolAddEventListener = zoneSymbol(ADD_EVENT_LISTENER); var ADD_EVENT_LISTENER_SOURCE = '.' + ADD_EVENT_LISTENER + ':'; var PREPEND_EVENT_LISTENER = 'prependListener'; var PREPEND_EVENT_LISTENER_SOURCE = '.' + PREPEND_EVENT_LISTENER + ':'; var invokeTask = function (task, target, event) { // for better performance, check isRemoved which is set // by removeEventListener if (task.isRemoved) { return; } var delegate = task.callback; if (typeof delegate === 'object' && delegate.handleEvent) { // create the bind version of handleEvent when invoke task.callback = function (event) { return delegate.handleEvent(event); }; task.originalDelegate = delegate; } // invoke static task.invoke task.invoke(task, target, [event]); var options = task.options; if (options && typeof options === 'object' && options.once) { // if options.once is true, after invoke once remove listener here // only browser need to do this, nodejs eventEmitter will cal removeListener // inside EventEmitter.once var delegate_1 = task.originalDelegate ? task.originalDelegate : task.callback; target[REMOVE_EVENT_LISTENER].call(target, event.type, delegate_1, options); } }; // global shared zoneAwareCallback to handle all event callback with capture = false var globalZoneAwareCallback = function (event) { // https://github.com/angular/zone.js/issues/911, in IE, sometimes // event will be undefined, so we need to use window.event event = event || _global.event; if (!event) { return; } // event.target is needed for Samsung TV and SourceBuffer // || global is needed https://github.com/angular/zone.js/issues/190 var target = this || event.target || _global; var tasks = target[zoneSymbolEventNames$1[event.type][FALSE_STR]]; if (tasks) { // invoke all tasks which attached to current target with given event.type and capture = false // for performance concern, if task.length === 1, just invoke if (tasks.length === 1) { invokeTask(tasks[0], target, event); } else { // https://github.com/angular/zone.js/issues/836 // copy the tasks array before invoke, to avoid // the callback will remove itself or other listener var copyTasks = tasks.slice(); for (var i = 0; i < copyTasks.length; i++) { if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) { break; } invokeTask(copyTasks[i], target, event); } } } }; // global shared zoneAwareCallback to handle all event callback with capture = true var globalZoneAwareCaptureCallback = function (event) { // https://github.com/angular/zone.js/issues/911, in IE, sometimes // event will be undefined, so we need to use window.event event = event || _global.event; if (!event) { return; } // event.target is needed for Samsung TV and SourceBuffer // || global is needed https://github.com/angular/zone.js/issues/190 var target = this || event.target || _global; var tasks = target[zoneSymbolEventNames$1[event.type][TRUE_STR]]; if (tasks) { // invoke all tasks which attached to current target with given event.type and capture = false // for performance concern, if task.length === 1, just invoke if (tasks.length === 1) { invokeTask(tasks[0], target, event); } else { // https://github.com/angular/zone.js/issues/836 // copy the tasks array before invoke, to avoid // the callback will remove itself or other listener var copyTasks = tasks.slice(); for (var i = 0; i < copyTasks.length; i++) { if (event && event[IMMEDIATE_PROPAGATION_SYMBOL] === true) { break; } invokeTask(copyTasks[i], target, event); } } } }; function patchEventTargetMethods(obj, patchOptions) { if (!obj) { return false; } var useGlobalCallback = true; if (patchOptions && patchOptions.useG !== undefined) { useGlobalCallback = patchOptions.useG; } var validateHandler = patchOptions && patchOptions.vh; var checkDuplicate = true; if (patchOptions && patchOptions.chkDup !== undefined) { checkDuplicate = patchOptions.chkDup; } var returnTarget = false; if (patchOptions && patchOptions.rt !== undefined) { returnTarget = patchOptions.rt; } var proto = obj; while (proto && !proto.hasOwnProperty(ADD_EVENT_LISTENER)) { proto = ObjectGetPrototypeOf(proto); } if (!proto && obj[ADD_EVENT_LISTENER]) { // somehow we did not find it, but we can see it. This happens on IE for Window properties. proto = obj; } if (!proto) { return false; } if (proto[zoneSymbolAddEventListener]) { return false; } // a shared global taskData to pass data for scheduleEventTask // so we do not need to create a new object just for pass some data var taskData = {}; var nativeAddEventListener = proto[zoneSymbolAddEventListener] = proto[ADD_EVENT_LISTENER]; var nativeRemoveEventListener = proto[zoneSymbol(REMOVE_EVENT_LISTENER)] = proto[REMOVE_EVENT_LISTENER]; var nativeListeners = proto[zoneSymbol(LISTENERS_EVENT_LISTENER)] = proto[LISTENERS_EVENT_LISTENER]; var nativeRemoveAllListeners = proto[zoneSymbol(REMOVE_ALL_LISTENERS_EVENT_LISTENER)] = proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER]; var nativePrependEventListener; if (patchOptions && patchOptions.prepend) { nativePrependEventListener = proto[zoneSymbol(patchOptions.prepend)] = proto[patchOptions.prepend]; } var customScheduleGlobal = function () { // if there is already a task for the eventName + capture, // just return, because we use the shared globalZoneAwareCallback here. if (taskData.isExisting) { return; } return nativeAddEventListener.call(taskData.target, taskData.eventName, taskData.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, taskData.options); }; var customCancelGlobal = function (task) { // if task is not marked as isRemoved, this call is directly // from Zone.prototype.cancelTask, we should remove the task // from tasksList of target first if (!task.isRemoved) { var symbolEventNames = zoneSymbolEventNames$1[task.eventName]; var symbolEventName = void 0; if (symbolEventNames) { symbolEventName = symbolEventNames[task.capture ? TRUE_STR : FALSE_STR]; } var existingTasks = symbolEventName && task.target[symbolEventName]; if (existingTasks) { for (var i = 0; i < existingTasks.length; i++) { var existingTask = existingTasks[i]; if (existingTask === task) { existingTasks.splice(i, 1); // set isRemoved to data for faster invokeTask check task.isRemoved = true; if (existingTasks.length === 0) { // all tasks for the eventName + capture have gone, // remove globalZoneAwareCallback and remove the task cache from target task.allRemoved = true; task.target[symbolEventName] = null; } break; } } } } // if all tasks for the eventName + capture have gone, // we will really remove the global event callback, // if not, return if (!task.allRemoved) { return; } return nativeRemoveEventListener.call(task.target, task.eventName, task.capture ? globalZoneAwareCaptureCallback : globalZoneAwareCallback, task.options); }; var customScheduleNonGlobal = function (task) { return nativeAddEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options); }; var customSchedulePrepend = function (task) { return nativePrependEventListener.call(taskData.target, taskData.eventName, task.invoke, taskData.options); }; var customCancelNonGlobal = function (task) { return nativeRemoveEventListener.call(task.target, task.eventName, task.invoke, task.options); }; var customSchedule = useGlobalCallback ? customScheduleGlobal : customScheduleNonGlobal; var customCancel = useGlobalCallback ? customCancelGlobal : customCancelNonGlobal; var compareTaskCallbackVsDelegate = function (task, delegate) { var typeOfDelegate = typeof delegate; return (typeOfDelegate === 'function' && task.callback === delegate) || (typeOfDelegate === 'object' && task.originalDelegate === delegate); }; var compare = (patchOptions && patchOptions.diff) ? patchOptions.diff : compareTaskCallbackVsDelegate; var blackListedEvents = Zone[Zone.__symbol__('BLACK_LISTED_EVENTS')]; var makeAddListener = function (nativeListener, addSource, customScheduleFn, customCancelFn, returnTarget, prepend) { if (returnTarget === void 0) { returnTarget = false; } if (prepend === void 0) { prepend = false; } return function () { var target = this || _global; var delegate = arguments[1]; if (!delegate) { return nativeListener.apply(this, arguments); } // don't create the bind delegate function for handleEvent // case here to improve addEventListener performance // we will create the bind delegate when invoke var isHandleEvent = false; if (typeof delegate !== 'function') { if (!delegate.handleEvent) { return nativeListener.apply(this, arguments); } isHandleEvent = true; } if (validateHandler && !validateHandler(nativeListener, delegate, target, arguments)) { return; } var eventName = arguments[0]; var options = arguments[2]; if (blackListedEvents) { // check black list for (var i = 0; i < blackListedEvents.length; i++) { if (eventName === blackListedEvents[i]) { return nativeListener.apply(this, arguments); } } } var capture; var once = false; if (options === undefined) { capture = false; } else if (options === true) { capture = true; } else if (options === false) { capture = false; } else { capture = options ? !!options.capture : false; once = options ? !!options.once : false; } var zone = Zone.current; var symbolEventNames = zoneSymbolEventNames$1[eventName]; var symbolEventName; if (!symbolEventNames) { // the code is duplicate, but I just want to get some better performance var falseEventName = eventName + FALSE_STR; var trueEventName = eventName + TRUE_STR; var symbol = ZONE_SYMBOL_PREFIX + falseEventName; var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName; zoneSymbolEventNames$1[eventName] = {}; zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol; zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture; symbolEventName = capture ? symbolCapture : symbol; } else { symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR]; } var existingTasks = target[symbolEventName]; var isExisting = false; if (existingTasks) { // already have task registered isExisting = true; if (checkDuplicate) { for (var i = 0; i < existingTasks.length; i++) { if (compare(existingTasks[i], delegate)) { // same callback, same capture, same event name, just return return; } } } } else { existingTasks = target[symbolEventName] = []; } var source; var constructorName = target.constructor['name']; var targetSource = globalSources[constructorName]; if (targetSource) { source = targetSource[eventName]; } if (!source) { source = constructorName + addSource + eventName; } // do not create a new object as task.data to pass those things // just use the global shared one taskData.options = options; if (once) { // if addEventListener with once options, we don't pass it to // native addEventListener, instead we keep the once setting // and handle ourselves. taskData.options.once = false; } taskData.target = target; taskData.capture = capture; taskData.eventName = eventName; taskData.isExisting = isExisting; var data = useGlobalCallback ? OPTIMIZED_ZONE_EVENT_TASK_DATA : null; // keep taskData into data to allow onScheduleEventTask to access the task information if (data) { data.taskData = taskData; } var task = zone.scheduleEventTask(source, delegate, data, customScheduleFn, customCancelFn); // should clear taskData.target to avoid memory leak // issue, https://github.com/angular/angular/issues/20442 taskData.target = null; // need to clear up taskData because it is a global object if (data) { data.taskData = null; } // have to save those information to task in case // application may call task.zone.cancelTask() directly if (once) { options.once = true; } task.options = options; task.target = target; task.capture = capture; task.eventName = eventName; if (isHandleEvent) { // save original delegate for compare to check duplicate task.originalDelegate = delegate; } if (!prepend) { existingTasks.push(task); } else { existingTasks.unshift(task); } if (returnTarget) { return target; } }; }; proto[ADD_EVENT_LISTENER] = makeAddListener(nativeAddEventListener, ADD_EVENT_LISTENER_SOURCE, customSchedule, customCancel, returnTarget); if (nativePrependEventListener) { proto[PREPEND_EVENT_LISTENER] = makeAddListener(nativePrependEventListener, PREPEND_EVENT_LISTENER_SOURCE, customSchedulePrepend, customCancel, returnTarget, true); } proto[REMOVE_EVENT_LISTENER] = function () { var target = this || _global; var eventName = arguments[0]; var options = arguments[2]; var capture; if (options === undefined) { capture = false; } else if (options === true) { capture = true; } else if (options === false) { capture = false; } else { capture = options ? !!options.capture : false; } var delegate = arguments[1]; if (!delegate) { return nativeRemoveEventListener.apply(this, arguments); } if (validateHandler && !validateHandler(nativeRemoveEventListener, delegate, target, arguments)) { return; } var symbolEventNames = zoneSymbolEventNames$1[eventName]; var symbolEventName; if (symbolEventNames) { symbolEventName = symbolEventNames[capture ? TRUE_STR : FALSE_STR]; } var existingTasks = symbolEventName && target[symbolEventName]; if (existingTasks) { for (var i = 0; i < existingTasks.length; i++) { var existingTask = existingTasks[i]; if (compare(existingTask, delegate)) { existingTasks.splice(i, 1); // set isRemoved to data for faster invokeTask check existingTask.isRemoved = true; if (existingTasks.length === 0) { // all tasks for the eventName + capture have gone, // remove globalZoneAwareCallback and remove the task cache from target existingTask.allRemoved = true; target[symbolEventName] = null; } existingTask.zone.cancelTask(existingTask); if (returnTarget) { return target; } return; } } } // issue 930, didn't find the event name or callback // from zone kept existingTasks, the callback maybe // added outside of zone, we need to call native removeEventListener // to try to remove it. return nativeRemoveEventListener.apply(this, arguments); }; proto[LISTENERS_EVENT_LISTENER] = function () { var target = this || _global; var eventName = arguments[0]; var listeners = []; var tasks = findEventTasks(target, eventName); for (var i = 0; i < tasks.length; i++) { var task = tasks[i]; var delegate = task.originalDelegate ? task.originalDelegate : task.callback; listeners.push(delegate); } return listeners; }; proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER] = function () { var target = this || _global; var eventName = arguments[0]; if (!eventName) { var keys = Object.keys(target); for (var i = 0; i < keys.length; i++) { var prop = keys[i]; var match = EVENT_NAME_SYMBOL_REGX.exec(prop); var evtName = match && match[1]; // in nodejs EventEmitter, removeListener event is // used for monitoring the removeListener call, // so just keep removeListener eventListener until // all other eventListeners are removed if (evtName && evtName !== 'removeListener') { this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, evtName); } } // remove removeListener listener finally this[REMOVE_ALL_LISTENERS_EVENT_LISTENER].call(this, 'removeListener'); } else { var symbolEventNames = zoneSymbolEventNames$1[eventName]; if (symbolEventNames) { var symbolEventName = symbolEventNames[FALSE_STR]; var symbolCaptureEventName = symbolEventNames[TRUE_STR]; var tasks = target[symbolEventName]; var captureTasks = target[symbolCaptureEventName]; if (tasks) { var removeTasks = tasks.slice(); for (var i = 0; i < removeTasks.length; i++) { var task = removeTasks[i]; var delegate = task.originalDelegate ? task.originalDelegate : task.callback; this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options); } } if (captureTasks) { var removeTasks = captureTasks.slice(); for (var i = 0; i < removeTasks.length; i++) { var task = removeTasks[i]; var delegate = task.originalDelegate ? task.originalDelegate : task.callback; this[REMOVE_EVENT_LISTENER].call(this, eventName, delegate, task.options); } } } } if (returnTarget) { return this; } }; // for native toString patch attachOriginToPatched(proto[ADD_EVENT_LISTENER], nativeAddEventListener); attachOriginToPatched(proto[REMOVE_EVENT_LISTENER], nativeRemoveEventListener); if (nativeRemoveAllListeners) { attachOriginToPatched(proto[REMOVE_ALL_LISTENERS_EVENT_LISTENER], nativeRemoveAllListeners); } if (nativeListeners) { attachOriginToPatched(proto[LISTENERS_EVENT_LISTENER], nativeListeners); } return true; } var results = []; for (var i = 0; i < apis.length; i++) { results[i] = patchEventTargetMethods(apis[i], patchOptions); } return results; } function findEventTasks(target, eventName) { var foundTasks = []; for (var prop in target) { var match = EVENT_NAME_SYMBOL_REGX.exec(prop); var evtName = match && match[1]; if (evtName && (!eventName || evtName === eventName)) { var tasks = target[prop]; if (tasks) { for (var i = 0; i < tasks.length; i++) { foundTasks.push(tasks[i]); } } } } return foundTasks; } function patchEventPrototype(global, api) { var Event = global['Event']; if (Event && Event.prototype) { api.patchMethod(Event.prototype, 'stopImmediatePropagation', function (delegate) { return function (self, args) { self[IMMEDIATE_PROPAGATION_SYMBOL] = true; // we need to call the native stopImmediatePropagation // in case in some hybrid application, some part of // application will be controlled by zone, some are not delegate && delegate.apply(self, args); }; }); } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @fileoverview * @suppress {missingRequire} */ var taskSymbol = zoneSymbol('zoneTask'); function patchTimer(window, setName, cancelName, nameSuffix) { var setNative = null; var clearNative = null; setName += nameSuffix; cancelName += nameSuffix; var tasksByHandleId = {}; function scheduleTask(task) { var data = task.data; function timer() { try { task.invoke.apply(this, arguments); } finally { // issue-934, task will be cancelled // even it is a periodic task such as // setInterval if (!(task.data && task.data.isPeriodic)) { if (typeof data.handleId === 'number') { // in non-nodejs env, we remove timerId // from local cache delete tasksByHandleId[data.handleId]; } else if (data.handleId) { // Node returns complex objects as handleIds // we remove task reference from timer object data.handleId[taskSymbol] = null; } } } } data.args[0] = timer; data.handleId = setNative.apply(window, data.args); return task; } function clearTask(task) { return clearNative(task.data.handleId); } setNative = patchMethod(window, setName, function (delegate) { return function (self, args) { if (typeof args[0] === 'function') { var options = { handleId: null, isPeriodic: nameSuffix === 'Interval', delay: (nameSuffix === 'Timeout' || nameSuffix === 'Interval') ? args[1] || 0 : null, args: args }; var task = scheduleMacroTaskWithCurrentZone(setName, args[0], options, scheduleTask, clearTask); if (!task) { return task; } // Node.js must additionally support the ref and unref functions. var handle = task.data.handleId; if (typeof handle === 'number') { // for non nodejs env, we save handleId: task // mapping in local cache for clearTimeout tasksByHandleId[handle] = task; } else if (handle) { // for nodejs env, we save task // reference in timerId Object for clearTimeout handle[taskSymbol] = task; } // check whether handle is null, because some polyfill or browser // may return undefined from setTimeout/setInterval/setImmediate/requestAnimationFrame if (handle && handle.ref && handle.unref && typeof handle.ref === 'function' && typeof handle.unref === 'function') { task.ref = handle.ref.bind(handle); task.unref = handle.unref.bind(handle); } if (typeof handle === 'number' || handle) { return handle; } return task; } else { // cause an error by calling it directly. return delegate.apply(window, args); } }; }); clearNative = patchMethod(window, cancelName, function (delegate) { return function (self, args) { var id = args[0]; var task; if (typeof id === 'number') { // non nodejs env. task = tasksByHandleId[id]; } else { // nodejs env. task = id && id[taskSymbol]; // other environments. if (!task) { task = id; } } if (task && typeof task.type === 'string') { if (task.state !== 'notScheduled' && (task.cancelFn && task.data.isPeriodic || task.runCount === 0)) { if (typeof id === 'number') { delete tasksByHandleId[id]; } else if (id) { id[taskSymbol] = null; } // Do not cancel already canceled functions task.zone.cancelTask(task); } } else { // cause an error by calling it directly. delegate.apply(window, args); } }; }); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /* * This is necessary for Chrome and Chrome mobile, to enable * things like redefining `createdCallback` on an element. */ var _defineProperty = Object[zoneSymbol('defineProperty')] = Object.defineProperty; var _getOwnPropertyDescriptor = Object[zoneSymbol('getOwnPropertyDescriptor')] = Object.getOwnPropertyDescriptor; var _create = Object.create; var unconfigurablesKey = zoneSymbol('unconfigurables'); function propertyPatch() { Object.defineProperty = function (obj, prop, desc) { if (isUnconfigurable(obj, prop)) { throw new TypeError('Cannot assign to read only property \'' + prop + '\' of ' + obj); } var originalConfigurableFlag = desc.configurable; if (prop !== 'prototype') { desc = rewriteDescriptor(obj, prop, desc); } return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag); }; Object.defineProperties = function (obj, props) { Object.keys(props).forEach(function (prop) { Object.defineProperty(obj, prop, props[prop]); }); return obj; }; Object.create = function (obj, proto) { if (typeof proto === 'object' && !Object.isFrozen(proto)) { Object.keys(proto).forEach(function (prop) { proto[prop] = rewriteDescriptor(obj, prop, proto[prop]); }); } return _create(obj, proto); }; Object.getOwnPropertyDescriptor = function (obj, prop) { var desc = _getOwnPropertyDescriptor(obj, prop); if (isUnconfigurable(obj, prop)) { desc.configurable = false; } return desc; }; } function _redefineProperty(obj, prop, desc) { var originalConfigurableFlag = desc.configurable; desc = rewriteDescriptor(obj, prop, desc); return _tryDefineProperty(obj, prop, desc, originalConfigurableFlag); } function isUnconfigurable(obj, prop) { return obj && obj[unconfigurablesKey] && obj[unconfigurablesKey][prop]; } function rewriteDescriptor(obj, prop, desc) { // issue-927, if the desc is frozen, don't try to change the desc if (!Object.isFrozen(desc)) { desc.configurable = true; } if (!desc.configurable) { // issue-927, if the obj is frozen, don't try to set the desc to obj if (!obj[unconfigurablesKey] && !Object.isFrozen(obj)) { _defineProperty(obj, unconfigurablesKey, { writable: true, value: {} }); } if (obj[unconfigurablesKey]) { obj[unconfigurablesKey][prop] = true; } } return desc; } function _tryDefineProperty(obj, prop, desc, originalConfigurableFlag) { try { return _defineProperty(obj, prop, desc); } catch (error) { if (desc.configurable) { // In case of errors, when the configurable flag was likely set by rewriteDescriptor(), let's // retry with the original flag value if (typeof originalConfigurableFlag == 'undefined') { delete desc.configurable; } else { desc.configurable = originalConfigurableFlag; } try { return _defineProperty(obj, prop, desc); } catch (error) { var descJson = null; try { descJson = JSON.stringify(desc); } catch (error) { descJson = desc.toString(); } console.log("Attempting to configure '" + prop + "' with descriptor '" + descJson + "' on object '" + obj + "' and got error, giving up: " + error); } } else { throw error; } } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ // we have to patch the instance since the proto is non-configurable function apply(api, _global) { var WS = _global.WebSocket; // On Safari window.EventTarget doesn't exist so need to patch WS add/removeEventListener // On older Chrome, no need since EventTarget was already patched if (!_global.EventTarget) { patchEventTarget(_global, [WS.prototype]); } _global.WebSocket = function (x, y) { var socket = arguments.length > 1 ? new WS(x, y) : new WS(x); var proxySocket; var proxySocketProto; // Safari 7.0 has non-configurable own 'onmessage' and friends properties on the socket instance var onmessageDesc = ObjectGetOwnPropertyDescriptor(socket, 'onmessage'); if (onmessageDesc && onmessageDesc.configurable === false) { proxySocket = ObjectCreate(socket); // socket have own property descriptor 'onopen', 'onmessage', 'onclose', 'onerror' // but proxySocket not, so we will keep socket as prototype and pass it to // patchOnProperties method proxySocketProto = socket; [ADD_EVENT_LISTENER_STR, REMOVE_EVENT_LISTENER_STR, 'send', 'close'].forEach(function (propName) { proxySocket[propName] = function () { var args = ArraySlice.call(arguments); if (propName === ADD_EVENT_LISTENER_STR || propName === REMOVE_EVENT_LISTENER_STR) { var eventName = args.length > 0 ? args[0] : undefined; if (eventName) { var propertySymbol = Zone.__symbol__('ON_PROPERTY' + eventName); socket[propertySymbol] = proxySocket[propertySymbol]; } } return socket[propName].apply(socket, args); }; }); } else { // we can patch the real socket proxySocket = socket; } patchOnProperties(proxySocket, ['close', 'error', 'message', 'open'], proxySocketProto); return proxySocket; }; var globalWebSocket = _global['WebSocket']; for (var prop in WS) { globalWebSocket[prop] = WS[prop]; } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @fileoverview * @suppress {globalThis} */ var globalEventHandlersEventNames = [ 'abort', 'animationcancel', 'animationend', 'animationiteration', 'auxclick', 'beforeinput', 'blur', 'cancel', 'canplay', 'canplaythrough', 'change', 'compositionstart', 'compositionupdate', 'compositionend', 'cuechange', 'click', 'close', 'contextmenu', 'curechange', 'dblclick', 'drag', 'dragend', 'dragenter', 'dragexit', 'dragleave', 'dragover', 'drop', 'durationchange', 'emptied', 'ended', 'error', 'focus', 'focusin', 'focusout', 'gotpointercapture', 'input', 'invalid', 'keydown', 'keypress', 'keyup', 'load', 'loadstart', 'loadeddata', 'loadedmetadata', 'lostpointercapture', 'mousedown', 'mouseenter', 'mouseleave', 'mousemove', 'mouseout', 'mouseover', 'mouseup', 'mousewheel', 'orientationchange', 'pause', 'play', 'playing', 'pointercancel', 'pointerdown', 'pointerenter', 'pointerleave', 'pointerlockchange', 'mozpointerlockchange', 'webkitpointerlockerchange', 'pointerlockerror', 'mozpointerlockerror', 'webkitpointerlockerror', 'pointermove', 'pointout', 'pointerover', 'pointerup', 'progress', 'ratechange', 'reset', 'resize', 'scroll', 'seeked', 'seeking', 'select', 'selectionchange', 'selectstart', 'show', 'sort', 'stalled', 'submit', 'suspend', 'timeupdate', 'volumechange', 'touchcancel', 'touchmove', 'touchstart', 'touchend', 'transitioncancel', 'transitionend', 'waiting', 'wheel' ]; var documentEventNames = [ 'afterscriptexecute', 'beforescriptexecute', 'DOMContentLoaded', 'fullscreenchange', 'mozfullscreenchange', 'webkitfullscreenchange', 'msfullscreenchange', 'fullscreenerror', 'mozfullscreenerror', 'webkitfullscreenerror', 'msfullscreenerror', 'readystatechange', 'visibilitychange' ]; var windowEventNames = [ 'absolutedeviceorientation', 'afterinput', 'afterprint', 'appinstalled', 'beforeinstallprompt', 'beforeprint', 'beforeunload', 'devicelight', 'devicemotion', 'deviceorientation', 'deviceorientationabsolute', 'deviceproximity', 'hashchange', 'languagechange', 'message', 'mozbeforepaint', 'offline', 'online', 'paint', 'pageshow', 'pagehide', 'popstate', 'rejectionhandled', 'storage', 'unhandledrejection', 'unload', 'userproximity', 'vrdisplyconnected', 'vrdisplaydisconnected', 'vrdisplaypresentchange' ]; var htmlElementEventNames = [ 'beforecopy', 'beforecut', 'beforepaste', 'copy', 'cut', 'paste', 'dragstart', 'loadend', 'animationstart', 'search', 'transitionrun', 'transitionstart', 'webkitanimationend', 'webkitanimationiteration', 'webkitanimationstart', 'webkittransitionend' ]; var mediaElementEventNames = ['encrypted', 'waitingforkey', 'msneedkey', 'mozinterruptbegin', 'mozinterruptend']; var ieElementEventNames = [ 'activate', 'afterupdate', 'ariarequest', 'beforeactivate', 'beforedeactivate', 'beforeeditfocus', 'beforeupdate', 'cellchange', 'controlselect', 'dataavailable', 'datasetchanged', 'datasetcomplete', 'errorupdate', 'filterchange', 'layoutcomplete', 'losecapture', 'move', 'moveend', 'movestart', 'propertychange', 'resizeend', 'resizestart', 'rowenter', 'rowexit', 'rowsdelete', 'rowsinserted', 'command', 'compassneedscalibration', 'deactivate', 'help', 'mscontentzoom', 'msmanipulationstatechanged', 'msgesturechange', 'msgesturedoubletap', 'msgestureend', 'msgesturehold', 'msgesturestart', 'msgesturetap', 'msgotpointercapture', 'msinertiastart', 'mslostpointercapture', 'mspointercancel', 'mspointerdown', 'mspointerenter', 'mspointerhover', 'mspointerleave', 'mspointermove', 'mspointerout', 'mspointerover', 'mspointerup', 'pointerout', 'mssitemodejumplistitemremoved', 'msthumbnailclick', 'stop', 'storagecommit' ]; var webglEventNames = ['webglcontextrestored', 'webglcontextlost', 'webglcontextcreationerror']; var formEventNames = ['autocomplete', 'autocompleteerror']; var detailEventNames = ['toggle']; var frameEventNames = ['load']; var frameSetEventNames = ['blur', 'error', 'focus', 'load', 'resize', 'scroll', 'messageerror']; var marqueeEventNames = ['bounce', 'finish', 'start']; var XMLHttpRequestEventNames = [ 'loadstart', 'progress', 'abort', 'error', 'load', 'progress', 'timeout', 'loadend', 'readystatechange' ]; var IDBIndexEventNames = ['upgradeneeded', 'complete', 'abort', 'success', 'error', 'blocked', 'versionchange', 'close']; var websocketEventNames = ['close', 'error', 'open', 'message']; var workerEventNames = ['error', 'message']; var eventNames = globalEventHandlersEventNames.concat(webglEventNames, formEventNames, detailEventNames, documentEventNames, windowEventNames, htmlElementEventNames, ieElementEventNames); function filterProperties(target, onProperties, ignoreProperties) { if (!ignoreProperties) { return onProperties; } var tip = ignoreProperties.filter(function (ip) { return ip.target === target; }); if (!tip || tip.length === 0) { return onProperties; } var targetIgnoreProperties = tip[0].ignoreProperties; return onProperties.filter(function (op) { return targetIgnoreProperties.indexOf(op) === -1; }); } function patchFilteredProperties(target, onProperties, ignoreProperties, prototype) { // check whether target is available, sometimes target will be undefined // because different browser or some 3rd party plugin. if (!target) { return; } var filteredProperties = filterProperties(target, onProperties, ignoreProperties); patchOnProperties(target, filteredProperties, prototype); } function propertyDescriptorPatch(api, _global) { if (isNode && !isMix) { return; } var supportsWebSocket = typeof WebSocket !== 'undefined'; if (canPatchViaPropertyDescriptor()) { var ignoreProperties = _global.__Zone_ignore_on_properties; // for browsers that we can patch the descriptor: Chrome & Firefox if (isBrowser) { var internalWindow = window; // in IE/Edge, onProp not exist in window object, but in WindowPrototype // so we need to pass WindowPrototype to check onProp exist or not patchFilteredProperties(internalWindow, eventNames.concat(['messageerror']), ignoreProperties, ObjectGetPrototypeOf(internalWindow)); patchFilteredProperties(Document.prototype, eventNames, ignoreProperties); if (typeof internalWindow['SVGElement'] !== 'undefined') { patchFilteredProperties(internalWindow['SVGElement'].prototype, eventNames, ignoreProperties); } patchFilteredProperties(Element.prototype, eventNames, ignoreProperties); patchFilteredProperties(HTMLElement.prototype, eventNames, ignoreProperties); patchFilteredProperties(HTMLMediaElement.prototype, mediaElementEventNames, ignoreProperties); patchFilteredProperties(HTMLFrameSetElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties); patchFilteredProperties(HTMLBodyElement.prototype, windowEventNames.concat(frameSetEventNames), ignoreProperties); patchFilteredProperties(HTMLFrameElement.prototype, frameEventNames, ignoreProperties); patchFilteredProperties(HTMLIFrameElement.prototype, frameEventNames, ignoreProperties); var HTMLMarqueeElement_1 = internalWindow['HTMLMarqueeElement']; if (HTMLMarqueeElement_1) { patchFilteredProperties(HTMLMarqueeElement_1.prototype, marqueeEventNames, ignoreProperties); } var Worker_1 = internalWindow['Worker']; if (Worker_1) { patchFilteredProperties(Worker_1.prototype, workerEventNames, ignoreProperties); } } patchFilteredProperties(XMLHttpRequest.prototype, XMLHttpRequestEventNames, ignoreProperties); var XMLHttpRequestEventTarget = _global['XMLHttpRequestEventTarget']; if (XMLHttpRequestEventTarget) { patchFilteredProperties(XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype, XMLHttpRequestEventNames, ignoreProperties); } if (typeof IDBIndex !== 'undefined') { patchFilteredProperties(IDBIndex.prototype, IDBIndexEventNames, ignoreProperties); patchFilteredProperties(IDBRequest.prototype, IDBIndexEventNames, ignoreProperties); patchFilteredProperties(IDBOpenDBRequest.prototype, IDBIndexEventNames, ignoreProperties); patchFilteredProperties(IDBDatabase.prototype, IDBIndexEventNames, ignoreProperties); patchFilteredProperties(IDBTransaction.prototype, IDBIndexEventNames, ignoreProperties); patchFilteredProperties(IDBCursor.prototype, IDBIndexEventNames, ignoreProperties); } if (supportsWebSocket) { patchFilteredProperties(WebSocket.prototype, websocketEventNames, ignoreProperties); } } else { // Safari, Android browsers (Jelly Bean) patchViaCapturingAllTheEvents(); patchClass('XMLHttpRequest'); if (supportsWebSocket) { apply(api, _global); } } } function canPatchViaPropertyDescriptor() { if ((isBrowser || isMix) && !ObjectGetOwnPropertyDescriptor(HTMLElement.prototype, 'onclick') && typeof Element !== 'undefined') { // WebKit https://bugs.webkit.org/show_bug.cgi?id=134364 // IDL interface attributes are not configurable var desc = ObjectGetOwnPropertyDescriptor(Element.prototype, 'onclick'); if (desc && !desc.configurable) return false; } var ON_READY_STATE_CHANGE = 'onreadystatechange'; var XMLHttpRequestPrototype = XMLHttpRequest.prototype; var xhrDesc = ObjectGetOwnPropertyDescriptor(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE); // add enumerable and configurable here because in opera // by default XMLHttpRequest.prototype.onreadystatechange is undefined // without adding enumerable and configurable will cause onreadystatechange // non-configurable // and if XMLHttpRequest.prototype.onreadystatechange is undefined, // we should set a real desc instead a fake one if (xhrDesc) { ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, { enumerable: true, configurable: true, get: function () { return true; } }); var req = new XMLHttpRequest(); var result = !!req.onreadystatechange; // restore original desc ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, xhrDesc || {}); return result; } else { var SYMBOL_FAKE_ONREADYSTATECHANGE_1 = zoneSymbol('fake'); ObjectDefineProperty(XMLHttpRequestPrototype, ON_READY_STATE_CHANGE, { enumerable: true, configurable: true, get: function () { return this[SYMBOL_FAKE_ONREADYSTATECHANGE_1]; }, set: function (value) { this[SYMBOL_FAKE_ONREADYSTATECHANGE_1] = value; } }); var req = new XMLHttpRequest(); var detectFunc = function () { }; req.onreadystatechange = detectFunc; var result = req[SYMBOL_FAKE_ONREADYSTATECHANGE_1] === detectFunc; req.onreadystatechange = null; return result; } } var unboundKey = zoneSymbol('unbound'); // Whenever any eventListener fires, we check the eventListener target and all parents // for `onwhatever` properties and replace them with zone-bound functions // - Chrome (for now) function patchViaCapturingAllTheEvents() { var _loop_1 = function (i) { var property = eventNames[i]; var onproperty = 'on' + property; self.addEventListener(property, function (event) { var elt = event.target, bound, source; if (elt) { source = elt.constructor['name'] + '.' + onproperty; } else { source = 'unknown.' + onproperty; } while (elt) { if (elt[onproperty] && !elt[onproperty][unboundKey]) { bound = wrapWithCurrentZone(elt[onproperty], source); bound[unboundKey] = elt[onproperty]; elt[onproperty] = bound; } elt = elt.parentElement; } }, true); }; for (var i = 0; i < eventNames.length; i++) { _loop_1(i); } } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function eventTargetPatch(_global, api) { var WTF_ISSUE_555 = 'Anchor,Area,Audio,BR,Base,BaseFont,Body,Button,Canvas,Content,DList,Directory,Div,Embed,FieldSet,Font,Form,Frame,FrameSet,HR,Head,Heading,Html,IFrame,Image,Input,Keygen,LI,Label,Legend,Link,Map,Marquee,Media,Menu,Meta,Meter,Mod,OList,Object,OptGroup,Option,Output,Paragraph,Pre,Progress,Quote,Script,Select,Source,Span,Style,TableCaption,TableCell,TableCol,Table,TableRow,TableSection,TextArea,Title,Track,UList,Unknown,Video'; var NO_EVENT_TARGET = 'ApplicationCache,EventSource,FileReader,InputMethodContext,MediaController,MessagePort,Node,Performance,SVGElementInstance,SharedWorker,TextTrack,TextTrackCue,TextTrackList,WebKitNamedFlow,Window,Worker,WorkerGlobalScope,XMLHttpRequest,XMLHttpRequestEventTarget,XMLHttpRequestUpload,IDBRequest,IDBOpenDBRequest,IDBDatabase,IDBTransaction,IDBCursor,DBIndex,WebSocket' .split(','); var EVENT_TARGET = 'EventTarget'; var apis = []; var isWtf = _global['wtf']; var WTF_ISSUE_555_ARRAY = WTF_ISSUE_555.split(','); if (isWtf) { // Workaround for: https://github.com/google/tracing-framework/issues/555 apis = WTF_ISSUE_555_ARRAY.map(function (v) { return 'HTML' + v + 'Element'; }).concat(NO_EVENT_TARGET); } else if (_global[EVENT_TARGET]) { apis.push(EVENT_TARGET); } else { // Note: EventTarget is not available in all browsers, // if it's not available, we instead patch the APIs in the IDL that inherit from EventTarget apis = NO_EVENT_TARGET; } var isDisableIECheck = _global['__Zone_disable_IE_check'] || false; var isEnableCrossContextCheck = _global['__Zone_enable_cross_context_check'] || false; var ieOrEdge = isIEOrEdge(); var ADD_EVENT_LISTENER_SOURCE = '.addEventListener:'; var FUNCTION_WRAPPER = '[object FunctionWrapper]'; var BROWSER_TOOLS = 'function __BROWSERTOOLS_CONSOLE_SAFEFUNC() { [native code] }'; // predefine all __zone_symbol__ + eventName + true/false string for (var i = 0; i < eventNames.length; i++) { var eventName = eventNames[i]; var falseEventName = eventName + FALSE_STR; var trueEventName = eventName + TRUE_STR; var symbol = ZONE_SYMBOL_PREFIX + falseEventName; var symbolCapture = ZONE_SYMBOL_PREFIX + trueEventName; zoneSymbolEventNames$1[eventName] = {}; zoneSymbolEventNames$1[eventName][FALSE_STR] = symbol; zoneSymbolEventNames$1[eventName][TRUE_STR] = symbolCapture; } // predefine all task.source string for (var i = 0; i < WTF_ISSUE_555.length; i++) { var target = WTF_ISSUE_555_ARRAY[i]; var targets = globalSources[target] = {}; for (var j = 0; j < eventNames.length; j++) { var eventName = eventNames[j]; targets[eventName] = target + ADD_EVENT_LISTENER_SOURCE + eventName; } } var checkIEAndCrossContext = function (nativeDelegate, delegate, target, args) { if (!isDisableIECheck && ieOrEdge) { if (isEnableCrossContextCheck) { try { var testString = delegate.toString(); if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) { nativeDelegate.apply(target, args); return false; } } catch (error) { nativeDelegate.apply(target, args); return false; } } else { var testString = delegate.toString(); if ((testString === FUNCTION_WRAPPER || testString == BROWSER_TOOLS)) { nativeDelegate.apply(target, args); return false; } } } else if (isEnableCrossContextCheck) { try { delegate.toString(); } catch (error) { nativeDelegate.apply(target, args); return false; } } return true; }; var apiTypes = []; for (var i = 0; i < apis.length; i++) { var type = _global[apis[i]]; apiTypes.push(type && type.prototype); } // vh is validateHandler to check event handler // is valid or not(for security check) patchEventTarget(_global, apiTypes, { vh: checkIEAndCrossContext }); api.patchEventTarget = patchEventTarget; return true; } function patchEvent(global, api) { patchEventPrototype(global, api); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ function registerElementPatch(_global) { if ((!isBrowser && !isMix) || !('registerElement' in _global.document)) { return; } var _registerElement = document.registerElement; var callbacks = ['createdCallback', 'attachedCallback', 'detachedCallback', 'attributeChangedCallback']; document.registerElement = function (name, opts) { if (opts && opts.prototype) { callbacks.forEach(function (callback) { var source = 'Document.registerElement::' + callback; var prototype = opts.prototype; if (prototype.hasOwnProperty(callback)) { var descriptor = ObjectGetOwnPropertyDescriptor(prototype, callback); if (descriptor && descriptor.value) { descriptor.value = wrapWithCurrentZone(descriptor.value, source); _redefineProperty(opts.prototype, callback, descriptor); } else { prototype[callback] = wrapWithCurrentZone(prototype[callback], source); } } else if (prototype[callback]) { prototype[callback] = wrapWithCurrentZone(prototype[callback], source); } }); } return _registerElement.call(document, name, opts); }; attachOriginToPatched(document.registerElement, _registerElement); } /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /** * @fileoverview * @suppress {missingRequire} */ Zone.__load_patch('util', function (global, Zone, api) { api.patchOnProperties = patchOnProperties; api.patchMethod = patchMethod; api.bindArguments = bindArguments; }); Zone.__load_patch('timers', function (global) { var set = 'set'; var clear = 'clear'; patchTimer(global, set, clear, 'Timeout'); patchTimer(global, set, clear, 'Interval'); patchTimer(global, set, clear, 'Immediate'); }); Zone.__load_patch('requestAnimationFrame', function (global) { patchTimer(global, 'request', 'cancel', 'AnimationFrame'); patchTimer(global, 'mozRequest', 'mozCancel', 'AnimationFrame'); patchTimer(global, 'webkitRequest', 'webkitCancel', 'AnimationFrame'); }); Zone.__load_patch('blocking', function (global, Zone) { var blockingMethods = ['alert', 'prompt', 'confirm']; for (var i = 0; i < blockingMethods.length; i++) { var name_1 = blockingMethods[i]; patchMethod(global, name_1, function (delegate, symbol, name) { return function (s, args) { return Zone.current.run(delegate, global, args, name); }; }); } }); Zone.__load_patch('EventTarget', function (global, Zone, api) { // load blackListEvents from global var SYMBOL_BLACK_LISTED_EVENTS = Zone.__symbol__('BLACK_LISTED_EVENTS'); if (global[SYMBOL_BLACK_LISTED_EVENTS]) { Zone[SYMBOL_BLACK_LISTED_EVENTS] = global[SYMBOL_BLACK_LISTED_EVENTS]; } patchEvent(global, api); eventTargetPatch(global, api); // patch XMLHttpRequestEventTarget's addEventListener/removeEventListener var XMLHttpRequestEventTarget = global['XMLHttpRequestEventTarget']; if (XMLHttpRequestEventTarget && XMLHttpRequestEventTarget.prototype) { api.patchEventTarget(global, [XMLHttpRequestEventTarget.prototype]); } patchClass('MutationObserver'); patchClass('WebKitMutationObserver'); patchClass('IntersectionObserver'); patchClass('FileReader'); }); Zone.__load_patch('on_property', function (global, Zone, api) { propertyDescriptorPatch(api, global); propertyPatch(); registerElementPatch(global); }); Zone.__load_patch('canvas', function (global) { var HTMLCanvasElement = global['HTMLCanvasElement']; if (typeof HTMLCanvasElement !== 'undefined' && HTMLCanvasElement.prototype && HTMLCanvasElement.prototype.toBlob) { patchMacroTask(HTMLCanvasElement.prototype, 'toBlob', function (self, args) { return { name: 'HTMLCanvasElement.toBlob', target: self, cbIdx: 0, args: args }; }); } }); Zone.__load_patch('XHR', function (global, Zone) { // Treat XMLHttpRequest as a macrotask. patchXHR(global); var XHR_TASK = zoneSymbol('xhrTask'); var XHR_SYNC = zoneSymbol('xhrSync'); var XHR_LISTENER = zoneSymbol('xhrListener'); var XHR_SCHEDULED = zoneSymbol('xhrScheduled'); var XHR_URL = zoneSymbol('xhrURL'); function patchXHR(window) { var XMLHttpRequestPrototype = XMLHttpRequest.prototype; function findPendingTask(target) { return target[XHR_TASK]; } var oriAddListener = XMLHttpRequestPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER]; var oriRemoveListener = XMLHttpRequestPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER]; if (!oriAddListener) { var XMLHttpRequestEventTarget = window['XMLHttpRequestEventTarget']; if (XMLHttpRequestEventTarget) { var XMLHttpRequestEventTargetPrototype = XMLHttpRequestEventTarget.prototype; oriAddListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_ADD_EVENT_LISTENER]; oriRemoveListener = XMLHttpRequestEventTargetPrototype[ZONE_SYMBOL_REMOVE_EVENT_LISTENER]; } } var READY_STATE_CHANGE = 'readystatechange'; var SCHEDULED = 'scheduled'; function scheduleTask(task) { XMLHttpRequest[XHR_SCHEDULED] = false; var data = task.data; var target = data.target; // remove existing event listener var listener = target[XHR_LISTENER]; if (!oriAddListener) { oriAddListener = target[ZONE_SYMBOL_ADD_EVENT_LISTENER]; oriRemoveListener = target[ZONE_SYMBOL_REMOVE_EVENT_LISTENER]; } if (listener) { oriRemoveListener.call(target, READY_STATE_CHANGE, listener); } var newListener = target[XHR_LISTENER] = function () { if (target.readyState === target.DONE) { // sometimes on some browsers XMLHttpRequest will fire onreadystatechange with // readyState=4 multiple times, so we need to check task state here if (!data.aborted && XMLHttpRequest[XHR_SCHEDULED] && task.state === SCHEDULED) { task.invoke(); } } }; oriAddListener.call(target, READY_STATE_CHANGE, newListener); var storedTask = target[XHR_TASK]; if (!storedTask) { target[XHR_TASK] = task; } sendNative.apply(target, data.args); XMLHttpRequest[XHR_SCHEDULED] = true; return task; } function placeholderCallback() { } function clearTask(task) { var data = task.data; // Note - ideally, we would call data.target.removeEventListener here, but it's too late // to prevent it from firing. So instead, we store info for the event listener. data.aborted = true; return abortNative.apply(data.target, data.args); } var openNative = patchMethod(XMLHttpRequestPrototype, 'open', function () { return function (self, args) { self[XHR_SYNC] = args[2] == false; self[XHR_URL] = args[1]; return openNative.apply(self, args); }; }); var XMLHTTPREQUEST_SOURCE = 'XMLHttpRequest.send'; var sendNative = patchMethod(XMLHttpRequestPrototype, 'send', function () { return function (self, args) { if (self[XHR_SYNC]) { // if the XHR is sync there is no task to schedule, just execute the code. return sendNative.apply(self, args); } else { var options = { target: self, url: self[XHR_URL], isPeriodic: false, delay: null, args: args, aborted: false }; return scheduleMacroTaskWithCurrentZone(XMLHTTPREQUEST_SOURCE, placeholderCallback, options, scheduleTask, clearTask); } }; }); var abortNative = patchMethod(XMLHttpRequestPrototype, 'abort', function () { return function (self) { var task = findPendingTask(self); if (task && typeof task.type == 'string') { // If the XHR has already completed, do nothing. // If the XHR has already been aborted, do nothing. // Fix #569, call abort multiple times before done will cause // macroTask task count be negative number if (task.cancelFn == null || (task.data && task.data.aborted)) { return; } task.zone.cancelTask(task); } // Otherwise, we are trying to abort an XHR which has not yet been sent, so there is no // task // to cancel. Do nothing. }; }); } }); Zone.__load_patch('geolocation', function (global) { /// GEO_LOCATION if (global['navigator'] && global['navigator'].geolocation) { patchPrototype(global['navigator'].geolocation, ['getCurrentPosition', 'watchPosition']); } }); Zone.__load_patch('PromiseRejectionEvent', function (global, Zone) { // handle unhandled promise rejection function findPromiseRejectionHandler(evtName) { return function (e) { var eventTasks = findEventTasks(global, evtName); eventTasks.forEach(function (eventTask) { // windows has added unhandledrejection event listener // trigger the event listener var PromiseRejectionEvent = global['PromiseRejectionEvent']; if (PromiseRejectionEvent) { var evt = new PromiseRejectionEvent(evtName, { promise: e.promise, reason: e.rejection }); eventTask.invoke(evt); } }); }; } if (global['PromiseRejectionEvent']) { Zone[zoneSymbol('unhandledPromiseRejectionHandler')] = findPromiseRejectionHandler('unhandledrejection'); Zone[zoneSymbol('rejectionHandledHandler')] = findPromiseRejectionHandler('rejectionhandled'); } }); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ Zone.__load_patch('EventEmitter', function (global) { // For EventEmitter var EE_ADD_LISTENER = 'addListener'; var EE_PREPEND_LISTENER = 'prependListener'; var EE_REMOVE_LISTENER = 'removeListener'; var EE_REMOVE_ALL_LISTENER = 'removeAllListeners'; var EE_LISTENERS = 'listeners'; var EE_ON = 'on'; var compareTaskCallbackVsDelegate = function (task, delegate) { // same callback, same capture, same event name, just return return task.callback === delegate || task.callback.listener === delegate; }; function patchEventEmitterMethods(obj) { var result = patchEventTarget(global, [obj], { useG: false, add: EE_ADD_LISTENER, rm: EE_REMOVE_LISTENER, prepend: EE_PREPEND_LISTENER, rmAll: EE_REMOVE_ALL_LISTENER, listeners: EE_LISTENERS, chkDup: false, rt: true, diff: compareTaskCallbackVsDelegate }); if (result && result[0]) { obj[EE_ON] = obj[EE_ADD_LISTENER]; } } // EventEmitter var events; try { events = require('events'); } catch (err) { } if (events && events.EventEmitter) { patchEventEmitterMethods(events.EventEmitter.prototype); } }); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ Zone.__load_patch('fs', function () { var fs; try { fs = require('fs'); } catch (err) { } // watch, watchFile, unwatchFile has been patched // because EventEmitter has been patched var TO_PATCH_MACROTASK_METHODS = [ 'access', 'appendFile', 'chmod', 'chown', 'close', 'exists', 'fchmod', 'fchown', 'fdatasync', 'fstat', 'fsync', 'ftruncate', 'futimes', 'lchmod', 'lchown', 'link', 'lstat', 'mkdir', 'mkdtemp', 'open', 'read', 'readdir', 'readFile', 'readlink', 'realpath', 'rename', 'rmdir', 'stat', 'symlink', 'truncate', 'unlink', 'utimes', 'write', 'writeFile', ]; if (fs) { TO_PATCH_MACROTASK_METHODS.filter(function (name) { return !!fs[name] && typeof fs[name] === 'function'; }) .forEach(function (name) { patchMacroTask(fs, name, function (self, args) { return { name: 'fs.' + name, args: args, cbIdx: args.length > 0 ? args.length - 1 : -1, target: self }; }); }); } }); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ var set = 'set'; var clear = 'clear'; Zone.__load_patch('node_util', function (global, Zone, api) { api.patchOnProperties = patchOnProperties; api.patchMethod = patchMethod; api.bindArguments = bindArguments; }); Zone.__load_patch('node_timers', function (global, Zone) { // Timers var globalUseTimeoutFromTimer = false; try { var timers = require('timers'); var globalEqualTimersTimeout = global.setTimeout === timers.setTimeout; if (!globalEqualTimersTimeout && !isMix) { // 1. if isMix, then we are in mix environment such as Electron // we should only patch timers.setTimeout because global.setTimeout // have been patched // 2. if global.setTimeout not equal timers.setTimeout, check // whether global.setTimeout use timers.setTimeout or not var originSetTimeout_1 = timers.setTimeout; timers.setTimeout = function () { globalUseTimeoutFromTimer = true; return originSetTimeout_1.apply(this, arguments); }; var detectTimeout = global.setTimeout(function () { }, 100); clearTimeout(detectTimeout); timers.setTimeout = originSetTimeout_1; } patchTimer(timers, set, clear, 'Timeout'); patchTimer(timers, set, clear, 'Interval'); patchTimer(timers, set, clear, 'Immediate'); } catch (error) { // timers module not exists, for example, when we using nativeScript // timers is not available } if (isMix) { // if we are in mix environment, such as Electron, // the global.setTimeout has already been patched, // so we just patch timers.setTimeout return; } if (!globalUseTimeoutFromTimer) { // 1. global setTimeout equals timers setTimeout // 2. or global don't use timers setTimeout(maybe some other library patch setTimeout) // 3. or load timers module error happens, we should patch global setTimeout patchTimer(global, set, clear, 'Timeout'); patchTimer(global, set, clear, 'Interval'); patchTimer(global, set, clear, 'Immediate'); } else { // global use timers setTimeout, but not equals // this happens when use nodejs v0.10.x, global setTimeout will // use a lazy load version of timers setTimeout // we should not double patch timer's setTimeout // so we only store the __symbol__ for consistency global[Zone.__symbol__('setTimeout')] = global.setTimeout; global[Zone.__symbol__('setInterval')] = global.setInterval; global[Zone.__symbol__('setImmediate')] = global.setImmediate; } }); // patch process related methods Zone.__load_patch('nextTick', function () { // patch nextTick as microTask patchMicroTask(process, 'nextTick', function (self, args) { return { name: 'process.nextTick', args: args, cbIdx: (args.length > 0 && typeof args[0] === 'function') ? 0 : -1, target: process }; }); }); Zone.__load_patch('handleUnhandledPromiseRejection', function (global, Zone, api) { Zone[api.symbol('unhandledPromiseRejectionHandler')] = findProcessPromiseRejectionHandler('unhandledRejection'); Zone[api.symbol('rejectionHandledHandler')] = findProcessPromiseRejectionHandler('rejectionHandled'); // handle unhandled promise rejection function findProcessPromiseRejectionHandler(evtName) { return function (e) { var eventTasks = findEventTasks(process, evtName); eventTasks.forEach(function (eventTask) { // process has added unhandledrejection event listener // trigger the event listener if (evtName === 'unhandledRejection') { eventTask.invoke(e.rejection, e.promise); } else if (evtName === 'rejectionHandled') { eventTask.invoke(e.promise); } }); }; } }); // Crypto Zone.__load_patch('crypto', function () { var crypto; try { crypto = require('crypto'); } catch (err) { } // use the generic patchMacroTask to patch crypto if (crypto) { var methodNames = ['randomBytes', 'pbkdf2']; methodNames.forEach(function (name) { patchMacroTask(crypto, name, function (self, args) { return { name: 'crypto.' + name, args: args, cbIdx: (args.length > 0 && typeof args[args.length - 1] === 'function') ? args.length - 1 : -1, target: crypto }; }); }); } }); Zone.__load_patch('console', function (global, Zone) { var consoleMethods = ['dir', 'log', 'info', 'error', 'warn', 'assert', 'debug', 'timeEnd', 'trace']; consoleMethods.forEach(function (m) { var originalMethod = console[Zone.__symbol__(m)] = console[m]; if (originalMethod) { console[m] = function () { var args = ArraySlice.call(arguments); if (Zone.current === Zone.root) { return originalMethod.apply(this, args); } else { return Zone.root.run(originalMethod, this, args); } }; } }); }); /** * @license * Copyright Google Inc. All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ })));
/*! * OOjs UI v0.18.3 * https://www.mediawiki.org/wiki/OOjs_UI * * Copyright 2011–2017 OOjs UI Team and other contributors. * Released under the MIT license * http://oojs.mit-license.org * * Date: 2017-01-04T00:22:40Z */ ( function ( OO ) { 'use strict'; /** * Namespace for all classes, static methods and static properties. * * @class * @singleton */ OO.ui = {}; OO.ui.bind = $.proxy; /** * @property {Object} */ OO.ui.Keys = { UNDEFINED: 0, BACKSPACE: 8, DELETE: 46, LEFT: 37, RIGHT: 39, UP: 38, DOWN: 40, ENTER: 13, END: 35, HOME: 36, TAB: 9, PAGEUP: 33, PAGEDOWN: 34, ESCAPE: 27, SHIFT: 16, SPACE: 32 }; /** * Constants for MouseEvent.which * * @property {Object} */ OO.ui.MouseButtons = { LEFT: 1, MIDDLE: 2, RIGHT: 3 }; /** * @property {number} */ OO.ui.elementId = 0; /** * Generate a unique ID for element * * @return {string} [id] */ OO.ui.generateElementId = function () { OO.ui.elementId += 1; return 'oojsui-' + OO.ui.elementId; }; /** * Check if an element is focusable. * Inspired from :focusable in jQueryUI v1.11.4 - 2015-04-14 * * @param {jQuery} $element Element to test * @return {boolean} */ OO.ui.isFocusableElement = function ( $element ) { var nodeName, element = $element[ 0 ]; // Anything disabled is not focusable if ( element.disabled ) { return false; } // Check if the element is visible if ( !( // This is quicker than calling $element.is( ':visible' ) $.expr.filters.visible( element ) && // Check that all parents are visible !$element.parents().addBack().filter( function () { return $.css( this, 'visibility' ) === 'hidden'; } ).length ) ) { return false; } // Check if the element is ContentEditable, which is the string 'true' if ( element.contentEditable === 'true' ) { return true; } // Anything with a non-negative numeric tabIndex is focusable. // Use .prop to avoid browser bugs if ( $element.prop( 'tabIndex' ) >= 0 ) { return true; } // Some element types are naturally focusable // (indexOf is much faster than regex in Chrome and about the // same in FF: https://jsperf.com/regex-vs-indexof-array2) nodeName = element.nodeName.toLowerCase(); if ( [ 'input', 'select', 'textarea', 'button', 'object' ].indexOf( nodeName ) !== -1 ) { return true; } // Links and areas are focusable if they have an href if ( ( nodeName === 'a' || nodeName === 'area' ) && $element.attr( 'href' ) !== undefined ) { return true; } return false; }; /** * Find a focusable child * * @param {jQuery} $container Container to search in * @param {boolean} [backwards] Search backwards * @return {jQuery} Focusable child, an empty jQuery object if none found */ OO.ui.findFocusable = function ( $container, backwards ) { var $focusable = $( [] ), // $focusableCandidates is a superset of things that // could get matched by isFocusableElement $focusableCandidates = $container .find( 'input, select, textarea, button, object, a, area, [contenteditable], [tabindex]' ); if ( backwards ) { $focusableCandidates = Array.prototype.reverse.call( $focusableCandidates ); } $focusableCandidates.each( function () { var $this = $( this ); if ( OO.ui.isFocusableElement( $this ) ) { $focusable = $this; return false; } } ); return $focusable; }; /** * Get the user's language and any fallback languages. * * These language codes are used to localize user interface elements in the user's language. * * In environments that provide a localization system, this function should be overridden to * return the user's language(s). The default implementation returns English (en) only. * * @return {string[]} Language codes, in descending order of priority */ OO.ui.getUserLanguages = function () { return [ 'en' ]; }; /** * Get a value in an object keyed by language code. * * @param {Object.<string,Mixed>} obj Object keyed by language code * @param {string|null} [lang] Language code, if omitted or null defaults to any user language * @param {string} [fallback] Fallback code, used if no matching language can be found * @return {Mixed} Local value */ OO.ui.getLocalValue = function ( obj, lang, fallback ) { var i, len, langs; // Requested language if ( obj[ lang ] ) { return obj[ lang ]; } // Known user language langs = OO.ui.getUserLanguages(); for ( i = 0, len = langs.length; i < len; i++ ) { lang = langs[ i ]; if ( obj[ lang ] ) { return obj[ lang ]; } } // Fallback language if ( obj[ fallback ] ) { return obj[ fallback ]; } // First existing language for ( lang in obj ) { return obj[ lang ]; } return undefined; }; /** * Check if a node is contained within another node * * Similar to jQuery#contains except a list of containers can be supplied * and a boolean argument allows you to include the container in the match list * * @param {HTMLElement|HTMLElement[]} containers Container node(s) to search in * @param {HTMLElement} contained Node to find * @param {boolean} [matchContainers] Include the container(s) in the list of nodes to match, otherwise only match descendants * @return {boolean} The node is in the list of target nodes */ OO.ui.contains = function ( containers, contained, matchContainers ) { var i; if ( !Array.isArray( containers ) ) { containers = [ containers ]; } for ( i = containers.length - 1; i >= 0; i-- ) { if ( ( matchContainers && contained === containers[ i ] ) || $.contains( containers[ i ], contained ) ) { return true; } } return false; }; /** * Return a function, that, as long as it continues to be invoked, will not * be triggered. The function will be called after it stops being called for * N milliseconds. If `immediate` is passed, trigger the function on the * leading edge, instead of the trailing. * * Ported from: http://underscorejs.org/underscore.js * * @param {Function} func * @param {number} wait * @param {boolean} immediate * @return {Function} */ OO.ui.debounce = function ( func, wait, immediate ) { var timeout; return function () { var context = this, args = arguments, later = function () { timeout = null; if ( !immediate ) { func.apply( context, args ); } }; if ( immediate && !timeout ) { func.apply( context, args ); } if ( !timeout || wait ) { clearTimeout( timeout ); timeout = setTimeout( later, wait ); } }; }; /** * Puts a console warning with provided message. * * @param {string} message */ OO.ui.warnDeprecation = function ( message ) { if ( OO.getProp( window, 'console', 'warn' ) !== undefined ) { // eslint-disable-next-line no-console console.warn( message ); } }; /** * Returns a function, that, when invoked, will only be triggered at most once * during a given window of time. If called again during that window, it will * wait until the window ends and then trigger itself again. * * As it's not knowable to the caller whether the function will actually run * when the wrapper is called, return values from the function are entirely * discarded. * * @param {Function} func * @param {number} wait * @return {Function} */ OO.ui.throttle = function ( func, wait ) { var context, args, timeout, previous = 0, run = function () { timeout = null; previous = OO.ui.now(); func.apply( context, args ); }; return function () { // Check how long it's been since the last time the function was // called, and whether it's more or less than the requested throttle // period. If it's less, run the function immediately. If it's more, // set a timeout for the remaining time -- but don't replace an // existing timeout, since that'd indefinitely prolong the wait. var remaining = wait - ( OO.ui.now() - previous ); context = this; args = arguments; if ( remaining <= 0 ) { // Note: unless wait was ridiculously large, this means we'll // automatically run the first time the function was called in a // given period. (If you provide a wait period larger than the // current Unix timestamp, you *deserve* unexpected behavior.) clearTimeout( timeout ); run(); } else if ( !timeout ) { timeout = setTimeout( run, remaining ); } }; }; /** * A (possibly faster) way to get the current timestamp as an integer * * @return {number} Current timestamp */ OO.ui.now = Date.now || function () { return new Date().getTime(); }; /** * Reconstitute a JavaScript object corresponding to a widget created by * the PHP implementation. * * This is an alias for `OO.ui.Element.static.infuse()`. * * @param {string|HTMLElement|jQuery} idOrNode * A DOM id (if a string) or node for the widget to infuse. * @return {OO.ui.Element} * The `OO.ui.Element` corresponding to this (infusable) document node. */ OO.ui.infuse = function ( idOrNode ) { return OO.ui.Element.static.infuse( idOrNode ); }; ( function () { /** * Message store for the default implementation of OO.ui.msg * * Environments that provide a localization system should not use this, but should override * OO.ui.msg altogether. * * @private */ var messages = { // Tool tip for a button that moves items in a list down one place 'ooui-outline-control-move-down': 'Move item down', // Tool tip for a button that moves items in a list up one place 'ooui-outline-control-move-up': 'Move item up', // Tool tip for a button that removes items from a list 'ooui-outline-control-remove': 'Remove item', // Label for the toolbar group that contains a list of all other available tools 'ooui-toolbar-more': 'More', // Label for the fake tool that expands the full list of tools in a toolbar group 'ooui-toolgroup-expand': 'More', // Label for the fake tool that collapses the full list of tools in a toolbar group 'ooui-toolgroup-collapse': 'Fewer', // Default label for the accept button of a confirmation dialog 'ooui-dialog-message-accept': 'OK', // Default label for the reject button of a confirmation dialog 'ooui-dialog-message-reject': 'Cancel', // Title for process dialog error description 'ooui-dialog-process-error': 'Something went wrong', // Label for process dialog dismiss error button, visible when describing errors 'ooui-dialog-process-dismiss': 'Dismiss', // Label for process dialog retry action button, visible when describing only recoverable errors 'ooui-dialog-process-retry': 'Try again', // Label for process dialog retry action button, visible when describing only warnings 'ooui-dialog-process-continue': 'Continue', // Label for the file selection widget's select file button 'ooui-selectfile-button-select': 'Select a file', // Label for the file selection widget if file selection is not supported 'ooui-selectfile-not-supported': 'File selection is not supported', // Label for the file selection widget when no file is currently selected 'ooui-selectfile-placeholder': 'No file is selected', // Label for the file selection widget's drop target 'ooui-selectfile-dragdrop-placeholder': 'Drop file here' }; /** * Get a localized message. * * In environments that provide a localization system, this function should be overridden to * return the message translated in the user's language. The default implementation always returns * English messages. * * After the message key, message parameters may optionally be passed. In the default implementation, * any occurrences of $1 are replaced with the first parameter, $2 with the second parameter, etc. * Alternative implementations of OO.ui.msg may use any substitution system they like, as long as * they support unnamed, ordered message parameters. * * @param {string} key Message key * @param {...Mixed} [params] Message parameters * @return {string} Translated message with parameters substituted */ OO.ui.msg = function ( key ) { var message = messages[ key ], params = Array.prototype.slice.call( arguments, 1 ); if ( typeof message === 'string' ) { // Perform $1 substitution message = message.replace( /\$(\d+)/g, function ( unused, n ) { var i = parseInt( n, 10 ); return params[ i - 1 ] !== undefined ? params[ i - 1 ] : '$' + n; } ); } else { // Return placeholder if message not found message = '[' + key + ']'; } return message; }; }() ); /** * Package a message and arguments for deferred resolution. * * Use this when you are statically specifying a message and the message may not yet be present. * * @param {string} key Message key * @param {...Mixed} [params] Message parameters * @return {Function} Function that returns the resolved message when executed */ OO.ui.deferMsg = function () { var args = arguments; return function () { return OO.ui.msg.apply( OO.ui, args ); }; }; /** * Resolve a message. * * If the message is a function it will be executed, otherwise it will pass through directly. * * @param {Function|string} msg Deferred message, or message text * @return {string} Resolved message */ OO.ui.resolveMsg = function ( msg ) { if ( $.isFunction( msg ) ) { return msg(); } return msg; }; /** * @param {string} url * @return {boolean} */ OO.ui.isSafeUrl = function ( url ) { // Keep this function in sync with php/Tag.php var i, protocolWhitelist; function stringStartsWith( haystack, needle ) { return haystack.substr( 0, needle.length ) === needle; } protocolWhitelist = [ 'bitcoin', 'ftp', 'ftps', 'geo', 'git', 'gopher', 'http', 'https', 'irc', 'ircs', 'magnet', 'mailto', 'mms', 'news', 'nntp', 'redis', 'sftp', 'sip', 'sips', 'sms', 'ssh', 'svn', 'tel', 'telnet', 'urn', 'worldwind', 'xmpp' ]; if ( url === '' ) { return true; } for ( i = 0; i < protocolWhitelist.length; i++ ) { if ( stringStartsWith( url, protocolWhitelist[ i ] + ':' ) ) { return true; } } // This matches '//' too if ( stringStartsWith( url, '/' ) || stringStartsWith( url, './' ) ) { return true; } if ( stringStartsWith( url, '?' ) || stringStartsWith( url, '#' ) ) { return true; } return false; }; /** * Check if the user has a 'mobile' device. * * For our purposes this means the user is primarily using an * on-screen keyboard, touch input instead of a mouse and may * have a physically small display. * * It is left up to implementors to decide how to compute this * so the default implementation always returns false. * * @return {boolean} Use is on a mobile device */ OO.ui.isMobile = function () { return false; }; /*! * Mixin namespace. */ /** * Namespace for OOjs UI mixins. * * Mixins are named according to the type of object they are intended to * be mixed in to. For example, OO.ui.mixin.GroupElement is intended to be * mixed in to an instance of OO.ui.Element, and OO.ui.mixin.GroupWidget * is intended to be mixed in to an instance of OO.ui.Widget. * * @class * @singleton */ OO.ui.mixin = {}; /** * Each Element represents a rendering in the DOM—a button or an icon, for example, or anything * that is visible to a user. Unlike {@link OO.ui.Widget widgets}, plain elements usually do not have events * connected to them and can't be interacted with. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {string[]} [classes] The names of the CSS classes to apply to the element. CSS styles are added * to the top level (e.g., the outermost div) of the element. See the [OOjs UI documentation on MediaWiki][2] * for an example. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#cssExample * @cfg {string} [id] The HTML id attribute used in the rendered tag. * @cfg {string} [text] Text to insert * @cfg {Array} [content] An array of content elements to append (after #text). * Strings will be html-escaped; use an OO.ui.HtmlSnippet to append raw HTML. * Instances of OO.ui.Element will have their $element appended. * @cfg {jQuery} [$content] Content elements to append (after #text). * @cfg {jQuery} [$element] Wrapper element. Defaults to a new element with #getTagName. * @cfg {Mixed} [data] Custom data of any type or combination of types (e.g., string, number, array, object). * Data can also be specified with the #setData method. */ OO.ui.Element = function OoUiElement( config ) { // Configuration initialization config = config || {}; // Properties this.$ = $; this.visible = true; this.data = config.data; this.$element = config.$element || $( document.createElement( this.getTagName() ) ); this.elementGroup = null; this.debouncedUpdateThemeClassesHandler = OO.ui.debounce( this.debouncedUpdateThemeClasses ); // Initialization if ( Array.isArray( config.classes ) ) { this.$element.addClass( config.classes.join( ' ' ) ); } if ( config.id ) { this.$element.attr( 'id', config.id ); } if ( config.text ) { this.$element.text( config.text ); } if ( config.content ) { // The `content` property treats plain strings as text; use an // HtmlSnippet to append HTML content. `OO.ui.Element`s get their // appropriate $element appended. this.$element.append( config.content.map( function ( v ) { if ( typeof v === 'string' ) { // Escape string so it is properly represented in HTML. return document.createTextNode( v ); } else if ( v instanceof OO.ui.HtmlSnippet ) { // Bypass escaping. return v.toString(); } else if ( v instanceof OO.ui.Element ) { return v.$element; } return v; } ) ); } if ( config.$content ) { // The `$content` property treats plain strings as HTML. this.$element.append( config.$content ); } }; /* Setup */ OO.initClass( OO.ui.Element ); /* Static Properties */ /** * The name of the HTML tag used by the element. * * The static value may be ignored if the #getTagName method is overridden. * * @static * @inheritable * @property {string} */ OO.ui.Element.static.tagName = 'div'; /* Static Methods */ /** * Reconstitute a JavaScript object corresponding to a widget created * by the PHP implementation. * * @param {string|HTMLElement|jQuery} idOrNode * A DOM id (if a string) or node for the widget to infuse. * @return {OO.ui.Element} * The `OO.ui.Element` corresponding to this (infusable) document node. * For `Tag` objects emitted on the HTML side (used occasionally for content) * the value returned is a newly-created Element wrapping around the existing * DOM node. */ OO.ui.Element.static.infuse = function ( idOrNode ) { var obj = OO.ui.Element.static.unsafeInfuse( idOrNode, false ); // Verify that the type matches up. // FIXME: uncomment after T89721 is fixed (see T90929) /* if ( !( obj instanceof this['class'] ) ) { throw new Error( 'Infusion type mismatch!' ); } */ return obj; }; /** * Implementation helper for `infuse`; skips the type check and has an * extra property so that only the top-level invocation touches the DOM. * * @private * @param {string|HTMLElement|jQuery} idOrNode * @param {jQuery.Promise|boolean} domPromise A promise that will be resolved * when the top-level widget of this infusion is inserted into DOM, * replacing the original node; or false for top-level invocation. * @return {OO.ui.Element} */ OO.ui.Element.static.unsafeInfuse = function ( idOrNode, domPromise ) { // look for a cached result of a previous infusion. var id, $elem, data, cls, parts, parent, obj, top, state, infusedChildren; if ( typeof idOrNode === 'string' ) { id = idOrNode; $elem = $( document.getElementById( id ) ); } else { $elem = $( idOrNode ); id = $elem.attr( 'id' ); } if ( !$elem.length ) { throw new Error( 'Widget not found: ' + id ); } if ( $elem[ 0 ].oouiInfused ) { $elem = $elem[ 0 ].oouiInfused; } data = $elem.data( 'ooui-infused' ); if ( data ) { // cached! if ( data === true ) { throw new Error( 'Circular dependency! ' + id ); } if ( domPromise ) { // pick up dynamic state, like focus, value of form inputs, scroll position, etc. state = data.constructor.static.gatherPreInfuseState( $elem, data ); // restore dynamic state after the new element is re-inserted into DOM under infused parent domPromise.done( data.restorePreInfuseState.bind( data, state ) ); infusedChildren = $elem.data( 'ooui-infused-children' ); if ( infusedChildren && infusedChildren.length ) { infusedChildren.forEach( function ( data ) { var state = data.constructor.static.gatherPreInfuseState( $elem, data ); domPromise.done( data.restorePreInfuseState.bind( data, state ) ); } ); } } return data; } data = $elem.attr( 'data-ooui' ); if ( !data ) { throw new Error( 'No infusion data found: ' + id ); } try { data = $.parseJSON( data ); } catch ( _ ) { data = null; } if ( !( data && data._ ) ) { throw new Error( 'No valid infusion data found: ' + id ); } if ( data._ === 'Tag' ) { // Special case: this is a raw Tag; wrap existing node, don't rebuild. return new OO.ui.Element( { $element: $elem } ); } parts = data._.split( '.' ); cls = OO.getProp.apply( OO, [ window ].concat( parts ) ); if ( cls === undefined ) { // The PHP output might be old and not including the "OO.ui" prefix // TODO: Remove this back-compat after next major release cls = OO.getProp.apply( OO, [ OO.ui ].concat( parts ) ); if ( cls === undefined ) { throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ ); } } // Verify that we're creating an OO.ui.Element instance parent = cls.parent; while ( parent !== undefined ) { if ( parent === OO.ui.Element ) { // Safe break; } parent = parent.parent; } if ( parent !== OO.ui.Element ) { throw new Error( 'Unknown widget type: id: ' + id + ', class: ' + data._ ); } if ( domPromise === false ) { top = $.Deferred(); domPromise = top.promise(); } $elem.data( 'ooui-infused', true ); // prevent loops data.id = id; // implicit infusedChildren = []; data = OO.copy( data, null, function deserialize( value ) { var infused; if ( OO.isPlainObject( value ) ) { if ( value.tag ) { infused = OO.ui.Element.static.unsafeInfuse( value.tag, domPromise ); infusedChildren.push( infused ); // Flatten the structure infusedChildren.push.apply( infusedChildren, infused.$element.data( 'ooui-infused-children' ) || [] ); infused.$element.removeData( 'ooui-infused-children' ); return infused; } if ( value.html !== undefined ) { return new OO.ui.HtmlSnippet( value.html ); } } } ); // allow widgets to reuse parts of the DOM data = cls.static.reusePreInfuseDOM( $elem[ 0 ], data ); // pick up dynamic state, like focus, value of form inputs, scroll position, etc. state = cls.static.gatherPreInfuseState( $elem[ 0 ], data ); // rebuild widget // eslint-disable-next-line new-cap obj = new cls( data ); // now replace old DOM with this new DOM. if ( top ) { // An efficient constructor might be able to reuse the entire DOM tree of the original element, // so only mutate the DOM if we need to. if ( $elem[ 0 ] !== obj.$element[ 0 ] ) { $elem.replaceWith( obj.$element ); // This element is now gone from the DOM, but if anyone is holding a reference to it, // let's allow them to OO.ui.infuse() it and do what they expect (T105828). // Do not use jQuery.data(), as using it on detached nodes leaks memory in 1.x line by design. $elem[ 0 ].oouiInfused = obj.$element; } top.resolve(); } obj.$element.data( 'ooui-infused', obj ); obj.$element.data( 'ooui-infused-children', infusedChildren ); // set the 'data-ooui' attribute so we can identify infused widgets obj.$element.attr( 'data-ooui', '' ); // restore dynamic state after the new element is inserted into DOM domPromise.done( obj.restorePreInfuseState.bind( obj, state ) ); return obj; }; /** * Pick out parts of `node`'s DOM to be reused when infusing a widget. * * This method **must not** make any changes to the DOM, only find interesting pieces and add them * to `config` (which should then be returned). Actual DOM juggling should then be done by the * constructor, which will be given the enhanced config. * * @protected * @param {HTMLElement} node * @param {Object} config * @return {Object} */ OO.ui.Element.static.reusePreInfuseDOM = function ( node, config ) { return config; }; /** * Gather the dynamic state (focus, value of form inputs, scroll position, etc.) of a HTML DOM node * (and its children) that represent an Element of the same class and the given configuration, * generated by the PHP implementation. * * This method is called just before `node` is detached from the DOM. The return value of this * function will be passed to #restorePreInfuseState after the newly created widget's #$element * is inserted into DOM to replace `node`. * * @protected * @param {HTMLElement} node * @param {Object} config * @return {Object} */ OO.ui.Element.static.gatherPreInfuseState = function () { return {}; }; /** * Get a jQuery function within a specific document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} context Context to bind the function to * @param {jQuery} [$iframe] HTML iframe element that contains the document, omit if document is * not in an iframe * @return {Function} Bound jQuery function */ OO.ui.Element.static.getJQuery = function ( context, $iframe ) { function wrapper( selector ) { return $( selector, wrapper.context ); } wrapper.context = this.getDocument( context ); if ( $iframe ) { wrapper.$iframe = $iframe; } return wrapper; }; /** * Get the document of an element. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Object to get the document for * @return {HTMLDocument|null} Document object */ OO.ui.Element.static.getDocument = function ( obj ) { // jQuery - selections created "offscreen" won't have a context, so .context isn't reliable return ( obj[ 0 ] && obj[ 0 ].ownerDocument ) || // Empty jQuery selections might have a context obj.context || // HTMLElement obj.ownerDocument || // Window obj.document || // HTMLDocument ( obj.nodeType === 9 && obj ) || null; }; /** * Get the window of an element or document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the window for * @return {Window} Window object */ OO.ui.Element.static.getWindow = function ( obj ) { var doc = this.getDocument( obj ); return doc.defaultView; }; /** * Get the direction of an element or document. * * @static * @param {jQuery|HTMLElement|HTMLDocument|Window} obj Context to get the direction for * @return {string} Text direction, either 'ltr' or 'rtl' */ OO.ui.Element.static.getDir = function ( obj ) { var isDoc, isWin; if ( obj instanceof jQuery ) { obj = obj[ 0 ]; } isDoc = obj.nodeType === 9; isWin = obj.document !== undefined; if ( isDoc || isWin ) { if ( isWin ) { obj = obj.document; } obj = obj.body; } return $( obj ).css( 'direction' ); }; /** * Get the offset between two frames. * * TODO: Make this function not use recursion. * * @static * @param {Window} from Window of the child frame * @param {Window} [to=window] Window of the parent frame * @param {Object} [offset] Offset to start with, used internally * @return {Object} Offset object, containing left and top properties */ OO.ui.Element.static.getFrameOffset = function ( from, to, offset ) { var i, len, frames, frame, rect; if ( !to ) { to = window; } if ( !offset ) { offset = { top: 0, left: 0 }; } if ( from.parent === from ) { return offset; } // Get iframe element frames = from.parent.document.getElementsByTagName( 'iframe' ); for ( i = 0, len = frames.length; i < len; i++ ) { if ( frames[ i ].contentWindow === from ) { frame = frames[ i ]; break; } } // Recursively accumulate offset values if ( frame ) { rect = frame.getBoundingClientRect(); offset.left += rect.left; offset.top += rect.top; if ( from !== to ) { this.getFrameOffset( from.parent, offset ); } } return offset; }; /** * Get the offset between two elements. * * The two elements may be in a different frame, but in that case the frame $element is in must * be contained in the frame $anchor is in. * * @static * @param {jQuery} $element Element whose position to get * @param {jQuery} $anchor Element to get $element's position relative to * @return {Object} Translated position coordinates, containing top and left properties */ OO.ui.Element.static.getRelativePosition = function ( $element, $anchor ) { var iframe, iframePos, pos = $element.offset(), anchorPos = $anchor.offset(), elementDocument = this.getDocument( $element ), anchorDocument = this.getDocument( $anchor ); // If $element isn't in the same document as $anchor, traverse up while ( elementDocument !== anchorDocument ) { iframe = elementDocument.defaultView.frameElement; if ( !iframe ) { throw new Error( '$element frame is not contained in $anchor frame' ); } iframePos = $( iframe ).offset(); pos.left += iframePos.left; pos.top += iframePos.top; elementDocument = iframe.ownerDocument; } pos.left -= anchorPos.left; pos.top -= anchorPos.top; return pos; }; /** * Get element border sizes. * * @static * @param {HTMLElement} el Element to measure * @return {Object} Dimensions object with `top`, `left`, `bottom` and `right` properties */ OO.ui.Element.static.getBorders = function ( el ) { var doc = el.ownerDocument, win = doc.defaultView, style = win.getComputedStyle( el, null ), $el = $( el ), top = parseFloat( style ? style.borderTopWidth : $el.css( 'borderTopWidth' ) ) || 0, left = parseFloat( style ? style.borderLeftWidth : $el.css( 'borderLeftWidth' ) ) || 0, bottom = parseFloat( style ? style.borderBottomWidth : $el.css( 'borderBottomWidth' ) ) || 0, right = parseFloat( style ? style.borderRightWidth : $el.css( 'borderRightWidth' ) ) || 0; return { top: top, left: left, bottom: bottom, right: right }; }; /** * Get dimensions of an element or window. * * @static * @param {HTMLElement|Window} el Element to measure * @return {Object} Dimensions object with `borders`, `scroll`, `scrollbar` and `rect` properties */ OO.ui.Element.static.getDimensions = function ( el ) { var $el, $win, doc = el.ownerDocument || el.document, win = doc.defaultView; if ( win === el || el === doc.documentElement ) { $win = $( win ); return { borders: { top: 0, left: 0, bottom: 0, right: 0 }, scroll: { top: $win.scrollTop(), left: $win.scrollLeft() }, scrollbar: { right: 0, bottom: 0 }, rect: { top: 0, left: 0, bottom: $win.innerHeight(), right: $win.innerWidth() } }; } else { $el = $( el ); return { borders: this.getBorders( el ), scroll: { top: $el.scrollTop(), left: $el.scrollLeft() }, scrollbar: { right: $el.innerWidth() - el.clientWidth, bottom: $el.innerHeight() - el.clientHeight }, rect: el.getBoundingClientRect() }; } }; /** * Get scrollable object parent * * documentElement can't be used to get or set the scrollTop * property on Blink. Changing and testing its value lets us * use 'body' or 'documentElement' based on what is working. * * https://code.google.com/p/chromium/issues/detail?id=303131 * * @static * @param {HTMLElement} el Element to find scrollable parent for * @return {HTMLElement} Scrollable parent */ OO.ui.Element.static.getRootScrollableElement = function ( el ) { var scrollTop, body; if ( OO.ui.scrollableElement === undefined ) { body = el.ownerDocument.body; scrollTop = body.scrollTop; body.scrollTop = 1; if ( body.scrollTop === 1 ) { body.scrollTop = scrollTop; OO.ui.scrollableElement = 'body'; } else { OO.ui.scrollableElement = 'documentElement'; } } return el.ownerDocument[ OO.ui.scrollableElement ]; }; /** * Get closest scrollable container. * * Traverses up until either a scrollable element or the root is reached, in which case the window * will be returned. * * @static * @param {HTMLElement} el Element to find scrollable container for * @param {string} [dimension] Dimension of scrolling to look for; `x`, `y` or omit for either * @return {HTMLElement} Closest scrollable container */ OO.ui.Element.static.getClosestScrollableContainer = function ( el, dimension ) { var i, val, // props = [ 'overflow' ] doesn't work due to https://bugzilla.mozilla.org/show_bug.cgi?id=889091 props = [ 'overflow-x', 'overflow-y' ], $parent = $( el ).parent(); if ( dimension === 'x' || dimension === 'y' ) { props = [ 'overflow-' + dimension ]; } while ( $parent.length ) { if ( $parent[ 0 ] === this.getRootScrollableElement( el ) ) { return $parent[ 0 ]; } i = props.length; while ( i-- ) { val = $parent.css( props[ i ] ); if ( val === 'auto' || val === 'scroll' ) { return $parent[ 0 ]; } } $parent = $parent.parent(); } return this.getDocument( el ).body; }; /** * Scroll element into view. * * @static * @param {HTMLElement} el Element to scroll into view * @param {Object} [config] Configuration options * @param {string} [config.duration='fast'] jQuery animation duration value * @param {string} [config.direction] Scroll in only one direction, e.g. 'x' or 'y', omit * to scroll in both directions * @param {Function} [config.complete] Function to call when scrolling completes. * Deprecated since 0.15.4, use the return promise instead. * @return {jQuery.Promise} Promise which resolves when the scroll is complete */ OO.ui.Element.static.scrollIntoView = function ( el, config ) { var position, animations, callback, container, $container, elementDimensions, containerDimensions, $window, deferred = $.Deferred(); // Configuration initialization config = config || {}; animations = {}; callback = typeof config.complete === 'function' && config.complete; container = this.getClosestScrollableContainer( el, config.direction ); $container = $( container ); elementDimensions = this.getDimensions( el ); containerDimensions = this.getDimensions( container ); $window = $( this.getWindow( el ) ); // Compute the element's position relative to the container if ( $container.is( 'html, body' ) ) { // If the scrollable container is the root, this is easy position = { top: elementDimensions.rect.top, bottom: $window.innerHeight() - elementDimensions.rect.bottom, left: elementDimensions.rect.left, right: $window.innerWidth() - elementDimensions.rect.right }; } else { // Otherwise, we have to subtract el's coordinates from container's coordinates position = { top: elementDimensions.rect.top - ( containerDimensions.rect.top + containerDimensions.borders.top ), bottom: containerDimensions.rect.bottom - containerDimensions.borders.bottom - containerDimensions.scrollbar.bottom - elementDimensions.rect.bottom, left: elementDimensions.rect.left - ( containerDimensions.rect.left + containerDimensions.borders.left ), right: containerDimensions.rect.right - containerDimensions.borders.right - containerDimensions.scrollbar.right - elementDimensions.rect.right }; } if ( !config.direction || config.direction === 'y' ) { if ( position.top < 0 ) { animations.scrollTop = containerDimensions.scroll.top + position.top; } else if ( position.top > 0 && position.bottom < 0 ) { animations.scrollTop = containerDimensions.scroll.top + Math.min( position.top, -position.bottom ); } } if ( !config.direction || config.direction === 'x' ) { if ( position.left < 0 ) { animations.scrollLeft = containerDimensions.scroll.left + position.left; } else if ( position.left > 0 && position.right < 0 ) { animations.scrollLeft = containerDimensions.scroll.left + Math.min( position.left, -position.right ); } } if ( !$.isEmptyObject( animations ) ) { $container.stop( true ).animate( animations, config.duration === undefined ? 'fast' : config.duration ); $container.queue( function ( next ) { if ( callback ) { callback(); } deferred.resolve(); next(); } ); } else { if ( callback ) { callback(); } deferred.resolve(); } return deferred.promise(); }; /** * Force the browser to reconsider whether it really needs to render scrollbars inside the element * and reserve space for them, because it probably doesn't. * * Workaround primarily for <https://code.google.com/p/chromium/issues/detail?id=387290>, but also * similar bugs in other browsers. "Just" forcing a reflow is not sufficient in all cases, we need * to first actually detach (or hide, but detaching is simpler) all children, *then* force a reflow, * and then reattach (or show) them back. * * @static * @param {HTMLElement} el Element to reconsider the scrollbars on */ OO.ui.Element.static.reconsiderScrollbars = function ( el ) { var i, len, scrollLeft, scrollTop, nodes = []; // Save scroll position scrollLeft = el.scrollLeft; scrollTop = el.scrollTop; // Detach all children while ( el.firstChild ) { nodes.push( el.firstChild ); el.removeChild( el.firstChild ); } // Force reflow void el.offsetHeight; // Reattach all children for ( i = 0, len = nodes.length; i < len; i++ ) { el.appendChild( nodes[ i ] ); } // Restore scroll position (no-op if scrollbars disappeared) el.scrollLeft = scrollLeft; el.scrollTop = scrollTop; }; /* Methods */ /** * Toggle visibility of an element. * * @param {boolean} [show] Make element visible, omit to toggle visibility * @fires visible * @chainable */ OO.ui.Element.prototype.toggle = function ( show ) { show = show === undefined ? !this.visible : !!show; if ( show !== this.isVisible() ) { this.visible = show; this.$element.toggleClass( 'oo-ui-element-hidden', !this.visible ); this.emit( 'toggle', show ); } return this; }; /** * Check if element is visible. * * @return {boolean} element is visible */ OO.ui.Element.prototype.isVisible = function () { return this.visible; }; /** * Get element data. * * @return {Mixed} Element data */ OO.ui.Element.prototype.getData = function () { return this.data; }; /** * Set element data. * * @param {Mixed} data Element data * @chainable */ OO.ui.Element.prototype.setData = function ( data ) { this.data = data; return this; }; /** * Check if element supports one or more methods. * * @param {string|string[]} methods Method or list of methods to check * @return {boolean} All methods are supported */ OO.ui.Element.prototype.supports = function ( methods ) { var i, len, support = 0; methods = Array.isArray( methods ) ? methods : [ methods ]; for ( i = 0, len = methods.length; i < len; i++ ) { if ( $.isFunction( this[ methods[ i ] ] ) ) { support++; } } return methods.length === support; }; /** * Update the theme-provided classes. * * @localdoc This is called in element mixins and widget classes any time state changes. * Updating is debounced, minimizing overhead of changing multiple attributes and * guaranteeing that theme updates do not occur within an element's constructor */ OO.ui.Element.prototype.updateThemeClasses = function () { this.debouncedUpdateThemeClassesHandler(); }; /** * @private * @localdoc This method is called directly from the QUnit tests instead of #updateThemeClasses, to * make them synchronous. */ OO.ui.Element.prototype.debouncedUpdateThemeClasses = function () { OO.ui.theme.updateElementClasses( this ); }; /** * Get the HTML tag name. * * Override this method to base the result on instance information. * * @return {string} HTML tag name */ OO.ui.Element.prototype.getTagName = function () { return this.constructor.static.tagName; }; /** * Check if the element is attached to the DOM * * @return {boolean} The element is attached to the DOM */ OO.ui.Element.prototype.isElementAttached = function () { return $.contains( this.getElementDocument(), this.$element[ 0 ] ); }; /** * Get the DOM document. * * @return {HTMLDocument} Document object */ OO.ui.Element.prototype.getElementDocument = function () { // Don't cache this in other ways either because subclasses could can change this.$element return OO.ui.Element.static.getDocument( this.$element ); }; /** * Get the DOM window. * * @return {Window} Window object */ OO.ui.Element.prototype.getElementWindow = function () { return OO.ui.Element.static.getWindow( this.$element ); }; /** * Get closest scrollable container. * * @return {HTMLElement} Closest scrollable container */ OO.ui.Element.prototype.getClosestScrollableElementContainer = function () { return OO.ui.Element.static.getClosestScrollableContainer( this.$element[ 0 ] ); }; /** * Get group element is in. * * @return {OO.ui.mixin.GroupElement|null} Group element, null if none */ OO.ui.Element.prototype.getElementGroup = function () { return this.elementGroup; }; /** * Set group element is in. * * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none * @chainable */ OO.ui.Element.prototype.setElementGroup = function ( group ) { this.elementGroup = group; return this; }; /** * Scroll element into view. * * @param {Object} [config] Configuration options * @return {jQuery.Promise} Promise which resolves when the scroll is complete */ OO.ui.Element.prototype.scrollElementIntoView = function ( config ) { if ( !this.isElementAttached() || !this.isVisible() || ( this.getElementGroup() && !this.getElementGroup().isVisible() ) ) { return $.Deferred().resolve(); } return OO.ui.Element.static.scrollIntoView( this.$element[ 0 ], config ); }; /** * Restore the pre-infusion dynamic state for this widget. * * This method is called after #$element has been inserted into DOM. The parameter is the return * value of #gatherPreInfuseState. * * @protected * @param {Object} state */ OO.ui.Element.prototype.restorePreInfuseState = function () { }; /** * Wraps an HTML snippet for use with configuration values which default * to strings. This bypasses the default html-escaping done to string * values. * * @class * * @constructor * @param {string} [content] HTML content */ OO.ui.HtmlSnippet = function OoUiHtmlSnippet( content ) { // Properties this.content = content; }; /* Setup */ OO.initClass( OO.ui.HtmlSnippet ); /* Methods */ /** * Render into HTML. * * @return {string} Unchanged HTML snippet. */ OO.ui.HtmlSnippet.prototype.toString = function () { return this.content; }; /** * Layouts are containers for elements and are used to arrange other widgets of arbitrary type in a way * that is centrally controlled and can be updated dynamically. Layouts can be, and usually are, combined. * See {@link OO.ui.FieldsetLayout FieldsetLayout}, {@link OO.ui.FieldLayout FieldLayout}, {@link OO.ui.FormLayout FormLayout}, * {@link OO.ui.PanelLayout PanelLayout}, {@link OO.ui.StackLayout StackLayout}, {@link OO.ui.PageLayout PageLayout}, * {@link OO.ui.HorizontalLayout HorizontalLayout}, and {@link OO.ui.BookletLayout BookletLayout} for more information and examples. * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options */ OO.ui.Layout = function OoUiLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.Layout.parent.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Initialization this.$element.addClass( 'oo-ui-layout' ); }; /* Setup */ OO.inheritClass( OO.ui.Layout, OO.ui.Element ); OO.mixinClass( OO.ui.Layout, OO.EventEmitter ); /** * Widgets are compositions of one or more OOjs UI elements that users can both view * and interact with. All widgets can be configured and modified via a standard API, * and their state can change dynamically according to a model. * * @abstract * @class * @extends OO.ui.Element * @mixins OO.EventEmitter * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [disabled=false] Disable the widget. Disabled widgets cannot be used and their * appearance reflects this state. */ OO.ui.Widget = function OoUiWidget( config ) { // Initialize config config = $.extend( { disabled: false }, config ); // Parent constructor OO.ui.Widget.parent.call( this, config ); // Mixin constructors OO.EventEmitter.call( this ); // Properties this.disabled = null; this.wasDisabled = null; // Initialization this.$element.addClass( 'oo-ui-widget' ); this.setDisabled( !!config.disabled ); }; /* Setup */ OO.inheritClass( OO.ui.Widget, OO.ui.Element ); OO.mixinClass( OO.ui.Widget, OO.EventEmitter ); /* Static Properties */ /** * Whether this widget will behave reasonably when wrapped in a HTML `<label>`. If this is true, * wrappers such as OO.ui.FieldLayout may use a `<label>` instead of implementing own label click * handling. * * @static * @inheritable * @property {boolean} */ OO.ui.Widget.static.supportsSimpleLabel = false; /* Events */ /** * @event disable * * A 'disable' event is emitted when the disabled state of the widget changes * (i.e. on disable **and** enable). * * @param {boolean} disabled Widget is disabled */ /** * @event toggle * * A 'toggle' event is emitted when the visibility of the widget changes. * * @param {boolean} visible Widget is visible */ /* Methods */ /** * Check if the widget is disabled. * * @return {boolean} Widget is disabled */ OO.ui.Widget.prototype.isDisabled = function () { return this.disabled; }; /** * Set the 'disabled' state of the widget. * * When a widget is disabled, it cannot be used and its appearance is updated to reflect this state. * * @param {boolean} disabled Disable widget * @chainable */ OO.ui.Widget.prototype.setDisabled = function ( disabled ) { var isDisabled; this.disabled = !!disabled; isDisabled = this.isDisabled(); if ( isDisabled !== this.wasDisabled ) { this.$element.toggleClass( 'oo-ui-widget-disabled', isDisabled ); this.$element.toggleClass( 'oo-ui-widget-enabled', !isDisabled ); this.$element.attr( 'aria-disabled', isDisabled.toString() ); this.emit( 'disable', isDisabled ); this.updateThemeClasses(); } this.wasDisabled = isDisabled; return this; }; /** * Update the disabled state, in case of changes in parent widget. * * @chainable */ OO.ui.Widget.prototype.updateDisabled = function () { this.setDisabled( this.disabled ); return this; }; /** * Theme logic. * * @abstract * @class * * @constructor */ OO.ui.Theme = function OoUiTheme() {}; /* Setup */ OO.initClass( OO.ui.Theme ); /* Methods */ /** * Get a list of classes to be applied to a widget. * * The 'on' and 'off' lists combined MUST contain keys for all classes the theme adds or removes, * otherwise state transitions will not work properly. * * @param {OO.ui.Element} element Element for which to get classes * @return {Object.<string,string[]>} Categorized class names with `on` and `off` lists */ OO.ui.Theme.prototype.getElementClasses = function () { return { on: [], off: [] }; }; /** * Update CSS classes provided by the theme. * * For elements with theme logic hooks, this should be called any time there's a state change. * * @param {OO.ui.Element} element Element for which to update classes */ OO.ui.Theme.prototype.updateElementClasses = function ( element ) { var $elements = $( [] ), classes = this.getElementClasses( element ); if ( element.$icon ) { $elements = $elements.add( element.$icon ); } if ( element.$indicator ) { $elements = $elements.add( element.$indicator ); } $elements .removeClass( classes.off.join( ' ' ) ) .addClass( classes.on.join( ' ' ) ); }; /** * Get the transition duration in milliseconds for dialogs opening/closing * * The dialog should be fully rendered this many milliseconds after the * ready process has executed. * * @return {number} Transition duration in milliseconds */ OO.ui.Theme.prototype.getDialogTransitionDuration = function () { return 0; }; /** * The TabIndexedElement class is an attribute mixin used to add additional functionality to an * element created by another class. The mixin provides a ‘tabIndex’ property, which specifies the * order in which users will navigate through the focusable elements via the "tab" key. * * @example * // TabIndexedElement is mixed into the ButtonWidget class * // to provide a tabIndex property. * var button1 = new OO.ui.ButtonWidget( { * label: 'fourth', * tabIndex: 4 * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'second', * tabIndex: 2 * } ); * var button3 = new OO.ui.ButtonWidget( { * label: 'third', * tabIndex: 3 * } ); * var button4 = new OO.ui.ButtonWidget( { * label: 'first', * tabIndex: 1 * } ); * $( 'body' ).append( button1.$element, button2.$element, button3.$element, button4.$element ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$tabIndexed] The element that should use the tabindex functionality. By default, * the functionality is applied to the element created by the class ($element). If a different element is specified, the tabindex * functionality will be applied to it instead. * @cfg {number|null} [tabIndex=0] Number that specifies the element’s position in the tab-navigation * order (e.g., 1 for the first focusable element). Use 0 to use the default navigation order; use -1 * to remove the element from the tab-navigation flow. */ OO.ui.mixin.TabIndexedElement = function OoUiMixinTabIndexedElement( config ) { // Configuration initialization config = $.extend( { tabIndex: 0 }, config ); // Properties this.$tabIndexed = null; this.tabIndex = null; // Events this.connect( this, { disable: 'onTabIndexedElementDisable' } ); // Initialization this.setTabIndex( config.tabIndex ); this.setTabIndexedElement( config.$tabIndexed || this.$element ); }; /* Setup */ OO.initClass( OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * Set the element that should use the tabindex functionality. * * This method is used to retarget a tabindex mixin so that its functionality applies * to the specified element. If an element is currently using the functionality, the mixin’s * effect on that element is removed before the new element is set up. * * @param {jQuery} $tabIndexed Element that should use the tabindex functionality * @chainable */ OO.ui.mixin.TabIndexedElement.prototype.setTabIndexedElement = function ( $tabIndexed ) { var tabIndex = this.tabIndex; // Remove attributes from old $tabIndexed this.setTabIndex( null ); // Force update of new $tabIndexed this.$tabIndexed = $tabIndexed; this.tabIndex = tabIndex; return this.updateTabIndex(); }; /** * Set the value of the tabindex. * * @param {number|null} tabIndex Tabindex value, or `null` for no tabindex * @chainable */ OO.ui.mixin.TabIndexedElement.prototype.setTabIndex = function ( tabIndex ) { tabIndex = typeof tabIndex === 'number' ? tabIndex : null; if ( this.tabIndex !== tabIndex ) { this.tabIndex = tabIndex; this.updateTabIndex(); } return this; }; /** * Update the `tabindex` attribute, in case of changes to tab index or * disabled state. * * @private * @chainable */ OO.ui.mixin.TabIndexedElement.prototype.updateTabIndex = function () { if ( this.$tabIndexed ) { if ( this.tabIndex !== null ) { // Do not index over disabled elements this.$tabIndexed.attr( { tabindex: this.isDisabled() ? -1 : this.tabIndex, // Support: ChromeVox and NVDA // These do not seem to inherit aria-disabled from parent elements 'aria-disabled': this.isDisabled().toString() } ); } else { this.$tabIndexed.removeAttr( 'tabindex aria-disabled' ); } } return this; }; /** * Handle disable events. * * @private * @param {boolean} disabled Element is disabled */ OO.ui.mixin.TabIndexedElement.prototype.onTabIndexedElementDisable = function () { this.updateTabIndex(); }; /** * Get the value of the tabindex. * * @return {number|null} Tabindex value */ OO.ui.mixin.TabIndexedElement.prototype.getTabIndex = function () { return this.tabIndex; }; /** * ButtonElement is often mixed into other classes to generate a button, which is a clickable * interface element that can be configured with access keys for accessibility. * See the [OOjs UI documentation on MediaWiki] [1] for examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches#Buttons * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$button] The button element created by the class. * If this configuration is omitted, the button element will use a generated `<a>`. * @cfg {boolean} [framed=true] Render the button with a frame */ OO.ui.mixin.ButtonElement = function OoUiMixinButtonElement( config ) { // Configuration initialization config = config || {}; // Properties this.$button = null; this.framed = null; this.active = config.active !== undefined && config.active; this.onMouseUpHandler = this.onMouseUp.bind( this ); this.onMouseDownHandler = this.onMouseDown.bind( this ); this.onKeyDownHandler = this.onKeyDown.bind( this ); this.onKeyUpHandler = this.onKeyUp.bind( this ); this.onClickHandler = this.onClick.bind( this ); this.onKeyPressHandler = this.onKeyPress.bind( this ); // Initialization this.$element.addClass( 'oo-ui-buttonElement' ); this.toggleFramed( config.framed === undefined || config.framed ); this.setButtonElement( config.$button || $( '<a>' ) ); }; /* Setup */ OO.initClass( OO.ui.mixin.ButtonElement ); /* Static Properties */ /** * Cancel mouse down events. * * This property is usually set to `true` to prevent the focus from changing when the button is clicked. * Classes such as {@link OO.ui.mixin.DraggableElement DraggableElement} and {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} * use a value of `false` so that dragging behavior is possible and mousedown events can be handled by a * parent widget. * * @static * @inheritable * @property {boolean} */ OO.ui.mixin.ButtonElement.static.cancelButtonMouseDownEvents = true; /* Events */ /** * A 'click' event is emitted when the button element is clicked. * * @event click */ /* Methods */ /** * Set the button element. * * This method is used to retarget a button mixin so that its functionality applies to * the specified button element instead of the one created by the class. If a button element * is already set, the method will remove the mixin’s effect on that element. * * @param {jQuery} $button Element to use as button */ OO.ui.mixin.ButtonElement.prototype.setButtonElement = function ( $button ) { if ( this.$button ) { this.$button .removeClass( 'oo-ui-buttonElement-button' ) .removeAttr( 'role accesskey' ) .off( { mousedown: this.onMouseDownHandler, keydown: this.onKeyDownHandler, click: this.onClickHandler, keypress: this.onKeyPressHandler } ); } this.$button = $button .addClass( 'oo-ui-buttonElement-button' ) .on( { mousedown: this.onMouseDownHandler, keydown: this.onKeyDownHandler, click: this.onClickHandler, keypress: this.onKeyPressHandler } ); // Add `role="button"` on `<a>` elements, where it's needed // `toUppercase()` is added for XHTML documents if ( this.$button.prop( 'tagName' ).toUpperCase() === 'A' ) { this.$button.attr( 'role', 'button' ); } }; /** * Handles mouse down events. * * @protected * @param {jQuery.Event} e Mouse down event */ OO.ui.mixin.ButtonElement.prototype.onMouseDown = function ( e ) { if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) { return; } this.$element.addClass( 'oo-ui-buttonElement-pressed' ); // Run the mouseup handler no matter where the mouse is when the button is let go, so we can // reliably remove the pressed class this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true ); // Prevent change of focus unless specifically configured otherwise if ( this.constructor.static.cancelButtonMouseDownEvents ) { return false; } }; /** * Handles mouse up events. * * @protected * @param {MouseEvent} e Mouse up event */ OO.ui.mixin.ButtonElement.prototype.onMouseUp = function ( e ) { if ( this.isDisabled() || e.which !== OO.ui.MouseButtons.LEFT ) { return; } this.$element.removeClass( 'oo-ui-buttonElement-pressed' ); // Stop listening for mouseup, since we only needed this once this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true ); }; /** * Handles mouse click events. * * @protected * @param {jQuery.Event} e Mouse click event * @fires click */ OO.ui.mixin.ButtonElement.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) { if ( this.emit( 'click' ) ) { return false; } } }; /** * Handles key down events. * * @protected * @param {jQuery.Event} e Key down event */ OO.ui.mixin.ButtonElement.prototype.onKeyDown = function ( e ) { if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) { return; } this.$element.addClass( 'oo-ui-buttonElement-pressed' ); // Run the keyup handler no matter where the key is when the button is let go, so we can // reliably remove the pressed class this.getElementDocument().addEventListener( 'keyup', this.onKeyUpHandler, true ); }; /** * Handles key up events. * * @protected * @param {KeyboardEvent} e Key up event */ OO.ui.mixin.ButtonElement.prototype.onKeyUp = function ( e ) { if ( this.isDisabled() || ( e.which !== OO.ui.Keys.SPACE && e.which !== OO.ui.Keys.ENTER ) ) { return; } this.$element.removeClass( 'oo-ui-buttonElement-pressed' ); // Stop listening for keyup, since we only needed this once this.getElementDocument().removeEventListener( 'keyup', this.onKeyUpHandler, true ); }; /** * Handles key press events. * * @protected * @param {jQuery.Event} e Key press event * @fires click */ OO.ui.mixin.ButtonElement.prototype.onKeyPress = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.ENTER ) ) { if ( this.emit( 'click' ) ) { return false; } } }; /** * Check if button has a frame. * * @return {boolean} Button is framed */ OO.ui.mixin.ButtonElement.prototype.isFramed = function () { return this.framed; }; /** * Render the button with or without a frame. Omit the `framed` parameter to toggle the button frame on and off. * * @param {boolean} [framed] Make button framed, omit to toggle * @chainable */ OO.ui.mixin.ButtonElement.prototype.toggleFramed = function ( framed ) { framed = framed === undefined ? !this.framed : !!framed; if ( framed !== this.framed ) { this.framed = framed; this.$element .toggleClass( 'oo-ui-buttonElement-frameless', !framed ) .toggleClass( 'oo-ui-buttonElement-framed', framed ); this.updateThemeClasses(); } return this; }; /** * Set the button's active state. * * The active state can be set on: * * - {@link OO.ui.ButtonOptionWidget ButtonOptionWidget} when it is selected * - {@link OO.ui.ToggleButtonWidget ToggleButtonWidget} when it is toggle on * - {@link OO.ui.ButtonWidget ButtonWidget} when clicking the button would only refresh the page * * @protected * @param {boolean} value Make button active * @chainable */ OO.ui.mixin.ButtonElement.prototype.setActive = function ( value ) { this.active = !!value; this.$element.toggleClass( 'oo-ui-buttonElement-active', this.active ); this.updateThemeClasses(); return this; }; /** * Check if the button is active * * @protected * @return {boolean} The button is active */ OO.ui.mixin.ButtonElement.prototype.isActive = function () { return this.active; }; /** * Any OOjs UI widget that contains other widgets (such as {@link OO.ui.ButtonWidget buttons} or * {@link OO.ui.OptionWidget options}) mixes in GroupElement. Adding, removing, and clearing * items from the group is done through the interface the class provides. * For more information, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Groups * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$group] The container element created by the class. If this configuration * is omitted, the group element will use a generated `<div>`. */ OO.ui.mixin.GroupElement = function OoUiMixinGroupElement( config ) { // Configuration initialization config = config || {}; // Properties this.$group = null; this.items = []; this.aggregateItemEvents = {}; // Initialization this.setGroupElement( config.$group || $( '<div>' ) ); }; /* Events */ /** * @event change * * A change event is emitted when the set of selected items changes. * * @param {OO.ui.Element[]} items Items currently in the group */ /* Methods */ /** * Set the group element. * * If an element is already set, items will be moved to the new element. * * @param {jQuery} $group Element to use as group */ OO.ui.mixin.GroupElement.prototype.setGroupElement = function ( $group ) { var i, len; this.$group = $group; for ( i = 0, len = this.items.length; i < len; i++ ) { this.$group.append( this.items[ i ].$element ); } }; /** * Check if a group contains no items. * * @return {boolean} Group is empty */ OO.ui.mixin.GroupElement.prototype.isEmpty = function () { return !this.items.length; }; /** * Get all items in the group. * * The method returns an array of item references (e.g., [button1, button2, button3]) and is useful * when synchronizing groups of items, or whenever the references are required (e.g., when removing items * from a group). * * @return {OO.ui.Element[]} An array of items. */ OO.ui.mixin.GroupElement.prototype.getItems = function () { return this.items.slice( 0 ); }; /** * Get an item by its data. * * Only the first item with matching data will be returned. To return all matching items, * use the #getItemsFromData method. * * @param {Object} data Item data to search for * @return {OO.ui.Element|null} Item with equivalent data, `null` if none exists */ OO.ui.mixin.GroupElement.prototype.getItemFromData = function ( data ) { var i, len, item, hash = OO.getHash( data ); for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( hash === OO.getHash( item.getData() ) ) { return item; } } return null; }; /** * Get items by their data. * * All items with matching data will be returned. To return only the first match, use the #getItemFromData method instead. * * @param {Object} data Item data to search for * @return {OO.ui.Element[]} Items with equivalent data */ OO.ui.mixin.GroupElement.prototype.getItemsFromData = function ( data ) { var i, len, item, hash = OO.getHash( data ), items = []; for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( hash === OO.getHash( item.getData() ) ) { items.push( item ); } } return items; }; /** * Aggregate the events emitted by the group. * * When events are aggregated, the group will listen to all contained items for the event, * and then emit the event under a new name. The new event will contain an additional leading * parameter containing the item that emitted the original event. Other arguments emitted from * the original event are passed through. * * @param {Object.<string,string|null>} events An object keyed by the name of the event that should be * aggregated (e.g., ‘click’) and the value of the new name to use (e.g., ‘groupClick’). * A `null` value will remove aggregated events. * @throws {Error} An error is thrown if aggregation already exists. */ OO.ui.mixin.GroupElement.prototype.aggregate = function ( events ) { var i, len, item, add, remove, itemEvent, groupEvent; for ( itemEvent in events ) { groupEvent = events[ itemEvent ]; // Remove existing aggregated event if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) { // Don't allow duplicate aggregations if ( groupEvent ) { throw new Error( 'Duplicate item event aggregation for ' + itemEvent ); } // Remove event aggregation from existing items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect ) { remove = {}; remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; item.disconnect( this, remove ); } } // Prevent future items from aggregating event delete this.aggregateItemEvents[ itemEvent ]; } // Add new aggregate event if ( groupEvent ) { // Make future items aggregate event this.aggregateItemEvents[ itemEvent ] = groupEvent; // Add event aggregation to existing items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect ) { add = {}; add[ itemEvent ] = [ 'emit', groupEvent, item ]; item.connect( this, add ); } } } } }; /** * Add items to the group. * * Items will be added to the end of the group array unless the optional `index` parameter specifies * a different insertion point. Adding an existing item will move it to the end of the array or the point specified by the `index`. * * @param {OO.ui.Element[]} items An array of items to add to the group * @param {number} [index] Index of the insertion point * @chainable */ OO.ui.mixin.GroupElement.prototype.addItems = function ( items, index ) { var i, len, item, itemEvent, events, currentIndex, itemElements = []; for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; // Check if item exists then remove it first, effectively "moving" it currentIndex = this.items.indexOf( item ); if ( currentIndex >= 0 ) { this.removeItems( [ item ] ); // Adjust index to compensate for removal if ( currentIndex < index ) { index--; } } // Add the item if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { events = {}; for ( itemEvent in this.aggregateItemEvents ) { events[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; } item.connect( this, events ); } item.setElementGroup( this ); itemElements.push( item.$element.get( 0 ) ); } if ( index === undefined || index < 0 || index >= this.items.length ) { this.$group.append( itemElements ); this.items.push.apply( this.items, items ); } else if ( index === 0 ) { this.$group.prepend( itemElements ); this.items.unshift.apply( this.items, items ); } else { this.items[ index ].$element.before( itemElements ); this.items.splice.apply( this.items, [ index, 0 ].concat( items ) ); } this.emit( 'change', this.getItems() ); return this; }; /** * Remove the specified items from a group. * * Removed items are detached (not removed) from the DOM so that they may be reused. * To remove all items from a group, you may wish to use the #clearItems method instead. * * @param {OO.ui.Element[]} items An array of items to remove * @chainable */ OO.ui.mixin.GroupElement.prototype.removeItems = function ( items ) { var i, len, item, index, events, itemEvent; // Remove specific items for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; index = this.items.indexOf( item ); if ( index !== -1 ) { if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { events = {}; for ( itemEvent in this.aggregateItemEvents ) { events[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; } item.disconnect( this, events ); } item.setElementGroup( null ); this.items.splice( index, 1 ); item.$element.detach(); } } this.emit( 'change', this.getItems() ); return this; }; /** * Clear all items from the group. * * Cleared items are detached from the DOM, not removed, so that they may be reused. * To remove only a subset of items from a group, use the #removeItems method. * * @chainable */ OO.ui.mixin.GroupElement.prototype.clearItems = function () { var i, len, item, remove, itemEvent; // Remove all items for ( i = 0, len = this.items.length; i < len; i++ ) { item = this.items[ i ]; if ( item.connect && item.disconnect && !$.isEmptyObject( this.aggregateItemEvents ) ) { remove = {}; if ( Object.prototype.hasOwnProperty.call( this.aggregateItemEvents, itemEvent ) ) { remove[ itemEvent ] = [ 'emit', this.aggregateItemEvents[ itemEvent ], item ]; } item.disconnect( this, remove ); } item.setElementGroup( null ); item.$element.detach(); } this.emit( 'change', this.getItems() ); this.items = []; return this; }; /** * IconElement is often mixed into other classes to generate an icon. * Icons are graphics, about the size of normal text. They are used to aid the user * in locating a control or to convey information in a space-efficient way. See the * [OOjs UI documentation on MediaWiki] [1] for a list of icons * included in the library. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$icon] The icon element created by the class. If this configuration is omitted, * the icon element will use a generated `<span>`. To use a different HTML tag, or to specify that * the icon element be set to an existing icon instead of the one generated by this class, set a * value using a jQuery selection. For example: * * // Use a <div> tag instead of a <span> * $icon: $("<div>") * // Use an existing icon element instead of the one generated by the class * $icon: this.$element * // Use an icon element from a child widget * $icon: this.childwidget.$element * @cfg {Object|string} [icon=''] The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of * symbolic names. A map is used for i18n purposes and contains a `default` icon * name and additional names keyed by language code. The `default` name is used when no icon is keyed * by the user's language. * * Example of an i18n map: * * { default: 'bold-a', en: 'bold-b', de: 'bold-f' } * See the [OOjs UI documentation on MediaWiki] [2] for a list of icons included in the library. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * @cfg {string|Function} [iconTitle] A text string used as the icon title, or a function that returns title * text. The icon title is displayed when users move the mouse over the icon. */ OO.ui.mixin.IconElement = function OoUiMixinIconElement( config ) { // Configuration initialization config = config || {}; // Properties this.$icon = null; this.icon = null; this.iconTitle = null; // Initialization this.setIcon( config.icon || this.constructor.static.icon ); this.setIconTitle( config.iconTitle || this.constructor.static.iconTitle ); this.setIconElement( config.$icon || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.mixin.IconElement ); /* Static Properties */ /** * The symbolic name of the icon (e.g., ‘remove’ or ‘menu’), or a map of symbolic names. A map is used * for i18n purposes and contains a `default` icon name and additional names keyed by * language code. The `default` name is used when no icon is keyed by the user's language. * * Example of an i18n map: * * { default: 'bold-a', en: 'bold-b', de: 'bold-f' } * * Note: the static property will be overridden if the #icon configuration is used. * * @static * @inheritable * @property {Object|string} */ OO.ui.mixin.IconElement.static.icon = null; /** * The icon title, displayed when users move the mouse over the icon. The value can be text, a * function that returns title text, or `null` for no title. * * The static property will be overridden if the #iconTitle configuration is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.IconElement.static.iconTitle = null; /* Methods */ /** * Set the icon element. This method is used to retarget an icon mixin so that its functionality * applies to the specified icon element instead of the one created by the class. If an icon * element is already set, the mixin’s effect on that element is removed. Generated CSS classes * and mixin methods will no longer affect the element. * * @param {jQuery} $icon Element to use as icon */ OO.ui.mixin.IconElement.prototype.setIconElement = function ( $icon ) { if ( this.$icon ) { this.$icon .removeClass( 'oo-ui-iconElement-icon oo-ui-icon-' + this.icon ) .removeAttr( 'title' ); } this.$icon = $icon .addClass( 'oo-ui-iconElement-icon' ) .toggleClass( 'oo-ui-icon-' + this.icon, !!this.icon ); if ( this.iconTitle !== null ) { this.$icon.attr( 'title', this.iconTitle ); } this.updateThemeClasses(); }; /** * Set icon by symbolic name (e.g., ‘remove’ or ‘menu’). Use `null` to remove an icon. * The icon parameter can also be set to a map of icon names. See the #icon config setting * for an example. * * @param {Object|string|null} icon A symbolic icon name, a {@link #icon map of icon names} keyed * by language code, or `null` to remove the icon. * @chainable */ OO.ui.mixin.IconElement.prototype.setIcon = function ( icon ) { icon = OO.isPlainObject( icon ) ? OO.ui.getLocalValue( icon, null, 'default' ) : icon; icon = typeof icon === 'string' && icon.trim().length ? icon.trim() : null; if ( this.icon !== icon ) { if ( this.$icon ) { if ( this.icon !== null ) { this.$icon.removeClass( 'oo-ui-icon-' + this.icon ); } if ( icon !== null ) { this.$icon.addClass( 'oo-ui-icon-' + icon ); } } this.icon = icon; } this.$element.toggleClass( 'oo-ui-iconElement', !!this.icon ); this.updateThemeClasses(); return this; }; /** * Set the icon title. Use `null` to remove the title. * * @param {string|Function|null} iconTitle A text string used as the icon title, * a function that returns title text, or `null` for no title. * @chainable */ OO.ui.mixin.IconElement.prototype.setIconTitle = function ( iconTitle ) { iconTitle = typeof iconTitle === 'function' || ( typeof iconTitle === 'string' && iconTitle.length ) ? OO.ui.resolveMsg( iconTitle ) : null; if ( this.iconTitle !== iconTitle ) { this.iconTitle = iconTitle; if ( this.$icon ) { if ( this.iconTitle !== null ) { this.$icon.attr( 'title', iconTitle ); } else { this.$icon.removeAttr( 'title' ); } } } return this; }; /** * Get the symbolic name of the icon. * * @return {string} Icon name */ OO.ui.mixin.IconElement.prototype.getIcon = function () { return this.icon; }; /** * Get the icon title. The title text is displayed when a user moves the mouse over the icon. * * @return {string} Icon title text */ OO.ui.mixin.IconElement.prototype.getIconTitle = function () { return this.iconTitle; }; /** * IndicatorElement is often mixed into other classes to generate an indicator. * Indicators are small graphics that are generally used in two ways: * * - To draw attention to the status of an item. For example, an indicator might be * used to show that an item in a list has errors that need to be resolved. * - To clarify the function of a control that acts in an exceptional way (a button * that opens a menu instead of performing an action directly, for example). * * For a list of indicators included in the library, please see the * [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$indicator] The indicator element created by the class. If this * configuration is omitted, the indicator element will use a generated `<span>`. * @cfg {string} [indicator] Symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * See the [OOjs UI documentation on MediaWiki][2] for a list of indicators included * in the library. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * @cfg {string|Function} [indicatorTitle] A text string used as the indicator title, * or a function that returns title text. The indicator title is displayed when users move * the mouse over the indicator. */ OO.ui.mixin.IndicatorElement = function OoUiMixinIndicatorElement( config ) { // Configuration initialization config = config || {}; // Properties this.$indicator = null; this.indicator = null; this.indicatorTitle = null; // Initialization this.setIndicator( config.indicator || this.constructor.static.indicator ); this.setIndicatorTitle( config.indicatorTitle || this.constructor.static.indicatorTitle ); this.setIndicatorElement( config.$indicator || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.mixin.IndicatorElement ); /* Static Properties */ /** * Symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * The static property will be overridden if the #indicator configuration is used. * * @static * @inheritable * @property {string|null} */ OO.ui.mixin.IndicatorElement.static.indicator = null; /** * A text string used as the indicator title, a function that returns title text, or `null` * for no title. The static property will be overridden if the #indicatorTitle configuration is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.IndicatorElement.static.indicatorTitle = null; /* Methods */ /** * Set the indicator element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $indicator Element to use as indicator */ OO.ui.mixin.IndicatorElement.prototype.setIndicatorElement = function ( $indicator ) { if ( this.$indicator ) { this.$indicator .removeClass( 'oo-ui-indicatorElement-indicator oo-ui-indicator-' + this.indicator ) .removeAttr( 'title' ); } this.$indicator = $indicator .addClass( 'oo-ui-indicatorElement-indicator' ) .toggleClass( 'oo-ui-indicator-' + this.indicator, !!this.indicator ); if ( this.indicatorTitle !== null ) { this.$indicator.attr( 'title', this.indicatorTitle ); } this.updateThemeClasses(); }; /** * Set the indicator by its symbolic name: ‘alert’, ‘down’, ‘next’, ‘previous’, ‘required’, ‘up’. Use `null` to remove the indicator. * * @param {string|null} indicator Symbolic name of indicator, or `null` for no indicator * @chainable */ OO.ui.mixin.IndicatorElement.prototype.setIndicator = function ( indicator ) { indicator = typeof indicator === 'string' && indicator.length ? indicator.trim() : null; if ( this.indicator !== indicator ) { if ( this.$indicator ) { if ( this.indicator !== null ) { this.$indicator.removeClass( 'oo-ui-indicator-' + this.indicator ); } if ( indicator !== null ) { this.$indicator.addClass( 'oo-ui-indicator-' + indicator ); } } this.indicator = indicator; } this.$element.toggleClass( 'oo-ui-indicatorElement', !!this.indicator ); this.updateThemeClasses(); return this; }; /** * Set the indicator title. * * The title is displayed when a user moves the mouse over the indicator. * * @param {string|Function|null} indicatorTitle Indicator title text, a function that returns text, or * `null` for no indicator title * @chainable */ OO.ui.mixin.IndicatorElement.prototype.setIndicatorTitle = function ( indicatorTitle ) { indicatorTitle = typeof indicatorTitle === 'function' || ( typeof indicatorTitle === 'string' && indicatorTitle.length ) ? OO.ui.resolveMsg( indicatorTitle ) : null; if ( this.indicatorTitle !== indicatorTitle ) { this.indicatorTitle = indicatorTitle; if ( this.$indicator ) { if ( this.indicatorTitle !== null ) { this.$indicator.attr( 'title', indicatorTitle ); } else { this.$indicator.removeAttr( 'title' ); } } } return this; }; /** * Get the symbolic name of the indicator (e.g., ‘alert’ or ‘down’). * * @return {string} Symbolic name of indicator */ OO.ui.mixin.IndicatorElement.prototype.getIndicator = function () { return this.indicator; }; /** * Get the indicator title. * * The title is displayed when a user moves the mouse over the indicator. * * @return {string} Indicator title text */ OO.ui.mixin.IndicatorElement.prototype.getIndicatorTitle = function () { return this.indicatorTitle; }; /** * LabelElement is often mixed into other classes to generate a label, which * helps identify the function of an interface element. * See the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$label] The label element created by the class. If this * configuration is omitted, the label element will use a generated `<span>`. * @cfg {jQuery|string|Function|OO.ui.HtmlSnippet} [label] The label text. The label can be specified * as a plaintext string, a jQuery selection of elements, or a function that will produce a string * in the future. See the [OOjs UI documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Labels */ OO.ui.mixin.LabelElement = function OoUiMixinLabelElement( config ) { // Configuration initialization config = config || {}; // Properties this.$label = null; this.label = null; // Initialization this.setLabel( config.label || this.constructor.static.label ); this.setLabelElement( config.$label || $( '<span>' ) ); }; /* Setup */ OO.initClass( OO.ui.mixin.LabelElement ); /* Events */ /** * @event labelChange * @param {string} value */ /* Static Properties */ /** * The label text. The label can be specified as a plaintext string, a function that will * produce a string in the future, or `null` for no label. The static value will * be overridden if a label is specified with the #label config option. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.LabelElement.static.label = null; /* Static methods */ /** * Highlight the first occurrence of the query in the given text * * @param {string} text Text * @param {string} query Query to find * @return {jQuery} Text with the first match of the query * sub-string wrapped in highlighted span */ OO.ui.mixin.LabelElement.static.highlightQuery = function ( text, query ) { var $result = $( '<span>' ), offset = text.toLowerCase().indexOf( query.toLowerCase() ); if ( !query.length || offset === -1 ) { return $result.text( text ); } $result.append( document.createTextNode( text.slice( 0, offset ) ), $( '<span>' ) .addClass( 'oo-ui-labelElement-label-highlight' ) .text( text.slice( offset, offset + query.length ) ), document.createTextNode( text.slice( offset + query.length ) ) ); return $result.contents(); }; /* Methods */ /** * Set the label element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $label Element to use as label */ OO.ui.mixin.LabelElement.prototype.setLabelElement = function ( $label ) { if ( this.$label ) { this.$label.removeClass( 'oo-ui-labelElement-label' ).empty(); } this.$label = $label.addClass( 'oo-ui-labelElement-label' ); this.setLabelContent( this.label ); }; /** * Set the label. * * An empty string will result in the label being hidden. A string containing only whitespace will * be converted to a single `&nbsp;`. * * @param {jQuery|string|OO.ui.HtmlSnippet|Function|null} label Label nodes; text; a function that returns nodes or * text; or null for no label * @chainable */ OO.ui.mixin.LabelElement.prototype.setLabel = function ( label ) { label = typeof label === 'function' ? OO.ui.resolveMsg( label ) : label; label = ( ( typeof label === 'string' || label instanceof jQuery ) && label.length ) || ( label instanceof OO.ui.HtmlSnippet && label.toString().length ) ? label : null; if ( this.label !== label ) { if ( this.$label ) { this.setLabelContent( label ); } this.label = label; this.emit( 'labelChange' ); } this.$element.toggleClass( 'oo-ui-labelElement', !!this.label ); return this; }; /** * Set the label as plain text with a highlighted query * * @param {string} text Text label to set * @param {string} query Substring of text to highlight * @chainable */ OO.ui.mixin.LabelElement.prototype.setHighlightedQuery = function ( text, query ) { return this.setLabel( this.constructor.static.highlightQuery( text, query ) ); }; /** * Get the label. * * @return {jQuery|string|Function|null} Label nodes; text; a function that returns nodes or * text; or null for no label */ OO.ui.mixin.LabelElement.prototype.getLabel = function () { return this.label; }; /** * Fit the label. * * @chainable * @deprecated since 0.16.0 */ OO.ui.mixin.LabelElement.prototype.fitLabel = function () { return this; }; /** * Set the content of the label. * * Do not call this method until after the label element has been set by #setLabelElement. * * @private * @param {jQuery|string|Function|null} label Label nodes; text; a function that returns nodes or * text; or null for no label */ OO.ui.mixin.LabelElement.prototype.setLabelContent = function ( label ) { if ( typeof label === 'string' ) { if ( label.match( /^\s*$/ ) ) { // Convert whitespace only string to a single non-breaking space this.$label.html( '&nbsp;' ); } else { this.$label.text( label ); } } else if ( label instanceof OO.ui.HtmlSnippet ) { this.$label.html( label.toString() ); } else if ( label instanceof jQuery ) { this.$label.empty().append( label ); } else { this.$label.empty(); } }; /** * The FlaggedElement class is an attribute mixin, meaning that it is used to add * additional functionality to an element created by another class. The class provides * a ‘flags’ property assigned the name (or an array of names) of styling flags, * which are used to customize the look and feel of a widget to better describe its * importance and functionality. * * The library currently contains the following styling flags for general use: * * - **progressive**: Progressive styling is applied to convey that the widget will move the user forward in a process. * - **destructive**: Destructive styling is applied to convey that the widget will remove something. * - **constructive**: Constructive styling is applied to convey that the widget will create something. * * The flags affect the appearance of the buttons: * * @example * // FlaggedElement is mixed into ButtonWidget to provide styling flags * var button1 = new OO.ui.ButtonWidget( { * label: 'Constructive', * flags: 'constructive' * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'Destructive', * flags: 'destructive' * } ); * var button3 = new OO.ui.ButtonWidget( { * label: 'Progressive', * flags: 'progressive' * } ); * $( 'body' ).append( button1.$element, button2.$element, button3.$element ); * * {@link OO.ui.ActionWidget ActionWidgets}, which are a special kind of button that execute an action, use these flags: **primary** and **safe**. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {string|string[]} [flags] The name or names of the flags (e.g., 'constructive' or 'primary') to apply. * Please see the [OOjs UI documentation on MediaWiki] [2] for more information about available flags. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Elements/Flagged * @cfg {jQuery} [$flagged] The flagged element. By default, * the flagged functionality is applied to the element created by the class ($element). * If a different element is specified, the flagged functionality will be applied to it instead. */ OO.ui.mixin.FlaggedElement = function OoUiMixinFlaggedElement( config ) { // Configuration initialization config = config || {}; // Properties this.flags = {}; this.$flagged = null; // Initialization this.setFlags( config.flags ); this.setFlaggedElement( config.$flagged || this.$element ); }; /* Events */ /** * @event flag * A flag event is emitted when the #clearFlags or #setFlags methods are used. The `changes` * parameter contains the name of each modified flag and indicates whether it was * added or removed. * * @param {Object.<string,boolean>} changes Object keyed by flag name. A Boolean `true` indicates * that the flag was added, `false` that the flag was removed. */ /* Methods */ /** * Set the flagged element. * * This method is used to retarget a flagged mixin so that its functionality applies to the specified element. * If an element is already set, the method will remove the mixin’s effect on that element. * * @param {jQuery} $flagged Element that should be flagged */ OO.ui.mixin.FlaggedElement.prototype.setFlaggedElement = function ( $flagged ) { var classNames = Object.keys( this.flags ).map( function ( flag ) { return 'oo-ui-flaggedElement-' + flag; } ).join( ' ' ); if ( this.$flagged ) { this.$flagged.removeClass( classNames ); } this.$flagged = $flagged.addClass( classNames ); }; /** * Check if the specified flag is set. * * @param {string} flag Name of flag * @return {boolean} The flag is set */ OO.ui.mixin.FlaggedElement.prototype.hasFlag = function ( flag ) { // This may be called before the constructor, thus before this.flags is set return this.flags && ( flag in this.flags ); }; /** * Get the names of all flags set. * * @return {string[]} Flag names */ OO.ui.mixin.FlaggedElement.prototype.getFlags = function () { // This may be called before the constructor, thus before this.flags is set return Object.keys( this.flags || {} ); }; /** * Clear all flags. * * @chainable * @fires flag */ OO.ui.mixin.FlaggedElement.prototype.clearFlags = function () { var flag, className, changes = {}, remove = [], classPrefix = 'oo-ui-flaggedElement-'; for ( flag in this.flags ) { className = classPrefix + flag; changes[ flag ] = false; delete this.flags[ flag ]; remove.push( className ); } if ( this.$flagged ) { this.$flagged.removeClass( remove.join( ' ' ) ); } this.updateThemeClasses(); this.emit( 'flag', changes ); return this; }; /** * Add one or more flags. * * @param {string|string[]|Object.<string, boolean>} flags A flag name, an array of flag names, * or an object keyed by flag name with a boolean value that indicates whether the flag should * be added (`true`) or removed (`false`). * @chainable * @fires flag */ OO.ui.mixin.FlaggedElement.prototype.setFlags = function ( flags ) { var i, len, flag, className, changes = {}, add = [], remove = [], classPrefix = 'oo-ui-flaggedElement-'; if ( typeof flags === 'string' ) { className = classPrefix + flags; // Set if ( !this.flags[ flags ] ) { this.flags[ flags ] = true; add.push( className ); } } else if ( Array.isArray( flags ) ) { for ( i = 0, len = flags.length; i < len; i++ ) { flag = flags[ i ]; className = classPrefix + flag; // Set if ( !this.flags[ flag ] ) { changes[ flag ] = true; this.flags[ flag ] = true; add.push( className ); } } } else if ( OO.isPlainObject( flags ) ) { for ( flag in flags ) { className = classPrefix + flag; if ( flags[ flag ] ) { // Set if ( !this.flags[ flag ] ) { changes[ flag ] = true; this.flags[ flag ] = true; add.push( className ); } } else { // Remove if ( this.flags[ flag ] ) { changes[ flag ] = false; delete this.flags[ flag ]; remove.push( className ); } } } } if ( this.$flagged ) { this.$flagged .addClass( add.join( ' ' ) ) .removeClass( remove.join( ' ' ) ); } this.updateThemeClasses(); this.emit( 'flag', changes ); return this; }; /** * TitledElement is mixed into other classes to provide a `title` attribute. * Titles are rendered by the browser and are made visible when the user moves * the mouse over the element. Titles are not visible on touch devices. * * @example * // TitledElement provides a 'title' attribute to the * // ButtonWidget class * var button = new OO.ui.ButtonWidget( { * label: 'Button with Title', * title: 'I am a button' * } ); * $( 'body' ).append( button.$element ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$titled] The element to which the `title` attribute is applied. * If this config is omitted, the title functionality is applied to $element, the * element created by the class. * @cfg {string|Function} [title] The title text or a function that returns text. If * this config is omitted, the value of the {@link #static-title static title} property is used. */ OO.ui.mixin.TitledElement = function OoUiMixinTitledElement( config ) { // Configuration initialization config = config || {}; // Properties this.$titled = null; this.title = null; // Initialization this.setTitle( config.title !== undefined ? config.title : this.constructor.static.title ); this.setTitledElement( config.$titled || this.$element ); }; /* Setup */ OO.initClass( OO.ui.mixin.TitledElement ); /* Static Properties */ /** * The title text, a function that returns text, or `null` for no title. The value of the static property * is overridden if the #title config option is used. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.TitledElement.static.title = null; /* Methods */ /** * Set the titled element. * * This method is used to retarget a titledElement mixin so that its functionality applies to the specified element. * If an element is already set, the mixin’s effect on that element is removed before the new element is set up. * * @param {jQuery} $titled Element that should use the 'titled' functionality */ OO.ui.mixin.TitledElement.prototype.setTitledElement = function ( $titled ) { if ( this.$titled ) { this.$titled.removeAttr( 'title' ); } this.$titled = $titled; if ( this.title ) { this.$titled.attr( 'title', this.title ); } }; /** * Set title. * * @param {string|Function|null} title Title text, a function that returns text, or `null` for no title * @chainable */ OO.ui.mixin.TitledElement.prototype.setTitle = function ( title ) { title = typeof title === 'function' ? OO.ui.resolveMsg( title ) : title; title = ( typeof title === 'string' && title.length ) ? title : null; if ( this.title !== title ) { if ( this.$titled ) { if ( title !== null ) { this.$titled.attr( 'title', title ); } else { this.$titled.removeAttr( 'title' ); } } this.title = title; } return this; }; /** * Get title. * * @return {string} Title string */ OO.ui.mixin.TitledElement.prototype.getTitle = function () { return this.title; }; /** * AccessKeyedElement is mixed into other classes to provide an `accesskey` attribute. * Accesskeys allow an user to go to a specific element by using * a shortcut combination of a browser specific keys + the key * set to the field. * * @example * // AccessKeyedElement provides an 'accesskey' attribute to the * // ButtonWidget class * var button = new OO.ui.ButtonWidget( { * label: 'Button with Accesskey', * accessKey: 'k' * } ); * $( 'body' ).append( button.$element ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$accessKeyed] The element to which the `accesskey` attribute is applied. * If this config is omitted, the accesskey functionality is applied to $element, the * element created by the class. * @cfg {string|Function} [accessKey] The key or a function that returns the key. If * this config is omitted, no accesskey will be added. */ OO.ui.mixin.AccessKeyedElement = function OoUiMixinAccessKeyedElement( config ) { // Configuration initialization config = config || {}; // Properties this.$accessKeyed = null; this.accessKey = null; // Initialization this.setAccessKey( config.accessKey || null ); this.setAccessKeyedElement( config.$accessKeyed || this.$element ); }; /* Setup */ OO.initClass( OO.ui.mixin.AccessKeyedElement ); /* Static Properties */ /** * The access key, a function that returns a key, or `null` for no accesskey. * * @static * @inheritable * @property {string|Function|null} */ OO.ui.mixin.AccessKeyedElement.static.accessKey = null; /* Methods */ /** * Set the accesskeyed element. * * This method is used to retarget a AccessKeyedElement mixin so that its functionality applies to the specified element. * If an element is already set, the mixin's effect on that element is removed before the new element is set up. * * @param {jQuery} $accessKeyed Element that should use the 'accesskeyes' functionality */ OO.ui.mixin.AccessKeyedElement.prototype.setAccessKeyedElement = function ( $accessKeyed ) { if ( this.$accessKeyed ) { this.$accessKeyed.removeAttr( 'accesskey' ); } this.$accessKeyed = $accessKeyed; if ( this.accessKey ) { this.$accessKeyed.attr( 'accesskey', this.accessKey ); } }; /** * Set accesskey. * * @param {string|Function|null} accessKey Key, a function that returns a key, or `null` for no accesskey * @chainable */ OO.ui.mixin.AccessKeyedElement.prototype.setAccessKey = function ( accessKey ) { accessKey = typeof accessKey === 'string' ? OO.ui.resolveMsg( accessKey ) : null; if ( this.accessKey !== accessKey ) { if ( this.$accessKeyed ) { if ( accessKey !== null ) { this.$accessKeyed.attr( 'accesskey', accessKey ); } else { this.$accessKeyed.removeAttr( 'accesskey' ); } } this.accessKey = accessKey; } return this; }; /** * Get accesskey. * * @return {string} accessKey string */ OO.ui.mixin.AccessKeyedElement.prototype.getAccessKey = function () { return this.accessKey; }; /** * ButtonWidget is a generic widget for buttons. A wide variety of looks, * feels, and functionality can be customized via the class’s configuration options * and methods. Please see the [OOjs UI documentation on MediaWiki] [1] for more information * and examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Buttons_and_Switches * * @example * // A button widget * var button = new OO.ui.ButtonWidget( { * label: 'Button with Icon', * icon: 'remove', * iconTitle: 'Remove' * } ); * $( 'body' ).append( button.$element ); * * NOTE: HTML form buttons should use the OO.ui.ButtonInputWidget class. * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.ButtonElement * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * @mixins OO.ui.mixin.AccessKeyedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [active=false] Whether button should be shown as active * @cfg {string} [href] Hyperlink to visit when the button is clicked. * @cfg {string} [target] The frame or window in which to open the hyperlink. * @cfg {boolean} [noFollow] Search engine traversal hint (default: true) */ OO.ui.ButtonWidget = function OoUiButtonWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ButtonWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ButtonElement.call( this, config ); OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$button } ) ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$button } ) ); OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$button } ) ); // Properties this.href = null; this.target = null; this.noFollow = false; // Events this.connect( this, { disable: 'onDisable' } ); // Initialization this.$button.append( this.$icon, this.$label, this.$indicator ); this.$element .addClass( 'oo-ui-buttonWidget' ) .append( this.$button ); this.setActive( config.active ); this.setHref( config.href ); this.setTarget( config.target ); this.setNoFollow( config.noFollow ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.ButtonElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.TabIndexedElement ); OO.mixinClass( OO.ui.ButtonWidget, OO.ui.mixin.AccessKeyedElement ); /* Static Properties */ /** * @inheritdoc */ OO.ui.ButtonWidget.static.cancelButtonMouseDownEvents = false; /* Methods */ /** * Get hyperlink location. * * @return {string} Hyperlink location */ OO.ui.ButtonWidget.prototype.getHref = function () { return this.href; }; /** * Get hyperlink target. * * @return {string} Hyperlink target */ OO.ui.ButtonWidget.prototype.getTarget = function () { return this.target; }; /** * Get search engine traversal hint. * * @return {boolean} Whether search engines should avoid traversing this hyperlink */ OO.ui.ButtonWidget.prototype.getNoFollow = function () { return this.noFollow; }; /** * Set hyperlink location. * * @param {string|null} href Hyperlink location, null to remove */ OO.ui.ButtonWidget.prototype.setHref = function ( href ) { href = typeof href === 'string' ? href : null; if ( href !== null && !OO.ui.isSafeUrl( href ) ) { href = './' + href; } if ( href !== this.href ) { this.href = href; this.updateHref(); } return this; }; /** * Update the `href` attribute, in case of changes to href or * disabled state. * * @private * @chainable */ OO.ui.ButtonWidget.prototype.updateHref = function () { if ( this.href !== null && !this.isDisabled() ) { this.$button.attr( 'href', this.href ); } else { this.$button.removeAttr( 'href' ); } return this; }; /** * Handle disable events. * * @private * @param {boolean} disabled Element is disabled */ OO.ui.ButtonWidget.prototype.onDisable = function () { this.updateHref(); }; /** * Set hyperlink target. * * @param {string|null} target Hyperlink target, null to remove */ OO.ui.ButtonWidget.prototype.setTarget = function ( target ) { target = typeof target === 'string' ? target : null; if ( target !== this.target ) { this.target = target; if ( target !== null ) { this.$button.attr( 'target', target ); } else { this.$button.removeAttr( 'target' ); } } return this; }; /** * Set search engine traversal hint. * * @param {boolean} noFollow True if search engines should avoid traversing this hyperlink */ OO.ui.ButtonWidget.prototype.setNoFollow = function ( noFollow ) { noFollow = typeof noFollow === 'boolean' ? noFollow : true; if ( noFollow !== this.noFollow ) { this.noFollow = noFollow; if ( noFollow ) { this.$button.attr( 'rel', 'nofollow' ); } else { this.$button.removeAttr( 'rel' ); } } return this; }; // Override method visibility hints from ButtonElement /** * @method setActive */ /** * @method isActive */ /** * A ButtonGroupWidget groups related buttons and is used together with OO.ui.ButtonWidget and * its subclasses. Each button in a group is addressed by a unique reference. Buttons can be added, * removed, and cleared from the group. * * @example * // Example: A ButtonGroupWidget with two buttons * var button1 = new OO.ui.PopupButtonWidget( { * label: 'Select a category', * icon: 'menu', * popup: { * $content: $( '<p>List of categories...</p>' ), * padded: true, * align: 'left' * } * } ); * var button2 = new OO.ui.ButtonWidget( { * label: 'Add item' * }); * var buttonGroup = new OO.ui.ButtonGroupWidget( { * items: [button1, button2] * } ); * $( 'body' ).append( buttonGroup.$element ); * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.ButtonWidget[]} [items] Buttons to add */ OO.ui.ButtonGroupWidget = function OoUiButtonGroupWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ButtonGroupWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-buttonGroupWidget' ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.ButtonGroupWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.ButtonGroupWidget, OO.ui.mixin.GroupElement ); /** * IconWidget is a generic widget for {@link OO.ui.mixin.IconElement icons}. In general, IconWidgets should be used with OO.ui.LabelWidget, * which creates a label that identifies the icon’s function. See the [OOjs UI documentation on MediaWiki] [1] * for a list of icons included in the library. * * @example * // An icon widget with a label * var myIcon = new OO.ui.IconWidget( { * icon: 'help', * iconTitle: 'Help' * } ); * // Create a label. * var iconLabel = new OO.ui.LabelWidget( { * label: 'Help' * } ); * $( 'body' ).append( myIcon.$element, iconLabel.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Icons * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.FlaggedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.IconWidget = function OoUiIconWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.IconWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, $.extend( {}, config, { $icon: this.$element } ) ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) ); OO.ui.mixin.FlaggedElement.call( this, $.extend( {}, config, { $flagged: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-iconWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.IconWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.IconWidget, OO.ui.mixin.FlaggedElement ); /* Static Properties */ OO.ui.IconWidget.static.tagName = 'span'; /** * IndicatorWidgets create indicators, which are small graphics that are generally used to draw * attention to the status of an item or to clarify the function of a control. For a list of * indicators included in the library, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of an indicator widget * var indicator1 = new OO.ui.IndicatorWidget( { * indicator: 'alert' * } ); * * // Create a fieldset layout to add a label * var fieldset = new OO.ui.FieldsetLayout(); * fieldset.addItems( [ * new OO.ui.FieldLayout( indicator1, { label: 'An alert indicator:' } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Icons,_Indicators,_and_Labels#Indicators * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.IndicatorWidget = function OoUiIndicatorWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.IndicatorWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IndicatorElement.call( this, $.extend( {}, config, { $indicator: this.$element } ) ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-indicatorWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.IndicatorWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.IndicatorWidget, OO.ui.mixin.TitledElement ); /* Static Properties */ OO.ui.IndicatorWidget.static.tagName = 'span'; /** * LabelWidgets help identify the function of interface elements. Each LabelWidget can * be configured with a `label` option that is set to a string, a label node, or a function: * * - String: a plaintext string * - jQuery selection: a jQuery selection, used for anything other than a plaintext label, e.g., a * label that includes a link or special styling, such as a gray color or additional graphical elements. * - Function: a function that will produce a string in the future. Functions are used * in cases where the value of the label is not currently defined. * * In addition, the LabelWidget can be associated with an {@link OO.ui.InputWidget input widget}, which * will come into focus when the label is clicked. * * @example * // Examples of LabelWidgets * var label1 = new OO.ui.LabelWidget( { * label: 'plaintext label' * } ); * var label2 = new OO.ui.LabelWidget( { * label: $( '<a href="default.html">jQuery label</a>' ) * } ); * // Create a fieldset layout with fields for each example * var fieldset = new OO.ui.FieldsetLayout(); * fieldset.addItems( [ * new OO.ui.FieldLayout( label1 ), * new OO.ui.FieldLayout( label2 ) * ] ); * $( 'body' ).append( fieldset.$element ); * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.InputWidget} [input] {@link OO.ui.InputWidget Input widget} that uses the label. * Clicking the label will focus the specified input field. */ OO.ui.LabelWidget = function OoUiLabelWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.LabelWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: this.$element } ) ); OO.ui.mixin.TitledElement.call( this, config ); // Properties this.input = config.input; // Events if ( this.input instanceof OO.ui.InputWidget ) { this.$element.on( 'click', this.onClick.bind( this ) ); } // Initialization this.$element.addClass( 'oo-ui-labelWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.LabelWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.LabelWidget, OO.ui.mixin.TitledElement ); /* Static Properties */ OO.ui.LabelWidget.static.tagName = 'span'; /* Methods */ /** * Handles label mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.LabelWidget.prototype.onClick = function () { this.input.simulateLabelClick(); return false; }; /** * PendingElement is a mixin that is used to create elements that notify users that something is happening * and that they should wait before proceeding. The pending state is visually represented with a pending * texture that appears in the head of a pending {@link OO.ui.ProcessDialog process dialog} or in the input * field of a {@link OO.ui.TextInputWidget text input widget}. * * Currently, {@link OO.ui.ActionWidget Action widgets}, which mix in this class, can also be marked as pending, but only when * used in {@link OO.ui.MessageDialog message dialogs}. The behavior is not currently supported for action widgets used * in process dialogs. * * @example * function MessageDialog( config ) { * MessageDialog.parent.call( this, config ); * } * OO.inheritClass( MessageDialog, OO.ui.MessageDialog ); * * MessageDialog.static.actions = [ * { action: 'save', label: 'Done', flags: 'primary' }, * { label: 'Cancel', flags: 'safe' } * ]; * * MessageDialog.prototype.initialize = function () { * MessageDialog.parent.prototype.initialize.apply( this, arguments ); * this.content = new OO.ui.PanelLayout( { $: this.$, padded: true } ); * this.content.$element.append( '<p>Click the \'Done\' action widget to see its pending state. Note that action widgets can be marked pending in message dialogs but not process dialogs.</p>' ); * this.$body.append( this.content.$element ); * }; * MessageDialog.prototype.getBodyHeight = function () { * return 100; * } * MessageDialog.prototype.getActionProcess = function ( action ) { * var dialog = this; * if ( action === 'save' ) { * dialog.getActions().get({actions: 'save'})[0].pushPending(); * return new OO.ui.Process() * .next( 1000 ) * .next( function () { * dialog.getActions().get({actions: 'save'})[0].popPending(); * } ); * } * return MessageDialog.parent.prototype.getActionProcess.call( this, action ); * }; * * var windowManager = new OO.ui.WindowManager(); * $( 'body' ).append( windowManager.$element ); * * var dialog = new MessageDialog(); * windowManager.addWindows( [ dialog ] ); * windowManager.openWindow( dialog ); * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$pending] Element to mark as pending, defaults to this.$element */ OO.ui.mixin.PendingElement = function OoUiMixinPendingElement( config ) { // Configuration initialization config = config || {}; // Properties this.pending = 0; this.$pending = null; // Initialisation this.setPendingElement( config.$pending || this.$element ); }; /* Setup */ OO.initClass( OO.ui.mixin.PendingElement ); /* Methods */ /** * Set the pending element (and clean up any existing one). * * @param {jQuery} $pending The element to set to pending. */ OO.ui.mixin.PendingElement.prototype.setPendingElement = function ( $pending ) { if ( this.$pending ) { this.$pending.removeClass( 'oo-ui-pendingElement-pending' ); } this.$pending = $pending; if ( this.pending > 0 ) { this.$pending.addClass( 'oo-ui-pendingElement-pending' ); } }; /** * Check if an element is pending. * * @return {boolean} Element is pending */ OO.ui.mixin.PendingElement.prototype.isPending = function () { return !!this.pending; }; /** * Increase the pending counter. The pending state will remain active until the counter is zero * (i.e., the number of calls to #pushPending and #popPending is the same). * * @chainable */ OO.ui.mixin.PendingElement.prototype.pushPending = function () { if ( this.pending === 0 ) { this.$pending.addClass( 'oo-ui-pendingElement-pending' ); this.updateThemeClasses(); } this.pending++; return this; }; /** * Decrease the pending counter. The pending state will remain active until the counter is zero * (i.e., the number of calls to #pushPending and #popPending is the same). * * @chainable */ OO.ui.mixin.PendingElement.prototype.popPending = function () { if ( this.pending === 1 ) { this.$pending.removeClass( 'oo-ui-pendingElement-pending' ); this.updateThemeClasses(); } this.pending = Math.max( 0, this.pending - 1 ); return this; }; /** * Element that can be automatically clipped to visible boundaries. * * Whenever the element's natural height changes, you have to call * {@link OO.ui.mixin.ClippableElement#clip} to make sure it's still * clipping correctly. * * The dimensions of #$clippableContainer will be compared to the boundaries of the * nearest scrollable container. If #$clippableContainer is too tall and/or too wide, * then #$clippable will be given a fixed reduced height and/or width and will be made * scrollable. By default, #$clippable and #$clippableContainer are the same element, * but you can build a static footer by setting #$clippableContainer to an element that contains * #$clippable and the footer. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$clippable] Node to clip, assigned to #$clippable, omit to use #$element * @cfg {jQuery} [$clippableContainer] Node to keep visible, assigned to #$clippableContainer, * omit to use #$clippable */ OO.ui.mixin.ClippableElement = function OoUiMixinClippableElement( config ) { // Configuration initialization config = config || {}; // Properties this.$clippable = null; this.$clippableContainer = null; this.clipping = false; this.clippedHorizontally = false; this.clippedVertically = false; this.$clippableScrollableContainer = null; this.$clippableScroller = null; this.$clippableWindow = null; this.idealWidth = null; this.idealHeight = null; this.onClippableScrollHandler = this.clip.bind( this ); this.onClippableWindowResizeHandler = this.clip.bind( this ); // Initialization if ( config.$clippableContainer ) { this.setClippableContainer( config.$clippableContainer ); } this.setClippableElement( config.$clippable || this.$element ); }; /* Methods */ /** * Set clippable element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $clippable Element to make clippable */ OO.ui.mixin.ClippableElement.prototype.setClippableElement = function ( $clippable ) { if ( this.$clippable ) { this.$clippable.removeClass( 'oo-ui-clippableElement-clippable' ); this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } ); OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); } this.$clippable = $clippable.addClass( 'oo-ui-clippableElement-clippable' ); this.clip(); }; /** * Set clippable container. * * This is the container that will be measured when deciding whether to clip. When clipping, * #$clippable will be resized in order to keep the clippable container fully visible. * * If the clippable container is unset, #$clippable will be used. * * @param {jQuery|null} $clippableContainer Container to keep visible, or null to unset */ OO.ui.mixin.ClippableElement.prototype.setClippableContainer = function ( $clippableContainer ) { this.$clippableContainer = $clippableContainer; if ( this.$clippable ) { this.clip(); } }; /** * Toggle clipping. * * Do not turn clipping on until after the element is attached to the DOM and visible. * * @param {boolean} [clipping] Enable clipping, omit to toggle * @chainable */ OO.ui.mixin.ClippableElement.prototype.toggleClipping = function ( clipping ) { clipping = clipping === undefined ? !this.clipping : !!clipping; if ( this.clipping !== clipping ) { this.clipping = clipping; if ( clipping ) { this.$clippableScrollableContainer = $( this.getClosestScrollableElementContainer() ); // If the clippable container is the root, we have to listen to scroll events and check // jQuery.scrollTop on the window because of browser inconsistencies this.$clippableScroller = this.$clippableScrollableContainer.is( 'html, body' ) ? $( OO.ui.Element.static.getWindow( this.$clippableScrollableContainer ) ) : this.$clippableScrollableContainer; this.$clippableScroller.on( 'scroll', this.onClippableScrollHandler ); this.$clippableWindow = $( this.getElementWindow() ) .on( 'resize', this.onClippableWindowResizeHandler ); // Initial clip after visible this.clip(); } else { this.$clippable.css( { width: '', height: '', overflowX: '', overflowY: '' } ); OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); this.$clippableScrollableContainer = null; this.$clippableScroller.off( 'scroll', this.onClippableScrollHandler ); this.$clippableScroller = null; this.$clippableWindow.off( 'resize', this.onClippableWindowResizeHandler ); this.$clippableWindow = null; } } return this; }; /** * Check if the element will be clipped to fit the visible area of the nearest scrollable container. * * @return {boolean} Element will be clipped to the visible area */ OO.ui.mixin.ClippableElement.prototype.isClipping = function () { return this.clipping; }; /** * Check if the bottom or right of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.mixin.ClippableElement.prototype.isClipped = function () { return this.clippedHorizontally || this.clippedVertically; }; /** * Check if the right of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.mixin.ClippableElement.prototype.isClippedHorizontally = function () { return this.clippedHorizontally; }; /** * Check if the bottom of the element is being clipped by the nearest scrollable container. * * @return {boolean} Part of the element is being clipped */ OO.ui.mixin.ClippableElement.prototype.isClippedVertically = function () { return this.clippedVertically; }; /** * Set the ideal size. These are the dimensions the element will have when it's not being clipped. * * @param {number|string} [width] Width as a number of pixels or CSS string with unit suffix * @param {number|string} [height] Height as a number of pixels or CSS string with unit suffix */ OO.ui.mixin.ClippableElement.prototype.setIdealSize = function ( width, height ) { this.idealWidth = width; this.idealHeight = height; if ( !this.clipping ) { // Update dimensions this.$clippable.css( { width: width, height: height } ); } // While clipping, idealWidth and idealHeight are not considered }; /** * Clip element to visible boundaries and allow scrolling when needed. You should call this method * when the element's natural height changes. * * Element will be clipped the bottom or right of the element is within 10px of the edge of, or * overlapped by, the visible area of the nearest scrollable container. * * Because calling clip() when the natural height changes isn't always possible, we also set * max-height when the element isn't being clipped. This means that if the element tries to grow * beyond the edge, something reasonable will happen before clip() is called. * * @chainable */ OO.ui.mixin.ClippableElement.prototype.clip = function () { var $container, extraHeight, extraWidth, ccOffset, $scrollableContainer, scOffset, scHeight, scWidth, ccWidth, scrollerIsWindow, scrollTop, scrollLeft, desiredWidth, desiredHeight, allotedWidth, allotedHeight, naturalWidth, naturalHeight, clipWidth, clipHeight, buffer = 7; // Chosen by fair dice roll if ( !this.clipping ) { // this.$clippableScrollableContainer and this.$clippableWindow are null, so the below will fail return this; } $container = this.$clippableContainer || this.$clippable; extraHeight = $container.outerHeight() - this.$clippable.outerHeight(); extraWidth = $container.outerWidth() - this.$clippable.outerWidth(); ccOffset = $container.offset(); if ( this.$clippableScrollableContainer.is( 'html, body' ) ) { $scrollableContainer = this.$clippableWindow; scOffset = { top: 0, left: 0 }; } else { $scrollableContainer = this.$clippableScrollableContainer; scOffset = $scrollableContainer.offset(); } scHeight = $scrollableContainer.innerHeight() - buffer; scWidth = $scrollableContainer.innerWidth() - buffer; ccWidth = $container.outerWidth() + buffer; scrollerIsWindow = this.$clippableScroller[ 0 ] === this.$clippableWindow[ 0 ]; scrollTop = scrollerIsWindow ? this.$clippableScroller.scrollTop() : 0; scrollLeft = scrollerIsWindow ? this.$clippableScroller.scrollLeft() : 0; desiredWidth = ccOffset.left < 0 ? ccWidth + ccOffset.left : ( scOffset.left + scrollLeft + scWidth ) - ccOffset.left; desiredHeight = ( scOffset.top + scrollTop + scHeight ) - ccOffset.top; // It should never be desirable to exceed the dimensions of the browser viewport... right? desiredWidth = Math.min( desiredWidth, document.documentElement.clientWidth ); desiredHeight = Math.min( desiredHeight, document.documentElement.clientHeight ); allotedWidth = Math.ceil( desiredWidth - extraWidth ); allotedHeight = Math.ceil( desiredHeight - extraHeight ); naturalWidth = this.$clippable.prop( 'scrollWidth' ); naturalHeight = this.$clippable.prop( 'scrollHeight' ); clipWidth = allotedWidth < naturalWidth; clipHeight = allotedHeight < naturalHeight; if ( clipWidth ) { this.$clippable.css( { overflowX: 'scroll', width: Math.max( 0, allotedWidth ), maxWidth: '' } ); } else { this.$clippable.css( { overflowX: '', width: this.idealWidth ? this.idealWidth - extraWidth : '', maxWidth: Math.max( 0, allotedWidth ) } ); } if ( clipHeight ) { this.$clippable.css( { overflowY: 'scroll', height: Math.max( 0, allotedHeight ), maxHeight: '' } ); } else { this.$clippable.css( { overflowY: '', height: this.idealHeight ? this.idealHeight - extraHeight : '', maxHeight: Math.max( 0, allotedHeight ) } ); } // If we stopped clipping in at least one of the dimensions if ( ( this.clippedHorizontally && !clipWidth ) || ( this.clippedVertically && !clipHeight ) ) { OO.ui.Element.static.reconsiderScrollbars( this.$clippable[ 0 ] ); } this.clippedHorizontally = clipWidth; this.clippedVertically = clipHeight; return this; }; /** * PopupWidget is a container for content. The popup is overlaid and positioned absolutely. * By default, each popup has an anchor that points toward its origin. * Please see the [OOjs UI documentation on Mediawiki] [1] for more information and examples. * * @example * // A popup widget. * var popup = new OO.ui.PopupWidget( { * $content: $( '<p>Hi there!</p>' ), * padded: true, * width: 300 * } ); * * $( 'body' ).append( popup.$element ); * // To display the popup, toggle the visibility to 'true'. * popup.toggle( true ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.ClippableElement * * @constructor * @param {Object} [config] Configuration options * @cfg {number} [width=320] Width of popup in pixels * @cfg {number} [height] Height of popup in pixels. Omit to use the automatic height. * @cfg {boolean} [anchor=true] Show anchor pointing to origin of popup * @cfg {string} [align='center'] Alignment of the popup: `center`, `force-left`, `force-right`, `backwards` or `forwards`. * If the popup is forced-left the popup body is leaning towards the left. For force-right alignment, the body of the * popup is leaning towards the right of the screen. * Using 'backwards' is a logical direction which will result in the popup leaning towards the beginning of the sentence * in the given language, which means it will flip to the correct positioning in right-to-left languages. * Using 'forward' will also result in a logical alignment where the body of the popup leans towards the end of the * sentence in the given language. * @cfg {jQuery} [$container] Constrain the popup to the boundaries of the specified container. * See the [OOjs UI docs on MediaWiki][3] for an example. * [3]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#containerExample * @cfg {number} [containerPadding=10] Padding between the popup and its container, specified as a number of pixels. * @cfg {jQuery} [$content] Content to append to the popup's body * @cfg {jQuery} [$footer] Content to append to the popup's footer * @cfg {boolean} [autoClose=false] Automatically close the popup when it loses focus. * @cfg {jQuery} [$autoCloseIgnore] Elements that will not close the popup when clicked. * This config option is only relevant if #autoClose is set to `true`. See the [OOjs UI docs on MediaWiki][2] * for an example. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Popups#autocloseExample * @cfg {boolean} [head=false] Show a popup header that contains a #label (if specified) and close * button. * @cfg {boolean} [padded=false] Add padding to the popup's body */ OO.ui.PopupWidget = function OoUiPopupWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.PopupWidget.parent.call( this, config ); // Properties (must be set before ClippableElement constructor call) this.$body = $( '<div>' ); this.$popup = $( '<div>' ); // Mixin constructors OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$body, $clippableContainer: this.$popup } ) ); // Properties this.$anchor = $( '<div>' ); // If undefined, will be computed lazily in updateDimensions() this.$container = config.$container; this.containerPadding = config.containerPadding !== undefined ? config.containerPadding : 10; this.autoClose = !!config.autoClose; this.$autoCloseIgnore = config.$autoCloseIgnore; this.transitionTimeout = null; this.anchor = null; this.width = config.width !== undefined ? config.width : 320; this.height = config.height !== undefined ? config.height : null; this.setAlignment( config.align ); this.onMouseDownHandler = this.onMouseDown.bind( this ); this.onDocumentKeyDownHandler = this.onDocumentKeyDown.bind( this ); // Initialization this.toggleAnchor( config.anchor === undefined || config.anchor ); this.$body.addClass( 'oo-ui-popupWidget-body' ); this.$anchor.addClass( 'oo-ui-popupWidget-anchor' ); this.$popup .addClass( 'oo-ui-popupWidget-popup' ) .append( this.$body ); this.$element .addClass( 'oo-ui-popupWidget' ) .append( this.$popup, this.$anchor ); // Move content, which was added to #$element by OO.ui.Widget, to the body // FIXME This is gross, we should use '$body' or something for the config if ( config.$content instanceof jQuery ) { this.$body.append( config.$content ); } if ( config.padded ) { this.$body.addClass( 'oo-ui-popupWidget-body-padded' ); } if ( config.head ) { this.closeButton = new OO.ui.ButtonWidget( { framed: false, icon: 'close' } ); this.closeButton.connect( this, { click: 'onCloseButtonClick' } ); this.$head = $( '<div>' ) .addClass( 'oo-ui-popupWidget-head' ) .append( this.$label, this.closeButton.$element ); this.$popup.prepend( this.$head ); } if ( config.$footer ) { this.$footer = $( '<div>' ) .addClass( 'oo-ui-popupWidget-footer' ) .append( config.$footer ); this.$popup.append( this.$footer ); } // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.PopupWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.PopupWidget, OO.ui.mixin.ClippableElement ); /* Methods */ /** * Handles mouse down events. * * @private * @param {MouseEvent} e Mouse down event */ OO.ui.PopupWidget.prototype.onMouseDown = function ( e ) { if ( this.isVisible() && !OO.ui.contains( this.$element.add( this.$autoCloseIgnore ).get(), e.target, true ) ) { this.toggle( false ); } }; /** * Bind mouse down listener. * * @private */ OO.ui.PopupWidget.prototype.bindMouseDownListener = function () { // Capture clicks outside popup this.getElementWindow().addEventListener( 'mousedown', this.onMouseDownHandler, true ); }; /** * Handles close button click events. * * @private */ OO.ui.PopupWidget.prototype.onCloseButtonClick = function () { if ( this.isVisible() ) { this.toggle( false ); } }; /** * Unbind mouse down listener. * * @private */ OO.ui.PopupWidget.prototype.unbindMouseDownListener = function () { this.getElementWindow().removeEventListener( 'mousedown', this.onMouseDownHandler, true ); }; /** * Handles key down events. * * @private * @param {KeyboardEvent} e Key down event */ OO.ui.PopupWidget.prototype.onDocumentKeyDown = function ( e ) { if ( e.which === OO.ui.Keys.ESCAPE && this.isVisible() ) { this.toggle( false ); e.preventDefault(); e.stopPropagation(); } }; /** * Bind key down listener. * * @private */ OO.ui.PopupWidget.prototype.bindKeyDownListener = function () { this.getElementWindow().addEventListener( 'keydown', this.onDocumentKeyDownHandler, true ); }; /** * Unbind key down listener. * * @private */ OO.ui.PopupWidget.prototype.unbindKeyDownListener = function () { this.getElementWindow().removeEventListener( 'keydown', this.onDocumentKeyDownHandler, true ); }; /** * Show, hide, or toggle the visibility of the anchor. * * @param {boolean} [show] Show anchor, omit to toggle */ OO.ui.PopupWidget.prototype.toggleAnchor = function ( show ) { show = show === undefined ? !this.anchored : !!show; if ( this.anchored !== show ) { if ( show ) { this.$element.addClass( 'oo-ui-popupWidget-anchored' ); } else { this.$element.removeClass( 'oo-ui-popupWidget-anchored' ); } this.anchored = show; } }; /** * Check if the anchor is visible. * * @return {boolean} Anchor is visible */ OO.ui.PopupWidget.prototype.hasAnchor = function () { return this.anchor; }; /** * @inheritdoc */ OO.ui.PopupWidget.prototype.toggle = function ( show ) { var change; show = show === undefined ? !this.isVisible() : !!show; change = show !== this.isVisible(); // Parent method OO.ui.PopupWidget.parent.prototype.toggle.call( this, show ); if ( change ) { if ( show ) { if ( this.autoClose ) { this.bindMouseDownListener(); this.bindKeyDownListener(); } this.updateDimensions(); this.toggleClipping( true ); } else { this.toggleClipping( false ); if ( this.autoClose ) { this.unbindMouseDownListener(); this.unbindKeyDownListener(); } } } return this; }; /** * Set the size of the popup. * * Changing the size may also change the popup's position depending on the alignment. * * @param {number} width Width in pixels * @param {number} height Height in pixels * @param {boolean} [transition=false] Use a smooth transition * @chainable */ OO.ui.PopupWidget.prototype.setSize = function ( width, height, transition ) { this.width = width; this.height = height !== undefined ? height : null; if ( this.isVisible() ) { this.updateDimensions( transition ); } }; /** * Update the size and position. * * Only use this to keep the popup properly anchored. Use #setSize to change the size, and this will * be called automatically. * * @param {boolean} [transition=false] Use a smooth transition * @chainable */ OO.ui.PopupWidget.prototype.updateDimensions = function ( transition ) { var popupOffset, originOffset, containerLeft, containerWidth, containerRight, popupLeft, popupRight, overlapLeft, overlapRight, anchorWidth, align = this.align, widget = this; if ( !this.$container ) { // Lazy-initialize $container if not specified in constructor this.$container = $( this.getClosestScrollableElementContainer() ); } // Set height and width before measuring things, since it might cause our measurements // to change (e.g. due to scrollbars appearing or disappearing) this.$popup.css( { width: this.width, height: this.height !== null ? this.height : 'auto' } ); // If we are in RTL, we need to flip the alignment, unless it is center if ( align === 'forwards' || align === 'backwards' ) { if ( this.$container.css( 'direction' ) === 'rtl' ) { align = ( { forwards: 'force-left', backwards: 'force-right' } )[ this.align ]; } else { align = ( { forwards: 'force-right', backwards: 'force-left' } )[ this.align ]; } } // Compute initial popupOffset based on alignment popupOffset = this.width * ( { 'force-left': -1, center: -0.5, 'force-right': 0 } )[ align ]; // Figure out if this will cause the popup to go beyond the edge of the container originOffset = this.$element.offset().left; containerLeft = this.$container.offset().left; containerWidth = this.$container.innerWidth(); containerRight = containerLeft + containerWidth; popupLeft = popupOffset - this.containerPadding; popupRight = popupOffset + this.containerPadding + this.width + this.containerPadding; overlapLeft = ( originOffset + popupLeft ) - containerLeft; overlapRight = containerRight - ( originOffset + popupRight ); // Adjust offset to make the popup not go beyond the edge, if needed if ( overlapRight < 0 ) { popupOffset += overlapRight; } else if ( overlapLeft < 0 ) { popupOffset -= overlapLeft; } // Adjust offset to avoid anchor being rendered too close to the edge // $anchor.width() doesn't work with the pure CSS anchor (returns 0) // TODO: Find a measurement that works for CSS anchors and image anchors anchorWidth = this.$anchor[ 0 ].scrollWidth * 2; if ( popupOffset + this.width < anchorWidth ) { popupOffset = anchorWidth - this.width; } else if ( -popupOffset < anchorWidth ) { popupOffset = -anchorWidth; } // Prevent transition from being interrupted clearTimeout( this.transitionTimeout ); if ( transition ) { // Enable transition this.$element.addClass( 'oo-ui-popupWidget-transitioning' ); } // Position body relative to anchor this.$popup.css( 'margin-left', popupOffset ); if ( transition ) { // Prevent transitioning after transition is complete this.transitionTimeout = setTimeout( function () { widget.$element.removeClass( 'oo-ui-popupWidget-transitioning' ); }, 200 ); } else { // Prevent transitioning immediately this.$element.removeClass( 'oo-ui-popupWidget-transitioning' ); } // Reevaluate clipping state since we've relocated and resized the popup this.clip(); return this; }; /** * Set popup alignment * * @param {string} align Alignment of the popup, `center`, `force-left`, `force-right`, * `backwards` or `forwards`. */ OO.ui.PopupWidget.prototype.setAlignment = function ( align ) { // Validate alignment and transform deprecated values if ( [ 'left', 'right', 'force-left', 'force-right', 'backwards', 'forwards', 'center' ].indexOf( align ) > -1 ) { this.align = { left: 'force-right', right: 'force-left' }[ align ] || align; } else { this.align = 'center'; } }; /** * Get popup alignment * * @return {string} align Alignment of the popup, `center`, `force-left`, `force-right`, * `backwards` or `forwards`. */ OO.ui.PopupWidget.prototype.getAlignment = function () { return this.align; }; /** * PopupElement is mixed into other classes to generate a {@link OO.ui.PopupWidget popup widget}. * A popup is a container for content. It is overlaid and positioned absolutely. By default, each * popup has an anchor, which is an arrow-like protrusion that points toward the popup’s origin. * See {@link OO.ui.PopupWidget PopupWidget} for an example. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {Object} [popup] Configuration to pass to popup * @cfg {boolean} [popup.autoClose=true] Popup auto-closes when it loses focus */ OO.ui.mixin.PopupElement = function OoUiMixinPopupElement( config ) { // Configuration initialization config = config || {}; // Properties this.popup = new OO.ui.PopupWidget( $.extend( { autoClose: true }, config.popup, { $autoCloseIgnore: this.$element.add( config.popup && config.popup.$autoCloseIgnore ) } ) ); }; /* Methods */ /** * Get popup. * * @return {OO.ui.PopupWidget} Popup widget */ OO.ui.mixin.PopupElement.prototype.getPopup = function () { return this.popup; }; /** * PopupButtonWidgets toggle the visibility of a contained {@link OO.ui.PopupWidget PopupWidget}, * which is used to display additional information or options. * * @example * // Example of a popup button. * var popupButton = new OO.ui.PopupButtonWidget( { * label: 'Popup button with options', * icon: 'menu', * popup: { * $content: $( '<p>Additional options here.</p>' ), * padded: true, * align: 'force-left' * } * } ); * // Append the button to the DOM. * $( 'body' ).append( popupButton.$element ); * * @class * @extends OO.ui.ButtonWidget * @mixins OO.ui.mixin.PopupElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.PopupButtonWidget = function OoUiPopupButtonWidget( config ) { // Parent constructor OO.ui.PopupButtonWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.PopupElement.call( this, config ); // Events this.connect( this, { click: 'onAction' } ); // Initialization this.$element .addClass( 'oo-ui-popupButtonWidget' ) .attr( 'aria-haspopup', 'true' ) .append( this.popup.$element ); }; /* Setup */ OO.inheritClass( OO.ui.PopupButtonWidget, OO.ui.ButtonWidget ); OO.mixinClass( OO.ui.PopupButtonWidget, OO.ui.mixin.PopupElement ); /* Methods */ /** * Handle the button action being triggered. * * @private */ OO.ui.PopupButtonWidget.prototype.onAction = function () { this.popup.toggle(); }; /** * Mixin for OO.ui.Widget subclasses to provide OO.ui.mixin.GroupElement. * * Use together with OO.ui.mixin.ItemWidget to make disabled state inheritable. * * @private * @abstract * @class * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.mixin.GroupWidget = function OoUiMixinGroupWidget( config ) { // Mixin constructors OO.ui.mixin.GroupElement.call( this, config ); }; /* Setup */ OO.mixinClass( OO.ui.mixin.GroupWidget, OO.ui.mixin.GroupElement ); /* Methods */ /** * Set the disabled state of the widget. * * This will also update the disabled state of child widgets. * * @param {boolean} disabled Disable widget * @chainable */ OO.ui.mixin.GroupWidget.prototype.setDisabled = function ( disabled ) { var i, len; // Parent method // Note: Calling #setDisabled this way assumes this is mixed into an OO.ui.Widget OO.ui.Widget.prototype.setDisabled.call( this, disabled ); // During construction, #setDisabled is called before the OO.ui.mixin.GroupElement constructor if ( this.items ) { for ( i = 0, len = this.items.length; i < len; i++ ) { this.items[ i ].updateDisabled(); } } return this; }; /** * Mixin for widgets used as items in widgets that mix in OO.ui.mixin.GroupWidget. * * Item widgets have a reference to a OO.ui.mixin.GroupWidget while they are attached to the group. This * allows bidirectional communication. * * Use together with OO.ui.mixin.GroupWidget to make disabled state inheritable. * * @private * @abstract * @class * * @constructor */ OO.ui.mixin.ItemWidget = function OoUiMixinItemWidget() { // }; /* Methods */ /** * Check if widget is disabled. * * Checks parent if present, making disabled state inheritable. * * @return {boolean} Widget is disabled */ OO.ui.mixin.ItemWidget.prototype.isDisabled = function () { return this.disabled || ( this.elementGroup instanceof OO.ui.Widget && this.elementGroup.isDisabled() ); }; /** * Set group element is in. * * @param {OO.ui.mixin.GroupElement|null} group Group element, null if none * @chainable */ OO.ui.mixin.ItemWidget.prototype.setElementGroup = function ( group ) { // Parent method // Note: Calling #setElementGroup this way assumes this is mixed into an OO.ui.Element OO.ui.Element.prototype.setElementGroup.call( this, group ); // Initialize item disabled states this.updateDisabled(); return this; }; /** * OptionWidgets are special elements that can be selected and configured with data. The * data is often unique for each option, but it does not have to be. OptionWidgets are used * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information * and examples, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.ItemWidget * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.AccessKeyedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.OptionWidget = function OoUiOptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.OptionWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ItemWidget.call( this ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.AccessKeyedElement.call( this, config ); // Properties this.selected = false; this.highlighted = false; this.pressed = false; // Initialization this.$element .data( 'oo-ui-optionWidget', this ) // Allow programmatic focussing (and by accesskey), but not tabbing .attr( 'tabindex', '-1' ) .attr( 'role', 'option' ) .attr( 'aria-selected', 'false' ) .addClass( 'oo-ui-optionWidget' ) .append( this.$label ); }; /* Setup */ OO.inheritClass( OO.ui.OptionWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.ItemWidget ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.OptionWidget, OO.ui.mixin.AccessKeyedElement ); /* Static Properties */ OO.ui.OptionWidget.static.selectable = true; OO.ui.OptionWidget.static.highlightable = true; OO.ui.OptionWidget.static.pressable = true; OO.ui.OptionWidget.static.scrollIntoViewOnSelect = false; /* Methods */ /** * Check if the option can be selected. * * @return {boolean} Item is selectable */ OO.ui.OptionWidget.prototype.isSelectable = function () { return this.constructor.static.selectable && !this.isDisabled() && this.isVisible(); }; /** * Check if the option can be highlighted. A highlight indicates that the option * may be selected when a user presses enter or clicks. Disabled items cannot * be highlighted. * * @return {boolean} Item is highlightable */ OO.ui.OptionWidget.prototype.isHighlightable = function () { return this.constructor.static.highlightable && !this.isDisabled() && this.isVisible(); }; /** * Check if the option can be pressed. The pressed state occurs when a user mouses * down on an item, but has not yet let go of the mouse. * * @return {boolean} Item is pressable */ OO.ui.OptionWidget.prototype.isPressable = function () { return this.constructor.static.pressable && !this.isDisabled() && this.isVisible(); }; /** * Check if the option is selected. * * @return {boolean} Item is selected */ OO.ui.OptionWidget.prototype.isSelected = function () { return this.selected; }; /** * Check if the option is highlighted. A highlight indicates that the * item may be selected when a user presses enter or clicks. * * @return {boolean} Item is highlighted */ OO.ui.OptionWidget.prototype.isHighlighted = function () { return this.highlighted; }; /** * Check if the option is pressed. The pressed state occurs when a user mouses * down on an item, but has not yet let go of the mouse. The item may appear * selected, but it will not be selected until the user releases the mouse. * * @return {boolean} Item is pressed */ OO.ui.OptionWidget.prototype.isPressed = function () { return this.pressed; }; /** * Set the option’s selected state. In general, all modifications to the selection * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Select option * @chainable */ OO.ui.OptionWidget.prototype.setSelected = function ( state ) { if ( this.constructor.static.selectable ) { this.selected = !!state; this.$element .toggleClass( 'oo-ui-optionWidget-selected', state ) .attr( 'aria-selected', state.toString() ); if ( state && this.constructor.static.scrollIntoViewOnSelect ) { this.scrollElementIntoView(); } this.updateThemeClasses(); } return this; }; /** * Set the option’s highlighted state. In general, all programmatic * modifications to the highlight should be handled by the * SelectWidget’s {@link OO.ui.SelectWidget#highlightItem highlightItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Highlight option * @chainable */ OO.ui.OptionWidget.prototype.setHighlighted = function ( state ) { if ( this.constructor.static.highlightable ) { this.highlighted = !!state; this.$element.toggleClass( 'oo-ui-optionWidget-highlighted', state ); this.updateThemeClasses(); } return this; }; /** * Set the option’s pressed state. In general, all * programmatic modifications to the pressed state should be handled by the * SelectWidget’s {@link OO.ui.SelectWidget#pressItem pressItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Press option * @chainable */ OO.ui.OptionWidget.prototype.setPressed = function ( state ) { if ( this.constructor.static.pressable ) { this.pressed = !!state; this.$element.toggleClass( 'oo-ui-optionWidget-pressed', state ); this.updateThemeClasses(); } return this; }; /** * A SelectWidget is of a generic selection of options. The OOjs UI library contains several types of * select widgets, including {@link OO.ui.ButtonSelectWidget button selects}, * {@link OO.ui.RadioSelectWidget radio selects}, and {@link OO.ui.MenuSelectWidget * menu selects}. * * This class should be used together with OO.ui.OptionWidget or OO.ui.DecoratedOptionWidget. For more * information, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of a select widget with three options * var select = new OO.ui.SelectWidget( { * items: [ * new OO.ui.OptionWidget( { * data: 'a', * label: 'Option One', * } ), * new OO.ui.OptionWidget( { * data: 'b', * label: 'Option Two', * } ), * new OO.ui.OptionWidget( { * data: 'c', * label: 'Option Three', * } ) * ] * } ); * $( 'body' ).append( select.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.OptionWidget[]} [items] An array of options to add to the select. * Options are created with {@link OO.ui.OptionWidget OptionWidget} classes. See * the [OOjs UI documentation on MediaWiki] [2] for examples. * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options */ OO.ui.SelectWidget = function OoUiSelectWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.SelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupWidget.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Properties this.pressed = false; this.selecting = null; this.onMouseUpHandler = this.onMouseUp.bind( this ); this.onMouseMoveHandler = this.onMouseMove.bind( this ); this.onKeyDownHandler = this.onKeyDown.bind( this ); this.onKeyPressHandler = this.onKeyPress.bind( this ); this.keyPressBuffer = ''; this.keyPressBufferTimer = null; this.blockMouseOverEvents = 0; // Events this.connect( this, { toggle: 'onToggle' } ); this.$element.on( { focusin: this.onFocus.bind( this ), mousedown: this.onMouseDown.bind( this ), mouseover: this.onMouseOver.bind( this ), mouseleave: this.onMouseLeave.bind( this ) } ); // Initialization this.$element .addClass( 'oo-ui-selectWidget oo-ui-selectWidget-depressed' ) .attr( 'role', 'listbox' ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.SelectWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.SelectWidget, OO.ui.mixin.GroupWidget ); /* Events */ /** * @event highlight * * A `highlight` event is emitted when the highlight is changed with the #highlightItem method. * * @param {OO.ui.OptionWidget|null} item Highlighted item */ /** * @event press * * A `press` event is emitted when the #pressItem method is used to programmatically modify the * pressed state of an option. * * @param {OO.ui.OptionWidget|null} item Pressed item */ /** * @event select * * A `select` event is emitted when the selection is modified programmatically with the #selectItem method. * * @param {OO.ui.OptionWidget|null} item Selected item */ /** * @event choose * A `choose` event is emitted when an item is chosen with the #chooseItem method. * @param {OO.ui.OptionWidget} item Chosen item */ /** * @event add * * An `add` event is emitted when options are added to the select with the #addItems method. * * @param {OO.ui.OptionWidget[]} items Added items * @param {number} index Index of insertion point */ /** * @event remove * * A `remove` event is emitted when options are removed from the select with the #clearItems * or #removeItems methods. * * @param {OO.ui.OptionWidget[]} items Removed items */ /* Methods */ /** * Handle focus events * * @private * @param {jQuery.Event} event */ OO.ui.SelectWidget.prototype.onFocus = function ( event ) { var item; if ( event.target === this.$element[ 0 ] ) { // This widget was focussed, e.g. by the user tabbing to it. // The styles for focus state depend on one of the items being selected. if ( !this.getSelectedItem() ) { item = this.getFirstSelectableItem(); } } else { // One of the options got focussed (and the event bubbled up here). // They can't be tabbed to, but they can be activated using accesskeys. item = this.getTargetItem( event ); } if ( item ) { if ( item.constructor.static.highlightable ) { this.highlightItem( item ); } else { this.selectItem( item ); } } if ( event.target !== this.$element[ 0 ] ) { this.$element.focus(); } }; /** * Handle mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.SelectWidget.prototype.onMouseDown = function ( e ) { var item; if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) { this.togglePressed( true ); item = this.getTargetItem( e ); if ( item && item.isSelectable() ) { this.pressItem( item ); this.selecting = item; this.getElementDocument().addEventListener( 'mouseup', this.onMouseUpHandler, true ); this.getElementDocument().addEventListener( 'mousemove', this.onMouseMoveHandler, true ); } } return false; }; /** * Handle mouse up events. * * @private * @param {MouseEvent} e Mouse up event */ OO.ui.SelectWidget.prototype.onMouseUp = function ( e ) { var item; this.togglePressed( false ); if ( !this.selecting ) { item = this.getTargetItem( e ); if ( item && item.isSelectable() ) { this.selecting = item; } } if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT && this.selecting ) { this.pressItem( null ); this.chooseItem( this.selecting ); this.selecting = null; } this.getElementDocument().removeEventListener( 'mouseup', this.onMouseUpHandler, true ); this.getElementDocument().removeEventListener( 'mousemove', this.onMouseMoveHandler, true ); return false; }; /** * Handle mouse move events. * * @private * @param {MouseEvent} e Mouse move event */ OO.ui.SelectWidget.prototype.onMouseMove = function ( e ) { var item; if ( !this.isDisabled() && this.pressed ) { item = this.getTargetItem( e ); if ( item && item !== this.selecting && item.isSelectable() ) { this.pressItem( item ); this.selecting = item; } } }; /** * Handle mouse over events. * * @private * @param {jQuery.Event} e Mouse over event */ OO.ui.SelectWidget.prototype.onMouseOver = function ( e ) { var item; if ( this.blockMouseOverEvents ) { return; } if ( !this.isDisabled() ) { item = this.getTargetItem( e ); this.highlightItem( item && item.isHighlightable() ? item : null ); } return false; }; /** * Handle mouse leave events. * * @private * @param {jQuery.Event} e Mouse over event */ OO.ui.SelectWidget.prototype.onMouseLeave = function () { if ( !this.isDisabled() ) { this.highlightItem( null ); } return false; }; /** * Handle key down events. * * @protected * @param {KeyboardEvent} e Key down event */ OO.ui.SelectWidget.prototype.onKeyDown = function ( e ) { var nextItem, handled = false, currentItem = this.getHighlightedItem() || this.getSelectedItem(); if ( !this.isDisabled() && this.isVisible() ) { switch ( e.keyCode ) { case OO.ui.Keys.ENTER: if ( currentItem && currentItem.constructor.static.highlightable ) { // Was only highlighted, now let's select it. No-op if already selected. this.chooseItem( currentItem ); handled = true; } break; case OO.ui.Keys.UP: case OO.ui.Keys.LEFT: this.clearKeyPressBuffer(); nextItem = this.getRelativeSelectableItem( currentItem, -1 ); handled = true; break; case OO.ui.Keys.DOWN: case OO.ui.Keys.RIGHT: this.clearKeyPressBuffer(); nextItem = this.getRelativeSelectableItem( currentItem, 1 ); handled = true; break; case OO.ui.Keys.ESCAPE: case OO.ui.Keys.TAB: if ( currentItem && currentItem.constructor.static.highlightable ) { currentItem.setHighlighted( false ); } this.unbindKeyDownListener(); this.unbindKeyPressListener(); // Don't prevent tabbing away / defocusing handled = false; break; } if ( nextItem ) { if ( nextItem.constructor.static.highlightable ) { this.highlightItem( nextItem ); } else { this.chooseItem( nextItem ); } this.scrollItemIntoView( nextItem ); } if ( handled ) { e.preventDefault(); e.stopPropagation(); } } }; /** * Bind key down listener. * * @protected */ OO.ui.SelectWidget.prototype.bindKeyDownListener = function () { this.getElementWindow().addEventListener( 'keydown', this.onKeyDownHandler, true ); }; /** * Unbind key down listener. * * @protected */ OO.ui.SelectWidget.prototype.unbindKeyDownListener = function () { this.getElementWindow().removeEventListener( 'keydown', this.onKeyDownHandler, true ); }; /** * Scroll item into view, preventing spurious mouse highlight actions from happening. * * @param {OO.ui.OptionWidget} item Item to scroll into view */ OO.ui.SelectWidget.prototype.scrollItemIntoView = function ( item ) { var widget = this; // Chromium's Blink engine will generate spurious 'mouseover' events during programmatic scrolling // and around 100-150 ms after it is finished. this.blockMouseOverEvents++; item.scrollElementIntoView().done( function () { setTimeout( function () { widget.blockMouseOverEvents--; }, 200 ); } ); }; /** * Clear the key-press buffer * * @protected */ OO.ui.SelectWidget.prototype.clearKeyPressBuffer = function () { if ( this.keyPressBufferTimer ) { clearTimeout( this.keyPressBufferTimer ); this.keyPressBufferTimer = null; } this.keyPressBuffer = ''; }; /** * Handle key press events. * * @protected * @param {KeyboardEvent} e Key press event */ OO.ui.SelectWidget.prototype.onKeyPress = function ( e ) { var c, filter, item; if ( !e.charCode ) { if ( e.keyCode === OO.ui.Keys.BACKSPACE && this.keyPressBuffer !== '' ) { this.keyPressBuffer = this.keyPressBuffer.substr( 0, this.keyPressBuffer.length - 1 ); return false; } return; } if ( String.fromCodePoint ) { c = String.fromCodePoint( e.charCode ); } else { c = String.fromCharCode( e.charCode ); } if ( this.keyPressBufferTimer ) { clearTimeout( this.keyPressBufferTimer ); } this.keyPressBufferTimer = setTimeout( this.clearKeyPressBuffer.bind( this ), 1500 ); item = this.getHighlightedItem() || this.getSelectedItem(); if ( this.keyPressBuffer === c ) { // Common (if weird) special case: typing "xxxx" will cycle through all // the items beginning with "x". if ( item ) { item = this.getRelativeSelectableItem( item, 1 ); } } else { this.keyPressBuffer += c; } filter = this.getItemMatcher( this.keyPressBuffer, false ); if ( !item || !filter( item ) ) { item = this.getRelativeSelectableItem( item, 1, filter ); } if ( item ) { if ( this.isVisible() && item.constructor.static.highlightable ) { this.highlightItem( item ); } else { this.chooseItem( item ); } this.scrollItemIntoView( item ); } e.preventDefault(); e.stopPropagation(); }; /** * Get a matcher for the specific string * * @protected * @param {string} s String to match against items * @param {boolean} [exact=false] Only accept exact matches * @return {Function} function ( OO.ui.OptionItem ) => boolean */ OO.ui.SelectWidget.prototype.getItemMatcher = function ( s, exact ) { var re; if ( s.normalize ) { s = s.normalize(); } s = exact ? s.trim() : s.replace( /^\s+/, '' ); re = '^\\s*' + s.replace( /([\\{}()|.?*+\-\^$\[\]])/g, '\\$1' ).replace( /\s+/g, '\\s+' ); if ( exact ) { re += '\\s*$'; } re = new RegExp( re, 'i' ); return function ( item ) { var l = item.getLabel(); if ( typeof l !== 'string' ) { l = item.$label.text(); } if ( l.normalize ) { l = l.normalize(); } return re.test( l ); }; }; /** * Bind key press listener. * * @protected */ OO.ui.SelectWidget.prototype.bindKeyPressListener = function () { this.getElementWindow().addEventListener( 'keypress', this.onKeyPressHandler, true ); }; /** * Unbind key down listener. * * If you override this, be sure to call this.clearKeyPressBuffer() from your * implementation. * * @protected */ OO.ui.SelectWidget.prototype.unbindKeyPressListener = function () { this.getElementWindow().removeEventListener( 'keypress', this.onKeyPressHandler, true ); this.clearKeyPressBuffer(); }; /** * Visibility change handler * * @protected * @param {boolean} visible */ OO.ui.SelectWidget.prototype.onToggle = function ( visible ) { if ( !visible ) { this.clearKeyPressBuffer(); } }; /** * Get the closest item to a jQuery.Event. * * @private * @param {jQuery.Event} e * @return {OO.ui.OptionWidget|null} Outline item widget, `null` if none was found */ OO.ui.SelectWidget.prototype.getTargetItem = function ( e ) { return $( e.target ).closest( '.oo-ui-optionWidget' ).data( 'oo-ui-optionWidget' ) || null; }; /** * Get selected item. * * @return {OO.ui.OptionWidget|null} Selected item, `null` if no item is selected */ OO.ui.SelectWidget.prototype.getSelectedItem = function () { var i, len; for ( i = 0, len = this.items.length; i < len; i++ ) { if ( this.items[ i ].isSelected() ) { return this.items[ i ]; } } return null; }; /** * Get highlighted item. * * @return {OO.ui.OptionWidget|null} Highlighted item, `null` if no item is highlighted */ OO.ui.SelectWidget.prototype.getHighlightedItem = function () { var i, len; for ( i = 0, len = this.items.length; i < len; i++ ) { if ( this.items[ i ].isHighlighted() ) { return this.items[ i ]; } } return null; }; /** * Toggle pressed state. * * Press is a state that occurs when a user mouses down on an item, but * has not yet let go of the mouse. The item may appear selected, but it will not be selected * until the user releases the mouse. * * @param {boolean} pressed An option is being pressed */ OO.ui.SelectWidget.prototype.togglePressed = function ( pressed ) { if ( pressed === undefined ) { pressed = !this.pressed; } if ( pressed !== this.pressed ) { this.$element .toggleClass( 'oo-ui-selectWidget-pressed', pressed ) .toggleClass( 'oo-ui-selectWidget-depressed', !pressed ); this.pressed = pressed; } }; /** * Highlight an option. If the `item` param is omitted, no options will be highlighted * and any existing highlight will be removed. The highlight is mutually exclusive. * * @param {OO.ui.OptionWidget} [item] Item to highlight, omit for no highlight * @fires highlight * @chainable */ OO.ui.SelectWidget.prototype.highlightItem = function ( item ) { var i, len, highlighted, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { highlighted = this.items[ i ] === item; if ( this.items[ i ].isHighlighted() !== highlighted ) { this.items[ i ].setHighlighted( highlighted ); changed = true; } } if ( changed ) { this.emit( 'highlight', item ); } return this; }; /** * Fetch an item by its label. * * @param {string} label Label of the item to select. * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches * @return {OO.ui.Element|null} Item with equivalent label, `null` if none exists */ OO.ui.SelectWidget.prototype.getItemFromLabel = function ( label, prefix ) { var i, item, found, len = this.items.length, filter = this.getItemMatcher( label, true ); for ( i = 0; i < len; i++ ) { item = this.items[ i ]; if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) { return item; } } if ( prefix ) { found = null; filter = this.getItemMatcher( label, false ); for ( i = 0; i < len; i++ ) { item = this.items[ i ]; if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && filter( item ) ) { if ( found ) { return null; } found = item; } } if ( found ) { return found; } } return null; }; /** * Programmatically select an option by its label. If the item does not exist, * all options will be deselected. * * @param {string} [label] Label of the item to select. * @param {boolean} [prefix=false] Allow a prefix match, if only a single item matches * @fires select * @chainable */ OO.ui.SelectWidget.prototype.selectItemByLabel = function ( label, prefix ) { var itemFromLabel = this.getItemFromLabel( label, !!prefix ); if ( label === undefined || !itemFromLabel ) { return this.selectItem(); } return this.selectItem( itemFromLabel ); }; /** * Programmatically select an option by its data. If the `data` parameter is omitted, * or if the item does not exist, all options will be deselected. * * @param {Object|string} [data] Value of the item to select, omit to deselect all * @fires select * @chainable */ OO.ui.SelectWidget.prototype.selectItemByData = function ( data ) { var itemFromData = this.getItemFromData( data ); if ( data === undefined || !itemFromData ) { return this.selectItem(); } return this.selectItem( itemFromData ); }; /** * Programmatically select an option by its reference. If the `item` parameter is omitted, * all options will be deselected. * * @param {OO.ui.OptionWidget} [item] Item to select, omit to deselect all * @fires select * @chainable */ OO.ui.SelectWidget.prototype.selectItem = function ( item ) { var i, len, selected, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { selected = this.items[ i ] === item; if ( this.items[ i ].isSelected() !== selected ) { this.items[ i ].setSelected( selected ); changed = true; } } if ( changed ) { this.emit( 'select', item ); } return this; }; /** * Press an item. * * Press is a state that occurs when a user mouses down on an item, but has not * yet let go of the mouse. The item may appear selected, but it will not be selected until the user * releases the mouse. * * @param {OO.ui.OptionWidget} [item] Item to press, omit to depress all * @fires press * @chainable */ OO.ui.SelectWidget.prototype.pressItem = function ( item ) { var i, len, pressed, changed = false; for ( i = 0, len = this.items.length; i < len; i++ ) { pressed = this.items[ i ] === item; if ( this.items[ i ].isPressed() !== pressed ) { this.items[ i ].setPressed( pressed ); changed = true; } } if ( changed ) { this.emit( 'press', item ); } return this; }; /** * Choose an item. * * Note that ‘choose’ should never be modified programmatically. A user can choose * an option with the keyboard or mouse and it becomes selected. To select an item programmatically, * use the #selectItem method. * * This method is identical to #selectItem, but may vary in subclasses that take additional action * when users choose an item with the keyboard or mouse. * * @param {OO.ui.OptionWidget} item Item to choose * @fires choose * @chainable */ OO.ui.SelectWidget.prototype.chooseItem = function ( item ) { if ( item ) { this.selectItem( item ); this.emit( 'choose', item ); } return this; }; /** * Get an option by its position relative to the specified item (or to the start of the option array, * if item is `null`). The direction in which to search through the option array is specified with a * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or * `null` if there are no options in the array. * * @param {OO.ui.OptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array. * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward * @param {Function} [filter] Only consider items for which this function returns * true. Function takes an OO.ui.OptionWidget and returns a boolean. * @return {OO.ui.OptionWidget|null} Item at position, `null` if there are no items in the select */ OO.ui.SelectWidget.prototype.getRelativeSelectableItem = function ( item, direction, filter ) { var currentIndex, nextIndex, i, increase = direction > 0 ? 1 : -1, len = this.items.length; if ( item instanceof OO.ui.OptionWidget ) { currentIndex = this.items.indexOf( item ); nextIndex = ( currentIndex + increase + len ) % len; } else { // If no item is selected and moving forward, start at the beginning. // If moving backward, start at the end. nextIndex = direction > 0 ? 0 : len - 1; } for ( i = 0; i < len; i++ ) { item = this.items[ nextIndex ]; if ( item instanceof OO.ui.OptionWidget && item.isSelectable() && ( !filter || filter( item ) ) ) { return item; } nextIndex = ( nextIndex + increase + len ) % len; } return null; }; /** * Get the next selectable item or `null` if there are no selectable items. * Disabled options and menu-section markers and breaks are not selectable. * * @return {OO.ui.OptionWidget|null} Item, `null` if there aren't any selectable items */ OO.ui.SelectWidget.prototype.getFirstSelectableItem = function () { return this.getRelativeSelectableItem( null, 1 ); }; /** * Add an array of options to the select. Optionally, an index number can be used to * specify an insertion point. * * @param {OO.ui.OptionWidget[]} items Items to add * @param {number} [index] Index to insert items after * @fires add * @chainable */ OO.ui.SelectWidget.prototype.addItems = function ( items, index ) { // Mixin method OO.ui.mixin.GroupWidget.prototype.addItems.call( this, items, index ); // Always provide an index, even if it was omitted this.emit( 'add', items, index === undefined ? this.items.length - items.length - 1 : index ); return this; }; /** * Remove the specified array of options from the select. Options will be detached * from the DOM, not removed, so they can be reused later. To remove all options from * the select, you may wish to use the #clearItems method instead. * * @param {OO.ui.OptionWidget[]} items Items to remove * @fires remove * @chainable */ OO.ui.SelectWidget.prototype.removeItems = function ( items ) { var i, len, item; // Deselect items being removed for ( i = 0, len = items.length; i < len; i++ ) { item = items[ i ]; if ( item.isSelected() ) { this.selectItem( null ); } } // Mixin method OO.ui.mixin.GroupWidget.prototype.removeItems.call( this, items ); this.emit( 'remove', items ); return this; }; /** * Clear all options from the select. Options will be detached from the DOM, not removed, * so that they can be reused later. To remove a subset of options from the select, use * the #removeItems method. * * @fires remove * @chainable */ OO.ui.SelectWidget.prototype.clearItems = function () { var items = this.items.slice(); // Mixin method OO.ui.mixin.GroupWidget.prototype.clearItems.call( this ); // Clear selection this.selectItem( null ); this.emit( 'remove', items ); return this; }; /** * DecoratedOptionWidgets are {@link OO.ui.OptionWidget options} that can be configured * with an {@link OO.ui.mixin.IconElement icon} and/or {@link OO.ui.mixin.IndicatorElement indicator}. * This class is used with OO.ui.SelectWidget to create a selection of mutually exclusive * options. For more information about options and selects, please see the * [OOjs UI documentation on MediaWiki][1]. * * @example * // Decorated options in a select widget * var select = new OO.ui.SelectWidget( { * items: [ * new OO.ui.DecoratedOptionWidget( { * data: 'a', * label: 'Option with icon', * icon: 'help' * } ), * new OO.ui.DecoratedOptionWidget( { * data: 'b', * label: 'Option with indicator', * indicator: 'next' * } ) * ] * } ); * $( 'body' ).append( select.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.OptionWidget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.DecoratedOptionWidget = function OoUiDecoratedOptionWidget( config ) { // Parent constructor OO.ui.DecoratedOptionWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-decoratedOptionWidget' ) .prepend( this.$icon ) .append( this.$indicator ); }; /* Setup */ OO.inheritClass( OO.ui.DecoratedOptionWidget, OO.ui.OptionWidget ); OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.DecoratedOptionWidget, OO.ui.mixin.IndicatorElement ); /** * MenuOptionWidget is an option widget that looks like a menu item. The class is used with * OO.ui.MenuSelectWidget to create a menu of mutually exclusive options. Please see * the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.DecoratedOptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MenuOptionWidget = function OoUiMenuOptionWidget( config ) { // Configuration initialization config = $.extend( { icon: 'check' }, config ); // Parent constructor OO.ui.MenuOptionWidget.parent.call( this, config ); // Initialization this.$element .attr( 'role', 'menuitem' ) .addClass( 'oo-ui-menuOptionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuOptionWidget, OO.ui.DecoratedOptionWidget ); /* Static Properties */ OO.ui.MenuOptionWidget.static.scrollIntoViewOnSelect = true; /** * MenuSectionOptionWidgets are used inside {@link OO.ui.MenuSelectWidget menu select widgets} to group one or more related * {@link OO.ui.MenuOptionWidget menu options}. MenuSectionOptionWidgets cannot be highlighted or selected. * * @example * var myDropdown = new OO.ui.DropdownWidget( { * menu: { * items: [ * new OO.ui.MenuSectionOptionWidget( { * label: 'Dogs' * } ), * new OO.ui.MenuOptionWidget( { * data: 'corgi', * label: 'Welsh Corgi' * } ), * new OO.ui.MenuOptionWidget( { * data: 'poodle', * label: 'Standard Poodle' * } ), * new OO.ui.MenuSectionOptionWidget( { * label: 'Cats' * } ), * new OO.ui.MenuOptionWidget( { * data: 'lion', * label: 'Lion' * } ) * ] * } * } ); * $( 'body' ).append( myDropdown.$element ); * * @class * @extends OO.ui.DecoratedOptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.MenuSectionOptionWidget = function OoUiMenuSectionOptionWidget( config ) { // Parent constructor OO.ui.MenuSectionOptionWidget.parent.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-menuSectionOptionWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuSectionOptionWidget, OO.ui.DecoratedOptionWidget ); /* Static Properties */ OO.ui.MenuSectionOptionWidget.static.selectable = false; OO.ui.MenuSectionOptionWidget.static.highlightable = false; /** * MenuSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains options and * is used together with OO.ui.MenuOptionWidget. It is designed be used as part of another widget. * See {@link OO.ui.DropdownWidget DropdownWidget}, {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget}, * and {@link OO.ui.mixin.LookupElement LookupElement} for examples of widgets that contain menus. * MenuSelectWidgets themselves are not instantiated directly, rather subclassed * and customized to be opened, closed, and displayed as needed. * * By default, menus are clipped to the visible viewport and are not visible when a user presses the * mouse outside the menu. * * Menus also have support for keyboard interaction: * * - Enter/Return key: choose and select a menu option * - Up-arrow key: highlight the previous menu option * - Down-arrow key: highlight the next menu option * - Esc key: hide the menu * * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.mixin.ClippableElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.TextInputWidget} [input] Text input used to implement option highlighting for menu items that match * the text the user types. This config is used by {@link OO.ui.ComboBoxInputWidget ComboBoxInputWidget} * and {@link OO.ui.mixin.LookupElement LookupElement} * @cfg {jQuery} [$input] Text input used to implement option highlighting for menu items that match * the text the user types. This config is used by {@link OO.ui.CapsuleMultiselectWidget CapsuleMultiselectWidget} * @cfg {OO.ui.Widget} [widget] Widget associated with the menu's active state. If the user clicks the mouse * anywhere on the page outside of this widget, the menu is hidden. For example, if there is a button * that toggles the menu's visibility on click, the menu will be hidden then re-shown when the user clicks * that button, unless the button (or its parent widget) is passed in here. * @cfg {boolean} [autoHide=true] Hide the menu when the mouse is pressed outside the menu. * @cfg {boolean} [filterFromInput=false] Filter the displayed options from the input */ OO.ui.MenuSelectWidget = function OoUiMenuSelectWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.MenuSelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ClippableElement.call( this, $.extend( {}, config, { $clippable: this.$group } ) ); // Properties this.autoHide = config.autoHide === undefined || !!config.autoHide; this.filterFromInput = !!config.filterFromInput; this.$input = config.$input ? config.$input : config.input ? config.input.$input : null; this.$widget = config.widget ? config.widget.$element : null; this.onDocumentMouseDownHandler = this.onDocumentMouseDown.bind( this ); this.onInputEditHandler = OO.ui.debounce( this.updateItemVisibility.bind( this ), 100 ); // Initialization this.$element .addClass( 'oo-ui-menuSelectWidget' ) .attr( 'role', 'menu' ); // Initially hidden - using #toggle may cause errors if subclasses override toggle with methods // that reference properties not initialized at that time of parent class construction // TODO: Find a better way to handle post-constructor setup this.visible = false; this.$element.addClass( 'oo-ui-element-hidden' ); }; /* Setup */ OO.inheritClass( OO.ui.MenuSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.MenuSelectWidget, OO.ui.mixin.ClippableElement ); /* Methods */ /** * Handles document mouse down events. * * @protected * @param {MouseEvent} e Mouse down event */ OO.ui.MenuSelectWidget.prototype.onDocumentMouseDown = function ( e ) { if ( !OO.ui.contains( this.$element[ 0 ], e.target, true ) && ( !this.$widget || !OO.ui.contains( this.$widget[ 0 ], e.target, true ) ) ) { this.toggle( false ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.onKeyDown = function ( e ) { var currentItem = this.getHighlightedItem() || this.getSelectedItem(); if ( !this.isDisabled() && this.isVisible() ) { switch ( e.keyCode ) { case OO.ui.Keys.LEFT: case OO.ui.Keys.RIGHT: // Do nothing if a text field is associated, arrow keys will be handled natively if ( !this.$input ) { OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e ); } break; case OO.ui.Keys.ESCAPE: case OO.ui.Keys.TAB: if ( currentItem ) { currentItem.setHighlighted( false ); } this.toggle( false ); // Don't prevent tabbing away, prevent defocusing if ( e.keyCode === OO.ui.Keys.ESCAPE ) { e.preventDefault(); e.stopPropagation(); } break; default: OO.ui.MenuSelectWidget.parent.prototype.onKeyDown.call( this, e ); return; } } }; /** * Update menu item visibility after input changes. * * @protected */ OO.ui.MenuSelectWidget.prototype.updateItemVisibility = function () { var i, item, len = this.items.length, showAll = !this.isVisible(), filter = showAll ? null : this.getItemMatcher( this.$input.val() ); for ( i = 0; i < len; i++ ) { item = this.items[ i ]; if ( item instanceof OO.ui.OptionWidget ) { item.toggle( showAll || filter( item ) ); } } // Reevaluate clipping this.clip(); }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.bindKeyDownListener = function () { if ( this.$input ) { this.$input.on( 'keydown', this.onKeyDownHandler ); } else { OO.ui.MenuSelectWidget.parent.prototype.bindKeyDownListener.call( this ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.unbindKeyDownListener = function () { if ( this.$input ) { this.$input.off( 'keydown', this.onKeyDownHandler ); } else { OO.ui.MenuSelectWidget.parent.prototype.unbindKeyDownListener.call( this ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.bindKeyPressListener = function () { if ( this.$input ) { if ( this.filterFromInput ) { this.$input.on( 'keydown mouseup cut paste change input select', this.onInputEditHandler ); } } else { OO.ui.MenuSelectWidget.parent.prototype.bindKeyPressListener.call( this ); } }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.unbindKeyPressListener = function () { if ( this.$input ) { if ( this.filterFromInput ) { this.$input.off( 'keydown mouseup cut paste change input select', this.onInputEditHandler ); this.updateItemVisibility(); } } else { OO.ui.MenuSelectWidget.parent.prototype.unbindKeyPressListener.call( this ); } }; /** * Choose an item. * * When a user chooses an item, the menu is closed. * * Note that ‘choose’ should never be modified programmatically. A user can choose an option with the keyboard * or mouse and it becomes selected. To select an item programmatically, use the #selectItem method. * * @param {OO.ui.OptionWidget} item Item to choose * @chainable */ OO.ui.MenuSelectWidget.prototype.chooseItem = function ( item ) { OO.ui.MenuSelectWidget.parent.prototype.chooseItem.call( this, item ); this.toggle( false ); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.addItems = function ( items, index ) { // Parent method OO.ui.MenuSelectWidget.parent.prototype.addItems.call( this, items, index ); // Reevaluate clipping this.clip(); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.removeItems = function ( items ) { // Parent method OO.ui.MenuSelectWidget.parent.prototype.removeItems.call( this, items ); // Reevaluate clipping this.clip(); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.clearItems = function () { // Parent method OO.ui.MenuSelectWidget.parent.prototype.clearItems.call( this ); // Reevaluate clipping this.clip(); return this; }; /** * @inheritdoc */ OO.ui.MenuSelectWidget.prototype.toggle = function ( visible ) { var change; visible = ( visible === undefined ? !this.visible : !!visible ) && !!this.items.length; change = visible !== this.isVisible(); // Parent method OO.ui.MenuSelectWidget.parent.prototype.toggle.call( this, visible ); if ( change ) { if ( visible ) { this.bindKeyDownListener(); this.bindKeyPressListener(); this.toggleClipping( true ); if ( this.getSelectedItem() ) { this.getSelectedItem().scrollElementIntoView( { duration: 0 } ); } // Auto-hide if ( this.autoHide ) { this.getElementDocument().addEventListener( 'mousedown', this.onDocumentMouseDownHandler, true ); } } else { this.unbindKeyDownListener(); this.unbindKeyPressListener(); this.getElementDocument().removeEventListener( 'mousedown', this.onDocumentMouseDownHandler, true ); this.toggleClipping( false ); } } return this; }; /** * DropdownWidgets are not menus themselves, rather they contain a menu of options created with * OO.ui.MenuOptionWidget. The DropdownWidget takes care of opening and displaying the menu so that * users can interact with it. * * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use * OO.ui.DropdownInputWidget instead. * * @example * // Example: A DropdownWidget with a menu that contains three options * var dropDown = new OO.ui.DropdownWidget( { * label: 'Dropdown menu: Select a menu option', * menu: { * items: [ * new OO.ui.MenuOptionWidget( { * data: 'a', * label: 'First' * } ), * new OO.ui.MenuOptionWidget( { * data: 'b', * label: 'Second' * } ), * new OO.ui.MenuOptionWidget( { * data: 'c', * label: 'Third' * } ) * ] * } * } ); * * $( 'body' ).append( dropDown.$element ); * * dropDown.getMenu().selectItemByData( 'b' ); * * dropDown.getMenu().getSelectedItem().getData(); // returns 'b' * * For more information, please see the [OOjs UI documentation on MediaWiki] [1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {Object} [menu] Configuration options to pass to {@link OO.ui.FloatingMenuSelectWidget menu select widget} * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the * containing `<div>` and has a larger area. By default, the menu uses relative positioning. */ OO.ui.DropdownWidget = function OoUiDropdownWidget( config ) { // Configuration initialization config = $.extend( { indicator: 'down' }, config ); // Parent constructor OO.ui.DropdownWidget.parent.call( this, config ); // Properties (must be set before TabIndexedElement constructor call) this.$handle = this.$( '<span>' ); this.$overlay = config.$overlay || this.$element; // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$handle } ) ); // Properties this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( { widget: this, $container: this.$element }, config.menu ) ); // Events this.$handle.on( { click: this.onClick.bind( this ), keydown: this.onKeyDown.bind( this ), // Hack? Handle type-to-search when menu is not expanded and not handling its own events keypress: this.menu.onKeyPressHandler, blur: this.menu.clearKeyPressBuffer.bind( this.menu ) } ); this.menu.connect( this, { select: 'onMenuSelect', toggle: 'onMenuToggle' } ); // Initialization this.$handle .addClass( 'oo-ui-dropdownWidget-handle' ) .append( this.$icon, this.$label, this.$indicator ); this.$element .addClass( 'oo-ui-dropdownWidget' ) .append( this.$handle ); this.$overlay.append( this.menu.$element ); }; /* Setup */ OO.inheritClass( OO.ui.DropdownWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.DropdownWidget, OO.ui.mixin.TabIndexedElement ); /* Methods */ /** * Get the menu. * * @return {OO.ui.MenuSelectWidget} Menu of widget */ OO.ui.DropdownWidget.prototype.getMenu = function () { return this.menu; }; /** * Handles menu select events. * * @private * @param {OO.ui.MenuOptionWidget} item Selected menu item */ OO.ui.DropdownWidget.prototype.onMenuSelect = function ( item ) { var selectedLabel; if ( !item ) { this.setLabel( null ); return; } selectedLabel = item.getLabel(); // If the label is a DOM element, clone it, because setLabel will append() it if ( selectedLabel instanceof jQuery ) { selectedLabel = selectedLabel.clone(); } this.setLabel( selectedLabel ); }; /** * Handle menu toggle events. * * @private * @param {boolean} isVisible Menu toggle event */ OO.ui.DropdownWidget.prototype.onMenuToggle = function ( isVisible ) { this.$element.toggleClass( 'oo-ui-dropdownWidget-open', isVisible ); }; /** * Handle mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.DropdownWidget.prototype.onClick = function ( e ) { if ( !this.isDisabled() && e.which === OO.ui.MouseButtons.LEFT ) { this.menu.toggle(); } return false; }; /** * Handle key down events. * * @private * @param {jQuery.Event} e Key down event */ OO.ui.DropdownWidget.prototype.onKeyDown = function ( e ) { if ( !this.isDisabled() && ( e.which === OO.ui.Keys.ENTER || ( !this.menu.isVisible() && ( e.which === OO.ui.Keys.SPACE || e.which === OO.ui.Keys.UP || e.which === OO.ui.Keys.DOWN ) ) ) ) { this.menu.toggle(); return false; } }; /** * RadioOptionWidget is an option widget that looks like a radio button. * The class is used with OO.ui.RadioSelectWidget to create a selection of radio options. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option * * @class * @extends OO.ui.OptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.RadioOptionWidget = function OoUiRadioOptionWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.radio = new OO.ui.RadioInputWidget( { value: config.data, tabIndex: -1 } ); // Parent constructor OO.ui.RadioOptionWidget.parent.call( this, config ); // Initialization // Remove implicit role, we're handling it ourselves this.radio.$input.attr( 'role', 'presentation' ); this.$element .addClass( 'oo-ui-radioOptionWidget' ) .attr( 'role', 'radio' ) .attr( 'aria-checked', 'false' ) .removeAttr( 'aria-selected' ) .prepend( this.radio.$element ); }; /* Setup */ OO.inheritClass( OO.ui.RadioOptionWidget, OO.ui.OptionWidget ); /* Static Properties */ OO.ui.RadioOptionWidget.static.highlightable = false; OO.ui.RadioOptionWidget.static.scrollIntoViewOnSelect = true; OO.ui.RadioOptionWidget.static.pressable = false; OO.ui.RadioOptionWidget.static.tagName = 'label'; /* Methods */ /** * @inheritdoc */ OO.ui.RadioOptionWidget.prototype.setSelected = function ( state ) { OO.ui.RadioOptionWidget.parent.prototype.setSelected.call( this, state ); this.radio.setSelected( state ); this.$element .attr( 'aria-checked', state.toString() ) .removeAttr( 'aria-selected' ); return this; }; /** * @inheritdoc */ OO.ui.RadioOptionWidget.prototype.setDisabled = function ( disabled ) { OO.ui.RadioOptionWidget.parent.prototype.setDisabled.call( this, disabled ); this.radio.setDisabled( this.isDisabled() ); return this; }; /** * RadioSelectWidget is a {@link OO.ui.SelectWidget select widget} that contains radio * options and is used together with OO.ui.RadioOptionWidget. The RadioSelectWidget provides * an interface for adding, removing and selecting options. * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use * OO.ui.RadioSelectInputWidget instead. * * @example * // A RadioSelectWidget with RadioOptions. * var option1 = new OO.ui.RadioOptionWidget( { * data: 'a', * label: 'Selected radio option' * } ); * * var option2 = new OO.ui.RadioOptionWidget( { * data: 'b', * label: 'Unselected radio option' * } ); * * var radioSelect=new OO.ui.RadioSelectWidget( { * items: [ option1, option2 ] * } ); * * // Select 'option 1' using the RadioSelectWidget's selectItem() method. * radioSelect.selectItem( option1 ); * * $( 'body' ).append( radioSelect.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.SelectWidget * @mixins OO.ui.mixin.TabIndexedElement * * @constructor * @param {Object} [config] Configuration options */ OO.ui.RadioSelectWidget = function OoUiRadioSelectWidget( config ) { // Parent constructor OO.ui.RadioSelectWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.TabIndexedElement.call( this, config ); // Events this.$element.on( { focus: this.bindKeyDownListener.bind( this ), blur: this.unbindKeyDownListener.bind( this ) } ); // Initialization this.$element .addClass( 'oo-ui-radioSelectWidget' ) .attr( 'role', 'radiogroup' ); }; /* Setup */ OO.inheritClass( OO.ui.RadioSelectWidget, OO.ui.SelectWidget ); OO.mixinClass( OO.ui.RadioSelectWidget, OO.ui.mixin.TabIndexedElement ); /** * MultioptionWidgets are special elements that can be selected and configured with data. The * data is often unique for each option, but it does not have to be. MultioptionWidgets are used * with OO.ui.SelectWidget to create a selection of mutually exclusive options. For more information * and examples, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Multioptions * * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.ItemWidget * @mixins OO.ui.mixin.LabelElement * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [selected=false] Whether the option is initially selected */ OO.ui.MultioptionWidget = function OoUiMultioptionWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.MultioptionWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ItemWidget.call( this ); OO.ui.mixin.LabelElement.call( this, config ); // Properties this.selected = null; // Initialization this.$element .addClass( 'oo-ui-multioptionWidget' ) .append( this.$label ); this.setSelected( config.selected ); }; /* Setup */ OO.inheritClass( OO.ui.MultioptionWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.ItemWidget ); OO.mixinClass( OO.ui.MultioptionWidget, OO.ui.mixin.LabelElement ); /* Events */ /** * @event change * * A change event is emitted when the selected state of the option changes. * * @param {boolean} selected Whether the option is now selected */ /* Methods */ /** * Check if the option is selected. * * @return {boolean} Item is selected */ OO.ui.MultioptionWidget.prototype.isSelected = function () { return this.selected; }; /** * Set the option’s selected state. In general, all modifications to the selection * should be handled by the SelectWidget’s {@link OO.ui.SelectWidget#selectItem selectItem( [item] )} * method instead of this method. * * @param {boolean} [state=false] Select option * @chainable */ OO.ui.MultioptionWidget.prototype.setSelected = function ( state ) { state = !!state; if ( this.selected !== state ) { this.selected = state; this.emit( 'change', state ); this.$element.toggleClass( 'oo-ui-multioptionWidget-selected', state ); } return this; }; /** * MultiselectWidget allows selecting multiple options from a list. * * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1]. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @abstract * @extends OO.ui.Widget * @mixins OO.ui.mixin.GroupWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.MultioptionWidget[]} [items] An array of options to add to the multiselect. */ OO.ui.MultiselectWidget = function OoUiMultiselectWidget( config ) { // Parent constructor OO.ui.MultiselectWidget.parent.call( this, config ); // Configuration initialization config = config || {}; // Mixin constructors OO.ui.mixin.GroupWidget.call( this, config ); // Events this.aggregate( { change: 'select' } ); // This is mostly for compatibility with CapsuleMultiselectWidget... normally, 'change' is emitted // by GroupElement only when items are added/removed this.connect( this, { select: [ 'emit', 'change' ] } ); // Initialization if ( config.items ) { this.addItems( config.items ); } this.$group.addClass( 'oo-ui-multiselectWidget-group' ); this.$element.addClass( 'oo-ui-multiselectWidget' ) .append( this.$group ); }; /* Setup */ OO.inheritClass( OO.ui.MultiselectWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.MultiselectWidget, OO.ui.mixin.GroupWidget ); /* Events */ /** * @event change * * A change event is emitted when the set of items changes, or an item is selected or deselected. */ /** * @event select * * A select event is emitted when an item is selected or deselected. */ /* Methods */ /** * Get options that are selected. * * @return {OO.ui.MultioptionWidget[]} Selected options */ OO.ui.MultiselectWidget.prototype.getSelectedItems = function () { return this.items.filter( function ( item ) { return item.isSelected(); } ); }; /** * Get the data of options that are selected. * * @return {Object[]|string[]} Values of selected options */ OO.ui.MultiselectWidget.prototype.getSelectedItemsData = function () { return this.getSelectedItems().map( function ( item ) { return item.data; } ); }; /** * Select options by reference. Options not mentioned in the `items` array will be deselected. * * @param {OO.ui.MultioptionWidget[]} items Items to select * @chainable */ OO.ui.MultiselectWidget.prototype.selectItems = function ( items ) { this.items.forEach( function ( item ) { var selected = items.indexOf( item ) !== -1; item.setSelected( selected ); } ); return this; }; /** * Select items by their data. Options not mentioned in the `datas` array will be deselected. * * @param {Object[]|string[]} datas Values of items to select * @chainable */ OO.ui.MultiselectWidget.prototype.selectItemsByData = function ( datas ) { var items, widget = this; items = datas.map( function ( data ) { return widget.getItemFromData( data ); } ); this.selectItems( items ); return this; }; /** * CheckboxMultioptionWidget is an option widget that looks like a checkbox. * The class is used with OO.ui.CheckboxMultiselectWidget to create a selection of checkbox options. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Button_selects_and_option * * @class * @extends OO.ui.MultioptionWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.CheckboxMultioptionWidget = function OoUiCheckboxMultioptionWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.checkbox = new OO.ui.CheckboxInputWidget(); // Parent constructor OO.ui.CheckboxMultioptionWidget.parent.call( this, config ); // Events this.checkbox.on( 'change', this.onCheckboxChange.bind( this ) ); this.$element.on( 'keydown', this.onKeyDown.bind( this ) ); // Initialization this.$element .addClass( 'oo-ui-checkboxMultioptionWidget' ) .prepend( this.checkbox.$element ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxMultioptionWidget, OO.ui.MultioptionWidget ); /* Static Properties */ OO.ui.CheckboxMultioptionWidget.static.tagName = 'label'; /* Methods */ /** * Handle checkbox selected state change. * * @private */ OO.ui.CheckboxMultioptionWidget.prototype.onCheckboxChange = function () { this.setSelected( this.checkbox.isSelected() ); }; /** * @inheritdoc */ OO.ui.CheckboxMultioptionWidget.prototype.setSelected = function ( state ) { OO.ui.CheckboxMultioptionWidget.parent.prototype.setSelected.call( this, state ); this.checkbox.setSelected( state ); return this; }; /** * @inheritdoc */ OO.ui.CheckboxMultioptionWidget.prototype.setDisabled = function ( disabled ) { OO.ui.CheckboxMultioptionWidget.parent.prototype.setDisabled.call( this, disabled ); this.checkbox.setDisabled( this.isDisabled() ); return this; }; /** * Focus the widget. */ OO.ui.CheckboxMultioptionWidget.prototype.focus = function () { this.checkbox.focus(); }; /** * Handle key down events. * * @protected * @param {jQuery.Event} e */ OO.ui.CheckboxMultioptionWidget.prototype.onKeyDown = function ( e ) { var element = this.getElementGroup(), nextItem; if ( e.keyCode === OO.ui.Keys.LEFT || e.keyCode === OO.ui.Keys.UP ) { nextItem = element.getRelativeFocusableItem( this, -1 ); } else if ( e.keyCode === OO.ui.Keys.RIGHT || e.keyCode === OO.ui.Keys.DOWN ) { nextItem = element.getRelativeFocusableItem( this, 1 ); } if ( nextItem ) { e.preventDefault(); nextItem.focus(); } }; /** * CheckboxMultiselectWidget is a {@link OO.ui.MultiselectWidget multiselect widget} that contains * checkboxes and is used together with OO.ui.CheckboxMultioptionWidget. The * CheckboxMultiselectWidget provides an interface for adding, removing and selecting options. * Please see the [OOjs UI documentation on MediaWiki][1] for more information. * * If you want to use this within a HTML form, such as a OO.ui.FormLayout, use * OO.ui.CheckboxMultiselectInputWidget instead. * * @example * // A CheckboxMultiselectWidget with CheckboxMultioptions. * var option1 = new OO.ui.CheckboxMultioptionWidget( { * data: 'a', * selected: true, * label: 'Selected checkbox' * } ); * * var option2 = new OO.ui.CheckboxMultioptionWidget( { * data: 'b', * label: 'Unselected checkbox' * } ); * * var multiselect=new OO.ui.CheckboxMultiselectWidget( { * items: [ option1, option2 ] * } ); * * $( 'body' ).append( multiselect.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options * * @class * @extends OO.ui.MultiselectWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.CheckboxMultiselectWidget = function OoUiCheckboxMultiselectWidget( config ) { // Parent constructor OO.ui.CheckboxMultiselectWidget.parent.call( this, config ); // Properties this.$lastClicked = null; // Events this.$group.on( 'click', this.onClick.bind( this ) ); // Initialization this.$element .addClass( 'oo-ui-checkboxMultiselectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxMultiselectWidget, OO.ui.MultiselectWidget ); /* Methods */ /** * Get an option by its position relative to the specified item (or to the start of the option array, * if item is `null`). The direction in which to search through the option array is specified with a * number: -1 for reverse (the default) or 1 for forward. The method will return an option, or * `null` if there are no options in the array. * * @param {OO.ui.CheckboxMultioptionWidget|null} item Item to describe the start position, or `null` to start at the beginning of the array. * @param {number} direction Direction to move in: -1 to move backward, 1 to move forward * @return {OO.ui.CheckboxMultioptionWidget|null} Item at position, `null` if there are no items in the select */ OO.ui.CheckboxMultiselectWidget.prototype.getRelativeFocusableItem = function ( item, direction ) { var currentIndex, nextIndex, i, increase = direction > 0 ? 1 : -1, len = this.items.length; if ( item ) { currentIndex = this.items.indexOf( item ); nextIndex = ( currentIndex + increase + len ) % len; } else { // If no item is selected and moving forward, start at the beginning. // If moving backward, start at the end. nextIndex = direction > 0 ? 0 : len - 1; } for ( i = 0; i < len; i++ ) { item = this.items[ nextIndex ]; if ( item && !item.isDisabled() ) { return item; } nextIndex = ( nextIndex + increase + len ) % len; } return null; }; /** * Handle click events on checkboxes. * * @param {jQuery.Event} e */ OO.ui.CheckboxMultiselectWidget.prototype.onClick = function ( e ) { var $options, lastClickedIndex, nowClickedIndex, i, direction, wasSelected, items, $lastClicked = this.$lastClicked, $nowClicked = $( e.target ).closest( '.oo-ui-checkboxMultioptionWidget' ) .not( '.oo-ui-widget-disabled' ); // Allow selecting multiple options at once by Shift-clicking them if ( $lastClicked && $nowClicked.length && e.shiftKey ) { $options = this.$group.find( '.oo-ui-checkboxMultioptionWidget' ); lastClickedIndex = $options.index( $lastClicked ); nowClickedIndex = $options.index( $nowClicked ); // If it's the same item, either the user is being silly, or it's a fake event generated by the // browser. In either case we don't need custom handling. if ( nowClickedIndex !== lastClickedIndex ) { items = this.items; wasSelected = items[ nowClickedIndex ].isSelected(); direction = nowClickedIndex > lastClickedIndex ? 1 : -1; // This depends on the DOM order of the items and the order of the .items array being the same. for ( i = lastClickedIndex; i !== nowClickedIndex; i += direction ) { if ( !items[ i ].isDisabled() ) { items[ i ].setSelected( !wasSelected ); } } // For the now-clicked element, use immediate timeout to allow the browser to do its own // handling first, then set our value. The order in which events happen is different for // clicks on the <input> and on the <label> and there are additional fake clicks fired for // non-click actions that change the checkboxes. e.preventDefault(); setTimeout( function () { if ( !items[ nowClickedIndex ].isDisabled() ) { items[ nowClickedIndex ].setSelected( !wasSelected ); } } ); } } if ( $nowClicked.length ) { this.$lastClicked = $nowClicked; } }; /** * Element that will stick under a specified container, even when it is inserted elsewhere in the * document (for example, in a OO.ui.Window's $overlay). * * The elements's position is automatically calculated and maintained when window is resized or the * page is scrolled. If you reposition the container manually, you have to call #position to make * sure the element is still placed correctly. * * As positioning is only possible when both the element and the container are attached to the DOM * and visible, it's only done after you call #togglePositioning. You might want to do this inside * the #toggle method to display a floating popup, for example. * * @abstract * @class * * @constructor * @param {Object} [config] Configuration options * @cfg {jQuery} [$floatable] Node to position, assigned to #$floatable, omit to use #$element * @cfg {jQuery} [$floatableContainer] Node to position below */ OO.ui.mixin.FloatableElement = function OoUiMixinFloatableElement( config ) { // Configuration initialization config = config || {}; // Properties this.$floatable = null; this.$floatableContainer = null; this.$floatableWindow = null; this.$floatableClosestScrollable = null; this.onFloatableScrollHandler = this.position.bind( this ); this.onFloatableWindowResizeHandler = this.position.bind( this ); // Initialization this.setFloatableContainer( config.$floatableContainer ); this.setFloatableElement( config.$floatable || this.$element ); }; /* Methods */ /** * Set floatable element. * * If an element is already set, it will be cleaned up before setting up the new element. * * @param {jQuery} $floatable Element to make floatable */ OO.ui.mixin.FloatableElement.prototype.setFloatableElement = function ( $floatable ) { if ( this.$floatable ) { this.$floatable.removeClass( 'oo-ui-floatableElement-floatable' ); this.$floatable.css( { left: '', top: '' } ); } this.$floatable = $floatable.addClass( 'oo-ui-floatableElement-floatable' ); this.position(); }; /** * Set floatable container. * * The element will be always positioned under the specified container. * * @param {jQuery|null} $floatableContainer Container to keep visible, or null to unset */ OO.ui.mixin.FloatableElement.prototype.setFloatableContainer = function ( $floatableContainer ) { this.$floatableContainer = $floatableContainer; if ( this.$floatable ) { this.position(); } }; /** * Toggle positioning. * * Do not turn positioning on until after the element is attached to the DOM and visible. * * @param {boolean} [positioning] Enable positioning, omit to toggle * @chainable */ OO.ui.mixin.FloatableElement.prototype.togglePositioning = function ( positioning ) { var closestScrollableOfContainer, closestScrollableOfFloatable; positioning = positioning === undefined ? !this.positioning : !!positioning; if ( this.positioning !== positioning ) { this.positioning = positioning; closestScrollableOfContainer = OO.ui.Element.static.getClosestScrollableContainer( this.$floatableContainer[ 0 ] ); closestScrollableOfFloatable = OO.ui.Element.static.getClosestScrollableContainer( this.$floatable[ 0 ] ); this.needsCustomPosition = closestScrollableOfContainer !== closestScrollableOfFloatable; // If the scrollable is the root, we have to listen to scroll events // on the window because of browser inconsistencies. if ( $( closestScrollableOfContainer ).is( 'html, body' ) ) { closestScrollableOfContainer = OO.ui.Element.static.getWindow( closestScrollableOfContainer ); } if ( positioning ) { this.$floatableWindow = $( this.getElementWindow() ); this.$floatableWindow.on( 'resize', this.onFloatableWindowResizeHandler ); this.$floatableClosestScrollable = $( closestScrollableOfContainer ); this.$floatableClosestScrollable.on( 'scroll', this.onFloatableScrollHandler ); // Initial position after visible this.position(); } else { if ( this.$floatableWindow ) { this.$floatableWindow.off( 'resize', this.onFloatableWindowResizeHandler ); this.$floatableWindow = null; } if ( this.$floatableClosestScrollable ) { this.$floatableClosestScrollable.off( 'scroll', this.onFloatableScrollHandler ); this.$floatableClosestScrollable = null; } this.$floatable.css( { left: '', top: '' } ); } } return this; }; /** * Check whether the bottom edge of the given element is within the viewport of the given container. * * @private * @param {jQuery} $element * @param {jQuery} $container * @return {boolean} */ OO.ui.mixin.FloatableElement.prototype.isElementInViewport = function ( $element, $container ) { var elemRect, contRect, leftEdgeInBounds = false, bottomEdgeInBounds = false, rightEdgeInBounds = false; elemRect = $element[ 0 ].getBoundingClientRect(); if ( $container[ 0 ] === window ) { contRect = { top: 0, left: 0, right: document.documentElement.clientWidth, bottom: document.documentElement.clientHeight }; } else { contRect = $container[ 0 ].getBoundingClientRect(); } // For completeness, if we still cared about topEdgeInBounds, that'd be: // elemRect.top >= contRect.top && elemRect.top <= contRect.bottom if ( elemRect.left >= contRect.left && elemRect.left <= contRect.right ) { leftEdgeInBounds = true; } if ( elemRect.bottom >= contRect.top && elemRect.bottom <= contRect.bottom ) { bottomEdgeInBounds = true; } if ( elemRect.right >= contRect.left && elemRect.right <= contRect.right ) { rightEdgeInBounds = true; } // We only care that any part of the bottom edge is visible return bottomEdgeInBounds && ( leftEdgeInBounds || rightEdgeInBounds ); }; /** * Position the floatable below its container. * * This should only be done when both of them are attached to the DOM and visible. * * @chainable */ OO.ui.mixin.FloatableElement.prototype.position = function () { var pos; if ( !this.positioning ) { return this; } if ( !this.isElementInViewport( this.$floatableContainer, this.$floatableClosestScrollable ) ) { this.$floatable.addClass( 'oo-ui-element-hidden' ); return; } else { this.$floatable.removeClass( 'oo-ui-element-hidden' ); } if ( !this.needsCustomPosition ) { return; } pos = OO.ui.Element.static.getRelativePosition( this.$floatableContainer, this.$floatable.offsetParent() ); // Position under container pos.top += this.$floatableContainer.height(); this.$floatable.css( pos ); // We updated the position, so re-evaluate the clipping state. // (ClippableElement does not listen to 'scroll' events on $floatableContainer's parent, and so // will not notice the need to update itself.) // TODO: This is terrible, we shouldn't need to know about ClippableElement at all here. Why does // it not listen to the right events in the right places? if ( this.clip ) { this.clip(); } return this; }; /** * FloatingMenuSelectWidget is a menu that will stick under a specified * container, even when it is inserted elsewhere in the document (for example, * in a OO.ui.Window's $overlay). This is sometimes necessary to prevent the * menu from being clipped too aggresively. * * The menu's position is automatically calculated and maintained when the menu * is toggled or the window is resized. * * See OO.ui.ComboBoxInputWidget for an example of a widget that uses this class. * * @class * @extends OO.ui.MenuSelectWidget * @mixins OO.ui.mixin.FloatableElement * * @constructor * @param {OO.ui.Widget} [inputWidget] Widget to provide the menu for. * Deprecated, omit this parameter and specify `$container` instead. * @param {Object} [config] Configuration options * @cfg {jQuery} [$container=inputWidget.$element] Element to render menu under */ OO.ui.FloatingMenuSelectWidget = function OoUiFloatingMenuSelectWidget( inputWidget, config ) { // Allow 'inputWidget' parameter and config for backwards compatibility if ( OO.isPlainObject( inputWidget ) && config === undefined ) { config = inputWidget; inputWidget = config.inputWidget; } // Configuration initialization config = config || {}; // Parent constructor OO.ui.FloatingMenuSelectWidget.parent.call( this, config ); // Properties (must be set before mixin constructors) this.inputWidget = inputWidget; // For backwards compatibility this.$container = config.$container || this.inputWidget.$element; // Mixins constructors OO.ui.mixin.FloatableElement.call( this, $.extend( {}, config, { $floatableContainer: this.$container } ) ); // Initialization this.$element.addClass( 'oo-ui-floatingMenuSelectWidget' ); // For backwards compatibility this.$element.addClass( 'oo-ui-textInputMenuSelectWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.FloatingMenuSelectWidget, OO.ui.MenuSelectWidget ); OO.mixinClass( OO.ui.FloatingMenuSelectWidget, OO.ui.mixin.FloatableElement ); // For backwards compatibility OO.ui.TextInputMenuSelectWidget = OO.ui.FloatingMenuSelectWidget; /* Methods */ /** * @inheritdoc */ OO.ui.FloatingMenuSelectWidget.prototype.toggle = function ( visible ) { var change; visible = visible === undefined ? !this.isVisible() : !!visible; change = visible !== this.isVisible(); if ( change && visible ) { // Make sure the width is set before the parent method runs. this.setIdealSize( this.$container.width() ); } // Parent method // This will call this.clip(), which is nonsensical since we're not positioned yet... OO.ui.FloatingMenuSelectWidget.parent.prototype.toggle.call( this, visible ); if ( change ) { this.togglePositioning( this.isVisible() ); } return this; }; /** * Progress bars visually display the status of an operation, such as a download, * and can be either determinate or indeterminate: * * - **determinate** process bars show the percent of an operation that is complete. * * - **indeterminate** process bars use a visual display of motion to indicate that an operation * is taking place. Because the extent of an indeterminate operation is unknown, the bar does * not use percentages. * * The value of the `progress` configuration determines whether the bar is determinate or indeterminate. * * @example * // Examples of determinate and indeterminate progress bars. * var progressBar1 = new OO.ui.ProgressBarWidget( { * progress: 33 * } ); * var progressBar2 = new OO.ui.ProgressBarWidget(); * * // Create a FieldsetLayout to layout progress bars * var fieldset = new OO.ui.FieldsetLayout; * fieldset.addItems( [ * new OO.ui.FieldLayout( progressBar1, {label: 'Determinate', align: 'top'}), * new OO.ui.FieldLayout( progressBar2, {label: 'Indeterminate', align: 'top'}) * ] ); * $( 'body' ).append( fieldset.$element ); * * @class * @extends OO.ui.Widget * * @constructor * @param {Object} [config] Configuration options * @cfg {number|boolean} [progress=false] The type of progress bar (determinate or indeterminate). * To create a determinate progress bar, specify a number that reflects the initial percent complete. * By default, the progress bar is indeterminate. */ OO.ui.ProgressBarWidget = function OoUiProgressBarWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.ProgressBarWidget.parent.call( this, config ); // Properties this.$bar = $( '<div>' ); this.progress = null; // Initialization this.setProgress( config.progress !== undefined ? config.progress : false ); this.$bar.addClass( 'oo-ui-progressBarWidget-bar' ); this.$element .attr( { role: 'progressbar', 'aria-valuemin': 0, 'aria-valuemax': 100 } ) .addClass( 'oo-ui-progressBarWidget' ) .append( this.$bar ); }; /* Setup */ OO.inheritClass( OO.ui.ProgressBarWidget, OO.ui.Widget ); /* Static Properties */ OO.ui.ProgressBarWidget.static.tagName = 'div'; /* Methods */ /** * Get the percent of the progress that has been completed. Indeterminate progresses will return `false`. * * @return {number|boolean} Progress percent */ OO.ui.ProgressBarWidget.prototype.getProgress = function () { return this.progress; }; /** * Set the percent of the process completed or `false` for an indeterminate process. * * @param {number|boolean} progress Progress percent or `false` for indeterminate */ OO.ui.ProgressBarWidget.prototype.setProgress = function ( progress ) { this.progress = progress; if ( progress !== false ) { this.$bar.css( 'width', this.progress + '%' ); this.$element.attr( 'aria-valuenow', this.progress ); } else { this.$bar.css( 'width', '' ); this.$element.removeAttr( 'aria-valuenow' ); } this.$element.toggleClass( 'oo-ui-progressBarWidget-indeterminate', progress === false ); }; /** * InputWidget is the base class for all input widgets, which * include {@link OO.ui.TextInputWidget text inputs}, {@link OO.ui.CheckboxInputWidget checkbox inputs}, * {@link OO.ui.RadioInputWidget radio inputs}, and {@link OO.ui.ButtonInputWidget button inputs}. * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @abstract * @class * @extends OO.ui.Widget * @mixins OO.ui.mixin.FlaggedElement * @mixins OO.ui.mixin.TabIndexedElement * @mixins OO.ui.mixin.TitledElement * @mixins OO.ui.mixin.AccessKeyedElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [name=''] The value of the input’s HTML `name` attribute. * @cfg {string} [value=''] The value of the input. * @cfg {string} [dir] The directionality of the input (ltr/rtl). * @cfg {Function} [inputFilter] The name of an input filter function. Input filters modify the value of an input * before it is accepted. */ OO.ui.InputWidget = function OoUiInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.InputWidget.parent.call( this, config ); // Properties // See #reusePreInfuseDOM about config.$input this.$input = config.$input || this.getInputElement( config ); this.value = ''; this.inputFilter = config.inputFilter; // Mixin constructors OO.ui.mixin.FlaggedElement.call( this, config ); OO.ui.mixin.TabIndexedElement.call( this, $.extend( {}, config, { $tabIndexed: this.$input } ) ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) ); OO.ui.mixin.AccessKeyedElement.call( this, $.extend( {}, config, { $accessKeyed: this.$input } ) ); // Events this.$input.on( 'keydown mouseup cut paste change input select', this.onEdit.bind( this ) ); // Initialization this.$input .addClass( 'oo-ui-inputWidget-input' ) .attr( 'name', config.name ) .prop( 'disabled', this.isDisabled() ); this.$element .addClass( 'oo-ui-inputWidget' ) .append( this.$input ); this.setValue( config.value ); if ( config.dir ) { this.setDir( config.dir ); } }; /* Setup */ OO.inheritClass( OO.ui.InputWidget, OO.ui.Widget ); OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.FlaggedElement ); OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TabIndexedElement ); OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.TitledElement ); OO.mixinClass( OO.ui.InputWidget, OO.ui.mixin.AccessKeyedElement ); /* Static Properties */ OO.ui.InputWidget.static.supportsSimpleLabel = true; /* Static Methods */ /** * @inheritdoc */ OO.ui.InputWidget.static.reusePreInfuseDOM = function ( node, config ) { config = OO.ui.InputWidget.parent.static.reusePreInfuseDOM( node, config ); // Reusing $input lets browsers preserve inputted values across page reloads (T114134) config.$input = $( node ).find( '.oo-ui-inputWidget-input' ); return config; }; /** * @inheritdoc */ OO.ui.InputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.InputWidget.parent.static.gatherPreInfuseState( node, config ); if ( config.$input && config.$input.length ) { state.value = config.$input.val(); // Might be better in TabIndexedElement, but it's awkward to do there because mixins are awkward state.focus = config.$input.is( ':focus' ); } return state; }; /* Events */ /** * @event change * * A change event is emitted when the value of the input changes. * * @param {string} value */ /* Methods */ /** * Get input element. * * Subclasses of OO.ui.InputWidget use the `config` parameter to produce different elements in * different circumstances. The element must have a `value` property (like form elements). * * @protected * @param {Object} config Configuration options * @return {jQuery} Input element */ OO.ui.InputWidget.prototype.getInputElement = function () { return $( '<input>' ); }; /** * Handle potentially value-changing events. * * @private * @param {jQuery.Event} e Key down, mouse up, cut, paste, change, input, or select event */ OO.ui.InputWidget.prototype.onEdit = function () { var widget = this; if ( !this.isDisabled() ) { // Allow the stack to clear so the value will be updated setTimeout( function () { widget.setValue( widget.$input.val() ); } ); } }; /** * Get the value of the input. * * @return {string} Input value */ OO.ui.InputWidget.prototype.getValue = function () { // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify // it, and we won't know unless they're kind enough to trigger a 'change' event. var value = this.$input.val(); if ( this.value !== value ) { this.setValue( value ); } return this.value; }; /** * Set the directionality of the input. * * @param {string} dir Text directionality: 'ltr', 'rtl' or 'auto' * @chainable */ OO.ui.InputWidget.prototype.setDir = function ( dir ) { this.$input.prop( 'dir', dir ); return this; }; /** * Set the value of the input. * * @param {string} value New value * @fires change * @chainable */ OO.ui.InputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); // Update the DOM if it has changed. Note that with cleanUpValue, it // is possible for the DOM value to change without this.value changing. if ( this.$input.val() !== value ) { this.$input.val( value ); } if ( this.value !== value ) { this.value = value; this.emit( 'change', this.value ); } return this; }; /** * Clean up incoming value. * * Ensures value is a string, and converts undefined and null to empty string. * * @private * @param {string} value Original value * @return {string} Cleaned up value */ OO.ui.InputWidget.prototype.cleanUpValue = function ( value ) { if ( value === undefined || value === null ) { return ''; } else if ( this.inputFilter ) { return this.inputFilter( String( value ) ); } else { return String( value ); } }; /** * Simulate the behavior of clicking on a label bound to this input. This method is only called by * {@link OO.ui.LabelWidget LabelWidget} and {@link OO.ui.FieldLayout FieldLayout}. It should not be * called directly. */ OO.ui.InputWidget.prototype.simulateLabelClick = function () { if ( !this.isDisabled() ) { if ( this.$input.is( ':checkbox, :radio' ) ) { this.$input.click(); } if ( this.$input.is( ':input' ) ) { this.$input[ 0 ].focus(); } } }; /** * @inheritdoc */ OO.ui.InputWidget.prototype.setDisabled = function ( state ) { OO.ui.InputWidget.parent.prototype.setDisabled.call( this, state ); if ( this.$input ) { this.$input.prop( 'disabled', this.isDisabled() ); } return this; }; /** * Focus the input. * * @chainable */ OO.ui.InputWidget.prototype.focus = function () { this.$input[ 0 ].focus(); return this; }; /** * Blur the input. * * @chainable */ OO.ui.InputWidget.prototype.blur = function () { this.$input[ 0 ].blur(); return this; }; /** * @inheritdoc */ OO.ui.InputWidget.prototype.restorePreInfuseState = function ( state ) { OO.ui.InputWidget.parent.prototype.restorePreInfuseState.call( this, state ); if ( state.value !== undefined && state.value !== this.getValue() ) { this.setValue( state.value ); } if ( state.focus ) { this.focus(); } }; /** * ButtonInputWidget is used to submit HTML forms and is intended to be used within * a OO.ui.FormLayout. If you do not need the button to work with HTML forms, you probably * want to use OO.ui.ButtonWidget instead. Button input widgets can be rendered as either an * HTML `<button>` (the default) or an HTML `<input>` tags. See the * [OOjs UI documentation on MediaWiki] [1] for more information. * * @example * // A ButtonInputWidget rendered as an HTML button, the default. * var button = new OO.ui.ButtonInputWidget( { * label: 'Input button', * icon: 'check', * value: 'check' * } ); * $( 'body' ).append( button.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs#Button_inputs * * @class * @extends OO.ui.InputWidget * @mixins OO.ui.mixin.ButtonElement * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [type='button'] The value of the HTML `'type'` attribute: 'button', 'submit' or 'reset'. * @cfg {boolean} [useInputTag=false] Use an `<input>` tag instead of a `<button>` tag, the default. * Widgets configured to be an `<input>` do not support {@link #icon icons} and {@link #indicator indicators}, * non-plaintext {@link #label labels}, or {@link #value values}. In general, useInputTag should only * be set to `true` when there’s need to support IE 6 in a form with multiple buttons. */ OO.ui.ButtonInputWidget = function OoUiButtonInputWidget( config ) { // Configuration initialization config = $.extend( { type: 'button', useInputTag: false }, config ); // See InputWidget#reusePreInfuseDOM about config.$input if ( config.$input ) { config.$input.empty(); } // Properties (must be set before parent constructor, which calls #setValue) this.useInputTag = config.useInputTag; // Parent constructor OO.ui.ButtonInputWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.ButtonElement.call( this, $.extend( {}, config, { $button: this.$input } ) ); OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$input } ) ); // Initialization if ( !config.useInputTag ) { this.$input.append( this.$icon, this.$label, this.$indicator ); } this.$element.addClass( 'oo-ui-buttonInputWidget' ); }; /* Setup */ OO.inheritClass( OO.ui.ButtonInputWidget, OO.ui.InputWidget ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.ButtonElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.ButtonInputWidget, OO.ui.mixin.TitledElement ); /* Static Properties */ /** * Disable generating `<label>` elements for buttons. One would very rarely need additional label * for a button, and it's already a big clickable target, and it causes unexpected rendering. */ OO.ui.ButtonInputWidget.static.supportsSimpleLabel = false; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.ButtonInputWidget.prototype.getInputElement = function ( config ) { var type; type = [ 'button', 'submit', 'reset' ].indexOf( config.type ) !== -1 ? config.type : 'button'; return $( '<' + ( config.useInputTag ? 'input' : 'button' ) + ' type="' + type + '">' ); }; /** * Set label value. * * If #useInputTag is `true`, the label is set as the `value` of the `<input>` tag. * * @param {jQuery|string|Function|null} label Label nodes, text, a function that returns nodes or * text, or `null` for no label * @chainable */ OO.ui.ButtonInputWidget.prototype.setLabel = function ( label ) { if ( typeof label === 'function' ) { label = OO.ui.resolveMsg( label ); } if ( this.useInputTag ) { // Discard non-plaintext labels if ( typeof label !== 'string' ) { label = ''; } this.$input.val( label ); } return OO.ui.mixin.LabelElement.prototype.setLabel.call( this, label ); }; /** * Set the value of the input. * * This method is disabled for button inputs configured as {@link #useInputTag <input> tags}, as * they do not support {@link #value values}. * * @param {string} value New value * @chainable */ OO.ui.ButtonInputWidget.prototype.setValue = function ( value ) { if ( !this.useInputTag ) { OO.ui.ButtonInputWidget.parent.prototype.setValue.call( this, value ); } return this; }; /** * CheckboxInputWidgets, like HTML checkboxes, can be selected and/or configured with a value. * Note that these {@link OO.ui.InputWidget input widgets} are best laid out * in {@link OO.ui.FieldLayout field layouts} that use the {@link OO.ui.FieldLayout#align inline} * alignment. For more information, please see the [OOjs UI documentation on MediaWiki][1]. * * This widget can be used inside a HTML form, such as a OO.ui.FormLayout. * * @example * // An example of selected, unselected, and disabled checkbox inputs * var checkbox1=new OO.ui.CheckboxInputWidget( { * value: 'a', * selected: true * } ); * var checkbox2=new OO.ui.CheckboxInputWidget( { * value: 'b' * } ); * var checkbox3=new OO.ui.CheckboxInputWidget( { * value:'c', * disabled: true * } ); * // Create a fieldset layout with fields for each checkbox. * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Checkboxes' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( checkbox1, { label: 'Selected checkbox', align: 'inline' } ), * new OO.ui.FieldLayout( checkbox2, { label: 'Unselected checkbox', align: 'inline' } ), * new OO.ui.FieldLayout( checkbox3, { label: 'Disabled checkbox', align: 'inline' } ), * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [selected=false] Select the checkbox initially. By default, the checkbox is not selected. */ OO.ui.CheckboxInputWidget = function OoUiCheckboxInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.CheckboxInputWidget.parent.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-checkboxInputWidget' ) // Required for pretty styling in MediaWiki theme .append( $( '<span>' ) ); this.setSelected( config.selected !== undefined ? config.selected : false ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxInputWidget, OO.ui.InputWidget ); /* Static Methods */ /** * @inheritdoc */ OO.ui.CheckboxInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.CheckboxInputWidget.parent.static.gatherPreInfuseState( node, config ); state.checked = config.$input.prop( 'checked' ); return state; }; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.CheckboxInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'checkbox' ); }; /** * @inheritdoc */ OO.ui.CheckboxInputWidget.prototype.onEdit = function () { var widget = this; if ( !this.isDisabled() ) { // Allow the stack to clear so the value will be updated setTimeout( function () { widget.setSelected( widget.$input.prop( 'checked' ) ); } ); } }; /** * Set selection state of this checkbox. * * @param {boolean} state `true` for selected * @chainable */ OO.ui.CheckboxInputWidget.prototype.setSelected = function ( state ) { state = !!state; if ( this.selected !== state ) { this.selected = state; this.$input.prop( 'checked', this.selected ); this.emit( 'change', this.selected ); } return this; }; /** * Check if this checkbox is selected. * * @return {boolean} Checkbox is selected */ OO.ui.CheckboxInputWidget.prototype.isSelected = function () { // Resynchronize our internal data with DOM data. Other scripts executing on the page can modify // it, and we won't know unless they're kind enough to trigger a 'change' event. var selected = this.$input.prop( 'checked' ); if ( this.selected !== selected ) { this.setSelected( selected ); } return this.selected; }; /** * @inheritdoc */ OO.ui.CheckboxInputWidget.prototype.restorePreInfuseState = function ( state ) { OO.ui.CheckboxInputWidget.parent.prototype.restorePreInfuseState.call( this, state ); if ( state.checked !== undefined && state.checked !== this.isSelected() ) { this.setSelected( state.checked ); } }; /** * DropdownInputWidget is a {@link OO.ui.DropdownWidget DropdownWidget} intended to be used * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for * more information about input widgets. * * A DropdownInputWidget always has a value (one of the options is always selected), unless there * are no options. If no `value` configuration option is provided, the first option is selected. * If you need a state representing no value (no option being selected), use a DropdownWidget. * * This and OO.ui.RadioSelectInputWidget support the same configuration options. * * @example * // Example: A DropdownInputWidget with three options * var dropdownInput = new OO.ui.DropdownInputWidget( { * options: [ * { data: 'a', label: 'First' }, * { data: 'b', label: 'Second'}, * { data: 'c', label: 'Third' } * ] * } ); * $( 'body' ).append( dropdownInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }` * @cfg {Object} [dropdown] Configuration options for {@link OO.ui.DropdownWidget DropdownWidget} */ OO.ui.DropdownInputWidget = function OoUiDropdownInputWidget( config ) { // Configuration initialization config = config || {}; // See InputWidget#reusePreInfuseDOM about config.$input if ( config.$input ) { config.$input.addClass( 'oo-ui-element-hidden' ); } // Properties (must be done before parent constructor which calls #setDisabled) this.dropdownWidget = new OO.ui.DropdownWidget( config.dropdown ); // Parent constructor OO.ui.DropdownInputWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.TitledElement.call( this, config ); // Events this.dropdownWidget.getMenu().connect( this, { select: 'onMenuSelect' } ); // Initialization this.setOptions( config.options || [] ); this.$element .addClass( 'oo-ui-dropdownInputWidget' ) .append( this.dropdownWidget.$element ); }; /* Setup */ OO.inheritClass( OO.ui.DropdownInputWidget, OO.ui.InputWidget ); OO.mixinClass( OO.ui.DropdownInputWidget, OO.ui.mixin.TitledElement ); /* Methods */ /** * @inheritdoc * @protected */ OO.ui.DropdownInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'hidden' ); }; /** * Handles menu select events. * * @private * @param {OO.ui.MenuOptionWidget} item Selected menu item */ OO.ui.DropdownInputWidget.prototype.onMenuSelect = function ( item ) { this.setValue( item.getData() ); }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); this.dropdownWidget.getMenu().selectItemByData( value ); OO.ui.DropdownInputWidget.parent.prototype.setValue.call( this, value ); return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.setDisabled = function ( state ) { this.dropdownWidget.setDisabled( state ); OO.ui.DropdownInputWidget.parent.prototype.setDisabled.call( this, state ); return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }` * @chainable */ OO.ui.DropdownInputWidget.prototype.setOptions = function ( options ) { var value = this.getValue(), widget = this; // Rebuild the dropdown menu this.dropdownWidget.getMenu() .clearItems() .addItems( options.map( function ( opt ) { var optValue = widget.cleanUpValue( opt.data ); return new OO.ui.MenuOptionWidget( { data: optValue, label: opt.label !== undefined ? opt.label : optValue } ); } ) ); // Restore the previous value, or reset to something sensible if ( this.dropdownWidget.getMenu().getItemFromData( value ) ) { // Previous value is still available, ensure consistency with the dropdown this.setValue( value ); } else { // No longer valid, reset if ( options.length ) { this.setValue( options[ 0 ].data ); } } return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.focus = function () { this.dropdownWidget.getMenu().toggle( true ); return this; }; /** * @inheritdoc */ OO.ui.DropdownInputWidget.prototype.blur = function () { this.dropdownWidget.getMenu().toggle( false ); return this; }; /** * RadioInputWidget creates a single radio button. Because radio buttons are usually used as a set, * in most cases you will want to use a {@link OO.ui.RadioSelectWidget radio select} * with {@link OO.ui.RadioOptionWidget radio options} instead of this class. For more information, * please see the [OOjs UI documentation on MediaWiki][1]. * * This widget can be used inside a HTML form, such as a OO.ui.FormLayout. * * @example * // An example of selected, unselected, and disabled radio inputs * var radio1 = new OO.ui.RadioInputWidget( { * value: 'a', * selected: true * } ); * var radio2 = new OO.ui.RadioInputWidget( { * value: 'b' * } ); * var radio3 = new OO.ui.RadioInputWidget( { * value: 'c', * disabled: true * } ); * // Create a fieldset layout with fields for each radio button. * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Radio inputs' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( radio1, { label: 'Selected', align: 'inline' } ), * new OO.ui.FieldLayout( radio2, { label: 'Unselected', align: 'inline' } ), * new OO.ui.FieldLayout( radio3, { label: 'Disabled', align: 'inline' } ), * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [selected=false] Select the radio button initially. By default, the radio button is not selected. */ OO.ui.RadioInputWidget = function OoUiRadioInputWidget( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.RadioInputWidget.parent.call( this, config ); // Initialization this.$element .addClass( 'oo-ui-radioInputWidget' ) // Required for pretty styling in MediaWiki theme .append( $( '<span>' ) ); this.setSelected( config.selected !== undefined ? config.selected : false ); }; /* Setup */ OO.inheritClass( OO.ui.RadioInputWidget, OO.ui.InputWidget ); /* Static Methods */ /** * @inheritdoc */ OO.ui.RadioInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.RadioInputWidget.parent.static.gatherPreInfuseState( node, config ); state.checked = config.$input.prop( 'checked' ); return state; }; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.RadioInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'radio' ); }; /** * @inheritdoc */ OO.ui.RadioInputWidget.prototype.onEdit = function () { // RadioInputWidget doesn't track its state. }; /** * Set selection state of this radio button. * * @param {boolean} state `true` for selected * @chainable */ OO.ui.RadioInputWidget.prototype.setSelected = function ( state ) { // RadioInputWidget doesn't track its state. this.$input.prop( 'checked', state ); return this; }; /** * Check if this radio button is selected. * * @return {boolean} Radio is selected */ OO.ui.RadioInputWidget.prototype.isSelected = function () { return this.$input.prop( 'checked' ); }; /** * @inheritdoc */ OO.ui.RadioInputWidget.prototype.restorePreInfuseState = function ( state ) { OO.ui.RadioInputWidget.parent.prototype.restorePreInfuseState.call( this, state ); if ( state.checked !== undefined && state.checked !== this.isSelected() ) { this.setSelected( state.checked ); } }; /** * RadioSelectInputWidget is a {@link OO.ui.RadioSelectWidget RadioSelectWidget} intended to be used * within a HTML form, such as a OO.ui.FormLayout. The selected value is synchronized with the value * of a hidden HTML `input` tag. Please see the [OOjs UI documentation on MediaWiki][1] for * more information about input widgets. * * This and OO.ui.DropdownInputWidget support the same configuration options. * * @example * // Example: A RadioSelectInputWidget with three options * var radioSelectInput = new OO.ui.RadioSelectInputWidget( { * options: [ * { data: 'a', label: 'First' }, * { data: 'b', label: 'Second'}, * { data: 'c', label: 'Third' } * ] * } ); * $( 'body' ).append( radioSelectInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }` */ OO.ui.RadioSelectInputWidget = function OoUiRadioSelectInputWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.radioSelectWidget = new OO.ui.RadioSelectWidget(); // Parent constructor OO.ui.RadioSelectInputWidget.parent.call( this, config ); // Events this.radioSelectWidget.connect( this, { select: 'onMenuSelect' } ); // Initialization this.setOptions( config.options || [] ); this.$element .addClass( 'oo-ui-radioSelectInputWidget' ) .append( this.radioSelectWidget.$element ); }; /* Setup */ OO.inheritClass( OO.ui.RadioSelectInputWidget, OO.ui.InputWidget ); /* Static Properties */ OO.ui.RadioSelectInputWidget.static.supportsSimpleLabel = false; /* Static Methods */ /** * @inheritdoc */ OO.ui.RadioSelectInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.RadioSelectInputWidget.parent.static.gatherPreInfuseState( node, config ); state.value = $( node ).find( '.oo-ui-radioInputWidget .oo-ui-inputWidget-input:checked' ).val(); return state; }; /** * @inheritdoc */ OO.ui.RadioSelectInputWidget.static.reusePreInfuseDOM = function ( node, config ) { config = OO.ui.RadioSelectInputWidget.parent.static.reusePreInfuseDOM( node, config ); // Cannot reuse the `<input type=radio>` set delete config.$input; return config; }; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.RadioSelectInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'hidden' ); }; /** * Handles menu select events. * * @private * @param {OO.ui.RadioOptionWidget} item Selected menu item */ OO.ui.RadioSelectInputWidget.prototype.onMenuSelect = function ( item ) { this.setValue( item.getData() ); }; /** * @inheritdoc */ OO.ui.RadioSelectInputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); this.radioSelectWidget.selectItemByData( value ); OO.ui.RadioSelectInputWidget.parent.prototype.setValue.call( this, value ); return this; }; /** * @inheritdoc */ OO.ui.RadioSelectInputWidget.prototype.setDisabled = function ( state ) { this.radioSelectWidget.setDisabled( state ); OO.ui.RadioSelectInputWidget.parent.prototype.setDisabled.call( this, state ); return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }` * @chainable */ OO.ui.RadioSelectInputWidget.prototype.setOptions = function ( options ) { var value = this.getValue(), widget = this; // Rebuild the radioSelect menu this.radioSelectWidget .clearItems() .addItems( options.map( function ( opt ) { var optValue = widget.cleanUpValue( opt.data ); return new OO.ui.RadioOptionWidget( { data: optValue, label: opt.label !== undefined ? opt.label : optValue } ); } ) ); // Restore the previous value, or reset to something sensible if ( this.radioSelectWidget.getItemFromData( value ) ) { // Previous value is still available, ensure consistency with the radioSelect this.setValue( value ); } else { // No longer valid, reset if ( options.length ) { this.setValue( options[ 0 ].data ); } } return this; }; /** * CheckboxMultiselectInputWidget is a * {@link OO.ui.CheckboxMultiselectWidget CheckboxMultiselectWidget} intended to be used within a * HTML form, such as a OO.ui.FormLayout. The selected values are synchronized with the value of * HTML `<input type=checkbox>` tags. Please see the [OOjs UI documentation on MediaWiki][1] for * more information about input widgets. * * @example * // Example: A CheckboxMultiselectInputWidget with three options * var multiselectInput = new OO.ui.CheckboxMultiselectInputWidget( { * options: [ * { data: 'a', label: 'First' }, * { data: 'b', label: 'Second'}, * { data: 'c', label: 'Third' } * ] * } ); * $( 'body' ).append( multiselectInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }` */ OO.ui.CheckboxMultiselectInputWidget = function OoUiCheckboxMultiselectInputWidget( config ) { // Configuration initialization config = config || {}; // Properties (must be done before parent constructor which calls #setDisabled) this.checkboxMultiselectWidget = new OO.ui.CheckboxMultiselectWidget(); // Parent constructor OO.ui.CheckboxMultiselectInputWidget.parent.call( this, config ); // Properties this.inputName = config.name; // Initialization this.$element .addClass( 'oo-ui-checkboxMultiselectInputWidget' ) .append( this.checkboxMultiselectWidget.$element ); // We don't use this.$input, but rather the CheckboxInputWidgets inside each option this.$input.detach(); this.setOptions( config.options || [] ); // Have to repeat this from parent, as we need options to be set up for this to make sense this.setValue( config.value ); }; /* Setup */ OO.inheritClass( OO.ui.CheckboxMultiselectInputWidget, OO.ui.InputWidget ); /* Static Properties */ OO.ui.CheckboxMultiselectInputWidget.static.supportsSimpleLabel = false; /* Static Methods */ /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.CheckboxMultiselectInputWidget.parent.static.gatherPreInfuseState( node, config ); state.value = $( node ).find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' ) .toArray().map( function ( el ) { return el.value; } ); return state; }; /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.static.reusePreInfuseDOM = function ( node, config ) { config = OO.ui.CheckboxMultiselectInputWidget.parent.static.reusePreInfuseDOM( node, config ); // Cannot reuse the `<input type=checkbox>` set delete config.$input; return config; }; /* Methods */ /** * @inheritdoc * @protected */ OO.ui.CheckboxMultiselectInputWidget.prototype.getInputElement = function () { // Actually unused return $( '<div>' ); }; /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.prototype.getValue = function () { var value = this.$element.find( '.oo-ui-checkboxInputWidget .oo-ui-inputWidget-input:checked' ) .toArray().map( function ( el ) { return el.value; } ); if ( this.value !== value ) { this.setValue( value ); } return this.value; }; /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.prototype.setValue = function ( value ) { value = this.cleanUpValue( value ); this.checkboxMultiselectWidget.selectItemsByData( value ); OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setValue.call( this, value ); return this; }; /** * Clean up incoming value. * * @param {string[]} value Original value * @return {string[]} Cleaned up value */ OO.ui.CheckboxMultiselectInputWidget.prototype.cleanUpValue = function ( value ) { var i, singleValue, cleanValue = []; if ( !Array.isArray( value ) ) { return cleanValue; } for ( i = 0; i < value.length; i++ ) { singleValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( this, value[ i ] ); // Remove options that we don't have here if ( !this.checkboxMultiselectWidget.getItemFromData( singleValue ) ) { continue; } cleanValue.push( singleValue ); } return cleanValue; }; /** * @inheritdoc */ OO.ui.CheckboxMultiselectInputWidget.prototype.setDisabled = function ( state ) { this.checkboxMultiselectWidget.setDisabled( state ); OO.ui.CheckboxMultiselectInputWidget.parent.prototype.setDisabled.call( this, state ); return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }` * @chainable */ OO.ui.CheckboxMultiselectInputWidget.prototype.setOptions = function ( options ) { var widget = this; // Rebuild the checkboxMultiselectWidget menu this.checkboxMultiselectWidget .clearItems() .addItems( options.map( function ( opt ) { var optValue, item; optValue = OO.ui.CheckboxMultiselectInputWidget.parent.prototype.cleanUpValue.call( widget, opt.data ); item = new OO.ui.CheckboxMultioptionWidget( { data: optValue, label: opt.label !== undefined ? opt.label : optValue } ); // Set the 'name' and 'value' for form submission item.checkbox.$input.attr( 'name', widget.inputName ); item.checkbox.setValue( optValue ); return item; } ) ); // Re-set the value, checking the checkboxes as needed. // This will also get rid of any stale options that we just removed. this.setValue( this.getValue() ); return this; }; /** * TextInputWidgets, like HTML text inputs, can be configured with options that customize the * size of the field as well as its presentation. In addition, these widgets can be configured * with {@link OO.ui.mixin.IconElement icons}, {@link OO.ui.mixin.IndicatorElement indicators}, an optional * validation-pattern (used to determine if an input value is valid or not) and an input filter, * which modifies incoming values rather than validating them. * Please see the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * This widget can be used inside a HTML form, such as a OO.ui.FormLayout. * * @example * // Example of a text input widget * var textInput = new OO.ui.TextInputWidget( { * value: 'Text input' * } ) * $( 'body' ).append( textInput.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @class * @extends OO.ui.InputWidget * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.IndicatorElement * @mixins OO.ui.mixin.PendingElement * @mixins OO.ui.mixin.LabelElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [type='text'] The value of the HTML `type` attribute: 'text', 'password', 'search', * 'email', 'url', 'date', 'month' or 'number'. Ignored if `multiline` is true. * * Some values of `type` result in additional behaviors: * * - `search`: implies `icon: 'search'` and `indicator: 'clear'`; when clicked, the indicator * empties the text field * @cfg {string} [placeholder] Placeholder text * @cfg {boolean} [autofocus=false] Use an HTML `autofocus` attribute to * instruct the browser to focus this widget. * @cfg {boolean} [readOnly=false] Prevent changes to the value of the text input. * @cfg {number} [maxLength] Maximum number of characters allowed in the input. * @cfg {boolean} [multiline=false] Allow multiple lines of text * @cfg {number} [rows] If multiline, number of visible lines in textarea. If used with `autosize`, * specifies minimum number of rows to display. * @cfg {boolean} [autosize=false] Automatically resize the text input to fit its content. * Use the #maxRows config to specify a maximum number of displayed rows. * @cfg {boolean} [maxRows] Maximum number of rows to display when #autosize is set to true. * Defaults to the maximum of `10` and `2 * rows`, or `10` if `rows` isn't provided. * @cfg {string} [labelPosition='after'] The position of the inline label relative to that of * the value or placeholder text: `'before'` or `'after'` * @cfg {boolean} [required=false] Mark the field as required. Implies `indicator: 'required'`. * @cfg {boolean} [autocomplete=true] Should the browser support autocomplete for this field * @cfg {RegExp|Function|string} [validate] Validation pattern: when string, a symbolic name of a * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' * (the value must contain only numbers); when RegExp, a regular expression that must match the * value for it to be considered valid; when Function, a function receiving the value as parameter * that must return true, or promise resolving to true, for it to be considered valid. */ OO.ui.TextInputWidget = function OoUiTextInputWidget( config ) { // Configuration initialization config = $.extend( { type: 'text', labelPosition: 'after' }, config ); if ( config.type === 'search' ) { OO.ui.warnDeprecation( 'TextInputWidget: config.type=\'search\' is deprecated. Use the SearchInputWidget instead. See T148471 for details.' ); if ( config.icon === undefined ) { config.icon = 'search'; } // indicator: 'clear' is set dynamically later, depending on value } // Parent constructor OO.ui.TextInputWidget.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.IndicatorElement.call( this, config ); OO.ui.mixin.PendingElement.call( this, $.extend( {}, config, { $pending: this.$input } ) ); OO.ui.mixin.LabelElement.call( this, config ); // Properties this.type = this.getSaneType( config ); this.readOnly = false; this.required = false; this.multiline = !!config.multiline; this.autosize = !!config.autosize; this.minRows = config.rows !== undefined ? config.rows : ''; this.maxRows = config.maxRows || Math.max( 2 * ( this.minRows || 0 ), 10 ); this.validate = null; this.styleHeight = null; this.scrollWidth = null; // Clone for resizing if ( this.autosize ) { this.$clone = this.$input .clone() .insertAfter( this.$input ) .attr( 'aria-hidden', 'true' ) .addClass( 'oo-ui-element-hidden' ); } this.setValidation( config.validate ); this.setLabelPosition( config.labelPosition ); // Events this.$input.on( { keypress: this.onKeyPress.bind( this ), blur: this.onBlur.bind( this ), focus: this.onFocus.bind( this ) } ); this.$icon.on( 'mousedown', this.onIconMouseDown.bind( this ) ); this.$indicator.on( 'mousedown', this.onIndicatorMouseDown.bind( this ) ); this.on( 'labelChange', this.updatePosition.bind( this ) ); this.connect( this, { change: 'onChange', disable: 'onDisable' } ); this.on( 'change', OO.ui.debounce( this.onDebouncedChange.bind( this ), 250 ) ); // Initialization this.$element .addClass( 'oo-ui-textInputWidget oo-ui-textInputWidget-type-' + this.type ) .append( this.$icon, this.$indicator ); this.setReadOnly( !!config.readOnly ); this.setRequired( !!config.required ); this.updateSearchIndicator(); if ( config.placeholder !== undefined ) { this.$input.attr( 'placeholder', config.placeholder ); } if ( config.maxLength !== undefined ) { this.$input.attr( 'maxlength', config.maxLength ); } if ( config.autofocus ) { this.$input.attr( 'autofocus', 'autofocus' ); } if ( config.autocomplete === false ) { this.$input.attr( 'autocomplete', 'off' ); // Turning off autocompletion also disables "form caching" when the user navigates to a // different page and then clicks "Back". Re-enable it when leaving. Borrowed from jQuery UI. $( window ).on( { beforeunload: function () { this.$input.removeAttr( 'autocomplete' ); }.bind( this ), pageshow: function () { // Browsers don't seem to actually fire this event on "Back", they instead just reload the // whole page... it shouldn't hurt, though. this.$input.attr( 'autocomplete', 'off' ); }.bind( this ) } ); } if ( this.multiline && config.rows ) { this.$input.attr( 'rows', config.rows ); } if ( this.label || config.autosize ) { this.isWaitingToBeAttached = true; this.installParentChangeDetector(); } }; /* Setup */ OO.inheritClass( OO.ui.TextInputWidget, OO.ui.InputWidget ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.IndicatorElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.PendingElement ); OO.mixinClass( OO.ui.TextInputWidget, OO.ui.mixin.LabelElement ); /* Static Properties */ OO.ui.TextInputWidget.static.validationPatterns = { 'non-empty': /.+/, integer: /^\d+$/ }; /* Static Methods */ /** * @inheritdoc */ OO.ui.TextInputWidget.static.gatherPreInfuseState = function ( node, config ) { var state = OO.ui.TextInputWidget.parent.static.gatherPreInfuseState( node, config ); if ( config.multiline ) { state.scrollTop = config.$input.scrollTop(); } return state; }; /* Events */ /** * An `enter` event is emitted when the user presses 'enter' inside the text box. * * Not emitted if the input is multiline. * * @event enter */ /** * A `resize` event is emitted when autosize is set and the widget resizes * * @event resize */ /* Methods */ /** * Handle icon mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.TextInputWidget.prototype.onIconMouseDown = function ( e ) { if ( e.which === OO.ui.MouseButtons.LEFT ) { this.$input[ 0 ].focus(); return false; } }; /** * Handle indicator mouse down events. * * @private * @param {jQuery.Event} e Mouse down event */ OO.ui.TextInputWidget.prototype.onIndicatorMouseDown = function ( e ) { if ( e.which === OO.ui.MouseButtons.LEFT ) { if ( this.type === 'search' ) { // Clear the text field this.setValue( '' ); } this.$input[ 0 ].focus(); return false; } }; /** * Handle key press events. * * @private * @param {jQuery.Event} e Key press event * @fires enter If enter key is pressed and input is not multiline */ OO.ui.TextInputWidget.prototype.onKeyPress = function ( e ) { if ( e.which === OO.ui.Keys.ENTER && !this.multiline ) { this.emit( 'enter', e ); } }; /** * Handle blur events. * * @private * @param {jQuery.Event} e Blur event */ OO.ui.TextInputWidget.prototype.onBlur = function () { this.setValidityFlag(); }; /** * Handle focus events. * * @private * @param {jQuery.Event} e Focus event */ OO.ui.TextInputWidget.prototype.onFocus = function () { if ( this.isWaitingToBeAttached ) { // If we've received focus, then we must be attached to the document, and if // isWaitingToBeAttached is still true, that means the handler never fired. Fire it now. this.onElementAttach(); } this.setValidityFlag( true ); }; /** * Handle element attach events. * * @private * @param {jQuery.Event} e Element attach event */ OO.ui.TextInputWidget.prototype.onElementAttach = function () { this.isWaitingToBeAttached = false; // Any previously calculated size is now probably invalid if we reattached elsewhere this.valCache = null; this.adjustSize(); this.positionLabel(); }; /** * Handle change events. * * @param {string} value * @private */ OO.ui.TextInputWidget.prototype.onChange = function () { this.updateSearchIndicator(); this.adjustSize(); }; /** * Handle debounced change events. * * @param {string} value * @private */ OO.ui.TextInputWidget.prototype.onDebouncedChange = function () { this.setValidityFlag(); }; /** * Handle disable events. * * @param {boolean} disabled Element is disabled * @private */ OO.ui.TextInputWidget.prototype.onDisable = function () { this.updateSearchIndicator(); }; /** * Check if the input is {@link #readOnly read-only}. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isReadOnly = function () { return this.readOnly; }; /** * Set the {@link #readOnly read-only} state of the input. * * @param {boolean} state Make input read-only * @chainable */ OO.ui.TextInputWidget.prototype.setReadOnly = function ( state ) { this.readOnly = !!state; this.$input.prop( 'readOnly', this.readOnly ); this.updateSearchIndicator(); return this; }; /** * Check if the input is {@link #required required}. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isRequired = function () { return this.required; }; /** * Set the {@link #required required} state of the input. * * @param {boolean} state Make input required * @chainable */ OO.ui.TextInputWidget.prototype.setRequired = function ( state ) { this.required = !!state; if ( this.required ) { this.$input .attr( 'required', 'required' ) .attr( 'aria-required', 'true' ); if ( this.getIndicator() === null ) { this.setIndicator( 'required' ); } } else { this.$input .removeAttr( 'required' ) .removeAttr( 'aria-required' ); if ( this.getIndicator() === 'required' ) { this.setIndicator( null ); } } this.updateSearchIndicator(); return this; }; /** * Support function for making #onElementAttach work across browsers. * * This whole function could be replaced with one line of code using the DOMNodeInsertedIntoDocument * event, but it's not supported by Firefox and allegedly deprecated, so we only use it as fallback. * * Due to MutationObserver performance woes, #onElementAttach is only somewhat reliably called the * first time that the element gets attached to the documented. */ OO.ui.TextInputWidget.prototype.installParentChangeDetector = function () { var mutationObserver, onRemove, topmostNode, fakeParentNode, MutationObserver = window.MutationObserver || window.WebKitMutationObserver || window.MozMutationObserver, widget = this; if ( MutationObserver ) { // The new way. If only it wasn't so ugly. if ( this.isElementAttached() ) { // Widget is attached already, do nothing. This breaks the functionality of this function when // the widget is detached and reattached. Alas, doing this correctly with MutationObserver // would require observation of the whole document, which would hurt performance of other, // more important code. return; } // Find topmost node in the tree topmostNode = this.$element[ 0 ]; while ( topmostNode.parentNode ) { topmostNode = topmostNode.parentNode; } // We have no way to detect the $element being attached somewhere without observing the entire // DOM with subtree modifications, which would hurt performance. So we cheat: we hook to the // parent node of $element, and instead detect when $element is removed from it (and thus // probably attached somewhere else). If there is no parent, we create a "fake" one. If it // doesn't get attached, we end up back here and create the parent. mutationObserver = new MutationObserver( function ( mutations ) { var i, j, removedNodes; for ( i = 0; i < mutations.length; i++ ) { removedNodes = mutations[ i ].removedNodes; for ( j = 0; j < removedNodes.length; j++ ) { if ( removedNodes[ j ] === topmostNode ) { setTimeout( onRemove, 0 ); return; } } } } ); onRemove = function () { // If the node was attached somewhere else, report it if ( widget.isElementAttached() ) { widget.onElementAttach(); } mutationObserver.disconnect(); widget.installParentChangeDetector(); }; // Create a fake parent and observe it fakeParentNode = $( '<div>' ).append( topmostNode )[ 0 ]; mutationObserver.observe( fakeParentNode, { childList: true } ); } else { // Using the DOMNodeInsertedIntoDocument event is much nicer and less magical, and works for // detachment and reattachment, but it's not supported by Firefox and allegedly deprecated. this.$element.on( 'DOMNodeInsertedIntoDocument', this.onElementAttach.bind( this ) ); } }; /** * Automatically adjust the size of the text input. * * This only affects #multiline inputs that are {@link #autosize autosized}. * * @chainable * @fires resize */ OO.ui.TextInputWidget.prototype.adjustSize = function () { var scrollHeight, innerHeight, outerHeight, maxInnerHeight, measurementError, idealHeight, newHeight, scrollWidth, property; if ( this.isWaitingToBeAttached ) { // #onElementAttach will be called soon, which calls this method return this; } if ( this.multiline && this.$input.val() !== this.valCache ) { if ( this.autosize ) { this.$clone .val( this.$input.val() ) .attr( 'rows', this.minRows ) // Set inline height property to 0 to measure scroll height .css( 'height', 0 ); this.$clone.removeClass( 'oo-ui-element-hidden' ); this.valCache = this.$input.val(); scrollHeight = this.$clone[ 0 ].scrollHeight; // Remove inline height property to measure natural heights this.$clone.css( 'height', '' ); innerHeight = this.$clone.innerHeight(); outerHeight = this.$clone.outerHeight(); // Measure max rows height this.$clone .attr( 'rows', this.maxRows ) .css( 'height', 'auto' ) .val( '' ); maxInnerHeight = this.$clone.innerHeight(); // Difference between reported innerHeight and scrollHeight with no scrollbars present. // This is sometimes non-zero on Blink-based browsers, depending on zoom level. measurementError = maxInnerHeight - this.$clone[ 0 ].scrollHeight; idealHeight = Math.min( maxInnerHeight, scrollHeight + measurementError ); this.$clone.addClass( 'oo-ui-element-hidden' ); // Only apply inline height when expansion beyond natural height is needed // Use the difference between the inner and outer height as a buffer newHeight = idealHeight > innerHeight ? idealHeight + ( outerHeight - innerHeight ) : ''; if ( newHeight !== this.styleHeight ) { this.$input.css( 'height', newHeight ); this.styleHeight = newHeight; this.emit( 'resize' ); } } scrollWidth = this.$input[ 0 ].offsetWidth - this.$input[ 0 ].clientWidth; if ( scrollWidth !== this.scrollWidth ) { property = this.$element.css( 'direction' ) === 'rtl' ? 'left' : 'right'; // Reset this.$label.css( { right: '', left: '' } ); this.$indicator.css( { right: '', left: '' } ); if ( scrollWidth ) { this.$indicator.css( property, scrollWidth ); if ( this.labelPosition === 'after' ) { this.$label.css( property, scrollWidth ); } } this.scrollWidth = scrollWidth; this.positionLabel(); } } return this; }; /** * @inheritdoc * @protected */ OO.ui.TextInputWidget.prototype.getInputElement = function ( config ) { if ( config.multiline ) { return $( '<textarea>' ); } else if ( this.getSaneType( config ) === 'number' ) { return $( '<input>' ) .attr( 'step', 'any' ) .attr( 'type', 'number' ); } else { return $( '<input>' ).attr( 'type', this.getSaneType( config ) ); } }; /** * Get sanitized value for 'type' for given config. * * @param {Object} config Configuration options * @return {string|null} * @private */ OO.ui.TextInputWidget.prototype.getSaneType = function ( config ) { var allowedTypes = [ 'text', 'password', 'search', 'email', 'url', 'date', 'month', 'number' ]; return allowedTypes.indexOf( config.type ) !== -1 ? config.type : 'text'; }; /** * Check if the input supports multiple lines. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isMultiline = function () { return !!this.multiline; }; /** * Check if the input automatically adjusts its size. * * @return {boolean} */ OO.ui.TextInputWidget.prototype.isAutosizing = function () { return !!this.autosize; }; /** * Focus the input and select a specified range within the text. * * @param {number} from Select from offset * @param {number} [to] Select to offset, defaults to from * @chainable */ OO.ui.TextInputWidget.prototype.selectRange = function ( from, to ) { var isBackwards, start, end, input = this.$input[ 0 ]; to = to || from; isBackwards = to < from; start = isBackwards ? to : from; end = isBackwards ? from : to; this.focus(); try { input.setSelectionRange( start, end, isBackwards ? 'backward' : 'forward' ); } catch ( e ) { // IE throws an exception if you call setSelectionRange on a unattached DOM node. // Rather than expensively check if the input is attached every time, just check // if it was the cause of an error being thrown. If not, rethrow the error. if ( this.getElementDocument().body.contains( input ) ) { throw e; } } return this; }; /** * Get an object describing the current selection range in a directional manner * * @return {Object} Object containing 'from' and 'to' offsets */ OO.ui.TextInputWidget.prototype.getRange = function () { var input = this.$input[ 0 ], start = input.selectionStart, end = input.selectionEnd, isBackwards = input.selectionDirection === 'backward'; return { from: isBackwards ? end : start, to: isBackwards ? start : end }; }; /** * Get the length of the text input value. * * This could differ from the length of #getValue if the * value gets filtered * * @return {number} Input length */ OO.ui.TextInputWidget.prototype.getInputLength = function () { return this.$input[ 0 ].value.length; }; /** * Focus the input and select the entire text. * * @chainable */ OO.ui.TextInputWidget.prototype.select = function () { return this.selectRange( 0, this.getInputLength() ); }; /** * Focus the input and move the cursor to the start. * * @chainable */ OO.ui.TextInputWidget.prototype.moveCursorToStart = function () { return this.selectRange( 0 ); }; /** * Focus the input and move the cursor to the end. * * @chainable */ OO.ui.TextInputWidget.prototype.moveCursorToEnd = function () { return this.selectRange( this.getInputLength() ); }; /** * Insert new content into the input. * * @param {string} content Content to be inserted * @chainable */ OO.ui.TextInputWidget.prototype.insertContent = function ( content ) { var start, end, range = this.getRange(), value = this.getValue(); start = Math.min( range.from, range.to ); end = Math.max( range.from, range.to ); this.setValue( value.slice( 0, start ) + content + value.slice( end ) ); this.selectRange( start + content.length ); return this; }; /** * Insert new content either side of a selection. * * @param {string} pre Content to be inserted before the selection * @param {string} post Content to be inserted after the selection * @chainable */ OO.ui.TextInputWidget.prototype.encapsulateContent = function ( pre, post ) { var start, end, range = this.getRange(), offset = pre.length; start = Math.min( range.from, range.to ); end = Math.max( range.from, range.to ); this.selectRange( start ).insertContent( pre ); this.selectRange( offset + end ).insertContent( post ); this.selectRange( offset + start, offset + end ); return this; }; /** * Set the validation pattern. * * The validation pattern is either a regular expression, a function, or the symbolic name of a * pattern defined by the class: 'non-empty' (the value cannot be an empty string) or 'integer' (the * value must contain only numbers). * * @param {RegExp|Function|string|null} validate Regular expression, function, or the symbolic name * of a pattern (either ‘integer’ or ‘non-empty’) defined by the class. */ OO.ui.TextInputWidget.prototype.setValidation = function ( validate ) { if ( validate instanceof RegExp || validate instanceof Function ) { this.validate = validate; } else { this.validate = this.constructor.static.validationPatterns[ validate ] || /.*/; } }; /** * Sets the 'invalid' flag appropriately. * * @param {boolean} [isValid] Optionally override validation result */ OO.ui.TextInputWidget.prototype.setValidityFlag = function ( isValid ) { var widget = this, setFlag = function ( valid ) { if ( !valid ) { widget.$input.attr( 'aria-invalid', 'true' ); } else { widget.$input.removeAttr( 'aria-invalid' ); } widget.setFlags( { invalid: !valid } ); }; if ( isValid !== undefined ) { setFlag( isValid ); } else { this.getValidity().then( function () { setFlag( true ); }, function () { setFlag( false ); } ); } }; /** * Get the validity of current value. * * This method returns a promise that resolves if the value is valid and rejects if * it isn't. Uses the {@link #validate validation pattern} to check for validity. * * @return {jQuery.Promise} A promise that resolves if the value is valid, rejects if not. */ OO.ui.TextInputWidget.prototype.getValidity = function () { var result; function rejectOrResolve( valid ) { if ( valid ) { return $.Deferred().resolve().promise(); } else { return $.Deferred().reject().promise(); } } if ( this.validate instanceof Function ) { result = this.validate( this.getValue() ); if ( result && $.isFunction( result.promise ) ) { return result.promise().then( function ( valid ) { return rejectOrResolve( valid ); } ); } else { return rejectOrResolve( result ); } } else { return rejectOrResolve( this.getValue().match( this.validate ) ); } }; /** * Set the position of the inline label relative to that of the value: `‘before’` or `‘after’`. * * @param {string} labelPosition Label position, 'before' or 'after' * @chainable */ OO.ui.TextInputWidget.prototype.setLabelPosition = function ( labelPosition ) { this.labelPosition = labelPosition; if ( this.label ) { // If there is no label and we only change the position, #updatePosition is a no-op, // but it takes really a lot of work to do nothing. this.updatePosition(); } return this; }; /** * Update the position of the inline label. * * This method is called by #setLabelPosition, and can also be called on its own if * something causes the label to be mispositioned. * * @chainable */ OO.ui.TextInputWidget.prototype.updatePosition = function () { var after = this.labelPosition === 'after'; this.$element .toggleClass( 'oo-ui-textInputWidget-labelPosition-after', !!this.label && after ) .toggleClass( 'oo-ui-textInputWidget-labelPosition-before', !!this.label && !after ); this.valCache = null; this.scrollWidth = null; this.adjustSize(); this.positionLabel(); return this; }; /** * Update the 'clear' indicator displayed on type: 'search' text fields, hiding it when the field is * already empty or when it's not editable. */ OO.ui.TextInputWidget.prototype.updateSearchIndicator = function () { if ( this.type === 'search' ) { if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) { this.setIndicator( null ); } else { this.setIndicator( 'clear' ); } } }; /** * Position the label by setting the correct padding on the input. * * @private * @chainable */ OO.ui.TextInputWidget.prototype.positionLabel = function () { var after, rtl, property; if ( this.isWaitingToBeAttached ) { // #onElementAttach will be called soon, which calls this method return this; } // Clear old values this.$input // Clear old values if present .css( { 'padding-right': '', 'padding-left': '' } ); if ( this.label ) { this.$element.append( this.$label ); } else { this.$label.detach(); return; } after = this.labelPosition === 'after'; rtl = this.$element.css( 'direction' ) === 'rtl'; property = after === rtl ? 'padding-left' : 'padding-right'; this.$input.css( property, this.$label.outerWidth( true ) + ( after ? this.scrollWidth : 0 ) ); return this; }; /** * @inheritdoc */ OO.ui.TextInputWidget.prototype.restorePreInfuseState = function ( state ) { OO.ui.TextInputWidget.parent.prototype.restorePreInfuseState.call( this, state ); if ( state.scrollTop !== undefined ) { this.$input.scrollTop( state.scrollTop ); } }; /** * @class * @extends OO.ui.TextInputWidget * * @constructor * @param {Object} [config] Configuration options */ OO.ui.SearchInputWidget = function OoUiSearchInputWidget( config ) { config = $.extend( { icon: 'search' }, config ); // Set type to text so that TextInputWidget doesn't // get stuck in an infinite loop. config.type = 'text'; // Parent constructor OO.ui.SearchInputWidget.parent.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-textInputWidget-type-search' ); this.updateSearchIndicator(); this.connect( this, { disable: 'onDisable' } ); }; /* Setup */ OO.inheritClass( OO.ui.SearchInputWidget, OO.ui.TextInputWidget ); /* Methods */ /** * @inheritdoc * @protected */ OO.ui.SearchInputWidget.prototype.getInputElement = function () { return $( '<input>' ).attr( 'type', 'search' ); }; /** * @inheritdoc */ OO.ui.SearchInputWidget.prototype.onIndicatorMouseDown = function ( e ) { if ( e.which === OO.ui.MouseButtons.LEFT ) { // Clear the text field this.setValue( '' ); this.$input[ 0 ].focus(); return false; } }; /** * Update the 'clear' indicator displayed on type: 'search' text * fields, hiding it when the field is already empty or when it's not * editable. */ OO.ui.SearchInputWidget.prototype.updateSearchIndicator = function () { if ( this.getValue() === '' || this.isDisabled() || this.isReadOnly() ) { this.setIndicator( null ); } else { this.setIndicator( 'clear' ); } }; /** * @inheritdoc */ OO.ui.SearchInputWidget.prototype.onChange = function () { OO.ui.SearchInputWidget.parent.prototype.onChange.call( this ); this.updateSearchIndicator(); }; /** * Handle disable events. * * @param {boolean} disabled Element is disabled * @private */ OO.ui.SearchInputWidget.prototype.onDisable = function () { this.updateSearchIndicator(); }; /** * @inheritdoc */ OO.ui.SearchInputWidget.prototype.setReadOnly = function ( state ) { OO.ui.SearchInputWidget.parent.prototype.setReadOnly.call( this, state ); this.updateSearchIndicator(); return this; }; /** * ComboBoxInputWidgets combine a {@link OO.ui.TextInputWidget text input} (where a value * can be entered manually) and a {@link OO.ui.MenuSelectWidget menu of options} (from which * a value can be chosen instead). Users can choose options from the combo box in one of two ways: * * - by typing a value in the text input field. If the value exactly matches the value of a menu * option, that option will appear to be selected. * - by choosing a value from the menu. The value of the chosen option will then appear in the text * input field. * * This widget can be used inside a HTML form, such as a OO.ui.FormLayout. * * For more information about menus and options, please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example: A ComboBoxInputWidget. * var comboBox = new OO.ui.ComboBoxInputWidget( { * label: 'ComboBoxInputWidget', * value: 'Option 1', * menu: { * items: [ * new OO.ui.MenuOptionWidget( { * data: 'Option 1', * label: 'Option One' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 2', * label: 'Option Two' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 3', * label: 'Option Three' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 4', * label: 'Option Four' * } ), * new OO.ui.MenuOptionWidget( { * data: 'Option 5', * label: 'Option Five' * } ) * ] * } * } ); * $( 'body' ).append( comboBox.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Selects_and_Options#Menu_selects_and_options * * @class * @extends OO.ui.TextInputWidget * * @constructor * @param {Object} [config] Configuration options * @cfg {Object[]} [options=[]] Array of menu options in the format `{ data: …, label: … }` * @cfg {Object} [menu] Configuration options to pass to the {@link OO.ui.FloatingMenuSelectWidget menu select widget}. * @cfg {jQuery} [$overlay] Render the menu into a separate layer. This configuration is useful in cases where * the expanded menu is larger than its containing `<div>`. The specified overlay layer is usually on top of the * containing `<div>` and has a larger area. By default, the menu uses relative positioning. */ OO.ui.ComboBoxInputWidget = function OoUiComboBoxInputWidget( config ) { // Configuration initialization config = $.extend( { autocomplete: false }, config ); // ComboBoxInputWidget shouldn't support multiline config.multiline = false; // Parent constructor OO.ui.ComboBoxInputWidget.parent.call( this, config ); // Properties this.$overlay = config.$overlay || this.$element; this.dropdownButton = new OO.ui.ButtonWidget( { classes: [ 'oo-ui-comboBoxInputWidget-dropdownButton' ], indicator: 'down', disabled: this.disabled } ); this.menu = new OO.ui.FloatingMenuSelectWidget( $.extend( { widget: this, input: this, $container: this.$element, disabled: this.isDisabled() }, config.menu ) ); // Events this.connect( this, { change: 'onInputChange', enter: 'onInputEnter' } ); this.dropdownButton.connect( this, { click: 'onDropdownButtonClick' } ); this.menu.connect( this, { choose: 'onMenuChoose', add: 'onMenuItemsChange', remove: 'onMenuItemsChange' } ); // Initialization this.$input.attr( { role: 'combobox', 'aria-autocomplete': 'list' } ); // Do not override options set via config.menu.items if ( config.options !== undefined ) { this.setOptions( config.options ); } this.$field = $( '<div>' ) .addClass( 'oo-ui-comboBoxInputWidget-field' ) .append( this.$input, this.dropdownButton.$element ); this.$element .addClass( 'oo-ui-comboBoxInputWidget' ) .append( this.$field ); this.$overlay.append( this.menu.$element ); this.onMenuItemsChange(); }; /* Setup */ OO.inheritClass( OO.ui.ComboBoxInputWidget, OO.ui.TextInputWidget ); /* Methods */ /** * Get the combobox's menu. * * @return {OO.ui.FloatingMenuSelectWidget} Menu widget */ OO.ui.ComboBoxInputWidget.prototype.getMenu = function () { return this.menu; }; /** * Get the combobox's text input widget. * * @return {OO.ui.TextInputWidget} Text input widget */ OO.ui.ComboBoxInputWidget.prototype.getInput = function () { return this; }; /** * Handle input change events. * * @private * @param {string} value New value */ OO.ui.ComboBoxInputWidget.prototype.onInputChange = function ( value ) { var match = this.menu.getItemFromData( value ); this.menu.selectItem( match ); if ( this.menu.getHighlightedItem() ) { this.menu.highlightItem( match ); } if ( !this.isDisabled() ) { this.menu.toggle( true ); } }; /** * Handle input enter events. * * @private */ OO.ui.ComboBoxInputWidget.prototype.onInputEnter = function () { if ( !this.isDisabled() ) { this.menu.toggle( false ); } }; /** * Handle button click events. * * @private */ OO.ui.ComboBoxInputWidget.prototype.onDropdownButtonClick = function () { this.menu.toggle(); this.$input[ 0 ].focus(); }; /** * Handle menu choose events. * * @private * @param {OO.ui.OptionWidget} item Chosen item */ OO.ui.ComboBoxInputWidget.prototype.onMenuChoose = function ( item ) { this.setValue( item.getData() ); }; /** * Handle menu item change events. * * @private */ OO.ui.ComboBoxInputWidget.prototype.onMenuItemsChange = function () { var match = this.menu.getItemFromData( this.getValue() ); this.menu.selectItem( match ); if ( this.menu.getHighlightedItem() ) { this.menu.highlightItem( match ); } this.$element.toggleClass( 'oo-ui-comboBoxInputWidget-empty', this.menu.isEmpty() ); }; /** * @inheritdoc */ OO.ui.ComboBoxInputWidget.prototype.setDisabled = function ( disabled ) { // Parent method OO.ui.ComboBoxInputWidget.parent.prototype.setDisabled.call( this, disabled ); if ( this.dropdownButton ) { this.dropdownButton.setDisabled( this.isDisabled() ); } if ( this.menu ) { this.menu.setDisabled( this.isDisabled() ); } return this; }; /** * Set the options available for this input. * * @param {Object[]} options Array of menu options in the format `{ data: …, label: … }` * @chainable */ OO.ui.ComboBoxInputWidget.prototype.setOptions = function ( options ) { this.getMenu() .clearItems() .addItems( options.map( function ( opt ) { return new OO.ui.MenuOptionWidget( { data: opt.data, label: opt.label !== undefined ? opt.label : opt.data } ); } ) ); return this; }; /** * FieldLayouts are used with OO.ui.FieldsetLayout. Each FieldLayout requires a field-widget, * which is a widget that is specified by reference before any optional configuration settings. * * Field layouts can be configured with help text and/or labels. Labels are aligned in one of four ways: * * - **left**: The label is placed before the field-widget and aligned with the left margin. * A left-alignment is used for forms with many fields. * - **right**: The label is placed before the field-widget and aligned to the right margin. * A right-alignment is used for long but familiar forms which users tab through, * verifying the current field with a quick glance at the label. * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms * that users fill out from top to bottom. * - **inline**: The label is placed after the field-widget and aligned to the left. * An inline-alignment is best used with checkboxes or radio buttons. * * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout. * Please see the [OOjs UI documentation on MediaWiki] [1] for examples and more information. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets * * @class * @extends OO.ui.Layout * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.TitledElement * * @constructor * @param {OO.ui.Widget} fieldWidget Field widget * @param {Object} [config] Configuration options * @cfg {string} [align='left'] Alignment of the label: 'left', 'right', 'top' or 'inline' * @cfg {Array} [errors] Error messages about the widget, which will be displayed below the widget. * The array may contain strings or OO.ui.HtmlSnippet instances. * @cfg {Array} [notices] Notices about the widget, which will be displayed below the widget. * The array may contain strings or OO.ui.HtmlSnippet instances. * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear * in the upper-right corner of the rendered field; clicking it will display the text in a popup. * For important messages, you are advised to use `notices`, as they are always shown. * * @throws {Error} An error is thrown if no widget is specified */ OO.ui.FieldLayout = function OoUiFieldLayout( fieldWidget, config ) { var hasInputWidget, $div; // Allow passing positional parameters inside the config object if ( OO.isPlainObject( fieldWidget ) && config === undefined ) { config = fieldWidget; fieldWidget = config.fieldWidget; } // Make sure we have required constructor arguments if ( fieldWidget === undefined ) { throw new Error( 'Widget not found' ); } hasInputWidget = fieldWidget.constructor.static.supportsSimpleLabel; // Configuration initialization config = $.extend( { align: 'left' }, config ); // Parent constructor OO.ui.FieldLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.LabelElement.call( this, config ); OO.ui.mixin.TitledElement.call( this, $.extend( {}, config, { $titled: this.$label } ) ); // Properties this.fieldWidget = fieldWidget; this.errors = []; this.notices = []; this.$field = $( '<div>' ); this.$messages = $( '<ul>' ); this.$body = $( '<' + ( hasInputWidget ? 'label' : 'div' ) + '>' ); this.align = null; if ( config.help ) { this.popupButtonWidget = new OO.ui.PopupButtonWidget( { classes: [ 'oo-ui-fieldLayout-help' ], framed: false, icon: 'info' } ); $div = $( '<div>' ); if ( config.help instanceof OO.ui.HtmlSnippet ) { $div.html( config.help.toString() ); } else { $div.text( config.help ); } this.popupButtonWidget.getPopup().$body.append( $div.addClass( 'oo-ui-fieldLayout-help-content' ) ); this.$help = this.popupButtonWidget.$element; } else { this.$help = $( [] ); } // Events if ( hasInputWidget ) { this.$label.on( 'click', this.onLabelClick.bind( this ) ); } this.fieldWidget.connect( this, { disable: 'onFieldDisable' } ); // Initialization this.$element .addClass( 'oo-ui-fieldLayout' ) .toggleClass( 'oo-ui-fieldLayout-disabled', this.fieldWidget.isDisabled() ) .append( this.$help, this.$body ); this.$body.addClass( 'oo-ui-fieldLayout-body' ); this.$messages.addClass( 'oo-ui-fieldLayout-messages' ); this.$field .addClass( 'oo-ui-fieldLayout-field' ) .append( this.fieldWidget.$element ); this.setErrors( config.errors || [] ); this.setNotices( config.notices || [] ); this.setAlignment( config.align ); }; /* Setup */ OO.inheritClass( OO.ui.FieldLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.FieldLayout, OO.ui.mixin.TitledElement ); /* Methods */ /** * Handle field disable events. * * @private * @param {boolean} value Field is disabled */ OO.ui.FieldLayout.prototype.onFieldDisable = function ( value ) { this.$element.toggleClass( 'oo-ui-fieldLayout-disabled', value ); }; /** * Handle label mouse click events. * * @private * @param {jQuery.Event} e Mouse click event */ OO.ui.FieldLayout.prototype.onLabelClick = function () { this.fieldWidget.simulateLabelClick(); return false; }; /** * Get the widget contained by the field. * * @return {OO.ui.Widget} Field widget */ OO.ui.FieldLayout.prototype.getField = function () { return this.fieldWidget; }; /** * @protected * @param {string} kind 'error' or 'notice' * @param {string|OO.ui.HtmlSnippet} text * @return {jQuery} */ OO.ui.FieldLayout.prototype.makeMessage = function ( kind, text ) { var $listItem, $icon, message; $listItem = $( '<li>' ); if ( kind === 'error' ) { $icon = new OO.ui.IconWidget( { icon: 'alert', flags: [ 'warning' ] } ).$element; } else if ( kind === 'notice' ) { $icon = new OO.ui.IconWidget( { icon: 'info' } ).$element; } else { $icon = ''; } message = new OO.ui.LabelWidget( { label: text } ); $listItem .append( $icon, message.$element ) .addClass( 'oo-ui-fieldLayout-messages-' + kind ); return $listItem; }; /** * Set the field alignment mode. * * @private * @param {string} value Alignment mode, either 'left', 'right', 'top' or 'inline' * @chainable */ OO.ui.FieldLayout.prototype.setAlignment = function ( value ) { if ( value !== this.align ) { // Default to 'left' if ( [ 'left', 'right', 'top', 'inline' ].indexOf( value ) === -1 ) { value = 'left'; } // Reorder elements if ( value === 'inline' ) { this.$body.append( this.$field, this.$label ); } else { this.$body.append( this.$label, this.$field ); } // Set classes. The following classes can be used here: // * oo-ui-fieldLayout-align-left // * oo-ui-fieldLayout-align-right // * oo-ui-fieldLayout-align-top // * oo-ui-fieldLayout-align-inline if ( this.align ) { this.$element.removeClass( 'oo-ui-fieldLayout-align-' + this.align ); } this.$element.addClass( 'oo-ui-fieldLayout-align-' + value ); this.align = value; } return this; }; /** * Set the list of error messages. * * @param {Array} errors Error messages about the widget, which will be displayed below the widget. * The array may contain strings or OO.ui.HtmlSnippet instances. * @chainable */ OO.ui.FieldLayout.prototype.setErrors = function ( errors ) { this.errors = errors.slice(); this.updateMessages(); return this; }; /** * Set the list of notice messages. * * @param {Array} notices Notices about the widget, which will be displayed below the widget. * The array may contain strings or OO.ui.HtmlSnippet instances. * @chainable */ OO.ui.FieldLayout.prototype.setNotices = function ( notices ) { this.notices = notices.slice(); this.updateMessages(); return this; }; /** * Update the rendering of error and notice messages. * * @private */ OO.ui.FieldLayout.prototype.updateMessages = function () { var i; this.$messages.empty(); if ( this.errors.length || this.notices.length ) { this.$body.after( this.$messages ); } else { this.$messages.remove(); return; } for ( i = 0; i < this.notices.length; i++ ) { this.$messages.append( this.makeMessage( 'notice', this.notices[ i ] ) ); } for ( i = 0; i < this.errors.length; i++ ) { this.$messages.append( this.makeMessage( 'error', this.errors[ i ] ) ); } }; /** * ActionFieldLayouts are used with OO.ui.FieldsetLayout. The layout consists of a field-widget, a button, * and an optional label and/or help text. The field-widget (e.g., a {@link OO.ui.TextInputWidget TextInputWidget}), * is required and is specified before any optional configuration settings. * * Labels can be aligned in one of four ways: * * - **left**: The label is placed before the field-widget and aligned with the left margin. * A left-alignment is used for forms with many fields. * - **right**: The label is placed before the field-widget and aligned to the right margin. * A right-alignment is used for long but familiar forms which users tab through, * verifying the current field with a quick glance at the label. * - **top**: The label is placed above the field-widget. A top-alignment is used for brief forms * that users fill out from top to bottom. * - **inline**: The label is placed after the field-widget and aligned to the left. * An inline-alignment is best used with checkboxes or radio buttons. * * Help text is accessed via a help icon that appears in the upper right corner of the rendered field layout when help * text is specified. * * @example * // Example of an ActionFieldLayout * var actionFieldLayout = new OO.ui.ActionFieldLayout( * new OO.ui.TextInputWidget( { * placeholder: 'Field widget' * } ), * new OO.ui.ButtonWidget( { * label: 'Button' * } ), * { * label: 'An ActionFieldLayout. This label is aligned top', * align: 'top', * help: 'This is help text' * } * ); * * $( 'body' ).append( actionFieldLayout.$element ); * * @class * @extends OO.ui.FieldLayout * * @constructor * @param {OO.ui.Widget} fieldWidget Field widget * @param {OO.ui.ButtonWidget} buttonWidget Button widget * @param {Object} config */ OO.ui.ActionFieldLayout = function OoUiActionFieldLayout( fieldWidget, buttonWidget, config ) { // Allow passing positional parameters inside the config object if ( OO.isPlainObject( fieldWidget ) && config === undefined ) { config = fieldWidget; fieldWidget = config.fieldWidget; buttonWidget = config.buttonWidget; } // Parent constructor OO.ui.ActionFieldLayout.parent.call( this, fieldWidget, config ); // Properties this.buttonWidget = buttonWidget; this.$button = $( '<div>' ); this.$input = $( '<div>' ); // Initialization this.$element .addClass( 'oo-ui-actionFieldLayout' ); this.$button .addClass( 'oo-ui-actionFieldLayout-button' ) .append( this.buttonWidget.$element ); this.$input .addClass( 'oo-ui-actionFieldLayout-input' ) .append( this.fieldWidget.$element ); this.$field .append( this.$input, this.$button ); }; /* Setup */ OO.inheritClass( OO.ui.ActionFieldLayout, OO.ui.FieldLayout ); /** * FieldsetLayouts are composed of one or more {@link OO.ui.FieldLayout FieldLayouts}, * which each contain an individual widget and, optionally, a label. Each Fieldset can be * configured with a label as well. For more information and examples, * please see the [OOjs UI documentation on MediaWiki][1]. * * @example * // Example of a fieldset layout * var input1 = new OO.ui.TextInputWidget( { * placeholder: 'A text input field' * } ); * * var input2 = new OO.ui.TextInputWidget( { * placeholder: 'A text input field' * } ); * * var fieldset = new OO.ui.FieldsetLayout( { * label: 'Example of a fieldset layout' * } ); * * fieldset.addItems( [ * new OO.ui.FieldLayout( input1, { * label: 'Field One' * } ), * new OO.ui.FieldLayout( input2, { * label: 'Field Two' * } ) * ] ); * $( 'body' ).append( fieldset.$element ); * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Fields_and_Fieldsets * * @class * @extends OO.ui.Layout * @mixins OO.ui.mixin.IconElement * @mixins OO.ui.mixin.LabelElement * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.FieldLayout[]} [items] An array of fields to add to the fieldset. See OO.ui.FieldLayout for more information about fields. * @cfg {string|OO.ui.HtmlSnippet} [help] Help text. When help text is specified, a "help" icon will appear * in the upper-right corner of the rendered field; clicking it will display the text in a popup. * For important messages, you are advised to use `notices`, as they are always shown. */ OO.ui.FieldsetLayout = function OoUiFieldsetLayout( config ) { var $div; // Configuration initialization config = config || {}; // Parent constructor OO.ui.FieldsetLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.IconElement.call( this, config ); OO.ui.mixin.LabelElement.call( this, $.extend( {}, config, { $label: $( '<div>' ) } ) ); OO.ui.mixin.GroupElement.call( this, config ); if ( config.help ) { this.popupButtonWidget = new OO.ui.PopupButtonWidget( { classes: [ 'oo-ui-fieldsetLayout-help' ], framed: false, icon: 'info' } ); $div = $( '<div>' ); if ( config.help instanceof OO.ui.HtmlSnippet ) { $div.html( config.help.toString() ); } else { $div.text( config.help ); } this.popupButtonWidget.getPopup().$body.append( $div.addClass( 'oo-ui-fieldsetLayout-help-content' ) ); this.$help = this.popupButtonWidget.$element; } else { this.$help = $( [] ); } // Initialization this.$group.addClass( 'oo-ui-fieldsetLayout-group' ); this.$element .addClass( 'oo-ui-fieldsetLayout' ) .prepend( this.$label, this.$help, this.$icon, this.$group ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.FieldsetLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.IconElement ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.LabelElement ); OO.mixinClass( OO.ui.FieldsetLayout, OO.ui.mixin.GroupElement ); /* Static Properties */ OO.ui.FieldsetLayout.static.tagName = 'fieldset'; /** * FormLayouts are used to wrap {@link OO.ui.FieldsetLayout FieldsetLayouts} when you intend to use browser-based * form submission for the fields instead of handling them in JavaScript. Form layouts can be configured with an * HTML form action, an encoding type, and a method using the #action, #enctype, and #method configs, respectively. * See the [OOjs UI documentation on MediaWiki] [1] for more information and examples. * * Only widgets from the {@link OO.ui.InputWidget InputWidget} family support form submission. It * includes standard form elements like {@link OO.ui.CheckboxInputWidget checkboxes}, {@link * OO.ui.RadioInputWidget radio buttons} and {@link OO.ui.TextInputWidget text fields}, as well as * some fancier controls. Some controls have both regular and InputWidget variants, for example * OO.ui.DropdownWidget and OO.ui.DropdownInputWidget – only the latter support form submission and * often have simplified APIs to match the capabilities of HTML forms. * See the [OOjs UI Inputs documentation on MediaWiki] [2] for more information about InputWidgets. * * [1]: https://www.mediawiki.org/wiki/OOjs_UI/Layouts/Forms * [2]: https://www.mediawiki.org/wiki/OOjs_UI/Widgets/Inputs * * @example * // Example of a form layout that wraps a fieldset layout * var input1 = new OO.ui.TextInputWidget( { * placeholder: 'Username' * } ); * var input2 = new OO.ui.TextInputWidget( { * placeholder: 'Password', * type: 'password' * } ); * var submit = new OO.ui.ButtonInputWidget( { * label: 'Submit' * } ); * * var fieldset = new OO.ui.FieldsetLayout( { * label: 'A form layout' * } ); * fieldset.addItems( [ * new OO.ui.FieldLayout( input1, { * label: 'Username', * align: 'top' * } ), * new OO.ui.FieldLayout( input2, { * label: 'Password', * align: 'top' * } ), * new OO.ui.FieldLayout( submit ) * ] ); * var form = new OO.ui.FormLayout( { * items: [ fieldset ], * action: '/api/formhandler', * method: 'get' * } ) * $( 'body' ).append( form.$element ); * * @class * @extends OO.ui.Layout * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {string} [method] HTML form `method` attribute * @cfg {string} [action] HTML form `action` attribute * @cfg {string} [enctype] HTML form `enctype` attribute * @cfg {OO.ui.FieldsetLayout[]} [items] Fieldset layouts to add to the form layout. */ OO.ui.FormLayout = function OoUiFormLayout( config ) { var action; // Configuration initialization config = config || {}; // Parent constructor OO.ui.FormLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Events this.$element.on( 'submit', this.onFormSubmit.bind( this ) ); // Make sure the action is safe action = config.action; if ( action !== undefined && !OO.ui.isSafeUrl( action ) ) { action = './' + action; } // Initialization this.$element .addClass( 'oo-ui-formLayout' ) .attr( { method: config.method, action: action, enctype: config.enctype } ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.FormLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.FormLayout, OO.ui.mixin.GroupElement ); /* Events */ /** * A 'submit' event is emitted when the form is submitted. * * @event submit */ /* Static Properties */ OO.ui.FormLayout.static.tagName = 'form'; /* Methods */ /** * Handle form submit events. * * @private * @param {jQuery.Event} e Submit event * @fires submit */ OO.ui.FormLayout.prototype.onFormSubmit = function () { if ( this.emit( 'submit' ) ) { return false; } }; /** * PanelLayouts expand to cover the entire area of their parent. They can be configured with scrolling, padding, * and a frame, and are often used together with {@link OO.ui.StackLayout StackLayouts}. * * @example * // Example of a panel layout * var panel = new OO.ui.PanelLayout( { * expanded: false, * framed: true, * padded: true, * $content: $( '<p>A panel layout with padding and a frame.</p>' ) * } ); * $( 'body' ).append( panel.$element ); * * @class * @extends OO.ui.Layout * * @constructor * @param {Object} [config] Configuration options * @cfg {boolean} [scrollable=false] Allow vertical scrolling * @cfg {boolean} [padded=false] Add padding between the content and the edges of the panel. * @cfg {boolean} [expanded=true] Expand the panel to fill the entire parent element. * @cfg {boolean} [framed=false] Render the panel with a frame to visually separate it from outside content. */ OO.ui.PanelLayout = function OoUiPanelLayout( config ) { // Configuration initialization config = $.extend( { scrollable: false, padded: false, expanded: true, framed: false }, config ); // Parent constructor OO.ui.PanelLayout.parent.call( this, config ); // Initialization this.$element.addClass( 'oo-ui-panelLayout' ); if ( config.scrollable ) { this.$element.addClass( 'oo-ui-panelLayout-scrollable' ); } if ( config.padded ) { this.$element.addClass( 'oo-ui-panelLayout-padded' ); } if ( config.expanded ) { this.$element.addClass( 'oo-ui-panelLayout-expanded' ); } if ( config.framed ) { this.$element.addClass( 'oo-ui-panelLayout-framed' ); } }; /* Setup */ OO.inheritClass( OO.ui.PanelLayout, OO.ui.Layout ); /* Methods */ /** * Focus the panel layout * * The default implementation just focuses the first focusable element in the panel */ OO.ui.PanelLayout.prototype.focus = function () { OO.ui.findFocusable( this.$element ).focus(); }; /** * HorizontalLayout arranges its contents in a single line (using `display: inline-block` for its * items), with small margins between them. Convenient when you need to put a number of block-level * widgets on a single line next to each other. * * Note that inline elements, such as OO.ui.ButtonWidgets, do not need this wrapper. * * @example * // HorizontalLayout with a text input and a label * var layout = new OO.ui.HorizontalLayout( { * items: [ * new OO.ui.LabelWidget( { label: 'Label' } ), * new OO.ui.TextInputWidget( { value: 'Text' } ) * ] * } ); * $( 'body' ).append( layout.$element ); * * @class * @extends OO.ui.Layout * @mixins OO.ui.mixin.GroupElement * * @constructor * @param {Object} [config] Configuration options * @cfg {OO.ui.Widget[]|OO.ui.Layout[]} [items] Widgets or other layouts to add to the layout. */ OO.ui.HorizontalLayout = function OoUiHorizontalLayout( config ) { // Configuration initialization config = config || {}; // Parent constructor OO.ui.HorizontalLayout.parent.call( this, config ); // Mixin constructors OO.ui.mixin.GroupElement.call( this, $.extend( {}, config, { $group: this.$element } ) ); // Initialization this.$element.addClass( 'oo-ui-horizontalLayout' ); if ( Array.isArray( config.items ) ) { this.addItems( config.items ); } }; /* Setup */ OO.inheritClass( OO.ui.HorizontalLayout, OO.ui.Layout ); OO.mixinClass( OO.ui.HorizontalLayout, OO.ui.mixin.GroupElement ); }( OO ) );
'use strict'; describe('Service: <%= cameledName %>', function () { // load the service's module beforeEach(module('<%= scriptAppName %>')); // instantiate service var <%= cameledName %>; beforeEach(inject(function (_<%= cameledName %>_) { <%= cameledName %> = _<%= cameledName %>_; })); it('should do something', function () {<% if (hasFilter('jasmine')) { %> expect(!!<%= cameledName %>).toBe(true);<% } if (hasFilter('mocha')) { %> expect(!!<%= cameledName %>).to.be.true;<% } %> }); });
exports.parse = function() { throw new Error("Boom!"); };
/* */ "format cjs"; "use strict"; exports.__esModule = true; // istanbul ignore next function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj["default"] = obj; return newObj; } } var _types = require("../../../types"); var t = _interopRequireWildcard(_types); var metadata = { optional: true }; /** * [Please add a description.] */ exports.metadata = metadata; var visitor = { /** * [Please add a description.] */ UnaryExpression: function UnaryExpression(node, parent, scope, file) { if (node._ignoreSpecSymbols) return; if (this.parentPath.isBinaryExpression() && t.EQUALITY_BINARY_OPERATORS.indexOf(parent.operator) >= 0) { // optimise `typeof foo === "string"` since we can determine that they'll never need to handle symbols var opposite = this.getOpposite(); if (opposite.isLiteral() && opposite.node.value !== "symbol" && opposite.node.value !== "object") return; } if (node.operator === "typeof") { var call = t.callExpression(file.addHelper("typeof"), [node.argument]); if (this.get("argument").isIdentifier()) { var undefLiteral = t.literal("undefined"); var unary = t.unaryExpression("typeof", node.argument); unary._ignoreSpecSymbols = true; return t.conditionalExpression(t.binaryExpression("===", unary, undefLiteral), undefLiteral, call); } else { return call; } } }, /** * [Please add a description.] */ BinaryExpression: function BinaryExpression(node, parent, scope, file) { if (node.operator === "instanceof") { return t.callExpression(file.addHelper("instanceof"), [node.left, node.right]); } }, /** * [Please add a description.] */ "VariableDeclaration|FunctionDeclaration": function VariableDeclarationFunctionDeclaration(node) { if (node._generated) this.skip(); } }; exports.visitor = visitor;
/* Copyright (c) 2003-2014, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'pagebreak', 'mn', { alt: 'Page Break', // MISSING toolbar: 'Хуудас тусгаарлагч оруулах' } );
/** * angular-ui-sortable - This directive allows you to jQueryUI Sortable. * @version v0.16.1 - 2016-12-16 * @link http://angular-ui.github.com * @license MIT */ (function(window, angular, undefined) { 'use strict'; /* jQuery UI Sortable plugin wrapper @param [ui-sortable] {object} Options to pass to $.fn.sortable() merged onto ui.config */ angular.module('ui.sortable', []) .value('uiSortableConfig',{ // the default for jquery-ui sortable is "> *", we need to restrict this to // ng-repeat items // if the user uses items: '> [ng-repeat],> [data-ng-repeat],> [x-ng-repeat]' }) .directive('uiSortable', [ 'uiSortableConfig', '$timeout', '$log', function(uiSortableConfig, $timeout, $log) { return { require: '?ngModel', scope: { ngModel: '=', uiSortable: '=' }, link: function(scope, element, attrs, ngModel) { var savedNodes; function combineCallbacks(first, second){ var firstIsFunc = typeof first === 'function'; var secondIsFunc = typeof second === 'function'; if(firstIsFunc && secondIsFunc) { return function() { first.apply(this, arguments); second.apply(this, arguments); }; } else if (secondIsFunc) { return second; } return first; } function getSortableWidgetInstance(element) { // this is a fix to support jquery-ui prior to v1.11.x // otherwise we should be using `element.sortable('instance')` var data = element.data('ui-sortable'); if (data && typeof data === 'object' && data.widgetFullName === 'ui-sortable') { return data; } return null; } function patchSortableOption(key, value) { if (callbacks[key]) { if( key === 'stop' ){ // call apply after stop value = combineCallbacks( value, function() { scope.$apply(); }); value = combineCallbacks(value, afterStop); } // wrap the callback value = combineCallbacks(callbacks[key], value); } else if (wrappers[key]) { value = wrappers[key](value); } // patch the options that need to have values set if (!value && (key === 'items' || key === 'ui-model-items')) { value = uiSortableConfig.items; } return value; } function patchUISortableOptions(newVal, oldVal, sortableWidgetInstance) { function addDummyOptionKey(value, key) { if (!(key in opts)) { // add the key in the opts object so that // the patch function detects and handles it opts[key] = null; } } // for this directive to work we have to attach some callbacks angular.forEach(callbacks, addDummyOptionKey); // only initialize it in case we have to // update some options of the sortable var optsDiff = null; if (oldVal) { // reset deleted options to default var defaultOptions; angular.forEach(oldVal, function(oldValue, key) { if (!newVal || !(key in newVal)) { if (key in directiveOpts) { if (key === 'ui-floating') { opts[key] = 'auto'; } else { opts[key] = patchSortableOption(key, undefined); } return; } if (!defaultOptions) { defaultOptions = angular.element.ui.sortable().options; } var defaultValue = defaultOptions[key]; defaultValue = patchSortableOption(key, defaultValue); if (!optsDiff) { optsDiff = {}; } optsDiff[key] = defaultValue; opts[key] = defaultValue; } }); } // update changed options angular.forEach(newVal, function(value, key) { // if it's a custom option of the directive, // handle it approprietly if (key in directiveOpts) { if (key === 'ui-floating' && (value === false || value === true) && sortableWidgetInstance) { sortableWidgetInstance.floating = value; } opts[key] = patchSortableOption(key, value); return; } value = patchSortableOption(key, value); if (!optsDiff) { optsDiff = {}; } optsDiff[key] = value; opts[key] = value; }); return optsDiff; } function getPlaceholderElement (element) { var placeholder = element.sortable('option','placeholder'); // placeholder.element will be a function if the placeholder, has // been created (placeholder will be an object). If it hasn't // been created, either placeholder will be false if no // placeholder class was given or placeholder.element will be // undefined if a class was given (placeholder will be a string) if (placeholder && placeholder.element && typeof placeholder.element === 'function') { var result = placeholder.element(); // workaround for jquery ui 1.9.x, // not returning jquery collection result = angular.element(result); return result; } return null; } function getPlaceholderExcludesludes (element, placeholder) { // exact match with the placeholder's class attribute to handle // the case that multiple connected sortables exist and // the placeholder option equals the class of sortable items var notCssSelector = opts['ui-model-items'].replace(/[^,]*>/g, ''); var excludes = element.find('[class="' + placeholder.attr('class') + '"]:not(' + notCssSelector + ')'); return excludes; } function hasSortingHelper (element, ui) { var helperOption = element.sortable('option','helper'); return helperOption === 'clone' || (typeof helperOption === 'function' && ui.item.sortable.isCustomHelperUsed()); } function getSortingHelper (element, ui, savedNodes) { var result = null; if (hasSortingHelper(element, ui) && element.sortable( 'option', 'appendTo' ) === 'parent') { // The .ui-sortable-helper element (that's the default class name) // is placed last. result = savedNodes.last(); } return result; } // thanks jquery-ui function isFloating (item) { return (/left|right/).test(item.css('float')) || (/inline|table-cell/).test(item.css('display')); } function getElementContext(elementScopes, element) { for (var i = 0; i < elementScopes.length; i++) { var c = elementScopes[i]; if (c.element[0] === element[0]) { return c; } } } function afterStop(e, ui) { ui.item.sortable._destroy(); } // return the index of ui.item among the items // we can't just do ui.item.index() because there it might have siblings // which are not items function getItemIndex(item) { return item.parent() .find(opts['ui-model-items']) .index(item); } var opts = {}; // directive specific options var directiveOpts = { 'ui-floating': undefined, 'ui-model-items': uiSortableConfig.items }; var callbacks = { receive: null, remove: null, start: null, stop: null, update: null }; var wrappers = { helper: null }; angular.extend(opts, directiveOpts, uiSortableConfig, scope.uiSortable); if (!angular.element.fn || !angular.element.fn.jquery) { $log.error('ui.sortable: jQuery should be included before AngularJS!'); return; } function wireUp () { // When we add or remove elements, we need the sortable to 'refresh' // so it can find the new/removed elements. scope.$watchCollection('ngModel', function() { // Timeout to let ng-repeat modify the DOM $timeout(function() { // ensure that the jquery-ui-sortable widget instance // is still bound to the directive's element if (!!getSortableWidgetInstance(element)) { element.sortable('refresh'); } }, 0, false); }); callbacks.start = function(e, ui) { if (opts['ui-floating'] === 'auto') { // since the drag has started, the element will be // absolutely positioned, so we check its siblings var siblings = ui.item.siblings(); var sortableWidgetInstance = getSortableWidgetInstance(angular.element(e.target)); sortableWidgetInstance.floating = isFloating(siblings); } // Save the starting position of dragged item var index = getItemIndex(ui.item); ui.item.sortable = { model: ngModel.$modelValue[index], index: index, source: element, sourceList: ui.item.parent(), sourceModel: ngModel.$modelValue, cancel: function () { ui.item.sortable._isCanceled = true; }, isCanceled: function () { return ui.item.sortable._isCanceled; }, isCustomHelperUsed: function () { return !!ui.item.sortable._isCustomHelperUsed; }, _isCanceled: false, _isCustomHelperUsed: ui.item.sortable._isCustomHelperUsed, _destroy: function () { angular.forEach(ui.item.sortable, function(value, key) { ui.item.sortable[key] = undefined; }); }, _connectedSortables: [], _getElementContext: function (element) { return getElementContext(this._connectedSortables, element); } }; }; callbacks.activate = function(e, ui) { var isSourceContext = ui.item.sortable.source === element; var savedNodesOrigin = isSourceContext ? ui.item.sortable.sourceList : element; var elementContext = { element: element, scope: scope, isSourceContext: isSourceContext, savedNodesOrigin: savedNodesOrigin }; // save the directive's scope so that it is accessible from ui.item.sortable ui.item.sortable._connectedSortables.push(elementContext); // We need to make a copy of the current element's contents so // we can restore it after sortable has messed it up. // This is inside activate (instead of start) in order to save // both lists when dragging between connected lists. savedNodes = savedNodesOrigin.contents(); // If this list has a placeholder (the connected lists won't), // don't inlcude it in saved nodes. var placeholder = getPlaceholderElement(element); if (placeholder && placeholder.length) { var excludes = getPlaceholderExcludesludes(element, placeholder); savedNodes = savedNodes.not(excludes); } }; callbacks.update = function(e, ui) { // Save current drop position but only if this is not a second // update that happens when moving between lists because then // the value will be overwritten with the old value if(!ui.item.sortable.received) { ui.item.sortable.dropindex = getItemIndex(ui.item); var droptarget = ui.item.closest('[ui-sortable], [data-ui-sortable], [x-ui-sortable]'); ui.item.sortable.droptarget = droptarget; ui.item.sortable.droptargetList = ui.item.parent(); var droptargetContext = ui.item.sortable._getElementContext(droptarget); ui.item.sortable.droptargetModel = droptargetContext.scope.ngModel; // Cancel the sort (let ng-repeat do the sort for us) // Don't cancel if this is the received list because it has // already been canceled in the other list, and trying to cancel // here will mess up the DOM. element.sortable('cancel'); } // Put the nodes back exactly the way they started (this is very // important because ng-repeat uses comment elements to delineate // the start and stop of repeat sections and sortable doesn't // respect their order (even if we cancel, the order of the // comments are still messed up). var sortingHelper = !ui.item.sortable.received && getSortingHelper(element, ui, savedNodes); if (sortingHelper && sortingHelper.length) { // Restore all the savedNodes except from the sorting helper element. // That way it will be garbage collected. savedNodes = savedNodes.not(sortingHelper); } var elementContext = ui.item.sortable._getElementContext(element); savedNodes.appendTo(elementContext.savedNodesOrigin); // If this is the target connected list then // it's safe to clear the restored nodes since: // update is currently running and // stop is not called for the target list. if(ui.item.sortable.received) { savedNodes = null; } // If received is true (an item was dropped in from another list) // then we add the new item to this list otherwise wait until the // stop event where we will know if it was a sort or item was // moved here from another list if(ui.item.sortable.received && !ui.item.sortable.isCanceled()) { scope.$apply(function () { ngModel.$modelValue.splice(ui.item.sortable.dropindex, 0, ui.item.sortable.moved); }); } }; callbacks.stop = function(e, ui) { // If the received flag hasn't be set on the item, this is a // normal sort, if dropindex is set, the item was moved, so move // the items in the list. var wasMoved = ('dropindex' in ui.item.sortable) && !ui.item.sortable.isCanceled(); if (wasMoved && !ui.item.sortable.received) { scope.$apply(function () { ngModel.$modelValue.splice( ui.item.sortable.dropindex, 0, ngModel.$modelValue.splice(ui.item.sortable.index, 1)[0]); }); } else if (!wasMoved && !angular.equals(element.contents().toArray(), savedNodes.toArray())) { // if the item was not moved // and the DOM element order has changed, // then restore the elements // so that the ngRepeat's comment are correct. var sortingHelper = getSortingHelper(element, ui, savedNodes); if (sortingHelper && sortingHelper.length) { // Restore all the savedNodes except from the sorting helper element. // That way it will be garbage collected. savedNodes = savedNodes.not(sortingHelper); } var elementContext = ui.item.sortable._getElementContext(element); savedNodes.appendTo(elementContext.savedNodesOrigin); } // It's now safe to clear the savedNodes // since stop is the last callback. savedNodes = null; }; callbacks.receive = function(e, ui) { // An item was dropped here from another list, set a flag on the // item. ui.item.sortable.received = true; }; callbacks.remove = function(e, ui) { // Workaround for a problem observed in nested connected lists. // There should be an 'update' event before 'remove' when moving // elements. If the event did not fire, cancel sorting. if (!('dropindex' in ui.item.sortable)) { element.sortable('cancel'); ui.item.sortable.cancel(); } // Remove the item from this list's model and copy data into item, // so the next list can retrive it if (!ui.item.sortable.isCanceled()) { scope.$apply(function () { ui.item.sortable.moved = ngModel.$modelValue.splice( ui.item.sortable.index, 1)[0]; }); } }; wrappers.helper = function (inner) { if (inner && typeof inner === 'function') { return function (e, item) { var oldItemSortable = item.sortable; var index = getItemIndex(item); item.sortable = { model: ngModel.$modelValue[index], index: index, source: element, sourceList: item.parent(), sourceModel: ngModel.$modelValue, _restore: function () { angular.forEach(item.sortable, function(value, key) { item.sortable[key] = undefined; }); item.sortable = oldItemSortable; } }; var innerResult = inner.apply(this, arguments); item.sortable._restore(); item.sortable._isCustomHelperUsed = item !== innerResult; return innerResult; }; } return inner; }; scope.$watchCollection('uiSortable', function(newVal, oldVal) { // ensure that the jquery-ui-sortable widget instance // is still bound to the directive's element var sortableWidgetInstance = getSortableWidgetInstance(element); if (!!sortableWidgetInstance) { var optsDiff = patchUISortableOptions(newVal, oldVal, sortableWidgetInstance); if (optsDiff) { element.sortable('option', optsDiff); } } }, true); patchUISortableOptions(opts); } function init () { if (ngModel) { wireUp(); } else { $log.info('ui.sortable: ngModel not provided!', element); } // Create sortable element.sortable(opts); } function initIfEnabled () { if (scope.uiSortable && scope.uiSortable.disabled) { return false; } init(); // Stop Watcher initIfEnabled.cancelWatcher(); initIfEnabled.cancelWatcher = angular.noop; return true; } initIfEnabled.cancelWatcher = angular.noop; if (!initIfEnabled()) { initIfEnabled.cancelWatcher = scope.$watch('uiSortable.disabled', initIfEnabled); } } }; } ]); })(window, window.angular);
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports, require('inferno'), require('inferno-create-element')) : typeof define === 'function' && define.amd ? define(['exports', 'inferno', 'inferno-create-element'], factory) : (factory((global.Inferno = global.Inferno || {}, global.Inferno.TestUtils = global.Inferno.TestUtils || {}),global.Inferno,global.Inferno.createElement)); }(this, (function (exports,inferno,createElement) { 'use strict'; createElement = createElement && 'default' in createElement ? createElement['default'] : createElement; /** * @module Inferno-Shared */ /** TypeDoc Comment */ var NO_OP = '$NO_OP'; var ERROR_MSG = 'a runtime error occured! Use Inferno in development environment to find the error.'; // This should be boolean and not reference to window.document var isBrowser = !!(typeof window !== 'undefined' && window.document); // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though var isArray = Array.isArray; function isStringOrNumber(o) { var type = typeof o; return type === 'string' || type === 'number'; } function isNullOrUndef(o) { return isUndefined(o) || isNull(o); } function isInvalid(o) { return isNull(o) || o === false || isTrue(o) || isUndefined(o); } function isFunction(o) { return typeof o === 'function'; } function isNull(o) { return o === null; } function isTrue(o) { return o === true; } function isUndefined(o) { return o === void 0; } function throwError(message) { if (!message) { message = ERROR_MSG; } throw new Error(("Inferno Error: " + message)); } function combineFrom(first, second) { var out = {}; if (first) { for (var key in first) { out[key] = first[key]; } } if (second) { for (var key$1 in second) { out[key$1] = second[key$1]; } } return out; } /** * @module Inferno-Component */ /** TypeDoc Comment */ // Make sure u use EMPTY_OBJ from 'inferno', otherwise it'll be a different reference var noOp = ERROR_MSG; { noOp = 'Inferno Error: Can only update a mounted or mounting component. This usually means you called setState() or forceUpdate() on an unmounted component. This is a no-op.'; } var componentCallbackQueue = new Map(); // when a components root VNode is also a component, we can run into issues // this will recursively look for vNode.parentNode if the VNode is a component function updateParentComponentVNodes(vNode, dom) { if (vNode.flags & 28 /* Component */) { var parentVNode = vNode.parentVNode; if (parentVNode) { parentVNode.dom = dom; updateParentComponentVNodes(parentVNode, dom); } } } var resolvedPromise = Promise.resolve(); function addToQueue(component, force, callback) { var queue = componentCallbackQueue.get(component); if (queue === void 0) { queue = []; componentCallbackQueue.set(component, queue); resolvedPromise.then((function () { componentCallbackQueue.delete(component); component._updating = true; applyState(component, force, (function () { for (var i = 0, len = queue.length; i < len; i++) { queue[i].call(component); } })); component._updating = false; })); } if (!isNullOrUndef(callback)) { queue.push(callback); } } function queueStateChanges(component, newState, callback) { if (isFunction(newState)) { newState = newState(component.state, component.props, component.context); } var pending = component._pendingState; if (isNullOrUndef(pending)) { component._pendingState = pending = newState; } else { for (var stateKey in newState) { pending[stateKey] = newState[stateKey]; } } if (isBrowser && !component._pendingSetState && !component._blockRender) { if (!component._updating) { component._pendingSetState = true; component._updating = true; applyState(component, false, callback); component._updating = false; } else { addToQueue(component, false, callback); } } else { var state = component.state; if (state === null) { component.state = pending; } else { for (var key in pending) { state[key] = pending[key]; } } component._pendingState = null; if (!isNullOrUndef(callback) && component._blockRender) { component._lifecycle.addListener(callback.bind(component)); } } } function applyState(component, force, callback) { if (component._unmounted) { return; } if (force || !component._blockRender) { component._pendingSetState = false; var pendingState = component._pendingState; var prevState = component.state; var nextState = combineFrom(prevState, pendingState); var props = component.props; var context = component.context; component._pendingState = null; var nextInput = component._updateComponent(prevState, nextState, props, props, context, force, true); var didUpdate = true; if (isInvalid(nextInput)) { nextInput = inferno.createVNode(4096 /* Void */, null); } else if (nextInput === NO_OP) { nextInput = component._lastInput; didUpdate = false; } else if (isStringOrNumber(nextInput)) { nextInput = inferno.createVNode(1 /* Text */, null, null, nextInput); } else if (isArray(nextInput)) { { throwError('a valid Inferno VNode (or null) must be returned from a component render. You may have returned an array or an invalid object.'); } throwError(); } var lastInput = component._lastInput; var vNode = component._vNode; var parentDom = (lastInput.dom && lastInput.dom.parentNode) || (lastInput.dom = vNode.dom); component._lastInput = nextInput; if (didUpdate) { var childContext; if (!isNullOrUndef(component.getChildContext)) { childContext = component.getChildContext(); } if (isNullOrUndef(childContext)) { childContext = component._childContext; } else { childContext = combineFrom(context, childContext); } var lifeCycle = component._lifecycle; inferno.internal_patch(lastInput, nextInput, parentDom, lifeCycle, childContext, component._isSVG, false); lifeCycle.trigger(); if (!isNullOrUndef(component.componentDidUpdate)) { component.componentDidUpdate(props, prevState, context); } if (!isNull(inferno.options.afterUpdate)) { inferno.options.afterUpdate(vNode); } } var dom = vNode.dom = nextInput.dom; if (inferno.options.findDOMNodeEnabled) { inferno.internal_DOMNodeMap.set(component, nextInput.dom); } updateParentComponentVNodes(vNode, dom); } else { component.state = component._pendingState; component._pendingState = null; } if (!isNullOrUndef(callback)) { callback.call(component); } } var alreadyWarned = false; var Component = function Component(props, context) { this.state = null; this._blockRender = false; this._blockSetState = true; this._pendingSetState = false; this._pendingState = null; this._lastInput = null; this._vNode = null; this._unmounted = false; this._lifecycle = null; this._childContext = null; this._isSVG = false; this._updating = true; /** @type {object} */ this.props = props || inferno.EMPTY_OBJ; /** @type {object} */ this.context = context || inferno.EMPTY_OBJ; // context should not be mutable }; Component.prototype.forceUpdate = function forceUpdate (callback) { if (this._unmounted || !isBrowser) { return; } applyState(this, true, callback); }; Component.prototype.setState = function setState (newState, callback) { if (this._unmounted) { return; } if (!this._blockSetState) { queueStateChanges(this, newState, callback); } else { { throwError('cannot update state via setState() in componentWillUpdate() or constructor.'); } throwError(); } }; Component.prototype.setStateSync = function setStateSync (newState) { { if (!alreadyWarned) { alreadyWarned = true; // tslint:disable-next-line:no-console console.warn('Inferno WARNING: setStateSync has been deprecated and will be removed in next release. Use setState instead.'); } } this.setState(newState); }; Component.prototype._updateComponent = function _updateComponent (prevState, nextState, prevProps, nextProps, context, force, fromSetState) { if (this._unmounted === true) { { throwError(noOp); } throwError(); } if ((prevProps !== nextProps || nextProps === inferno.EMPTY_OBJ) || prevState !== nextState || force) { if (prevProps !== nextProps || nextProps === inferno.EMPTY_OBJ) { if (!isNullOrUndef(this.componentWillReceiveProps) && !fromSetState) { // keep a copy of state before componentWillReceiveProps var beforeState = combineFrom(this.state); this._blockRender = true; this.componentWillReceiveProps(nextProps, context); this._blockRender = false; var afterState = this.state; if (beforeState !== afterState) { // if state changed in componentWillReceiveProps, reassign the beforeState this.state = beforeState; // set the afterState as pending state so the change gets picked up below this._pendingSetState = true; this._pendingState = afterState; } } if (this._pendingSetState) { nextState = combineFrom(nextState, this._pendingState); this._pendingSetState = false; this._pendingState = null; } } /* Update if scu is not defined, or it returns truthy value or force */ if (force || isNullOrUndef(this.shouldComponentUpdate) || (this.shouldComponentUpdate && this.shouldComponentUpdate(nextProps, nextState, context))) { if (!isNullOrUndef(this.componentWillUpdate)) { this._blockSetState = true; this.componentWillUpdate(nextProps, nextState, context); this._blockSetState = false; } this.props = nextProps; this.state = nextState; this.context = context; if (inferno.options.beforeRender) { inferno.options.beforeRender(this); } var render$$1 = this.render(nextProps, nextState, context); if (inferno.options.afterRender) { inferno.options.afterRender(this); } return render$$1; } else { this.props = nextProps; this.state = nextState; this.context = context; } } return NO_OP; }; // tslint:disable-next-line:no-empty Component.prototype.render = function render$$1 (nextProps, nextState, nextContext) { }; /** * @module Inferno-Shared */ /** TypeDoc Comment */ var ERROR_MSG$1 = 'a runtime error occured! Use Inferno in development environment to find the error.'; // this is MUCH faster than .constructor === Array and instanceof Array // in Node 7 and the later versions of V8, slower in older versions though var isArray$1 = Array.isArray; function isNullOrUndef$1(o) { return isUndefined$1(o) || isNull$1(o); } function isFunction$1(o) { return typeof o === 'function'; } function isString(o) { return typeof o === 'string'; } function isNumber(o) { return typeof o === 'number'; } function isNull$1(o) { return o === null; } function isUndefined$1(o) { return o === void 0; } function isObject(o) { return typeof o === 'object'; } function throwError$1(message) { if (!message) { message = ERROR_MSG$1; } throw new Error(("Inferno Error: " + message)); } /** * @module Inferno-Test-Utils */ /** TypeDoc Comment */ // Jest Snapshot Utilities // Jest formats it's snapshots prettily because it knows how to play with the React test renderer. // Symbols and algorithm have been reversed from the following file: // https://github.com/facebook/react/blob/v15.4.2/src/renderers/testing/ReactTestRenderer.js#L98 function createSnapshotObject(object) { Object.defineProperty(object, "$$typeof", { value: Symbol.for("react.test.json") }); return object; } function vNodeToSnapshot(node) { var object; var children = []; if (isDOMVNode(node)) { var props = Object.assign({}, node.props); // Remove undefined props Object.keys(props).forEach((function (propKey) { if (props[propKey] === undefined) { delete props[propKey]; } })); // Create the actual object that Jest will interpret as the snapshot for this VNode object = createSnapshotObject({ props: props, type: getTagNameOfVNode(node) }); } if (isArray$1(node.children)) { node.children.forEach((function (child) { var asJSON = vNodeToSnapshot(child); if (asJSON) { children.push(asJSON); } })); } else if (isString(node.children)) { children.push(node.children); } else if (isObject(node.children) && !isNull$1(node.children)) { var asJSON = vNodeToSnapshot(node.children); if (asJSON) { children.push(asJSON); } } if (object) { object.children = children.length ? children : null; return object; } if (children.length > 1) { return children; } else if (children.length === 1) { return children[0]; } return object; } function renderToSnapshot(input) { var wrapper = renderIntoDocument(input); var vnode = wrapper.props.children; if (!isNull$1(wrapper.props)) { var snapshot = vNodeToSnapshot(vnode.children); delete snapshot.props.children; return snapshot; } return undefined; } /** * @module Inferno-Test-Utils */ /** TypeDoc Comment */ // Type Checkers function isVNode(instance) { return (Boolean(instance) && isObject(instance) && isNumber(instance.flags) && instance.flags > 0); } function isVNodeOfType(instance, type) { return isVNode(instance) && instance.type === type; } function isDOMVNode(inst) { return !isComponentVNode(inst) && !isTextVNode(inst); } function isDOMVNodeOfType(instance, type) { return isDOMVNode(instance) && instance.type === type; } function isFunctionalVNode(instance) { return (isVNode(instance) && Boolean(instance.flags & 8 /* ComponentFunction */)); } function isFunctionalVNodeOfType(instance, type) { return isFunctionalVNode(instance) && instance.type === type; } function isClassVNode(instance) { return (isVNode(instance) && Boolean(instance.flags & 4 /* ComponentClass */)); } function isClassVNodeOfType(instance, type) { return isClassVNode(instance) && instance.type === type; } function isComponentVNode(inst) { return isFunctionalVNode(inst) || isClassVNode(inst); } function isComponentVNodeOfType(inst, type) { return (isFunctionalVNode(inst) || isClassVNode(inst)) && inst.type === type; } function isTextVNode(inst) { return inst.flags === 1 /* Text */; } function isDOMElement(instance) { return (Boolean(instance) && isObject(instance) && instance.nodeType === 1 && isString(instance.tagName)); } function isDOMElementOfType(instance, type) { return (isDOMElement(instance) && isString(type) && instance.tagName.toLowerCase() === type.toLowerCase()); } function isRenderedClassComponent(instance) { return (Boolean(instance) && isObject(instance) && isVNode(instance._vNode) && isFunction$1(instance.render) && isFunction$1(instance.setState)); } function isRenderedClassComponentOfType(instance, type) { return (isRenderedClassComponent(instance) && isFunction$1(type) && instance._vNode.type === type); } // Render Utilities var Wrapper = (function (Component$$1) { function Wrapper () { Component$$1.apply(this, arguments); } if ( Component$$1 ) Wrapper.__proto__ = Component$$1; Wrapper.prototype = Object.create( Component$$1 && Component$$1.prototype ); Wrapper.prototype.constructor = Wrapper; Wrapper.prototype.render = function render$$1 () { return this.props.children; }; Wrapper.prototype.repaint = function repaint () { var this$1 = this; return new Promise(function (resolve) { return this$1.setState({}, resolve); }); }; return Wrapper; }(Component)); function renderIntoDocument(input) { var wrappedInput = createElement(Wrapper, null, input); var parent = document.createElement("div"); document.body.appendChild(parent); return inferno.render(wrappedInput, parent); } // Recursive Finder Functions function findAllInRenderedTree(renderedTree, predicate) { if (isRenderedClassComponent(renderedTree)) { return findAllInVNodeTree(renderedTree._lastInput, predicate); } else { throwError$1("findAllInRenderedTree(renderedTree, predicate) renderedTree must be a rendered class component"); } } function findAllInVNodeTree(vNodeTree, predicate) { if (isVNode(vNodeTree)) { var result = predicate(vNodeTree) ? [vNodeTree] : []; var children = vNodeTree.children; if (isRenderedClassComponent(children)) { result = result.concat(findAllInVNodeTree(children._lastInput, predicate)); } else if (isVNode(children)) { result = result.concat(findAllInVNodeTree(children, predicate)); } else if (isArray$1(children)) { children.forEach((function (child) { result = result.concat(findAllInVNodeTree(child, predicate)); })); } return result; } else { throwError$1("findAllInVNodeTree(vNodeTree, predicate) vNodeTree must be a VNode instance"); } } // Finder Helpers function parseSelector(filter) { if (isArray$1(filter)) { return filter; } else if (isString(filter)) { return filter.trim().split(/\s+/); } else { return []; } } function findOneOf(tree, filter, name, finder) { var all = finder(tree, filter); if (all.length > 1) { throwError$1(("Did not find exactly one match (found " + (all.length) + ") for " + name + ": " + filter)); } else { return all[0]; } } // Scry Utilities function scryRenderedDOMElementsWithClass(renderedTree, classNames) { return findAllInRenderedTree(renderedTree, (function (instance) { if (isDOMVNode(instance)) { var domClassName = instance.dom.className; if (!isString(domClassName) && !isNullOrUndef$1(instance.dom) && isFunction$1(instance.dom.getAttribute)) { // SVG || null, probably domClassName = instance.dom.getAttribute("class") || ""; } var domClassList = parseSelector(domClassName); return parseSelector(classNames).every((function (className) { return domClassList.indexOf(className) !== -1; })); } return false; })).map((function (instance) { return instance.dom; })); } function scryRenderedDOMElementsWithTag(renderedTree, tagName) { return findAllInRenderedTree(renderedTree, (function (instance) { return isDOMVNodeOfType(instance, tagName); })).map((function (instance) { return instance.dom; })); } function scryRenderedVNodesWithType(renderedTree, type) { return findAllInRenderedTree(renderedTree, (function (instance) { return isVNodeOfType(instance, type); })); } function scryVNodesWithType(vNodeTree, type) { return findAllInVNodeTree(vNodeTree, (function (instance) { return isVNodeOfType(instance, type); })); } // Find Utilities function findRenderedDOMElementWithClass(renderedTree, classNames) { return findOneOf(renderedTree, classNames, "class", scryRenderedDOMElementsWithClass); } function findRenderedDOMElementWithTag(renderedTree, tagName) { return findOneOf(renderedTree, tagName, "tag", scryRenderedDOMElementsWithTag); } function findRenderedVNodeWithType(renderedTree, type) { return findOneOf(renderedTree, type, "component", scryRenderedVNodesWithType); } function findVNodeWithType(vNodeTree, type) { return findOneOf(vNodeTree, type, "VNode", scryVNodesWithType); } function getTagNameOfVNode(inst) { return ((inst && inst.dom && inst.dom.tagName.toLowerCase()) || (inst && inst._vNode && inst._vNode.dom && inst._vNode.dom.tagName.toLowerCase()) || undefined); } var index = { Wrapper: Wrapper, findAllInRenderedTree: findAllInRenderedTree, findAllInVNodeTree: findAllInVNodeTree, findRenderedDOMElementWithClass: findRenderedDOMElementWithClass, findRenderedDOMElementWithTag: findRenderedDOMElementWithTag, findRenderedVNodeWithType: findRenderedVNodeWithType, findVNodeWithType: findVNodeWithType, getTagNameOfVNode: getTagNameOfVNode, isClassVNode: isClassVNode, isClassVNodeOfType: isClassVNodeOfType, isComponentVNode: isComponentVNode, isComponentVNodeOfType: isComponentVNodeOfType, isDOMElement: isDOMElement, isDOMElementOfType: isDOMElementOfType, isDOMVNode: isDOMVNode, isDOMVNodeOfType: isDOMVNodeOfType, isFunctionalVNode: isFunctionalVNode, isFunctionalVNodeOfType: isFunctionalVNodeOfType, isRenderedClassComponent: isRenderedClassComponent, isRenderedClassComponentOfType: isRenderedClassComponentOfType, isTextVNode: isTextVNode, isVNode: isVNode, isVNodeOfType: isVNodeOfType, renderIntoDocument: renderIntoDocument, renderToSnapshot: renderToSnapshot, scryRenderedDOMElementsWithClass: scryRenderedDOMElementsWithClass, scryRenderedDOMElementsWithTag: scryRenderedDOMElementsWithTag, scryRenderedVNodesWithType: scryRenderedVNodesWithType, scryVNodesWithType: scryVNodesWithType, vNodeToSnapshot: vNodeToSnapshot }; exports.isVNode = isVNode; exports.isVNodeOfType = isVNodeOfType; exports.isDOMVNode = isDOMVNode; exports.isDOMVNodeOfType = isDOMVNodeOfType; exports.isFunctionalVNode = isFunctionalVNode; exports.isFunctionalVNodeOfType = isFunctionalVNodeOfType; exports.isClassVNode = isClassVNode; exports.isClassVNodeOfType = isClassVNodeOfType; exports.isComponentVNode = isComponentVNode; exports.isComponentVNodeOfType = isComponentVNodeOfType; exports.isTextVNode = isTextVNode; exports.isDOMElement = isDOMElement; exports.isDOMElementOfType = isDOMElementOfType; exports.isRenderedClassComponent = isRenderedClassComponent; exports.isRenderedClassComponentOfType = isRenderedClassComponentOfType; exports.Wrapper = Wrapper; exports.renderIntoDocument = renderIntoDocument; exports.findAllInRenderedTree = findAllInRenderedTree; exports.findAllInVNodeTree = findAllInVNodeTree; exports.scryRenderedDOMElementsWithClass = scryRenderedDOMElementsWithClass; exports.scryRenderedDOMElementsWithTag = scryRenderedDOMElementsWithTag; exports.scryRenderedVNodesWithType = scryRenderedVNodesWithType; exports.scryVNodesWithType = scryVNodesWithType; exports.findRenderedDOMElementWithClass = findRenderedDOMElementWithClass; exports.findRenderedDOMElementWithTag = findRenderedDOMElementWithTag; exports.findRenderedVNodeWithType = findRenderedVNodeWithType; exports.findVNodeWithType = findVNodeWithType; exports.getTagNameOfVNode = getTagNameOfVNode; exports['default'] = index; Object.defineProperty(exports, '__esModule', { value: true }); })));
(function() { /* global define, Ember */ define('ember', [], function() { "use strict"; return { 'default': Ember }; }); define('ember-data', [], function() { "use strict"; return { 'default': DS }; }); })(); define('jquery', [], function() { "use strict"; return { 'default': jQuery }; });
class C { [Symbol.iterator]: number; [Symbol.iterator]?: number; }
'use strict'; const assert = require('assert'); let battle; describe('Substitute', function () { afterEach(function () { battle.destroy(); }); it('should deduct 25% of max HP, rounded down', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['substitute']}]); battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['recover']}]); battle.commitDecisions(); let pokemon = battle.p1.active[0]; assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 4)); }); it('should not block the user\'s own moves from targetting itself', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['substitute', 'calmmind']}]); battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['recover']}]); battle.commitDecisions(); battle.choose('p1', 'move 2'); battle.commitDecisions(); assert.strictEqual(battle.p1.active[0].boosts['spa'], 1); assert.strictEqual(battle.p1.active[0].boosts['spd'], 1); }); it('should block damage from most moves', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['substitute']}]); battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'pressure', item: 'laggingtail', moves: ['psystrike']}]); battle.commitDecisions(); let pokemon = battle.p1.active[0]; assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 4)); }); it('should not block recoil damage', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['substitute', 'doubleedge']}]); battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['nastyplot']}]); battle.commitDecisions(); battle.choose('p1', 'move 2'); battle.commitDecisions(); let pokemon = battle.p1.active[0]; assert.notStrictEqual(pokemon.maxhp - pokemon.hp, Math.floor(pokemon.maxhp / 4)); }); it('should cause recoil damage from an opponent\'s moves to be based on damage dealt to the substitute', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'pressure', moves: ['substitute']}]); battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'noguard', moves: ['nastyplot', 'lightofruin']}]); battle.commitDecisions(); battle.choose('p2', 'move 2'); battle.commitDecisions(); let pokemon = battle.p2.active[0]; assert.strictEqual(pokemon.maxhp - pokemon.hp, Math.ceil(Math.floor(battle.p1.active[0].maxhp / 4) / 2)); }); it('should cause recovery from an opponent\'s draining moves to be based on damage dealt to the substitute', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: 'Zangoose', ability: 'pressure', moves: ['substitute']}]); battle.join('p2', 'Guest 2', 1, [{species: 'Zangoose', ability: 'noguard', moves: ['bellydrum', 'drainpunch']}]); battle.commitDecisions(); let hp = battle.p2.active[0].hp; battle.choose('p2', 'move 2'); battle.commitDecisions(); assert.strictEqual(battle.p2.active[0].hp - hp, Math.ceil(Math.floor(battle.p1.active[0].maxhp / 4) / 2)); }); it('should block most status moves targetting the user', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: 'Mewtwo', ability: 'noguard', moves: ['substitute']}]); battle.join('p2', 'Guest 2', 1, [{species: 'Mewtwo', ability: 'pressure', item: 'laggingtail', moves: ['hypnosis', 'toxic', 'poisongas', 'thunderwave', 'willowisp']}]); for (let i = 1; i <= 5; i++) { battle.choose('p2', 'move ' + i); battle.commitDecisions(); assert.strictEqual(battle.p1.active[0].status, ''); } }); it('should allow multi-hit moves to continue after the substitute fades', function () { battle = BattleEngine.Battle.construct(); battle.join('p1', 'Guest 1', 1, [{species: 'Dragonite', ability: 'noguard', item: 'focussash', moves: ['substitute', 'roost']}]); battle.join('p2', 'Guest 2', 1, [{species: 'Dragonite', ability: 'hugepower', item: 'laggingtail', moves: ['roost', 'dualchop']}]); battle.commitDecisions(); battle.choose('p1', 'move 2'); battle.choose('p2', 'move 2'); assert.notStrictEqual(battle.p1.active[0].hp, battle.p1.active[0].maxhp); }); });
/* Copyright (c) 2014 Ramesh Nair (hiddentao.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (function() { var cls, getValueHandler, registerValueHandler, squel, _extend, _ref, _ref1, _ref2, _ref3, _ref4, _without, __slice = [].slice, __hasProp = {}.hasOwnProperty, __extends = function(child, parent) { for (var key in parent) { if (__hasProp.call(parent, key)) child[key] = parent[key]; } function ctor() { this.constructor = child; } ctor.prototype = parent.prototype; child.prototype = new ctor(); child.__super__ = parent.prototype; return child; }, __bind = function(fn, me){ return function(){ return fn.apply(me, arguments); }; }; cls = {}; _extend = function() { var dst, k, sources, src, v, _i, _len; dst = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if (sources) { for (_i = 0, _len = sources.length; _i < _len; _i++) { src = sources[_i]; if (src) { for (k in src) { if (!__hasProp.call(src, k)) continue; v = src[k]; dst[k] = v; } } } } return dst; }; _without = function() { var dst, obj, p, properties, _i, _len; obj = arguments[0], properties = 2 <= arguments.length ? __slice.call(arguments, 1) : []; dst = _extend({}, obj); for (_i = 0, _len = properties.length; _i < _len; _i++) { p = properties[_i]; delete dst[p]; } return dst; }; cls.DefaultQueryBuilderOptions = { autoQuoteTableNames: false, autoQuoteFieldNames: false, autoQuoteAliasNames: true, nameQuoteCharacter: '`', tableAliasQuoteCharacter: '`', fieldAliasQuoteCharacter: '"', valueHandlers: [], numberedParameters: false, numberedParametersStartAt: 1, replaceSingleQuotes: false, singleQuoteReplacement: '\'\'', separator: ' ' }; cls.globalValueHandlers = []; registerValueHandler = function(handlers, type, handler) { var typeHandler, _i, _len; if ('function' !== typeof type && 'string' !== typeof type) { throw new Error("type must be a class constructor or string denoting 'typeof' result"); } if ('function' !== typeof handler) { throw new Error("handler must be a function"); } for (_i = 0, _len = handlers.length; _i < _len; _i++) { typeHandler = handlers[_i]; if (typeHandler.type === type) { typeHandler.handler = handler; return; } } return handlers.push({ type: type, handler: handler }); }; getValueHandler = function() { var handlerLists, handlers, typeHandler, value, _i, _j, _len, _len1; value = arguments[0], handlerLists = 2 <= arguments.length ? __slice.call(arguments, 1) : []; for (_i = 0, _len = handlerLists.length; _i < _len; _i++) { handlers = handlerLists[_i]; for (_j = 0, _len1 = handlers.length; _j < _len1; _j++) { typeHandler = handlers[_j]; if (typeHandler.type === typeof value || (typeof typeHandler.type !== 'string' && value instanceof typeHandler.type)) { return typeHandler.handler; } } } return void 0; }; cls.registerValueHandler = function(type, handler) { return registerValueHandler(cls.globalValueHandlers, type, handler); }; cls.Cloneable = (function() { function Cloneable() {} Cloneable.prototype.clone = function() { var newInstance; newInstance = new this.constructor; return _extend(newInstance, JSON.parse(JSON.stringify(this))); }; return Cloneable; })(); cls.BaseBuilder = (function(_super) { __extends(BaseBuilder, _super); function BaseBuilder(options) { var defaults; defaults = JSON.parse(JSON.stringify(cls.DefaultQueryBuilderOptions)); this.options = _extend({}, defaults, options); } BaseBuilder.prototype.registerValueHandler = function(type, handler) { registerValueHandler(this.options.valueHandlers, type, handler); return this; }; BaseBuilder.prototype._getObjectClassName = function(obj) { var arr; if (obj && obj.constructor && obj.constructor.toString) { arr = obj.constructor.toString().match(/function\s*(\w+)/); if (arr && arr.length === 2) { return arr[1]; } } return void 0; }; BaseBuilder.prototype._sanitizeCondition = function(condition) { if (!(condition instanceof cls.Expression)) { if ("string" !== typeof condition) { throw new Error("condition must be a string or Expression instance"); } } return condition; }; BaseBuilder.prototype._sanitizeName = function(value, type) { if ("string" !== typeof value) { throw new Error("" + type + " must be a string"); } return value; }; BaseBuilder.prototype._sanitizeField = function(item, formattingOptions) { var quoteChar; if (formattingOptions == null) { formattingOptions = {}; } if (item instanceof cls.QueryBuilder) { item = "(" + item + ")"; } else { item = this._sanitizeName(item, "field name"); if (this.options.autoQuoteFieldNames) { quoteChar = this.options.nameQuoteCharacter; if (formattingOptions.ignorePeriodsForFieldNameQuotes) { item = "" + quoteChar + item + quoteChar; } else { item = item.split('.').map(function(v) { if ('*' === v) { return v; } else { return "" + quoteChar + v + quoteChar; } }).join('.'); } } } return item; }; BaseBuilder.prototype._sanitizeTable = function(item, allowNested) { var sanitized; if (allowNested == null) { allowNested = false; } if (allowNested) { if ("string" === typeof item) { sanitized = item; } else if (item instanceof cls.QueryBuilder && item.isNestable()) { return item; } else { throw new Error("table name must be a string or a nestable query instance"); } } else { sanitized = this._sanitizeName(item, 'table name'); } if (this.options.autoQuoteTableNames) { return "" + this.options.nameQuoteCharacter + sanitized + this.options.nameQuoteCharacter; } else { return sanitized; } }; BaseBuilder.prototype._sanitizeTableAlias = function(item) { var sanitized; sanitized = this._sanitizeName(item, "table alias"); if (this.options.autoQuoteAliasNames) { return "" + this.options.tableAliasQuoteCharacter + sanitized + this.options.tableAliasQuoteCharacter; } else { return sanitized; } }; BaseBuilder.prototype._sanitizeFieldAlias = function(item) { var sanitized; sanitized = this._sanitizeName(item, "field alias"); if (this.options.autoQuoteAliasNames) { return "" + this.options.fieldAliasQuoteCharacter + sanitized + this.options.fieldAliasQuoteCharacter; } else { return sanitized; } }; BaseBuilder.prototype._sanitizeLimitOffset = function(value) { value = parseInt(value); if (0 > value || isNaN(value)) { throw new Error("limit/offset must be >= 0"); } return value; }; BaseBuilder.prototype._sanitizeValue = function(item) { var itemType, typeIsValid; itemType = typeof item; if (null === item) { } else if ("string" === itemType || "number" === itemType || "boolean" === itemType) { } else if (item instanceof cls.QueryBuilder && item.isNestable()) { } else { typeIsValid = void 0 !== getValueHandler(item, this.options.valueHandlers, cls.globalValueHandlers); if (!typeIsValid) { throw new Error("field value must be a string, number, boolean, null or one of the registered custom value types"); } } return item; }; BaseBuilder.prototype._escapeValue = function(value) { if (true !== this.options.replaceSingleQuotes) { return value; } return value.replace(/\'/g, this.options.singleQuoteReplacement); }; BaseBuilder.prototype._formatCustomValue = function(value) { var customHandler; customHandler = getValueHandler(value, this.options.valueHandlers, cls.globalValueHandlers); if (customHandler) { value = customHandler(value); } return value; }; BaseBuilder.prototype._formatValueAsParam = function(value) { var p, _this = this; if (Array.isArray(value)) { return value.map(function(v) { return _this._formatValueAsParam(v); }); } else { if (value instanceof cls.QueryBuilder && value.isNestable()) { value.updateOptions({ "nestedBuilder": true }); return p = value.toParam(); } else if (value instanceof cls.Expression) { return p = value.toParam(); } else { return this._formatCustomValue(value); } } }; BaseBuilder.prototype._formatValue = function(value, formattingOptions) { var _this = this; if (formattingOptions == null) { formattingOptions = {}; } value = this._formatCustomValue(value); if (Array.isArray(value)) { value = value.map(function(v) { return _this._formatValue(v); }); value = "(" + (value.join(', ')) + ")"; } else { if (null === value) { value = "NULL"; } else if ("boolean" === typeof value) { value = value ? "TRUE" : "FALSE"; } else if (value instanceof cls.QueryBuilder) { value = "(" + value + ")"; } else if (value instanceof cls.Expression) { value = "(" + value + ")"; } else if ("number" !== typeof value) { value = this._escapeValue(value); value = formattingOptions.dontQuote ? "" + value : "'" + value + "'"; } } return value; }; return BaseBuilder; })(cls.Cloneable); cls.Expression = (function(_super) { __extends(Expression, _super); Expression.prototype.tree = null; Expression.prototype.current = null; function Expression() { var _this = this; Expression.__super__.constructor.call(this); this.tree = { parent: null, nodes: [] }; this.current = this.tree; this._begin = function(op) { var new_tree; new_tree = { type: op, parent: _this.current, nodes: [] }; _this.current.nodes.push(new_tree); _this.current = _this.current.nodes[_this.current.nodes.length - 1]; return _this; }; } Expression.prototype.and_begin = function() { return this._begin('AND'); }; Expression.prototype.or_begin = function() { return this._begin('OR'); }; Expression.prototype.end = function() { if (!this.current.parent) { throw new Error("begin() needs to be called"); } this.current = this.current.parent; return this; }; Expression.prototype.and = function(expr, param) { if (!expr || "string" !== typeof expr) { throw new Error("expr must be a string"); } this.current.nodes.push({ type: 'AND', expr: expr, para: param }); return this; }; Expression.prototype.or = function(expr, param) { if (!expr || "string" !== typeof expr) { throw new Error("expr must be a string"); } this.current.nodes.push({ type: 'OR', expr: expr, para: param }); return this; }; Expression.prototype.toString = function() { if (null !== this.current.parent) { throw new Error("end() needs to be called"); } return this._toString(this.tree); }; Expression.prototype.toParam = function() { if (null !== this.current.parent) { throw new Error("end() needs to be called"); } return this._toString(this.tree, true); }; Expression.prototype._toString = function(node, paramMode) { var child, cv, inStr, nodeStr, params, str, _i, _len, _ref; if (paramMode == null) { paramMode = false; } str = ""; params = []; _ref = node.nodes; for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; if (child.expr != null) { nodeStr = child.expr; if (child.para != null) { if (!paramMode) { nodeStr = nodeStr.replace('?', this._formatValue(child.para)); } else { cv = this._formatValueAsParam(child.para); if ((cv.text != null)) { params = params.concat(cv.values); nodeStr = nodeStr.replace('?', "(" + cv.text + ")"); } else { params = params.concat(cv); } if (Array.isArray(child.para)) { inStr = Array.apply(null, new Array(child.para.length)).map(function() { return '?'; }); nodeStr = nodeStr.replace('?', "(" + (inStr.join(', ')) + ")"); } } } } else { nodeStr = this._toString(child, paramMode); if (paramMode) { params = params.concat(nodeStr.values); nodeStr = nodeStr.text; } if ("" !== nodeStr) { nodeStr = "(" + nodeStr + ")"; } } if ("" !== nodeStr) { if ("" !== str) { str += " " + child.type + " "; } str += nodeStr; } } if (paramMode) { return { text: str, values: params }; } else { return str; } }; /* Clone this expression. Note that the algorithm contained within this method is probably non-optimal, so please avoid cloning large expression trees. */ Expression.prototype.clone = function() { var newInstance, _cloneTree; newInstance = new this.constructor; (_cloneTree = function(node) { var child, _i, _len, _ref, _results; _ref = node.nodes; _results = []; for (_i = 0, _len = _ref.length; _i < _len; _i++) { child = _ref[_i]; if (child.expr != null) { _results.push(newInstance.current.nodes.push(JSON.parse(JSON.stringify(child)))); } else { newInstance._begin(child.type); _cloneTree(child); if (!this.current === child) { _results.push(newInstance.end()); } else { _results.push(void 0); } } } return _results; })(this.tree); return newInstance; }; return Expression; })(cls.BaseBuilder); cls.Block = (function(_super) { __extends(Block, _super); function Block() { _ref = Block.__super__.constructor.apply(this, arguments); return _ref; } Block.prototype.exposedMethods = function() { var attr, ret, value; ret = {}; for (attr in this) { value = this[attr]; if (typeof value === "function" && attr.charAt(0) !== '_' && !cls.Block.prototype[attr]) { ret[attr] = value; } } return ret; }; Block.prototype.buildStr = function(queryBuilder) { return ''; }; Block.prototype.buildParam = function(queryBuilder) { return { text: this.buildStr(queryBuilder), values: [] }; }; return Block; })(cls.BaseBuilder); cls.StringBlock = (function(_super) { __extends(StringBlock, _super); function StringBlock(options, str) { StringBlock.__super__.constructor.call(this, options); this.str = str; } StringBlock.prototype.buildStr = function(queryBuilder) { return this.str; }; return StringBlock; })(cls.Block); cls.AbstractTableBlock = (function(_super) { __extends(AbstractTableBlock, _super); function AbstractTableBlock(options) { AbstractTableBlock.__super__.constructor.call(this, options); this.tables = []; } AbstractTableBlock.prototype._table = function(table, alias) { if (alias == null) { alias = null; } if (alias) { alias = this._sanitizeTableAlias(alias); } table = this._sanitizeTable(table, this.options.allowNested || false); if (this.options.singleTable) { this.tables = []; } return this.tables.push({ table: table, alias: alias }); }; AbstractTableBlock.prototype.buildStr = function(queryBuilder) { var table, tables, _i, _len, _ref1; if (0 >= this.tables.length) { throw new Error("_table() needs to be called"); } tables = ""; _ref1 = this.tables; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { table = _ref1[_i]; if ("" !== tables) { tables += ", "; } if ("string" === typeof table.table) { tables += table.table; } else { tables += "(" + table.table + ")"; } if (table.alias) { tables += " " + table.alias; } } return tables; }; AbstractTableBlock.prototype._buildParam = function(queryBuilder, prefix) { var blk, p, paramStr, params, ret, v, _i, _j, _k, _len, _len1, _len2, _ref1, _ref2; if (prefix == null) { prefix = null; } ret = { text: "", values: [] }; params = []; paramStr = ""; if (0 >= this.tables.length) { return ret; } _ref1 = this.tables; for (_i = 0, _len = _ref1.length; _i < _len; _i++) { blk = _ref1[_i]; if ("string" === typeof blk.table) { p = { "text": "" + blk.table, "values": [] }; } else if (blk.table instanceof cls.QueryBuilder) { blk.table.updateOptions({ "nestedBuilder": true }); p = blk.table.toParam(); } else { blk.updateOptions({ "nestedBuilder": true }); p = blk.buildParam(queryBuilder); } p.table = blk; params.push(p); } for (_j = 0, _len1 = params.length; _j < _len1; _j++) { p = params[_j]; if (paramStr !== "") { paramStr += ", "; } else { if ((prefix != null) && prefix !== "") { paramStr += "" + prefix + " " + paramStr; } paramStr; } if ("string" === typeof p.table.table) { paramStr += "" + p.text; } else { paramStr += "(" + p.text + ")"; } if (p.table.alias != null) { paramStr += " " + p.table.alias; } _ref2 = p.values; for (_k = 0, _len2 = _ref2.length; _k < _len2; _k++) { v = _ref2[_k]; ret.values.push(this._formatCustomValue(v)); } } ret.text += paramStr; return ret; }; AbstractTableBlock.prototype.buildParam = function(queryBuilder) { return this._buildParam(queryBuilder); }; return AbstractTableBlock; })(cls.Block); cls.UpdateTableBlock = (function(_super) { __extends(UpdateTableBlock, _super); function UpdateTableBlock() { _ref1 = UpdateTableBlock.__super__.constructor.apply(this, arguments); return _ref1; } UpdateTableBlock.prototype.table = function(table, alias) { if (alias == null) { alias = null; } return this._table(table, alias); }; return UpdateTableBlock; })(cls.AbstractTableBlock); cls.FromTableBlock = (function(_super) { __extends(FromTableBlock, _super); function FromTableBlock() { _ref2 = FromTableBlock.__super__.constructor.apply(this, arguments); return _ref2; } FromTableBlock.prototype.from = function(table, alias) { if (alias == null) { alias = null; } return this._table(table, alias); }; FromTableBlock.prototype.buildStr = function(queryBuilder) { var tables; if (0 >= this.tables.length) { throw new Error("from() needs to be called"); } tables = FromTableBlock.__super__.buildStr.call(this, queryBuilder); return "FROM " + tables; }; FromTableBlock.prototype.buildParam = function(queryBuilder) { if (0 >= this.tables.length) { throw new Error("from() needs to be called"); } return this._buildParam(queryBuilder, "FROM"); }; return FromTableBlock; })(cls.AbstractTableBlock); cls.IntoTableBlock = (function(_super) { __extends(IntoTableBlock, _super); function IntoTableBlock(options) { IntoTableBlock.__super__.constructor.call(this, options); this.table = null; } IntoTableBlock.prototype.into = function(table) { return this.table = this._sanitizeTable(table, false); }; IntoTableBlock.prototype.buildStr = function(queryBuilder) { if (!this.table) { throw new Error("into() needs to be called"); } return "INTO " + this.table; }; return IntoTableBlock; })(cls.Block); cls.GetFieldBlock = (function(_super) { __extends(GetFieldBlock, _super); function GetFieldBlock(options) { GetFieldBlock.__super__.constructor.call(this, options); this._fields = []; } GetFieldBlock.prototype.fields = function(_fields, options) { var alias, field, _results; if (options == null) { options = {}; } _results = []; for (field in _fields) { alias = _fields[field]; _results.push(this.field(field, alias, options)); } return _results; }; GetFieldBlock.prototype.field = function(field, alias, options) { if (alias == null) { alias = null; } if (options == null) { options = {}; } field = this._sanitizeField(field, options); if (alias) { alias = this._sanitizeFieldAlias(alias); } return this._fields.push({ name: field, alias: alias }); }; GetFieldBlock.prototype.buildStr = function(queryBuilder) { var field, fields, _i, _len, _ref3; fields = ""; _ref3 = this._fields; for (_i = 0, _len = _ref3.length; _i < _len; _i++) { field = _ref3[_i]; if ("" !== fields) { fields += ", "; } fields += field.name; if (field.alias) { fields += " AS " + field.alias; } } if ("" === fields) { return "*"; } else { return fields; } }; return GetFieldBlock; })(cls.Block); cls.AbstractSetFieldBlock = (function(_super) { __extends(AbstractSetFieldBlock, _super); function AbstractSetFieldBlock(options) { AbstractSetFieldBlock.__super__.constructor.call(this, options); this.fieldOptions = []; this.fields = []; this.values = []; } AbstractSetFieldBlock.prototype._set = function(field, value, options) { var index; if (options == null) { options = {}; } if (this.values.length > 1) { throw new Error("Cannot call set or setFields on multiple rows of fields."); } if (void 0 !== value) { value = this._sanitizeValue(value); } index = this.fields.indexOf(this._sanitizeField(field, options)); if (index !== -1) { this.values[0][index] = value; this.fieldOptions[0][index] = options; } else { this.fields.push(this._sanitizeField(field, options)); index = this.fields.length - 1; if (Array.isArray(this.values[0])) { this.values[0][index] = value; this.fieldOptions[0][index] = options; } else { this.values.push([value]); this.fieldOptions.push([options]); } } return this; }; AbstractSetFieldBlock.prototype._setFields = function(fields, options) { var field; if (options == null) { options = {}; } if (typeof fields !== 'object') { throw new Error("Expected an object but got " + typeof fields); } for (field in fields) { if (!__hasProp.call(fields, field)) continue; this._set(field, fields[field], options); } return this; }; AbstractSetFieldBlock.prototype._setFieldsRows = function(fieldsRows, options) { var field, i, index, value, _i, _ref3, _ref4; if (options == null) { options = {}; } if (!Array.isArray(fieldsRows)) { throw new Error("Expected an array of objects but got " + typeof fieldsRows); } this.fields = []; this.values = []; for (i = _i = 0, _ref3 = fieldsRows.length; 0 <= _ref3 ? _i < _ref3 : _i > _ref3; i = 0 <= _ref3 ? ++_i : --_i) { _ref4 = fieldsRows[i]; for (field in _ref4) { if (!__hasProp.call(_ref4, field)) continue; index = this.fields.indexOf(this._sanitizeField(field, options)); if (0 < i && -1 === index) { throw new Error('All fields in subsequent rows must match the fields in the first row'); } if (-1 === index) { this.fields.push(this._sanitizeField(field, options)); index = this.fields.length - 1; } value = this._sanitizeValue(fieldsRows[i][field]); if (Array.isArray(this.values[i])) { this.values[i][index] = value; this.fieldOptions[i][index] = options; } else { this.values[i] = [value]; this.fieldOptions[i] = [options]; } } } return this; }; AbstractSetFieldBlock.prototype.buildStr = function() { throw new Error('Not yet implemented'); }; AbstractSetFieldBlock.prototype.buildParam = function() { throw new Error('Not yet implemented'); }; return AbstractSetFieldBlock; })(cls.Block); cls.SetFieldBlock = (function(_super) { __extends(SetFieldBlock, _super); function SetFieldBlock() { _ref3 = SetFieldBlock.__super__.constructor.apply(this, arguments); return _ref3; } SetFieldBlock.prototype.set = function(field, value, options) { return this._set(field, value, options); }; SetFieldBlock.prototype.setFields = function(fields, options) { return this._setFields(fields, options); }; SetFieldBlock.prototype.buildStr = function(queryBuilder) { var field, fieldOptions, i, str, value, _i, _ref4; if (0 >= this.fields.length) { throw new Error("set() needs to be called"); } str = ""; for (i = _i = 0, _ref4 = this.fields.length; 0 <= _ref4 ? _i < _ref4 : _i > _ref4; i = 0 <= _ref4 ? ++_i : --_i) { field = this.fields[i]; if ("" !== str) { str += ", "; } value = this.values[0][i]; fieldOptions = this.fieldOptions[0][i]; if (typeof value === 'undefined') { str += field; } else { str += "" + field + " = " + (this._formatValue(value, fieldOptions)); } } return "SET " + str; }; SetFieldBlock.prototype.buildParam = function(queryBuilder) { var field, i, p, str, v, vals, value, _i, _j, _len, _ref4, _ref5; if (0 >= this.fields.length) { throw new Error("set() needs to be called"); } str = ""; vals = []; for (i = _i = 0, _ref4 = this.fields.length; 0 <= _ref4 ? _i < _ref4 : _i > _ref4; i = 0 <= _ref4 ? ++_i : --_i) { field = this.fields[i]; if ("" !== str) { str += ", "; } value = this.values[0][i]; if (typeof value === 'undefined') { str += field; } else { p = this._formatValueAsParam(value); if (p.text != null) { str += "" + field + " = (" + p.text + ")"; _ref5 = p.values; for (_j = 0, _len = _ref5.length; _j < _len; _j++) { v = _ref5[_j]; vals.push(v); } } else { str += "" + field + " = ?"; vals.push(p); } } } return { text: "SET " + str, values: vals }; }; return SetFieldBlock; })(cls.AbstractSetFieldBlock); cls.InsertFieldValueBlock = (function(_super) { __extends(InsertFieldValueBlock, _super); function InsertFieldValueBlock() { _ref4 = InsertFieldValueBlock.__super__.constructor.apply(this, arguments); return _ref4; } InsertFieldValueBlock.prototype.set = function(field, value, options) { if (options == null) { options = {}; } return this._set(field, value, options); }; InsertFieldValueBlock.prototype.setFields = function(fields, options) { return this._setFields(fields, options); }; InsertFieldValueBlock.prototype.setFieldsRows = function(fieldsRows, options) { return this._setFieldsRows(fieldsRows, options); }; InsertFieldValueBlock.prototype._buildVals = function() { var formattedValue, i, j, vals, _i, _j, _ref5, _ref6; vals = []; for (i = _i = 0, _ref5 = this.values.length; 0 <= _ref5 ? _i < _ref5 : _i > _ref5; i = 0 <= _ref5 ? ++_i : --_i) { for (j = _j = 0, _ref6 = this.values[i].length; 0 <= _ref6 ? _j < _ref6 : _j > _ref6; j = 0 <= _ref6 ? ++_j : --_j) { formattedValue = this._formatValue(this.values[i][j], this.fieldOptions[i][j]); if ('string' === typeof vals[i]) { vals[i] += ', ' + formattedValue; } else { vals[i] = '' + formattedValue; } } } return vals; }; InsertFieldValueBlock.prototype._buildValParams = function() { var i, j, p, params, str, v, vals, _i, _j, _k, _len, _ref5, _ref6, _ref7; vals = []; params = []; for (i = _i = 0, _ref5 = this.values.length; 0 <= _ref5 ? _i < _ref5 : _i > _ref5; i = 0 <= _ref5 ? ++_i : --_i) { for (j = _j = 0, _ref6 = this.values[i].length; 0 <= _ref6 ? _j < _ref6 : _j > _ref6; j = 0 <= _ref6 ? ++_j : --_j) { p = this._formatValueAsParam(this.values[i][j]); if (p.text != null) { str = p.text; _ref7 = p.values; for (_k = 0, _len = _ref7.length; _k < _len; _k++) { v = _ref7[_k]; params.push(v); } } else { str = '?'; params.push(p); } if ('string' === typeof vals[i]) { vals[i] += ", " + str; } else { vals[i] = "" + str; } } } return { vals: vals, params: params }; }; InsertFieldValueBlock.prototype.buildStr = function(queryBuilder) { if (0 >= this.fields.length) { throw new Error("set() needs to be called"); } return "(" + (this.fields.join(', ')) + ") VALUES (" + (this._buildVals().join('), (')) + ")"; }; InsertFieldValueBlock.prototype.buildParam = function(queryBuilder) { var i, params, str, vals, _i, _ref5, _ref6; if (0 >= this.fields.length) { throw new Error("set() needs to be called"); } str = ""; _ref5 = this._buildValParams(), vals = _ref5.vals, params = _ref5.params; for (i = _i = 0, _ref6 = this.fields.length; 0 <= _ref6 ? _i < _ref6 : _i > _ref6; i = 0 <= _ref6 ? ++_i : --_i) { if ("" !== str) { str += ", "; } str += this.fields[i]; } return { text: "(" + str + ") VALUES (" + (vals.join('), (')) + ")", values: params }; }; return InsertFieldValueBlock; })(cls.AbstractSetFieldBlock); cls.DistinctBlock = (function(_super) { __extends(DistinctBlock, _super); function DistinctBlock(options) { DistinctBlock.__super__.constructor.call(this, options); this.useDistinct = false; } DistinctBlock.prototype.distinct = function() { return this.useDistinct = true; }; DistinctBlock.prototype.buildStr = function(queryBuilder) { if (this.useDistinct) { return "DISTINCT"; } else { return ""; } }; return DistinctBlock; })(cls.Block); cls.GroupByBlock = (function(_super) { __extends(GroupByBlock, _super); function GroupByBlock(options) { GroupByBlock.__super__.constructor.call(this, options); this.groups = []; } GroupByBlock.prototype.group = function(field) { field = this._sanitizeField(field); return this.groups.push(field); }; GroupByBlock.prototype.buildStr = function(queryBuilder) { var f, groups, _i, _len, _ref5; groups = ""; if (0 < this.groups.length) { _ref5 = this.groups; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { f = _ref5[_i]; if ("" !== groups) { groups += ", "; } groups += f; } groups = "GROUP BY " + groups; } return groups; }; return GroupByBlock; })(cls.Block); cls.OffsetBlock = (function(_super) { __extends(OffsetBlock, _super); function OffsetBlock(options) { OffsetBlock.__super__.constructor.call(this, options); this.offsets = null; } OffsetBlock.prototype.offset = function(start) { start = this._sanitizeLimitOffset(start); return this.offsets = start; }; OffsetBlock.prototype.buildStr = function(queryBuilder) { if (this.offsets) { return "OFFSET " + this.offsets; } else { return ""; } }; return OffsetBlock; })(cls.Block); cls.WhereBlock = (function(_super) { __extends(WhereBlock, _super); function WhereBlock(options) { WhereBlock.__super__.constructor.call(this, options); this.wheres = []; } WhereBlock.prototype.where = function() { var c, condition, finalCondition, finalValues, idx, inValues, item, nextValue, t, values, _i, _j, _len, _ref5; condition = arguments[0], values = 2 <= arguments.length ? __slice.call(arguments, 1) : []; condition = this._sanitizeCondition(condition); finalCondition = ""; finalValues = []; if (condition instanceof cls.Expression) { t = condition.toParam(); finalCondition = t.text; finalValues = t.values; } else { for (idx = _i = 0, _ref5 = condition.length; 0 <= _ref5 ? _i < _ref5 : _i > _ref5; idx = 0 <= _ref5 ? ++_i : --_i) { c = condition.charAt(idx); if ('?' === c && 0 < values.length) { nextValue = values.shift(); if (Array.isArray(nextValue)) { inValues = []; for (_j = 0, _len = nextValue.length; _j < _len; _j++) { item = nextValue[_j]; inValues.push(this._sanitizeValue(item)); } finalValues = finalValues.concat(inValues); finalCondition += "(" + (((function() { var _k, _len1, _results; _results = []; for (_k = 0, _len1 = inValues.length; _k < _len1; _k++) { item = inValues[_k]; _results.push('?'); } return _results; })()).join(', ')) + ")"; } else { finalCondition += '?'; finalValues.push(this._sanitizeValue(nextValue)); } } else { finalCondition += c; } } } if ("" !== finalCondition) { return this.wheres.push({ text: finalCondition, values: finalValues }); } }; WhereBlock.prototype.buildStr = function(queryBuilder) { var c, idx, pIndex, where, whereStr, _i, _j, _len, _ref5, _ref6; if (0 >= this.wheres.length) { return ""; } whereStr = ""; _ref5 = this.wheres; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { where = _ref5[_i]; if ("" !== whereStr) { whereStr += ") AND ("; } if (0 < where.values.length) { pIndex = 0; for (idx = _j = 0, _ref6 = where.text.length; 0 <= _ref6 ? _j < _ref6 : _j > _ref6; idx = 0 <= _ref6 ? ++_j : --_j) { c = where.text.charAt(idx); if ('?' === c) { whereStr += this._formatValue(where.values[pIndex++]); } else { whereStr += c; } } } else { whereStr += where.text; } } return "WHERE (" + whereStr + ")"; }; WhereBlock.prototype.buildParam = function(queryBuilder) { var i, p, qv, ret, str, v, where, whereStr, _i, _j, _k, _len, _len1, _len2, _ref5, _ref6, _ref7; ret = { text: "", values: [] }; if (0 >= this.wheres.length) { return ret; } whereStr = ""; _ref5 = this.wheres; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { where = _ref5[_i]; if ("" !== whereStr) { whereStr += ") AND ("; } str = where.text.split('?'); i = 0; _ref6 = where.values; for (_j = 0, _len1 = _ref6.length; _j < _len1; _j++) { v = _ref6[_j]; p = this._formatValueAsParam(v); if (str[i] != null) { whereStr += "" + str[i]; } if ((p.text != null)) { whereStr += "(" + p.text + ")"; _ref7 = p.values; for (_k = 0, _len2 = _ref7.length; _k < _len2; _k++) { qv = _ref7[_k]; ret.values.push(qv); } } else { whereStr += "?"; ret.values.push(p); } i = i + 1; } if (str[i] != null) { whereStr += "" + str[i]; } } ret.text = "WHERE (" + whereStr + ")"; return ret; }; return WhereBlock; })(cls.Block); cls.OrderByBlock = (function(_super) { __extends(OrderByBlock, _super); function OrderByBlock(options) { OrderByBlock.__super__.constructor.call(this, options); this.orders = []; this._values = []; } OrderByBlock.prototype.order = function() { var asc, field, values; field = arguments[0], asc = arguments[1], values = 3 <= arguments.length ? __slice.call(arguments, 2) : []; if (asc == null) { asc = true; } field = this._sanitizeField(field); this._values = values; return this.orders.push({ field: field, dir: asc ? true : false }); }; OrderByBlock.prototype._buildStr = function(toParam) { var c, fstr, idx, o, orders, pIndex, _i, _j, _len, _ref5, _ref6; if (toParam == null) { toParam = false; } if (0 < this.orders.length) { pIndex = 0; orders = ""; _ref5 = this.orders; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { o = _ref5[_i]; if ("" !== orders) { orders += ", "; } fstr = ""; if (!toParam) { for (idx = _j = 0, _ref6 = o.field.length; 0 <= _ref6 ? _j < _ref6 : _j > _ref6; idx = 0 <= _ref6 ? ++_j : --_j) { c = o.field.charAt(idx); if ('?' === c) { fstr += this._formatValue(this._values[pIndex++]); } else { fstr += c; } } } else { fstr = o.field; } orders += "" + fstr + " " + (o.dir ? 'ASC' : 'DESC'); } return "ORDER BY " + orders; } else { return ""; } }; OrderByBlock.prototype.buildStr = function(queryBuilder) { return this._buildStr(); }; OrderByBlock.prototype.buildParam = function(queryBuilder) { var _this = this; return { text: this._buildStr(true), values: this._values.map(function(v) { return _this._formatValueAsParam(v); }) }; }; return OrderByBlock; })(cls.Block); cls.LimitBlock = (function(_super) { __extends(LimitBlock, _super); function LimitBlock(options) { LimitBlock.__super__.constructor.call(this, options); this.limits = null; } LimitBlock.prototype.limit = function(max) { max = this._sanitizeLimitOffset(max); return this.limits = max; }; LimitBlock.prototype.buildStr = function(queryBuilder) { if (this.limits) { return "LIMIT " + this.limits; } else { return ""; } }; return LimitBlock; })(cls.Block); cls.JoinBlock = (function(_super) { __extends(JoinBlock, _super); function JoinBlock(options) { JoinBlock.__super__.constructor.call(this, options); this.joins = []; } JoinBlock.prototype.join = function(table, alias, condition, type) { if (alias == null) { alias = null; } if (condition == null) { condition = null; } if (type == null) { type = 'INNER'; } table = this._sanitizeTable(table, true); if (alias) { alias = this._sanitizeTableAlias(alias); } if (condition) { condition = this._sanitizeCondition(condition); } this.joins.push({ type: type, table: table, alias: alias, condition: condition }); return this; }; JoinBlock.prototype.left_join = function(table, alias, condition) { if (alias == null) { alias = null; } if (condition == null) { condition = null; } return this.join(table, alias, condition, 'LEFT'); }; JoinBlock.prototype.right_join = function(table, alias, condition) { if (alias == null) { alias = null; } if (condition == null) { condition = null; } return this.join(table, alias, condition, 'RIGHT'); }; JoinBlock.prototype.outer_join = function(table, alias, condition) { if (alias == null) { alias = null; } if (condition == null) { condition = null; } return this.join(table, alias, condition, 'OUTER'); }; JoinBlock.prototype.left_outer_join = function(table, alias, condition) { if (alias == null) { alias = null; } if (condition == null) { condition = null; } return this.join(table, alias, condition, 'LEFT OUTER'); }; JoinBlock.prototype.full_join = function(table, alias, condition) { if (alias == null) { alias = null; } if (condition == null) { condition = null; } return this.join(table, alias, condition, 'FULL'); }; JoinBlock.prototype.buildStr = function(queryBuilder) { var j, joins, _i, _len, _ref5; joins = ""; _ref5 = this.joins || []; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { j = _ref5[_i]; if (joins !== "") { joins += " "; } joins += "" + j.type + " JOIN "; if ("string" === typeof j.table) { joins += j.table; } else { joins += "(" + j.table + ")"; } if (j.alias) { joins += " " + j.alias; } if (j.condition) { joins += " ON (" + j.condition + ")"; } } return joins; }; JoinBlock.prototype.buildParam = function(queryBuilder) { var blk, cp, joinStr, p, params, ret, v, _i, _j, _k, _len, _len1, _len2, _ref5, _ref6; ret = { text: "", values: [] }; params = []; joinStr = ""; if (0 >= this.joins.length) { return ret; } _ref5 = this.joins; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { blk = _ref5[_i]; if ("string" === typeof blk.table) { p = { "text": "" + blk.table, "values": [] }; } else if (blk.table instanceof cls.QueryBuilder) { blk.table.updateOptions({ "nestedBuilder": true }); p = blk.table.toParam(); } else { blk.updateOptions({ "nestedBuilder": true }); p = blk.buildParam(queryBuilder); } if (blk.condition instanceof cls.Expression) { cp = blk.condition.toParam(); p.condition = cp.text; p.values = p.values.concat(cp.values); } else { p.condition = blk.condition; } p.join = blk; params.push(p); } for (_j = 0, _len1 = params.length; _j < _len1; _j++) { p = params[_j]; if (joinStr !== "") { joinStr += " "; } joinStr += "" + p.join.type + " JOIN "; if ("string" === typeof p.join.table) { joinStr += p.text; } else { joinStr += "(" + p.text + ")"; } if (p.join.alias) { joinStr += " " + p.join.alias; } if (p.condition) { joinStr += " ON (" + p.condition + ")"; } _ref6 = p.values; for (_k = 0, _len2 = _ref6.length; _k < _len2; _k++) { v = _ref6[_k]; ret.values.push(this._formatCustomValue(v)); } } ret.text += joinStr; return ret; }; return JoinBlock; })(cls.Block); cls.UnionBlock = (function(_super) { __extends(UnionBlock, _super); function UnionBlock(options) { UnionBlock.__super__.constructor.call(this, options); this.unions = []; } UnionBlock.prototype.union = function(table, type) { if (type == null) { type = 'UNION'; } table = this._sanitizeTable(table, true); this.unions.push({ type: type, table: table }); return this; }; UnionBlock.prototype.union_all = function(table) { return this.union(table, 'UNION ALL'); }; UnionBlock.prototype.buildStr = function(queryBuilder) { var j, unionStr, _i, _len, _ref5; unionStr = ""; _ref5 = this.unions || []; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { j = _ref5[_i]; if (unionStr !== "") { unionStr += " "; } unionStr += "" + j.type + " "; if ("string" === typeof j.table) { unionStr += j.table; } else { unionStr += "(" + j.table + ")"; } } return unionStr; }; UnionBlock.prototype.buildParam = function(queryBuilder) { var blk, p, params, ret, unionStr, v, _i, _j, _k, _len, _len1, _len2, _ref5, _ref6; ret = { text: "", values: [] }; params = []; unionStr = ""; if (0 >= this.unions.length) { return ret; } _ref5 = this.unions || []; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { blk = _ref5[_i]; if ("string" === typeof blk.table) { p = { "text": "" + blk.table, "values": [] }; } else if (blk.table instanceof cls.QueryBuilder) { blk.table.updateOptions({ "nestedBuilder": true }); p = blk.table.toParam(); } else { blk.updateOptions({ "nestedBuilder": true }); p = blk.buildParam(queryBuilder); } p.type = blk.type; params.push(p); } for (_j = 0, _len1 = params.length; _j < _len1; _j++) { p = params[_j]; if (unionStr !== "") { unionStr += " "; } unionStr += "" + p.type + " (" + p.text + ")"; _ref6 = p.values; for (_k = 0, _len2 = _ref6.length; _k < _len2; _k++) { v = _ref6[_k]; ret.values.push(this._formatCustomValue(v)); } } ret.text += unionStr; return ret; }; return UnionBlock; })(cls.Block); cls.QueryBuilder = (function(_super) { __extends(QueryBuilder, _super); function QueryBuilder(options, blocks) { var block, methodBody, methodName, _fn, _i, _len, _ref5, _ref6, _this = this; QueryBuilder.__super__.constructor.call(this, options); this.blocks = blocks || []; _ref5 = this.blocks; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { block = _ref5[_i]; _ref6 = block.exposedMethods(); _fn = function(block, name, body) { return _this[name] = function() { body.apply(block, arguments); return _this; }; }; for (methodName in _ref6) { methodBody = _ref6[methodName]; if (this[methodName] != null) { throw new Error("" + (this._getObjectClassName(this)) + " already has a builder method called: " + methodName); } _fn(block, methodName, methodBody); } } } QueryBuilder.prototype.registerValueHandler = function(type, handler) { var block, _i, _len, _ref5; _ref5 = this.blocks; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { block = _ref5[_i]; block.registerValueHandler(type, handler); } QueryBuilder.__super__.registerValueHandler.call(this, type, handler); return this; }; QueryBuilder.prototype.updateOptions = function(options) { var block, _i, _len, _ref5, _results; this.options = _extend({}, this.options, options); _ref5 = this.blocks; _results = []; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { block = _ref5[_i]; _results.push(block.options = _extend({}, block.options, options)); } return _results; }; QueryBuilder.prototype.toString = function() { var block; return ((function() { var _i, _len, _ref5, _results; _ref5 = this.blocks; _results = []; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { block = _ref5[_i]; _results.push(block.buildStr(this)); } return _results; }).call(this)).filter(function(v) { return 0 < v.length; }).join(this.options.separator); }; QueryBuilder.prototype.toParam = function(options) { var block, blocks, i, old, result, _ref5; if (options == null) { options = void 0; } old = this.options; if (options != null) { this.options = _extend({}, this.options, options); } result = { text: '', values: [] }; blocks = (function() { var _i, _len, _ref5, _results; _ref5 = this.blocks; _results = []; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { block = _ref5[_i]; _results.push(block.buildParam(this)); } return _results; }).call(this); result.text = ((function() { var _i, _len, _results; _results = []; for (_i = 0, _len = blocks.length; _i < _len; _i++) { block = blocks[_i]; _results.push(block.text); } return _results; })()).filter(function(v) { return 0 < v.length; }).join(this.options.separator); result.values = (_ref5 = []).concat.apply(_ref5, (function() { var _i, _len, _results; _results = []; for (_i = 0, _len = blocks.length; _i < _len; _i++) { block = blocks[_i]; _results.push(block.values); } return _results; })()); if (this.options.nestedBuilder == null) { if (this.options.numberedParameters || ((options != null ? options.numberedParametersStartAt : void 0) != null)) { i = 1; if (this.options.numberedParametersStartAt != null) { i = this.options.numberedParametersStartAt; } result.text = result.text.replace(/\?/g, function() { return "$" + (i++); }); } } this.options = old; return result; }; QueryBuilder.prototype.clone = function() { var block; return new this.constructor(this.options, (function() { var _i, _len, _ref5, _results; _ref5 = this.blocks; _results = []; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { block = _ref5[_i]; _results.push(block.clone()); } return _results; }).call(this)); }; QueryBuilder.prototype.isNestable = function() { return false; }; return QueryBuilder; })(cls.BaseBuilder); cls.Select = (function(_super) { __extends(Select, _super); function Select(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [ new cls.StringBlock(options, 'SELECT'), new cls.DistinctBlock(options), new cls.GetFieldBlock(options), new cls.FromTableBlock(_extend({}, options, { allowNested: true })), new cls.JoinBlock(_extend({}, options, { allowNested: true })), new cls.WhereBlock(options), new cls.GroupByBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options), new cls.OffsetBlock(options), new cls.UnionBlock(_extend({}, options, { allowNested: true })) ]); Select.__super__.constructor.call(this, options, blocks); } Select.prototype.isNestable = function() { return true; }; return Select; })(cls.QueryBuilder); cls.Update = (function(_super) { __extends(Update, _super); function Update(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [new cls.StringBlock(options, 'UPDATE'), new cls.UpdateTableBlock(options), new cls.SetFieldBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options)]); Update.__super__.constructor.call(this, options, blocks); } return Update; })(cls.QueryBuilder); cls.Delete = (function(_super) { __extends(Delete, _super); function Delete(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [ new cls.StringBlock(options, 'DELETE'), new cls.FromTableBlock(_extend({}, options, { singleTable: true })), new cls.JoinBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options) ]); Delete.__super__.constructor.call(this, options, blocks); } return Delete; })(cls.QueryBuilder); cls.Insert = (function(_super) { __extends(Insert, _super); function Insert(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [new cls.StringBlock(options, 'INSERT'), new cls.IntoTableBlock(options), new cls.InsertFieldValueBlock(options)]); Insert.__super__.constructor.call(this, options, blocks); } return Insert; })(cls.QueryBuilder); squel = { VERSION: '3.9.0', expr: function() { return new cls.Expression; }, select: function(options, blocks) { return new cls.Select(options, blocks); }, update: function(options, blocks) { return new cls.Update(options, blocks); }, insert: function(options, blocks) { return new cls.Insert(options, blocks); }, "delete": function(options, blocks) { return new cls.Delete(options, blocks); }, registerValueHandler: cls.registerValueHandler }; squel.remove = squel["delete"]; squel.cls = cls; if (typeof define !== "undefined" && define !== null ? define.amd : void 0) { define(function() { return squel; }); } else if (typeof module !== "undefined" && module !== null ? module.exports : void 0) { module.exports = squel; } else { if (typeof window !== "undefined" && window !== null) { window.squel = squel; } } squel.flavours = {}; squel.useFlavour = function(flavour) { if (squel.flavours[flavour] instanceof Function) { squel.flavours[flavour].call(null, squel); } else { throw new Error("Flavour not available: " + flavour); } return squel; }; /* Copyright (c) Ramesh Nair (hiddentao.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ squel.flavours['postgres'] = function() { cls = squel.cls; cls.DefaultQueryBuilderOptions.numberedParameters = true; cls.DefaultQueryBuilderOptions.numberedParametersStartAt = 1; cls.ReturningBlock = (function(_super) { __extends(ReturningBlock, _super); function ReturningBlock(options) { ReturningBlock.__super__.constructor.call(this, options); this._str = null; } ReturningBlock.prototype.returning = function(ret) { return this._str = this._sanitizeField(ret); }; ReturningBlock.prototype.buildStr = function() { if (this._str) { return "RETURNING " + this._str; } else { return ""; } }; return ReturningBlock; })(cls.Block); cls.Insert = (function(_super) { __extends(Insert, _super); function Insert(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [new cls.StringBlock(options, 'INSERT'), new cls.IntoTableBlock(options), new cls.InsertFieldValueBlock(options), new cls.ReturningBlock(options)]); Insert.__super__.constructor.call(this, options, blocks); } return Insert; })(cls.QueryBuilder); cls.Update = (function(_super) { __extends(Update, _super); function Update(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [new cls.StringBlock(options, 'UPDATE'), new cls.UpdateTableBlock(options), new cls.SetFieldBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options), new cls.ReturningBlock(options)]); Update.__super__.constructor.call(this, options, blocks); } return Update; })(cls.QueryBuilder); return cls.Delete = (function(_super) { __extends(Delete, _super); function Delete(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [ new cls.StringBlock(options, 'DELETE'), new cls.FromTableBlock(_extend({}, options, { singleTable: true })), new cls.JoinBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options), new cls.ReturningBlock(options) ]); Delete.__super__.constructor.call(this, options, blocks); } return Delete; })(cls.QueryBuilder); }; /* Copyright (c) Ramesh Nair (hiddentao.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ squel.flavours['mysql'] = function() { var _ref5; cls = squel.cls; cls.MysqlOnDuplicateKeyUpdateBlock = (function(_super) { __extends(MysqlOnDuplicateKeyUpdateBlock, _super); function MysqlOnDuplicateKeyUpdateBlock() { _ref5 = MysqlOnDuplicateKeyUpdateBlock.__super__.constructor.apply(this, arguments); return _ref5; } MysqlOnDuplicateKeyUpdateBlock.prototype.onDupUpdate = function(field, value, options) { return this._set(field, value, options); }; MysqlOnDuplicateKeyUpdateBlock.prototype.buildStr = function() { var field, fieldOptions, i, str, value, _i, _ref6; str = ""; for (i = _i = 0, _ref6 = this.fields.length; 0 <= _ref6 ? _i < _ref6 : _i > _ref6; i = 0 <= _ref6 ? ++_i : --_i) { field = this.fields[i]; if ("" !== str) { str += ", "; } value = this.values[0][i]; fieldOptions = this.fieldOptions[0][i]; if (typeof value === 'undefined') { str += field; } else { str += "" + field + " = " + (this._formatValue(value, fieldOptions)); } } if (str === "") { return ""; } else { return "ON DUPLICATE KEY UPDATE " + str; } }; MysqlOnDuplicateKeyUpdateBlock.prototype.buildParam = function(queryBuilder) { var field, i, str, vals, value, _i, _ref6; str = ""; vals = []; for (i = _i = 0, _ref6 = this.fields.length; 0 <= _ref6 ? _i < _ref6 : _i > _ref6; i = 0 <= _ref6 ? ++_i : --_i) { field = this.fields[i]; if ("" !== str) { str += ", "; } value = this.values[0][i]; if (typeof value === 'undefined') { str += field; } else { str += "" + field + " = ?"; vals.push(this._formatValueAsParam(value)); } } return { text: str === "" ? "" : "ON DUPLICATE KEY UPDATE " + str, values: vals }; }; return MysqlOnDuplicateKeyUpdateBlock; })(cls.AbstractSetFieldBlock); return cls.Insert = (function(_super) { __extends(Insert, _super); function Insert(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [new cls.StringBlock(options, 'INSERT'), new cls.IntoTableBlock(options), new cls.InsertFieldValueBlock(options), new cls.MysqlOnDuplicateKeyUpdateBlock(options)]); Insert.__super__.constructor.call(this, options, blocks); } return Insert; })(cls.QueryBuilder); }; /* Copyright (c) Ramesh Nair (hiddentao.com) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ _extend = function() { var dst, k, sources, src, v, _i, _len; dst = arguments[0], sources = 2 <= arguments.length ? __slice.call(arguments, 1) : []; if (sources) { for (_i = 0, _len = sources.length; _i < _len; _i++) { src = sources[_i]; if (src) { for (k in src) { if (!__hasProp.call(src, k)) continue; v = src[k]; dst[k] = v; } } } } return dst; }; squel.flavours['mssql'] = function() { cls = squel.cls; cls.DefaultQueryBuilderOptions.replaceSingleQuotes = true; cls.DefaultQueryBuilderOptions.autoQuoteAliasNames = false; squel.registerValueHandler(Date, function(date) { return "" + (date.getUTCFullYear()) + "-" + (date.getUTCMonth() + 1) + "-" + (date.getUTCDate()) + " " + (date.getUTCHours()) + ":" + (date.getUTCMinutes()) + ":" + (date.getUTCSeconds()); }); cls.MssqlLimitOffsetTopBlock = (function(_super) { var LimitBlock, OffsetBlock, ParentBlock, TopBlock, _limit, _ref5, _ref6, _ref7; __extends(MssqlLimitOffsetTopBlock, _super); function MssqlLimitOffsetTopBlock(options) { MssqlLimitOffsetTopBlock.__super__.constructor.call(this, options); this.limits = null; this.offsets = null; } _limit = function(max) { max = this._sanitizeLimitOffset(max); return this._parent.limits = max; }; ParentBlock = (function(_super1) { __extends(ParentBlock, _super1); function ParentBlock(parent) { ParentBlock.__super__.constructor.call(this, parent.options); this._parent = parent; } return ParentBlock; })(cls.Block); LimitBlock = (function(_super1) { __extends(LimitBlock, _super1); function LimitBlock() { _ref5 = LimitBlock.__super__.constructor.apply(this, arguments); return _ref5; } LimitBlock.prototype.limit = _limit; LimitBlock.prototype.buildStr = function(queryBuilder) { if (this._parent.limits && this._parent.offsets) { return "FETCH NEXT " + this._parent.limits + " ROWS ONLY"; } else { return ""; } }; return LimitBlock; })(ParentBlock); TopBlock = (function(_super1) { __extends(TopBlock, _super1); function TopBlock() { _ref6 = TopBlock.__super__.constructor.apply(this, arguments); return _ref6; } TopBlock.prototype.top = _limit; TopBlock.prototype.buildStr = function(queryBuilder) { if (this._parent.limits && !this._parent.offsets) { return "TOP (" + this._parent.limits + ")"; } else { return ""; } }; return TopBlock; })(ParentBlock); OffsetBlock = (function(_super1) { __extends(OffsetBlock, _super1); function OffsetBlock() { this.offset = __bind(this.offset, this); _ref7 = OffsetBlock.__super__.constructor.apply(this, arguments); return _ref7; } OffsetBlock.prototype.offset = function(start) { start = this._sanitizeLimitOffset(start); return this._parent.offsets = start; }; OffsetBlock.prototype.buildStr = function(queryBuilder) { if (this._parent.offsets) { return "OFFSET " + this._parent.offsets + " ROWS"; } else { return ""; } }; return OffsetBlock; })(ParentBlock); MssqlLimitOffsetTopBlock.prototype.LIMIT = function(options) { this.constructor(options); return new LimitBlock(this); }; MssqlLimitOffsetTopBlock.prototype.TOP = function(options) { this.constructor(options); return new TopBlock(this); }; MssqlLimitOffsetTopBlock.prototype.OFFSET = function(options) { this.constructor(options); return new OffsetBlock(this); }; return MssqlLimitOffsetTopBlock; }).call(this, cls.Block); cls.MssqlUpdateTopBlock = (function(_super) { var _limit; __extends(MssqlUpdateTopBlock, _super); function MssqlUpdateTopBlock(options) { MssqlUpdateTopBlock.__super__.constructor.call(this, options); this.limits = null; } _limit = function(max) { max = this._sanitizeLimitOffset(max); return this.limits = max; }; MssqlUpdateTopBlock.prototype.limit = _limit; MssqlUpdateTopBlock.prototype.top = _limit; MssqlUpdateTopBlock.prototype.buildStr = function(queryBuilder) { if (this.limits) { return "TOP (" + this.limits + ")"; } else { return ""; } }; return MssqlUpdateTopBlock; })(cls.Block); cls.MssqlInsertFieldValueBlock = (function(_super) { __extends(MssqlInsertFieldValueBlock, _super); function MssqlInsertFieldValueBlock(options) { MssqlInsertFieldValueBlock.__super__.constructor.call(this, options); this.outputs = []; } MssqlInsertFieldValueBlock.prototype.output = function(fields) { var f, _i, _len, _results; if ('string' === typeof fields) { return this.outputs.push("INSERTED." + (this._sanitizeField(fields))); } else { _results = []; for (_i = 0, _len = fields.length; _i < _len; _i++) { f = fields[_i]; _results.push(this.outputs.push("INSERTED." + (this._sanitizeField(f)))); } return _results; } }; MssqlInsertFieldValueBlock.prototype.buildStr = function(queryBuilder) { if (0 >= this.fields.length) { throw new Error("set() needs to be called"); } return "(" + (this.fields.join(', ')) + ") " + (this.outputs.length !== 0 ? "OUTPUT " + (this.outputs.join(', ')) + " " : '') + "VALUES (" + (this._buildVals().join('), (')) + ")"; }; MssqlInsertFieldValueBlock.prototype.buildParam = function(queryBuilder) { var i, params, str, vals, _i, _ref5, _ref6; if (0 >= this.fields.length) { throw new Error("set() needs to be called"); } str = ""; _ref5 = this._buildValParams(), vals = _ref5.vals, params = _ref5.params; for (i = _i = 0, _ref6 = this.fields.length; 0 <= _ref6 ? _i < _ref6 : _i > _ref6; i = 0 <= _ref6 ? ++_i : --_i) { if ("" !== str) { str += ", "; } str += this.fields[i]; } return { text: "(" + str + ") " + (this.outputs.length !== 0 ? "OUTPUT " + (this.outputs.join(', ')) + " " : '') + "VALUES (" + (vals.join('), (')) + ")", values: params }; }; return MssqlInsertFieldValueBlock; })(cls.InsertFieldValueBlock); cls.MssqlUpdateOutputBlock = (function(_super) { __extends(MssqlUpdateOutputBlock, _super); function MssqlUpdateOutputBlock(options) { MssqlUpdateOutputBlock.__super__.constructor.call(this, options); this._outputs = []; } MssqlUpdateOutputBlock.prototype.outputs = function(_outputs) { var alias, output, _results; _results = []; for (output in _outputs) { alias = _outputs[output]; _results.push(this.output(output, alias)); } return _results; }; MssqlUpdateOutputBlock.prototype.output = function(output, alias) { if (alias == null) { alias = null; } output = this._sanitizeField(output); if (alias) { alias = this._sanitizeFieldAlias(alias); } return this._outputs.push({ name: "INSERTED." + output, alias: alias }); }; MssqlUpdateOutputBlock.prototype.buildStr = function(queryBuilder) { var output, outputs, _i, _len, _ref5; outputs = ""; if (this._outputs.length > 0) { _ref5 = this._outputs; for (_i = 0, _len = _ref5.length; _i < _len; _i++) { output = _ref5[_i]; if ("" !== outputs) { outputs += ", "; } outputs += output.name; if (output.alias) { outputs += " AS " + output.alias; } } outputs = "OUTPUT " + outputs; } return outputs; }; return MssqlUpdateOutputBlock; })(cls.Block); cls.Select = (function(_super) { __extends(Select, _super); function Select(options, blocks) { var limitOffsetTopBlock; if (blocks == null) { blocks = null; } limitOffsetTopBlock = new cls.MssqlLimitOffsetTopBlock(options); blocks || (blocks = [ new cls.StringBlock(options, 'SELECT'), new cls.DistinctBlock(options), limitOffsetTopBlock.TOP(options), new cls.GetFieldBlock(options), new cls.FromTableBlock(_extend({}, options, { allowNested: true })), new cls.JoinBlock(_extend({}, options, { allowNested: true })), new cls.WhereBlock(options), new cls.GroupByBlock(options), new cls.OrderByBlock(options), limitOffsetTopBlock.OFFSET(options), limitOffsetTopBlock.LIMIT(options) ]); Select.__super__.constructor.call(this, options, blocks); } Select.prototype.isNestable = function() { return true; }; return Select; })(cls.QueryBuilder); cls.Update = (function(_super) { __extends(Update, _super); function Update(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [new cls.StringBlock(options, 'UPDATE'), new cls.MssqlUpdateTopBlock(options), new cls.UpdateTableBlock(options), new cls.SetFieldBlock(options), new cls.MssqlUpdateOutputBlock(options), new cls.WhereBlock(options)]); Update.__super__.constructor.call(this, options, blocks); } return Update; })(cls.QueryBuilder); cls.Delete = (function(_super) { __extends(Delete, _super); function Delete(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [ new cls.StringBlock(options, 'DELETE'), new cls.FromTableBlock(_extend({}, options, { singleTable: true })), new cls.JoinBlock(options), new cls.WhereBlock(options), new cls.OrderByBlock(options), new cls.LimitBlock(options) ]); Delete.__super__.constructor.call(this, options, blocks); } return Delete; })(cls.QueryBuilder); return cls.Insert = (function(_super) { __extends(Insert, _super); function Insert(options, blocks) { if (blocks == null) { blocks = null; } blocks || (blocks = [new cls.StringBlock(options, 'INSERT'), new cls.IntoTableBlock(options), new cls.MssqlInsertFieldValueBlock(options)]); Insert.__super__.constructor.call(this, options, blocks); } return Insert; })(cls.QueryBuilder); }; }).call(this);
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global.PopperUtils = factory()); }(this, (function () { 'use strict'; /** * Get CSS computed property of the given element * @method * @memberof Popper.Utils * @argument {Eement} element * @argument {String} property */ function getStyleComputedProperty(element, property) { if (element.nodeType !== 1) { return []; } // NOTE: 1 DOM access here const css = window.getComputedStyle(element, null); return property ? css[property] : css; } /** * Returns the parentNode or the host of the element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} parent */ function getParentNode(element) { if (element.nodeName === 'HTML') { return element; } return element.parentNode || element.host; } /** * Returns the scrolling parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} scroll parent */ function getScrollParent(element) { // Return body, `getScroll` will take care to get the correct `scrollTop` from it if (!element || ['HTML', 'BODY', '#document'].indexOf(element.nodeName) !== -1) { return window.document.body; } // Firefox want us to check `-x` and `-y` variations as well const { overflow, overflowX, overflowY } = getStyleComputedProperty(element); if (/(auto|scroll)/.test(overflow + overflowY + overflowX)) { return element; } return getScrollParent(getParentNode(element)); } function isOffsetContainer(element) { return element.nodeName === 'HTML' || element.firstElementChild.offsetParent === element; } /** * Finds the root node (document, shadowDOM root) of the given element * @method * @memberof Popper.Utils * @argument {Element} node * @returns {Element} root node */ function getRoot(node) { if (node.parentNode !== null) { return getRoot(node.parentNode); } return node; } /** * Returns the offset parent of the given element * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Element} offset parent */ function getOffsetParent(element) { // NOTE: 1 DOM access here const offsetParent = element && element.offsetParent; const nodeName = offsetParent && offsetParent.nodeName; if (!nodeName || nodeName === 'BODY' || nodeName === 'HTML') { return window.document.documentElement; } return offsetParent; } /** * Finds the offset parent common to the two provided nodes * @method * @memberof Popper.Utils * @argument {Element} element1 * @argument {Element} element2 * @returns {Element} common offset parent */ function findCommonOffsetParent(element1, element2) { // This check is needed to avoid errors in case one of the elements isn't defined for any reason if (!element1 || !element1.nodeType || !element2 || !element2.nodeType) { return window.document.documentElement; } // Here we make sure to give as "start" the element that comes first in the DOM const order = element1.compareDocumentPosition(element2) & Node.DOCUMENT_POSITION_FOLLOWING; const start = order ? element1 : element2; const end = order ? element2 : element1; // Get common ancestor container const range = document.createRange(); range.setStart(start, 0); range.setEnd(end, 0); const { commonAncestorContainer } = range; // Both nodes are inside #document if (element1 !== commonAncestorContainer && element2 !== commonAncestorContainer) { if (isOffsetContainer(commonAncestorContainer)) { return commonAncestorContainer; } return getOffsetParent(commonAncestorContainer); } // one of the nodes is inside shadowDOM, find which one const element1root = getRoot(element1); if (element1root.host) { return findCommonOffsetParent(element1root.host, element2); } else { return findCommonOffsetParent(element1, getRoot(element2).host); } } /** * Gets the scroll value of the given element in the given side (top and left) * @method * @memberof Popper.Utils * @argument {Element} element * @argument {String} side `top` or `left` * @returns {Number} amount of scrolled pixels */ function getScroll(element, side = 'top') { const upperSide = side === 'top' ? 'scrollTop' : 'scrollLeft'; const nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { const html = window.document.documentElement; const scrollingElement = window.document.scrollingElement || html; return scrollingElement[upperSide]; } return element[upperSide]; } /* * Sum or subtract the element scroll values (left and top) from a given rect object * @method * @memberof Popper.Utils * @param {Object} rect - Rect object you want to change * @param {HTMLElement} element - The element from the function reads the scroll values * @param {Boolean} subtract - set to true if you want to subtract the scroll values * @return {Object} rect - The modifier rect object */ function includeScroll(rect, element, subtract = false) { const scrollTop = getScroll(element, 'top'); const scrollLeft = getScroll(element, 'left'); const modifier = subtract ? -1 : 1; rect.top += scrollTop * modifier; rect.bottom += scrollTop * modifier; rect.left += scrollLeft * modifier; rect.right += scrollLeft * modifier; return rect; } /* * Helper to detect borders of a given element * @method * @memberof Popper.Utils * @param {CSSStyleDeclaration} styles - result of `getStyleComputedProperty` on the given element * @param {String} axis - `x` or `y` * @return {Number} borders - the borders size of the given axis */ function getBordersSize(styles, axis) { const sideA = axis === 'x' ? 'Left' : 'Top'; const sideB = sideA === 'Left' ? 'Right' : 'Bottom'; return +styles[`border${sideA}Width`].split('px')[0] + +styles[`border${sideB}Width`].split('px')[0]; } function getWindowSizes() { const body = window.document.body; const html = window.document.documentElement; return { height: Math.max(body.scrollHeight, body.offsetHeight, html.clientHeight, html.scrollHeight, html.offsetHeight), width: Math.max(body.scrollWidth, body.offsetWidth, html.clientWidth, html.scrollWidth, html.offsetWidth) }; } 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; }; /** * Given element offsets, generate an output similar to getBoundingClientRect * @method * @memberof Popper.Utils * @argument {Object} offsets * @returns {Object} ClientRect like output */ function getClientRect(offsets) { return _extends({}, offsets, { right: offsets.left + offsets.width, bottom: offsets.top + offsets.height }); } /** * Tells if you are running Internet Explorer 10 * @returns {Boolean} isIE10 */ var runIsIE10 = function () { return navigator.appVersion.indexOf('MSIE 10') !== -1; }; const isIE10$1 = runIsIE10(); /** * Get bounding client rect of given element * @method * @memberof Popper.Utils * @param {HTMLElement} element * @return {Object} client rect */ function getBoundingClientRect(element) { let rect = {}; // IE10 10 FIX: Please, don't ask, the element isn't // considered in DOM in some circumstances... // This isn't reproducible in IE10 compatibility mode of IE11 if (isIE10$1) { try { rect = element.getBoundingClientRect(); } catch (err) {} const scrollTop = getScroll(element, 'top'); const scrollLeft = getScroll(element, 'left'); rect.top += scrollTop; rect.left += scrollLeft; } else { rect = element.getBoundingClientRect(); } const result = { left: rect.left, top: rect.top, width: rect.right - rect.left, height: rect.bottom - rect.top }; // subtract scrollbar size from sizes const sizes = element.nodeName === 'HTML' ? getWindowSizes() : {}; const width = sizes.width || element.clientWidth || result.right - result.left; const height = sizes.height || element.clientHeight || result.bottom - result.top; let horizScrollbar = element.offsetWidth - width; let vertScrollbar = element.offsetHeight - height; // if an hypothetical scrollbar is detected, we must be sure it's not a `border` // we make this check conditional for performance reasons if (horizScrollbar || vertScrollbar) { const styles = getStyleComputedProperty(element); horizScrollbar -= getBordersSize(styles, 'x'); vertScrollbar -= getBordersSize(styles, 'y'); result.width -= horizScrollbar; result.height -= vertScrollbar; } return getClientRect(result); } const isIE10 = runIsIE10(); function getOffsetRectRelativeToArbitraryNode(children, parent) { const isHTML = parent.nodeName === 'HTML'; const childrenRect = getBoundingClientRect(children); const parentRect = getBoundingClientRect(parent); const scrollParent = getScrollParent(children); let offsets = getClientRect({ top: childrenRect.top - parentRect.top, left: childrenRect.left - parentRect.left, width: childrenRect.width, height: childrenRect.height }); // Subtract margins of documentElement in case it's being used as parent // we do this only on HTML because it's the only element that behaves // differently when margins are applied to it. The margins are included in // the box of the documentElement, in the other cases not. if (isHTML || parent.nodeName === 'BODY') { const styles = getStyleComputedProperty(parent); const borderTopWidth = isIE10 && isHTML ? 0 : +styles.borderTopWidth.split('px')[0]; const borderLeftWidth = isIE10 && isHTML ? 0 : +styles.borderLeftWidth.split('px')[0]; const marginTop = isIE10 && isHTML ? 0 : +styles.marginTop.split('px')[0]; const marginLeft = isIE10 && isHTML ? 0 : +styles.marginLeft.split('px')[0]; offsets.top -= borderTopWidth - marginTop; offsets.bottom -= borderTopWidth - marginTop; offsets.left -= borderLeftWidth - marginLeft; offsets.right -= borderLeftWidth - marginLeft; // Attach marginTop and marginLeft because in some circumstances we may need them offsets.marginTop = marginTop; offsets.marginLeft = marginLeft; } if (parent.contains(scrollParent) && (isIE10 || scrollParent.nodeName !== 'BODY')) { offsets = includeScroll(offsets, parent); } return offsets; } function getViewportOffsetRectRelativeToArtbitraryNode(element) { const html = window.document.documentElement; const relativeOffset = getOffsetRectRelativeToArbitraryNode(element, html); const width = Math.max(html.clientWidth, window.innerWidth || 0); const height = Math.max(html.clientHeight, window.innerHeight || 0); const scrollTop = getScroll(html); const scrollLeft = getScroll(html, 'left'); const offset = { top: scrollTop - relativeOffset.top + relativeOffset.marginTop, left: scrollLeft - relativeOffset.left + relativeOffset.marginLeft, width, height }; return getClientRect(offset); } /** * Check if the given element is fixed or is inside a fixed parent * @method * @memberof Popper.Utils * @argument {Element} element * @argument {Element} customContainer * @returns {Boolean} answer to "isFixed?" */ function isFixed(element) { const nodeName = element.nodeName; if (nodeName === 'BODY' || nodeName === 'HTML') { return false; } if (getStyleComputedProperty(element, 'position') === 'fixed') { return true; } return isFixed(getParentNode(element)); } /** * Computed the boundaries limits and return them * @method * @memberof Popper.Utils * @param {Object} data - Object containing the property "offsets" generated by `_getOffsets` * @param {Number} padding - Boundaries padding * @param {Element} boundariesElement - Element used to define the boundaries * @returns {Object} Coordinates of the boundaries */ function getBoundaries(popper, reference, padding, boundariesElement) { // NOTE: 1 DOM access here let boundaries = { top: 0, left: 0 }; const offsetParent = findCommonOffsetParent(popper, reference); // Handle viewport case if (boundariesElement === 'viewport') { boundaries = getViewportOffsetRectRelativeToArtbitraryNode(offsetParent); } else { // Handle other cases based on DOM element used as boundaries let boundariesNode; if (boundariesElement === 'scrollParent') { boundariesNode = getScrollParent(getParentNode(popper)); if (boundariesNode.nodeName === 'BODY') { boundariesNode = window.document.documentElement; } } else if (boundariesElement === 'window') { boundariesNode = window.document.documentElement; } else { boundariesNode = boundariesElement; } const offsets = getOffsetRectRelativeToArbitraryNode(boundariesNode, offsetParent); // In case of HTML, we need a different computation if (boundariesNode.nodeName === 'HTML' && !isFixed(offsetParent)) { const { height, width } = getWindowSizes(); boundaries.top += offsets.top - offsets.marginTop; boundaries.bottom = height + offsets.top; boundaries.left += offsets.left - offsets.marginLeft; boundaries.right = width + offsets.left; } else { // for all the other DOM elements, this one is good boundaries = offsets; } } // Add paddings boundaries.left += padding; boundaries.top += padding; boundaries.right -= padding; boundaries.bottom -= padding; return boundaries; } /** * Utility used to transform the `auto` placement to the placement with more * available space. * @method * @memberof Popper.Utils * @argument {Object} data - The data object generated by update method * @argument {Object} options - Modifiers configuration and options * @returns {Object} The data object, properly modified */ function computeAutoPlacement(placement, refRect, popper, reference) { if (placement.indexOf('auto') === -1) { return placement; } const boundaries = getBoundaries(popper, reference, 0, 'scrollParent'); const sides = { top: refRect.top - boundaries.top, right: boundaries.right - refRect.right, bottom: boundaries.bottom - refRect.bottom, left: refRect.left - boundaries.left }; const computedPlacement = Object.keys(sides).sort((a, b) => sides[b] - sides[a])[0]; const variation = placement.split('-')[1]; return computedPlacement + (variation ? `-${variation}` : ''); } const nativeHints = ['native code', '[object MutationObserverConstructor]']; /** * Determine if a function is implemented natively (as opposed to a polyfill). * @argument {Function | undefined} fn the function to check * @returns {boolean} */ var isNative = (fn => nativeHints.some(hint => (fn || '').toString().indexOf(hint) > -1)); const isBrowser = typeof window !== 'undefined'; const longerTimeoutBrowsers = ['Edge', 'Trident', 'Firefox']; let timeoutDuration = 0; for (let i = 0; i < longerTimeoutBrowsers.length; i += 1) { if (isBrowser && navigator.userAgent.indexOf(longerTimeoutBrowsers[i]) >= 0) { timeoutDuration = 1; break; } } function microtaskDebounce(fn) { let scheduled = false; let i = 0; const elem = document.createElement('span'); // MutationObserver provides a mechanism for scheduling microtasks, which // are scheduled *before* the next task. This gives us a way to debounce // a function but ensure it's called *before* the next paint. const observer = new MutationObserver(() => { fn(); scheduled = false; }); observer.observe(elem, { attributes: true }); return () => { if (!scheduled) { scheduled = true; elem.setAttribute('x-index', i); i = i + 1; // don't use compund (+=) because it doesn't get optimized in V8 } }; } function taskDebounce(fn) { let scheduled = false; return () => { if (!scheduled) { scheduled = true; setTimeout(() => { scheduled = false; fn(); }, timeoutDuration); } }; } // It's common for MutationObserver polyfills to be seen in the wild, however // these rely on Mutation Events which only occur when an element is connected // to the DOM. The algorithm used in this module does not use a connected element, // and so we must ensure that a *native* MutationObserver is available. const supportsNativeMutationObserver = isBrowser && isNative(window.MutationObserver); /** * Create a debounced version of a method, that's asynchronously deferred * but called in the minimum time possible. * * @method * @memberof Popper.Utils * @argument {Function} fn * @returns {Function} */ var debounce = supportsNativeMutationObserver ? microtaskDebounce : taskDebounce; /** * Mimics the `find` method of Array * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function find(arr, check) { // use native find if supported if (Array.prototype.find) { return arr.find(check); } // use `filter` to obtain the same behavior of `find` return arr.filter(check)[0]; } /** * Return the index of the matching object * @method * @memberof Popper.Utils * @argument {Array} arr * @argument prop * @argument value * @returns index or -1 */ function findIndex(arr, prop, value) { // use native findIndex if supported if (Array.prototype.findIndex) { return arr.findIndex(cur => cur[prop] === value); } // use `find` + `indexOf` if `findIndex` isn't supported const match = find(arr, obj => obj[prop] === value); return arr.indexOf(match); } /** * Get the position of the given element, relative to its offset parent * @method * @memberof Popper.Utils * @param {Element} element * @return {Object} position - Coordinates of the element and its `scrollTop` */ function getOffsetRect(element) { let elementRect; if (element.nodeName === 'HTML') { const { width, height } = getWindowSizes(); elementRect = { width, height, left: 0, top: 0 }; } else { elementRect = { width: element.offsetWidth, height: element.offsetHeight, left: element.offsetLeft, top: element.offsetTop }; } // position return getClientRect(elementRect); } /** * Get the outer sizes of the given element (offset size + margins) * @method * @memberof Popper.Utils * @argument {Element} element * @returns {Object} object containing width and height properties */ function getOuterSizes(element) { const styles = window.getComputedStyle(element); const x = parseFloat(styles.marginTop) + parseFloat(styles.marginBottom); const y = parseFloat(styles.marginLeft) + parseFloat(styles.marginRight); const result = { width: element.offsetWidth + y, height: element.offsetHeight + x }; return result; } /** * Get the opposite placement of the given one/ * @method * @memberof Popper.Utils * @argument {String} placement * @returns {String} flipped placement */ function getOppositePlacement(placement) { const hash = { left: 'right', right: 'left', bottom: 'top', top: 'bottom' }; return placement.replace(/left|right|bottom|top/g, matched => hash[matched]); } /** * Get offsets to the popper * @method * @memberof Popper.Utils * @param {Object} position - CSS position the Popper will get applied * @param {HTMLElement} popper - the popper element * @param {Object} referenceOffsets - the reference offsets (the popper will be relative to this) * @param {String} placement - one of the valid placement options * @returns {Object} popperOffsets - An object containing the offsets which will be applied to the popper */ function getPopperOffsets(position, popper, referenceOffsets, placement) { placement = placement.split('-')[0]; // Get popper node sizes const popperRect = getOuterSizes(popper); // Add position, width and height to our offsets object const popperOffsets = { position, width: popperRect.width, height: popperRect.height }; // depending by the popper placement we have to compute its offsets slightly differently const isHoriz = ['right', 'left'].indexOf(placement) !== -1; const mainSide = isHoriz ? 'top' : 'left'; const secondarySide = isHoriz ? 'left' : 'top'; const measurement = isHoriz ? 'height' : 'width'; const secondaryMeasurement = !isHoriz ? 'height' : 'width'; popperOffsets[mainSide] = referenceOffsets[mainSide] + referenceOffsets[measurement] / 2 - popperRect[measurement] / 2; if (placement === secondarySide) { popperOffsets[secondarySide] = referenceOffsets[secondarySide] - popperRect[secondaryMeasurement]; } else { popperOffsets[secondarySide] = referenceOffsets[getOppositePlacement(secondarySide)]; } return popperOffsets; } /** * Get offsets to the reference element * @method * @memberof Popper.Utils * @param {Object} state * @param {Element} popper - the popper element * @param {Element} reference - the reference element (the popper will be relative to this) * @returns {Object} An object containing the offsets which will be applied to the popper */ function getReferenceOffsets(state, popper, reference) { const commonOffsetParent = findCommonOffsetParent(popper, reference); return getOffsetRectRelativeToArbitraryNode(reference, commonOffsetParent); } /** * Get the prefixed supported property name * @method * @memberof Popper.Utils * @argument {String} property (camelCase) * @returns {String} prefixed property (camelCase) */ function getSupportedPropertyName(property) { const prefixes = [false, 'ms', 'webkit', 'moz', 'o']; const upperProp = property.charAt(0).toUpperCase() + property.slice(1); for (let i = 0; i < prefixes.length - 1; i++) { const prefix = prefixes[i]; const toCheck = prefix ? `${prefix}${upperProp}` : property; if (typeof window.document.body.style[toCheck] !== 'undefined') { return toCheck; } } return null; } /** * Gets the scroll value of the given element relative to the given parent/ * It will not include the scroll values of elements that aren't positioned. * @method * @memberof Popper.Utils * @argument {Element} element * @argument {Element} parent * @argument {String} side `top` or `left` * @returns {Number} amount of scrolled pixels */ function getTotalScroll(element, parent, side = 'top') { const scrollParent = getScrollParent(element); let scroll = 0; const isParentFixed = isFixed(parent); // NOTE: I'm not sure the second line of this check is completely correct, review it if // someone complains about viewport problems in future if (isOffsetContainer(scrollParent.nodeName === 'BODY' ? window.document.documentElement : scrollParent) && (parent.contains(scrollParent) && isParentFixed || !isParentFixed)) { scroll = getScroll(scrollParent, side); } if (parent === scrollParent || ['BODY', 'HTML'].indexOf(scrollParent.nodeName) === -1) { return scroll + getTotalScroll(getParentNode(scrollParent), parent, side); } return scroll; } /** * Check if the given variable is a function * @method * @memberof Popper.Utils * @argument {*} functionToCheck - variable to check * @returns {Boolean} answer to: is a function? */ function isFunction(functionToCheck) { const getType = {}; return functionToCheck && getType.toString.call(functionToCheck) === '[object Function]'; } /** * Helper used to know if the given modifier is enabled. * @method * @memberof Popper.Utils * @returns {Boolean} */ function isModifierEnabled(modifiers, modifierName) { return modifiers.some(({ name, enabled }) => enabled && name === modifierName); } /** * Helper used to know if the given modifier depends from another one. * It checks if the needed modifier is listed and enabled. * @method * @memberof Popper.Utils * @param {Array} modifiers - list of modifiers * @param {String} requestingName - name of requesting modifier * @param {String} requestedName - name of requested modifier * @returns {Boolean} */ function isModifierRequired(modifiers, requestingName, requestedName) { const requesting = find(modifiers, ({ name }) => name === requestingName); return !!requesting && modifiers.some(modifier => { return modifier.name === requestedName && modifier.enabled && modifier.order < requesting.order; }); } /** * Tells if a given input is a number * @method * @memberof Popper.Utils * @param {*} input to check * @return {Boolean} */ function isNumeric(n) { return n !== '' && !isNaN(parseFloat(n)) && isFinite(n); } /** * Remove event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function removeEventListeners(reference, state) { // Remove resize event listener on window window.removeEventListener('resize', state.updateBound); // Remove scroll event listener on scroll parents state.scrollParents.forEach(target => { target.removeEventListener('scroll', state.updateBound); }); // Reset state state.updateBound = null; state.scrollParents = []; state.scrollElement = null; state.eventsEnabled = false; return state; } /** * Loop trough the list of modifiers and run them in order, each of them will then edit the data object * @method * @memberof Popper.Utils * @param {Object} data * @param {Array} modifiers * @param {Function} ends */ function runModifiers(modifiers, data, ends) { const modifiersToRun = ends === undefined ? modifiers : modifiers.slice(0, findIndex(modifiers, 'name', ends)); modifiersToRun.forEach(modifier => { if (modifier.enabled && isFunction(modifier.function)) { data = modifier.function(data, modifier); } }); return data; } /** * Set the attributes to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the attributes to * @argument {Object} styles - Object with a list of properties and values which will be applied to the element */ function setAttributes(element, attributes) { Object.keys(attributes).forEach(function (prop) { const value = attributes[prop]; if (value !== false) { element.setAttribute(prop, attributes[prop]); } else { element.removeAttribute(prop); } }); } /** * Set the style to the given popper * @method * @memberof Popper.Utils * @argument {Element} element - Element to apply the style to * @argument {Object} styles - Object with a list of properties and values which will be applied to the element */ function setStyles(element, styles) { Object.keys(styles).forEach(prop => { let unit = ''; // add unit if the value is numeric and is one of the following if (['width', 'height', 'top', 'right', 'bottom', 'left'].indexOf(prop) !== -1 && isNumeric(styles[prop])) { unit = 'px'; } element.style[prop] = styles[prop] + unit; }); } function attachToScrollParents(scrollParent, event, callback, scrollParents) { const isBody = scrollParent.nodeName === 'BODY'; const target = isBody ? window : scrollParent; target.addEventListener(event, callback, { passive: true }); if (!isBody) { attachToScrollParents(getScrollParent(target.parentNode), event, callback, scrollParents); } scrollParents.push(target); } /** * Setup needed event listeners used to update the popper position * @method * @memberof Popper.Utils * @private */ function setupEventListeners(reference, options, state, updateBound) { // Resize event listener on window state.updateBound = updateBound; window.addEventListener('resize', state.updateBound, { passive: true }); // Scroll event listener on scroll parents const scrollElement = getScrollParent(reference); attachToScrollParents(scrollElement, 'scroll', state.updateBound, state.scrollParents); state.scrollElement = scrollElement; state.eventsEnabled = true; return state; } /** @namespace Popper.Utils */ var index = { computeAutoPlacement, debounce, findIndex, getBordersSize, getBoundaries, getBoundingClientRect, getClientRect, getOffsetParent, getOffsetRect, getOffsetRectRelativeToArbitraryNode, getOuterSizes, getParentNode, getPopperOffsets, getReferenceOffsets, getScroll, getScrollParent, getStyleComputedProperty, getSupportedPropertyName, getTotalScroll, getWindowSizes, isFixed, isFunction, isModifierEnabled, isModifierRequired, isNative, isNumeric, removeEventListeners, runModifiers, setAttributes, setStyles, setupEventListeners }; return index; }))); //# sourceMappingURL=popper-utils.js.map
function intval(mixed_var, base) { // discuss at: http://phpjs.org/functions/intval/ // original by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // improved by: stensi // bugfixed by: Kevin van Zonneveld (http://kevin.vanzonneveld.net) // bugfixed by: Brett Zamir (http://brett-zamir.me) // bugfixed by: Rafał Kukawski (http://kukawski.pl) // input by: Matteo // example 1: intval('Kevin van Zonneveld'); // returns 1: 0 // example 2: intval(4.2); // returns 2: 4 // example 3: intval(42, 8); // returns 3: 42 // example 4: intval('09'); // returns 4: 9 // example 5: intval('1e', 16); // returns 5: 30 var tmp; var type = typeof mixed_var; if (type === 'boolean') { return +mixed_var; } else if (type === 'string') { tmp = parseInt(mixed_var, base || 10); return (isNaN(tmp) || !isFinite(tmp)) ? 0 : tmp; } else if (type === 'number' && isFinite(mixed_var)) { return mixed_var | 0; } else { return 0; } }
export default function debounce(fn) { var pending; return function () { if (!pending) { pending = new Promise(function (resolve) { Promise.resolve().then(function () { pending = undefined; resolve(fn()); }); }); } return pending; }; }
/** * Copyright 2013-2014, Facebook, Inc. * All rights reserved. * * This source code is licensed under the BSD-style license found in the * LICENSE file in the root directory of this source tree. An additional grant * of patent rights can be found in the PATENTS file in the same directory. * * @providesModule ReactPropTransferer */ "use strict"; var assign = require("./Object.assign"); var emptyFunction = require("./emptyFunction"); var invariant = require("./invariant"); var joinClasses = require("./joinClasses"); var warning = require("./warning"); var didWarn = false; /** * Creates a transfer strategy that will merge prop values using the supplied * `mergeStrategy`. If a prop was previously unset, this just sets it. * * @param {function} mergeStrategy * @return {function} */ function createTransferStrategy(mergeStrategy) { return function(props, key, value) { if (!props.hasOwnProperty(key)) { props[key] = value; } else { props[key] = mergeStrategy(props[key], value); } }; } var transferStrategyMerge = createTransferStrategy(function(a, b) { // `merge` overrides the first object's (`props[key]` above) keys using the // second object's (`value`) keys. An object's style's existing `propA` would // get overridden. Flip the order here. return assign({}, b, a); }); /** * Transfer strategies dictate how props are transferred by `transferPropsTo`. * NOTE: if you add any more exceptions to this list you should be sure to * update `cloneWithProps()` accordingly. */ var TransferStrategies = { /** * Never transfer `children`. */ children: emptyFunction, /** * Transfer the `className` prop by merging them. */ className: createTransferStrategy(joinClasses), /** * Transfer the `style` prop (which is an object) by merging them. */ style: transferStrategyMerge }; /** * Mutates the first argument by transferring the properties from the second * argument. * * @param {object} props * @param {object} newProps * @return {object} */ function transferInto(props, newProps) { for (var thisKey in newProps) { if (!newProps.hasOwnProperty(thisKey)) { continue; } var transferStrategy = TransferStrategies[thisKey]; if (transferStrategy && TransferStrategies.hasOwnProperty(thisKey)) { transferStrategy(props, thisKey, newProps[thisKey]); } else if (!props.hasOwnProperty(thisKey)) { props[thisKey] = newProps[thisKey]; } } return props; } /** * ReactPropTransferer are capable of transferring props to another component * using a `transferPropsTo` method. * * @class ReactPropTransferer */ var ReactPropTransferer = { TransferStrategies: TransferStrategies, /** * Merge two props objects using TransferStrategies. * * @param {object} oldProps original props (they take precedence) * @param {object} newProps new props to merge in * @return {object} a new object containing both sets of props merged. */ mergeProps: function(oldProps, newProps) { return transferInto(assign({}, oldProps), newProps); }, /** * @lends {ReactPropTransferer.prototype} */ Mixin: { /** * Transfer props from this component to a target component. * * Props that do not have an explicit transfer strategy will be transferred * only if the target component does not already have the prop set. * * This is usually used to pass down props to a returned root component. * * @param {ReactElement} element Component receiving the properties. * @return {ReactElement} The supplied `component`. * @final * @protected */ transferPropsTo: function(element) { ("production" !== process.env.NODE_ENV ? invariant( element._owner === this, '%s: You can\'t call transferPropsTo() on a component that you ' + 'don\'t own, %s. This usually means you are calling ' + 'transferPropsTo() on a component passed in as props or children.', this.constructor.displayName, typeof element.type === 'string' ? element.type : element.type.displayName ) : invariant(element._owner === this)); if ("production" !== process.env.NODE_ENV) { if (!didWarn) { didWarn = true; ("production" !== process.env.NODE_ENV ? warning( false, 'transferPropsTo is deprecated. ' + 'See http://fb.me/react-transferpropsto for more information.' ) : null); } } // Because elements are immutable we have to merge into the existing // props object rather than clone it. transferInto(element.props, this.props); return element; } } }; module.exports = ReactPropTransferer;
/* Highmaps JS v5.0.8 (2017-03-08) Highmaps as a plugin for Highcharts 4.1.x or Highstock 2.1.x (x being the patch version of this file) (c) 2011-2016 Torstein Honsi License: www.highcharts.com/license */ (function(y){"object"===typeof module&&module.exports?module.exports=y:y(Highcharts)})(function(y){(function(a){var m=a.Axis,p=a.each,l=a.pick;a=a.wrap;a(m.prototype,"getSeriesExtremes",function(a){var e=this.isXAxis,w,m,v=[],d;e&&p(this.series,function(b,a){b.useMapGeometry&&(v[a]=b.xData,b.xData=[])});a.call(this);e&&(w=l(this.dataMin,Number.MAX_VALUE),m=l(this.dataMax,-Number.MAX_VALUE),p(this.series,function(b,a){b.useMapGeometry&&(w=Math.min(w,l(b.minX,w)),m=Math.max(m,l(b.maxX,w)),b.xData=v[a], d=!0)}),d&&(this.dataMin=w,this.dataMax=m))});a(m.prototype,"setAxisTranslation",function(a){var q=this.chart,e=q.plotWidth/q.plotHeight,q=q.xAxis[0],l;a.call(this);"yAxis"===this.coll&&void 0!==q.transA&&p(this.series,function(a){a.preserveAspectRatio&&(l=!0)});if(l&&(this.transA=q.transA=Math.min(this.transA,q.transA),a=e/((q.max-q.min)/(this.max-this.min)),a=1>a?this:q,e=(a.max-a.min)*a.transA,a.pixelPadding=a.len-e,a.minPixelPadding=a.pixelPadding/2,e=a.fixTo)){e=e[1]-a.toValue(e[0],!0);e*=a.transA; if(Math.abs(e)>a.minPixelPadding||a.min===a.dataMin&&a.max===a.dataMax)e=0;a.minPixelPadding-=e}});a(m.prototype,"render",function(a){a.call(this);this.fixTo=null})})(y);(function(a){var m=a.Axis,p=a.Chart,l=a.color,e,q=a.each,w=a.extend,x=a.isNumber,v=a.Legend,d=a.LegendSymbolMixin,b=a.noop,c=a.merge,g=a.pick,t=a.wrap;e=a.ColorAxis=function(){this.init.apply(this,arguments)};w(e.prototype,m.prototype);w(e.prototype,{defaultColorAxisOptions:{lineWidth:0,minPadding:0,maxPadding:0,gridLineWidth:1,tickPixelInterval:72, startOnTick:!0,endOnTick:!0,offset:0,marker:{animation:{duration:50},width:.01,color:"#999999"},labels:{overflow:"justify",rotation:0},minColor:"#e6ebf5",maxColor:"#003399",tickLength:5,showInLegend:!0},keepProps:["legendGroup","legendItemHeight","legendItemWidth","legendItem","legendSymbol"].concat(m.prototype.keepProps),init:function(a,f){var b="vertical"!==a.options.legend.layout,k;this.coll="colorAxis";k=c(this.defaultColorAxisOptions,{side:b?2:1,reversed:!b},f,{opposite:!b,showEmpty:!1,title:null}); m.prototype.init.call(this,a,k);f.dataClasses&&this.initDataClasses(f);this.initStops(f);this.horiz=b;this.zoomEnabled=!1;this.defaultLegendLength=200},tweenColors:function(a,f,b){var k;f.rgba.length&&a.rgba.length?(a=a.rgba,f=f.rgba,k=1!==f[3]||1!==a[3],a=(k?"rgba(":"rgb(")+Math.round(f[0]+(a[0]-f[0])*(1-b))+","+Math.round(f[1]+(a[1]-f[1])*(1-b))+","+Math.round(f[2]+(a[2]-f[2])*(1-b))+(k?","+(f[3]+(a[3]-f[3])*(1-b)):"")+")"):a=f.input||"none";return a},initDataClasses:function(a){var b=this,k=this.chart, r,h=0,u=k.options.chart.colorCount,g=this.options,d=a.dataClasses.length;this.dataClasses=r=[];this.legendItems=[];q(a.dataClasses,function(a,f){a=c(a);r.push(a);a.color||("category"===g.dataClassColor?(f=k.options.colors,u=f.length,a.color=f[h],a.colorIndex=h,h++,h===u&&(h=0)):a.color=b.tweenColors(l(g.minColor),l(g.maxColor),2>d?.5:f/(d-1)))})},initStops:function(a){this.stops=a.stops||[[0,this.options.minColor],[1,this.options.maxColor]];q(this.stops,function(a){a.color=l(a[1])})},setOptions:function(a){m.prototype.setOptions.call(this, a);this.options.crosshair=this.options.marker},setAxisSize:function(){var a=this.legendSymbol,b=this.chart,n=b.options.legend||{},c,h;a?(this.left=n=a.attr("x"),this.top=c=a.attr("y"),this.width=h=a.attr("width"),this.height=a=a.attr("height"),this.right=b.chartWidth-n-h,this.bottom=b.chartHeight-c-a,this.len=this.horiz?h:a,this.pos=this.horiz?n:c):this.len=(this.horiz?n.symbolWidth:n.symbolHeight)||this.defaultLegendLength},toColor:function(a,b){var f=this.stops,k,h,c=this.dataClasses,g,d;if(c)for(d= c.length;d--;){if(g=c[d],k=g.from,f=g.to,(void 0===k||a>=k)&&(void 0===f||a<=f)){h=g.color;b&&(b.dataClass=d,b.colorIndex=g.colorIndex);break}}else{this.isLog&&(a=this.val2lin(a));a=1-(this.max-a)/(this.max-this.min||1);for(d=f.length;d--&&!(a>f[d][0]););k=f[d]||f[d+1];f=f[d+1]||k;a=1-(f[0]-a)/(f[0]-k[0]||1);h=this.tweenColors(k.color,f.color,a)}return h},getOffset:function(){var a=this.legendGroup,b=this.chart.axisOffset[this.side];a&&(this.axisParent=a,m.prototype.getOffset.call(this),this.added|| (this.added=!0,this.labelLeft=0,this.labelRight=this.width),this.chart.axisOffset[this.side]=b)},setLegendColor:function(){var a,b=this.options,n=this.reversed;a=n?1:0;n=n?0:1;a=this.horiz?[a,0,n,0]:[0,n,0,a];this.legendColor={linearGradient:{x1:a[0],y1:a[1],x2:a[2],y2:a[3]},stops:b.stops||[[0,b.minColor],[1,b.maxColor]]}},drawLegendSymbol:function(a,b){var f=a.padding,k=a.options,h=this.horiz,c=g(k.symbolWidth,h?this.defaultLegendLength:12),d=g(k.symbolHeight,h?12:this.defaultLegendLength),e=g(k.labelPadding, h?16:30),k=g(k.itemDistance,10);this.setLegendColor();b.legendSymbol=this.chart.renderer.rect(0,a.baseline-11,c,d).attr({zIndex:1}).add(b.legendGroup);this.legendItemWidth=c+f+(h?k:e);this.legendItemHeight=d+f+(h?e:0)},setState:b,visible:!0,setVisible:b,getSeriesExtremes:function(){var a=this.series,b=a.length;this.dataMin=Infinity;for(this.dataMax=-Infinity;b--;)void 0!==a[b].valueMin&&(this.dataMin=Math.min(this.dataMin,a[b].valueMin),this.dataMax=Math.max(this.dataMax,a[b].valueMax))},drawCrosshair:function(a, b){var f=b&&b.plotX,c=b&&b.plotY,h,k=this.pos,d=this.len;b&&(h=this.toPixels(b[b.series.colorKey]),h<k?h=k-2:h>k+d&&(h=k+d+2),b.plotX=h,b.plotY=this.len-h,m.prototype.drawCrosshair.call(this,a,b),b.plotX=f,b.plotY=c,this.cross&&(this.cross.addClass("highcharts-coloraxis-marker").add(this.legendGroup),this.cross.attr({fill:this.crosshair.color})))},getPlotLinePath:function(a,b,c,d,h){return x(h)?this.horiz?["M",h-4,this.top-6,"L",h+4,this.top-6,h,this.top,"Z"]:["M",this.left,h,"L",this.left-6,h+6, this.left-6,h-6,"Z"]:m.prototype.getPlotLinePath.call(this,a,b,c,d)},update:function(a,b){var f=this.chart,k=f.legend;q(this.series,function(a){a.isDirtyData=!0});a.dataClasses&&k.allItems&&(q(k.allItems,function(a){a.isDataClass&&a.legendGroup.destroy()}),f.isDirtyLegend=!0);f.options[this.coll]=c(this.userOptions,a);m.prototype.update.call(this,a,b);this.legendItem&&(this.setLegendColor(),k.colorizeItem(this,!0))},getDataClassLegendSymbols:function(){var c=this,f=this.chart,n=this.legendItems,g= f.options.legend,h=g.valueDecimals,e=g.valueSuffix||"",t;n.length||q(this.dataClasses,function(k,g){var u=!0,r=k.from,z=k.to;t="";void 0===r?t="\x3c ":void 0===z&&(t="\x3e ");void 0!==r&&(t+=a.numberFormat(r,h)+e);void 0!==r&&void 0!==z&&(t+=" - ");void 0!==z&&(t+=a.numberFormat(z,h)+e);n.push(w({chart:f,name:t,options:{},drawLegendSymbol:d.drawRectangle,visible:!0,setState:b,isDataClass:!0,setVisible:function(){u=this.visible=!u;q(c.series,function(a){q(a.points,function(a){a.dataClass===g&&a.setVisible(u)})}); f.legend.colorizeItem(this,u)}},k))});return n},name:""});q(["fill","stroke"],function(b){a.Fx.prototype[b+"Setter"]=function(){this.elem.attr(b,e.prototype.tweenColors(l(this.start),l(this.end),this.pos),null,!0)}});t(p.prototype,"getAxes",function(a){var b=this.options.colorAxis;a.call(this);this.colorAxis=[];b&&new e(this,b)});t(v.prototype,"getAllItems",function(a){var b=[],c=this.chart.colorAxis[0];c&&c.options&&(c.options.showInLegend&&(c.options.dataClasses?b=b.concat(c.getDataClassLegendSymbols()): b.push(c)),q(c.series,function(a){a.options.showInLegend=!1}));return b.concat(a.call(this))});t(v.prototype,"colorizeItem",function(a,b,c){a.call(this,b,c);c&&b.legendColor&&b.legendSymbol.attr({fill:b.legendColor})})})(y);(function(a){var m=a.defined,p=a.each,l=a.noop,e=a.seriesTypes;a.colorPointMixin={isValid:function(){return null!==this.value},setVisible:function(a){var e=this,q=a?"show":"hide";p(["graphic","dataLabel"],function(a){if(e[a])e[a][q]()})},setState:function(e){a.Point.prototype.setState.call(this, e);this.graphic&&this.graphic.attr({zIndex:"hover"===e?1:0})}};a.colorSeriesMixin={pointArrayMap:["value"],axisTypes:["xAxis","yAxis","colorAxis"],optionalAxis:"colorAxis",trackerGroups:["group","markerGroup","dataLabelsGroup"],getSymbol:l,parallelArrays:["x","y","value"],colorKey:"value",pointAttribs:e.column.prototype.pointAttribs,translateColors:function(){var a=this,e=this.options.nullColor,l=this.colorAxis,m=this.colorKey;p(this.data,function(d){var b=d[m];if(b=d.options.color||(d.isNull?e:l&& void 0!==b?l.toColor(b,d):d.color||a.color))d.color=b})},colorAttribs:function(a){var e={};m(a.color)&&(e[this.colorProp||"fill"]=a.color);return e}}})(y);(function(a){function m(a){a&&(a.preventDefault&&a.preventDefault(),a.stopPropagation&&a.stopPropagation(),a.cancelBubble=!0)}function p(a){this.init(a)}var l=a.addEvent,e=a.Chart,q=a.doc,w=a.each,x=a.extend,v=a.merge,d=a.pick;a=a.wrap;p.prototype.init=function(a){this.chart=a;a.mapNavButtons=[]};p.prototype.update=function(a){var b=this.chart, g=b.options.mapNavigation,e,k,f,n,r,h=function(a){this.handler.call(b,a);m(a)},u=b.mapNavButtons;a&&(g=b.options.mapNavigation=v(b.options.mapNavigation,a));for(;u.length;)u.pop().destroy();if(d(g.enableButtons,g.enabled)&&!b.renderer.forExport)for(e in a=g.buttons,a)a.hasOwnProperty(e)&&(f=v(g.buttonOptions,a[e]),k=f.theme,k.style=v(f.theme.style,f.style),r=(n=k.states)&&n.hover,n=n&&n.select,k=b.renderer.button(f.text,0,0,h,k,r,n,0,"zoomIn"===e?"topbutton":"bottombutton").addClass("highcharts-map-navigation").attr({width:f.width, height:f.height,title:b.options.lang[e],padding:f.padding,zIndex:5}).add(),k.handler=f.onclick,k.align(x(f,{width:k.width,height:2*k.height}),null,f.alignTo),l(k.element,"dblclick",m),u.push(k));this.updateEvents(g)};p.prototype.updateEvents=function(a){var b=this.chart;d(a.enableDoubleClickZoom,a.enabled)||a.enableDoubleClickZoomTo?this.unbindDblClick=this.unbindDblClick||l(b.container,"dblclick",function(a){b.pointer.onContainerDblClick(a)}):this.unbindDblClick&&(this.unbindDblClick=this.unbindDblClick()); d(a.enableMouseWheelZoom,a.enabled)?this.unbindMouseWheel=this.unbindMouseWheel||l(b.container,void 0===q.onmousewheel?"DOMMouseScroll":"mousewheel",function(a){b.pointer.onContainerMouseWheel(a);m(a);return!1}):this.unbindMouseWheel&&(this.unbindMouseWheel=this.unbindMouseWheel())};x(e.prototype,{fitToBox:function(a,c){w([["x","width"],["y","height"]],function(b){var d=b[0];b=b[1];a[d]+a[b]>c[d]+c[b]&&(a[b]>c[b]?(a[b]=c[b],a[d]=c[d]):a[d]=c[d]+c[b]-a[b]);a[b]>c[b]&&(a[b]=c[b]);a[d]<c[d]&&(a[d]=c[d])}); return a},mapZoom:function(a,c,e,q,k){var b=this.xAxis[0],n=b.max-b.min,g=d(c,b.min+n/2),h=n*a,n=this.yAxis[0],u=n.max-n.min,z=d(e,n.min+u/2),u=u*a,g=this.fitToBox({x:g-h*(q?(q-b.pos)/b.len:.5),y:z-u*(k?(k-n.pos)/n.len:.5),width:h,height:u},{x:b.dataMin,y:n.dataMin,width:b.dataMax-b.dataMin,height:n.dataMax-n.dataMin}),h=g.x<=b.dataMin&&g.width>=b.dataMax-b.dataMin&&g.y<=n.dataMin&&g.height>=n.dataMax-n.dataMin;q&&(b.fixTo=[q-b.pos,c]);k&&(n.fixTo=[k-n.pos,e]);void 0===a||h?(b.setExtremes(void 0, void 0,!1),n.setExtremes(void 0,void 0,!1)):(b.setExtremes(g.x,g.x+g.width,!1),n.setExtremes(g.y,g.y+g.height,!1));this.redraw()}});a(e.prototype,"render",function(a){this.mapNavigation=new p(this);this.mapNavigation.update();a.call(this)})})(y);(function(a){var m=a.extend,p=a.pick,l=a.Pointer;a=a.wrap;m(l.prototype,{onContainerDblClick:function(a){var e=this.chart;a=this.normalize(a);e.options.mapNavigation.enableDoubleClickZoomTo?e.pointer.inClass(a.target,"highcharts-tracker")&&e.hoverPoint&&e.hoverPoint.zoomTo(): e.isInsidePlot(a.chartX-e.plotLeft,a.chartY-e.plotTop)&&e.mapZoom(.5,e.xAxis[0].toValue(a.chartX),e.yAxis[0].toValue(a.chartY),a.chartX,a.chartY)},onContainerMouseWheel:function(a){var e=this.chart,l;a=this.normalize(a);l=a.detail||-(a.wheelDelta/120);e.isInsidePlot(a.chartX-e.plotLeft,a.chartY-e.plotTop)&&e.mapZoom(Math.pow(e.options.mapNavigation.mouseWheelSensitivity,l),e.xAxis[0].toValue(a.chartX),e.yAxis[0].toValue(a.chartY),a.chartX,a.chartY)}});a(l.prototype,"zoomOption",function(a){var e= this.chart.options.mapNavigation;p(e.enableTouchZoom,e.enabled)&&(this.chart.options.chart.pinchType="xy");a.apply(this,[].slice.call(arguments,1))});a(l.prototype,"pinchTranslate",function(a,l,m,p,v,d,b){a.call(this,l,m,p,v,d,b);"map"===this.chart.options.chart.type&&this.hasZoom&&(a=p.scaleX>p.scaleY,this.pinchTranslateDirection(!a,l,m,p,v,d,b,a?p.scaleX:p.scaleY))})})(y);(function(a){var m=a.color,p=a.ColorAxis,l=a.colorPointMixin,e=a.each,q=a.extend,w=a.isNumber,x=a.map,v=a.merge,d=a.noop,b=a.pick, c=a.isArray,g=a.Point,t=a.Series,k=a.seriesType,f=a.seriesTypes,n=a.splat,r=void 0!==a.doc.documentElement.style.vectorEffect;k("map","scatter",{allAreas:!0,animation:!1,nullColor:"#f7f7f7",borderColor:"#cccccc",borderWidth:1,marker:null,stickyTracking:!1,joinBy:"hc-key",dataLabels:{formatter:function(){return this.point.value},inside:!0,verticalAlign:"middle",crop:!1,overflow:!1,padding:0},turboThreshold:0,tooltip:{followPointer:!0,pointFormat:"{point.name}: {point.value}\x3cbr/\x3e"},states:{normal:{animation:!0}, hover:{brightness:.2,halo:null},select:{color:"#cccccc"}}},v(a.colorSeriesMixin,{type:"map",supportsDrilldown:!0,getExtremesFromAll:!0,useMapGeometry:!0,forceDL:!0,searchPoint:d,directTouch:!0,preserveAspectRatio:!0,pointArrayMap:["value"],getBox:function(h){var c=Number.MAX_VALUE,f=-c,d=c,k=-c,n=c,g=c,l=this.xAxis,t=this.yAxis,r;e(h||[],function(h){if(h.path){"string"===typeof h.path&&(h.path=a.splitPath(h.path));var e=h.path||[],u=e.length,l=!1,t=-c,z=c,q=-c,m=c,p=h.properties;if(!h._foundBox){for(;u--;)w(e[u])&& (l?(t=Math.max(t,e[u]),z=Math.min(z,e[u])):(q=Math.max(q,e[u]),m=Math.min(m,e[u])),l=!l);h._midX=z+(t-z)*(h.middleX||p&&p["hc-middle-x"]||.5);h._midY=m+(q-m)*(h.middleY||p&&p["hc-middle-y"]||.5);h._maxX=t;h._minX=z;h._maxY=q;h._minY=m;h.labelrank=b(h.labelrank,(t-z)*(q-m));h._foundBox=!0}f=Math.max(f,h._maxX);d=Math.min(d,h._minX);k=Math.max(k,h._maxY);n=Math.min(n,h._minY);g=Math.min(h._maxX-h._minX,h._maxY-h._minY,g);r=!0}});r&&(this.minY=Math.min(n,b(this.minY,c)),this.maxY=Math.max(k,b(this.maxY, -c)),this.minX=Math.min(d,b(this.minX,c)),this.maxX=Math.max(f,b(this.maxX,-c)),l&&void 0===l.options.minRange&&(l.minRange=Math.min(5*g,(this.maxX-this.minX)/5,l.minRange||c)),t&&void 0===t.options.minRange&&(t.minRange=Math.min(5*g,(this.maxY-this.minY)/5,t.minRange||c)))},getExtremes:function(){t.prototype.getExtremes.call(this,this.valueData);this.chart.hasRendered&&this.isDirtyData&&this.getBox(this.options.data);this.valueMin=this.dataMin;this.valueMax=this.dataMax;this.dataMin=this.minY;this.dataMax= this.maxY},translatePath:function(a){var b=!1,h=this.xAxis,c=this.yAxis,f=h.min,d=h.transA,h=h.minPixelPadding,k=c.min,e=c.transA,c=c.minPixelPadding,n,g=[];if(a)for(n=a.length;n--;)w(a[n])?(g[n]=b?(a[n]-f)*d+h:(a[n]-k)*e+c,b=!b):g[n]=a[n];return g},setData:function(b,f,d,k){var h=this.options,g=this.chart.options.chart,l=g&&g.map,u=h.mapData,r=h.joinBy,z=null===r,q=h.keys||this.pointArrayMap,m=[],p={},A,B=this.chart.mapTransforms;!u&&l&&(u="string"===typeof l?a.maps[l]:l);z&&(r="_i");r=this.joinBy= n(r);r[1]||(r[1]=r[0]);b&&e(b,function(a,f){var d=0;if(w(a))b[f]={value:a};else if(c(a)){b[f]={};!h.keys&&a.length>q.length&&"string"===typeof a[0]&&(b[f]["hc-key"]=a[0],++d);for(var k=0;k<q.length;++k,++d)q[k]&&(b[f][q[k]]=a[d])}z&&(b[f]._i=f)});this.getBox(b);if(this.chart.mapTransforms=B=g&&g.mapTransforms||u&&u["hc-transform"]||B)for(A in B)B.hasOwnProperty(A)&&A.rotation&&(A.cosAngle=Math.cos(A.rotation),A.sinAngle=Math.sin(A.rotation));if(u){"FeatureCollection"===u.type&&(this.mapTitle=u.title, u=a.geojson(u,this.type,this));this.mapData=u;this.mapMap={};for(A=0;A<u.length;A++)g=u[A],l=g.properties,g._i=A,r[0]&&l&&l[r[0]]&&(g[r[0]]=l[r[0]]),p[g[r[0]]]=g;this.mapMap=p;b&&r[1]&&e(b,function(a){p[a[r[1]]]&&m.push(p[a[r[1]]])});h.allAreas?(this.getBox(u),b=b||[],r[1]&&e(b,function(a){m.push(a[r[1]])}),m="|"+x(m,function(a){return a&&a[r[0]]}).join("|")+"|",e(u,function(a){r[0]&&-1!==m.indexOf("|"+a[r[0]]+"|")||(b.push(v(a,{value:null})),k=!1)})):this.getBox(m)}t.prototype.setData.call(this, b,f,d,k)},drawGraph:d,drawDataLabels:d,doFullTranslate:function(){return this.isDirtyData||this.chart.isResizing||this.chart.renderer.isVML||!this.baseTrans},translate:function(){var a=this,b=a.xAxis,c=a.yAxis,f=a.doFullTranslate();a.generatePoints();e(a.data,function(h){h.plotX=b.toPixels(h._midX,!0);h.plotY=c.toPixels(h._midY,!0);f&&(h.shapeType="path",h.shapeArgs={d:a.translatePath(h.path)})});a.translateColors()},pointAttribs:function(a,b){b=f.column.prototype.pointAttribs.call(this,a,b);a.isFading&& delete b.fill;r?b["vector-effect"]="non-scaling-stroke":b["stroke-width"]="inherit";return b},drawPoints:function(){var a=this,b=a.xAxis,c=a.yAxis,d=a.group,k=a.chart,g=k.renderer,n,l,t,m,q=this.baseTrans,p,w,v,x,y;a.transformGroup||(a.transformGroup=g.g().attr({scaleX:1,scaleY:1}).add(d),a.transformGroup.survive=!0);a.doFullTranslate()?(k.hasRendered&&e(a.points,function(b){b.shapeArgs&&(b.shapeArgs.fill=a.pointAttribs(b,b.state).fill)}),a.group=a.transformGroup,f.column.prototype.drawPoints.apply(a), a.group=d,e(a.points,function(a){a.graphic&&(a.name&&a.graphic.addClass("highcharts-name-"+a.name.replace(/ /g,"-").toLowerCase()),a.properties&&a.properties["hc-key"]&&a.graphic.addClass("highcharts-key-"+a.properties["hc-key"].toLowerCase()))}),this.baseTrans={originX:b.min-b.minPixelPadding/b.transA,originY:c.min-c.minPixelPadding/c.transA+(c.reversed?0:c.len/c.transA),transAX:b.transA,transAY:c.transA},this.transformGroup.animate({translateX:0,translateY:0,scaleX:1,scaleY:1})):(n=b.transA/q.transAX, l=c.transA/q.transAY,t=b.toPixels(q.originX,!0),m=c.toPixels(q.originY,!0),.99<n&&1.01>n&&.99<l&&1.01>l&&(l=n=1,t=Math.round(t),m=Math.round(m)),p=this.transformGroup,k.renderer.globalAnimation?(w=p.attr("translateX"),v=p.attr("translateY"),x=p.attr("scaleX"),y=p.attr("scaleY"),p.attr({animator:0}).animate({animator:1},{step:function(a,b){p.attr({translateX:w+(t-w)*b.pos,translateY:v+(m-v)*b.pos,scaleX:x+(n-x)*b.pos,scaleY:y+(l-y)*b.pos})}})):p.attr({translateX:t,translateY:m,scaleX:n,scaleY:l})); r||a.group.element.setAttribute("stroke-width",a.options[a.pointAttrToOptions&&a.pointAttrToOptions["stroke-width"]||"borderWidth"]/(n||1));this.drawMapDataLabels()},drawMapDataLabels:function(){t.prototype.drawDataLabels.call(this);this.dataLabelsGroup&&this.dataLabelsGroup.clip(this.chart.clipRect)},render:function(){var a=this,b=t.prototype.render;a.chart.renderer.isVML&&3E3<a.data.length?setTimeout(function(){b.call(a)}):b.call(a)},animate:function(a){var b=this.options.animation,c=this.group, h=this.xAxis,f=this.yAxis,k=h.pos,d=f.pos;this.chart.renderer.isSVG&&(!0===b&&(b={duration:1E3}),a?c.attr({translateX:k+h.len/2,translateY:d+f.len/2,scaleX:.001,scaleY:.001}):(c.animate({translateX:k,translateY:d,scaleX:1,scaleY:1},b),this.animate=null))},animateDrilldown:function(a){var b=this.chart.plotBox,c=this.chart.drilldownLevels[this.chart.drilldownLevels.length-1],h=c.bBox,f=this.chart.options.drilldown.animation;a||(a=Math.min(h.width/b.width,h.height/b.height),c.shapeArgs={scaleX:a,scaleY:a, translateX:h.x,translateY:h.y},e(this.points,function(a){a.graphic&&a.graphic.attr(c.shapeArgs).animate({scaleX:1,scaleY:1,translateX:0,translateY:0},f)}),this.animate=null)},drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,animateDrillupFrom:function(a){f.column.prototype.animateDrillupFrom.call(this,a)},animateDrillupTo:function(a){f.column.prototype.animateDrillupTo.call(this,a)}}),q({applyOptions:function(a,b){a=g.prototype.applyOptions.call(this,a,b);b=this.series;var c=b.joinBy;b.mapData&& ((c=void 0!==a[c[1]]&&b.mapMap[a[c[1]]])?(b.xyFromShape&&(a.x=c._midX,a.y=c._midY),q(a,c)):a.value=a.value||null);return a},onMouseOver:function(a){clearTimeout(this.colorInterval);if(null!==this.value)g.prototype.onMouseOver.call(this,a);else this.series.onMouseOut(a)},onMouseOut:function(){var a=this,b=+new Date,c=m(this.series.pointAttribs(a).fill),f=m(this.series.pointAttribs(a,"hover").fill),k=a.series.options.states.normal.animation,d=k&&(k.duration||500);d&&4===c.rgba.length&&4===f.rgba.length&& "select"!==a.state&&(clearTimeout(a.colorInterval),a.colorInterval=setInterval(function(){var k=(new Date-b)/d,h=a.graphic;1<k&&(k=1);h&&h.attr("fill",p.prototype.tweenColors.call(0,f,c,k));1<=k&&clearTimeout(a.colorInterval)},13),a.isFading=!0);g.prototype.onMouseOut.call(a);a.isFading=null},zoomTo:function(){var a=this.series;a.xAxis.setExtremes(this._minX,this._maxX,!1);a.yAxis.setExtremes(this._minY,this._maxY,!1);a.chart.redraw()}},l))})(y);(function(a){var m=a.seriesType,p=a.seriesTypes;m("mapline", "map",{lineWidth:1,fillColor:"none"},{type:"mapline",colorProp:"stroke",pointAttrToOptions:{stroke:"color","stroke-width":"lineWidth"},pointAttribs:function(a,e){a=p.map.prototype.pointAttribs.call(this,a,e);a.fill=this.options.fillColor;return a},drawLegendSymbol:p.line.prototype.drawLegendSymbol})})(y);(function(a){var m=a.merge,p=a.Point;a=a.seriesType;a("mappoint","scatter",{dataLabels:{enabled:!0,formatter:function(){return this.point.name},crop:!1,defer:!1,overflow:!1,style:{color:"#000000"}}}, {type:"mappoint",forceDL:!0},{applyOptions:function(a,e){a=void 0!==a.lat&&void 0!==a.lon?m(a,this.series.chart.fromLatLonToPoint(a)):a;return p.prototype.applyOptions.call(this,a,e)}})})(y);(function(a){var m=a.arrayMax,p=a.arrayMin,l=a.Axis,e=a.color,q=a.each,w=a.isNumber,x=a.noop,v=a.pick,d=a.pInt,b=a.Point,c=a.Series,g=a.seriesType,t=a.seriesTypes;g("bubble","scatter",{dataLabels:{formatter:function(){return this.point.z},inside:!0,verticalAlign:"middle"},marker:{lineColor:null,lineWidth:1,radius:null, states:{hover:{radiusPlus:0}},symbol:"circle"},minSize:8,maxSize:"20%",softThreshold:!1,states:{hover:{halo:{size:5}}},tooltip:{pointFormat:"({point.x}, {point.y}), Size: {point.z}"},turboThreshold:0,zThreshold:0,zoneAxis:"z"},{pointArrayMap:["y","z"],parallelArrays:["x","y","z"],trackerGroups:["markerGroup","dataLabelsGroup"],bubblePadding:!0,zoneAxis:"z",pointAttribs:function(a,b){var f=v(this.options.marker.fillOpacity,.5);a=c.prototype.pointAttribs.call(this,a,b);1!==f&&(a.fill=e(a.fill).setOpacity(f).get("rgba")); return a},getRadii:function(a,b,c,d){var f,k,g,n=this.zData,e=[],r=this.options,t="width"!==r.sizeBy,l=r.zThreshold,m=b-a;k=0;for(f=n.length;k<f;k++)g=n[k],r.sizeByAbsoluteValue&&null!==g&&(g=Math.abs(g-l),b=Math.max(b-l,Math.abs(a-l)),a=0),null===g?g=null:g<a?g=c/2-1:(g=0<m?(g-a)/m:.5,t&&0<=g&&(g=Math.sqrt(g)),g=Math.ceil(c+g*(d-c))/2),e.push(g);this.radii=e},animate:function(a){var b=this.options.animation;a||(q(this.points,function(a){var c=a.graphic,f;c&&c.width&&(f={x:c.x,y:c.y,width:c.width, height:c.height},c.attr({x:a.plotX,y:a.plotY,width:1,height:1}),c.animate(f,b))}),this.animate=null)},translate:function(){var b,c=this.data,d,g,h=this.radii;t.scatter.prototype.translate.call(this);for(b=c.length;b--;)d=c[b],g=h?h[b]:0,w(g)&&g>=this.minPxSize/2?(d.marker=a.extend(d.marker,{radius:g,width:2*g,height:2*g}),d.dlBox={x:d.plotX-g,y:d.plotY-g,width:2*g,height:2*g}):d.shapeArgs=d.plotY=d.dlBox=void 0},alignDataLabel:t.column.prototype.alignDataLabel,buildKDTree:x,applyZones:x},{haloPath:function(a){return b.prototype.haloPath.call(this, 0===a?0:(this.marker?this.marker.radius||0:0)+a)},ttBelow:!1});l.prototype.beforePadding=function(){var a=this,b=this.len,c=this.chart,g=0,h=b,e=this.isXAxis,t=e?"xData":"yData",l=this.min,x={},y=Math.min(c.plotWidth,c.plotHeight),D=Number.MAX_VALUE,E=-Number.MAX_VALUE,F=this.max-l,C=b/F,G=[];q(this.series,function(b){var g=b.options;!b.bubblePadding||!b.visible&&c.options.chart.ignoreHiddenSeries||(a.allowZoomOutside=!0,G.push(b),e&&(q(["minSize","maxSize"],function(a){var b=g[a],c=/%$/.test(b), b=d(b);x[a]=c?y*b/100:b}),b.minPxSize=x.minSize,b.maxPxSize=Math.max(x.maxSize,x.minSize),b=b.zData,b.length&&(D=v(g.zMin,Math.min(D,Math.max(p(b),!1===g.displayNegative?g.zThreshold:-Number.MAX_VALUE))),E=v(g.zMax,Math.max(E,m(b))))))});q(G,function(b){var c=b[t],d=c.length,f;e&&b.getRadii(D,E,b.minPxSize,b.maxPxSize);if(0<F)for(;d--;)w(c[d])&&a.dataMin<=c[d]&&c[d]<=a.dataMax&&(f=b.radii[d],g=Math.min((c[d]-l)*C-f,g),h=Math.max((c[d]-l)*C+f,h))});G.length&&0<F&&!this.isLog&&(h-=b,C*=(b+g-h)/b,q([["min", "userMin",g],["max","userMax",h]],function(b){void 0===v(a.options[b[0]],a[b[1]])&&(a[b[0]]+=b[2]/C)}))}})(y);(function(a){var m=a.merge,p=a.Point,l=a.seriesType,e=a.seriesTypes;e.bubble&&l("mapbubble","bubble",{animationLimit:500,tooltip:{pointFormat:"{point.name}: {point.z}"}},{xyFromShape:!0,type:"mapbubble",pointArrayMap:["z"],getMapData:e.map.prototype.getMapData,getBox:e.map.prototype.getBox,setData:e.map.prototype.setData},{applyOptions:function(a,l){return a&&void 0!==a.lat&&void 0!==a.lon? p.prototype.applyOptions.call(this,m(a,this.series.chart.fromLatLonToPoint(a)),l):e.map.prototype.pointClass.prototype.applyOptions.call(this,a,l)},ttBelow:!1})})(y);(function(a){var m=a.colorPointMixin,p=a.each,l=a.merge,e=a.noop,q=a.pick,w=a.Series,x=a.seriesType,v=a.seriesTypes;x("heatmap","scatter",{animation:!1,borderWidth:0,nullColor:"#f7f7f7",dataLabels:{formatter:function(){return this.point.value},inside:!0,verticalAlign:"middle",crop:!1,overflow:!1,padding:0},marker:null,pointRange:null, tooltip:{pointFormat:"{point.x}, {point.y}: {point.value}\x3cbr/\x3e"},states:{normal:{animation:!0},hover:{halo:!1,brightness:.2}}},l(a.colorSeriesMixin,{pointArrayMap:["y","value"],hasPointSpecificOptions:!0,supportsDrilldown:!0,getExtremesFromAll:!0,directTouch:!0,init:function(){var a;v.scatter.prototype.init.apply(this,arguments);a=this.options;a.pointRange=q(a.pointRange,a.colsize||1);this.yAxis.axisPointRange=a.rowsize||1},translate:function(){var a=this.options,b=this.xAxis,c=this.yAxis,g= function(a,b,c){return Math.min(Math.max(b,a),c)};this.generatePoints();p(this.points,function(d){var k=(a.colsize||1)/2,f=(a.rowsize||1)/2,e=g(Math.round(b.len-b.translate(d.x-k,0,1,0,1)),-b.len,2*b.len),k=g(Math.round(b.len-b.translate(d.x+k,0,1,0,1)),-b.len,2*b.len),l=g(Math.round(c.translate(d.y-f,0,1,0,1)),-c.len,2*c.len),f=g(Math.round(c.translate(d.y+f,0,1,0,1)),-c.len,2*c.len);d.plotX=d.clientX=(e+k)/2;d.plotY=(l+f)/2;d.shapeType="rect";d.shapeArgs={x:Math.min(e,k),y:Math.min(l,f),width:Math.abs(k- e),height:Math.abs(f-l)}});this.translateColors()},drawPoints:function(){v.column.prototype.drawPoints.call(this);p(this.points,function(a){a.graphic.attr(this.colorAttribs(a))},this)},animate:e,getBox:e,drawLegendSymbol:a.LegendSymbolMixin.drawRectangle,alignDataLabel:v.column.prototype.alignDataLabel,getExtremes:function(){w.prototype.getExtremes.call(this,this.valueData);this.valueMin=this.dataMin;this.valueMax=this.dataMax;w.prototype.getExtremes.call(this)}}),m)})(y);(function(a){function m(a, b){var c,g,d,e=!1,f=a.x,n=a.y;a=0;for(c=b.length-1;a<b.length;c=a++)g=b[a][1]>n,d=b[c][1]>n,g!==d&&f<(b[c][0]-b[a][0])*(n-b[a][1])/(b[c][1]-b[a][1])+b[a][0]&&(e=!e);return e}var p=a.Chart,l=a.each,e=a.extend,q=a.format,w=a.merge,x=a.win,v=a.wrap;p.prototype.transformFromLatLon=function(d,b){if(void 0===x.proj4)return a.error(21),{x:0,y:null};d=x.proj4(b.crs,[d.lon,d.lat]);var c=b.cosAngle||b.rotation&&Math.cos(b.rotation),g=b.sinAngle||b.rotation&&Math.sin(b.rotation);d=b.rotation?[d[0]*c+d[1]*g, -d[0]*g+d[1]*c]:d;return{x:((d[0]-(b.xoffset||0))*(b.scale||1)+(b.xpan||0))*(b.jsonres||1)+(b.jsonmarginX||0),y:(((b.yoffset||0)-d[1])*(b.scale||1)+(b.ypan||0))*(b.jsonres||1)-(b.jsonmarginY||0)}};p.prototype.transformToLatLon=function(d,b){if(void 0===x.proj4)a.error(21);else{d={x:((d.x-(b.jsonmarginX||0))/(b.jsonres||1)-(b.xpan||0))/(b.scale||1)+(b.xoffset||0),y:((-d.y-(b.jsonmarginY||0))/(b.jsonres||1)+(b.ypan||0))/(b.scale||1)+(b.yoffset||0)};var c=b.cosAngle||b.rotation&&Math.cos(b.rotation), g=b.sinAngle||b.rotation&&Math.sin(b.rotation);b=x.proj4(b.crs,"WGS84",b.rotation?{x:d.x*c+d.y*-g,y:d.x*g+d.y*c}:d);return{lat:b.y,lon:b.x}}};p.prototype.fromPointToLatLon=function(d){var b=this.mapTransforms,c;if(b){for(c in b)if(b.hasOwnProperty(c)&&b[c].hitZone&&m({x:d.x,y:-d.y},b[c].hitZone.coordinates[0]))return this.transformToLatLon(d,b[c]);return this.transformToLatLon(d,b["default"])}a.error(22)};p.prototype.fromLatLonToPoint=function(d){var b=this.mapTransforms,c,g;if(!b)return a.error(22), {x:0,y:null};for(c in b)if(b.hasOwnProperty(c)&&b[c].hitZone&&(g=this.transformFromLatLon(d,b[c]),m({x:g.x,y:-g.y},b[c].hitZone.coordinates[0])))return g;return this.transformFromLatLon(d,b["default"])};a.geojson=function(a,b,c){var g=[],d=[],k=function(a){var b,c=a.length;d.push("M");for(b=0;b<c;b++)1===b&&d.push("L"),d.push(a[b][0],-a[b][1])};b=b||"map";l(a.features,function(a){var c=a.geometry,f=c.type,c=c.coordinates;a=a.properties;var h;d=[];"map"===b||"mapbubble"===b?("Polygon"===f?(l(c,k), d.push("Z")):"MultiPolygon"===f&&(l(c,function(a){l(a,k)}),d.push("Z")),d.length&&(h={path:d})):"mapline"===b?("LineString"===f?k(c):"MultiLineString"===f&&l(c,k),d.length&&(h={path:d})):"mappoint"===b&&"Point"===f&&(h={x:c[0],y:-c[1]});h&&g.push(e(h,{name:a.name||a.NAME,properties:a}))});c&&a.copyrightShort&&(c.chart.mapCredits=q(c.chart.options.credits.mapText,{geojson:a}),c.chart.mapCreditsFull=q(c.chart.options.credits.mapTextFull,{geojson:a}));return g};v(p.prototype,"addCredits",function(a, b){b=w(!0,this.options.credits,b);this.mapCredits&&(b.href=null);a.call(this,b);this.credits&&this.mapCreditsFull&&this.credits.attr({title:this.mapCreditsFull})})})(y);(function(a){function m(a,b,d,e,f,l,m,h){return["M",a+f,b,"L",a+d-l,b,"C",a+d-l/2,b,a+d,b+l/2,a+d,b+l,"L",a+d,b+e-m,"C",a+d,b+e-m/2,a+d-m/2,b+e,a+d-m,b+e,"L",a+h,b+e,"C",a+h/2,b+e,a,b+e-h/2,a,b+e-h,"L",a,b+f,"C",a,b+f/2,a+f/2,b,a+f,b,"Z"]}var p=a.Chart,l=a.defaultOptions,e=a.each,q=a.extend,w=a.merge,x=a.pick,v=a.Renderer,d=a.SVGRenderer, b=a.VMLRenderer;q(l.lang,{zoomIn:"Zoom in",zoomOut:"Zoom out"});l.mapNavigation={buttonOptions:{alignTo:"plotBox",align:"left",verticalAlign:"top",x:0,width:18,height:18,padding:5,style:{fontSize:"15px",fontWeight:"bold"},theme:{"stroke-width":1,"text-align":"center"}},buttons:{zoomIn:{onclick:function(){this.mapZoom(.5)},text:"+",y:0},zoomOut:{onclick:function(){this.mapZoom(2)},text:"-",y:28}},mouseWheelSensitivity:1.1};a.splitPath=function(a){var b;a=a.replace(/([A-Za-z])/g," $1 ");a=a.replace(/^\s*/, "").replace(/\s*$/,"");a=a.split(/[ ,]+/);for(b=0;b<a.length;b++)/[a-zA-Z]/.test(a[b])||(a[b]=parseFloat(a[b]));return a};a.maps={};d.prototype.symbols.topbutton=function(a,b,d,e,f){return m(a-1,b-1,d,e,f.r,f.r,0,0)};d.prototype.symbols.bottombutton=function(a,b,d,e,f){return m(a-1,b-1,d,e,0,0,f.r,f.r)};v===b&&e(["topbutton","bottombutton"],function(a){b.prototype.symbols[a]=d.prototype.symbols[a]});a.Map=a.mapChart=function(b,d,e){var c="string"===typeof b||b.nodeName,f=arguments[c?1:0],g={endOnTick:!1, visible:!1,minPadding:0,maxPadding:0,startOnTick:!1},l,h=a.getOptions().credits;l=f.series;f.series=null;f=w({chart:{panning:"xy",type:"map"},credits:{mapText:x(h.mapText,' \u00a9 \x3ca href\x3d"{geojson.copyrightUrl}"\x3e{geojson.copyrightShort}\x3c/a\x3e'),mapTextFull:x(h.mapTextFull,"{geojson.copyright}")},tooltip:{followTouchMove:!1},xAxis:g,yAxis:w(g,{reversed:!0})},f,{chart:{inverted:!1,alignTicks:!1}});f.series=l;return c?new p(b,f,e):new p(f,d)}})(y)});
var Keen = require('keen.io'); var wifi = require('wifi-cc3000'); var keen = Keen.configure({ projectId: "542b084ce8759666375da5e5", writeKey: "5eb5ca575ff8bb7108c21fe13a6cd0e81c1e82b8df8d0fdf7d583029a0702cf892dc5a8b8e9b3884c0415d8a3603ce06465b4b7053aee014a8ab25e640af5b8750ea316034afbdc01899177aa55795829a146bc050e609dfd761324cbd6a8a5ef805b2cc14073fbd3dfd7a2bee2727e2", readKey: "f7069f777acb01ea3883696c1cbaca038f37a5615edbaf1535b1a5d28563afafa1d1c85a0807650dc8c2a971f4f28d5b54139277c41c31d700715ff92cb6caad00af478d2426286620d82af20ea055a2673678b571858fcb03f3f836d95995255f48968266508dc1963bfd4c484698fa" }); // src colony modules tls.js var tessel = require('tessel'); var climatelib = require('climate-si7020'); var ambientlib = require('ambient-attx4'); var climate = climatelib.use(tessel.port['A']); var ambient = ambientlib.use(tessel.port['B']); //------------------------------------------------ // Climate Temp and Humidity //------------------------------------------------ climate.on('ready', function () { console.log('Connected to si7020'); ambient.on('ready', function () { // Loop forever setInterval(function () { climate.readTemperature('f', function (err, temp) { climate.readHumidity(function (err, humid) { ambient.getLightLevel( function (err, light) { ambient.getSoundLevel( function (err, sound) { console.log('Degrees:', temp.toFixed(4) + 'F', 'Humidity:', humid.toFixed(4) + '%RH'); console.log("Light level:", light.toFixed(8), " ", "Sound Level:", sound.toFixed(8)); if (wifi.isConnected()) { sendToCloud(temp, humid, light, sound, function(){ setTimeout(loop, 10000); }); } else { console.log("nope not connected"); setTimeout(loop, 10000); } }); }); }); }); }, 500); ambient.setLightTrigger(0.5); // Set a light level trigger // The trigger is a float between 0 and 1 ambient.on('light-trigger', function(data) { console.log("Our light trigger was hit:", data); if (wifi.isConnected()) { sendLightTrigger(data); } else { console.log("nope not connected"); } // Clear the trigger so it stops firing ambient.clearLightTrigger(); //After 1.5 seconds reset light trigger setTimeout(function () { ambient.setLightTrigger(0.5); },1500); }); // Set a sound level trigger // The trigger is a float between 0 and 1 ambient.setSoundTrigger(0.1); ambient.on('sound-trigger', function(data) { console.log("Something happened with sound: ", data); if (wifi.isConnected()) { sendSoundTrigger(data); } else { console.log("nope not connected"); } // Clear it ambient.clearSoundTrigger(); //After 1.5 seconds reset sound trigger setTimeout(function () { ambient.setSoundTrigger(0.1); },1500); }); }); }); climate.on('error', function(err) { console.log('error connecting module', err); }); ambient.on('error', function (err) { console.log(err); }); function sendToCloud(tdata, hdata, ldata, sdata, cb){ keen.addEvent("climate", { "temp": tdata, "humidity": hdata, "light": ldata, "sound": sdata }, function(){ console.log("added event"); cb(); }); } function sendLightTrigger(data){ keen.addEvent("climate", { "light-trigger": data }, function(){ console.log("added event"); }); } function sendSoundTrigger(data){ keen.addEvent("climate", { "sound-trigger": data }, function(){ console.log("added event"); }); } wifi.on('disconnect', function(){ console.log("disconnected, trying to reconnect"); wifi.connect({ ssid: 'technicallyWifi', password:'scriptstick' }); });
/* * Translated default messages for the jQuery validation plugin. * Locale: NL */ jQuery.extend(jQuery.validator.messages, { required: "Dit is een verplicht veld.", remote: "Controleer dit veld.", email: "Vul hier een geldig e-mailadres in.", url: "Vul hier een geldige URL in.", date: "Vul hier een geldige datum in.", dateISO: "Vul hier een geldige datum in (ISO-formaat).", number: "Vul hier een geldig getal in.", digits: "Vul hier alleen getallen in.", creditcard: "Vul hier een geldig creditcardnummer in.", equalTo: "Vul hier dezelfde waarde in.", accept: "Vul hier een waarde in met een geldige extensie.", maxlength: jQuery.validator.format("Vul hier maximaal {0} tekens in."), minlength: jQuery.validator.format("Vul hier minimaal {0} tekens in."), rangelength: jQuery.validator.format("Vul hier een waarde in van minimaal {0} en maximaal {1} tekens."), range: jQuery.validator.format("Vul hier een waarde in van minimaal {0} en maximaal {1}."), max: jQuery.validator.format("Vul hier een waarde in kleiner dan of gelijk aan {0}."), min: jQuery.validator.format("Vul hier een waarde in groter dan of gelijk aan {0}.") });
(function e(t,n,r){function s(o,u){if(!n[o]){if(!t[o]){var a=typeof require=="function"&&require;if(!u&&a)return a(o,!0);if(i)return i(o,!0);var f=new Error("Cannot find module '"+o+"'");throw f.code="MODULE_NOT_FOUND",f}var l=n[o]={exports:{}};t[o][0].call(l.exports,function(e){var n=t[o][1][e];return s(n?n:e)},l,l.exports,e,t,n,r)}return n[o].exports}var i=typeof require=="function"&&require;for(var o=0;o<r.length;o++)s(r[o]);return s})({1:[function(_dereq_,module,exports){ var Core = _dereq_('./core'), View = _dereq_('../lib/View'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/View":33,"./core":2}],2:[function(_dereq_,module,exports){ var Core = _dereq_('../lib/Core'), ShimIE8 = _dereq_('../lib/Shim.IE8'); if (typeof window !== 'undefined') { window.ForerunnerDB = Core; } module.exports = Core; },{"../lib/Core":7,"../lib/Shim.IE8":32}],3:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver; /** * Creates an always-sorted multi-key bucket that allows ForerunnerDB to * know the index that a document will occupy in an array with minimal * processing, speeding up things like sorted views. * @param {object} orderBy An order object. * @constructor */ var ActiveBucket = function (orderBy) { this._primaryKey = '_id'; this._keyArr = []; this._data = []; this._objLookup = {}; this._count = 0; this._keyArr = sharedPathSolver.parse(orderBy, true); }; Shared.addModule('ActiveBucket', ActiveBucket); Shared.mixin(ActiveBucket.prototype, 'Mixin.Sorting'); sharedPathSolver = new Path(); /** * Gets / sets the primary key used by the active bucket. * @returns {String} The current primary key. */ Shared.synthesize(ActiveBucket.prototype, 'primaryKey'); /** * Quicksorts a single document into the passed array and * returns the index that the document should occupy. * @param {object} obj The document to calculate index for. * @param {array} arr The array the document index will be * calculated for. * @param {string} item The string key representation of the * document whose index is being calculated. * @param {function} fn The comparison function that is used * to determine if a document is sorted below or above the * document we are calculating the index for. * @returns {number} The index the document should occupy. */ ActiveBucket.prototype.qs = function (obj, arr, item, fn) { // If the array is empty then return index zero if (!arr.length) { return 0; } var lastMidwayIndex = -1, midwayIndex, lookupItem, result, start = 0, end = arr.length - 1; // Loop the data until our range overlaps while (end >= start) { // Calculate the midway point (divide and conquer) midwayIndex = Math.floor((start + end) / 2); if (lastMidwayIndex === midwayIndex) { // No more items to scan break; } // Get the item to compare against lookupItem = arr[midwayIndex]; if (lookupItem !== undefined) { // Compare items result = fn(this, obj, item, lookupItem); if (result > 0) { start = midwayIndex + 1; } if (result < 0) { end = midwayIndex - 1; } } lastMidwayIndex = midwayIndex; } if (result > 0) { return midwayIndex + 1; } else { return midwayIndex; } }; /** * Calculates the sort position of an item against another item. * @param {object} sorter An object or instance that contains * sortAsc and sortDesc methods. * @param {object} obj The document to compare. * @param {string} a The first key to compare. * @param {string} b The second key to compare. * @returns {number} Either 1 for sort a after b or -1 to sort * a before b. * @private */ ActiveBucket.prototype._sortFunc = function (sorter, obj, a, b) { var aVals = a.split('.:.'), bVals = b.split('.:.'), arr = sorter._keyArr, count = arr.length, index, sortType, castType; for (index = 0; index < count; index++) { sortType = arr[index]; castType = typeof sharedPathSolver.get(obj, sortType.path); if (castType === 'number') { aVals[index] = Number(aVals[index]); bVals[index] = Number(bVals[index]); } // Check for non-equal items if (aVals[index] !== bVals[index]) { // Return the sorted items if (sortType.value === 1) { return sorter.sortAsc(aVals[index], bVals[index]); } if (sortType.value === -1) { return sorter.sortDesc(aVals[index], bVals[index]); } } } }; /** * Inserts a document into the active bucket. * @param {object} obj The document to insert. * @returns {number} The index the document now occupies. */ ActiveBucket.prototype.insert = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Insert key keyIndex = this.qs(obj, this._data, key, this._sortFunc); this._data.splice(keyIndex, 0, key); } else { this._data.splice(keyIndex, 0, key); } this._objLookup[obj[this._primaryKey]] = key; this._count++; return keyIndex; }; /** * Removes a document from the active bucket. * @param {object} obj The document to remove. * @returns {boolean} True if the document was removed * successfully or false if it wasn't found in the active * bucket. */ ActiveBucket.prototype.remove = function (obj) { var key, keyIndex; key = this._objLookup[obj[this._primaryKey]]; if (key) { keyIndex = this._data.indexOf(key); if (keyIndex > -1) { this._data.splice(keyIndex, 1); delete this._objLookup[obj[this._primaryKey]]; this._count--; return true; } else { return false; } } return false; }; /** * Get the index that the passed document currently occupies * or the index it will occupy if added to the active bucket. * @param {object} obj The document to get the index for. * @returns {number} The index. */ ActiveBucket.prototype.index = function (obj) { var key, keyIndex; key = this.documentKey(obj); keyIndex = this._data.indexOf(key); if (keyIndex === -1) { // Get key index keyIndex = this.qs(obj, this._data, key, this._sortFunc); } return keyIndex; }; /** * The key that represents the passed document. * @param {object} obj The document to get the key for. * @returns {string} The document key. */ ActiveBucket.prototype.documentKey = function (obj) { var key = '', arr = this._keyArr, count = arr.length, index, sortType; for (index = 0; index < count; index++) { sortType = arr[index]; if (key) { key += '.:.'; } key += sharedPathSolver.get(obj, sortType.path); } // Add the unique identifier on the end of the key key += '.:.' + obj[this._primaryKey]; return key; }; /** * Get the number of documents currently indexed in the active * bucket instance. * @returns {number} The number of documents. */ ActiveBucket.prototype.count = function () { return this._count; }; Shared.finishModule('ActiveBucket'); module.exports = ActiveBucket; },{"./Path":28,"./Shared":31}],4:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), sharedPathSolver = new Path(); var BinaryTree = function (data, compareFunc, hashFunc) { this.init.apply(this, arguments); }; BinaryTree.prototype.init = function (data, index, primaryKey, compareFunc, hashFunc) { this._store = []; this._keys = []; if (primaryKey !== undefined) { this.primaryKey(primaryKey); } if (index !== undefined) { this.index(index); } if (compareFunc !== undefined) { this.compareFunc(compareFunc); } if (hashFunc !== undefined) { this.hashFunc(hashFunc); } if (data !== undefined) { this.data(data); } }; Shared.addModule('BinaryTree', BinaryTree); Shared.mixin(BinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(BinaryTree.prototype, 'Mixin.Sorting'); Shared.mixin(BinaryTree.prototype, 'Mixin.Common'); Shared.synthesize(BinaryTree.prototype, 'compareFunc'); Shared.synthesize(BinaryTree.prototype, 'hashFunc'); Shared.synthesize(BinaryTree.prototype, 'indexDir'); Shared.synthesize(BinaryTree.prototype, 'primaryKey'); Shared.synthesize(BinaryTree.prototype, 'keys'); Shared.synthesize(BinaryTree.prototype, 'index', function (index) { if (index !== undefined) { if (this.debug()) { console.log('Setting index', index, sharedPathSolver.parse(index, true)); } // Convert the index object to an array of key val objects this.keys(sharedPathSolver.parse(index, true)); } return this.$super.call(this, index); }); /** * Remove all data from the binary tree. */ BinaryTree.prototype.clear = function () { delete this._data; delete this._left; delete this._right; this._store = []; }; /** * Sets this node's data object. All further inserted documents that * match this node's key and value will be pushed via the push() * method into the this._store array. When deciding if a new data * should be created left, right or middle (pushed) of this node the * new data is checked against the data set via this method. * @param val * @returns {*} */ BinaryTree.prototype.data = function (val) { if (val !== undefined) { this._data = val; if (this._hashFunc) { this._hash = this._hashFunc(val); } return this; } return this._data; }; /** * Pushes an item to the binary tree node's store array. * @param {*} val The item to add to the store. * @returns {*} */ BinaryTree.prototype.push = function (val) { if (val !== undefined) { this._store.push(val); return this; } return false; }; /** * Pulls an item from the binary tree node's store array. * @param {*} val The item to remove from the store. * @returns {*} */ BinaryTree.prototype.pull = function (val) { if (val !== undefined) { var index = this._store.indexOf(val); if (index > -1) { this._store.splice(index, 1); return this; } } return false; }; /** * Default compare method. Can be overridden. * @param a * @param b * @returns {number} * @private */ BinaryTree.prototype._compareFunc = function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (indexData.value === 1) { result = this.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = this.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (this.debug()) { console.log('Compared %s with %s order %d in path %s and result was %d', sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path), indexData.value, indexData.path, result); } if (result !== 0) { if (this.debug()) { console.log('Retuning result %d', result); } return result; } } if (this.debug()) { console.log('Retuning result %d', result); } return result; }; /** * Default hash function. Can be overridden. * @param obj * @private */ BinaryTree.prototype._hashFunc = function (obj) { /*var i, indexData, hash = ''; for (i = 0; i < this._keys.length; i++) { indexData = this._keys[i]; if (hash) { hash += '_'; } hash += obj[indexData.path]; } return hash;*/ return obj[this._keys[0].path]; }; /** * Removes (deletes reference to) either left or right child if the passed * node matches one of them. * @param {BinaryTree} node The node to remove. */ BinaryTree.prototype.removeChildNode = function (node) { if (this._left === node) { // Remove left delete this._left; } else if (this._right === node) { // Remove right delete this._right; } }; /** * Returns the branch this node matches (left or right). * @param node * @returns {String} */ BinaryTree.prototype.nodeBranch = function (node) { if (this._left === node) { return 'left'; } else if (this._right === node) { return 'right'; } }; /** * Inserts a document into the binary tree. * @param data * @returns {*} */ BinaryTree.prototype.insert = function (data) { var result, inserted, failed, i; if (data instanceof Array) { // Insert array of data inserted = []; failed = []; for (i = 0; i < data.length; i++) { if (this.insert(data[i])) { inserted.push(data[i]); } else { failed.push(data[i]); } } return { inserted: inserted, failed: failed }; } if (this.debug()) { console.log('Inserting', data); } if (!this._data) { if (this.debug()) { console.log('Node has no data, setting data', data); } // Insert into this node (overwrite) as there is no data this.data(data); //this.push(data); return true; } result = this._compareFunc(this._data, data); if (result === 0) { if (this.debug()) { console.log('Data is equal (currrent, new)', this._data, data); } //this.push(data); // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } if (result === -1) { if (this.debug()) { console.log('Data is greater (currrent, new)', this._data, data); } // Greater than this node if (this._right) { // Propagate down the right branch this._right.insert(data); } else { // Assign to right branch this._right = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._right._parent = this; } return true; } if (result === 1) { if (this.debug()) { console.log('Data is less (currrent, new)', this._data, data); } // Less than this node if (this._left) { // Propagate down the left branch this._left.insert(data); } else { // Assign to left branch this._left = new BinaryTree(data, this._index, this._binaryTree, this._compareFunc, this._hashFunc); this._left._parent = this; } return true; } return false; }; BinaryTree.prototype.remove = function (data) { var pk = this.primaryKey(), result, removed, i; if (data instanceof Array) { // Insert array of data removed = []; for (i = 0; i < data.length; i++) { if (this.remove(data[i])) { removed.push(data[i]); } } return removed; } if (this.debug()) { console.log('Removing', data); } if (this._data[pk] === data[pk]) { // Remove this node return this._remove(this); } // Compare the data to work out which branch to send the remove command down result = this._compareFunc(this._data, data); if (result === -1 && this._right) { return this._right.remove(data); } if (result === 1 && this._left) { return this._left.remove(data); } return false; }; BinaryTree.prototype._remove = function (node) { var leftNode, rightNode; if (this._left) { // Backup branch data leftNode = this._left; rightNode = this._right; // Copy data from left node this._left = leftNode._left; this._right = leftNode._right; this._data = leftNode._data; this._store = leftNode._store; if (rightNode) { // Attach the rightNode data to the right-most node // of the leftNode leftNode.rightMost()._right = rightNode; } } else if (this._right) { // Backup branch data rightNode = this._right; // Copy data from right node this._left = rightNode._left; this._right = rightNode._right; this._data = rightNode._data; this._store = rightNode._store; } else { this.clear(); } return true; }; BinaryTree.prototype.leftMost = function () { if (!this._left) { return this; } else { return this._left.leftMost(); } }; BinaryTree.prototype.rightMost = function () { if (!this._right) { return this; } else { return this._right.rightMost(); } }; /** * Searches the binary tree for all matching documents based on the data * passed (query). * @param data * @param options * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.lookup = function (data, options, resultArr) { var result = this._compareFunc(this._data, data); resultArr = resultArr || []; if (result === 0) { if (this._left) { this._left.lookup(data, options, resultArr); } resultArr.push(this._data); if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === -1) { if (this._right) { this._right.lookup(data, options, resultArr); } } if (result === 1) { if (this._left) { this._left.lookup(data, options, resultArr); } } return resultArr; }; /** * Returns the entire binary tree ordered. * @param {String} type * @param resultArr * @returns {*|Array} */ BinaryTree.prototype.inOrder = function (type, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.inOrder(type, resultArr); } switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } if (this._right) { this._right.inOrder(type, resultArr); } return resultArr; }; /** * Searches the binary tree for all matching documents based on the regular * expression passed. * @param path * @param val * @param regex * @param {Array=} resultArr The results passed between recursive calls. * Do not pass anything into this argument when calling externally. * @returns {*|Array} */ BinaryTree.prototype.startsWith = function (path, val, regex, resultArr) { var reTest, thisDataPathVal = sharedPathSolver.get(this._data, path), thisDataPathValSubStr = thisDataPathVal.substr(0, val.length), result; regex = regex || new RegExp('^' + val); resultArr = resultArr || []; if (resultArr._visited === undefined) { resultArr._visited = 0; } resultArr._visited++; result = this.sortAsc(thisDataPathVal, val); reTest = thisDataPathValSubStr === val; if (result === 0) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === -1) { if (reTest) { resultArr.push(this._data); } if (this._right) { this._right.startsWith(path, val, regex, resultArr); } } if (result === 1) { if (this._left) { this._left.startsWith(path, val, regex, resultArr); } if (reTest) { resultArr.push(this._data); } } return resultArr; }; /*BinaryTree.prototype.find = function (type, search, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.find(type, search, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.find(type, search, resultArr); } return resultArr; };*/ /** * * @param {String} type * @param {String} key The data key / path to range search against. * @param {Number} from Range search from this value (inclusive) * @param {Number} to Range search to this value (inclusive) * @param {Array=} resultArr Leave undefined when calling (internal use), * passes the result array between recursive calls to be returned when * the recursion chain completes. * @param {Path=} pathResolver Leave undefined when calling (internal use), * caches the path resolver instance for performance. * @returns {Array} Array of matching document objects */ BinaryTree.prototype.findRange = function (type, key, from, to, resultArr, pathResolver) { resultArr = resultArr || []; pathResolver = pathResolver || new Path(key); if (this._left) { this._left.findRange(type, key, from, to, resultArr, pathResolver); } // Check if this node's data is greater or less than the from value var pathVal = pathResolver.value(this._data), fromResult = this.sortAsc(pathVal, from), toResult = this.sortAsc(pathVal, to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRange(type, key, from, to, resultArr, pathResolver); } return resultArr; }; /*BinaryTree.prototype.findRegExp = function (type, key, pattern, resultArr) { resultArr = resultArr || []; if (this._left) { this._left.findRegExp(type, key, pattern, resultArr); } // Check if this node's data is greater or less than the from value var fromResult = this.sortAsc(this._data[key], from), toResult = this.sortAsc(this._data[key], to); if ((fromResult === 0 || fromResult === 1) && (toResult === 0 || toResult === -1)) { // This data node is greater than or equal to the from value, // and less than or equal to the to value so include it switch (type) { case 'hash': resultArr.push(this._hash); break; case 'data': resultArr.push(this._data); break; default: resultArr.push({ key: this._data, arr: this._store }); break; } } if (this._right) { this._right.findRegExp(type, key, pattern, resultArr); } return resultArr; };*/ /** * Determines if the passed query and options object will be served * by this index successfully or not and gives a score so that the * DB search system can determine how useful this index is in comparison * to other indexes on the same collection. * @param query * @param queryOptions * @param matchOptions * @returns {{matchedKeys: Array, totalKeyCount: Number, score: number}} */ BinaryTree.prototype.match = function (query, queryOptions, matchOptions) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var indexKeyArr, queryArr, matchedKeys = [], matchedKeyCount = 0, i; indexKeyArr = sharedPathSolver.parseArr(this._index, { verbose: true }); queryArr = sharedPathSolver.parseArr(query, matchOptions && matchOptions.pathOptions ? matchOptions.pathOptions : { ignore:/\$/, verbose: true }); // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return sharedPathSolver.countObjectPaths(this._keys, query); }; Shared.finishModule('BinaryTree'); module.exports = BinaryTree; },{"./Path":28,"./Shared":31}],5:[function(_dereq_,module,exports){ "use strict"; var Shared, Db, Metrics, KeyValueStore, Path, IndexHashMap, IndexBinaryTree, Index2d, Crc, Overload, ReactorIO, sharedPathSolver; Shared = _dereq_('./Shared'); /** * Creates a new collection. Collections store multiple documents and * handle CRUD against those documents. * @constructor */ var Collection = function (name) { this.init.apply(this, arguments); }; Collection.prototype.init = function (name, options) { this._primaryKey = '_id'; this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._name = name; this._data = []; this._metrics = new Metrics(); this._options = options || { changeTimestamp: false }; if (this._options.db) { this.db(this._options.db); } // Create an object to store internal protected data this._metaData = {}; this._deferQueue = { insert: [], update: [], remove: [], upsert: [], async: [] }; this._deferThreshold = { insert: 100, update: 100, remove: 100, upsert: 100 }; this._deferTime = { insert: 1, update: 1, remove: 1, upsert: 1 }; this._deferredCalls = true; // Set the subset to itself since it is the root collection this.subsetOf(this); }; Shared.addModule('Collection', Collection); Shared.mixin(Collection.prototype, 'Mixin.Common'); Shared.mixin(Collection.prototype, 'Mixin.Events'); Shared.mixin(Collection.prototype, 'Mixin.ChainReactor'); Shared.mixin(Collection.prototype, 'Mixin.CRUD'); Shared.mixin(Collection.prototype, 'Mixin.Constants'); Shared.mixin(Collection.prototype, 'Mixin.Triggers'); Shared.mixin(Collection.prototype, 'Mixin.Sorting'); Shared.mixin(Collection.prototype, 'Mixin.Matching'); Shared.mixin(Collection.prototype, 'Mixin.Updating'); Shared.mixin(Collection.prototype, 'Mixin.Tags'); Metrics = _dereq_('./Metrics'); KeyValueStore = _dereq_('./KeyValueStore'); Path = _dereq_('./Path'); IndexHashMap = _dereq_('./IndexHashMap'); IndexBinaryTree = _dereq_('./IndexBinaryTree'); Index2d = _dereq_('./Index2d'); Crc = _dereq_('./Crc'); Db = Shared.modules.Db; Overload = _dereq_('./Overload'); ReactorIO = _dereq_('./ReactorIO'); sharedPathSolver = new Path(); /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Collection.prototype.crc = Crc; /** * Gets / sets the deferred calls flag. If set to true (default) * then operations on large data sets can be broken up and done * over multiple CPU cycles (creating an async state). For purely * synchronous behaviour set this to false. * @param {Boolean=} val The value to set. * @returns {Boolean} */ Shared.synthesize(Collection.prototype, 'deferredCalls'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'state'); /** * Gets / sets the name of the collection. * @param {String=} val The name of the collection to set. * @returns {*} */ Shared.synthesize(Collection.prototype, 'name'); /** * Gets / sets the metadata stored in the collection. */ Shared.synthesize(Collection.prototype, 'metaData'); /** * Gets / sets boolean to determine if the collection should be * capped or not. */ Shared.synthesize(Collection.prototype, 'capped'); /** * Gets / sets capped collection size. This is the maximum number * of records that the capped collection will store. */ Shared.synthesize(Collection.prototype, 'cappedSize'); Collection.prototype._asyncPending = function (key) { this._deferQueue.async.push(key); }; Collection.prototype._asyncComplete = function (key) { // Remove async flag for this type var index = this._deferQueue.async.indexOf(key); while (index > -1) { this._deferQueue.async.splice(index, 1); index = this._deferQueue.async.indexOf(key); } if (this._deferQueue.async.length === 0) { this.deferEmit('ready'); } }; /** * Get the data array that represents the collection's data. * This data is returned by reference and should not be altered outside * of the provided CRUD functionality of the collection as doing so * may cause unstable index behaviour within the collection. * @returns {Array} */ Collection.prototype.data = function () { return this._data; }; /** * Drops a collection and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ Collection.prototype.drop = function (callback) { var key; if (!this.isDropped()) { if (this._db && this._db._collection && this._name) { if (this.debug()) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; this.emit('drop', this); delete this._db._collection[this._name]; // Remove any reactor IO chain links if (this._collate) { for (key in this._collate) { if (this._collate.hasOwnProperty(key)) { this.collateRemove(key); } } } delete this._primaryKey; delete this._primaryIndex; delete this._primaryCrc; delete this._crcLookup; delete this._name; delete this._data; delete this._metrics; delete this._listeners; if (callback) { callback(false, true); } return true; } } else { if (callback) { callback(false, true); } return true; } if (callback) { callback(false, true); } return false; }; /** * Gets / sets the primary key for this collection. * @param {String=} keyName The name of the primary key. * @returns {*} */ Collection.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { if (this._primaryKey !== keyName) { var oldKey = this._primaryKey; this._primaryKey = keyName; // Set the primary key index primary key this._primaryIndex.primaryKey(keyName); // Rebuild the primary key index this.rebuildPrimaryKeyIndex(); // Propagate change down the chain this.chainSend('primaryKey', keyName, {oldData: oldKey}); } return this; } return this._primaryKey; }; /** * Handles insert events and routes changes to binds and views as required. * @param {Array} inserted An array of inserted documents. * @param {Array} failed An array of documents that failed to insert. * @private */ Collection.prototype._onInsert = function (inserted, failed) { this.emit('insert', inserted, failed); }; /** * Handles update events and routes changes to binds and views as required. * @param {Array} items An array of updated documents. * @private */ Collection.prototype._onUpdate = function (items) { this.emit('update', items); }; /** * Handles remove events and routes changes to binds and views as required. * @param {Array} items An array of removed documents. * @private */ Collection.prototype._onRemove = function (items) { this.emit('remove', items); }; /** * Handles any change to the collection. * @private */ Collection.prototype._onChange = function () { if (this._options.changeTimestamp) { // Record the last change timestamp this._metaData.lastChange = new Date(); } }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(Collection.prototype, 'db', function (db) { if (db) { if (this.primaryKey() === '_id') { // Set primary key to the db's key by default this.primaryKey(db.primaryKey()); // Apply the same debug settings this.debug(db.debug()); } } return this.$super.apply(this, arguments); }); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Collection.prototype, 'mongoEmulation'); /** * Sets the collection's data to the array / documents passed. If any * data already exists in the collection it will be removed before the * new data is set. * @param {Array|Object} data The array of documents or a single document * that will be set as the collections data. * @param options Optional options object. * @param callback Optional callback function. */ Collection.prototype.setData = function (data, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (data) { var op = this._metrics.create('setData'); op.start(); options = this.options(options); this.preSetData(data, options, callback); if (options.$decouple) { data = this.decouple(data); } if (!(data instanceof Array)) { data = [data]; } op.time('transformIn'); data = this.transformIn(data); op.time('transformIn'); var oldData = [].concat(this._data); this._dataReplace(data); // Update the primary key index op.time('Rebuild Primary Key Index'); this.rebuildPrimaryKeyIndex(options); op.time('Rebuild Primary Key Index'); // Rebuild all other indexes op.time('Rebuild All Other Indexes'); this._rebuildIndexes(); op.time('Rebuild All Other Indexes'); op.time('Resolve chains'); this.chainSend('setData', data, {oldData: oldData}); op.time('Resolve chains'); op.stop(); this._onChange(); this.emit('setData', this._data, oldData); } if (callback) { callback(false); } return this; }; /** * Drops and rebuilds the primary key index for all documents in the collection. * @param {Object=} options An optional options object. * @private */ Collection.prototype.rebuildPrimaryKeyIndex = function (options) { options = options || { $ensureKeys: undefined, $violationCheck: undefined }; var ensureKeys = options && options.$ensureKeys !== undefined ? options.$ensureKeys : true, violationCheck = options && options.$violationCheck !== undefined ? options.$violationCheck : true, arr, arrCount, arrItem, pIndex = this._primaryIndex, crcIndex = this._primaryCrc, crcLookup = this._crcLookup, pKey = this._primaryKey, jString; // Drop the existing primary index pIndex.truncate(); crcIndex.truncate(); crcLookup.truncate(); // Loop the data and check for a primary key in each object arr = this._data; arrCount = arr.length; while (arrCount--) { arrItem = arr[arrCount]; if (ensureKeys) { // Make sure the item has a primary key this.ensurePrimaryKey(arrItem); } if (violationCheck) { // Check for primary key violation if (!pIndex.uniqueSet(arrItem[pKey], arrItem)) { // Primary key violation throw(this.logIdentifier() + ' Call to setData on collection failed because your data violates the primary key unique constraint. One or more documents are using the same primary key: ' + arrItem[this._primaryKey]); } } else { pIndex.set(arrItem[pKey], arrItem); } // Generate a CRC string jString = this.jStringify(arrItem); crcIndex.set(arrItem[pKey], jString); crcLookup.set(jString, arrItem); } }; /** * Checks for a primary key on the document and assigns one if none * currently exists. * @param {Object} obj The object to check a primary key against. * @private */ Collection.prototype.ensurePrimaryKey = function (obj) { if (obj[this._primaryKey] === undefined) { // Assign a primary key automatically obj[this._primaryKey] = this.objectId(); } }; /** * Clears all data from the collection. * @returns {Collection} */ Collection.prototype.truncate = function () { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this.emit('truncate', this._data); // Clear all the data from the collection this._data.length = 0; // Re-create the primary index data this._primaryIndex = new KeyValueStore('primary'); this._primaryCrc = new KeyValueStore('primaryCrc'); this._crcLookup = new KeyValueStore('crcLookup'); this._onChange(); this.deferEmit('change', {type: 'truncate'}); return this; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} obj The document object to upsert or an array containing * documents to upsert. * * If the document contains a primary key field (based on the collections's primary * key) then the database will search for an existing document with a matching id. * If a matching document is found, the document will be updated. Any keys that * match keys on the existing document will be overwritten with new data. Any keys * that do not currently exist on the document will be added to the document. * * If the document does not contain an id or the id passed does not match an existing * document, an insert is performed instead. If no id is present a new primary key * id is provided for the item. * * @param {Function=} callback Optional callback method. * @returns {Object} An object containing two keys, "op" contains either "insert" or * "update" depending on the type of operation that was performed and "result" * contains the return data from the operation used. */ Collection.prototype.upsert = function (obj, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (obj) { var queue = this._deferQueue.upsert, deferThreshold = this._deferThreshold.upsert, returnData = {}, query, i; // Determine if the object passed is an array or not if (obj instanceof Array) { if (this._deferredCalls && obj.length > deferThreshold) { // Break up upsert into blocks this._deferQueue.upsert = queue.concat(obj); this._asyncPending('upsert'); // Fire off the insert queue handler this.processQueue('upsert', callback); return {}; } else { // Loop the array and upsert each item returnData = []; for (i = 0; i < obj.length; i++) { returnData.push(this.upsert(obj[i])); } if (callback) { callback(); } return returnData; } } // Determine if the operation is an insert or an update if (obj[this._primaryKey]) { // Check if an object with this primary key already exists query = {}; query[this._primaryKey] = obj[this._primaryKey]; if (this._primaryIndex.lookup(query)[0]) { // The document already exists with this id, this operation is an update returnData.op = 'update'; } else { // No document with this id exists, this operation is an insert returnData.op = 'insert'; } } else { // The document passed does not contain an id, this operation is an insert returnData.op = 'insert'; } switch (returnData.op) { case 'insert': returnData.result = this.insert(obj); break; case 'update': returnData.result = this.update(query, obj); break; default: break; } return returnData; } else { if (callback) { callback(); } } return {}; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ Collection.prototype.filter = function (query, func, options) { return (this.find(query, options)).filter(func); }; /** * Executes a method against each document that matches query and then executes * an update based on the return data of the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the update. * @param {Object=} options Optional options object passed to the initial find call. * @returns {Array} */ Collection.prototype.filterUpdate = function (query, func, options) { var items = this.find(query, options), results = [], singleItem, singleQuery, singleUpdate, pk = this.primaryKey(), i; for (i = 0; i < items.length; i++) { singleItem = items[i]; singleUpdate = func(singleItem); if (singleUpdate) { singleQuery = {}; singleQuery[pk] = singleItem[pk]; results.push(this.update(singleQuery, singleUpdate)); } } return results; }; /** * Modifies an existing document or documents in a collection. This will update * all matches for 'query' with the data held in 'update'. It will not overwrite * the matched documents with the update document. * * @param {Object} query The query that must be matched for a document to be * operated on. * @param {Object} update The object containing updated key/values. Any keys that * match keys on the existing document will be overwritten with this data. Any * keys that do not currently exist on the document will be added to the document. * @param {Object=} options An options object. * @returns {Array} The items that were updated. */ Collection.prototype.update = function (query, update, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // Decouple the update data update = this.decouple(update); // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); this.convertToFdb(update); } // Handle transform update = this.transformIn(update); if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data'); } var self = this, op = this._metrics.create('update'), dataSet, updated, updateCall = function (referencedDoc) { var oldDoc = self.decouple(referencedDoc), newDoc, triggerOperation, result; if (self.willTrigger(self.TYPE_UPDATE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_UPDATE, self.PHASE_AFTER)) { newDoc = self.decouple(referencedDoc); triggerOperation = { type: 'update', query: self.decouple(query), update: self.decouple(update), options: self.decouple(options), op: op }; // Update newDoc with the update criteria so we know what the data will look // like AFTER the update is processed result = self.updateObject(newDoc, triggerOperation.update, triggerOperation.query, triggerOperation.options, ''); if (self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_BEFORE, referencedDoc, newDoc) !== false) { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, newDoc, triggerOperation.query, triggerOperation.options, ''); // NOTE: If for some reason we would only like to fire this event if changes are actually going // to occur on the object from the proposed update then we can add "result &&" to the if self.processTrigger(triggerOperation, self.TYPE_UPDATE, self.PHASE_AFTER, oldDoc, newDoc); } else { // Trigger cancelled operation so tell result that it was not updated result = false; } } else { // No triggers complained so let's execute the replacement of the existing // object with the new one result = self.updateObject(referencedDoc, update, query, options, ''); } // Inform indexes of the change self._updateIndexes(oldDoc, referencedDoc); return result; }; op.start(); op.time('Retrieve documents to update'); dataSet = this.find(query, {$decouple: false}); op.time('Retrieve documents to update'); if (dataSet.length) { op.time('Update documents'); updated = dataSet.filter(updateCall); op.time('Update documents'); if (updated.length) { op.time('Resolve chains'); this.chainSend('update', { query: query, update: update, dataSet: updated }, options); op.time('Resolve chains'); this._onUpdate(updated); this._onChange(); this.deferEmit('change', {type: 'update', data: updated}); } } op.stop(); // TODO: Should we decouple the updated array before return by default? return updated || []; }; /** * Replaces an existing object with data from the new object without * breaking data references. * @param {Object} currentObj The object to alter. * @param {Object} newObj The new object to overwrite the existing one with. * @returns {*} Chain. * @private */ Collection.prototype._replaceObj = function (currentObj, newObj) { var i; // Check if the new document has a different primary key value from the existing one // Remove item from indexes this._removeFromIndexes(currentObj); // Remove existing keys from current object for (i in currentObj) { if (currentObj.hasOwnProperty(i)) { delete currentObj[i]; } } // Add new keys to current object for (i in newObj) { if (newObj.hasOwnProperty(i)) { currentObj[i] = newObj[i]; } } // Update the item in the primary index if (!this._insertIntoIndexes(currentObj)) { throw(this.logIdentifier() + ' Primary key violation in update! Key violated: ' + currentObj[this._primaryKey]); } // Update the object in the collection data //this._data.splice(this._data.indexOf(currentObj), 1, newObj); return this; }; /** * Helper method to update a document from it's id. * @param {String} id The id of the document. * @param {Object} update The object containing the key/values to update to. * @returns {Object} The document that was updated or undefined * if no document was updated. */ Collection.prototype.updateById = function (id, update) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.update(searchObj, update)[0]; }; /** * Internal method for document updating. * @param {Object} doc The document to update. * @param {Object} update The object with key/value pairs to update the document with. * @param {Object} query The query object that we need to match to perform an update. * @param {Object} options An options object. * @param {String} path The current recursive path. * @param {String} opType The type of update operation to perform, if none is specified * default is to set new data against matching fields. * @returns {Boolean} True if the document was updated with new / changed data or * false if it was not updated because the data was the same. * @private */ Collection.prototype.updateObject = function (doc, update, query, options, path, opType) { // TODO: This method is long, try to break it into smaller pieces update = this.decouple(update); // Clear leading dots from path path = path || ''; if (path.substr(0, 1) === '.') { path = path.substr(1, path.length -1); } //var oldDoc = this.decouple(doc), var updated = false, recurseUpdated = false, operation, tmpArray, tmpIndex, tmpCount, tempIndex, tempKey, replaceObj, pk, pathInstance, sourceIsArray, updateIsArray, i; // Loop each key in the update object for (i in update) { if (update.hasOwnProperty(i)) { // Reset operation flag operation = false; // Check if the property starts with a dollar (function) if (i.substr(0, 1) === '$') { // Check for commands switch (i) { case '$key': case '$index': case '$data': case '$min': case '$max': // Ignore some operators operation = true; break; case '$each': operation = true; // Loop over the array of updates and run each one tmpCount = update.$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { recurseUpdated = this.updateObject(doc, update.$each[tmpIndex], query, options, path); if (recurseUpdated) { updated = true; } } updated = updated || recurseUpdated; break; case '$replace': operation = true; replaceObj = update.$replace; pk = this.primaryKey(); // Loop the existing item properties and compare with // the replacement (never remove primary key) for (tempKey in doc) { if (doc.hasOwnProperty(tempKey) && tempKey !== pk) { if (replaceObj[tempKey] === undefined) { // The new document doesn't have this field, remove it from the doc this._updateUnset(doc, tempKey); updated = true; } } } // Loop the new item props and update the doc for (tempKey in replaceObj) { if (replaceObj.hasOwnProperty(tempKey) && tempKey !== pk) { this._updateOverwrite(doc, tempKey, replaceObj[tempKey]); updated = true; } } break; default: operation = true; // Now run the operation recurseUpdated = this.updateObject(doc, update[i], query, options, path, i); updated = updated || recurseUpdated; break; } } // Check if the key has a .$ at the end, denoting an array lookup if (this._isPositionalKey(i)) { operation = true; // Modify i to be the name of the field i = i.substr(0, i.length - 2); pathInstance = new Path(path + '.' + i); // Check if the key is an array and has items if (doc[i] && doc[i] instanceof Array && doc[i].length) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], pathInstance.value(query)[0], options, '', {})) { tmpArray.push(tmpIndex); } } // Loop the items that matched and update them for (tmpIndex = 0; tmpIndex < tmpArray.length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpArray[tmpIndex]], update[i + '.$'], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } } if (!operation) { if (!opType && typeof(update[i]) === 'object') { if (doc[i] !== null && typeof(doc[i]) === 'object') { // Check if we are dealing with arrays sourceIsArray = doc[i] instanceof Array; updateIsArray = update[i] instanceof Array; if (sourceIsArray || updateIsArray) { // Check if the update is an object and the doc is an array if (!updateIsArray && sourceIsArray) { // Update is an object, source is an array so match the array items // with our query object to find the one to update inside this array // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { recurseUpdated = this.updateObject(doc[i][tmpIndex], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { // Either both source and update are arrays or the update is // an array and the source is not, so set source to update if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { // The doc key is an object so traverse the // update further recurseUpdated = this.updateObject(doc[i], update[i], query, options, path + '.' + i, opType); updated = updated || recurseUpdated; } } else { if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } } } else { switch (opType) { case '$inc': var doUpdate = true; // Check for a $min / $max operator if (update[i] > 0) { if (update.$max) { // Check current value if (doc[i] >= update.$max) { // Don't update doUpdate = false; } } } else if (update[i] < 0) { if (update.$min) { // Check current value if (doc[i] <= update.$min) { // Don't update doUpdate = false; } } } if (doUpdate) { this._updateIncrement(doc, i, update[i]); updated = true; } break; case '$cast': // Casts a property to the type specified if it is not already // that type. If the cast is an array or an object and the property // is not already that type a new array or object is created and // set to the property, overwriting the previous value switch (update[i]) { case 'array': if (!(doc[i] instanceof Array)) { // Cast to an array this._updateProperty(doc, i, update.$data || []); updated = true; } break; case 'object': if (!(doc[i] instanceof Object) || (doc[i] instanceof Array)) { // Cast to an object this._updateProperty(doc, i, update.$data || {}); updated = true; } break; case 'number': if (typeof doc[i] !== 'number') { // Cast to a number this._updateProperty(doc, i, Number(doc[i])); updated = true; } break; case 'string': if (typeof doc[i] !== 'string') { // Cast to a string this._updateProperty(doc, i, String(doc[i])); updated = true; } break; default: throw(this.logIdentifier() + ' Cannot update cast to unknown type: ' + update[i]); } break; case '$push': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Check for a $position modifier with an $each if (update[i].$position !== undefined && update[i].$each instanceof Array) { // Grab the position to insert at tempIndex = update[i].$position; // Loop the each array and push each item tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updateSplicePush(doc[i], tempIndex + tmpIndex, update[i].$each[tmpIndex]); } } else if (update[i].$each instanceof Array) { // Do a loop over the each to push multiple items tmpCount = update[i].$each.length; for (tmpIndex = 0; tmpIndex < tmpCount; tmpIndex++) { this._updatePush(doc[i], update[i].$each[tmpIndex]); } } else { // Do a standard push this._updatePush(doc[i], update[i]); } updated = true; } else { throw(this.logIdentifier() + ' Cannot push to a key that is not an array! (' + i + ')'); } break; case '$pull': if (doc[i] instanceof Array) { tmpArray = []; // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { tmpArray.push(tmpIndex); } } tmpCount = tmpArray.length; // Now loop the pull array and remove items to be pulled while (tmpCount--) { this._updatePull(doc[i], tmpArray[tmpCount]); updated = true; } } break; case '$pullAll': if (doc[i] instanceof Array) { if (update[i] instanceof Array) { tmpArray = doc[i]; tmpCount = tmpArray.length; if (tmpCount > 0) { // Now loop the pull array and remove items to be pulled while (tmpCount--) { for (tempIndex = 0; tempIndex < update[i].length; tempIndex++) { if (tmpArray[tmpCount] === update[i][tempIndex]) { this._updatePull(doc[i], tmpCount); tmpCount--; updated = true; } } if (tmpCount < 0) { break; } } } } else { throw(this.logIdentifier() + ' Cannot pullAll without being given an array of values to pull! (' + i + ')'); } } break; case '$addToSet': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { // Loop the target array and check for existence of item var targetArr = doc[i], targetArrIndex, targetArrCount = targetArr.length, objHash, addObj = true, optionObj = (options && options.$addToSet), hashMode, pathSolver; // Check if we have an options object for our operation if (update[i].$key) { hashMode = false; pathSolver = new Path(update[i].$key); objHash = pathSolver.value(update[i])[0]; // Remove the key from the object before we add it delete update[i].$key; } else if (optionObj && optionObj.key) { hashMode = false; pathSolver = new Path(optionObj.key); objHash = pathSolver.value(update[i])[0]; } else { objHash = this.jStringify(update[i]); hashMode = true; } for (targetArrIndex = 0; targetArrIndex < targetArrCount; targetArrIndex++) { if (hashMode) { // Check if objects match via a string hash (JSON) if (this.jStringify(targetArr[targetArrIndex]) === objHash) { // The object already exists, don't add it addObj = false; break; } } else { // Check if objects match based on the path if (objHash === pathSolver.value(targetArr[targetArrIndex])[0]) { // The object already exists, don't add it addObj = false; break; } } } if (addObj) { this._updatePush(doc[i], update[i]); updated = true; } } else { throw(this.logIdentifier() + ' Cannot addToSet on a key that is not an array! (' + i + ')'); } break; case '$splicePush': // Check if the target key is undefined and if so, create an array if (doc[i] === undefined) { // Initialise a new array this._updateProperty(doc, i, []); } // Check that the target key is an array if (doc[i] instanceof Array) { tempIndex = update.$index; if (tempIndex !== undefined) { delete update.$index; // Check for out of bounds index if (tempIndex > doc[i].length) { tempIndex = doc[i].length; } this._updateSplicePush(doc[i], tempIndex, update[i]); updated = true; } else { throw(this.logIdentifier() + ' Cannot splicePush without a $index integer value!'); } } else { throw(this.logIdentifier() + ' Cannot splicePush with a key that is not an array! (' + i + ')'); } break; case '$move': if (doc[i] instanceof Array) { // Loop the array and find matches to our search for (tmpIndex = 0; tmpIndex < doc[i].length; tmpIndex++) { if (this._match(doc[i][tmpIndex], update[i], options, '', {})) { var moveToIndex = update.$index; if (moveToIndex !== undefined) { delete update.$index; this._updateSpliceMove(doc[i], tmpIndex, moveToIndex); updated = true; } else { throw(this.logIdentifier() + ' Cannot move without a $index integer value!'); } break; } } } else { throw(this.logIdentifier() + ' Cannot move on a key that is not an array! (' + i + ')'); } break; case '$mul': this._updateMultiply(doc, i, update[i]); updated = true; break; case '$rename': this._updateRename(doc, i, update[i]); updated = true; break; case '$overwrite': this._updateOverwrite(doc, i, update[i]); updated = true; break; case '$unset': this._updateUnset(doc, i); updated = true; break; case '$clear': this._updateClear(doc, i); updated = true; break; case '$pop': if (doc[i] instanceof Array) { if (this._updatePop(doc[i], update[i])) { updated = true; } } else { throw(this.logIdentifier() + ' Cannot pop from a key that is not an array! (' + i + ')'); } break; case '$toggle': // Toggle the boolean property between true and false this._updateProperty(doc, i, !doc[i]); updated = true; break; default: if (doc[i] !== update[i]) { this._updateProperty(doc, i, update[i]); updated = true; } break; } } } } } return updated; }; /** * Determines if the passed key has an array positional mark (a dollar at the end * of its name). * @param {String} key The key to check. * @returns {Boolean} True if it is a positional or false if not. * @private */ Collection.prototype._isPositionalKey = function (key) { return key.substr(key.length - 2, 2) === '.$'; }; /** * Removes any documents from the collection that match the search query * key/values. * @param {Object} query The query object. * @param {Object=} options An options object. * @param {Function=} callback A callback method. * @returns {Array} An array of the documents that were removed. */ Collection.prototype.remove = function (query, options, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var self = this, dataSet, index, arrIndex, returnArr, removeMethod, triggerOperation, doc, newDoc; if (typeof(options) === 'function') { callback = options; options = {}; } // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (query instanceof Array) { returnArr = []; for (arrIndex = 0; arrIndex < query.length; arrIndex++) { returnArr.push(this.remove(query[arrIndex], {noEmit: true})); } if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } if (callback) { callback(false, returnArr); } return returnArr; } else { returnArr = []; dataSet = this.find(query, {$decouple: false}); if (dataSet.length) { removeMethod = function (dataItem) { // Remove the item from the collection's indexes self._removeFromIndexes(dataItem); // Remove data from internal stores index = self._data.indexOf(dataItem); self._dataRemoveAtIndex(index); returnArr.push(dataItem); }; // Remove the data from the collection for (var i = 0; i < dataSet.length; i++) { doc = dataSet[i]; if (self.willTrigger(self.TYPE_REMOVE, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_REMOVE, self.PHASE_AFTER)) { triggerOperation = { type: 'remove' }; newDoc = self.decouple(doc); if (self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_BEFORE, newDoc, newDoc) !== false) { // The trigger didn't ask to cancel so execute the removal method removeMethod(doc); self.processTrigger(triggerOperation, self.TYPE_REMOVE, self.PHASE_AFTER, newDoc, newDoc); } } else { // No triggers to execute removeMethod(doc); } } if (returnArr.length) { //op.time('Resolve chains'); self.chainSend('remove', { query: query, dataSet: returnArr }, options); //op.time('Resolve chains'); if (!options || (options && !options.noEmit)) { this._onRemove(returnArr); } this._onChange(); this.deferEmit('change', {type: 'remove', data: returnArr}); } } if (callback) { callback(false, returnArr); } return returnArr; } }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. * @returns {Object} The document that was removed or undefined if * nothing was removed. */ Collection.prototype.removeById = function (id) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.remove(searchObj)[0]; }; /** * Processes a deferred action queue. * @param {String} type The queue name to process. * @param {Function} callback A method to call when the queue has processed. * @param {Object=} resultObj A temp object to hold results in. */ Collection.prototype.processQueue = function (type, callback, resultObj) { var self = this, queue = this._deferQueue[type], deferThreshold = this._deferThreshold[type], deferTime = this._deferTime[type], dataArr, result; resultObj = resultObj || { deferred: true }; if (queue.length) { // Process items up to the threshold if (queue.length > deferThreshold) { // Grab items up to the threshold value dataArr = queue.splice(0, deferThreshold); } else { // Grab all the remaining items dataArr = queue.splice(0, queue.length); } result = self[type](dataArr); switch (type) { case 'insert': resultObj.inserted = resultObj.inserted || []; resultObj.failed = resultObj.failed || []; resultObj.inserted = resultObj.inserted.concat(result.inserted); resultObj.failed = resultObj.failed.concat(result.failed); break; } // Queue another process setTimeout(function () { self.processQueue.call(self, type, callback, resultObj); }, deferTime); } else { if (callback) { callback(resultObj); } this._asyncComplete(type); } // Check if all queues are complete if (!this.isProcessingQueue()) { this.deferEmit('queuesComplete'); } }; /** * Checks if any CRUD operations have been deferred and are still waiting to * be processed. * @returns {Boolean} True if there are still deferred CRUD operations to process * or false if all queues are clear. */ Collection.prototype.isProcessingQueue = function () { var i; for (i in this._deferQueue) { if (this._deferQueue.hasOwnProperty(i)) { if (this._deferQueue[i].length) { return true; } } } return false; }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype.insert = function (data, index, callback) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } if (typeof(index) === 'function') { callback = index; index = this._data.length; } else if (index === undefined) { index = this._data.length; } data = this.transformIn(data); return this._insertHandle(data, index, callback); }; /** * Inserts a document or array of documents into the collection. * @param {Object|Array} data Either a document object or array of document * @param {Number=} index Optional index to insert the record at. * @param {Function=} callback Optional callback called once action is complete. * objects to insert into the collection. */ Collection.prototype._insertHandle = function (data, index, callback) { var //self = this, queue = this._deferQueue.insert, deferThreshold = this._deferThreshold.insert, //deferTime = this._deferTime.insert, inserted = [], failed = [], insertResult, resultObj, i; if (data instanceof Array) { // Check if there are more insert items than the insert defer // threshold, if so, break up inserts so we don't tie up the // ui or thread if (this._deferredCalls && data.length > deferThreshold) { // Break up insert into blocks this._deferQueue.insert = queue.concat(data); this._asyncPending('insert'); // Fire off the insert queue handler this.processQueue('insert', callback); return; } else { // Loop the array and add items for (i = 0; i < data.length; i++) { insertResult = this._insert(data[i], index + i); if (insertResult === true) { inserted.push(data[i]); } else { failed.push({ doc: data[i], reason: insertResult }); } } } } else { // Store the data item insertResult = this._insert(data, index); if (insertResult === true) { inserted.push(data); } else { failed.push({ doc: data, reason: insertResult }); } } resultObj = { deferred: false, inserted: inserted, failed: failed }; this._onInsert(inserted, failed); if (callback) { callback(resultObj); } this._onChange(); this.deferEmit('change', {type: 'insert', data: inserted}); return resultObj; }; /** * Internal method to insert a document into the collection. Will * check for index violations before allowing the document to be inserted. * @param {Object} doc The document to insert after passing index violation * tests. * @param {Number=} index Optional index to insert the document at. * @returns {Boolean|Object} True on success, false if no document passed, * or an object containing details about an index violation if one occurred. * @private */ Collection.prototype._insert = function (doc, index) { if (doc) { var self = this, indexViolation, triggerOperation, insertMethod, newDoc, capped = this.capped(), cappedSize = this.cappedSize(); this.ensurePrimaryKey(doc); // Check indexes are not going to be broken by the document indexViolation = this.insertIndexViolation(doc); insertMethod = function (doc) { // Add the item to the collection's indexes self._insertIntoIndexes(doc); // Check index overflow if (index > self._data.length) { index = self._data.length; } // Insert the document self._dataInsertAtIndex(index, doc); // Check capped collection status and remove first record // if we are over the threshold if (capped && self._data.length > cappedSize) { // Remove the first item in the data array self.removeById(self._data[0][self._primaryKey]); } //op.time('Resolve chains'); self.chainSend('insert', doc, {index: index}); //op.time('Resolve chains'); }; if (!indexViolation) { if (self.willTrigger(self.TYPE_INSERT, self.PHASE_BEFORE) || self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { triggerOperation = { type: 'insert' }; if (self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_BEFORE, {}, doc) !== false) { insertMethod(doc); if (self.willTrigger(self.TYPE_INSERT, self.PHASE_AFTER)) { // Clone the doc so that the programmer cannot update the internal document // on the "after" phase trigger newDoc = self.decouple(doc); self.processTrigger(triggerOperation, self.TYPE_INSERT, self.PHASE_AFTER, {}, newDoc); } } else { // The trigger just wants to cancel the operation return 'Trigger cancelled operation'; } } else { // No triggers to execute insertMethod(doc); } return true; } else { return 'Index violation in index: ' + indexViolation; } } return 'No document passed to insert'; }; /** * Inserts a document into the internal collection data array at * Inserts a document into the internal collection data array at * the specified index. * @param {number} index The index to insert at. * @param {object} doc The document to insert. * @private */ Collection.prototype._dataInsertAtIndex = function (index, doc) { this._data.splice(index, 0, doc); }; /** * Removes a document from the internal collection data array at * the specified index. * @param {number} index The index to remove from. * @private */ Collection.prototype._dataRemoveAtIndex = function (index) { this._data.splice(index, 1); }; /** * Replaces all data in the collection's internal data array with * the passed array of data. * @param {array} data The array of data to replace existing data with. * @private */ Collection.prototype._dataReplace = function (data) { // Clear the array - using a while loop with pop is by far the // fastest way to clear an array currently while (this._data.length) { this._data.pop(); } // Append new items to the array this._data = this._data.concat(data); }; /** * Inserts a document into the collection indexes. * @param {Object} doc The document to insert. * @private */ Collection.prototype._insertIntoIndexes = function (doc) { var arr = this._indexByName, arrIndex, violated, jString = this.jStringify(doc); // Insert to primary key index violated = this._primaryIndex.uniqueSet(doc[this._primaryKey], doc); this._primaryCrc.uniqueSet(doc[this._primaryKey], jString); this._crcLookup.uniqueSet(jString, doc); // Insert into other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].insert(doc); } } return violated; }; /** * Removes a document from the collection indexes. * @param {Object} doc The document to remove. * @private */ Collection.prototype._removeFromIndexes = function (doc) { var arr = this._indexByName, arrIndex, jString = this.jStringify(doc); // Remove from primary key index this._primaryIndex.unSet(doc[this._primaryKey]); this._primaryCrc.unSet(doc[this._primaryKey]); this._crcLookup.unSet(jString); // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].remove(doc); } } }; /** * Updates collection index data for the passed document. * @param {Object} oldDoc The old document as it was before the update. * @param {Object} newDoc The document as it now is after the update. * @private */ Collection.prototype._updateIndexes = function (oldDoc, newDoc) { this._removeFromIndexes(oldDoc); this._insertIntoIndexes(newDoc); }; /** * Rebuild collection indexes. * @private */ Collection.prototype._rebuildIndexes = function () { var arr = this._indexByName, arrIndex; // Remove from other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arr[arrIndex].rebuild(); } } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param {Object} query The query object to generate the subset with. * @param {Object=} options An options object. * @returns {*} */ Collection.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Gets / sets the collection that this collection is a subset of. * @param {Collection=} collection The collection to set as the parent of this subset. * @returns {Collection} */ Shared.synthesize(Collection.prototype, 'subsetOf'); /** * Checks if the collection is a subset of the passed collection. * @param {Collection} collection The collection to test against. * @returns {Boolean} True if the passed collection is the parent of * the current collection. */ Collection.prototype.isSubsetOf = function (collection) { return this._subsetOf === collection; }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ Collection.prototype.distinct = function (key, query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } var data = this.find(query, options), pathSolver = new Path(key), valueUsed = {}, distinctValues = [], value, i; // Loop the data and build array of distinct values for (i = 0; i < data.length; i++) { value = pathSolver.value(data[i])[0]; if (value && !valueUsed[value]) { valueUsed[value] = true; distinctValues.push(value); } } return distinctValues; }; /** * Helper method to find a document by it's id. * @param {String} id The id of the document. * @param {Object=} options The options object, allowed keys are sort and limit. * @returns {Array} The items that were updated. */ Collection.prototype.findById = function (id, options) { var searchObj = {}; searchObj[this._primaryKey] = id; return this.find(searchObj, options)[0]; }; /** * Finds all documents that contain the passed string or search object * regardless of where the string might occur within the document. This * will match strings from the start, middle or end of the document's * string (partial match). * @param search The string to search for. Case sensitive. * @param options A standard find() options object. * @returns {Array} An array of documents that matched the search string. */ Collection.prototype.peek = function (search, options) { // Loop all items var arr = this._data, arrCount = arr.length, arrIndex, arrItem, tempColl = new Collection(), typeOfSearch = typeof search; if (typeOfSearch === 'string') { for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Get json representation of object arrItem = this.jStringify(arr[arrIndex]); // Check if string exists in object json if (arrItem.indexOf(search) > -1) { // Add this item to the temp collection tempColl.insert(arr[arrIndex]); } } return tempColl.find({}, options); } else { return this.find(search, options); } }; /** * Provides a query plan / operations log for a query. * @param {Object} query The query to execute. * @param {Object=} options Optional options object. * @returns {Object} The query plan. */ Collection.prototype.explain = function (query, options) { var result = this.find(query, options); return result.__fdbOp._data; }; /** * Generates an options object with default values or adds default * values to a passed object if those values are not currently set * to anything. * @param {object=} obj Optional options object to modify. * @returns {object} The options object. */ Collection.prototype.options = function (obj) { obj = obj || {}; obj.$decouple = obj.$decouple !== undefined ? obj.$decouple : true; obj.$explain = obj.$explain !== undefined ? obj.$explain : false; return obj; }; /** * Queries the collection based on the query object passed. * @param {Object} query The query key/values that a document must match in * order for it to be returned in the result array. * @param {Object=} options An optional options object. * @param {Function=} callback !! DO NOT USE, THIS IS NON-OPERATIONAL !! * Optional callback. If specified the find process * will not return a value and will assume that you wish to operate under an * async mode. This will break up large find requests into smaller chunks and * process them in a non-blocking fashion allowing large datasets to be queried * without causing the browser UI to pause. Results from this type of operation * will be passed back to the callback once completed. * * @returns {Array} The results array from the find operation, containing all * documents that matched the query. */ Collection.prototype.find = function (query, options, callback) { // Convert queries from mongo dot notation to forerunner queries if (this.mongoEmulation()) { this.convertToFdb(query); } if (callback) { // Check the size of the collection's data array // Split operation into smaller tasks and callback when complete callback('Callbacks for the find() operation are not yet implemented!', []); return []; } return this._find.apply(this, arguments); }; Collection.prototype._find = function (query, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } // TODO: This method is quite long, break into smaller pieces query = query || {}; options = this.options(options); var op = this._metrics.create('find'), pk = this.primaryKey(), self = this, analysis, scanLength, requiresTableScan = true, resultArr, joinCollectionIndex, joinIndex, joinCollection = {}, joinQuery, joinPath, joinCollectionName, joinCollectionInstance, joinMatch, joinMatchIndex, joinSearchQuery, joinSearchOptions, joinMulti, joinRequire, joinFindResults, joinFindResult, joinItem, joinPrefix, resultCollectionName, resultIndex, resultRemove = [], index, i, j, k, l, fieldListOn = [], fieldListOff = [], elemMatchPathSolver, elemMatchSubArr, elemMatchSpliceArr, matcherTmpOptions = {}, result, cursor = {}, pathSolver, //renameFieldMethod, //renameFieldPath, matcher = function (doc) { return self._match(doc, query, options, 'and', matcherTmpOptions); }; op.start(); if (query) { // Get query analysis to execute best optimised code path op.time('analyseQuery'); analysis = this._analyseQuery(self.decouple(query), options, op); op.time('analyseQuery'); op.data('analysis', analysis); if (analysis.hasJoin && analysis.queriesJoin) { // The query has a join and tries to limit by it's joined data // Get an instance reference to the join collections op.time('joinReferences'); for (joinIndex = 0; joinIndex < analysis.joinsOn.length; joinIndex++) { joinCollectionName = analysis.joinsOn[joinIndex]; joinPath = new Path(analysis.joinQueries[joinCollectionName]); joinQuery = joinPath.value(query)[0]; joinCollection[analysis.joinsOn[joinIndex]] = this._db.collection(analysis.joinsOn[joinIndex]).subset(joinQuery); // Remove join clause from main query delete query[analysis.joinQueries[joinCollectionName]]; } op.time('joinReferences'); } // Check if an index lookup can be used to return this result if (analysis.indexMatch.length && (!options || (options && !options.$skipIndex))) { op.data('index.potential', analysis.indexMatch); op.data('index.used', analysis.indexMatch[0].index); // Get the data from the index op.time('indexLookup'); resultArr = analysis.indexMatch[0].lookup || []; op.time('indexLookup'); // Check if the index coverage is all keys, if not we still need to table scan it if (analysis.indexMatch[0].keyData.totalKeyCount === analysis.indexMatch[0].keyData.score) { // Don't require a table scan to find relevant documents requiresTableScan = false; } } else { op.flag('usedIndex', false); } if (requiresTableScan) { if (resultArr && resultArr.length) { scanLength = resultArr.length; op.time('tableScan: ' + scanLength); // Filter the source data and return the result resultArr = resultArr.filter(matcher); } else { // Filter the source data and return the result scanLength = this._data.length; op.time('tableScan: ' + scanLength); resultArr = this._data.filter(matcher); } op.time('tableScan: ' + scanLength); } // Order the array if we were passed a sort clause if (options.$orderBy) { op.time('sort'); resultArr = this.sort(options.$orderBy, resultArr); op.time('sort'); } if (options.$page !== undefined && options.$limit !== undefined) { // Record paging data cursor.page = options.$page; cursor.pages = Math.ceil(resultArr.length / options.$limit); cursor.records = resultArr.length; // Check if we actually need to apply the paging logic if (options.$page && options.$limit > 0) { op.data('cursor', cursor); // Skip to the page specified based on limit resultArr.splice(0, options.$page * options.$limit); } } if (options.$skip) { cursor.skip = options.$skip; // Skip past the number of records specified resultArr.splice(0, options.$skip); op.data('skip', options.$skip); } if (options.$limit && resultArr && resultArr.length > options.$limit) { cursor.limit = options.$limit; resultArr.length = options.$limit; op.data('limit', options.$limit); } if (options.$decouple) { // Now decouple the data from the original objects op.time('decouple'); resultArr = this.decouple(resultArr); op.time('decouple'); op.data('flag.decouple', true); } // Now process any joins on the final data if (options.$join) { for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { // Set the key to store the join result in to the collection name by default resultCollectionName = joinCollectionName; // Get the join collection instance from the DB if (joinCollection[joinCollectionName]) { joinCollectionInstance = joinCollection[joinCollectionName]; } else { joinCollectionInstance = this._db.collection(joinCollectionName); } // Get the match data for the join joinMatch = options.$join[joinCollectionIndex][joinCollectionName]; // Loop our result data array for (resultIndex = 0; resultIndex < resultArr.length; resultIndex++) { // Loop the join conditions and build a search object from them joinSearchQuery = {}; joinMulti = false; joinRequire = false; joinPrefix = ''; for (joinMatchIndex in joinMatch) { if (joinMatch.hasOwnProperty(joinMatchIndex)) { // Check the join condition name for a special command operator if (joinMatchIndex.substr(0, 1) === '$') { // Special command switch (joinMatchIndex) { case '$where': if (joinMatch[joinMatchIndex].query) { // Commented old code here, new one does dynamic reverse lookups //joinSearchQuery = joinMatch[joinMatchIndex].query; joinSearchQuery = self._resolveDynamicQuery(joinMatch[joinMatchIndex].query, resultArr[resultIndex]); } if (joinMatch[joinMatchIndex].options) { joinSearchOptions = joinMatch[joinMatchIndex].options; } break; case '$as': // Rename the collection when stored in the result document resultCollectionName = joinMatch[joinMatchIndex]; break; case '$multi': // Return an array of documents instead of a single matching document joinMulti = joinMatch[joinMatchIndex]; break; case '$require': // Remove the result item if no matching join data is found joinRequire = joinMatch[joinMatchIndex]; break; case '$prefix': // Add a prefix to properties mixed in joinPrefix = joinMatch[joinMatchIndex]; break; default: break; } } else { // Get the data to match against and store in the search object // Resolve complex referenced query joinSearchQuery[joinMatchIndex] = self._resolveDynamicQuery(joinMatch[joinMatchIndex], resultArr[resultIndex]); } } } // Do a find on the target collection against the match data joinFindResults = joinCollectionInstance.find(joinSearchQuery, joinSearchOptions); // Check if we require a joined row to allow the result item if (!joinRequire || (joinRequire && joinFindResults[0])) { // Join is not required or condition is met if (resultCollectionName === '$root') { // The property name to store the join results in is $root // which means we need to mixin the results but this only // works if joinMulti is disabled if (joinMulti !== false) { // Throw an exception here as this join is not physically possible! throw(this.logIdentifier() + ' Cannot combine [$as: "$root"] with [$multi: true] in $join clause!'); } // Mixin the result joinFindResult = joinFindResults[0]; joinItem = resultArr[resultIndex]; for (l in joinFindResult) { if (joinFindResult.hasOwnProperty(l) && joinItem[joinPrefix + l] === undefined) { // Properties are only mixed in if they do not already exist // in the target item (are undefined). Using a prefix denoted via // $prefix is a good way to prevent property name conflicts joinItem[joinPrefix + l] = joinFindResult[l]; } } } else { resultArr[resultIndex][resultCollectionName] = joinMulti === false ? joinFindResults[0] : joinFindResults; } } else { // Join required but condition not met, add item to removal queue resultRemove.push(resultArr[resultIndex]); } } } } } op.data('flag.join', true); } // Process removal queue if (resultRemove.length) { op.time('removalQueue'); for (i = 0; i < resultRemove.length; i++) { index = resultArr.indexOf(resultRemove[i]); if (index > -1) { resultArr.splice(index, 1); } } op.time('removalQueue'); } if (options.$transform) { op.time('transform'); for (i = 0; i < resultArr.length; i++) { resultArr.splice(i, 1, options.$transform(resultArr[i])); } op.time('transform'); op.data('flag.transform', true); } // Process transforms if (this._transformEnabled && this._transformOut) { op.time('transformOut'); resultArr = this.transformOut(resultArr); op.time('transformOut'); } op.data('results', resultArr.length); } else { resultArr = []; } // Check for an $as operator in the options object and if it exists // iterate over the fields and generate a rename function that will // operate over the entire returned data array and rename each object's // fields to their new names // TODO: Enable $as in collection find to allow renaming fields /*if (options.$as) { renameFieldPath = new Path(); renameFieldMethod = function (obj, oldFieldPath, newFieldName) { renameFieldPath.path(oldFieldPath); renameFieldPath.rename(newFieldName); }; for (i in options.$as) { if (options.$as.hasOwnProperty(i)) { } } }*/ if (!options.$aggregate) { // Generate a list of fields to limit data by // Each property starts off being enabled by default (= 1) then // if any property is explicitly specified as 1 then all switch to // zero except _id. // // Any that are explicitly set to zero are switched off. op.time('scanFields'); for (i in options) { if (options.hasOwnProperty(i) && i.indexOf('$') !== 0) { if (options[i] === 1) { fieldListOn.push(i); } else if (options[i] === 0) { fieldListOff.push(i); } } } op.time('scanFields'); // Limit returned fields by the options data if (fieldListOn.length || fieldListOff.length) { op.data('flag.limitFields', true); op.data('limitFields.on', fieldListOn); op.data('limitFields.off', fieldListOff); op.time('limitFields'); // We have explicit fields switched on or off for (i = 0; i < resultArr.length; i++) { result = resultArr[i]; for (j in result) { if (result.hasOwnProperty(j)) { if (fieldListOn.length) { // We have explicit fields switched on so remove all fields // that are not explicitly switched on // Check if the field name is not the primary key if (j !== pk) { if (fieldListOn.indexOf(j) === -1) { // This field is not in the on list, remove it delete result[j]; } } } if (fieldListOff.length) { // We have explicit fields switched off so remove fields // that are explicitly switched off if (fieldListOff.indexOf(j) > -1) { // This field is in the off list, remove it delete result[j]; } } } } } op.time('limitFields'); } // Now run any projections on the data required if (options.$elemMatch) { op.data('flag.elemMatch', true); op.time('projection-elemMatch'); for (i in options.$elemMatch) { if (options.$elemMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemMatch[i], options, '', {})) { // The item matches the projection query so set the sub-array // to an array that ONLY contains the matching item and then // exit the loop since we only want to match the first item elemMatchPathSolver.set(resultArr[j], i, [elemMatchSubArr[k]]); break; } } } } } } op.time('projection-elemMatch'); } if (options.$elemsMatch) { op.data('flag.elemsMatch', true); op.time('projection-elemsMatch'); for (i in options.$elemsMatch) { if (options.$elemsMatch.hasOwnProperty(i)) { elemMatchPathSolver = new Path(i); // Loop the results array for (j = 0; j < resultArr.length; j++) { elemMatchSubArr = elemMatchPathSolver.value(resultArr[j])[0]; // Check we have a sub-array to loop if (elemMatchSubArr && elemMatchSubArr.length) { elemMatchSpliceArr = []; // Loop the sub-array and check for projection query matches for (k = 0; k < elemMatchSubArr.length; k++) { // Check if the current item in the sub-array matches the projection query if (self._match(elemMatchSubArr[k], options.$elemsMatch[i], options, '', {})) { // The item matches the projection query so add it to the final array elemMatchSpliceArr.push(elemMatchSubArr[k]); } } // Now set the final sub-array to the matched items elemMatchPathSolver.set(resultArr[j], i, elemMatchSpliceArr); } } } } op.time('projection-elemsMatch'); } } // Process aggregation if (options.$aggregate) { op.data('flag.aggregate', true); op.time('aggregate'); pathSolver = new Path(options.$aggregate); resultArr = pathSolver.value(resultArr); op.time('aggregate'); } op.stop(); resultArr.__fdbOp = op; resultArr.$cursor = cursor; return resultArr; }; Collection.prototype._resolveDynamicQuery = function (query, item) { var self = this, newQuery, propType, propVal, pathResult, i; if (typeof query === 'string') { // Check if the property name starts with a back-reference if (query.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value pathResult = new Path(query.substr(3, query.length - 3)).value(item); } else { pathResult = new Path(query).value(item); } if (pathResult.length > 1) { return {$in: pathResult}; } else { return pathResult[0]; } } newQuery = {}; for (i in query) { if (query.hasOwnProperty(i)) { propType = typeof query[i]; propVal = query[i]; switch (propType) { case 'string': // Check if the property name starts with a back-reference if (propVal.substr(0, 3) === '$$.') { // Fill the query with a back-referenced value newQuery[i] = new Path(propVal.substr(3, propVal.length - 3)).value(item)[0]; } else { newQuery[i] = propVal; } break; case 'object': newQuery[i] = self._resolveDynamicQuery(propVal, item); break; default: newQuery[i] = propVal; break; } } } return newQuery; }; /** * Returns one document that satisfies the specified query criteria. If multiple * documents satisfy the query, this method returns the first document to match * the query. * @returns {*} */ Collection.prototype.findOne = function () { return (this.find.apply(this, arguments))[0]; }; /** * Gets the index in the collection data array of the first item matched by * the passed query object. * @param {Object} query The query to run to find the item to return the index of. * @param {Object=} options An options object. * @returns {Number} */ Collection.prototype.indexOf = function (query, options) { var item = this.find(query, {$decouple: false})[0], sortedData; if (item) { if (!options || options && !options.$orderBy) { // Basic lookup from order of insert return this._data.indexOf(item); } else { // Trying to locate index based on query with sort order options.$decouple = false; sortedData = this.find(query, options); return sortedData.indexOf(item); } } return -1; }; /** * Returns the index of the document identified by the passed item's primary key. * @param {*} itemLookup The document whose primary key should be used to lookup * or the id to lookup. * @param {Object=} options An options object. * @returns {Number} The index the item with the matching primary key is occupying. */ Collection.prototype.indexOfDocById = function (itemLookup, options) { var item, sortedData; if (typeof itemLookup !== 'object') { item = this._primaryIndex.get(itemLookup); } else { item = this._primaryIndex.get(itemLookup[this._primaryKey]); } if (item) { if (!options || options && !options.$orderBy) { // Basic lookup return this._data.indexOf(item); } else { // Sorted lookup options.$decouple = false; sortedData = this.find({}, options); return sortedData.indexOf(item); } } return -1; }; /** * Removes a document from the collection by it's index in the collection's * data array. * @param {Number} index The index of the document to remove. * @returns {Object} The document that has been removed or false if none was * removed. */ Collection.prototype.removeByIndex = function (index) { var doc, docId; doc = this._data[index]; if (doc !== undefined) { doc = this.decouple(doc); docId = doc[this.primaryKey()]; return this.removeById(docId); } return false; }; /** * Gets / sets the collection transform options. * @param {Object} obj A collection transform options object. * @returns {*} */ Collection.prototype.transform = function (obj) { if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Transforms data using the set transformIn method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformIn = function (data) { if (this._transformEnabled && this._transformIn) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformIn(data[i]); } return finalArr; } else { return this._transformIn(data); } } return data; }; /** * Transforms data using the set transformOut method. * @param {Object} data The data to transform. * @returns {*} */ Collection.prototype.transformOut = function (data) { if (this._transformEnabled && this._transformOut) { if (data instanceof Array) { var finalArr = [], i; for (i = 0; i < data.length; i++) { finalArr[i] = this._transformOut(data[i]); } return finalArr; } else { return this._transformOut(data); } } return data; }; /** * Sorts an array of documents by the given sort path. * @param {*} sortObj The keys and orders the array objects should be sorted by. * @param {Array} arr The array of documents to sort. * @returns {Array} */ Collection.prototype.sort = function (sortObj, arr) { // Convert the index object to an array of key val objects var self = this, keys = sharedPathSolver.parse(sortObj, true); if (keys.length) { // Execute sort arr.sort(function (a, b) { // Loop the index array var i, indexData, result = 0; for (i = 0; i < keys.length; i++) { indexData = keys[i]; if (indexData.value === 1) { result = self.sortAsc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } else if (indexData.value === -1) { result = self.sortDesc(sharedPathSolver.get(a, indexData.path), sharedPathSolver.get(b, indexData.path)); } if (result !== 0) { return result; } } return result; }); } return arr; }; // Commented as we have a new method that was originally implemented for binary trees. // This old method actually has problems with nested sort objects /*Collection.prototype.sortold = function (sortObj, arr) { // Make sure we have an array object arr = arr || []; var sortArr = [], sortKey, sortSingleObj; for (sortKey in sortObj) { if (sortObj.hasOwnProperty(sortKey)) { sortSingleObj = {}; sortSingleObj[sortKey] = sortObj[sortKey]; sortSingleObj.___fdbKey = String(sortKey); sortArr.push(sortSingleObj); } } if (sortArr.length < 2) { // There is only one sort criteria, do a simple sort and return it return this._sort(sortObj, arr); } else { return this._bucketSort(sortArr, arr); } };*/ /** * Takes array of sort paths and sorts them into buckets before returning final * array fully sorted by multi-keys. * @param keyArr * @param arr * @returns {*} * @private */ /*Collection.prototype._bucketSort = function (keyArr, arr) { var keyObj = keyArr.shift(), arrCopy, bucketData, bucketOrder, bucketKey, buckets, i, finalArr = []; if (keyArr.length > 0) { // Sort array by bucket key arr = this._sort(keyObj, arr); // Split items into buckets bucketData = this.bucket(keyObj.___fdbKey, arr); bucketOrder = bucketData.order; buckets = bucketData.buckets; // Loop buckets and sort contents for (i = 0; i < bucketOrder.length; i++) { bucketKey = bucketOrder[i]; arrCopy = [].concat(keyArr); finalArr = finalArr.concat(this._bucketSort(arrCopy, buckets[bucketKey])); } return finalArr; } else { return this._sort(keyObj, arr); } };*/ /** * Sorts array by individual sort path. * @param key * @param arr * @returns {Array|*} * @private */ Collection.prototype._sort = function (key, arr) { var self = this, sorterMethod, pathSolver = new Path(), dataPath = pathSolver.parse(key, true)[0]; pathSolver.path(dataPath.path); if (dataPath.value === 1) { // Sort ascending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortAsc(valA, valB); }; } else if (dataPath.value === -1) { // Sort descending sorterMethod = function (a, b) { var valA = pathSolver.value(a)[0], valB = pathSolver.value(b)[0]; return self.sortDesc(valA, valB); }; } else { throw(this.logIdentifier() + ' $orderBy clause has invalid direction: ' + dataPath.value + ', accepted values are 1 or -1 for ascending or descending!'); } return arr.sort(sorterMethod); }; /** * Takes an array of objects and returns a new object with the array items * split into buckets by the passed key. * @param {String} key The key to split the array into buckets by. * @param {Array} arr An array of objects. * @returns {Object} */ Collection.prototype.bucket = function (key, arr) { var i, oldField, field, fieldArr = [], buckets = {}; for (i = 0; i < arr.length; i++) { field = String(arr[i][key]); if (oldField !== field) { fieldArr.push(field); oldField = field; } buckets[field] = buckets[field] || []; buckets[field].push(arr[i]); } return { buckets: buckets, order: fieldArr }; }; /** * Internal method that takes a search query and options and returns an object * containing details about the query which can be used to optimise the search. * * @param query * @param options * @param op * @returns {Object} * @private */ Collection.prototype._analyseQuery = function (query, options, op) { var analysis = { queriesOn: [this._name], indexMatch: [], hasJoin: false, queriesJoin: false, joinQueries: {}, query: query, options: options }, joinCollectionIndex, joinCollectionName, joinCollections = [], joinCollectionReferences = [], queryPath, index, indexMatchData, indexRef, indexRefName, indexLookup, pathSolver, queryKeyCount, pkQueryType, lookupResult, i; // Check if the query is a primary key lookup op.time('checkIndexes'); pathSolver = new Path(); queryKeyCount = pathSolver.parseArr(query, { ignore:/\$/, verbose: true }).length; if (queryKeyCount) { if (query[this._primaryKey] !== undefined) { // Check suitability of querying key value index pkQueryType = typeof query[this._primaryKey]; if (pkQueryType === 'string' || pkQueryType === 'number' || query[this._primaryKey] instanceof Array) { // Return item via primary key possible op.time('checkIndexMatch: Primary Key'); lookupResult = this._primaryIndex.lookup(query, options); analysis.indexMatch.push({ lookup: lookupResult, keyData: { matchedKeys: [this._primaryKey], totalKeyCount: queryKeyCount, score: 1 }, index: this._primaryIndex }); op.time('checkIndexMatch: Primary Key'); } } // Check if an index can speed up the query for (i in this._indexById) { if (this._indexById.hasOwnProperty(i)) { indexRef = this._indexById[i]; indexRefName = indexRef.name(); op.time('checkIndexMatch: ' + indexRefName); indexMatchData = indexRef.match(query, options); if (indexMatchData.score > 0) { // This index can be used, store it indexLookup = indexRef.lookup(query, options); analysis.indexMatch.push({ lookup: indexLookup, keyData: indexMatchData, index: indexRef }); } op.time('checkIndexMatch: ' + indexRefName); if (indexMatchData.score === queryKeyCount) { // Found an optimal index, do not check for any more break; } } } op.time('checkIndexes'); // Sort array descending on index key count (effectively a measure of relevance to the query) if (analysis.indexMatch.length > 1) { op.time('findOptimalIndex'); analysis.indexMatch.sort(function (a, b) { if (a.keyData.score > b.keyData.score) { // This index has a higher score than the other return -1; } if (a.keyData.score < b.keyData.score) { // This index has a lower score than the other return 1; } // The indexes have the same score but can still be compared by the number of records // they return from the query. The fewer records they return the better so order by // record count if (a.keyData.score === b.keyData.score) { return a.lookup.length - b.lookup.length; } }); op.time('findOptimalIndex'); } } // Check for join data if (options.$join) { analysis.hasJoin = true; // Loop all join operations for (joinCollectionIndex = 0; joinCollectionIndex < options.$join.length; joinCollectionIndex++) { // Loop the join collections and keep a reference to them for (joinCollectionName in options.$join[joinCollectionIndex]) { if (options.$join[joinCollectionIndex].hasOwnProperty(joinCollectionName)) { joinCollections.push(joinCollectionName); // Check if the join uses an $as operator if ('$as' in options.$join[joinCollectionIndex][joinCollectionName]) { joinCollectionReferences.push(options.$join[joinCollectionIndex][joinCollectionName].$as); } else { joinCollectionReferences.push(joinCollectionName); } } } } // Loop the join collection references and determine if the query references // any of the collections that are used in the join. If there no queries against // joined collections the find method can use a code path optimised for this. // Queries against joined collections requires the joined collections to be filtered // first and then joined so requires a little more work. for (index = 0; index < joinCollectionReferences.length; index++) { // Check if the query references any collection data that the join will create queryPath = this._queryReferencesCollection(query, joinCollectionReferences[index], ''); if (queryPath) { analysis.joinQueries[joinCollections[index]] = queryPath; analysis.queriesJoin = true; } } analysis.joinsOn = joinCollections; analysis.queriesOn = analysis.queriesOn.concat(joinCollections); } return analysis; }; /** * Checks if the passed query references this collection. * @param query * @param collection * @param path * @returns {*} * @private */ Collection.prototype._queryReferencesCollection = function (query, collection, path) { var i; for (i in query) { if (query.hasOwnProperty(i)) { // Check if this key is a reference match if (i === collection) { if (path) { path += '.'; } return path + i; } else { if (typeof(query[i]) === 'object') { // Recurse if (path) { path += '.'; } path += i; return this._queryReferencesCollection(query[i], collection, path); } } } } return false; }; /** * Returns the number of documents currently in the collection. * @returns {Number} */ Collection.prototype.count = function (query, options) { if (!query) { return this._data.length; } else { // Run query and return count return this.find(query, options).length; } }; /** * Finds sub-documents from the collection's documents. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {*} */ Collection.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { var pathHandler = new Path(path), docArr = this.find(match), docCount = docArr.length, docIndex, subDocArr, subDocCollection = this._db.collection('__FDB_temp_' + this.objectId()), subDocResults, resultObj = { parents: docCount, subDocTotal: 0, subDocs: [], pathFound: false, err: '' }; subDocOptions = subDocOptions || {}; for (docIndex = 0; docIndex < docCount; docIndex++) { subDocArr = pathHandler.value(docArr[docIndex])[0]; if (subDocArr) { subDocCollection.setData(subDocArr); subDocResults = subDocCollection.find(subDocQuery, subDocOptions); if (subDocOptions.returnFirst && subDocResults.length) { return subDocResults[0]; } if (subDocOptions.$split) { resultObj.subDocs.push(subDocResults); } else { resultObj.subDocs = resultObj.subDocs.concat(subDocResults); } resultObj.subDocTotal += subDocResults.length; resultObj.pathFound = true; } } // Drop the sub-document collection subDocCollection.drop(); // Check if the call should not return stats, if so return only subDocs array if (subDocOptions.$stats) { return resultObj; } else { return resultObj.subDocs; } if (!resultObj.pathFound) { resultObj.err = 'No objects found in the parent documents with a matching path of: ' + path; } return resultObj; }; /** * Finds the first sub-document from the collection's documents that matches * the subDocQuery parameter. * @param {Object} match The query object to use when matching parent documents * from which the sub-documents are queried. * @param {String} path The path string used to identify the key in which * sub-documents are stored in parent documents. * @param {Object=} subDocQuery The query to use when matching which sub-documents * to return. * @param {Object=} subDocOptions The options object to use when querying for * sub-documents. * @returns {Object} */ Collection.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.findSub(match, path, subDocQuery, subDocOptions)[0]; }; /** * Checks that the passed document will not violate any index rules if * inserted into the collection. * @param {Object} doc The document to check indexes against. * @returns {Boolean} Either false (no violation occurred) or true if * a violation was detected. */ Collection.prototype.insertIndexViolation = function (doc) { var indexViolated, arr = this._indexByName, arrIndex, arrItem; // Check the item's primary key is not already in use if (this._primaryIndex.get(doc[this._primaryKey])) { indexViolated = this._primaryIndex; } else { // Check violations of other indexes for (arrIndex in arr) { if (arr.hasOwnProperty(arrIndex)) { arrItem = arr[arrIndex]; if (arrItem.unique()) { if (arrItem.violation(doc)) { indexViolated = arrItem; break; } } } } } return indexViolated ? indexViolated.name() : false; }; /** * Creates an index on the specified keys. * @param {Object} keys The object containing keys to index. * @param {Object} options An options object. * @returns {*} */ Collection.prototype.ensureIndex = function (keys, options) { if (this.isDropped()) { throw(this.logIdentifier() + ' Cannot operate in a dropped state!'); } this._indexByName = this._indexByName || {}; this._indexById = this._indexById || {}; var index, time = { start: new Date().getTime() }; if (options) { switch (options.type) { case 'hashed': index = new IndexHashMap(keys, options, this); break; case 'btree': index = new IndexBinaryTree(keys, options, this); break; case '2d': index = new Index2d(keys, options, this); break; default: // Default index = new IndexHashMap(keys, options, this); break; } } else { // Default index = new IndexHashMap(keys, options, this); } // Check the index does not already exist if (this._indexByName[index.name()]) { // Index already exists return { err: 'Index with that name already exists' }; } /*if (this._indexById[index.id()]) { // Index already exists return { err: 'Index with those keys already exists' }; }*/ // Create the index index.rebuild(); // Add the index this._indexByName[index.name()] = index; this._indexById[index.id()] = index; time.end = new Date().getTime(); time.total = time.end - time.start; this._lastOp = { type: 'ensureIndex', stats: { time: time } }; return { index: index, id: index.id(), name: index.name(), state: index.state() }; }; /** * Gets an index by it's name. * @param {String} name The name of the index to retreive. * @returns {*} */ Collection.prototype.index = function (name) { if (this._indexByName) { return this._indexByName[name]; } }; /** * Gets the last reporting operation's details such as run time. * @returns {Object} */ Collection.prototype.lastOp = function () { return this._metrics.list(); }; /** * Generates a difference object that contains insert, update and remove arrays * representing the operations to execute to make this collection have the same * data as the one passed. * @param {Collection} collection The collection to diff against. * @returns {{}} */ Collection.prototype.diff = function (collection) { var diff = { insert: [], update: [], remove: [] }; var pk = this.primaryKey(), arr, arrIndex, arrItem, arrCount; // Check if the primary key index of each collection can be utilised if (pk !== collection.primaryKey()) { throw(this.logIdentifier() + ' Diffing requires that both collections have the same primary key!'); } // Use the collection primary key index to do the diff (super-fast) arr = collection._data; // Check if we have an array or another collection while (arr && !(arr instanceof Array)) { // We don't have an array, assign collection and get data collection = arr; arr = collection._data; } arrCount = arr.length; // Loop the collection's data array and check for matching items for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; // Check for a matching item in this collection if (this._primaryIndex.get(arrItem[pk])) { // Matching item exists, check if the data is the same if (this._primaryCrc.get(arrItem[pk]) !== collection._primaryCrc.get(arrItem[pk])) { // The documents exist in both collections but data differs, update required diff.update.push(arrItem); } } else { // The document is missing from this collection, insert required diff.insert.push(arrItem); } } // Now loop this collection's data and check for matching items arr = this._data; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = arr[arrIndex]; if (!collection._primaryIndex.get(arrItem[pk])) { // The document does not exist in the other collection, remove required diff.remove.push(arrItem); } } return diff; }; Collection.prototype.collateAdd = new Overload({ /** * Adds a data source to collate data from and specifies the * key name to collate data to. * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {String=} keyName Optional name of the key to collate data to. * If none is provided the record CRUD is operated on the root collection * data. */ 'object, string': function (collection, keyName) { var self = this; self.collateAdd(collection, function (packet) { var obj1, obj2; switch (packet.type) { case 'insert': if (keyName) { obj1 = { $push: {} }; obj1.$push[keyName] = self.decouple(packet.data); self.update({}, obj1); } else { self.insert(packet.data); } break; case 'update': if (keyName) { obj1 = {}; obj2 = {}; obj1[keyName] = packet.data.query; obj2[keyName + '.$'] = packet.data.update; self.update(obj1, obj2); } else { self.update(packet.data.query, packet.data.update); } break; case 'remove': if (keyName) { obj1 = { $pull: {} }; obj1.$pull[keyName] = {}; obj1.$pull[keyName][self.primaryKey()] = packet.data.dataSet[0][collection.primaryKey()]; self.update({}, obj1); } else { self.remove(packet.data); } break; default: } }); }, /** * Adds a data source to collate data from and specifies a process * method that will handle the collation functionality (for custom * collation). * @func collateAdd * @memberof Collection * @param {Collection} collection The collection to collate data from. * @param {Function} process The process method. */ 'object, function': function (collection, process) { if (typeof collection === 'string') { // The collection passed is a name, not a reference so get // the reference from the name collection = this._db.collection(collection, { autoCreate: false, throwError: false }); } if (collection) { this._collate = this._collate || {}; this._collate[collection.name()] = new ReactorIO(collection, this, process); return this; } else { throw('Cannot collate from a non-existent collection!'); } } }); Collection.prototype.collateRemove = function (collection) { if (typeof collection === 'object') { // We need to have the name of the collection to remove it collection = collection.name(); } if (collection) { // Drop the reactor IO chain node this._collate[collection].drop(); // Remove the collection data from the collate object delete this._collate[collection]; return this; } else { throw('No collection name passed to collateRemove() or collection not found!'); } }; Db.prototype.collection = new Overload({ /** * Get a collection with no name (generates a random name). If the * collection does not already exist then one is created for that * name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ '': function () { return this.$main.call(this, { name: this.objectId() }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {Object} data An options object or a collection instance. * @returns {Collection} */ 'object': function (data) { // Handle being passed an instance if (data instanceof Collection) { if (data.state() !== 'droppped') { return data; } else { return this.$main.call(this, { name: data.name() }); } } return this.$main.call(this, data); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @returns {Collection} */ 'string': function (collectionName) { return this.$main.call(this, { name: collectionName }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @returns {Collection} */ 'string, string': function (collectionName, primaryKey) { return this.$main.call(this, { name: collectionName, primaryKey: primaryKey }); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {Object} options An options object. * @returns {Collection} */ 'string, object': function (collectionName, options) { options.name = collectionName; return this.$main.call(this, options); }, /** * Get a collection by name. If the collection does not already exist * then one is created for that name automatically. * @func collection * @memberof Db * @param {String} collectionName The name of the collection. * @param {String} primaryKey Optional primary key to specify the primary key field on the collection * objects. Defaults to "_id". * @param {Object} options An options object. * @returns {Collection} */ 'string, string, object': function (collectionName, primaryKey, options) { options.name = collectionName; options.primaryKey = primaryKey; return this.$main.call(this, options); }, /** * The main handler method. This gets called by all the other variants and * handles the actual logic of the overloaded method. * @func collection * @memberof Db * @param {Object} options An options object. * @returns {*} */ '$main': function (options) { var self = this, name = options.name; if (name) { if (this._collection[name]) { return this._collection[name]; } else { if (options && options.autoCreate === false) { if (options && options.throwError !== false) { throw(this.logIdentifier() + ' Cannot get collection ' + name + ' because it does not exist and auto-create has been disabled!'); } return undefined; } if (this.debug()) { console.log(this.logIdentifier() + ' Creating collection ' + name); } } this._collection[name] = this._collection[name] || new Collection(name, options).db(this); this._collection[name].mongoEmulation(this.mongoEmulation()); if (options.primaryKey !== undefined) { this._collection[name].primaryKey(options.primaryKey); } if (options.capped !== undefined) { // Check we have a size if (options.size !== undefined) { this._collection[name].capped(options.capped); this._collection[name].cappedSize(options.size); } else { throw(this.logIdentifier() + ' Cannot create a capped collection without specifying a size!'); } } // Listen for events on this collection so we can fire global events // on the database in response to it self._collection[name].on('change', function () { self.emit('change', self._collection[name], 'collection', name); }); self.emit('create', self._collection[name], 'collection', name); return this._collection[name]; } else { if (!options || (options && options.throwError !== false)) { throw(this.logIdentifier() + ' Cannot get collection with undefined name!'); } } } }); /** * Determine if a collection with the passed name already exists. * @memberof Db * @param {String} viewName The name of the collection to check for. * @returns {boolean} */ Db.prototype.collectionExists = function (viewName) { return Boolean(this._collection[viewName]); }; /** * Returns an array of collections the DB currently has. * @memberof Db * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each collection * the database is currently managing. */ Db.prototype.collections = function (search) { var arr = [], collections = this._collection, collection, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in collections) { if (collections.hasOwnProperty(i)) { collection = collections[i]; if (search) { if (search.exec(i)) { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } else { arr.push({ name: i, count: collection.count(), linked: collection.isLinked !== undefined ? collection.isLinked() : false }); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Collection'); module.exports = Collection; },{"./Crc":8,"./Index2d":11,"./IndexBinaryTree":12,"./IndexHashMap":13,"./KeyValueStore":14,"./Metrics":15,"./Overload":27,"./Path":28,"./ReactorIO":29,"./Shared":31}],6:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, DbInit, Collection; Shared = _dereq_('./Shared'); /** * Creates a new collection group. Collection groups allow single operations to be * propagated to multiple collections at once. CRUD operations against a collection * group are in fed to the group's collections. Useful when separating out slightly * different data into multiple collections but querying as one collection. * @constructor */ var CollectionGroup = function () { this.init.apply(this, arguments); }; CollectionGroup.prototype.init = function (name) { var self = this; self._name = name; self._data = new Collection('__FDB__cg_data_' + self._name); self._collections = []; self._view = []; }; Shared.addModule('CollectionGroup', CollectionGroup); Shared.mixin(CollectionGroup.prototype, 'Mixin.Common'); Shared.mixin(CollectionGroup.prototype, 'Mixin.ChainReactor'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Constants'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Triggers'); Shared.mixin(CollectionGroup.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); Db = Shared.modules.Db; DbInit = Shared.modules.Db.prototype.init; CollectionGroup.prototype.on = function () { this._data.on.apply(this._data, arguments); }; CollectionGroup.prototype.off = function () { this._data.off.apply(this._data, arguments); }; CollectionGroup.prototype.emit = function () { this._data.emit.apply(this._data, arguments); }; /** * Gets / sets the primary key for this collection group. * @param {String=} keyName The name of the primary key. * @returns {*} */ CollectionGroup.prototype.primaryKey = function (keyName) { if (keyName !== undefined) { this._primaryKey = keyName; return this; } return this._primaryKey; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'state'); /** * Gets / sets the db instance the collection group belongs to. * @param {Db=} db The db instance. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'db'); /** * Gets / sets the instance name. * @param {Name=} name The new name to set. * @returns {*} */ Shared.synthesize(CollectionGroup.prototype, 'name'); CollectionGroup.prototype.addCollection = function (collection) { if (collection) { if (this._collections.indexOf(collection) === -1) { //var self = this; // Check for compatible primary keys if (this._collections.length) { if (this._primaryKey !== collection.primaryKey()) { throw(this.logIdentifier() + ' All collections in a collection group must have the same primary key!'); } } else { // Set the primary key to the first collection added this.primaryKey(collection.primaryKey()); } // Add the collection this._collections.push(collection); collection._groups = collection._groups || []; collection._groups.push(this); collection.chain(this); // Hook the collection's drop event to destroy group data collection.on('drop', function () { // Remove collection from any group associations if (collection._groups && collection._groups.length) { var groupArr = [], i; // Copy the group array because if we call removeCollection on a group // it will alter the groups array of this collection mid-loop! for (i = 0; i < collection._groups.length; i++) { groupArr.push(collection._groups[i]); } // Loop any groups we are part of and remove ourselves from them for (i = 0; i < groupArr.length; i++) { collection._groups[i].removeCollection(collection); } } delete collection._groups; }); // Add collection's data this._data.insert(collection.find()); } } return this; }; CollectionGroup.prototype.removeCollection = function (collection) { if (collection) { var collectionIndex = this._collections.indexOf(collection), groupIndex; if (collectionIndex !== -1) { collection.unChain(this); this._collections.splice(collectionIndex, 1); collection._groups = collection._groups || []; groupIndex = collection._groups.indexOf(this); if (groupIndex !== -1) { collection._groups.splice(groupIndex, 1); } collection.off('drop'); } if (this._collections.length === 0) { // Wipe the primary key delete this._primaryKey; } } return this; }; CollectionGroup.prototype._chainHandler = function (chainPacket) { //sender = chainPacket.sender; switch (chainPacket.type) { case 'setData': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Remove old data this._data.remove(chainPacket.options.oldData); // Add new data this._data.insert(chainPacket.data); break; case 'insert': // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Add new data this._data.insert(chainPacket.data); break; case 'update': // Update data this._data.update(chainPacket.data.query, chainPacket.data.update, chainPacket.options); break; case 'remove': this._data.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; CollectionGroup.prototype.insert = function () { this._collectionsRun('insert', arguments); }; CollectionGroup.prototype.update = function () { this._collectionsRun('update', arguments); }; CollectionGroup.prototype.updateById = function () { this._collectionsRun('updateById', arguments); }; CollectionGroup.prototype.remove = function () { this._collectionsRun('remove', arguments); }; CollectionGroup.prototype._collectionsRun = function (type, args) { for (var i = 0; i < this._collections.length; i++) { this._collections[i][type].apply(this._collections[i], args); } }; CollectionGroup.prototype.find = function (query, options) { return this._data.find(query, options); }; /** * Helper method that removes a document that matches the given id. * @param {String} id The id of the document to remove. */ CollectionGroup.prototype.removeById = function (id) { // Loop the collections in this group and apply the remove for (var i = 0; i < this._collections.length; i++) { this._collections[i].removeById(id); } }; /** * Uses the passed query to generate a new collection with results * matching the query parameters. * * @param query * @param options * @returns {*} */ CollectionGroup.prototype.subset = function (query, options) { var result = this.find(query, options); return new Collection() .subsetOf(this) .primaryKey(this._primaryKey) .setData(result); }; /** * Drops a collection group from the database. * @returns {boolean} True on success, false on failure. */ CollectionGroup.prototype.drop = function (callback) { if (!this.isDropped()) { var i, collArr, viewArr; if (this._debug) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; if (this._collections && this._collections.length) { collArr = [].concat(this._collections); for (i = 0; i < collArr.length; i++) { this.removeCollection(collArr[i]); } } if (this._view && this._view.length) { viewArr = [].concat(this._view); for (i = 0; i < viewArr.length; i++) { this._removeView(viewArr[i]); } } this.emit('drop', this); delete this._listeners; if (callback) { callback(false, true); } } return true; }; // Extend DB to include collection groups Db.prototype.init = function () { this._collectionGroup = {}; DbInit.apply(this, arguments); }; Db.prototype.collectionGroup = function (collectionGroupName) { if (collectionGroupName) { // Handle being passed an instance if (collectionGroupName instanceof CollectionGroup) { return collectionGroupName; } this._collectionGroup[collectionGroupName] = this._collectionGroup[collectionGroupName] || new CollectionGroup(collectionGroupName).db(this); return this._collectionGroup[collectionGroupName]; } else { // Return an object of collection data return this._collectionGroup; } }; /** * Returns an array of collection groups the DB currently has. * @returns {Array} An array of objects containing details of each collection group * the database is currently managing. */ Db.prototype.collectionGroups = function () { var arr = [], i; for (i in this._collectionGroup) { if (this._collectionGroup.hasOwnProperty(i)) { arr.push({ name: i }); } } return arr; }; module.exports = CollectionGroup; },{"./Collection":5,"./Shared":31}],7:[function(_dereq_,module,exports){ /* License Copyright (c) 2015 Irrelon Software Limited http://www.irrelon.com http://www.forerunnerdb.com Please visit the license page to see latest license information: http://www.forerunnerdb.com/licensing.html */ "use strict"; var Shared, Db, Metrics, Overload, _instances = []; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB instance. Core instances handle the lifecycle of * multiple database instances. * @constructor */ var Core = function (name) { this.init.apply(this, arguments); }; Core.prototype.init = function (name) { this._db = {}; this._debug = {}; this._name = name || 'ForerunnerDB'; _instances.push(this); }; /** * Returns the number of instantiated ForerunnerDB objects. * @returns {Number} The number of instantiated instances. */ Core.prototype.instantiatedCount = function () { return _instances.length; }; /** * Get all instances as an array or a single ForerunnerDB instance * by it's array index. * @param {Number=} index Optional index of instance to get. * @returns {Array|Object} Array of instances or a single instance. */ Core.prototype.instances = function (index) { if (index !== undefined) { return _instances[index]; } return _instances; }; /** * Get all instances as an array of instance names or a single ForerunnerDB * instance by it's name. * @param {String=} name Optional name of instance to get. * @returns {Array|Object} Array of instance names or a single instance. */ Core.prototype.namedInstances = function (name) { var i, instArr; if (name !== undefined) { for (i = 0; i < _instances.length; i++) { if (_instances[i].name === name) { return _instances[i]; } } return undefined; } instArr = []; for (i = 0; i < _instances.length; i++) { instArr.push(_instances[i].name); } return instArr; }; Core.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if an array of named modules are loaded and if so * calls the passed callback method. * @func moduleLoaded * @memberof Core * @param {Array} moduleName The array of module names to check for. * @param {Function} callback The callback method to call if modules are loaded. */ 'array, function': function (moduleNameArr, callback) { var moduleName, i; for (i = 0; i < moduleNameArr.length; i++) { moduleName = moduleNameArr[i]; if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } } } if (callback) { callback(); } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Core * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Core.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded() method to non-instantiated object ForerunnerDB Core.moduleLoaded = Core.prototype.moduleLoaded; // Expose version() method to non-instantiated object ForerunnerDB Core.version = Core.prototype.version; // Expose instances() method to non-instantiated object ForerunnerDB Core.instances = Core.prototype.instances; // Expose instantiatedCount() method to non-instantiated object ForerunnerDB Core.instantiatedCount = Core.prototype.instantiatedCount; // Provide public access to the Shared object Core.shared = Shared; Core.prototype.shared = Shared; Shared.addModule('Core', Core); Shared.mixin(Core.prototype, 'Mixin.Common'); Shared.mixin(Core.prototype, 'Mixin.Constants'); Db = _dereq_('./Db.js'); Metrics = _dereq_('./Metrics.js'); /** * Gets / sets the name of the instance. This is primarily used for * name-spacing persistent storage. * @param {String=} val The name of the instance to set. * @returns {*} */ Shared.synthesize(Core.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Core.prototype, 'mongoEmulation'); // Set a flag to determine environment Core.prototype._isServer = false; /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Core.prototype.isServer = function () { return this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Core.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Core.prototype.isServer = function () { return this._isServer; }; /** * Added to provide an error message for users who have not seen * the new instantiation breaking change warning and try to get * a collection directly from the core instance. */ Core.prototype.collection = function () { throw("ForerunnerDB's instantiation has changed since version 1.3.36 to support multiple database instances. Please see the readme.md file for the minor change you have to make to get your project back up and running, or see the issue related to this change at https://github.com/Irrelon/ForerunnerDB/issues/44"); }; module.exports = Core; },{"./Db.js":9,"./Metrics.js":15,"./Overload":27,"./Shared":31}],8:[function(_dereq_,module,exports){ "use strict"; /** * @mixin */ var crcTable = (function () { var crcTable = [], c, n, k; for (n = 0; n < 256; n++) { c = n; for (k = 0; k < 8; k++) { c = ((c & 1) ? (0xEDB88320 ^ (c >>> 1)) : (c >>> 1)); // jshint ignore:line } crcTable[n] = c; } return crcTable; }()); module.exports = function(str) { var crc = 0 ^ (-1), // jshint ignore:line i; for (i = 0; i < str.length; i++) { crc = (crc >>> 8) ^ crcTable[(crc ^ str.charCodeAt(i)) & 0xFF]; // jshint ignore:line } return (crc ^ (-1)) >>> 0; // jshint ignore:line }; },{}],9:[function(_dereq_,module,exports){ "use strict"; var Shared, Core, Collection, Metrics, Crc, Overload; Shared = _dereq_('./Shared'); Overload = _dereq_('./Overload'); /** * Creates a new ForerunnerDB database instance. * @constructor */ var Db = function (name, core) { this.init.apply(this, arguments); }; Db.prototype.init = function (name, core) { this.core(core); this._primaryKey = '_id'; this._name = name; this._collection = {}; this._debug = {}; }; Shared.addModule('Db', Db); Db.prototype.moduleLoaded = new Overload({ /** * Checks if a module has been loaded into the database. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @returns {Boolean} True if the module is loaded, false if not. */ 'string': function (moduleName) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } return true; } return false; }, /** * Checks if a module is loaded and if so calls the passed * callback method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} callback The callback method to call if module is loaded. */ 'string, function': function (moduleName, callback) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { return false; } } if (callback) { callback(); } } }, /** * Checks if a module is loaded and if so calls the passed * success method, otherwise calls the failure method. * @func moduleLoaded * @memberof Db * @param {String} moduleName The name of the module to check for. * @param {Function} success The callback method to call if module is loaded. * @param {Function} failure The callback method to call if module not loaded. */ 'string, function, function': function (moduleName, success, failure) { if (moduleName !== undefined) { moduleName = moduleName.replace(/ /g, ''); var modules = moduleName.split(','), index; for (index = 0; index < modules.length; index++) { if (!Shared.modules[modules[index]]) { failure(); return false; } } success(); } } }); /** * Checks version against the string passed and if it matches (or partially matches) * then the callback is called. * @param {String} val The version to check against. * @param {Function} callback The callback to call if match is true. * @returns {Boolean} */ Db.prototype.version = function (val, callback) { if (val !== undefined) { if (Shared.version.indexOf(val) === 0) { if (callback) { callback(); } return true; } return false; } return Shared.version; }; // Expose moduleLoaded method to non-instantiated object ForerunnerDB Db.moduleLoaded = Db.prototype.moduleLoaded; // Expose version method to non-instantiated object ForerunnerDB Db.version = Db.prototype.version; // Provide public access to the Shared object Db.shared = Shared; Db.prototype.shared = Shared; Shared.addModule('Db', Db); Shared.mixin(Db.prototype, 'Mixin.Common'); Shared.mixin(Db.prototype, 'Mixin.ChainReactor'); Shared.mixin(Db.prototype, 'Mixin.Constants'); Shared.mixin(Db.prototype, 'Mixin.Tags'); Core = Shared.modules.Core; Collection = _dereq_('./Collection.js'); Metrics = _dereq_('./Metrics.js'); Crc = _dereq_('./Crc.js'); Db.prototype._isServer = false; /** * Gets / sets the core object this database belongs to. */ Shared.synthesize(Db.prototype, 'core'); /** * Gets / sets the default primary key for new collections. * @param {String=} val The name of the primary key to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'primaryKey'); /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'state'); /** * Gets / sets the name of the database. * @param {String=} val The name of the database to set. * @returns {*} */ Shared.synthesize(Db.prototype, 'name'); /** * Gets / sets mongodb emulation mode. * @param {Boolean=} val True to enable, false to disable. * @returns {*} */ Shared.synthesize(Db.prototype, 'mongoEmulation'); /** * Returns true if ForerunnerDB is running on a client browser. * @returns {boolean} */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Returns true if ForerunnerDB is running on a server. * @returns {boolean} */ Db.prototype.isServer = function () { return this._isServer; }; /** * Returns a checksum of a string. * @param {String} string The string to checksum. * @return {String} The checksum generated. */ Db.prototype.crc = Crc; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a browser. */ Db.prototype.isClient = function () { return !this._isServer; }; /** * Checks if the database is running on a client (browser) or * a server (node.js). * @returns {Boolean} Returns true if running on a server. */ Db.prototype.isServer = function () { return this._isServer; }; /** * Converts a normal javascript array of objects into a DB collection. * @param {Array} arr An array of objects. * @returns {Collection} A new collection instance with the data set to the * array passed. */ Db.prototype.arrayToCollection = function (arr) { return new Collection().setData(arr); }; /** * Registers an event listener against an event name. * @param {String} event The name of the event to listen for. * @param {Function} listener The listener method to call when * the event is fired. * @returns {*} */ Db.prototype.on = function(event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || []; this._listeners[event].push(listener); return this; }; /** * De-registers an event listener from an event name. * @param {String} event The name of the event to stop listening for. * @param {Function} listener The listener method passed to on() when * registering the event listener. * @returns {*} */ Db.prototype.off = function(event, listener) { if (event in this._listeners) { var arr = this._listeners[event], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } return this; }; /** * Emits an event by name with the given data. * @param {String} event The name of the event to emit. * @param {*=} data The data to emit with the event. * @returns {*} */ Db.prototype.emit = function(event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arr = this._listeners[event], arrCount = arr.length, arrIndex; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arr[arrIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } return this; }; Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object. * @param search String or search object. * @returns {Array} */ Db.prototype.peek = function (search) { var i, coll, arr = [], typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = arr.concat(coll.peek(search)); } else { arr = arr.concat(coll.find(search)); } } } return arr; }; /** * Find all documents across all collections in the database that match the passed * string or search object and return them in an object where each key is the name * of the collection that the document was matched in. * @param search String or search object. * @returns {object} */ Db.prototype.peekCat = function (search) { var i, coll, cat = {}, arr, typeOfSearch = typeof search; // Loop collections for (i in this._collection) { if (this._collection.hasOwnProperty(i)) { coll = this._collection[i]; if (typeOfSearch === 'string') { arr = coll.peek(search); if (arr && arr.length) { cat[coll.name()] = arr; } } else { arr = coll.find(search); if (arr && arr.length) { cat[coll.name()] = arr; } } } } return cat; }; Db.prototype.drop = new Overload({ /** * Drops the database. * @func drop * @memberof Db */ '': function () { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional callback method. * @func drop * @memberof Db * @param {Function} callback Optional callback method. */ 'function': function (callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database with optional persistent storage drop. Persistent * storage is dropped by default if no preference is provided. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. */ 'boolean': function (removePersist) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; }, /** * Drops the database and optionally controls dropping persistent storage * and callback method. * @func drop * @memberof Db * @param {Boolean} removePersist Drop persistent storage for this database. * @param {Function} callback Optional callback method. */ 'boolean, function': function (removePersist, callback) { if (!this.isDropped()) { var arr = this.collections(), arrCount = arr.length, arrIndex, finishCount = 0, afterDrop = function () { finishCount++; if (finishCount === arrCount) { if (callback) { callback(); } } }; this._state = 'dropped'; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { this.collection(arr[arrIndex].name).drop(removePersist, afterDrop); delete this._collection[arr[arrIndex].name]; } this.emit('drop', this); delete this._listeners; delete this._core._db[this._name]; } return true; } }); /** * Gets a database instance by name. * @memberof Core * @param {String=} name Optional name of the database. If none is provided * a random name is assigned. * @returns {Db} */ Core.prototype.db = function (name) { // Handle being passed an instance if (name instanceof Db) { return name; } if (!name) { name = this.objectId(); } this._db[name] = this._db[name] || new Db(name, this); this._db[name].mongoEmulation(this.mongoEmulation()); return this._db[name]; }; /** * Returns an array of databases that ForerunnerDB currently has. * @memberof Core * @param {String|RegExp=} search The optional search string or regular expression to use * to match collection names against. * @returns {Array} An array of objects containing details of each database * that ForerunnerDB is currently managing and it's child entities. */ Core.prototype.databases = function (search) { var arr = [], tmpObj, addDb, i; if (search) { if (!(search instanceof RegExp)) { // Turn the search into a regular expression search = new RegExp(search); } } for (i in this._db) { if (this._db.hasOwnProperty(i)) { addDb = true; if (search) { if (!search.exec(i)) { addDb = false; } } if (addDb) { tmpObj = { name: i, children: [] }; if (this.shared.moduleExists('Collection')) { tmpObj.children.push({ module: 'collection', moduleName: 'Collections', count: this._db[i].collections().length }); } if (this.shared.moduleExists('CollectionGroup')) { tmpObj.children.push({ module: 'collectionGroup', moduleName: 'Collection Groups', count: this._db[i].collectionGroups().length }); } if (this.shared.moduleExists('Document')) { tmpObj.children.push({ module: 'document', moduleName: 'Documents', count: this._db[i].documents().length }); } if (this.shared.moduleExists('Grid')) { tmpObj.children.push({ module: 'grid', moduleName: 'Grids', count: this._db[i].grids().length }); } if (this.shared.moduleExists('Overview')) { tmpObj.children.push({ module: 'overview', moduleName: 'Overviews', count: this._db[i].overviews().length }); } if (this.shared.moduleExists('View')) { tmpObj.children.push({ module: 'view', moduleName: 'Views', count: this._db[i].views().length }); } arr.push(tmpObj); } } } arr.sort(function (a, b) { return a.name.localeCompare(b.name); }); return arr; }; Shared.finishModule('Db'); module.exports = Db; },{"./Collection.js":5,"./Crc.js":8,"./Metrics.js":15,"./Overload":27,"./Shared":31}],10:[function(_dereq_,module,exports){ // geohash.js // Geohash library for Javascript // (c) 2008 David Troy // Distributed under the MIT License // Original at: https://github.com/davetroy/geohash-js // Modified by Irrelon Software Limited (http://www.irrelon.com) // to clean up and modularise the code using Node.js-style exports // and add a few helper methods. // @by Rob Evans - rob@irrelon.com "use strict"; /* Define some shared constants that will be used by all instances of the module. */ var bits, base32, neighbors, borders; bits = [16, 8, 4, 2, 1]; base32 = "0123456789bcdefghjkmnpqrstuvwxyz"; neighbors = { right: {even: "bc01fg45238967deuvhjyznpkmstqrwx"}, left: {even: "238967debc01fg45kmstqrwxuvhjyznp"}, top: {even: "p0r21436x8zb9dcf5h7kjnmqesgutwvy"}, bottom: {even: "14365h7k9dcfesgujnmqp0r2twvyx8zb"} }; borders = { right: {even: "bcfguvyz"}, left: {even: "0145hjnp"}, top: {even: "prxz"}, bottom: {even: "028b"} }; neighbors.bottom.odd = neighbors.left.even; neighbors.top.odd = neighbors.right.even; neighbors.left.odd = neighbors.bottom.even; neighbors.right.odd = neighbors.top.even; borders.bottom.odd = borders.left.even; borders.top.odd = borders.right.even; borders.left.odd = borders.bottom.even; borders.right.odd = borders.top.even; var GeoHash = function () {}; GeoHash.prototype.refineInterval = function (interval, cd, mask) { if (cd & mask) { //jshint ignore: line interval[0] = (interval[0] + interval[1]) / 2; } else { interval[1] = (interval[0] + interval[1]) / 2; } }; /** * Calculates all surrounding neighbours of a hash and returns them. * @param {String} centerHash The hash at the center of the grid. * @param options * @returns {*} */ GeoHash.prototype.calculateNeighbours = function (centerHash, options) { var response; if (!options || options.type === 'object') { response = { center: centerHash, left: this.calculateAdjacent(centerHash, 'left'), right: this.calculateAdjacent(centerHash, 'right'), top: this.calculateAdjacent(centerHash, 'top'), bottom: this.calculateAdjacent(centerHash, 'bottom') }; response.topLeft = this.calculateAdjacent(response.left, 'top'); response.topRight = this.calculateAdjacent(response.right, 'top'); response.bottomLeft = this.calculateAdjacent(response.left, 'bottom'); response.bottomRight = this.calculateAdjacent(response.right, 'bottom'); } else { response = []; response[4] = centerHash; response[3] = this.calculateAdjacent(centerHash, 'left'); response[5] = this.calculateAdjacent(centerHash, 'right'); response[1] = this.calculateAdjacent(centerHash, 'top'); response[7] = this.calculateAdjacent(centerHash, 'bottom'); response[0] = this.calculateAdjacent(response[3], 'top'); response[2] = this.calculateAdjacent(response[5], 'top'); response[6] = this.calculateAdjacent(response[3], 'bottom'); response[8] = this.calculateAdjacent(response[5], 'bottom'); } return response; }; /** * Calculates an adjacent hash to the hash passed, in the direction * specified. * @param {String} srcHash The hash to calculate adjacent to. * @param {String} dir Either "top", "left", "bottom" or "right". * @returns {String} The resulting geohash. */ GeoHash.prototype.calculateAdjacent = function (srcHash, dir) { srcHash = srcHash.toLowerCase(); var lastChr = srcHash.charAt(srcHash.length - 1), type = (srcHash.length % 2) ? 'odd' : 'even', base = srcHash.substring(0, srcHash.length - 1); if (borders[dir][type].indexOf(lastChr) !== -1) { base = this.calculateAdjacent(base, dir); } return base + base32[neighbors[dir][type].indexOf(lastChr)]; }; /** * Decodes a string geohash back to longitude/latitude. * @param {String} geohash The hash to decode. * @returns {Object} */ GeoHash.prototype.decode = function (geohash) { var isEven = 1, lat = [], lon = [], i, c, cd, j, mask, latErr, lonErr; lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; latErr = 90.0; lonErr = 180.0; for (i = 0; i < geohash.length; i++) { c = geohash[i]; cd = base32.indexOf(c); for (j = 0; j < 5; j++) { mask = bits[j]; if (isEven) { lonErr /= 2; this.refineInterval(lon, cd, mask); } else { latErr /= 2; this.refineInterval(lat, cd, mask); } isEven = !isEven; } } lat[2] = (lat[0] + lat[1]) / 2; lon[2] = (lon[0] + lon[1]) / 2; return { latitude: lat, longitude: lon }; }; /** * Encodes a longitude/latitude to geohash string. * @param latitude * @param longitude * @param {Number=} precision Length of the geohash string. Defaults to 12. * @returns {String} */ GeoHash.prototype.encode = function (latitude, longitude, precision) { var isEven = 1, mid, lat = [], lon = [], bit = 0, ch = 0, geoHash = ""; if (!precision) { precision = 12; } lat[0] = -90.0; lat[1] = 90.0; lon[0] = -180.0; lon[1] = 180.0; while (geoHash.length < precision) { if (isEven) { mid = (lon[0] + lon[1]) / 2; if (longitude > mid) { ch |= bits[bit]; //jshint ignore: line lon[0] = mid; } else { lon[1] = mid; } } else { mid = (lat[0] + lat[1]) / 2; if (latitude > mid) { ch |= bits[bit]; //jshint ignore: line lat[0] = mid; } else { lat[1] = mid; } } isEven = !isEven; if (bit < 4) { bit++; } else { geoHash += base32[ch]; bit = 0; ch = 0; } } return geoHash; }; module.exports = GeoHash; },{}],11:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'), GeoHash = _dereq_('./GeoHash'), sharedPathSolver = new Path(), sharedGeoHashSolver = new GeoHash(), // GeoHash Distances in Kilometers geoHashDistance = [ 5000, 1250, 156, 39.1, 4.89, 1.22, 0.153, 0.0382, 0.00477, 0.00119, 0.000149, 0.0000372 ]; /** * The index class used to instantiate 2d indexes that the database can * use to handle high-performance geospatial queries. * @constructor */ var Index2d = function () { this.init.apply(this, arguments); }; Index2d.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('Index2d', Index2d); Shared.mixin(Index2d.prototype, 'Mixin.Common'); Shared.mixin(Index2d.prototype, 'Mixin.ChainReactor'); Shared.mixin(Index2d.prototype, 'Mixin.Sorting'); Index2d.prototype.id = function () { return this._id; }; Index2d.prototype.state = function () { return this._state; }; Index2d.prototype.size = function () { return this._size; }; Shared.synthesize(Index2d.prototype, 'data'); Shared.synthesize(Index2d.prototype, 'name'); Shared.synthesize(Index2d.prototype, 'collection'); Shared.synthesize(Index2d.prototype, 'type'); Shared.synthesize(Index2d.prototype, 'unique'); Index2d.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = sharedPathSolver.parse(this._keys).length; return this; } return this._keys; }; Index2d.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; Index2d.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; dataItem = this.decouple(dataItem); if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Convert 2d indexed values to geohashes var keys = this._btree.keys(), pathVal, geoHash, lng, lat, i; for (i = 0; i < keys.length; i++) { pathVal = sharedPathSolver.get(dataItem, keys[i].path); if (pathVal instanceof Array) { lng = pathVal[0]; lat = pathVal[1]; geoHash = sharedGeoHashSolver.encode(lng, lat); sharedPathSolver.set(dataItem, keys[i].path, geoHash); } } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; Index2d.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; Index2d.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; Index2d.prototype.lookup = function (query, options) { // Loop the indexed keys and determine if the query has any operators // that we want to handle differently from a standard lookup var keys = this._btree.keys(), pathStr, pathVal, results, i; for (i = 0; i < keys.length; i++) { pathStr = keys[i].path; pathVal = sharedPathSolver.get(query, pathStr); if (typeof pathVal === 'object') { if (pathVal.$near) { results = []; // Do a near point lookup results = results.concat(this.near(pathStr, pathVal.$near, options)); } if (pathVal.$geoWithin) { results = []; // Do a geoWithin shape lookup results = results.concat(this.geoWithin(pathStr, pathVal.$geoWithin, options)); } return results; } } return this._btree.lookup(query, options); }; Index2d.prototype.near = function (pathStr, query, options) { var self = this, geoHash, neighbours, visited, search, results, finalResults = [], precision, maxDistanceKm, distance, distCache, latLng, pk = this._collection.primaryKey(), i; // Calculate the required precision to encapsulate the distance // TODO: Instead of opting for the "one size larger" than the distance boxes, // TODO: we should calculate closest divisible box size as a multiple and then // TODO: scan neighbours until we have covered the area otherwise we risk // TODO: opening the results up to vastly more information as the box size // TODO: increases dramatically between the geohash precisions if (query.$distanceUnits === 'km') { maxDistanceKm = query.$maxDistance; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } else if (query.$distanceUnits === 'miles') { maxDistanceKm = query.$maxDistance * 1.60934; for (i = 0; i < geoHashDistance.length; i++) { if (maxDistanceKm > geoHashDistance[i]) { precision = i; break; } } if (precision === 0) { precision = 1; } } // Get the lngLat geohash from the query geoHash = sharedGeoHashSolver.encode(query.$point[0], query.$point[1], precision); // Calculate 9 box geohashes neighbours = sharedGeoHashSolver.calculateNeighbours(geoHash, {type: 'array'}); // Lookup all matching co-ordinates from the btree results = []; visited = 0; for (i = 0; i < 9; i++) { search = this._btree.startsWith(pathStr, neighbours[i]); visited += search._visited; results = results.concat(search); } // Work with original data results = this._collection._primaryIndex.lookup(results); if (results.length) { distance = {}; // Loop the results and calculate distance for (i = 0; i < results.length; i++) { latLng = sharedPathSolver.get(results[i], pathStr); distCache = distance[results[i][pk]] = this.distanceBetweenPoints(query.$point[0], query.$point[1], latLng[0], latLng[1]); if (distCache <= maxDistanceKm) { // Add item inside radius distance finalResults.push(results[i]); } } // Sort by distance from center finalResults.sort(function (a, b) { return self.sortAsc(distance[a[pk]], distance[b[pk]]); }); } // Return data return finalResults; }; Index2d.prototype.geoWithin = function (pathStr, query, options) { return []; }; Index2d.prototype.distanceBetweenPoints = function (lat1, lng1, lat2, lng2) { var R = 6371; // kilometres var φ1 = this.toRadians(lat1); var φ2 = this.toRadians(lat2); var Δφ = this.toRadians(lat2-lat1); var Δλ = this.toRadians(lng2-lng1); var a = Math.sin(Δφ/2) * Math.sin(Δφ/2) + Math.cos(φ1) * Math.cos(φ2) * Math.sin(Δλ/2) * Math.sin(Δλ/2); var c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a)); return R * c; }; Index2d.prototype.toRadians = function (degrees) { return degrees * 0.01747722222222; }; Index2d.prototype.match = function (query, options) { // TODO: work out how to represent that this is a better match if the query has $near than // TODO: a basic btree index which will not be able to resolve a $near operator return this._btree.match(query, options); }; Index2d.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; Index2d.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; Index2d.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('Index2d'); module.exports = Index2d; },{"./BinaryTree":4,"./GeoHash":10,"./Path":28,"./Shared":31}],12:[function(_dereq_,module,exports){ "use strict"; /* name(string) id(string) rebuild(null) state ?? needed? match(query, options) lookup(query, options) insert(doc) remove(doc) primaryKey(string) collection(collection) */ var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'), BinaryTree = _dereq_('./BinaryTree'); /** * The index class used to instantiate btree indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexBinaryTree = function () { this.init.apply(this, arguments); }; IndexBinaryTree.prototype.init = function (keys, options, collection) { this._btree = new BinaryTree(); this._btree.index(keys); this._size = 0; this._id = this._itemKeyHash(keys, keys); this._debug = options && options.debug ? options.debug : false; this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); this._btree.primaryKey(collection.primaryKey()); } this.name(options && options.name ? options.name : this._id); this._btree.debug(this._debug); }; Shared.addModule('IndexBinaryTree', IndexBinaryTree); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.ChainReactor'); Shared.mixin(IndexBinaryTree.prototype, 'Mixin.Sorting'); IndexBinaryTree.prototype.id = function () { return this._id; }; IndexBinaryTree.prototype.state = function () { return this._state; }; IndexBinaryTree.prototype.size = function () { return this._size; }; Shared.synthesize(IndexBinaryTree.prototype, 'data'); Shared.synthesize(IndexBinaryTree.prototype, 'name'); Shared.synthesize(IndexBinaryTree.prototype, 'collection'); Shared.synthesize(IndexBinaryTree.prototype, 'type'); Shared.synthesize(IndexBinaryTree.prototype, 'unique'); IndexBinaryTree.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexBinaryTree.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._btree.clear(); this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexBinaryTree.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } if (this._btree.insert(dataItem)) { this._size++; return true; } return false; }; IndexBinaryTree.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } if (this._btree.remove(dataItem)) { this._size--; return true; } return false; }; IndexBinaryTree.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexBinaryTree.prototype.lookup = function (query, options) { return this._btree.lookup(query, options); }; IndexBinaryTree.prototype.match = function (query, options) { return this._btree.match(query, options); }; IndexBinaryTree.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexBinaryTree.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexBinaryTree.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexBinaryTree'); module.exports = IndexBinaryTree; },{"./BinaryTree":4,"./Path":28,"./Shared":31}],13:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The index class used to instantiate hash map indexes that the database can * use to speed up queries on collections and views. * @constructor */ var IndexHashMap = function () { this.init.apply(this, arguments); }; IndexHashMap.prototype.init = function (keys, options, collection) { this._crossRef = {}; this._size = 0; this._id = this._itemKeyHash(keys, keys); this.data({}); this.unique(options && options.unique ? options.unique : false); if (keys !== undefined) { this.keys(keys); } if (collection !== undefined) { this.collection(collection); } this.name(options && options.name ? options.name : this._id); }; Shared.addModule('IndexHashMap', IndexHashMap); Shared.mixin(IndexHashMap.prototype, 'Mixin.ChainReactor'); IndexHashMap.prototype.id = function () { return this._id; }; IndexHashMap.prototype.state = function () { return this._state; }; IndexHashMap.prototype.size = function () { return this._size; }; Shared.synthesize(IndexHashMap.prototype, 'data'); Shared.synthesize(IndexHashMap.prototype, 'name'); Shared.synthesize(IndexHashMap.prototype, 'collection'); Shared.synthesize(IndexHashMap.prototype, 'type'); Shared.synthesize(IndexHashMap.prototype, 'unique'); IndexHashMap.prototype.keys = function (val) { if (val !== undefined) { this._keys = val; // Count the keys this._keyCount = (new Path()).parse(this._keys).length; return this; } return this._keys; }; IndexHashMap.prototype.rebuild = function () { // Do we have a collection? if (this._collection) { // Get sorted data var collection = this._collection.subset({}, { $decouple: false, $orderBy: this._keys }), collectionData = collection.find(), dataIndex, dataCount = collectionData.length; // Clear the index data for the index this._data = {}; this._size = 0; if (this._unique) { this._uniqueLookup = {}; } // Loop the collection data for (dataIndex = 0; dataIndex < dataCount; dataIndex++) { this.insert(collectionData[dataIndex]); } } this._state = { name: this._name, keys: this._keys, indexSize: this._size, built: new Date(), updated: new Date(), ok: true }; }; IndexHashMap.prototype.insert = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); this._uniqueLookup[uniqueHash] = dataItem; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pushToPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.update = function (dataItem, options) { // TODO: Write updates to work // 1: Get uniqueHash for the dataItem primary key value (may need to generate a store for this) // 2: Remove the uniqueHash as it currently stands // 3: Generate a new uniqueHash for dataItem // 4: Insert the new uniqueHash }; IndexHashMap.prototype.remove = function (dataItem, options) { var uniqueFlag = this._unique, uniqueHash, itemHashArr, hashIndex; if (uniqueFlag) { uniqueHash = this._itemHash(dataItem, this._keys); delete this._uniqueLookup[uniqueHash]; } // Generate item hash itemHashArr = this._itemHashArr(dataItem, this._keys); // Get the path search results and store them for (hashIndex = 0; hashIndex < itemHashArr.length; hashIndex++) { this.pullFromPathValue(itemHashArr[hashIndex], dataItem); } }; IndexHashMap.prototype.violation = function (dataItem) { // Generate item hash var uniqueHash = this._itemHash(dataItem, this._keys); // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.hashViolation = function (uniqueHash) { // Check if the item breaks the unique constraint return Boolean(this._uniqueLookup[uniqueHash]); }; IndexHashMap.prototype.pushToPathValue = function (hash, obj) { var pathValArr = this._data[hash] = this._data[hash] || []; // Make sure we have not already indexed this object at this path/value if (pathValArr.indexOf(obj) === -1) { // Index the object pathValArr.push(obj); // Record the reference to this object in our index size this._size++; // Cross-reference this association for later lookup this.pushToCrossRef(obj, pathValArr); } }; IndexHashMap.prototype.pullFromPathValue = function (hash, obj) { var pathValArr = this._data[hash], indexOfObject; // Make sure we have already indexed this object at this path/value indexOfObject = pathValArr.indexOf(obj); if (indexOfObject > -1) { // Un-index the object pathValArr.splice(indexOfObject, 1); // Record the reference to this object in our index size this._size--; // Remove object cross-reference this.pullFromCrossRef(obj, pathValArr); } // Check if we should remove the path value array if (!pathValArr.length) { // Remove the array delete this._data[hash]; } }; IndexHashMap.prototype.pull = function (obj) { // Get all places the object has been used and remove them var id = obj[this._collection.primaryKey()], crossRefArr = this._crossRef[id], arrIndex, arrCount = crossRefArr.length, arrItem; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { arrItem = crossRefArr[arrIndex]; // Remove item from this index lookup array this._pullFromArray(arrItem, obj); } // Record the reference to this object in our index size this._size--; // Now remove the cross-reference entry for this object delete this._crossRef[id]; }; IndexHashMap.prototype._pullFromArray = function (arr, obj) { var arrCount = arr.length; while (arrCount--) { if (arr[arrCount] === obj) { arr.splice(arrCount, 1); } } }; IndexHashMap.prototype.pushToCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()], crObj; this._crossRef[id] = this._crossRef[id] || []; // Check if the cross-reference to the pathVal array already exists crObj = this._crossRef[id]; if (crObj.indexOf(pathValArr) === -1) { // Add the cross-reference crObj.push(pathValArr); } }; IndexHashMap.prototype.pullFromCrossRef = function (obj, pathValArr) { var id = obj[this._collection.primaryKey()]; delete this._crossRef[id]; }; IndexHashMap.prototype.lookup = function (query) { return this._data[this._itemHash(query, this._keys)] || []; }; IndexHashMap.prototype.match = function (query, options) { // Check if the passed query has data in the keys our index // operates on and if so, is the query sort matching our order var pathSolver = new Path(); var indexKeyArr = pathSolver.parseArr(this._keys), queryArr = pathSolver.parseArr(query), matchedKeys = [], matchedKeyCount = 0, i; // Loop the query array and check the order of keys against the // index key array to see if this index can be used for (i = 0; i < indexKeyArr.length; i++) { if (queryArr[i] === indexKeyArr[i]) { matchedKeyCount++; matchedKeys.push(queryArr[i]); } else { // Query match failed - this is a hash map index so partial key match won't work return { matchedKeys: [], totalKeyCount: queryArr.length, score: 0 }; } } return { matchedKeys: matchedKeys, totalKeyCount: queryArr.length, score: matchedKeyCount }; //return pathSolver.countObjectPaths(this._keys, query); }; IndexHashMap.prototype._itemHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.value(item, pathData[k].path).join(':'); } return hash; }; IndexHashMap.prototype._itemKeyHash = function (item, keys) { var path = new Path(), pathData, hash = '', k; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { if (hash) { hash += '_'; } hash += path.keyValue(item, pathData[k].path); } return hash; }; IndexHashMap.prototype._itemHashArr = function (item, keys) { var path = new Path(), pathData, //hash = '', hashArr = [], valArr, i, k, j; pathData = path.parse(keys); for (k = 0; k < pathData.length; k++) { valArr = path.value(item, pathData[k].path); for (i = 0; i < valArr.length; i++) { if (k === 0) { // Setup the initial hash array hashArr.push(valArr[i]); } else { // Loop the hash array and concat the value to it for (j = 0; j < hashArr.length; j++) { hashArr[j] = hashArr[j] + '_' + valArr[i]; } } } } return hashArr; }; Shared.finishModule('IndexHashMap'); module.exports = IndexHashMap; },{"./Path":28,"./Shared":31}],14:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * The key value store class used when storing basic in-memory KV data, * and can be queried for quick retrieval. Mostly used for collection * primary key indexes and lookups. * @param {String=} name Optional KV store name. * @constructor */ var KeyValueStore = function (name) { this.init.apply(this, arguments); }; KeyValueStore.prototype.init = function (name) { this._name = name; this._data = {}; this._primaryKey = '_id'; }; Shared.addModule('KeyValueStore', KeyValueStore); Shared.mixin(KeyValueStore.prototype, 'Mixin.ChainReactor'); /** * Get / set the name of the key/value store. * @param {String} val The name to set. * @returns {*} */ Shared.synthesize(KeyValueStore.prototype, 'name'); /** * Get / set the primary key. * @param {String} key The key to set. * @returns {*} */ KeyValueStore.prototype.primaryKey = function (key) { if (key !== undefined) { this._primaryKey = key; return this; } return this._primaryKey; }; /** * Removes all data from the store. * @returns {*} */ KeyValueStore.prototype.truncate = function () { this._data = {}; return this; }; /** * Sets data against a key in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {*} */ KeyValueStore.prototype.set = function (key, value) { this._data[key] = value ? value : true; return this; }; /** * Gets data stored for the passed key. * @param {String} key The key to get data for. * @returns {*} */ KeyValueStore.prototype.get = function (key) { return this._data[key]; }; /** * Get / set the primary key. * @param {*} val A lookup query. * @returns {*} */ KeyValueStore.prototype.lookup = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, result = []; // Check for early exit conditions if (valType === 'string' || valType === 'number') { lookupItem = this.get(val); if (lookupItem !== undefined) { return [lookupItem]; } else { return []; } } else if (valType === 'object') { if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { lookupItem = this.lookup(val[arrIndex]); if (lookupItem) { if (lookupItem instanceof Array) { result = result.concat(lookupItem); } else { result.push(lookupItem); } } } return result; } else if (val[pk]) { return this.lookup(val[pk]); } } // COMMENTED AS CODE WILL NEVER BE REACHED // Complex lookup /*lookupData = this._lookupKeys(val); keys = lookupData.keys; negate = lookupData.negate; if (!negate) { // Loop keys and return values for (arrIndex = 0; arrIndex < keys.length; arrIndex++) { result.push(this.get(keys[arrIndex])); } } else { // Loop data and return non-matching keys for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (keys.indexOf(arrIndex) === -1) { result.push(this.get(arrIndex)); } } } } return result;*/ }; // COMMENTED AS WE ARE NOT CURRENTLY PASSING COMPLEX QUERIES TO KEYVALUESTORE INDEXES /*KeyValueStore.prototype._lookupKeys = function (val) { var pk = this._primaryKey, valType = typeof val, arrIndex, arrCount, lookupItem, bool, result; if (valType === 'string' || valType === 'number') { return { keys: [val], negate: false }; } else if (valType === 'object') { if (val instanceof RegExp) { // Create new data result = []; for (arrIndex in this._data) { if (this._data.hasOwnProperty(arrIndex)) { if (val.test(arrIndex)) { result.push(arrIndex); } } } return { keys: result, negate: false }; } else if (val instanceof Array) { // An array of primary keys, find all matches arrCount = val.length; result = []; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { result = result.concat(this._lookupKeys(val[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val.$in && (val.$in instanceof Array)) { return { keys: this._lookupKeys(val.$in).keys, negate: false }; } else if (val.$nin && (val.$nin instanceof Array)) { return { keys: this._lookupKeys(val.$nin).keys, negate: true }; } else if (val.$ne) { return { keys: this._lookupKeys(val.$ne, true).keys, negate: true }; } else if (val.$or && (val.$or instanceof Array)) { // Create new data result = []; for (arrIndex = 0; arrIndex < val.$or.length; arrIndex++) { result = result.concat(this._lookupKeys(val.$or[arrIndex]).keys); } return { keys: result, negate: false }; } else if (val[pk]) { return this._lookupKeys(val[pk]); } } };*/ /** * Removes data for the given key from the store. * @param {String} key The key to un-set. * @returns {*} */ KeyValueStore.prototype.unSet = function (key) { delete this._data[key]; return this; }; /** * Sets data for the give key in the store only where the given key * does not already have a value in the store. * @param {String} key The key to set data for. * @param {*} value The value to assign to the key. * @returns {Boolean} True if data was set or false if data already * exists for the key. */ KeyValueStore.prototype.uniqueSet = function (key, value) { if (this._data[key] === undefined) { this._data[key] = value; return true; } return false; }; Shared.finishModule('KeyValueStore'); module.exports = KeyValueStore; },{"./Shared":31}],15:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Operation = _dereq_('./Operation'); /** * The metrics class used to store details about operations. * @constructor */ var Metrics = function () { this.init.apply(this, arguments); }; Metrics.prototype.init = function () { this._data = []; }; Shared.addModule('Metrics', Metrics); Shared.mixin(Metrics.prototype, 'Mixin.ChainReactor'); /** * Creates an operation within the metrics instance and if metrics * are currently enabled (by calling the start() method) the operation * is also stored in the metrics log. * @param {String} name The name of the operation. * @returns {Operation} */ Metrics.prototype.create = function (name) { var op = new Operation(name); if (this._enabled) { this._data.push(op); } return op; }; /** * Starts logging operations. * @returns {Metrics} */ Metrics.prototype.start = function () { this._enabled = true; return this; }; /** * Stops logging operations. * @returns {Metrics} */ Metrics.prototype.stop = function () { this._enabled = false; return this; }; /** * Clears all logged operations. * @returns {Metrics} */ Metrics.prototype.clear = function () { this._data = []; return this; }; /** * Returns an array of all logged operations. * @returns {Array} */ Metrics.prototype.list = function () { return this._data; }; Shared.finishModule('Metrics'); module.exports = Metrics; },{"./Operation":26,"./Shared":31}],16:[function(_dereq_,module,exports){ "use strict"; var CRUD = { preSetData: function () { }, postSetData: function () { } }; module.exports = CRUD; },{}],17:[function(_dereq_,module,exports){ "use strict"; /** * The chain reactor mixin, provides methods to the target object that allow chain * reaction events to propagate to the target and be handled, processed and passed * on down the chain. * @mixin */ var ChainReactor = { /** * * @param obj */ chain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Adding target "' + obj._reactorOut.instanceIdentifier() + '" to the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Adding target "' + obj.instanceIdentifier() + '" to the chain reactor target list'); } } this._chain = this._chain || []; var index = this._chain.indexOf(obj); if (index === -1) { this._chain.push(obj); } }, unChain: function (obj) { if (this.debug && this.debug()) { if (obj._reactorIn && obj._reactorOut) { console.log(obj._reactorIn.logIdentifier() + ' Removing target "' + obj._reactorOut.instanceIdentifier() + '" from the chain reactor target list'); } else { console.log(this.logIdentifier() + ' Removing target "' + obj.instanceIdentifier() + '" from the chain reactor target list'); } } if (this._chain) { var index = this._chain.indexOf(obj); if (index > -1) { this._chain.splice(index, 1); } } }, chainSend: function (type, data, options) { if (this._chain) { var arr = this._chain, arrItem, count = arr.length, index; for (index = 0; index < count; index++) { arrItem = arr[index]; if (!arrItem._state || (arrItem._state && !arrItem.isDropped())) { if (this.debug && this.debug()) { if (arrItem._reactorIn && arrItem._reactorOut) { console.log(arrItem._reactorIn.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem._reactorOut.instanceIdentifier() + '"'); } else { console.log(this.logIdentifier() + ' Sending data down the chain reactor pipe to "' + arrItem.instanceIdentifier() + '"'); } } if (arrItem.chainReceive) { arrItem.chainReceive(this, type, data, options); } } else { console.log('Reactor Data:', type, data, options); console.log('Reactor Node:', arrItem); throw('Chain reactor attempting to send data to target reactor node that is in a dropped state!'); } } } }, chainReceive: function (sender, type, data, options) { var chainPacket = { sender: sender, type: type, data: data, options: options }; if (this.debug && this.debug()) { console.log(this.logIdentifier() + 'Received data from parent reactor node'); } // Fire our internal handler if (!this._chainHandler || (this._chainHandler && !this._chainHandler(chainPacket))) { // Propagate the message down the chain this.chainSend(chainPacket.type, chainPacket.data, chainPacket.options); } } }; module.exports = ChainReactor; },{}],18:[function(_dereq_,module,exports){ "use strict"; var idCounter = 0, Overload = _dereq_('./Overload'), Serialiser = _dereq_('./Serialiser'), Common, serialiser = new Serialiser(); /** * Provides commonly used methods to most classes in ForerunnerDB. * @mixin */ Common = { // Expose the serialiser object so it can be extended with new data handlers. serialiser: serialiser, /** * Gets / sets data in the item store. The store can be used to set and * retrieve data against a key. Useful for adding arbitrary key/value data * to a collection / view etc and retrieving it later. * @param {String|*} key The key under which to store the passed value or * retrieve the existing stored value. * @param {*=} val Optional value. If passed will overwrite the existing value * stored against the specified key if one currently exists. * @returns {*} */ store: function (key, val) { if (key !== undefined) { if (val !== undefined) { // Store the data this._store = this._store || {}; this._store[key] = val; return this; } if (this._store) { return this._store[key]; } } return undefined; }, /** * Removes a previously stored key/value pair from the item store, set previously * by using the store() method. * @param {String|*} key The key of the key/value pair to remove; * @returns {Common} Returns this for chaining. */ unStore: function (key) { if (key !== undefined) { delete this._store[key]; } return this; }, /** * Returns a non-referenced version of the passed object / array. * @param {Object} data The object or array to return as a non-referenced version. * @param {Number=} copies Optional number of copies to produce. If specified, the return * value will be an array of decoupled objects, each distinct from the other. * @returns {*} */ decouple: function (data, copies) { if (data !== undefined) { if (!copies) { return this.jParse(this.jStringify(data)); } else { var i, json = this.jStringify(data), copyArr = []; for (i = 0; i < copies; i++) { copyArr.push(this.jParse(json)); } return copyArr; } } return undefined; }, /** * Parses and returns data from stringified version. * @param {String} data The stringified version of data to parse. * @returns {Object} The parsed JSON object from the data. */ jParse: function (data) { return serialiser.parse(data); //return JSON.parse(data); }, /** * Converts a JSON object into a stringified version. * @param {Object} data The data to stringify. * @returns {String} The stringified data. */ jStringify: function (data) { return serialiser.stringify(data); //return JSON.stringify(data); }, /** * Generates a new 16-character hexadecimal unique ID or * generates a new 16-character hexadecimal ID based on * the passed string. Will always generate the same ID * for the same string. * @param {String=} str A string to generate the ID from. * @return {String} */ objectId: function (str) { var id, pow = Math.pow(10, 17); if (!str) { idCounter++; id = (idCounter + ( Math.random() * pow + Math.random() * pow + Math.random() * pow + Math.random() * pow )).toString(16); } else { var val = 0, count = str.length, i; for (i = 0; i < count; i++) { val += str.charCodeAt(i) * pow; } id = val.toString(16); } return id; }, /** * Gets / sets debug flag that can enable debug message output to the * console if required. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ /** * Sets debug flag for a particular type that can enable debug message * output to the console if required. * @param {String} type The name of the debug type to set flag for. * @param {Boolean} val The value to set debug flag to. * @return {Boolean} True if enabled, false otherwise. */ debug: new Overload([ function () { return this._debug && this._debug.all; }, function (val) { if (val !== undefined) { if (typeof val === 'boolean') { this._debug = this._debug || {}; this._debug.all = val; this.chainSend('debug', this._debug); return this; } else { return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[val]) || (this._debug && this._debug.all); } } return this._debug && this._debug.all; }, function (type, val) { if (type !== undefined) { if (val !== undefined) { this._debug = this._debug || {}; this._debug[type] = val; this.chainSend('debug', this._debug); return this; } return (this._debug && this._debug[val]) || (this._db && this._db._debug && this._db._debug[type]); } return this._debug && this._debug.all; } ]), /** * Returns a string describing the class this instance is derived from. * @returns {string} */ classIdentifier: function () { return 'ForerunnerDB.' + this.className; }, /** * Returns a string describing the instance by it's class name and instance * object name. * @returns {String} The instance identifier. */ instanceIdentifier: function () { return '[' + this.className + ']' + this.name(); }, /** * Returns a string used to denote a console log against this instance, * consisting of the class identifier and instance identifier. * @returns {string} The log identifier. */ logIdentifier: function () { return this.classIdentifier() + ': ' + this.instanceIdentifier(); }, /** * Converts a query object with MongoDB dot notation syntax * to Forerunner's object notation syntax. * @param {Object} obj The object to convert. */ convertToFdb: function (obj) { var varName, splitArr, objCopy, i; for (i in obj) { if (obj.hasOwnProperty(i)) { objCopy = obj; if (i.indexOf('.') > -1) { // Replace .$ with a placeholder before splitting by . char i = i.replace('.$', '[|$|]'); splitArr = i.split('.'); while ((varName = splitArr.shift())) { // Replace placeholder back to original .$ varName = varName.replace('[|$|]', '.$'); if (splitArr.length) { objCopy[varName] = {}; } else { objCopy[varName] = obj[i]; } objCopy = objCopy[varName]; } delete obj[i]; } } } }, /** * Checks if the state is dropped. * @returns {boolean} True when dropped, false otherwise. */ isDropped: function () { return this._state === 'dropped'; } }; module.exports = Common; },{"./Overload":27,"./Serialiser":30}],19:[function(_dereq_,module,exports){ "use strict"; /** * Provides some database constants. * @mixin */ var Constants = { TYPE_INSERT: 0, TYPE_UPDATE: 1, TYPE_REMOVE: 2, PHASE_BEFORE: 0, PHASE_AFTER: 1 }; module.exports = Constants; },{}],20:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides event emitter functionality including the methods: on, off, once, emit, deferEmit. * @mixin */ var Events = { on: new Overload({ /** * Attach an event listener to the passed event. * @param {String} event The name of the event to listen for. * @param {Function} listener The method to call when the event is fired. */ 'string, function': function (event, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event]['*'] = this._listeners[event]['*'] || []; this._listeners[event]['*'].push(listener); return this; }, /** * Attach an event listener to the passed event only if the passed * id matches the document id for the event being fired. * @param {String} event The name of the event to listen for. * @param {*} id The document id to match against. * @param {Function} listener The method to call when the event is fired. */ 'string, *, function': function (event, id, listener) { this._listeners = this._listeners || {}; this._listeners[event] = this._listeners[event] || {}; this._listeners[event][id] = this._listeners[event][id] || []; this._listeners[event][id].push(listener); return this; } }), once: new Overload({ 'string, function': function (eventName, callback) { var self = this, internalCallback = function () { self.off(eventName, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, internalCallback); }, 'string, *, function': function (eventName, id, callback) { var self = this, internalCallback = function () { self.off(eventName, id, internalCallback); callback.apply(self, arguments); }; return this.on(eventName, id, internalCallback); } }), off: new Overload({ 'string': function (event) { if (this._listeners && this._listeners[event] && event in this._listeners) { delete this._listeners[event]; } return this; }, 'string, function': function (event, listener) { var arr, index; if (typeof(listener) === 'string') { if (this._listeners && this._listeners[event] && this._listeners[event][listener]) { delete this._listeners[event][listener]; } } else { if (this._listeners && event in this._listeners) { arr = this._listeners[event]['*']; index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } } return this; }, 'string, *, function': function (event, id, listener) { if (this._listeners && event in this._listeners && id in this.listeners[event]) { var arr = this._listeners[event][id], index = arr.indexOf(listener); if (index > -1) { arr.splice(index, 1); } } }, 'string, *': function (event, id) { if (this._listeners && event in this._listeners && id in this._listeners[event]) { // Kill all listeners for this event id delete this._listeners[event][id]; } } }), emit: function (event, data) { this._listeners = this._listeners || {}; if (event in this._listeners) { var arrIndex, arrCount, tmpFunc, arr, listenerIdArr, listenerIdCount, listenerIdIndex; // Handle global emit if (this._listeners[event]['*']) { arr = this._listeners[event]['*']; arrCount = arr.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { // Check we have a function to execute tmpFunc = arr[arrIndex]; if (typeof tmpFunc === 'function') { tmpFunc.apply(this, Array.prototype.slice.call(arguments, 1)); } } } // Handle individual emit if (data instanceof Array) { // Check if the array is an array of objects in the collection if (data[0] && data[0][this._primaryKey]) { // Loop the array and check for listeners against the primary key listenerIdArr = this._listeners[event]; arrCount = data.length; for (arrIndex = 0; arrIndex < arrCount; arrIndex++) { if (listenerIdArr[data[arrIndex][this._primaryKey]]) { // Emit for this id listenerIdCount = listenerIdArr[data[arrIndex][this._primaryKey]].length; for (listenerIdIndex = 0; listenerIdIndex < listenerIdCount; listenerIdIndex++) { tmpFunc = listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex]; if (typeof tmpFunc === 'function') { listenerIdArr[data[arrIndex][this._primaryKey]][listenerIdIndex].apply(this, Array.prototype.slice.call(arguments, 1)); } } } } } } } return this; }, /** * Queues an event to be fired. This has automatic de-bouncing so that any * events of the same type that occur within 100 milliseconds of a previous * one will all be wrapped into a single emit rather than emitting tons of * events for lots of chained inserts etc. Only the data from the last * de-bounced event will be emitted. * @param {String} eventName The name of the event to emit. * @param {*=} data Optional data to emit with the event. */ deferEmit: function (eventName, data) { var self = this, args; if (!this._noEmitDefer && (!this._db || (this._db && !this._db._noEmitDefer))) { args = arguments; // Check for an existing timeout this._deferTimeout = this._deferTimeout || {}; if (this._deferTimeout[eventName]) { clearTimeout(this._deferTimeout[eventName]); } // Set a timeout this._deferTimeout[eventName] = setTimeout(function () { if (self.debug()) { console.log(self.logIdentifier() + ' Emitting ' + args[0]); } self.emit.apply(self, args); }, 1); } else { this.emit.apply(this, arguments); } return this; } }; module.exports = Events; },{"./Overload":27}],21:[function(_dereq_,module,exports){ "use strict"; /** * Provides object matching algorithm methods. * @mixin */ var Matching = { /** * Internal method that checks a document against a test object. * @param {*} source The source object or value to test against. * @param {*} test The test object or value to test with. * @param {Object} queryOptions The options the query was passed with. * @param {String=} opToApply The special operation to apply to the test such * as 'and' or an 'or' operator. * @param {Object=} options An object containing options to apply to the * operation such as limiting the fields returned etc. * @returns {Boolean} True if the test was positive, false on negative. * @private */ _match: function (source, test, queryOptions, opToApply, options) { // TODO: This method is quite long, break into smaller pieces var operation, applyOp = opToApply, recurseVal, tmpIndex, sourceType = typeof source, testType = typeof test, matchedAll = true, opResult, substringCache, i; options = options || {}; queryOptions = queryOptions || {}; // Check if options currently holds a root query object if (!options.$rootQuery) { // Root query not assigned, hold the root query options.$rootQuery = test; } // Check if options currently holds a root source object if (!options.$rootSource) { // Root query not assigned, hold the root query options.$rootSource = source; } // Assign current query data options.$currentQuery = test; options.$rootData = options.$rootData || {}; // Check if the comparison data are both strings or numbers if ((sourceType === 'string' || sourceType === 'number') && (testType === 'string' || testType === 'number')) { // The source and test data are flat types that do not require recursive searches, // so just compare them and return the result if (sourceType === 'number') { // Number comparison if (source !== test) { matchedAll = false; } } else { // String comparison // TODO: We can probably use a queryOptions.$locale as a second parameter here // TODO: to satisfy https://github.com/Irrelon/ForerunnerDB/issues/35 if (source.localeCompare(test)) { matchedAll = false; } } } else if ((sourceType === 'string' || sourceType === 'number') && (testType === 'object' && test instanceof RegExp)) { if (!test.test(source)) { matchedAll = false; } } else { for (i in test) { if (test.hasOwnProperty(i)) { // Assign previous query data options.$previousQuery = options.$parent; // Assign parent query data options.$parent = { query: test[i], key: i, parent: options.$previousQuery }; // Reset operation flag operation = false; // Grab first two chars of the key name to check for $ substringCache = i.substr(0, 2); // Check if the property is a comment (ignorable) if (substringCache === '//') { // Skip this property continue; } // Check if the property starts with a dollar (function) if (substringCache.indexOf('$') === 0) { // Ask the _matchOp method to handle the operation opResult = this._matchOp(i, source, test[i], queryOptions, options); // Check the result of the matchOp operation // If the result is -1 then no operation took place, otherwise the result // will be a boolean denoting a match (true) or no match (false) if (opResult > -1) { if (opResult) { if (opToApply === 'or') { return true; } } else { // Set the matchedAll flag to the result of the operation // because the operation did not return true matchedAll = opResult; } // Record that an operation was handled operation = true; } } // Check for regex if (!operation && test[i] instanceof RegExp) { operation = true; if (sourceType === 'object' && source[i] !== undefined && test[i].test(source[i])) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } if (!operation) { // Check if our query is an object if (typeof(test[i]) === 'object') { // Because test[i] is an object, source must also be an object // Check if our source data we are checking the test query against // is an object or an array if (source[i] !== undefined) { if (source[i] instanceof Array && !(test[i] instanceof Array)) { // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (!(source[i] instanceof Array) && test[i] instanceof Array) { // The test key data is an array and the source key data is not so check // each item in the test key data to see if the source item matches one // of them. This is effectively an $in search. recurseVal = false; for (tmpIndex = 0; tmpIndex < test[i].length; tmpIndex++) { recurseVal = this._match(source[i], test[i][tmpIndex], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else if (typeof(source) === 'object') { // Recurse down the object tree recurseVal = this._match(source[i], test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } } else { // First check if the test match is an $exists if (test[i] && test[i].$exists !== undefined) { // Push the item through another match recurse recurseVal = this._match(undefined, test[i], queryOptions, applyOp, options); if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } else { // Check if the prop matches our test value if (source && source[i] === test[i]) { if (opToApply === 'or') { return true; } } else if (source && source[i] && source[i] instanceof Array && test[i] && typeof(test[i]) !== "object") { // We are looking for a value inside an array // The source data is an array, so check each item until a // match is found recurseVal = false; for (tmpIndex = 0; tmpIndex < source[i].length; tmpIndex++) { recurseVal = this._match(source[i][tmpIndex], test[i], queryOptions, applyOp, options); if (recurseVal) { // One of the array items matched the query so we can // include this item in the results, so break now break; } } if (recurseVal) { if (opToApply === 'or') { return true; } } else { matchedAll = false; } } else { matchedAll = false; } } } if (opToApply === 'and' && !matchedAll) { return false; } } } } return matchedAll; }, /** * Internal method, performs a matching process against a query operator such as $gt or $nin. * @param {String} key The property name in the test that matches the operator to perform * matching against. * @param {*} source The source data to match the query against. * @param {*} test The query to match the source against. * @param {Object} queryOptions The options the query was passed with. * @param {Object=} options An options object. * @returns {*} * @private */ _matchOp: function (key, source, test, queryOptions, options) { // Check for commands switch (key) { case '$gt': // Greater than return source > test; case '$gte': // Greater than or equal return source >= test; case '$lt': // Less than return source < test; case '$lte': // Less than or equal return source <= test; case '$exists': // Property exists return (source === undefined) !== test; case '$eq': // Equals return source == test; // jshint ignore:line case '$eeq': // Equals equals return source === test; case '$ne': // Not equals return source != test; // jshint ignore:line case '$nee': // Not equals equals return source !== test; case '$or': // Match true on ANY check to pass for (var orIndex = 0; orIndex < test.length; orIndex++) { if (this._match(source, test[orIndex], queryOptions, 'and', options)) { return true; } } return false; case '$and': // Match true on ALL checks to pass for (var andIndex = 0; andIndex < test.length; andIndex++) { if (!this._match(source, test[andIndex], queryOptions, 'and', options)) { return false; } } return true; case '$in': // In // Check that the in test is an array if (test instanceof Array) { var inArr = test, inArrCount = inArr.length, inArrIndex; for (inArrIndex = 0; inArrIndex < inArrCount; inArrIndex++) { if (this._match(source, inArr[inArrIndex], queryOptions, 'and', options)) { return true; } } return false; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use an $in operator on a non-array key: ' + key); } break; case '$nin': // Not in // Check that the not-in test is an array if (test instanceof Array) { var notInArr = test, notInArrCount = notInArr.length, notInArrIndex; for (notInArrIndex = 0; notInArrIndex < notInArrCount; notInArrIndex++) { if (this._match(source, notInArr[notInArrIndex], queryOptions, 'and', options)) { return false; } } return true; } else if (typeof test === 'object') { return this._match(source, test, queryOptions, 'and', options); } else { throw(this.logIdentifier() + ' Cannot use a $nin operator on a non-array key: ' + key); } break; case '$distinct': // Ensure options holds a distinct lookup options.$rootData['//distinctLookup'] = options.$rootData['//distinctLookup'] || {}; for (var distinctProp in test) { if (test.hasOwnProperty(distinctProp)) { options.$rootData['//distinctLookup'][distinctProp] = options.$rootData['//distinctLookup'][distinctProp] || {}; // Check if the options distinct lookup has this field's value if (options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]]) { // Value is already in use return false; } else { // Set the value in the lookup options.$rootData['//distinctLookup'][distinctProp][source[distinctProp]] = true; // Allow the item in the results return true; } } } break; case '$count': var countKey, countArr, countVal; // Iterate the count object's keys for (countKey in test) { if (test.hasOwnProperty(countKey)) { // Check the property exists and is an array. If the property being counted is not // an array (or doesn't exist) then use a value of zero in any further count logic countArr = source[countKey]; if (typeof countArr === 'object' && countArr instanceof Array) { countVal = countArr.length; } else { countVal = 0; } // Now recurse down the query chain further to satisfy the query for this key (countKey) if (!this._match(countVal, test[countKey], queryOptions, 'and', options)) { return false; } } } // Allow the item in the results return true; case '$find': case '$findOne': case '$findSub': var fromType = 'collection', findQuery, findOptions, subQuery, subOptions, subPath, result, operation = {}; // Check we have a database object to work from if (!this.db()) { throw('Cannot operate a ' + key + ' sub-query on an anonymous collection (one with no db set)!'); } // Check all parts of the $find operation exist if (!test.$from) { throw(key + ' missing $from property!'); } if (test.$fromType) { fromType = test.$fromType; // Check the fromType exists as a method if (!this.db()[fromType] || typeof this.db()[fromType] !== 'function') { throw(key + ' cannot operate against $fromType "' + fromType + '" because the database does not recognise this type of object!'); } } // Perform the find operation findQuery = test.$query || {}; findOptions = test.$options || {}; if (key === '$findSub') { if (!test.$path) { throw(key + ' missing $path property!'); } subPath = test.$path; subQuery = test.$subQuery || {}; subOptions = test.$subOptions || {}; result = this.db()[fromType](test.$from).findSub(findQuery, subPath, subQuery, subOptions); } else { result = this.db()[fromType](test.$from)[key.substr(1)](findQuery, findOptions); } operation[options.$parent.parent.key] = result; return this._match(source, operation, queryOptions, 'and', options); } return -1; } }; module.exports = Matching; },{}],22:[function(_dereq_,module,exports){ "use strict"; /** * Provides sorting methods. * @mixin */ var Sorting = { /** * Sorts the passed value a against the passed value b ascending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortAsc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return a.localeCompare(b); } else { if (a > b) { return 1; } else if (a < b) { return -1; } } return 0; }, /** * Sorts the passed value a against the passed value b descending. * @param {*} a The first value to compare. * @param {*} b The second value to compare. * @returns {*} 1 if a is sorted after b, -1 if a is sorted before b. */ sortDesc: function (a, b) { if (typeof(a) === 'string' && typeof(b) === 'string') { return b.localeCompare(a); } else { if (a > b) { return -1; } else if (a < b) { return 1; } } return 0; } }; module.exports = Sorting; },{}],23:[function(_dereq_,module,exports){ "use strict"; var Tags, tagMap = {}; /** * Provides class instance tagging and tag operation methods. * @mixin */ Tags = { /** * Tags a class instance for later lookup. * @param {String} name The tag to add. * @returns {boolean} */ tagAdd: function (name) { var i, self = this, mapArr = tagMap[name] = tagMap[name] || []; for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === self) { return true; } } mapArr.push(self); // Hook the drop event for this so we can react if (self.on) { self.on('drop', function () { // We've been dropped so remove ourselves from the tag map self.tagRemove(name); }); } return true; }, /** * Removes a tag from a class instance. * @param {String} name The tag to remove. * @returns {boolean} */ tagRemove: function (name) { var i, mapArr = tagMap[name]; if (mapArr) { for (i = 0; i < mapArr.length; i++) { if (mapArr[i] === this) { mapArr.splice(i, 1); return true; } } } return false; }, /** * Gets an array of all instances tagged with the passed tag name. * @param {String} name The tag to lookup. * @returns {Array} The array of instances that have the passed tag. */ tagLookup: function (name) { return tagMap[name] || []; }, /** * Drops all instances that are tagged with the passed tag name. * @param {String} name The tag to lookup. * @param {Function} callback Callback once dropping has completed * for all instances that match the passed tag name. * @returns {boolean} */ tagDrop: function (name, callback) { var arr = this.tagLookup(name), dropCb, dropCount, i; dropCb = function () { dropCount--; if (callback && dropCount === 0) { callback(false); } }; if (arr.length) { dropCount = arr.length; // Loop the array and drop all items for (i = arr.length - 1; i >= 0; i--) { arr[i].drop(dropCb); } } return true; } }; module.exports = Tags; },{}],24:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * Provides trigger functionality methods. * @mixin */ var Triggers = { /** * Add a trigger by id. * @param {String} id The id of the trigger. This must be unique to the type and * phase of the trigger. Only one trigger may be added with this id per type and * phase. * @param {Number} type The type of operation to apply the trigger to. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of an operation to fire the trigger on. See * Mixin.Constants for constants to use. * @param {Function} method The method to call when the trigger is fired. * @returns {boolean} True if the trigger was added successfully, false if not. */ addTrigger: function (id, type, phase, method) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex === -1) { // The trigger does not exist, create it self._trigger = self._trigger || {}; self._trigger[type] = self._trigger[type] || {}; self._trigger[type][phase] = self._trigger[type][phase] || []; self._trigger[type][phase].push({ id: id, method: method, enabled: true }); return true; } return false; }, /** * * @param {String} id The id of the trigger to remove. * @param {Number} type The type of operation to remove the trigger from. See * Mixin.Constants for constants to use. * @param {Number} phase The phase of the operation to remove the trigger from. * See Mixin.Constants for constants to use. * @returns {boolean} True if removed successfully, false if not. */ removeTrigger: function (id, type, phase) { var self = this, triggerIndex; // Check if the trigger already exists triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // The trigger exists, remove it self._trigger[type][phase].splice(triggerIndex, 1); } return false; }, enableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = true; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to enabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = true; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = true; return true; } return false; } }), disableTrigger: new Overload({ 'string': function (id) { // Alter all triggers of this type var self = this, types = self._trigger, phases, triggers, result = false, i, k, j; if (types) { for (j in types) { if (types.hasOwnProperty(j)) { phases = types[j]; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set enabled flag for (k = 0; k < triggers.length; k++) { if (triggers[k].id === id) { triggers[k].enabled = false; result = true; } } } } } } } } return result; }, 'number': function (type) { // Alter all triggers of this type var self = this, phases = self._trigger[type], triggers, result = false, i, k; if (phases) { for (i in phases) { if (phases.hasOwnProperty(i)) { triggers = phases[i]; // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } } return result; }, 'number, number': function (type, phase) { // Alter all triggers of this type and phase var self = this, phases = self._trigger[type], triggers, result = false, k; if (phases) { triggers = phases[phase]; if (triggers) { // Loop triggers and set to disabled for (k = 0; k < triggers.length; k++) { triggers[k].enabled = false; result = true; } } } return result; }, 'string, number, number': function (id, type, phase) { // Check if the trigger already exists var self = this, triggerIndex = self._triggerIndexOf(id, type, phase); if (triggerIndex > -1) { // Update the trigger self._trigger[type][phase][triggerIndex].enabled = false; return true; } return false; } }), /** * Checks if a trigger will fire based on the type and phase provided. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {Boolean} True if the trigger will fire, false otherwise. */ willTrigger: function (type, phase) { if (this._trigger && this._trigger[type] && this._trigger[type][phase] && this._trigger[type][phase].length) { // Check if a trigger in this array is enabled var arr = this._trigger[type][phase], i; for (i = 0; i < arr.length; i++) { if (arr[i].enabled) { return true; } } } return false; }, /** * Processes trigger actions based on the operation, type and phase. * @param {Object} operation Operation data to pass to the trigger. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @param {Object} oldDoc The document snapshot before operations are * carried out against the data. * @param {Object} newDoc The document snapshot after operations are * carried out against the data. * @returns {boolean} */ processTrigger: function (operation, type, phase, oldDoc, newDoc) { var self = this, triggerArr, triggerIndex, triggerCount, triggerItem, response; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { triggerItem = triggerArr[triggerIndex]; // Check if the trigger is enabled if (triggerItem.enabled) { if (this.debug()) { var typeName, phaseName; switch (type) { case this.TYPE_INSERT: typeName = 'insert'; break; case this.TYPE_UPDATE: typeName = 'update'; break; case this.TYPE_REMOVE: typeName = 'remove'; break; default: typeName = ''; break; } switch (phase) { case this.PHASE_BEFORE: phaseName = 'before'; break; case this.PHASE_AFTER: phaseName = 'after'; break; default: phaseName = ''; break; } //console.log('Triggers: Processing trigger "' + id + '" for ' + typeName + ' in phase "' + phaseName + '"'); } // Run the trigger's method and store the response response = triggerItem.method.call(self, operation, oldDoc, newDoc); // Check the response for a non-expected result (anything other than // undefined, true or false is considered a throwable error) if (response === false) { // The trigger wants us to cancel operations return false; } if (response !== undefined && response !== true && response !== false) { // Trigger responded with error, throw the error throw('ForerunnerDB.Mixin.Triggers: Trigger error: ' + response); } } } // Triggers all ran without issue, return a success (true) return true; } }, /** * Returns the index of a trigger by id based on type and phase. * @param {String} id The id of the trigger to find the index of. * @param {Number} type The type of operation. See Mixin.Constants for * constants to use. * @param {Number} phase The phase of the operation. See Mixin.Constants * for constants to use. * @returns {number} * @private */ _triggerIndexOf: function (id, type, phase) { var self = this, triggerArr, triggerCount, triggerIndex; if (self._trigger && self._trigger[type] && self._trigger[type][phase]) { triggerArr = self._trigger[type][phase]; triggerCount = triggerArr.length; for (triggerIndex = 0; triggerIndex < triggerCount; triggerIndex++) { if (triggerArr[triggerIndex].id === id) { return triggerIndex; } } } return -1; } }; module.exports = Triggers; },{"./Overload":27}],25:[function(_dereq_,module,exports){ "use strict"; /** * Provides methods to handle object update operations. * @mixin */ var Updating = { /** * Updates a property on an object. * @param {Object} doc The object whose property is to be updated. * @param {String} prop The property to update. * @param {*} val The new value of the property. * @private */ _updateProperty: function (doc, prop, val) { doc[prop] = val; if (this.debug()) { console.log(this.logIdentifier() + ' Setting non-data-bound document property "' + prop + '"'); } }, /** * Increments a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to increment by. * @private */ _updateIncrement: function (doc, prop, val) { doc[prop] += val; }, /** * Changes the index of an item in the passed array. * @param {Array} arr The array to modify. * @param {Number} indexFrom The index to move the item from. * @param {Number} indexTo The index to move the item to. * @private */ _updateSpliceMove: function (arr, indexFrom, indexTo) { arr.splice(indexTo, 0, arr.splice(indexFrom, 1)[0]); if (this.debug()) { console.log(this.logIdentifier() + ' Moving non-data-bound document array index from "' + indexFrom + '" to "' + indexTo + '"'); } }, /** * Inserts an item into the passed array at the specified index. * @param {Array} arr The array to insert into. * @param {Number} index The index to insert at. * @param {Object} doc The document to insert. * @private */ _updateSplicePush: function (arr, index, doc) { if (arr.length > index) { arr.splice(index, 0, doc); } else { arr.push(doc); } }, /** * Inserts an item at the end of an array. * @param {Array} arr The array to insert the item into. * @param {Object} doc The document to insert. * @private */ _updatePush: function (arr, doc) { arr.push(doc); }, /** * Removes an item from the passed array. * @param {Array} arr The array to modify. * @param {Number} index The index of the item in the array to remove. * @private */ _updatePull: function (arr, index) { arr.splice(index, 1); }, /** * Multiplies a value for a property on a document by the passed number. * @param {Object} doc The document to modify. * @param {String} prop The property to modify. * @param {Number} val The amount to multiply by. * @private */ _updateMultiply: function (doc, prop, val) { doc[prop] *= val; }, /** * Renames a property on a document to the passed property. * @param {Object} doc The document to modify. * @param {String} prop The property to rename. * @param {Number} val The new property name. * @private */ _updateRename: function (doc, prop, val) { doc[val] = doc[prop]; delete doc[prop]; }, /** * Sets a property on a document to the passed value. * @param {Object} doc The document to modify. * @param {String} prop The property to set. * @param {*} val The new property value. * @private */ _updateOverwrite: function (doc, prop, val) { doc[prop] = val; }, /** * Deletes a property on a document. * @param {Object} doc The document to modify. * @param {String} prop The property to delete. * @private */ _updateUnset: function (doc, prop) { delete doc[prop]; }, /** * Removes all properties from an object without destroying * the object instance, thereby maintaining data-bound linking. * @param {Object} doc The parent object to modify. * @param {String} prop The name of the child object to clear. * @private */ _updateClear: function (doc, prop) { var obj = doc[prop], i; if (obj && typeof obj === 'object') { for (i in obj) { if (obj.hasOwnProperty(i)) { this._updateUnset(obj, i); } } } }, /** * Pops an item or items from the array stack. * @param {Object} doc The document to modify. * @param {Number} val If set to a positive integer, will pop the number specified * from the stack, if set to a negative integer will shift the number specified * from the stack. * @return {Boolean} * @private */ _updatePop: function (doc, val) { var updated = false, i; if (doc.length > 0) { if (val > 0) { for (i = 0; i < val; i++) { doc.pop(); } updated = true; } else if (val < 0) { for (i = 0; i > val; i--) { doc.shift(); } updated = true; } } return updated; } }; module.exports = Updating; },{}],26:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'), Path = _dereq_('./Path'); /** * The operation class, used to store details about an operation being * performed by the database. * @param {String} name The name of the operation. * @constructor */ var Operation = function (name) { this.pathSolver = new Path(); this.counter = 0; this.init.apply(this, arguments); }; Operation.prototype.init = function (name) { this._data = { operation: name, // The name of the operation executed such as "find", "update" etc index: { potential: [], // Indexes that could have potentially been used used: false // The index that was picked to use }, steps: [], // The steps taken to generate the query results, time: { startMs: 0, stopMs: 0, totalMs: 0, process: {} }, flag: {}, // An object with flags that denote certain execution paths log: [] // Any extra data that might be useful such as warnings or helpful hints }; }; Shared.addModule('Operation', Operation); Shared.mixin(Operation.prototype, 'Mixin.ChainReactor'); /** * Starts the operation timer. */ Operation.prototype.start = function () { this._data.time.startMs = new Date().getTime(); }; /** * Adds an item to the operation log. * @param {String} event The item to log. * @returns {*} */ Operation.prototype.log = function (event) { if (event) { var lastLogTime = this._log.length > 0 ? this._data.log[this._data.log.length - 1].time : 0, logObj = { event: event, time: new Date().getTime(), delta: 0 }; this._data.log.push(logObj); if (lastLogTime) { logObj.delta = logObj.time - lastLogTime; } return this; } return this._data.log; }; /** * Called when starting and ending a timed operation, used to time * internal calls within an operation's execution. * @param {String} section An operation name. * @returns {*} */ Operation.prototype.time = function (section) { if (section !== undefined) { var process = this._data.time.process, processObj = process[section] = process[section] || {}; if (!processObj.startMs) { // Timer started processObj.startMs = new Date().getTime(); processObj.stepObj = { name: section }; this._data.steps.push(processObj.stepObj); } else { processObj.stopMs = new Date().getTime(); processObj.totalMs = processObj.stopMs - processObj.startMs; processObj.stepObj.totalMs = processObj.totalMs; delete processObj.stepObj; } return this; } return this._data.time; }; /** * Used to set key/value flags during operation execution. * @param {String} key * @param {String} val * @returns {*} */ Operation.prototype.flag = function (key, val) { if (key !== undefined && val !== undefined) { this._data.flag[key] = val; } else if (key !== undefined) { return this._data.flag[key]; } else { return this._data.flag; } }; Operation.prototype.data = function (path, val, noTime) { if (val !== undefined) { // Assign value to object path this.pathSolver.set(this._data, path, val); return this; } return this.pathSolver.get(this._data, path); }; Operation.prototype.pushData = function (path, val, noTime) { // Assign value to object path this.pathSolver.push(this._data, path, val); }; /** * Stops the operation timer. */ Operation.prototype.stop = function () { this._data.time.stopMs = new Date().getTime(); this._data.time.totalMs = this._data.time.stopMs - this._data.time.startMs; }; Shared.finishModule('Operation'); module.exports = Operation; },{"./Path":28,"./Shared":31}],27:[function(_dereq_,module,exports){ "use strict"; /** * Allows a method to accept overloaded calls with different parameters controlling * which passed overload function is called. * @param {Object} def * @returns {Function} * @constructor */ var Overload = function (def) { if (def) { var self = this, index, count, tmpDef, defNewKey, sigIndex, signatures; if (!(def instanceof Array)) { tmpDef = {}; // Def is an object, make sure all prop names are devoid of spaces for (index in def) { if (def.hasOwnProperty(index)) { defNewKey = index.replace(/ /g, ''); // Check if the definition array has a * string in it if (defNewKey.indexOf('*') === -1) { // No * found tmpDef[defNewKey] = def[index]; } else { // A * was found, generate the different signatures that this // definition could represent signatures = this.generateSignaturePermutations(defNewKey); for (sigIndex = 0; sigIndex < signatures.length; sigIndex++) { if (!tmpDef[signatures[sigIndex]]) { tmpDef[signatures[sigIndex]] = def[index]; } } } } } def = tmpDef; } return function () { var arr = [], lookup, type, name; // Check if we are being passed a key/function object or an array of functions if (def instanceof Array) { // We were passed an array of functions count = def.length; for (index = 0; index < count; index++) { if (def[index].length === arguments.length) { return self.callExtend(this, '$main', def, def[index], arguments); } } } else { // Generate lookup key from arguments // Copy arguments to an array for (index = 0; index < arguments.length; index++) { type = typeof arguments[index]; // Handle detecting arrays if (type === 'object' && arguments[index] instanceof Array) { type = 'array'; } // Handle been presented with a single undefined argument if (arguments.length === 1 && type === 'undefined') { break; } // Add the type to the argument types array arr.push(type); } lookup = arr.join(','); // Check for an exact lookup match if (def[lookup]) { return self.callExtend(this, '$main', def, def[lookup], arguments); } else { for (index = arr.length; index >= 0; index--) { // Get the closest match lookup = arr.slice(0, index).join(','); if (def[lookup + ',...']) { // Matched against arguments + "any other" return self.callExtend(this, '$main', def, def[lookup + ',...'], arguments); } } } } name = typeof this.name === 'function' ? this.name() : 'Unknown'; console.log('Overload: ', def); throw('ForerunnerDB.Overload "' + name + '": Overloaded method does not have a matching signature for the passed arguments: ' + this.jStringify(arr)); }; } return function () {}; }; /** * Generates an array of all the different definition signatures that can be * created from the passed string with a catch-all wildcard *. E.g. it will * convert the signature: string,*,string to all potentials: * string,string,string * string,number,string * string,object,string, * string,function,string, * string,undefined,string * * @param {String} str Signature string with a wildcard in it. * @returns {Array} An array of signature strings that are generated. */ Overload.prototype.generateSignaturePermutations = function (str) { var signatures = [], newSignature, types = ['string', 'object', 'number', 'function', 'undefined'], index; if (str.indexOf('*') > -1) { // There is at least one "any" type, break out into multiple keys // We could do this at query time with regular expressions but // would be significantly slower for (index = 0; index < types.length; index++) { newSignature = str.replace('*', types[index]); signatures = signatures.concat(this.generateSignaturePermutations(newSignature)); } } else { signatures.push(str); } return signatures; }; Overload.prototype.callExtend = function (context, prop, propContext, func, args) { var tmp, ret; if (context && propContext[prop]) { tmp = context[prop]; context[prop] = propContext[prop]; ret = func.apply(context, args); context[prop] = tmp; return ret; } else { return func.apply(context, args); } }; module.exports = Overload; },{}],28:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Path object used to resolve object paths and retrieve data from * objects by using paths. * @param {String=} path The path to assign. * @constructor */ var Path = function (path) { this.init.apply(this, arguments); }; Path.prototype.init = function (path) { if (path) { this.path(path); } }; Shared.addModule('Path', Path); Shared.mixin(Path.prototype, 'Mixin.Common'); Shared.mixin(Path.prototype, 'Mixin.ChainReactor'); /** * Gets / sets the given path for the Path instance. * @param {String=} path The path to assign. */ Path.prototype.path = function (path) { if (path !== undefined) { this._path = this.clean(path); this._pathParts = this._path.split('.'); return this; } return this._path; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Boolean} True if the object paths exist. */ Path.prototype.hasObjectPaths = function (testKeys, testObj) { var result = true, i; for (i in testKeys) { if (testKeys.hasOwnProperty(i)) { if (testObj[i] === undefined) { return false; } if (typeof testKeys[i] === 'object') { // Recurse object result = this.hasObjectPaths(testKeys[i], testObj[i]); // Should we exit early? if (!result) { return false; } } } } return result; }; /** * Counts the total number of key endpoints in the passed object. * @param {Object} testObj The object to count key endpoints for. * @returns {Number} The number of endpoints. */ Path.prototype.countKeys = function (testObj) { var totalKeys = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (testObj[i] !== undefined) { if (typeof testObj[i] !== 'object') { totalKeys++; } else { totalKeys += this.countKeys(testObj[i]); } } } } return totalKeys; }; /** * Tests if the passed object has the paths that are specified and that * a value exists in those paths and if so returns the number matched. * @param {Object} testKeys The object describing the paths to test for. * @param {Object} testObj The object to test paths against. * @returns {Object} Stats on the matched keys */ Path.prototype.countObjectPaths = function (testKeys, testObj) { var matchData, matchedKeys = {}, matchedKeyCount = 0, totalKeyCount = 0, i; for (i in testObj) { if (testObj.hasOwnProperty(i)) { if (typeof testObj[i] === 'object') { // The test / query object key is an object, recurse matchData = this.countObjectPaths(testKeys[i], testObj[i]); matchedKeys[i] = matchData.matchedKeys; totalKeyCount += matchData.totalKeyCount; matchedKeyCount += matchData.matchedKeyCount; } else { // The test / query object has a property that is not an object so add it as a key totalKeyCount++; // Check if the test keys also have this key and it is also not an object if (testKeys && testKeys[i] && typeof testKeys[i] !== 'object') { matchedKeys[i] = true; matchedKeyCount++; } else { matchedKeys[i] = false; } } } } return { matchedKeys: matchedKeys, matchedKeyCount: matchedKeyCount, totalKeyCount: totalKeyCount }; }; /** * Takes a non-recursive object and converts the object hierarchy into * a path string. * @param {Object} obj The object to parse. * @param {Boolean=} withValue If true will include a 'value' key in the returned * object that represents the value the object path points to. * @returns {Object} */ Path.prototype.parse = function (obj, withValue) { var paths = [], path = '', resultData, i, k; for (i in obj) { if (obj.hasOwnProperty(i)) { // Set the path to the key path = i; if (typeof(obj[i]) === 'object') { if (withValue) { resultData = this.parse(obj[i], withValue); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path, value: resultData[k].value }); } } else { resultData = this.parse(obj[i]); for (k = 0; k < resultData.length; k++) { paths.push({ path: path + '.' + resultData[k].path }); } } } else { if (withValue) { paths.push({ path: path, value: obj[i] }); } else { paths.push({ path: path }); } } } } return paths; }; /** * Takes a non-recursive object and converts the object hierarchy into * an array of path strings that allow you to target all possible paths * in an object. * * The options object accepts an "ignore" field with a regular expression * as the value. If any key matches the expression it is not included in * the results. * * The options object accepts a boolean "verbose" field. If set to true * the results will include all paths leading up to endpoints as well as * they endpoints themselves. * * @returns {Array} */ Path.prototype.parseArr = function (obj, options) { options = options || {}; return this._parseArr(obj, '', [], options); }; Path.prototype._parseArr = function (obj, path, paths, options) { var i, newPath = ''; path = path || ''; paths = paths || []; for (i in obj) { if (obj.hasOwnProperty(i)) { if (!options.ignore || (options.ignore && !options.ignore.test(i))) { if (path) { newPath = path + '.' + i; } else { newPath = i; } if (typeof(obj[i]) === 'object') { if (options.verbose) { paths.push(newPath); } this._parseArr(obj[i], newPath, paths, options); } else { paths.push(newPath); } } } } return paths; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Gets a single value from the passed object and given path. * @param {Object} obj The object to inspect. * @param {String} path The path to retrieve data from. * @returns {*} */ Path.prototype.get = function (obj, path) { return this.value(obj, path)[0]; }; /** * Gets the value(s) that the object contains for the currently assigned path string. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @param {Object=} options An optional options object. * @returns {Array} An array of values for the given path. */ Path.prototype.value = function (obj, path, options) { var pathParts, arr, arrCount, objPart, objPartParent, valuesArr, returnArr, i, k; // Detect early exit if (path && path.indexOf('.') === -1) { return [obj[path]]; } if (obj !== undefined && typeof obj === 'object') { if (!options || options && !options.skipArrCheck) { // Check if we were passed an array of objects and if so, // iterate over the array and return the value from each // array item if (obj instanceof Array) { returnArr = []; for (i = 0; i < obj.length; i++) { returnArr.push(this.get(obj[i], path)); } return returnArr; } } valuesArr = []; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (objPartParent instanceof Array) { // Search inside the array for the next key for (k = 0; k < objPartParent.length; k++) { valuesArr = valuesArr.concat(this.value(objPartParent, k + '.' + arr[i], {skipArrCheck: true})); } return valuesArr; } else { if (!objPart || typeof(objPart) !== 'object') { break; } } objPartParent = objPart; } return [objPart]; } else { return []; } }; /** * Push a value to an array on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to the array to push to. * @param {*} val The value to push to the array at the object path. * @returns {*} */ Path.prototype.push = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = obj[part] || []; if (obj[part] instanceof Array) { obj[part].push(val); } else { throw('ForerunnerDB.Path: Cannot push to a path whose endpoint is not an array!'); } } } return obj; }; /** * Gets the value(s) that the object contains for the currently assigned path string * with their associated keys. * @param {Object} obj The object to evaluate the path against. * @param {String=} path A path to use instead of the existing one passed in path(). * @returns {Array} An array of values for the given path with the associated key. */ Path.prototype.keyValue = function (obj, path) { var pathParts, arr, arrCount, objPart, objPartParent, objPartHash, i; if (path !== undefined) { path = this.clean(path); pathParts = path.split('.'); } arr = pathParts || this._pathParts; arrCount = arr.length; objPart = obj; for (i = 0; i < arrCount; i++) { objPart = objPart[arr[i]]; if (!objPart || typeof(objPart) !== 'object') { objPartHash = arr[i] + ':' + objPart; break; } objPartParent = objPart; } return objPartHash; }; /** * Sets a value on an object for the specified path. * @param {Object} obj The object to update. * @param {String} path The path to update. * @param {*} val The value to set the object path to. * @returns {*} */ Path.prototype.set = function (obj, path, val) { if (obj !== undefined && path !== undefined) { var pathParts, part; path = this.clean(path); pathParts = path.split('.'); part = pathParts.shift(); if (pathParts.length) { // Generate the path part in the object if it does not already exist obj[part] = obj[part] || {}; // Recurse this.set(obj[part], pathParts.join('.'), val); } else { // Set the value obj[part] = val; } } return obj; }; /** * Removes leading period (.) from string and returns it. * @param {String} str The string to clean. * @returns {*} */ Path.prototype.clean = function (str) { if (str.substr(0, 1) === '.') { str = str.substr(1, str.length -1); } return str; }; Shared.finishModule('Path'); module.exports = Path; },{"./Shared":31}],29:[function(_dereq_,module,exports){ "use strict"; var Shared = _dereq_('./Shared'); /** * Provides chain reactor node linking so that a chain reaction can propagate * down a node tree. Effectively creates a chain link between the reactorIn and * reactorOut objects where a chain reaction from the reactorIn is passed through * the reactorProcess before being passed to the reactorOut object. Reactor * packets are only passed through to the reactorOut if the reactor IO method * chainSend is used. * @param {*} reactorIn An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur inside this object will be passed through * to the reactorOut object. * @param {*} reactorOut An object that has the Mixin.ChainReactor methods mixed * in to it. Chain reactions that occur in the reactorIn object will be passed * through to this object. * @param {Function} reactorProcess The processing method to use when chain * reactions occur. * @constructor */ var ReactorIO = function (reactorIn, reactorOut, reactorProcess) { if (reactorIn && reactorOut && reactorProcess) { this._reactorIn = reactorIn; this._reactorOut = reactorOut; this._chainHandler = reactorProcess; if (!reactorIn.chain) { throw('ForerunnerDB.ReactorIO: ReactorIO requires passed in and out objects to implement the ChainReactor mixin!'); } // Register the reactorIO with the input reactorIn.chain(this); // Register the output with the reactorIO this.chain(reactorOut); } else { throw('ForerunnerDB.ReactorIO: ReactorIO requires in, out and process arguments to instantiate!'); } }; Shared.addModule('ReactorIO', ReactorIO); /** * Drop a reactor IO object, breaking the reactor link between the in and out * reactor nodes. * @returns {boolean} */ ReactorIO.prototype.drop = function () { if (!this.isDropped()) { this._state = 'dropped'; // Remove links if (this._reactorIn) { this._reactorIn.unChain(this); } if (this._reactorOut) { this.unChain(this._reactorOut); } delete this._reactorIn; delete this._reactorOut; delete this._chainHandler; this.emit('drop', this); delete this._listeners; } return true; }; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(ReactorIO.prototype, 'state'); Shared.mixin(ReactorIO.prototype, 'Mixin.Common'); Shared.mixin(ReactorIO.prototype, 'Mixin.ChainReactor'); Shared.mixin(ReactorIO.prototype, 'Mixin.Events'); Shared.finishModule('ReactorIO'); module.exports = ReactorIO; },{"./Shared":31}],30:[function(_dereq_,module,exports){ "use strict"; /** * Provides functionality to encode and decode JavaScript objects to strings * and back again. This differs from JSON.stringify and JSON.parse in that * special objects such as dates can be encoded to strings and back again * so that the reconstituted version of the string still contains a JavaScript * date object. * @constructor */ var Serialiser = function () { this.init.apply(this, arguments); }; Serialiser.prototype.init = function () { this._encoder = []; this._decoder = {}; // Handler for Date() objects this.registerEncoder('$date', function (data) { if (data instanceof Date) { return data.toISOString(); } }); this.registerDecoder('$date', function (data) { return new Date(data); }); // Handler for RegExp() objects this.registerEncoder('$regexp', function (data) { if (data instanceof RegExp) { return { source: data.source, params: '' + (data.global ? 'g' : '') + (data.ignoreCase ? 'i' : '') }; } }); this.registerDecoder('$regexp', function (data) { return new RegExp(data.source, data.params); }); }; /** * Register an encoder that can handle encoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. * @param {Function} method The encoder method. */ Serialiser.prototype.registerEncoder = function (handles, method) { this._encoder.push(function (data) { var methodVal = method(data), returnObj; if (methodVal !== undefined) { returnObj = {}; returnObj[handles] = methodVal; } return returnObj; }); }; /** * Register a decoder that can handle decoding for a particular * object type. * @param {String} handles The name of the handler e.g. $date. When an object * has a field matching this handler name then this decode will be invoked * to provide a decoded version of the data that was previously encoded by * it's counterpart encoder method. * @param {Function} method The decoder method. */ Serialiser.prototype.registerDecoder = function (handles, method) { this._decoder[handles] = method; }; /** * Loops the encoders and asks each one if it wants to handle encoding for * the passed data object. If no value is returned (undefined) then the data * will be passed to the next encoder and so on. If a value is returned the * loop will break and the encoded data will be used. * @param {Object} data The data object to handle. * @returns {*} The encoded data. * @private */ Serialiser.prototype._encode = function (data) { // Loop the encoders and if a return value is given by an encoder // the loop will exit and return that value. var count = this._encoder.length, retVal; while (count-- && !retVal) { retVal = this._encoder[count](data); } return retVal; }; /** * Converts a previously encoded string back into an object. * @param {String} data The string to convert to an object. * @returns {Object} The reconstituted object. */ Serialiser.prototype.parse = function (data) { return this._parse(JSON.parse(data)); }; /** * Handles restoring an object with special data markers back into * it's original format. * @param {Object} data The object to recurse. * @param {Object=} target The target object to restore data to. * @returns {Object} The final restored object. * @private */ Serialiser.prototype._parse = function (data, target) { var i; if (typeof data === 'object' && data !== null) { if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and handle // special object types and restore them for (i in data) { if (data.hasOwnProperty(i)) { if (i.substr(0, 1) === '$' && this._decoder[i]) { // This is a special object type and a handler // exists, restore it return this._decoder[i](data[i]); } // Not a special object or no handler, recurse as normal target[i] = this._parse(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; /** * Converts an object to a encoded string representation. * @param {Object} data The object to encode. */ Serialiser.prototype.stringify = function (data) { return JSON.stringify(this._stringify(data)); }; /** * Recurse down an object and encode special objects so they can be * stringified and later restored. * @param {Object} data The object to parse. * @param {Object=} target The target object to store converted data to. * @returns {Object} The converted object. * @private */ Serialiser.prototype._stringify = function (data, target) { var handledData, i; if (typeof data === 'object' && data !== null) { // Handle special object types so they can be encoded with // a special marker and later restored by a decoder counterpart handledData = this._encode(data); if (handledData) { // An encoder handled this object type so return it now return handledData; } if (data instanceof Array) { target = target || []; } else { target = target || {}; } // Iterate through the object's keys and serialise for (i in data) { if (data.hasOwnProperty(i)) { target[i] = this._stringify(data[i], target[i]); } } } else { target = data; } // The data is a basic type return target; }; module.exports = Serialiser; },{}],31:[function(_dereq_,module,exports){ "use strict"; var Overload = _dereq_('./Overload'); /** * A shared object that can be used to store arbitrary data between class * instances, and access helper methods. * @mixin */ var Shared = { version: '1.3.533', modules: {}, plugins: {}, _synth: {}, /** * Adds a module to ForerunnerDB. * @memberof Shared * @param {String} name The name of the module. * @param {Function} module The module class. */ addModule: function (name, module) { // Store the module in the module registry this.modules[name] = module; // Tell the universe we are loading this module this.emit('moduleLoad', [name, module]); }, /** * Called by the module once all processing has been completed. Used to determine * if the module is ready for use by other modules. * @memberof Shared * @param {String} name The name of the module. */ finishModule: function (name) { if (this.modules[name]) { // Set the finished loading flag to true this.modules[name]._fdbFinished = true; // Assign the module name to itself so it knows what it // is called if (this.modules[name].prototype) { this.modules[name].prototype.className = name; } else { this.modules[name].className = name; } this.emit('moduleFinished', [name, this.modules[name]]); } else { throw('ForerunnerDB.Shared: finishModule called on a module that has not been registered with addModule(): ' + name); } }, /** * Will call your callback method when the specified module has loaded. If the module * is already loaded the callback is called immediately. * @memberof Shared * @param {String} name The name of the module. * @param {Function} callback The callback method to call when the module is loaded. */ moduleFinished: function (name, callback) { if (this.modules[name] && this.modules[name]._fdbFinished) { if (callback) { callback(name, this.modules[name]); } } else { this.on('moduleFinished', callback); } }, /** * Determines if a module has been added to ForerunnerDB or not. * @memberof Shared * @param {String} name The name of the module. * @returns {Boolean} True if the module exists or false if not. */ moduleExists: function (name) { return Boolean(this.modules[name]); }, /** * Adds the properties and methods defined in the mixin to the passed object. * @memberof Shared * @param {Object} obj The target object to add mixin key/values to. * @param {String} mixinName The name of the mixin to add to the object. */ mixin: new Overload({ 'object, string': function (obj, mixinName) { var mixinObj; if (typeof mixinName === 'string') { mixinObj = this.mixins[mixinName]; if (!mixinObj) { throw('ForerunnerDB.Shared: Cannot find mixin named: ' + mixinName); } } return this.$main.call(this, obj, mixinObj); }, 'object, *': function (obj, mixinObj) { return this.$main.call(this, obj, mixinObj); }, '$main': function (obj, mixinObj) { if (mixinObj && typeof mixinObj === 'object') { for (var i in mixinObj) { if (mixinObj.hasOwnProperty(i)) { obj[i] = mixinObj[i]; } } } return obj; } }), /** * Generates a generic getter/setter method for the passed method name. * @memberof Shared * @param {Object} obj The object to add the getter/setter to. * @param {String} name The name of the getter/setter to generate. * @param {Function=} extend A method to call before executing the getter/setter. * The existing getter/setter can be accessed from the extend method via the * $super e.g. this.$super(); */ synthesize: function (obj, name, extend) { this._synth[name] = this._synth[name] || function (val) { if (val !== undefined) { this['_' + name] = val; return this; } return this['_' + name]; }; if (extend) { var self = this; obj[name] = function () { var tmp = this.$super, ret; this.$super = self._synth[name]; ret = extend.apply(this, arguments); this.$super = tmp; return ret; }; } else { obj[name] = this._synth[name]; } }, /** * Allows a method to be overloaded. * @memberof Shared * @param arr * @returns {Function} * @constructor */ overload: Overload, /** * Define the mixins that other modules can use as required. * @memberof Shared */ mixins: { 'Mixin.Common': _dereq_('./Mixin.Common'), 'Mixin.Events': _dereq_('./Mixin.Events'), 'Mixin.ChainReactor': _dereq_('./Mixin.ChainReactor'), 'Mixin.CRUD': _dereq_('./Mixin.CRUD'), 'Mixin.Constants': _dereq_('./Mixin.Constants'), 'Mixin.Triggers': _dereq_('./Mixin.Triggers'), 'Mixin.Sorting': _dereq_('./Mixin.Sorting'), 'Mixin.Matching': _dereq_('./Mixin.Matching'), 'Mixin.Updating': _dereq_('./Mixin.Updating'), 'Mixin.Tags': _dereq_('./Mixin.Tags') } }; // Add event handling to shared Shared.mixin(Shared, 'Mixin.Events'); module.exports = Shared; },{"./Mixin.CRUD":16,"./Mixin.ChainReactor":17,"./Mixin.Common":18,"./Mixin.Constants":19,"./Mixin.Events":20,"./Mixin.Matching":21,"./Mixin.Sorting":22,"./Mixin.Tags":23,"./Mixin.Triggers":24,"./Mixin.Updating":25,"./Overload":27}],32:[function(_dereq_,module,exports){ /* jshint strict:false */ if (!Array.prototype.filter) { Array.prototype.filter = function(fun/*, thisArg*/) { if (this === void 0 || this === null) { throw new TypeError(); } var t = Object(this); var len = t.length >>> 0; // jshint ignore:line if (typeof fun !== 'function') { throw new TypeError(); } var res = []; var thisArg = arguments.length >= 2 ? arguments[1] : void 0; for (var i = 0; i < len; i++) { if (i in t) { var val = t[i]; // NOTE: Technically this should Object.defineProperty at // the next index, as push can be affected by // properties on Object.prototype and Array.prototype. // But that method's new, and collisions should be // rare, so use the more-compatible alternative. if (fun.call(thisArg, val, i, t)) { res.push(val); } } } return res; }; } if (typeof Object.create !== 'function') { Object.create = (function() { var Temp = function() {}; return function (prototype) { if (arguments.length > 1) { throw Error('Second argument not supported'); } if (typeof prototype !== 'object') { throw TypeError('Argument must be an object'); } Temp.prototype = prototype; var result = new Temp(); Temp.prototype = null; return result; }; })(); } // Production steps of ECMA-262, Edition 5, 15.4.4.14 // Reference: http://es5.github.io/#x15.4.4.14e if (!Array.prototype.indexOf) { Array.prototype.indexOf = function(searchElement, fromIndex) { var k; // 1. Let O be the result of calling ToObject passing // the this value as the argument. if (this === null) { throw new TypeError('"this" is null or not defined'); } var O = Object(this); // 2. Let lenValue be the result of calling the Get // internal method of O with the argument "length". // 3. Let len be ToUint32(lenValue). var len = O.length >>> 0; // jshint ignore:line // 4. If len is 0, return -1. if (len === 0) { return -1; } // 5. If argument fromIndex was passed let n be // ToInteger(fromIndex); else let n be 0. var n = +fromIndex || 0; if (Math.abs(n) === Infinity) { n = 0; } // 6. If n >= len, return -1. if (n >= len) { return -1; } // 7. If n >= 0, then Let k be n. // 8. Else, n<0, Let k be len - abs(n). // If k is less than 0, then let k be 0. k = Math.max(n >= 0 ? n : len - Math.abs(n), 0); // 9. Repeat, while k < len while (k < len) { // a. Let Pk be ToString(k). // This is implicit for LHS operands of the in operator // b. Let kPresent be the result of calling the // HasProperty internal method of O with argument Pk. // This step can be combined with c // c. If kPresent is true, then // i. Let elementK be the result of calling the Get // internal method of O with the argument ToString(k). // ii. Let same be the result of applying the // Strict Equality Comparison Algorithm to // searchElement and elementK. // iii. If same is true, return k. if (k in O && O[k] === searchElement) { return k; } k++; } return -1; }; } module.exports = {}; },{}],33:[function(_dereq_,module,exports){ "use strict"; // Import external names locally var Shared, Db, Collection, CollectionGroup, CollectionInit, DbInit, ReactorIO, ActiveBucket; Shared = _dereq_('./Shared'); /** * Creates a new view instance. * @param {String} name The name of the view. * @param {Object=} query The view's query. * @param {Object=} options An options object. * @constructor */ var View = function (name, query, options) { this.init.apply(this, arguments); }; View.prototype.init = function (name, query, options) { var self = this; this._name = name; this._listeners = {}; this._querySettings = {}; this._debug = {}; this.query(query, false); this.queryOptions(options, false); this._collectionDroppedWrap = function () { self._collectionDropped.apply(self, arguments); }; this._privateData = new Collection(this.name() + '_internalPrivate'); }; Shared.addModule('View', View); Shared.mixin(View.prototype, 'Mixin.Common'); Shared.mixin(View.prototype, 'Mixin.ChainReactor'); Shared.mixin(View.prototype, 'Mixin.Constants'); Shared.mixin(View.prototype, 'Mixin.Triggers'); Shared.mixin(View.prototype, 'Mixin.Tags'); Collection = _dereq_('./Collection'); CollectionGroup = _dereq_('./CollectionGroup'); ActiveBucket = _dereq_('./ActiveBucket'); ReactorIO = _dereq_('./ReactorIO'); CollectionInit = Collection.prototype.init; Db = Shared.modules.Db; DbInit = Db.prototype.init; /** * Gets / sets the current state. * @param {String=} val The name of the state to set. * @returns {*} */ Shared.synthesize(View.prototype, 'state'); /** * Gets / sets the current name. * @param {String=} val The new name to set. * @returns {*} */ Shared.synthesize(View.prototype, 'name'); /** * Gets / sets the current cursor. * @param {String=} val The new cursor to set. * @returns {*} */ Shared.synthesize(View.prototype, 'cursor', function (val) { if (val === undefined) { return this._cursor || {}; } this.$super.apply(this, arguments); }); /** * Executes an insert against the view's underlying data-source. * @see Collection::insert() */ View.prototype.insert = function () { this._from.insert.apply(this._from, arguments); }; /** * Executes an update against the view's underlying data-source. * @see Collection::update() */ View.prototype.update = function () { this._from.update.apply(this._from, arguments); }; /** * Executes an updateById against the view's underlying data-source. * @see Collection::updateById() */ View.prototype.updateById = function () { this._from.updateById.apply(this._from, arguments); }; /** * Executes a remove against the view's underlying data-source. * @see Collection::remove() */ View.prototype.remove = function () { this._from.remove.apply(this._from, arguments); }; /** * Queries the view data. * @see Collection::find() * @returns {Array} The result of the find query. */ View.prototype.find = function (query, options) { return this.publicData().find(query, options); }; /** * Queries the view data for a single document. * @see Collection::findOne() * @returns {Object} The result of the find query. */ View.prototype.findOne = function (query, options) { return this.publicData().findOne(query, options); }; /** * Queries the view data by specific id. * @see Collection::findById() * @returns {Array} The result of the find query. */ View.prototype.findById = function (id, options) { return this.publicData().findById(id, options); }; /** * Queries the view data in a sub-array. * @see Collection::findSub() * @returns {Array} The result of the find query. */ View.prototype.findSub = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSub(match, path, subDocQuery, subDocOptions); }; /** * Queries the view data in a sub-array and returns first match. * @see Collection::findSubOne() * @returns {Object} The result of the find query. */ View.prototype.findSubOne = function (match, path, subDocQuery, subDocOptions) { return this.publicData().findSubOne(match, path, subDocQuery, subDocOptions); }; /** * Gets the module's internal data collection. * @returns {Collection} */ View.prototype.data = function () { return this._privateData; }; /** * Sets the source from which the view will assemble its data. * @param {Collection|View} source The source to use to assemble view data. * @param {Function=} callback A callback method. * @returns {*} If no argument is passed, returns the current value of from, * otherwise returns itself for chaining. */ View.prototype.from = function (source, callback) { var self = this; if (source !== undefined) { // Check if we have an existing from if (this._from) { // Remove the listener to the drop event this._from.off('drop', this._collectionDroppedWrap); delete this._from; } // Check if we have an existing reactor io if (this._io) { // Drop the io and remove it this._io.drop(); delete this._io; } if (typeof(source) === 'string') { source = this._db.collection(source); } if (source.className === 'View') { // The source is a view so IO to the internal data collection // instead of the view proper source = source.privateData(); if (this.debug()) { console.log(this.logIdentifier() + ' Using internal private data "' + source.instanceIdentifier() + '" for IO graph linking'); } } this._from = source; this._from.on('drop', this._collectionDroppedWrap); // Create a new reactor IO graph node that intercepts chain packets from the // view's "from" source and determines how they should be interpreted by // this view. If the view does not have a query then this reactor IO will // simply pass along the chain packet without modifying it. this._io = new ReactorIO(source, this, function (chainPacket) { var data, diff, query, filteredData, doSend, pk, i; // Check that the state of the "self" object is not dropped if (self && !self.isDropped()) { // Check if we have a constraining query if (self._querySettings.query) { if (chainPacket.type === 'insert') { data = chainPacket.data; // Check if the data matches our query if (data instanceof Array) { filteredData = []; for (i = 0; i < data.length; i++) { if (self._privateData._match(data[i], self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData.push(data[i]); doSend = true; } } } else { if (self._privateData._match(data, self._querySettings.query, self._querySettings.options, 'and', {})) { filteredData = data; doSend = true; } } if (doSend) { this.chainSend('insert', filteredData); } return true; } if (chainPacket.type === 'update') { // Do a DB diff between this view's data and the underlying collection it reads from // to see if something has changed diff = self._privateData.diff(self._from.subset(self._querySettings.query, self._querySettings.options)); if (diff.insert.length || diff.remove.length) { // Now send out new chain packets for each operation if (diff.insert.length) { this.chainSend('insert', diff.insert); } if (diff.update.length) { pk = self._privateData.primaryKey(); for (i = 0; i < diff.update.length; i++) { query = {}; query[pk] = diff.update[i][pk]; this.chainSend('update', { query: query, update: diff.update[i] }); } } if (diff.remove.length) { pk = self._privateData.primaryKey(); var $or = [], removeQuery = { query: { $or: $or } }; for (i = 0; i < diff.remove.length; i++) { $or.push({_id: diff.remove[i][pk]}); } this.chainSend('remove', removeQuery); } // Return true to stop further propagation of the chain packet return true; } else { // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; } } } } // Returning false informs the chain reactor to continue propagation // of the chain packet down the graph tree return false; }); var collData = source.find(this._querySettings.query, this._querySettings.options); this._privateData.primaryKey(source.primaryKey()); this._privateData.setData(collData, {}, callback); if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; } return this._from; }; /** * Handles when an underlying collection the view is using as a data * source is dropped. * @param {Collection} collection The collection that has been dropped. * @private */ View.prototype._collectionDropped = function (collection) { if (collection) { // Collection was dropped, remove from view delete this._from; } }; /** * Creates an index on the view. * @see Collection::ensureIndex() * @returns {*} */ View.prototype.ensureIndex = function () { return this._privateData.ensureIndex.apply(this._privateData, arguments); }; /** * The chain reaction handler method for the view. * @param {Object} chainPacket The chain reaction packet to handle. * @private */ View.prototype._chainHandler = function (chainPacket) { var //self = this, arr, count, index, insertIndex, updates, primaryKey, item, currentIndex; if (this.debug()) { console.log(this.logIdentifier() + ' Received chain reactor data'); } switch (chainPacket.type) { case 'setData': if (this.debug()) { console.log(this.logIdentifier() + ' Setting data in underlying (internal) view collection "' + this._privateData.name() + '"'); } // Get the new data from our underlying data source sorted as we want var collData = this._from.find(this._querySettings.query, this._querySettings.options); this._privateData.setData(collData); break; case 'insert': if (this.debug()) { console.log(this.logIdentifier() + ' Inserting some data into underlying (internal) view collection "' + this._privateData.name() + '"'); } // Decouple the data to ensure we are working with our own copy chainPacket.data = this.decouple(chainPacket.data); // Make sure we are working with an array if (!(chainPacket.data instanceof Array)) { chainPacket.data = [chainPacket.data]; } if (this._querySettings.options && this._querySettings.options.$orderBy) { // Loop the insert data and find each item's index arr = chainPacket.data; count = arr.length; for (index = 0; index < count; index++) { insertIndex = this._activeBucket.insert(arr[index]); this._privateData._insertHandle(chainPacket.data, insertIndex); } } else { // Set the insert index to the passed index, or if none, the end of the view data array insertIndex = this._privateData._data.length; this._privateData._insertHandle(chainPacket.data, insertIndex); } break; case 'update': if (this.debug()) { console.log(this.logIdentifier() + ' Updating some data in underlying (internal) view collection "' + this._privateData.name() + '"'); } primaryKey = this._privateData.primaryKey(); // Do the update updates = this._privateData.update( chainPacket.data.query, chainPacket.data.update, chainPacket.data.options ); if (this._querySettings.options && this._querySettings.options.$orderBy) { // TODO: This would be a good place to improve performance by somehow // TODO: inspecting the change that occurred when update was performed // TODO: above and determining if it affected the order clause keys // TODO: and if not, skipping the active bucket updates here // Loop the updated items and work out their new sort locations count = updates.length; for (index = 0; index < count; index++) { item = updates[index]; // Remove the item from the active bucket (via it's id) this._activeBucket.remove(item); // Get the current location of the item currentIndex = this._privateData._data.indexOf(item); // Add the item back in to the active bucket insertIndex = this._activeBucket.insert(item); if (currentIndex !== insertIndex) { // Move the updated item to the new index this._privateData._updateSpliceMove(this._privateData._data, currentIndex, insertIndex); } } } break; case 'remove': if (this.debug()) { console.log(this.logIdentifier() + ' Removing some data from underlying (internal) view collection "' + this._privateData.name() + '"'); } this._privateData.remove(chainPacket.data.query, chainPacket.options); break; default: break; } }; /** * Listens for an event. * @see Mixin.Events::on() */ View.prototype.on = function () { return this._privateData.on.apply(this._privateData, arguments); }; /** * Cancels an event listener. * @see Mixin.Events::off() */ View.prototype.off = function () { return this._privateData.off.apply(this._privateData, arguments); }; /** * Emits an event. * @see Mixin.Events::emit() */ View.prototype.emit = function () { return this._privateData.emit.apply(this._privateData, arguments); }; /** * Find the distinct values for a specified field across a single collection and * returns the results in an array. * @param {String} key The field path to return distinct values for e.g. "person.name". * @param {Object=} query The query to use to filter the documents used to return values from. * @param {Object=} options The query options to use when running the query. * @returns {Array} */ View.prototype.distinct = function (key, query, options) { var coll = this.publicData(); return coll.distinct.apply(coll, arguments); }; /** * Gets the primary key for this view from the assigned collection. * @see Collection::primaryKey() * @returns {String} */ View.prototype.primaryKey = function () { return this.publicData().primaryKey(); }; /** * Drops a view and all it's stored data from the database. * @returns {boolean} True on success, false on failure. */ View.prototype.drop = function (callback) { if (!this.isDropped()) { if (this._from) { this._from.off('drop', this._collectionDroppedWrap); this._from._removeView(this); } if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Dropping'); } this._state = 'dropped'; // Clear io and chains if (this._io) { this._io.drop(); } // Drop the view's internal collection if (this._privateData) { this._privateData.drop(); } if (this._publicData && this._publicData !== this._privateData) { this._publicData.drop(); } if (this._db && this._name) { delete this._db._view[this._name]; } this.emit('drop', this); if (callback) { callback(false, true); } delete this._chain; delete this._from; delete this._privateData; delete this._io; delete this._listeners; delete this._querySettings; delete this._db; return true; } return false; }; /** * Gets / sets the db instance this class instance belongs to. * @param {Db=} db The db instance. * @memberof View * @returns {*} */ Shared.synthesize(View.prototype, 'db', function (db) { if (db) { this.privateData().db(db); this.publicData().db(db); // Apply the same debug settings this.debug(db.debug()); this.privateData().debug(db.debug()); this.publicData().debug(db.debug()); } return this.$super.apply(this, arguments); }); /** * Gets / sets the query object and query options that the view uses * to build it's data set. This call modifies both the query and * query options at the same time. * @param {Object=} query The query to set. * @param {Boolean=} options The query options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryData = function (query, options, refresh) { if (query !== undefined) { this._querySettings.query = query; } if (options !== undefined) { this._querySettings.options = options; } if (query !== undefined || options !== undefined) { if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings; }; /** * Add data to the existing query. * @param {Object} obj The data whose keys will be added to the existing * query object. * @param {Boolean} overwrite Whether or not to overwrite data that already * exists in the query object. Defaults to true. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryAdd = function (obj, overwrite, refresh) { this._querySettings.query = this._querySettings.query || {}; var query = this._querySettings.query, i; if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { if (query[i] === undefined || (query[i] !== undefined && overwrite !== false)) { query[i] = obj[i]; } } } } if (refresh === undefined || refresh === true) { this.refresh(); } }; /** * Remove data from the existing query. * @param {Object} obj The data whose keys will be removed from the existing * query object. * @param {Boolean=} refresh Whether or not to refresh the view data set * once the operation is complete. Defaults to true. */ View.prototype.queryRemove = function (obj, refresh) { var query = this._querySettings.query, i; if (query) { if (obj !== undefined) { // Loop object properties and add to existing query for (i in obj) { if (obj.hasOwnProperty(i)) { delete query[i]; } } } if (refresh === undefined || refresh === true) { this.refresh(); } } }; /** * Gets / sets the query being used to generate the view data. It * does not change or modify the view's query options. * @param {Object=} query The query to set. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.query = function (query, refresh) { if (query !== undefined) { this._querySettings.query = query; if (refresh === undefined || refresh === true) { this.refresh(); } return this; } return this._querySettings.query; }; /** * Gets / sets the orderBy clause in the query options for the view. * @param {Object=} val The order object. * @returns {*} */ View.prototype.orderBy = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; queryOptions.$orderBy = val; this.queryOptions(queryOptions); return this; } return (this.queryOptions() || {}).$orderBy; }; /** * Gets / sets the page clause in the query options for the view. * @param {Number=} val The page number to change to (zero index). * @returns {*} */ View.prototype.page = function (val) { if (val !== undefined) { var queryOptions = this.queryOptions() || {}; // Only execute a query options update if page has changed if (val !== queryOptions.$page) { queryOptions.$page = val; this.queryOptions(queryOptions); } return this; } return (this.queryOptions() || {}).$page; }; /** * Jump to the first page in the data set. * @returns {*} */ View.prototype.pageFirst = function () { return this.page(0); }; /** * Jump to the last page in the data set. * @returns {*} */ View.prototype.pageLast = function () { var pages = this.cursor().pages, lastPage = pages !== undefined ? pages : 0; return this.page(lastPage - 1); }; /** * Move forward or backwards in the data set pages by passing a positive * or negative integer of the number of pages to move. * @param {Number} val The number of pages to move. * @returns {*} */ View.prototype.pageScan = function (val) { if (val !== undefined) { var pages = this.cursor().pages, queryOptions = this.queryOptions() || {}, currentPage = queryOptions.$page !== undefined ? queryOptions.$page : 0; currentPage += val; if (currentPage < 0) { currentPage = 0; } if (currentPage >= pages) { currentPage = pages - 1; } return this.page(currentPage); } }; /** * Gets / sets the query options used when applying sorting etc to the * view data set. * @param {Object=} options An options object. * @param {Boolean=} refresh Whether to refresh the view data after * this operation. Defaults to true. * @returns {*} */ View.prototype.queryOptions = function (options, refresh) { if (options !== undefined) { this._querySettings.options = options; if (options.$decouple === undefined) { options.$decouple = true; } if (refresh === undefined || refresh === true) { this.refresh(); } else { this.rebuildActiveBucket(options.$orderBy); } return this; } return this._querySettings.options; }; View.prototype.rebuildActiveBucket = function (orderBy) { if (orderBy) { var arr = this._privateData._data, arrCount = arr.length; // Build a new active bucket this._activeBucket = new ActiveBucket(orderBy); this._activeBucket.primaryKey(this._privateData.primaryKey()); // Loop the current view data and add each item for (var i = 0; i < arrCount; i++) { this._activeBucket.insert(arr[i]); } } else { // Remove any existing active bucket delete this._activeBucket; } }; /** * Refreshes the view data such as ordering etc. */ View.prototype.refresh = function () { if (this._from) { var pubData = this.publicData(), refreshResults; // Re-grab all the data for the view from the collection this._privateData.remove(); //pubData.remove(); refreshResults = this._from.find(this._querySettings.query, this._querySettings.options); this.cursor(refreshResults.$cursor); this._privateData.insert(refreshResults); this._privateData._data.$cursor = refreshResults.$cursor; pubData._data.$cursor = refreshResults.$cursor; /*if (pubData._linked) { // Update data and observers //var transformedData = this._privateData.find(); // TODO: Shouldn't this data get passed into a transformIn first? // TODO: This breaks linking because its passing decoupled data and overwriting non-decoupled data // TODO: Is this even required anymore? After commenting it all seems to work // TODO: Might be worth setting up a test to check transforms and linking then remove this if working? //jQuery.observable(pubData._data).refresh(transformedData); }*/ } if (this._querySettings.options && this._querySettings.options.$orderBy) { this.rebuildActiveBucket(this._querySettings.options.$orderBy); } else { this.rebuildActiveBucket(); } return this; }; /** * Returns the number of documents currently in the view. * @returns {Number} */ View.prototype.count = function () { if (this.publicData()) { return this.publicData().count.apply(this.publicData(), arguments); } return 0; }; // Call underlying View.prototype.subset = function () { return this.publicData().subset.apply(this._privateData, arguments); }; /** * Takes the passed data and uses it to set transform methods and globally * enable or disable the transform system for the view. * @param {Object} obj The new transform system settings "enabled", "dataIn" and "dataOut": * { * "enabled": true, * "dataIn": function (data) { return data; }, * "dataOut": function (data) { return data; } * } * @returns {*} */ View.prototype.transform = function (obj) { var self = this; if (obj !== undefined) { if (typeof obj === "object") { if (obj.enabled !== undefined) { this._transformEnabled = obj.enabled; } if (obj.dataIn !== undefined) { this._transformIn = obj.dataIn; } if (obj.dataOut !== undefined) { this._transformOut = obj.dataOut; } } else { this._transformEnabled = obj !== false; } if (this._transformEnabled) { // Check for / create the public data collection if (!this._publicData) { // Create the public data collection this._publicData = new Collection('__FDB__view_publicData_' + this._name); this._publicData.db(this._privateData._db); this._publicData.transform({ enabled: true, dataIn: this._transformIn, dataOut: this._transformOut }); // Create a chain reaction IO node to keep the private and // public data collections in sync this._transformIo = new ReactorIO(this._privateData, this._publicData, function (chainPacket) { var data = chainPacket.data; switch (chainPacket.type) { case 'primaryKey': self._publicData.primaryKey(data); this.chainSend('primaryKey', data); break; case 'setData': self._publicData.setData(data); this.chainSend('setData', data); break; case 'insert': self._publicData.insert(data); this.chainSend('insert', data); break; case 'update': // Do the update self._publicData.update( data.query, data.update, data.options ); this.chainSend('update', data); break; case 'remove': self._publicData.remove(data.query, chainPacket.options); this.chainSend('remove', data); break; default: break; } }); } // Set initial data and settings this._publicData.primaryKey(this.privateData().primaryKey()); this._publicData.setData(this.privateData().find()); } else { // Remove the public data collection if (this._publicData) { this._publicData.drop(); delete this._publicData; if (this._transformIo) { this._transformIo.drop(); delete this._transformIo; } } } return this; } return { enabled: this._transformEnabled, dataIn: this._transformIn, dataOut: this._transformOut }; }; /** * Executes a method against each document that matches query and returns an * array of documents that may have been modified by the method. * @param {Object} query The query object. * @param {Function} func The method that each document is passed to. If this method * returns false for a particular document it is excluded from the results. * @param {Object=} options Optional options object. * @returns {Array} */ View.prototype.filter = function (query, func, options) { return (this.publicData()).filter(query, func, options); }; /** * Returns the non-transformed data the view holds as a collection * reference. * @return {Collection} The non-transformed collection reference. */ View.prototype.privateData = function () { return this._privateData; }; /** * Returns a data object representing the public data this view * contains. This can change depending on if transforms are being * applied to the view or not. * * If no transforms are applied then the public data will be the * same as the private data the view holds. If transforms are * applied then the public data will contain the transformed version * of the private data. * * The public data collection is also used by data binding to only * changes to the publicData will show in a data-bound element. */ View.prototype.publicData = function () { if (this._transformEnabled) { return this._publicData; } else { return this._privateData; } }; // Extend collection with view init Collection.prototype.init = function () { this._view = []; CollectionInit.apply(this, arguments); }; /** * Creates a view and assigns the collection as its data source. * @param {String} name The name of the new view. * @param {Object} query The query to apply to the new view. * @param {Object} options The options object to apply to the view. * @returns {*} */ Collection.prototype.view = function (name, query, options) { if (this._db && this._db._view ) { if (!this._db._view[name]) { var view = new View(name, query, options) .db(this._db) .from(this); this._view = this._view || []; this._view.push(view); return view; } else { throw(this.logIdentifier() + ' Cannot create a view using this collection because a view with this name already exists: ' + name); } } }; /** * Adds a view to the internal view lookup. * @param {View} view The view to add. * @returns {Collection} * @private */ Collection.prototype._addView = CollectionGroup.prototype._addView = function (view) { if (view !== undefined) { this._view.push(view); } return this; }; /** * Removes a view from the internal view lookup. * @param {View} view The view to remove. * @returns {Collection} * @private */ Collection.prototype._removeView = CollectionGroup.prototype._removeView = function (view) { if (view !== undefined) { var index = this._view.indexOf(view); if (index > -1) { this._view.splice(index, 1); } } return this; }; // Extend DB with views init Db.prototype.init = function () { this._view = {}; DbInit.apply(this, arguments); }; /** * Gets a view by it's name. * @param {String} viewName The name of the view to retrieve. * @returns {*} */ Db.prototype.view = function (viewName) { var self = this; // Handle being passed an instance if (viewName instanceof View) { return viewName; } if (this._view[viewName]) { return this._view[viewName]; } else { if (this.debug() || (this._db && this._db.debug())) { console.log(this.logIdentifier() + ' Creating view ' + viewName); } } this._view[viewName] = this._view[viewName] || new View(viewName).db(this); self.emit('create', [self._view[viewName], 'view', viewName]); return this._view[viewName]; }; /** * Determine if a view with the passed name already exists. * @param {String} viewName The name of the view to check for. * @returns {boolean} */ Db.prototype.viewExists = function (viewName) { return Boolean(this._view[viewName]); }; /** * Returns an array of views the DB currently has. * @returns {Array} An array of objects containing details of each view * the database is currently managing. */ Db.prototype.views = function () { var arr = [], view, i; for (i in this._view) { if (this._view.hasOwnProperty(i)) { view = this._view[i]; arr.push({ name: i, count: view.count(), linked: view.isLinked !== undefined ? view.isLinked() : false }); } } return arr; }; Shared.finishModule('View'); module.exports = View; },{"./ActiveBucket":3,"./Collection":5,"./CollectionGroup":6,"./ReactorIO":29,"./Shared":31}]},{},[1]);
loadIonicon('<svg xmlns="http://www.w3.org/2000/svg" width="512" height="512" viewBox="0 0 512 512"><path d="M391.553 64H57.607C53.13 64 48 67.745 48 72.16v214.216c0 4.413 5.13 8.624 9.607 8.624H115v88.894L205.128 295h186.425c4.477 0 7.447-4.21 7.447-8.624V72.16c0-4.415-2.97-8.16-7.447-8.16z"/><path d="M456.396 127H424v166.57c0 15.987-6.915 26.43-25.152 26.43H218.096l-38.905 39h129.69L399 448v-89h57.396c4.478 0 7.604-4.262 7.604-8.682V136.103c0-4.414-3.126-9.103-7.604-9.103z"/></svg>','md-chatboxes');
require('./angular-locale_yue'); module.exports = 'ngLocale';
/*! SWFMini - a SWFObject 2.2 cut down version for webshims * * based on SWFObject v2.2 <http://code.google.com/p/swfobject/> is released under the MIT License <http://www.opensource.org/licenses/mit-license.php> */ var swfmini = function() { var wasRemoved = function(){webshims.error('This method was removed from swfmini');}; var UNDEF = "undefined", OBJECT = "object", webshims = window.webshims, SHOCKWAVE_FLASH = "Shockwave Flash", SHOCKWAVE_FLASH_AX = "ShockwaveFlash.ShockwaveFlash", FLASH_MIME_TYPE = "application/x-shockwave-flash", win = window, doc = document, nav = navigator, plugin = false, domLoadFnArr = [main], isDomLoaded = false, autoHideShow = true, /* Centralized function for browser feature detection - User agent string detection is only used when no good alternative is possible - Is executed directly for optimal performance */ ua = function() { var w3cdom = typeof doc.getElementById != UNDEF && typeof doc.getElementsByTagName != UNDEF && typeof doc.createElement != UNDEF, u = nav.userAgent.toLowerCase(), p = nav.platform.toLowerCase(), windows = p ? /win/.test(p) : /win/.test(u), mac = p ? /mac/.test(p) : /mac/.test(u), webkit = /webkit/.test(u) ? parseFloat(u.replace(/^.*webkit\/(\d+(\.\d+)?).*$/, "$1")) : false, // returns either the webkit version or false if not webkit ie = !+"\v1", // feature detection based on Andrea Giammarchi's solution: http://webreflection.blogspot.com/2009/01/32-bytes-to-know-if-your-browser-is-ie.html playerVersion = [0,0,0], d = null; if (typeof nav.plugins != UNDEF && typeof nav.plugins[SHOCKWAVE_FLASH] == OBJECT) { d = nav.plugins[SHOCKWAVE_FLASH].description; if (d && !(typeof nav.mimeTypes != UNDEF && nav.mimeTypes[FLASH_MIME_TYPE] && !nav.mimeTypes[FLASH_MIME_TYPE].enabledPlugin)) { // navigator.mimeTypes["application/x-shockwave-flash"].enabledPlugin indicates whether plug-ins are enabled or disabled in Safari 3+ plugin = true; ie = false; // cascaded feature detection for Internet Explorer d = d.replace(/^.*\s+(\S+\s+\S+$)/, "$1"); playerVersion[0] = parseInt(d.replace(/^(.*)\..*$/, "$1"), 10); playerVersion[1] = parseInt(d.replace(/^.*\.(.*)\s.*$/, "$1"), 10); playerVersion[2] = /[a-zA-Z]/.test(d) ? parseInt(d.replace(/^.*[a-zA-Z]+(.*)$/, "$1"), 10) : 0; } } else if (typeof win.ActiveXObject != UNDEF) { try { var a = new ActiveXObject(SHOCKWAVE_FLASH_AX); if (a) { // a will return null when ActiveX is disabled d = a.GetVariable("$version"); if (d) { ie = true; // cascaded feature detection for Internet Explorer d = d.split(" ")[1].split(","); playerVersion = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } } catch(e) {} } return { w3:w3cdom, pv:playerVersion, wk:webkit, ie:ie, win:windows, mac:mac }; }(); function callDomLoadFunctions() { if (isDomLoaded) { return; } isDomLoaded = true; var dl = domLoadFnArr.length; for (var i = 0; i < dl; i++) { domLoadFnArr[i](); } } function addDomLoadEvent(fn) { if (isDomLoaded) { fn(); } else { domLoadFnArr[domLoadFnArr.length] = fn; // Array.push() is only available in IE5.5+ } } /* Main function - Will preferably execute onDomLoad, otherwise onload (as a fallback) */ function main() { if (plugin) { testPlayerVersion(); } } /* Detect the Flash Player version for non-Internet Explorer browsers - Detecting the plug-in version via the object element is more precise than using the plugins collection item's description: a. Both release and build numbers can be detected b. Avoid wrong descriptions by corrupt installers provided by Adobe c. Avoid wrong descriptions by multiple Flash Player entries in the plugin Array, caused by incorrect browser imports - Disadvantage of this method is that it depends on the availability of the DOM, while the plugins collection is immediately available */ function testPlayerVersion() { var b = doc.getElementsByTagName("body")[0]; var o = createElement(OBJECT); o.setAttribute("type", FLASH_MIME_TYPE); var t = b.appendChild(o); if (t) { var counter = 0; (function(){ if (typeof t.GetVariable != UNDEF) { var d = t.GetVariable("$version"); if (d) { d = d.split(" ")[1].split(","); ua.pv = [parseInt(d[0], 10), parseInt(d[1], 10), parseInt(d[2], 10)]; } } else if (counter < 10) { counter++; setTimeout(arguments.callee, 10); return; } b.removeChild(o); t = null; })(); } } function createElement(el) { return doc.createElement(el); } /* Flash Player and SWF content version matching */ function hasPlayerVersion(rv) { var pv = ua.pv, v = rv.split("."); v[0] = parseInt(v[0], 10); v[1] = parseInt(v[1], 10) || 0; // supports short notation, e.g. "9" instead of "9.0.0" v[2] = parseInt(v[2], 10) || 0; return (pv[0] > v[0] || (pv[0] == v[0] && pv[1] > v[1]) || (pv[0] == v[0] && pv[1] == v[1] && pv[2] >= v[2])) ? true : false; } webshims.ready('DOM', callDomLoadFunctions); webshims.loader.addModule('swfmini-embed', {d: ['swfmini']}); var loadEmbed = hasPlayerVersion('9.0.0') ? function(){ webshims.loader.loadList(['swfmini-embed']); return true; } : webshims.$.noop ; if(!webshims.support.mediaelement){ loadEmbed(); } else { webshims.ready('WINDOWLOAD', loadEmbed); } return { /* Public API - Reference: http://code.google.com/p/swfobject/wiki/documentation */ registerObject: wasRemoved, getObjectById: wasRemoved, embedSWF: function(swfUrlStr, replaceElemIdStr, widthStr, heightStr, swfVersionStr, xiSwfUrlStr, flashvarsObj, parObj, attObj, callbackFn) { var args = arguments; if(loadEmbed()){ webshims.ready('swfmini-embed', function(){ swfmini.embedSWF.apply(swfmini, args); }); } else if(callbackFn) { callbackFn({success:false, id:replaceElemIdStr}); } }, switchOffAutoHideShow: function() { autoHideShow = false; }, ua: ua, getFlashPlayerVersion: function() { return { major:ua.pv[0], minor:ua.pv[1], release:ua.pv[2] }; }, hasFlashPlayerVersion: hasPlayerVersion, createSWF: function(attObj, parObj, replaceElemIdStr) { if (ua.w3) { return createSWF(attObj, parObj, replaceElemIdStr); } else { return undefined; } }, showExpressInstall: wasRemoved, removeSWF: wasRemoved, createCSS: wasRemoved, addDomLoadEvent: addDomLoadEvent, addLoadEvent: wasRemoved, // For internal usage only expressInstallCallback: wasRemoved }; }(); webshims.isReady('swfmini', true); ;(function(webshims){ "use strict"; var support = webshims.support; var hasNative = support.mediaelement; var supportsLoop = false; var bugs = webshims.bugs; var swfType = 'mediaelement-jaris'; var loadSwf = function(){ webshims.ready(swfType, function(){ if(!webshims.mediaelement.createSWF){ webshims.mediaelement.loadSwf = true; webshims.reTest([swfType], hasNative); } }); }; var wsCfg = webshims.cfg; var options = wsCfg.mediaelement; var isIE = navigator.userAgent.indexOf('MSIE') != -1; if(!options){ webshims.error("mediaelement wasn't implemented but loaded"); return; } if(hasNative){ var videoElem = document.createElement('video'); support.videoBuffered = ('buffered' in videoElem); support.mediaDefaultMuted = ('defaultMuted' in videoElem); supportsLoop = ('loop' in videoElem); support.mediaLoop = supportsLoop; webshims.capturingEvents(['play', 'playing', 'waiting', 'paused', 'ended', 'durationchange', 'loadedmetadata', 'canplay', 'volumechange']); if( !support.videoBuffered || !supportsLoop || (!support.mediaDefaultMuted && isIE && 'ActiveXObject' in window) ){ webshims.addPolyfill('mediaelement-native-fix', { d: ['dom-support'] }); webshims.loader.loadList(['mediaelement-native-fix']); } } if(support.track && !bugs.track){ (function(){ if(!bugs.track){ if(window.VTTCue && !window.TextTrackCue){ window.TextTrackCue = window.VTTCue; } else if(!window.VTTCue){ window.VTTCue = window.TextTrackCue; } try { new VTTCue(2, 3, ''); } catch(e){ bugs.track = true; } } })(); } webshims.register('mediaelement-core', function($, webshims, window, document, undefined, options){ var hasSwf = swfmini.hasFlashPlayerVersion('11.3'); var mediaelement = webshims.mediaelement; var allowYtLoading = false; mediaelement.parseRtmp = function(data){ var src = data.src.split('://'); var paths = src[1].split('/'); var i, len, found; data.server = src[0]+'://'+paths[0]+'/'; data.streamId = []; for(i = 1, len = paths.length; i < len; i++){ if(!found && paths[i].indexOf(':') !== -1){ paths[i] = paths[i].split(':')[1]; found = true; } if(!found){ data.server += paths[i]+'/'; } else { data.streamId.push(paths[i]); } } if(!data.streamId.length){ webshims.error('Could not parse rtmp url'); } data.streamId = data.streamId.join('/'); }; var getSrcObj = function(elem, nodeName){ elem = $(elem); var src = {src: elem.attr('src') || '', elem: elem, srcProp: elem.prop('src')}; var tmp; if(!src.src){return src;} tmp = elem.attr('data-server'); if(tmp != null){ src.server = tmp; } tmp = elem.attr('type') || elem.attr('data-type'); if(tmp){ src.type = tmp; src.container = $.trim(tmp.split(';')[0]); } else { if(!nodeName){ nodeName = elem[0].nodeName.toLowerCase(); if(nodeName == 'source'){ nodeName = (elem.closest('video, audio')[0] || {nodeName: 'video'}).nodeName.toLowerCase(); } } if(src.server){ src.type = nodeName+'/rtmp'; src.container = nodeName+'/rtmp'; } else { tmp = mediaelement.getTypeForSrc( src.src, nodeName, src ); if(tmp){ src.type = tmp; src.container = tmp; } } } tmp = elem.attr('media'); if(tmp){ src.media = tmp; } if(src.type == 'audio/rtmp' || src.type == 'video/rtmp'){ if(src.server){ src.streamId = src.src; } else { mediaelement.parseRtmp(src); } } return src; }; var hasYt = !hasSwf && ('postMessage' in window) && hasNative; var loadTrackUi = function(){ if(loadTrackUi.loaded){return;} loadTrackUi.loaded = true; if(!options.noAutoTrack){ webshims.ready('WINDOWLOAD', function(){ loadThird(); webshims.loader.loadList(['track-ui']); }); } }; var loadYt = (function(){ var loaded; return function(){ if(loaded || !hasYt){return;} loaded = true; if(allowYtLoading){ webshims.loader.loadScript("https://www.youtube.com/player_api"); } $(function(){ webshims._polyfill(["mediaelement-yt"]); }); }; })(); var loadThird = function(){ if(hasSwf){ loadSwf(); } else { loadYt(); } }; webshims.addPolyfill('mediaelement-yt', { test: !hasYt, d: ['dom-support'] }); mediaelement.mimeTypes = { audio: { //ogm shouldn´t be used! 'audio/ogg': ['ogg','oga', 'ogm'], 'audio/ogg;codecs="opus"': 'opus', 'audio/mpeg': ['mp2','mp3','mpga','mpega'], 'audio/mp4': ['mp4','mpg4', 'm4r', 'm4a', 'm4p', 'm4b', 'aac'], 'audio/wav': ['wav'], 'audio/3gpp': ['3gp','3gpp'], 'audio/webm': ['webm'], 'audio/fla': ['flv', 'f4a', 'fla'], 'application/x-mpegURL': ['m3u8', 'm3u'] }, video: { //ogm shouldn´t be used! 'video/ogg': ['ogg','ogv', 'ogm'], 'video/mpeg': ['mpg','mpeg','mpe'], 'video/mp4': ['mp4','mpg4', 'm4v'], 'video/quicktime': ['mov','qt'], 'video/x-msvideo': ['avi'], 'video/x-ms-asf': ['asf', 'asx'], 'video/flv': ['flv', 'f4v'], 'video/3gpp': ['3gp','3gpp'], 'video/webm': ['webm'], 'application/x-mpegURL': ['m3u8', 'm3u'], 'video/MP2T': ['ts'] } } ; mediaelement.mimeTypes.source = $.extend({}, mediaelement.mimeTypes.audio, mediaelement.mimeTypes.video); mediaelement.getTypeForSrc = function(src, nodeName){ if(src.indexOf('youtube.com/watch?') != -1 || src.indexOf('youtube.com/v/') != -1){ return 'video/youtube'; } if(!src.indexOf('mediastream:') || !src.indexOf('blob:http')){ return 'usermedia'; } if(!src.indexOf('webshimstream')){ return 'jarisplayer/stream'; } if(!src.indexOf('rtmp')){ return nodeName+'/rtmp'; } src = src.split('?')[0].split('#')[0].split('.'); src = src[src.length - 1]; var mt; $.each(mediaelement.mimeTypes[nodeName], function(mimeType, exts){ if(exts.indexOf(src) !== -1){ mt = mimeType; return false; } }); return mt; }; mediaelement.srces = function(mediaElem){ var srces = []; mediaElem = $(mediaElem); var nodeName = mediaElem[0].nodeName.toLowerCase(); var src = getSrcObj(mediaElem, nodeName); if(!src.src){ $('source', mediaElem).each(function(){ src = getSrcObj(this, nodeName); if(src.src){srces.push(src);} }); } else { srces.push(src); } return srces; }; mediaelement.swfMimeTypes = ['video/3gpp', 'video/x-msvideo', 'video/quicktime', 'video/x-m4v', 'video/mp4', 'video/m4p', 'video/x-flv', 'video/flv', 'audio/mpeg', 'audio/aac', 'audio/mp4', 'audio/x-m4a', 'audio/m4a', 'audio/mp3', 'audio/x-fla', 'audio/fla', 'youtube/flv', 'video/jarisplayer', 'jarisplayer/jarisplayer', 'jarisplayer/stream', 'video/youtube', 'video/rtmp', 'audio/rtmp']; mediaelement.canThirdPlaySrces = function(mediaElem, srces){ var ret = ''; if(hasSwf || hasYt){ mediaElem = $(mediaElem); srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.container && src.src && ((hasSwf && mediaelement.swfMimeTypes.indexOf(src.container) != -1) || (hasYt && src.container == 'video/youtube'))){ ret = src; return false; } }); } return ret; }; var nativeCanPlayType = {}; mediaelement.canNativePlaySrces = function(mediaElem, srces){ var ret = ''; if(hasNative){ mediaElem = $(mediaElem); var nodeName = (mediaElem[0].nodeName || '').toLowerCase(); var nativeCanPlay = (nativeCanPlayType[nodeName] || {prop: {_supvalue: false}}).prop._supvalue || mediaElem[0].canPlayType; if(!nativeCanPlay){return ret;} srces = srces || mediaelement.srces(mediaElem); $.each(srces, function(i, src){ if(src.type == 'usermedia' || (src.type && nativeCanPlay.call(mediaElem[0], src.type)) ){ ret = src; return false; } }); } return ret; }; var emptyType = (/^\s*application\/octet\-stream\s*$/i); var getRemoveEmptyType = function(){ var ret = emptyType.test($.attr(this, 'type') || ''); if(ret){ $(this).removeAttr('type'); } return ret; }; mediaelement.setError = function(elem, message){ if($('source', elem).filter(getRemoveEmptyType).length){ webshims.error('"application/octet-stream" is a useless mimetype for audio/video. Please change this attribute.'); try { $(elem).mediaLoad(); } catch(er){} } else { if(!message){ message = "can't play sources"; } $(elem).pause().data('mediaerror', message); webshims.error('mediaelementError: '+ message +'. Run the following line in your console to get more info: webshim.mediaelement.loadDebugger();'); setTimeout(function(){ if($(elem).data('mediaerror')){ $(elem).addClass('media-error').trigger('mediaerror'); } }, 1); } }; var handleThird = (function(){ var requested; var readyType = hasSwf ? swfType : 'mediaelement-yt'; return function( mediaElem, ret, data ){ //readd to ready webshims.ready(readyType, function(){ if(mediaelement.createSWF && $(mediaElem).parent()[0]){ mediaelement.createSWF( mediaElem, ret, data ); } else if(!requested) { requested = true; loadThird(); handleThird( mediaElem, ret, data ); } }); if(!requested && hasYt && !mediaelement.createSWF){ allowYtLoading = true; loadYt(); } }; })(); var activate = { native: function(elem, src, data){ if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } }, third: handleThird }; var stepSources = function(elem, data, srces){ var i, src; var testOrder = [{test: 'canNativePlaySrces', activate: 'native'}, {test: 'canThirdPlaySrces', activate: 'third'}]; if(options.preferFlash || (data && data.isActive == 'third') ){ testOrder.reverse(); } for(i = 0; i < 2; i++){ src = mediaelement[testOrder[i].test](elem, srces); if(src){ activate[testOrder[i].activate](elem, src, data); break; } } if(!src){ mediaelement.setError(elem, false); if(data && data.isActive == 'third') { mediaelement.setActive(elem, 'html5', data); } } }; var stopParent = /^(?:embed|object|datalist|picture)$/i; var selectSource = function(elem, data){ var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); var _srces = mediaelement.srces(elem); var parent = elem.parentNode; clearTimeout(baseData.loadTimer); $(elem).removeClass('media-error'); $.data(elem, 'mediaerror', false); if(!_srces.length || !parent || parent.nodeType != 1 || stopParent.test(parent.nodeName || '')){return;} data = data || webshims.data(elem, 'mediaelement'); if(mediaelement.sortMedia){ _srces.sort(mediaelement.sortMedia); } stepSources(elem, data, _srces); }; mediaelement.selectSource = selectSource; $(document).on('ended', function(e){ var data = webshims.data(e.target, 'mediaelement'); if( supportsLoop && (!data || data.isActive == 'html5') && !$.prop(e.target, 'loop')){return;} setTimeout(function(){ if( $.prop(e.target, 'paused') || !$.prop(e.target, 'loop') ){return;} $(e.target).prop('currentTime', 0).play(); }); }); var handleMedia = false; var initMediaElements = function(){ var testFixMedia = function(){ if(webshims.implement(this, 'mediaelement')){ selectSource(this); if(!support.mediaDefaultMuted && $.attr(this, 'muted') != null){ $.prop(this, 'muted', true); } } }; webshims.ready('dom-support', function(){ handleMedia = true; if(!supportsLoop){ webshims.defineNodeNamesBooleanProperty(['audio', 'video'], 'loop'); } ['audio', 'video'].forEach(function(nodeName){ var supLoad; supLoad = webshims.defineNodeNameProperty(nodeName, 'load', { prop: { value: function(){ var data = webshims.data(this, 'mediaelement'); selectSource(this, data); if(hasNative && (!data || data.isActive == 'html5') && supLoad.prop._supvalue){ supLoad.prop._supvalue.apply(this, arguments); } if(!loadTrackUi.loaded && this.querySelector('track')){ loadTrackUi(); } $(this).triggerHandler('wsmediareload'); } } }); nativeCanPlayType[nodeName] = webshims.defineNodeNameProperty(nodeName, 'canPlayType', { prop: { value: function(type){ var ret = ''; if(hasNative && nativeCanPlayType[nodeName].prop._supvalue){ ret = nativeCanPlayType[nodeName].prop._supvalue.call(this, type); if(ret == 'no'){ ret = ''; } } if(!ret && hasSwf){ type = $.trim((type || '').split(';')[0]); if(mediaelement.swfMimeTypes.indexOf(type) != -1){ ret = 'maybe'; } } if(!ret && hasYt && type == 'video/youtube'){ ret = 'maybe'; } return ret; } } }); }); webshims.onNodeNamesPropertyModify(['audio', 'video'], ['src', 'poster'], { set: function(){ var elem = this; var baseData = webshims.data(elem, 'mediaelementBase') || webshims.data(elem, 'mediaelementBase', {}); clearTimeout(baseData.loadTimer); baseData.loadTimer = setTimeout(function(){ selectSource(elem); elem = null; }, 9); } }); webshims.addReady(function(context, insertedElement){ var media = $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(testFixMedia) ; if(!loadTrackUi.loaded && $('track', media).length){ loadTrackUi(); } media = null; }); }); if(hasNative && !handleMedia){ webshims.addReady(function(context, insertedElement){ if(!handleMedia){ $('video, audio', context) .add(insertedElement.filter('video, audio')) .each(function(){ if(!mediaelement.canNativePlaySrces(this)){ allowYtLoading = true; loadThird(); handleMedia = true; return false; } }) ; } }); } }; mediaelement.loadDebugger = function(){ webshims.ready('dom-support', function(){ webshims.loader.loadScript('mediaelement-debug'); }); }; if(({noCombo: 1, media: 1})[webshims.cfg.debug]){ $(document).on('mediaerror', function(e){ mediaelement.loadDebugger(); }); } //set native implementation ready, before swf api is retested if(hasNative){ webshims.isReady('mediaelement-core', true); initMediaElements(); webshims.ready('WINDOWLOAD mediaelement', loadThird); } else { webshims.ready(swfType, initMediaElements); } webshims.ready('track', loadTrackUi); if(document.readyState == 'complete'){ webshims.isReady('WINDOWLOAD', true); } }); })(webshims); ;webshims.register('track', function($, webshims, window, document, undefined){ "use strict"; var mediaelement = webshims.mediaelement; var id = new Date().getTime(); //descriptions are not really shown, but they are inserted into the dom var showTracks = {subtitles: 1, captions: 1, descriptions: 1}; var dummyTrack = $('<track />'); var support = webshims.support; var supportTrackMod = support.ES5 && support.objectAccessor; var createEventTarget = function(obj){ var eventList = {}; obj.addEventListener = function(name, fn){ if(eventList[name]){ webshims.error('always use $.on to the shimed event: '+ name +' already bound fn was: '+ eventList[name] +' your fn was: '+ fn); } eventList[name] = fn; }; obj.removeEventListener = function(name, fn){ if(eventList[name] && eventList[name] != fn){ webshims.error('always use $.on/$.off to the shimed event: '+ name +' already bound fn was: '+ eventList[name] +' your fn was: '+ fn); } if(eventList[name]){ delete eventList[name]; } }; return obj; }; var cueListProto = { getCueById: function(id){ var cue = null; for(var i = 0, len = this.length; i < len; i++){ if(this[i].id === id){ cue = this[i]; break; } } return cue; } }; var numericModes = { 0: 'disabled', 1: 'hidden', 2: 'showing' }; var textTrackProto = { shimActiveCues: null, _shimActiveCues: null, activeCues: null, cues: null, kind: 'subtitles', label: '', language: '', id: '', mode: 'disabled', oncuechange: null, toString: function() { return "[object TextTrack]"; }, addCue: function(cue){ if(!this.cues){ this.cues = mediaelement.createCueList(); } else { var lastCue = this.cues[this.cues.length-1]; if(lastCue && lastCue.startTime > cue.startTime){ webshims.error("cue startTime higher than previous cue's startTime"); return; } } if(cue.startTime >= cue.endTime ){ webshim.error('startTime >= endTime of cue: '+ cue.text); } if(cue.track && cue.track.removeCue){ cue.track.removeCue(cue); } cue.track = this; this.cues.push(cue); }, //ToDo: make it more dynamic removeCue: function(cue){ var cues = this.cues || []; var i = 0; var len = cues.length; if(cue.track != this){ webshims.error("cue not part of track"); return; } for(; i < len; i++){ if(cues[i] === cue){ cues.splice(i, 1); cue.track = null; break; } } if(cue.track){ webshims.error("cue not part of track"); return; } }/*, DISABLED: 'disabled', OFF: 'disabled', HIDDEN: 'hidden', SHOWING: 'showing', ERROR: 3, LOADED: 2, LOADING: 1, NONE: 0*/ }; var copyProps = ['kind', 'label', 'srclang']; var copyName = {srclang: 'language'}; var updateMediaTrackList = function(baseData, trackList){ var removed = []; var added = []; var newTracks = []; var i, len; if(!baseData){ baseData = webshims.data(this, 'mediaelementBase') || webshims.data(this, 'mediaelementBase', {}); } if(!trackList){ baseData.blockTrackListUpdate = true; trackList = $.prop(this, 'textTracks'); baseData.blockTrackListUpdate = false; } clearTimeout(baseData.updateTrackListTimer); $('track', this).each(function(){ var track = $.prop(this, 'track'); newTracks.push(track); if(trackList.indexOf(track) == -1){ added.push(track); } }); if(baseData.scriptedTextTracks){ for(i = 0, len = baseData.scriptedTextTracks.length; i < len; i++){ newTracks.push(baseData.scriptedTextTracks[i]); if(trackList.indexOf(baseData.scriptedTextTracks[i]) == -1){ added.push(baseData.scriptedTextTracks[i]); } } } for(i = 0, len = trackList.length; i < len; i++){ if(newTracks.indexOf(trackList[i]) == -1){ removed.push(trackList[i]); } } if(removed.length || added.length){ trackList.splice(0); for(i = 0, len = newTracks.length; i < len; i++){ trackList.push(newTracks[i]); } for(i = 0, len = removed.length; i < len; i++){ $([trackList]).triggerHandler($.Event({type: 'removetrack', track: removed[i]})); } for(i = 0, len = added.length; i < len; i++){ $([trackList]).triggerHandler($.Event({type: 'addtrack', track: added[i]})); } //todo: remove if(baseData.scriptedTextTracks || removed.length){ $(this).triggerHandler('updatetrackdisplay'); } } }; var refreshTrack = function(track, trackData){ if(!trackData){ trackData = webshims.data(track, 'trackData'); } if(trackData && !trackData.isTriggering){ trackData.isTriggering = true; setTimeout(function(){ $(track).closest('audio, video').triggerHandler('updatetrackdisplay'); trackData.isTriggering = false; }, 9); } }; var isDefaultTrack = (function(){ var defaultKinds = { subtitles: { subtitles: 1, captions: 1 }, descriptions: {descriptions: 1}, chapters: {chapters: 1} }; defaultKinds.captions = defaultKinds.subtitles; return function(track){ var kind, firstDefaultTrack; var isDefault = $.prop(track, 'default'); if(isDefault && (kind = $.prop(track, 'kind')) != 'metadata'){ firstDefaultTrack = $(track) .parent() .find('track[default]') .filter(function(){ return !!(defaultKinds[kind][$.prop(this, 'kind')]); })[0] ; if(firstDefaultTrack != track){ isDefault = false; webshims.error('more than one default track of a specific kind detected. Fall back to default = false'); } } return isDefault; }; })(); var emptyDiv = $('<div />')[0]; function VTTCue(startTime, endTime, text){ if(arguments.length != 3){ webshims.error("wrong arguments.length for VTTCue.constructor"); } this.startTime = startTime; this.endTime = endTime; this.text = text; this.onenter = null; this.onexit = null; this.pauseOnExit = false; this.track = null; this.id = null; this.getCueAsHTML = (function(){ var lastText = ""; var parsedText = ""; var fragment; return function(){ var i, len; if(!fragment){ fragment = document.createDocumentFragment(); } if(lastText != this.text){ lastText = this.text; parsedText = mediaelement.parseCueTextToHTML(lastText); emptyDiv.innerHTML = parsedText; for(i = 0, len = emptyDiv.childNodes.length; i < len; i++){ fragment.appendChild(emptyDiv.childNodes[i].cloneNode(true)); } } return fragment.cloneNode(true); }; })(); } window.VTTCue = VTTCue; window.TextTrackCue = function(){ webshims.error("Use VTTCue constructor instead of abstract TextTrackCue constructor."); VTTCue.apply(this, arguments); }; window.TextTrackCue.prototype = VTTCue.prototype; mediaelement.createCueList = function(){ return $.extend([], cueListProto); }; mediaelement.parseCueTextToHTML = (function(){ var tagSplits = /(<\/?[^>]+>)/ig; var allowedTags = /^(?:c|v|ruby|rt|b|i|u)/; var regEnd = /\<\s*\//; var addToTemplate = function(localName, attribute, tag, html){ var ret; if(regEnd.test(html)){ ret = '</'+ localName +'>'; } else { tag.splice(0, 1); ret = '<'+ localName +' '+ attribute +'="'+ (tag.join(' ').replace(/\"/g, '&#34;')) +'">'; } return ret; }; var replacer = function(html){ var tag = html.replace(/[<\/>]+/ig,"").split(/[\s\.]+/); if(tag[0]){ tag[0] = tag[0].toLowerCase(); if(allowedTags.test(tag[0])){ if(tag[0] == 'c'){ html = addToTemplate('span', 'class', tag, html); } else if(tag[0] == 'v'){ html = addToTemplate('q', 'title', tag, html); } } else { html = ""; } } return html; }; return function(cueText){ return cueText.replace(tagSplits, replacer); }; })(); var mapTtmlToVtt = function(i){ var content = i+''; var begin = this.getAttribute('begin') || ''; var end = this.getAttribute('end') || ''; var text = $.trim($.text(this)); if(!/\./.test(begin)){ begin += '.000'; } if(!/\./.test(end)){ end += '.000'; } content += '\n'; content += begin +' --> '+end+'\n'; content += text; return content; }; var ttmlTextToVTT = function(ttml){ ttml = $.parseXML(ttml) || []; return $(ttml).find('[begin][end]').map(mapTtmlToVtt).get().join('\n\n') || ''; }; var loadingTracks = 0; mediaelement.loadTextTrack = function(mediaelem, track, trackData, _default){ var loadEvents = 'play playing loadedmetadata loadstart'; var obj = trackData.track; var load = function(){ var error, ajax, createAjax; var isDisabled = obj.mode == 'disabled'; var videoState = !!($.prop(mediaelem, 'readyState') > 0 || $.prop(mediaelem, 'networkState') == 2 || !$.prop(mediaelem, 'paused')); var src = (!isDisabled || videoState) && ($.attr(track, 'src') && $.prop(track, 'src')); if(src){ $(mediaelem).off(loadEvents, load).off('updatetrackdisplay', load); if(!trackData.readyState){ error = function(){ loadingTracks--; trackData.readyState = 3; obj.cues = null; obj.activeCues = obj.shimActiveCues = obj._shimActiveCues = null; $(track).triggerHandler('error'); }; trackData.readyState = 1; try { obj.cues = mediaelement.createCueList(); obj.activeCues = obj.shimActiveCues = obj._shimActiveCues = mediaelement.createCueList(); loadingTracks++; createAjax = function(){ ajax = $.ajax({ dataType: 'text', url: src, success: function(text){ loadingTracks--; var contentType = ajax.getResponseHeader('content-type') || ''; if(!contentType.indexOf('application/xml')){ text = ttmlTextToVTT(text); } else if(contentType.indexOf('text/vtt')){ webshims.error('set the mime-type of your WebVTT files to text/vtt. see: http://dev.w3.org/html5/webvtt/#text/vtt'); } mediaelement.parseCaptions(text, obj, function(cues){ if(cues && 'length' in cues){ trackData.readyState = 2; $(track).triggerHandler('load'); $(mediaelem).triggerHandler('updatetrackdisplay'); } else { error(); } }); }, error: error }); }; if(isDisabled){ setTimeout(createAjax, loadingTracks * 2); } else { createAjax(); } } catch(er){ error(); webshims.error(er); } } } }; trackData.readyState = 0; obj.shimActiveCues = null; obj._shimActiveCues = null; obj.activeCues = null; obj.cues = null; $(mediaelem).on(loadEvents, load); if(_default){ obj.mode = showTracks[obj.kind] ? 'showing' : 'hidden'; load(); } else { $(mediaelem).on('updatetrackdisplay', load); } }; mediaelement.createTextTrack = function(mediaelem, track){ var obj, trackData; if(track.nodeName){ trackData = webshims.data(track, 'trackData'); if(trackData){ refreshTrack(track, trackData); obj = trackData.track; } } if(!obj){ obj = createEventTarget(webshims.objectCreate(textTrackProto)); if(!supportTrackMod){ copyProps.forEach(function(copyProp){ var prop = $.prop(track, copyProp); if(prop){ obj[copyName[copyProp] || copyProp] = prop; } }); } if(track.nodeName){ if(supportTrackMod){ copyProps.forEach(function(copyProp){ webshims.defineProperty(obj, copyName[copyProp] || copyProp, { get: function(){ return $.prop(track, copyProp); } }); }); } obj.id = $(track).prop('id'); trackData = webshims.data(track, 'trackData', {track: obj}); mediaelement.loadTextTrack(mediaelem, track, trackData, isDefaultTrack(track)); } else { if(supportTrackMod){ copyProps.forEach(function(copyProp){ webshims.defineProperty(obj, copyName[copyProp] || copyProp, { value: track[copyProp], writeable: false }); }); } obj.cues = mediaelement.createCueList(); obj.activeCues = obj._shimActiveCues = obj.shimActiveCues = mediaelement.createCueList(); obj.mode = 'hidden'; obj.readyState = 2; } if(obj.kind == 'subtitles' && !obj.language){ webshims.error('you must provide a language for track in subtitles state'); } obj.__wsmode = obj.mode; webshims.defineProperty(obj, '_wsUpdateMode', { value: function(){ $(mediaelem).triggerHandler('updatetrackdisplay'); }, enumerable: false }); } return obj; }; if(!$.propHooks.mode){ $.propHooks.mode = { set: function(obj, value){ obj.mode = value; if(obj._wsUpdateMode && obj._wsUpdateMode.call){ obj._wsUpdateMode(); } return obj.mode; } }; } /* taken from: Captionator 0.5.1 [CaptionCrunch] Christopher Giffard, 2011 Share and enjoy https://github.com/cgiffard/Captionator modified for webshims */ mediaelement.parseCaptionChunk = (function(){ // Set up timestamp parsers var WebVTTTimestampParser = /^(\d{2})?:?(\d{2}):(\d{2})\.(\d+)\s+\-\-\>\s+(\d{2})?:?(\d{2}):(\d{2})\.(\d+)\s*(.*)/; var WebVTTDEFAULTSCueParser = /^(DEFAULTS|DEFAULT)\s+\-\-\>\s+(.*)/g; var WebVTTSTYLECueParser = /^(STYLE|STYLES)\s+\-\-\>\s*\n([\s\S]*)/g; var WebVTTCOMMENTCueParser = /^(COMMENT|COMMENTS)\s+\-\-\>\s+(.*)/g; var SRTTimestampParser = /^(\d{2})?:?(\d{2}):(\d{2})[\.\,](\d+)\s+\-\-\>\s+(\d{2})?:?(\d{2}):(\d{2})[\.\,](\d+)\s*(.*)/; return function(subtitleElement,objectCount){ var subtitleParts, timeIn, timeOut, html, timeData, subtitlePartIndex, id; var timestampMatch, tmpCue; // WebVTT Special Cue Logic if (WebVTTDEFAULTSCueParser.exec(subtitleElement) || WebVTTCOMMENTCueParser.exec(subtitleElement) || WebVTTSTYLECueParser.exec(subtitleElement)) { return null; } subtitleParts = subtitleElement.split(/\n/g); // Trim off any blank lines (logically, should only be max. one, but loop to be sure) while (!subtitleParts[0].replace(/\s+/ig,"").length && subtitleParts.length > 0) { subtitleParts.shift(); } if (subtitleParts[0].match(/^\s*[a-z0-9-\_]+\s*$/ig)) { // The identifier becomes the cue ID (when *we* load the cues from file. Programatically created cues can have an ID of whatever.) id = String(subtitleParts.shift().replace(/\s*/ig,"")); } for (subtitlePartIndex = 0; subtitlePartIndex < subtitleParts.length; subtitlePartIndex ++) { var timestamp = subtitleParts[subtitlePartIndex]; if ((timestampMatch = WebVTTTimestampParser.exec(timestamp)) || (timestampMatch = SRTTimestampParser.exec(timestamp))) { // WebVTT timeData = timestampMatch.slice(1); timeIn = parseInt((timeData[0]||0) * 60 * 60,10) + // Hours parseInt((timeData[1]||0) * 60,10) + // Minutes parseInt((timeData[2]||0),10) + // Seconds parseFloat("0." + (timeData[3]||0)); // MS timeOut = parseInt((timeData[4]||0) * 60 * 60,10) + // Hours parseInt((timeData[5]||0) * 60,10) + // Minutes parseInt((timeData[6]||0),10) + // Seconds parseFloat("0." + (timeData[7]||0)); // MS /* if (timeData[8]) { cueSettings = timeData[8]; } */ } // We've got the timestamp - return all the other unmatched lines as the raw subtitle data subtitleParts = subtitleParts.slice(0,subtitlePartIndex).concat(subtitleParts.slice(subtitlePartIndex+1)); break; } if (!timeIn && !timeOut) { // We didn't extract any time information. Assume the cue is invalid! webshims.warn("couldn't extract time information: "+[timeIn, timeOut, subtitleParts.join("\n"), id].join(' ; ')); return null; } /* // Consolidate cue settings, convert defaults to object var compositeCueSettings = cueDefaults .reduce(function(previous,current,index,array){ previous[current.split(":")[0]] = current.split(":")[1]; return previous; },{}); // Loop through cue settings, replace defaults with cue specific settings if they exist compositeCueSettings = cueSettings .split(/\s+/g) .filter(function(set) { return set && !!set.length; }) // Convert array to a key/val object .reduce(function(previous,current,index,array){ previous[current.split(":")[0]] = current.split(":")[1]; return previous; },compositeCueSettings); // Turn back into string like the VTTCue constructor expects cueSettings = ""; for (var key in compositeCueSettings) { if (compositeCueSettings.hasOwnProperty(key)) { cueSettings += !!cueSettings.length ? " " : ""; cueSettings += key + ":" + compositeCueSettings[key]; } } */ // The remaining lines are the subtitle payload itself (after removing an ID if present, and the time); html = subtitleParts.join("\n"); tmpCue = new VTTCue(timeIn, timeOut, html); if(id){ tmpCue.id = id; } return tmpCue; }; })(); mediaelement.parseCaptions = function(captionData, track, complete) { var cue, lazyProcess, regWevVTT, startDate, isWEBVTT; mediaelement.createCueList(); if (captionData) { regWevVTT = /^WEBVTT(\s*FILE)?/ig; lazyProcess = function(i, len){ for(; i < len; i++){ cue = captionData[i]; if(regWevVTT.test(cue)){ isWEBVTT = true; } else if(cue.replace(/\s*/ig,"").length){ cue = mediaelement.parseCaptionChunk(cue, i); if(cue){ track.addCue(cue); } } if(startDate < (new Date().getTime()) - 30){ i++; setTimeout(function(){ startDate = new Date().getTime(); lazyProcess(i, len); }, 90); break; } } if(i >= len){ if(!isWEBVTT){ webshims.error('please use WebVTT format. This is the standard'); } complete(track.cues); } }; captionData = captionData.replace(/\r\n/g,"\n"); setTimeout(function(){ captionData = captionData.replace(/\r/g,"\n"); setTimeout(function(){ startDate = new Date().getTime(); captionData = captionData.split(/\n\n+/g); lazyProcess(0, captionData.length); }, 9); }, 9); } else { webshims.error("Required parameter captionData not supplied."); } }; mediaelement.createTrackList = function(mediaelem, baseData){ baseData = baseData || webshims.data(mediaelem, 'mediaelementBase') || webshims.data(mediaelem, 'mediaelementBase', {}); if(!baseData.textTracks){ baseData.textTracks = []; webshims.defineProperties(baseData.textTracks, { onaddtrack: {value: null}, onremovetrack: {value: null}, onchange: {value: null}, getTrackById: { value: function(id){ var track = null; for(var i = 0; i < baseData.textTracks.length; i++){ if(id == baseData.textTracks[i].id){ track = baseData.textTracks[i]; break; } } return track; } } }); createEventTarget(baseData.textTracks); $(mediaelem).on('updatetrackdisplay', function(){ var track; for(var i = 0; i < baseData.textTracks.length; i++){ track = baseData.textTracks[i]; if(track.__wsmode != track.mode){ track.__wsmode = track.mode; $([ baseData.textTracks ]).triggerHandler('change'); } } }); } return baseData.textTracks; }; if(!support.track){ webshims.defineNodeNamesBooleanProperty(['track'], 'default'); webshims.reflectProperties(['track'], ['srclang', 'label']); webshims.defineNodeNameProperties('track', { src: { //attr: {}, reflect: true, propType: 'src' } }); } webshims.defineNodeNameProperties('track', { kind: { attr: support.track ? { set: function(value){ var trackData = webshims.data(this, 'trackData'); this.setAttribute('data-kind', value); if(trackData){ trackData.attrKind = value; } }, get: function(){ var trackData = webshims.data(this, 'trackData'); if(trackData && ('attrKind' in trackData)){ return trackData.attrKind; } return this.getAttribute('kind'); } } : {}, reflect: true, propType: 'enumarated', defaultValue: 'subtitles', limitedTo: ['subtitles', 'captions', 'descriptions', 'chapters', 'metadata'] } }); $.each(copyProps, function(i, copyProp){ var name = copyName[copyProp] || copyProp; webshims.onNodeNamesPropertyModify('track', copyProp, function(){ var trackData = webshims.data(this, 'trackData'); if(trackData){ if(copyProp == 'kind'){ refreshTrack(this, trackData); } if(!supportTrackMod){ trackData.track[name] = $.prop(this, copyProp); } } }); }); webshims.onNodeNamesPropertyModify('track', 'src', function(val){ if(val){ var data = webshims.data(this, 'trackData'); var media; if(data){ media = $(this).closest('video, audio'); if(media[0]){ mediaelement.loadTextTrack(media, this, data); } } } }); // webshims.defineNodeNamesProperties(['track'], { ERROR: { value: 3 }, LOADED: { value: 2 }, LOADING: { value: 1 }, NONE: { value: 0 }, readyState: { get: function(){ return (webshims.data(this, 'trackData') || {readyState: 0}).readyState; }, writeable: false }, track: { get: function(){ return mediaelement.createTextTrack($(this).closest('audio, video')[0], this); }, writeable: false } }, 'prop'); webshims.defineNodeNamesProperties(['audio', 'video'], { textTracks: { get: function(){ var media = this; var baseData = webshims.data(media, 'mediaelementBase') || webshims.data(media, 'mediaelementBase', {}); var tracks = mediaelement.createTrackList(media, baseData); if(!baseData.blockTrackListUpdate){ updateMediaTrackList.call(media, baseData, tracks); } return tracks; }, writeable: false }, addTextTrack: { value: function(kind, label, lang){ var textTrack = mediaelement.createTextTrack(this, { kind: dummyTrack.prop('kind', kind || '').prop('kind'), label: label || '', srclang: lang || '' }); var baseData = webshims.data(this, 'mediaelementBase') || webshims.data(this, 'mediaelementBase', {}); if (!baseData.scriptedTextTracks) { baseData.scriptedTextTracks = []; } baseData.scriptedTextTracks.push(textTrack); updateMediaTrackList.call(this); return textTrack; } } }, 'prop'); //wsmediareload var thUpdateList = function(e){ if($(e.target).is('audio, video')){ var baseData = webshims.data(e.target, 'mediaelementBase'); if(baseData){ clearTimeout(baseData.updateTrackListTimer); baseData.updateTrackListTimer = setTimeout(function(){ updateMediaTrackList.call(e.target, baseData); }, 0); } } }; var getNativeReadyState = function(trackElem, textTrack){ return textTrack.readyState || trackElem.readyState; }; var stopOriginalEvent = function(e){ if(e.originalEvent){ e.stopImmediatePropagation(); } }; var hideNativeTracks = function(){ if(webshims.implement(this, 'track')){ var kind; var origTrack = this.track; if(origTrack){ if (!webshims.bugs.track && (origTrack.mode || getNativeReadyState(this, origTrack))) { $.prop(this, 'track').mode = numericModes[origTrack.mode] || origTrack.mode; } //disable track from showing + remove UI kind = $.prop(this, 'kind'); origTrack.mode = (typeof origTrack.mode == 'string') ? 'disabled' : 0; this.kind = 'metadata'; $(this).attr({kind: kind}); } $(this).on('load error', stopOriginalEvent); } }; webshims.addReady(function(context, insertedElement){ var insertedMedia = insertedElement.filter('video, audio, track').closest('audio, video'); $('video, audio', context) .add(insertedMedia) .each(function(){ updateMediaTrackList.call(this); }) .on('emptied updatetracklist wsmediareload', thUpdateList) .each(function(){ if(support.track){ var shimedTextTracks = $.prop(this, 'textTracks'); var origTextTracks = this.textTracks; if(shimedTextTracks.length != origTextTracks.length){ webshims.warn("textTracks couldn't be copied"); } $('track', this).each(hideNativeTracks); } }) ; insertedMedia.each(function(){ var media = this; var baseData = webshims.data(media, 'mediaelementBase'); if(baseData){ clearTimeout(baseData.updateTrackListTimer); baseData.updateTrackListTimer = setTimeout(function(){ updateMediaTrackList.call(media, baseData); }, 9); } }); }); if(support.texttrackapi){ $('video, audio').trigger('trackapichange'); } });
define(['exports', './utils', './exception'], function (exports, _utils, _exception) { 'use strict'; var _interopRequire = function (obj) { return obj && obj.__esModule ? obj['default'] : obj; }; exports.__esModule = true; exports.HandlebarsEnvironment = HandlebarsEnvironment; exports.createFrame = createFrame; var _Exception = _interopRequire(_exception); var VERSION = '3.0.1'; exports.VERSION = VERSION; var COMPILER_REVISION = 6; exports.COMPILER_REVISION = COMPILER_REVISION; var REVISION_CHANGES = { 1: '<= 1.0.rc.2', // 1.0.rc.2 is actually rev2 but doesn't report it 2: '== 1.0.0-rc.3', 3: '== 1.0.0-rc.4', 4: '== 1.x.x', 5: '== 2.0.0-alpha.x', 6: '>= 2.0.0-beta.1' }; exports.REVISION_CHANGES = REVISION_CHANGES; var isArray = _utils.isArray, isFunction = _utils.isFunction, toString = _utils.toString, objectType = '[object Object]'; function HandlebarsEnvironment(helpers, partials) { this.helpers = helpers || {}; this.partials = partials || {}; registerDefaultHelpers(this); } HandlebarsEnvironment.prototype = { constructor: HandlebarsEnvironment, logger: logger, log: log, registerHelper: function registerHelper(name, fn) { if (toString.call(name) === objectType) { if (fn) { throw new _Exception('Arg not supported with multiple helpers'); } _utils.extend(this.helpers, name); } else { this.helpers[name] = fn; } }, unregisterHelper: function unregisterHelper(name) { delete this.helpers[name]; }, registerPartial: function registerPartial(name, partial) { if (toString.call(name) === objectType) { _utils.extend(this.partials, name); } else { if (typeof partial === 'undefined') { throw new _Exception('Attempting to register a partial as undefined'); } this.partials[name] = partial; } }, unregisterPartial: function unregisterPartial(name) { delete this.partials[name]; } }; function registerDefaultHelpers(instance) { instance.registerHelper('helperMissing', function () { if (arguments.length === 1) { // A missing field in a {{foo}} constuct. return undefined; } else { // Someone is actually trying to call something, blow up. throw new _Exception('Missing helper: "' + arguments[arguments.length - 1].name + '"'); } }); instance.registerHelper('blockHelperMissing', function (context, options) { var inverse = options.inverse, fn = options.fn; if (context === true) { return fn(this); } else if (context === false || context == null) { return inverse(this); } else if (isArray(context)) { if (context.length > 0) { if (options.ids) { options.ids = [options.name]; } return instance.helpers.each(context, options); } else { return inverse(this); } } else { if (options.data && options.ids) { var data = createFrame(options.data); data.contextPath = _utils.appendContextPath(options.data.contextPath, options.name); options = { data: data }; } return fn(context, options); } }); instance.registerHelper('each', function (context, options) { if (!options) { throw new _Exception('Must pass iterator to #each'); } var fn = options.fn, inverse = options.inverse, i = 0, ret = '', data = undefined, contextPath = undefined; if (options.data && options.ids) { contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]) + '.'; } if (isFunction(context)) { context = context.call(this); } if (options.data) { data = createFrame(options.data); } function execIteration(field, index, last) { if (data) { data.key = field; data.index = index; data.first = index === 0; data.last = !!last; if (contextPath) { data.contextPath = contextPath + field; } } ret = ret + fn(context[field], { data: data, blockParams: _utils.blockParams([context[field], field], [contextPath + field, null]) }); } if (context && typeof context === 'object') { if (isArray(context)) { for (var j = context.length; i < j; i++) { execIteration(i, i, i === context.length - 1); } } else { var priorKey = undefined; for (var key in context) { if (context.hasOwnProperty(key)) { // We're running the iterations one step out of sync so we can detect // the last iteration without have to scan the object twice and create // an itermediate keys array. if (priorKey) { execIteration(priorKey, i - 1); } priorKey = key; i++; } } if (priorKey) { execIteration(priorKey, i - 1, true); } } } if (i === 0) { ret = inverse(this); } return ret; }); instance.registerHelper('if', function (conditional, options) { if (isFunction(conditional)) { conditional = conditional.call(this); } // Default behavior is to render the positive path if the value is truthy and not empty. // The `includeZero` option may be set to treat the condtional as purely not empty based on the // behavior of isEmpty. Effectively this determines if 0 is handled by the positive path or negative. if (!options.hash.includeZero && !conditional || _utils.isEmpty(conditional)) { return options.inverse(this); } else { return options.fn(this); } }); instance.registerHelper('unless', function (conditional, options) { return instance.helpers['if'].call(this, conditional, { fn: options.inverse, inverse: options.fn, hash: options.hash }); }); instance.registerHelper('with', function (context, options) { if (isFunction(context)) { context = context.call(this); } var fn = options.fn; if (!_utils.isEmpty(context)) { if (options.data && options.ids) { var data = createFrame(options.data); data.contextPath = _utils.appendContextPath(options.data.contextPath, options.ids[0]); options = { data: data }; } return fn(context, options); } else { return options.inverse(this); } }); instance.registerHelper('log', function (message, options) { var level = options.data && options.data.level != null ? parseInt(options.data.level, 10) : 1; instance.log(level, message); }); instance.registerHelper('lookup', function (obj, field) { return obj && obj[field]; }); } var logger = { methodMap: { 0: 'debug', 1: 'info', 2: 'warn', 3: 'error' }, // State enum DEBUG: 0, INFO: 1, WARN: 2, ERROR: 3, level: 1, // Can be overridden in the host environment log: function log(level, message) { if (typeof console !== 'undefined' && logger.level <= level) { var method = logger.methodMap[level]; (console[method] || console.log).call(console, message); // eslint-disable-line no-console } } }; exports.logger = logger; var log = logger.log; exports.log = log; function createFrame(object) { var frame = _utils.extend({}, object); frame._parent = object; return frame; } }); /* [args, ]options */
this is file 391
var moment = require("../../moment"); /************************************************** Portuguese - Brazilian *************************************************/ exports["lang:pt-br"] = { setUp : function (cb) { moment.lang('pt-br'); cb(); }, tearDown : function (cb) { moment.lang('en'); cb(); }, "parse" : function(test) { test.expect(96); var tests = 'Janeiro Jan_Fevereiro Fev_Março Mar_Abril Abr_Maio Mai_Junho Jun_Julho Jul_Agosto Ago_Setembro Set_Outubro Out_Novembro Nov_Dezembro Dez'.split("_"); var i; function equalTest(input, mmm, i) { test.equal(moment(input, mmm).month(), i, input + ' should be month ' + (i + 1)); } for (i = 0; i < 12; i++) { tests[i] = tests[i].split(' '); equalTest(tests[i][0], 'MMM', i); equalTest(tests[i][1], 'MMM', i); equalTest(tests[i][0], 'MMMM', i); equalTest(tests[i][1], 'MMMM', i); equalTest(tests[i][0].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleLowerCase(), 'MMMM', i); equalTest(tests[i][0].toLocaleUpperCase(), 'MMMM', i); equalTest(tests[i][1].toLocaleUpperCase(), 'MMMM', i); } test.done(); }, "format" : function(test) { test.expect(22); var a = [ ['dddd, MMMM Do YYYY, h:mm:ss a', 'Domingo, Fevereiro 14º 2010, 3:25:50 pm'], ['ddd, hA', 'Dom, 3PM'], ['M Mo MM MMMM MMM', '2 2º 02 Fevereiro Fev'], ['YYYY YY', '2010 10'], ['D Do DD', '14 14º 14'], ['d do dddd ddd', '0 0º Domingo Dom'], ['DDD DDDo DDDD', '45 45º 045'], ['w wo ww', '8 8º 08'], ['h hh', '3 03'], ['H HH', '15 15'], ['m mm', '25 25'], ['s ss', '50 50'], ['a A', 'pm PM'], ['[the] DDDo [day of the year]', 'the 45º day of the year'], ['L', '14/02/2010'], ['LL', '14 de Fevereiro de 2010'], ['LLL', '14 de Fevereiro de 2010 15:25'], ['LLLL', 'Domingo, 14 de Fevereiro de 2010 15:25'], ['l', '14/2/2010'], ['ll', '14 de Fev de 2010'], ['lll', '14 de Fev de 2010 15:25'], ['llll', 'Dom, 14 de Fev de 2010 15:25'] ], b = moment(new Date(2010, 1, 14, 15, 25, 50, 125)), i; for (i = 0; i < a.length; i++) { test.equal(b.format(a[i][0]), a[i][1], a[i][0] + ' ---> ' + a[i][1]); } test.done(); }, "format ordinal" : function(test) { test.expect(31); test.equal(moment([2011, 0, 1]).format('DDDo'), '1º', '1º'); test.equal(moment([2011, 0, 2]).format('DDDo'), '2º', '2º'); test.equal(moment([2011, 0, 3]).format('DDDo'), '3º', '3º'); test.equal(moment([2011, 0, 4]).format('DDDo'), '4º', '4º'); test.equal(moment([2011, 0, 5]).format('DDDo'), '5º', '5º'); test.equal(moment([2011, 0, 6]).format('DDDo'), '6º', '6º'); test.equal(moment([2011, 0, 7]).format('DDDo'), '7º', '7º'); test.equal(moment([2011, 0, 8]).format('DDDo'), '8º', '8º'); test.equal(moment([2011, 0, 9]).format('DDDo'), '9º', '9º'); test.equal(moment([2011, 0, 10]).format('DDDo'), '10º', '10º'); test.equal(moment([2011, 0, 11]).format('DDDo'), '11º', '11º'); test.equal(moment([2011, 0, 12]).format('DDDo'), '12º', '12º'); test.equal(moment([2011, 0, 13]).format('DDDo'), '13º', '13º'); test.equal(moment([2011, 0, 14]).format('DDDo'), '14º', '14º'); test.equal(moment([2011, 0, 15]).format('DDDo'), '15º', '15º'); test.equal(moment([2011, 0, 16]).format('DDDo'), '16º', '16º'); test.equal(moment([2011, 0, 17]).format('DDDo'), '17º', '17º'); test.equal(moment([2011, 0, 18]).format('DDDo'), '18º', '18º'); test.equal(moment([2011, 0, 19]).format('DDDo'), '19º', '19º'); test.equal(moment([2011, 0, 20]).format('DDDo'), '20º', '20º'); test.equal(moment([2011, 0, 21]).format('DDDo'), '21º', '21º'); test.equal(moment([2011, 0, 22]).format('DDDo'), '22º', '22º'); test.equal(moment([2011, 0, 23]).format('DDDo'), '23º', '23º'); test.equal(moment([2011, 0, 24]).format('DDDo'), '24º', '24º'); test.equal(moment([2011, 0, 25]).format('DDDo'), '25º', '25º'); test.equal(moment([2011, 0, 26]).format('DDDo'), '26º', '26º'); test.equal(moment([2011, 0, 27]).format('DDDo'), '27º', '27º'); test.equal(moment([2011, 0, 28]).format('DDDo'), '28º', '28º'); test.equal(moment([2011, 0, 29]).format('DDDo'), '29º', '29º'); test.equal(moment([2011, 0, 30]).format('DDDo'), '30º', '30º'); test.equal(moment([2011, 0, 31]).format('DDDo'), '31º', '31º'); test.done(); }, "format month" : function(test) { test.expect(12); var expected = 'Janeiro Jan_Fevereiro Fev_Março Mar_Abril Abr_Maio Mai_Junho Jun_Julho Jul_Agosto Ago_Setembro Set_Outubro Out_Novembro Nov_Dezembro Dez'.split("_"); var i; for (i = 0; i < expected.length; i++) { test.equal(moment([2011, i, 1]).format('MMMM MMM'), expected[i], expected[i]); } test.done(); }, "format week" : function(test) { test.expect(7); var expected = 'Domingo Dom_Segunda-feira Seg_Terça-feira Ter_Quarta-feira Qua_Quinta-feira Qui_Sexta-feira Sex_Sábado Sáb'.split("_"); var i; for (i = 0; i < expected.length; i++) { test.equal(moment([2011, 0, 2 + i]).format('dddd ddd'), expected[i], expected[i]); } test.done(); }, "from" : function(test) { test.expect(30); var start = moment([2007, 1, 28]); test.equal(start.from(moment([2007, 1, 28]).add({s:44}), true), "segundos", "44 seconds = seconds"); test.equal(start.from(moment([2007, 1, 28]).add({s:45}), true), "um minuto", "45 seconds = a minute"); test.equal(start.from(moment([2007, 1, 28]).add({s:89}), true), "um minuto", "89 seconds = a minute"); test.equal(start.from(moment([2007, 1, 28]).add({s:90}), true), "2 minutos", "90 seconds = 2 minutes"); test.equal(start.from(moment([2007, 1, 28]).add({m:44}), true), "44 minutos", "44 minutes = 44 minutes"); test.equal(start.from(moment([2007, 1, 28]).add({m:45}), true), "uma hora", "45 minutes = an hour"); test.equal(start.from(moment([2007, 1, 28]).add({m:89}), true), "uma hora", "89 minutes = an hour"); test.equal(start.from(moment([2007, 1, 28]).add({m:90}), true), "2 horas", "90 minutes = 2 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h:5}), true), "5 horas", "5 hours = 5 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h:21}), true), "21 horas", "21 hours = 21 hours"); test.equal(start.from(moment([2007, 1, 28]).add({h:22}), true), "um dia", "22 hours = a day"); test.equal(start.from(moment([2007, 1, 28]).add({h:35}), true), "um dia", "35 hours = a day"); test.equal(start.from(moment([2007, 1, 28]).add({h:36}), true), "2 dias", "36 hours = 2 days"); test.equal(start.from(moment([2007, 1, 28]).add({d:1}), true), "um dia", "1 day = a day"); test.equal(start.from(moment([2007, 1, 28]).add({d:5}), true), "5 dias", "5 days = 5 days"); test.equal(start.from(moment([2007, 1, 28]).add({d:25}), true), "25 dias", "25 days = 25 days"); test.equal(start.from(moment([2007, 1, 28]).add({d:26}), true), "um mês", "26 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d:30}), true), "um mês", "30 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d:45}), true), "um mês", "45 days = a month"); test.equal(start.from(moment([2007, 1, 28]).add({d:46}), true), "2 meses", "46 days = 2 months"); test.equal(start.from(moment([2007, 1, 28]).add({d:74}), true), "2 meses", "75 days = 2 months"); test.equal(start.from(moment([2007, 1, 28]).add({d:76}), true), "3 meses", "76 days = 3 months"); test.equal(start.from(moment([2007, 1, 28]).add({M:1}), true), "um mês", "1 month = a month"); test.equal(start.from(moment([2007, 1, 28]).add({M:5}), true), "5 meses", "5 months = 5 months"); test.equal(start.from(moment([2007, 1, 28]).add({d:344}), true), "11 meses", "344 days = 11 months"); test.equal(start.from(moment([2007, 1, 28]).add({d:345}), true), "um ano", "345 days = a year"); test.equal(start.from(moment([2007, 1, 28]).add({d:547}), true), "um ano", "547 days = a year"); test.equal(start.from(moment([2007, 1, 28]).add({d:548}), true), "2 anos", "548 days = 2 years"); test.equal(start.from(moment([2007, 1, 28]).add({y:1}), true), "um ano", "1 year = a year"); test.equal(start.from(moment([2007, 1, 28]).add({y:5}), true), "5 anos", "5 years = 5 years"); test.done(); }, "suffix" : function(test) { test.expect(2); test.equal(moment(30000).from(0), "em segundos", "prefix"); test.equal(moment(0).from(30000), "segundos atrás", "suffix"); test.done(); }, "fromNow" : function(test) { test.expect(2); test.equal(moment().add({s:30}).fromNow(), "em segundos", "in seconds"); test.equal(moment().add({d:5}).fromNow(), "em 5 dias", "in 5 days"); test.done(); }, "calendar day" : function(test) { test.expect(6); var a = moment().hours(2).minutes(0).seconds(0); test.equal(moment(a).calendar(), "Hoje às 02:00", "today at the same time"); test.equal(moment(a).add({ m: 25 }).calendar(), "Hoje às 02:25", "Now plus 25 min"); test.equal(moment(a).add({ h: 1 }).calendar(), "Hoje às 03:00", "Now plus 1 hour"); test.equal(moment(a).add({ d: 1 }).calendar(), "Amanhã às 02:00", "tomorrow at the same time"); test.equal(moment(a).subtract({ h: 1 }).calendar(), "Hoje às 01:00", "Now minus 1 hour"); test.equal(moment(a).subtract({ d: 1 }).calendar(), "Ontem às 02:00", "yesterday at the same time"); test.done(); }, "calendar next week" : function(test) { test.expect(15); var i; var m; for (i = 2; i < 7; i++) { m = moment().add({ d: i }); test.equal(m.calendar(), m.format('dddd [às] LT'), "Today + " + i + " days current time"); m.hours(0).minutes(0).seconds(0).milliseconds(0); test.equal(m.calendar(), m.format('dddd [às] LT'), "Today + " + i + " days beginning of day"); m.hours(23).minutes(59).seconds(59).milliseconds(999); test.equal(m.calendar(), m.format('dddd [às] LT'), "Today + " + i + " days end of day"); } test.done(); }, "calendar last week" : function(test) { test.expect(15); var i; var m; for (i = 2; i < 7; i++) { m = moment().subtract({ d: i }); test.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[Último] dddd [às] LT' : '[Última] dddd [às] LT'), "Today - " + i + " days current time"); m.hours(0).minutes(0).seconds(0).milliseconds(0); test.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[Último] dddd [às] LT' : '[Última] dddd [às] LT'), "Today - " + i + " days beginning of day"); m.hours(23).minutes(59).seconds(59).milliseconds(999); test.equal(m.calendar(), m.format((m.day() === 0 || m.day() === 6) ? '[Último] dddd [às] LT' : '[Última] dddd [às] LT'), "Today - " + i + " days end of day"); } test.done(); }, "calendar all else" : function(test) { test.expect(4); var weeksAgo = moment().subtract({ w: 1 }); var weeksFromNow = moment().add({ w: 1 }); test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "1 week ago"); test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 1 week"); weeksAgo = moment().subtract({ w: 2 }); weeksFromNow = moment().add({ w: 2 }); test.equal(weeksAgo.calendar(), weeksAgo.format('L'), "2 weeks ago"); test.equal(weeksFromNow.calendar(), weeksFromNow.format('L'), "in 2 weeks"); test.done(); }, // Sunday is the first day of the week. // The week that contains Jan 1st is the first week of the year. "weeks year starting sunday" : function(test) { test.expect(5); test.equal(moment([2012, 0, 1]).week(), 1, "Jan 1 2012 should be week 1"); test.equal(moment([2012, 0, 7]).week(), 1, "Jan 7 2012 should be week 1"); test.equal(moment([2012, 0, 8]).week(), 2, "Jan 8 2012 should be week 2"); test.equal(moment([2012, 0, 14]).week(), 2, "Jan 14 2012 should be week 2"); test.equal(moment([2012, 0, 15]).week(), 3, "Jan 15 2012 should be week 3"); test.done(); }, "weeks year starting monday" : function(test) { test.expect(6); test.equal(moment([2006, 11, 31]).week(), 1, "Dec 31 2006 should be week 1"); test.equal(moment([2007, 0, 1]).week(), 1, "Jan 1 2007 should be week 1"); test.equal(moment([2007, 0, 6]).week(), 1, "Jan 6 2007 should be week 1"); test.equal(moment([2007, 0, 7]).week(), 2, "Jan 7 2007 should be week 2"); test.equal(moment([2007, 0, 13]).week(), 2, "Jan 13 2007 should be week 2"); test.equal(moment([2007, 0, 14]).week(), 3, "Jan 14 2007 should be week 3"); test.done(); }, "weeks year starting tuesday" : function(test) { test.expect(6); test.equal(moment([2007, 11, 30]).week(), 1, "Dec 30 2007 should be week 1"); test.equal(moment([2008, 0, 1]).week(), 1, "Jan 1 2008 should be week 1"); test.equal(moment([2008, 0, 5]).week(), 1, "Jan 5 2008 should be week 1"); test.equal(moment([2008, 0, 6]).week(), 2, "Jan 6 2008 should be week 2"); test.equal(moment([2008, 0, 12]).week(), 2, "Jan 12 2008 should be week 2"); test.equal(moment([2008, 0, 13]).week(), 3, "Jan 13 2008 should be week 3"); test.done(); }, "weeks year starting wednesday" : function(test) { test.expect(6); test.equal(moment([2002, 11, 29]).week(), 1, "Dec 29 2002 should be week 1"); test.equal(moment([2003, 0, 1]).week(), 1, "Jan 1 2003 should be week 1"); test.equal(moment([2003, 0, 4]).week(), 1, "Jan 4 2003 should be week 1"); test.equal(moment([2003, 0, 5]).week(), 2, "Jan 5 2003 should be week 2"); test.equal(moment([2003, 0, 11]).week(), 2, "Jan 11 2003 should be week 2"); test.equal(moment([2003, 0, 12]).week(), 3, "Jan 12 2003 should be week 3"); test.done(); }, "weeks year starting thursday" : function(test) { test.expect(6); test.equal(moment([2008, 11, 28]).week(), 1, "Dec 28 2008 should be week 1"); test.equal(moment([2009, 0, 1]).week(), 1, "Jan 1 2009 should be week 1"); test.equal(moment([2009, 0, 3]).week(), 1, "Jan 3 2009 should be week 1"); test.equal(moment([2009, 0, 4]).week(), 2, "Jan 4 2009 should be week 2"); test.equal(moment([2009, 0, 10]).week(), 2, "Jan 10 2009 should be week 2"); test.equal(moment([2009, 0, 11]).week(), 3, "Jan 11 2009 should be week 3"); test.done(); }, "weeks year starting friday" : function(test) { test.expect(6); test.equal(moment([2009, 11, 27]).week(), 1, "Dec 27 2009 should be week 1"); test.equal(moment([2010, 0, 1]).week(), 1, "Jan 1 2010 should be week 1"); test.equal(moment([2010, 0, 2]).week(), 1, "Jan 2 2010 should be week 1"); test.equal(moment([2010, 0, 3]).week(), 2, "Jan 3 2010 should be week 2"); test.equal(moment([2010, 0, 9]).week(), 2, "Jan 9 2010 should be week 2"); test.equal(moment([2010, 0, 10]).week(), 3, "Jan 10 2010 should be week 3"); test.done(); }, "weeks year starting saturday" : function(test) { test.expect(5); test.equal(moment([2010, 11, 26]).week(), 1, "Dec 26 2010 should be week 1"); test.equal(moment([2011, 0, 1]).week(), 1, "Jan 1 2011 should be week 1"); test.equal(moment([2011, 0, 2]).week(), 2, "Jan 2 2011 should be week 2"); test.equal(moment([2011, 0, 8]).week(), 2, "Jan 8 2011 should be week 2"); test.equal(moment([2011, 0, 9]).week(), 3, "Jan 9 2011 should be week 3"); test.done(); }, "weeks year starting sunday format" : function(test) { test.expect(5); test.equal(moment([2012, 0, 1]).format('w ww wo'), '1 01 1º', "Jan 1 2012 should be week 1"); test.equal(moment([2012, 0, 7]).format('w ww wo'), '1 01 1º', "Jan 7 2012 should be week 1"); test.equal(moment([2012, 0, 8]).format('w ww wo'), '2 02 2º', "Jan 8 2012 should be week 2"); test.equal(moment([2012, 0, 14]).format('w ww wo'), '2 02 2º', "Jan 14 2012 should be week 2"); test.equal(moment([2012, 0, 15]).format('w ww wo'), '3 03 3º', "Jan 15 2012 should be week 3"); test.done(); } };
var webpack = require('webpack'); module.exports = { context: __dirname, entry: [ // Add the client which connects to our middleware // You can use full urls like 'webpack-hot-middleware/client?path=http://localhost:3000/__webpack_hmr' // useful if you run your app from another point like django 'webpack-hot-middleware/client?path=/__webpack_hmr&timeout=20000', // And then the actual application './client.js' ], output: { path: __dirname, publicPath: '/', filename: 'bundle.js' }, devtool: '#source-map', plugins: [ new webpack.optimize.OccurenceOrderPlugin(), new webpack.HotModuleReplacementPlugin(), new webpack.NoErrorsPlugin() ], };
Package.describe({ summary: "Moved to the 'mongo' package", version: '1.0.9-plugins.0' }); Package.onUse(function (api) { api.imply("mongo"); });
var path = require( 'path' ); var fs = require( 'graceful-fs' ); var del = require( 'del' ).sync; var utils = require( './utils' ); var writeJSON = utils.writeJSON; var cache = { /** * Load a cache identified by the given Id. If the element does not exists, then initialize an empty * cache storage. If specified `cacheDir` will be used as the directory to persist the data to. If omitted * then the cache module directory `./cache` will be used instead * * @method load * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param [cacheDir] {String} directory for the cache entry */ load: function ( docId, cacheDir ) { var me = this; me._visited = { }; me._persisted = { }; me._pathToFile = cacheDir ? path.resolve( cacheDir, docId ) : path.resolve( __dirname, './.cache/', docId ); if ( fs.existsSync( me._pathToFile ) ) { me._persisted = utils.tryParse( me._pathToFile, { } ); } }, /** * Load the cache from the provided file * @method loadFile * @param {String} pathToFile the path to the file containing the info for the cache */ loadFile: function ( pathToFile ) { var me = this; var dir = path.dirname( pathToFile ); var fName = path.basename( pathToFile ); me.load( fName, dir ); }, /** * Returns the entire persisted object * @method all * @returns {*} */ all: function () { return this._persisted; }, keys: function () { return Object.keys( this._persisted ); }, /** * sets a key to a given value * @method setKey * @param key {string} the key to set * @param value {object} the value of the key. Could be any object that can be serialized with JSON.stringify */ setKey: function ( key, value ) { this._visited[ key ] = true; this._persisted[ key ] = value; }, /** * remove a given key from the cache * @method removeKey * @param key {String} the key to remove from the object */ removeKey: function ( key ) { delete this._visited[ key ]; // esfmt-ignore-line delete this._persisted[ key ]; // esfmt-ignore-line }, /** * Return the value of the provided key * @method getKey * @param key {String} the name of the key to retrieve * @returns {*} the value from the key */ getKey: function ( key ) { this._visited[ key ] = true; return this._persisted[ key ]; }, /** * Remove keys that were not accessed/set since the * last time the `prune` method was called. * @method _prune * @private */ _prune: function () { var me = this; var obj = { }; var keys = Object.keys( me._visited ); // no keys visited for either get or set value if ( keys.length === 0 ) { return; } keys.forEach( function ( key ) { obj[ key ] = me._persisted[ key ]; } ); me._visited = { }; me._persisted = obj; }, /** * Save the state of the cache identified by the docId to disk * as a JSON structure * @param [noPrune=false] {Boolean} whether to remove from cache the non visited files * @method save */ save: function ( noPrune ) { var me = this; (!noPrune) && me._prune(); writeJSON( me._pathToFile, me._persisted ); }, /** * remove the file where the cache is persisted * @method removeCacheFile * @return {Boolean} true or false if the file was successfully deleted */ removeCacheFile: function () { return del( this._pathToFile, { force: true } ); }, /** * Destroy the file cache and cache content. * @method destroy */ destroy: function () { var me = this; me._visited = { }; me._persisted = { }; me.removeCacheFile(); } }; module.exports = { /** * Alias for create. Should be considered depreacted. Will be removed in next releases * * @method load * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param [cacheDir] {String} directory for the cache entry * @returns {cache} cache instance */ load: function ( docId, cacheDir ) { return this.create( docId, cacheDir ); }, /** * Load a cache identified by the given Id. If the element does not exists, then initialize an empty * cache storage. * * @method create * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param [cacheDir] {String} directory for the cache entry * @returns {cache} cache instance */ create: function ( docId, cacheDir ) { var obj = Object.create( cache ); obj.load( docId, cacheDir ); return obj; }, createFromFile: function ( filePath ) { var obj = Object.create( cache ); obj.loadFile( filePath ); return obj; }, /** * Clear the cache identified by the given id. Caches stored in a different cache directory can be deleted directly * * @method clearCache * @param docId {String} the id of the cache, would also be used as the name of the file cache * @param cacheDir {String} the directory where the cache file was written * @returns {Boolean} true if the cache folder was deleted. False otherwise */ clearCacheById: function ( docId, cacheDir ) { var filePath = cacheDir ? path.resolve( cacheDir, docId ) : path.resolve( __dirname, './.cache/', docId ); return del( filePath, { force: true } ).length > 0; }, /** * Remove all cache stored in the cache directory * @method clearAll * @returns {Boolean} true if the cache folder was deleted. False otherwise */ clearAll: function ( cacheDir ) { var filePath = cacheDir ? path.resolve( cacheDir ) : path.resolve( __dirname, './.cache/' ); return del( filePath, { force: true } ).length > 0; } };
(function(factory){if(typeof define==="function"&&define.amd){define("bootstrap.wysihtml5.ja-JP",["jquery","bootstrap.wysihtml5"],factory)}else{factory(jQuery)}})(function($){$.fn.wysihtml5.locale["ja-JP"]={font_styles:{normal:"通常の文字",h1:"見出し1",h2:"見出し2",h3:"見出し3"},emphasis:{bold:"太字",italic:"斜体",underline:"下線"},lists:{unordered:"点字リスト",ordered:"数字リスト",outdent:"左寄せ",indent:"右寄せ"},link:{insert:"リンクの挿入",cancel:"キャンセル"},image:{insert:"画像の挿入",cancel:"キャンセル"},html:{edit:"HTMLを編集"},colours:{black:"黒色",silver:"シルバー",gray:"グレー",maroon:"栗色",red:"赤色",purple:"紫色",green:"緑色",olive:"オリーブ",navy:"ネイビー",blue:"青色",orange:"オレンジ"}}});
$ch.define("layout",function(){"use strict";var a="https://cdn.jsdelivr.net/chopjs-layout/"+$$CHOP.MODULE_VERSION.layout+"/chopjs-layout.css",b=void 0!==$$CHOP.find(".chopjs-layout-css");if(!b){var c=document.createElement("style");c.className+=" chopjs-layout-css",c.innerHTML=$$CHOP.http({url:a,async:!1}).responseText,document.head.appendChild(c)}});
import { add } from '../../_i18n'; import nl from './nl'; import fa from './fa'; import de from './de'; import ru from './ru'; export default function () { add(nl, 'nl'); add(fa, 'fa'); add(de, 'de'); add(ru, 'ru'); }
var progress = require('request-progress'); var request = require('request'); var Q = require('q'); var mout = require('mout'); var retry = require('retry'); var createError = require('./createError'); var createWriteStream = require('fs-write-stream-atomic'); var destroy = require('destroy'); var errorCodes = [ 'EADDRINFO', 'ETIMEDOUT', 'ECONNRESET', 'ESOCKETTIMEDOUT', 'ENOTFOUND' ]; function download(url, file, options) { var operation; var deferred = Q.defer(); var progressDelay = 8000; options = mout.object.mixIn({ retries: 5, factor: 2, minTimeout: 1000, maxTimeout: 35000, randomize: true, progressDelay: progressDelay, gzip: true }, options || {}); // Retry on network errors operation = retry.operation(options); operation.attempt(function () { Q.fcall(fetch, url, file, options) .then(function (response) { deferred.resolve(response); }) .progress(function (status) { deferred.notify(status); }) .fail(function (error) { // Save timeout before retrying to report var timeout = operation._timeouts[0]; // Reject if error is not a network error if (errorCodes.indexOf(error.code) === -1) { return deferred.reject(error); } // Next attempt will start reporting download progress immediately progressDelay = 0; // This will schedule next retry or return false if (operation.retry(error)) { deferred.notify({ retry: true, delay: timeout, error: error }); } else { deferred.reject(error); } }); }); return deferred.promise; } function fetch(url, file, options) { var deferred = Q.defer(); var contentLength; var bytesDownloaded = 0; var reject = function (error) { deferred.reject(error); }; var req = progress(request(url, options), { delay: options.progressDelay }) .on('response', function (response) { contentLength = Number(response.headers['content-length']); var status = response.statusCode; if (status < 200 || status >= 300) { return deferred.reject(createError('Status code of ' + status, 'EHTTP')); } var writeStream = createWriteStream(file); var errored = false; // Change error listener so it cleans up writeStream before exiting req.removeListener('error', reject); req.on('error', function (error) { errored = true; destroy(req); destroy(writeStream); // Wait for writeStream to cleanup after itself... // TODO: Maybe there's a better way? setTimeout(function () { deferred.reject(error); }, 50); }); writeStream.on('finish', function () { if (!errored) { destroy(req); deferred.resolve(response); } }); req.pipe(writeStream); }) .on('data', function (data) { bytesDownloaded += data.length; }) .on('progress', function (state) { deferred.notify(state); }) .on('error', reject) .on('end', function () { // Check if the whole file was downloaded // In some unstable connections the ACK/FIN packet might be sent in the // middle of the download // See: https://github.com/joyent/node/issues/6143 if (contentLength && bytesDownloaded < contentLength) { req.emit('error', createError( 'Transfer closed with ' + (contentLength - bytesDownloaded) + ' bytes remaining to read', 'EINCOMPLETE' )); } }); return deferred.promise; } module.exports = download;
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'contextmenu', 'eo', { options: 'Opcioj de Kunteksta Menuo' });
/*! * Justified Gallery - v3.5.0 * http://miromannino.github.io/Justified-Gallery/ * Copyright (c) 2014 Miro Mannino * Licensed under the MIT license. */ (function($) { /* Events jg.complete : called when all the gallery has been created jg.resize : called when the gallery has been resized */ $.fn.justifiedGallery = function (arg) { // Default options var defaults = { sizeRangeSuffixes : { 'lt100': '', // e.g. Flickr uses '_t' 'lt240': '', // e.g. Flickr uses '_m' 'lt320': '', // e.g. Flickr uses '_n' 'lt500': '', // e.g. Flickr uses '' 'lt640': '', // e.g. Flickr uses '_z' 'lt1024': '', // e.g. Flickr uses '_b' }, rowHeight : 120, maxRowHeight : 0, // negative value = no limits, 0 = 1.5 * rowHeight margins : 1, lastRow : 'nojustify', // or can be 'justify' or 'hide' justifyThreshold: 0.75, /* if row width / available space > 0.75 it will be always justified (i.e. lastRow setting is not considered) */ fixedHeight : false, waitThumbnailsLoad : true, captions : true, cssAnimation: false, imagesAnimationDuration : 500, // ignored with css animations captionSettings : { // ignored with css animations animationDuration : 500, visibleOpacity : 0.7, nonVisibleOpacity : 0.0 }, rel : null, // rewrite the rel of each analyzed links target : null, // rewrite the target of all links extension : /\.[^.\\/]+$/, refreshTime : 100, randomize : false }; function getSuffix(width, height, context) { var longestSide; longestSide = (width > height) ? width : height; if (longestSide <= 100) { return context.settings.sizeRangeSuffixes.lt100; } else if (longestSide <= 240) { return context.settings.sizeRangeSuffixes.lt240; } else if (longestSide <= 320) { return context.settings.sizeRangeSuffixes.lt320; } else if (longestSide <= 500) { return context.settings.sizeRangeSuffixes.lt500; } else if (longestSide <= 640) { return context.settings.sizeRangeSuffixes.lt640; } else { return context.settings.sizeRangeSuffixes.lt1024; } } function endsWith(str, suffix) { return str.indexOf(suffix, str.length - suffix.length) !== -1; } function removeSuffix(str, suffix) { return str.substring(0, str.length - suffix.length); } function getUsedSuffix(str, context) { var voidSuffix = false; for (var si in context.settings.sizeRangeSuffixes) { if (context.settings.sizeRangeSuffixes[si].length === 0) { voidSuffix = true; continue; } if (endsWith(str, context.settings.sizeRangeSuffixes[si])) { return context.settings.sizeRangeSuffixes[si]; } } if (voidSuffix) return ""; else throw 'unknown suffix for ' + str; } /* Given an image src, with the width and the height, returns the new image src with the best suffix to show the best quality thumbnail. */ function newSrc(imageSrc, imgWidth, imgHeight, context) { var matchRes = imageSrc.match(context.settings.extension); var ext = (matchRes != null) ? matchRes[0] : ''; var newImageSrc = imageSrc.replace(context.settings.extension, ''); newImageSrc = removeSuffix(newImageSrc, getUsedSuffix(newImageSrc, context)); newImageSrc += getSuffix(imgWidth, imgHeight, context) + ext; return newImageSrc; } function onEntryMouseEnterForCaption (ev) { var $caption = $(ev.currentTarget).find('.caption'); if (ev.data.settings.cssAnimation) { $caption.addClass('caption-visible').removeClass('caption-hidden'); } else { $caption.stop().fadeTo(ev.data.settings.captionSettings.animationDuration, ev.data.settings.captionSettings.visibleOpacity); } } function onEntryMouseLeaveForCaption (ev) { var $caption = $(ev.currentTarget).find('.caption'); if (ev.data.settings.cssAnimation) { $caption.removeClass('caption-visible').removeClass('caption-hidden'); } else { $caption.stop().fadeTo(ev.data.settings.captionSettings.animationDuration, ev.data.settings.captionSettings.nonVisibleOpacity); } } function showImg($entry, callback, context) { if (context.settings.cssAnimation) { $entry.addClass('entry-visible'); callback(); } else { $entry.stop().fadeTo(context.settings.imagesAnimationDuration, 1.0, callback); } } function hideImgImmediately($entry, context) { if (context.settings.cssAnimation) { $entry.removeClass('entry-visible'); } else { $entry.stop().fadeTo(0, 0); } } function imgFromEntry($entry) { var $img = $entry.find('> img'); if ($img.length === 0) $img = $entry.find('> a > img'); return $img; } function displayEntry($entry, x, y, imgWidth, imgHeight, rowHeight, context) { var $image = imgFromEntry($entry); $image.css('width', imgWidth); $image.css('height', imgHeight); if ($entry.get(0) === $image.parent().get(0)) { $image.css('margin-left', - imgWidth / 2); $image.css('margin-top', - imgHeight / 2); } $entry.width(imgWidth); $entry.height(rowHeight); $entry.css('top', y); $entry.css('left', x); //DEBUG// console.log('displayEntry (w: ' + $image.width() + ' h: ' + $image.height()); // Image reloading for an high quality of thumbnails var imageSrc = $image.attr('src'); var newImageSrc = newSrc(imageSrc, imgWidth, imgHeight, context); $image.one('error', function () { //DEBUG// console.log('revert the original image'); $image.attr('src', $image.data('jg.originalSrc')); //revert to the original thumbnail, we got it. }); function loadNewImage() { if (imageSrc !== newImageSrc) { //load the new image after the fadeIn $image.attr('src', newImageSrc); } } if ($image.data('jg.loaded') === 'skipped') { $image.one('load', function() { showImg($entry, loadNewImage, context); $image.data('jg.loaded', true); }); } else { showImg($entry, loadNewImage, context); } // Captions ------------------------------ var captionMouseEvents = $entry.data('jg.captionMouseEvents'); if (context.settings.captions === true) { var $imgCaption = $entry.find('.caption'); if ($imgCaption.length === 0) { // Create it if it doesn't exists var caption = $image.attr('alt'); if (typeof caption === 'undefined') caption = $entry.attr('title'); if (typeof caption !== 'undefined') { // Create only we found something $imgCaption = $('<div class="caption">' + caption + '</div>'); $entry.append($imgCaption); } } // Create events (we check again the $imgCaption because it can be still inexistent) if ($imgCaption.length !== 0) { if (!context.settings.cssAnimation) { $imgCaption.stop().fadeTo(context.settings.imagesAnimationDuration, context.settings.captionSettings.nonVisibleOpacity); } if (typeof captionMouseEvents === 'undefined') { captionMouseEvents = { mouseenter: onEntryMouseEnterForCaption, mouseleave: onEntryMouseLeaveForCaption }; $entry.on('mouseenter', undefined, context, captionMouseEvents.mouseenter); $entry.on('mouseleave', undefined, context, captionMouseEvents.mouseleave); $entry.data('jg.captionMouseEvents', captionMouseEvents); } } } else { if (typeof captionMouseEvents !== 'undefined') { $entry.off('mouseenter', undefined, context, captionMouseEvents.mouseenter); $entry.off('mouseleave', undefined, context, captionMouseEvents.mouseleave); $entry.removeData('jg.captionMouseEvents'); } } } function prepareBuildingRow(context, isLastRow) { var settings = context.settings; var i, $entry, $image, imgAspectRatio, newImgW, newImgH, justify = true; var minHeight = 0; var availableWidth = context.galleryWidth - ( (context.buildingRow.entriesBuff.length + 1) * settings.margins); var rowHeight = availableWidth / context.buildingRow.aspectRatio; var justificable = context.buildingRow.width / availableWidth > settings.justifyThreshold; //Skip the last row if we can't justify it and the lastRow == 'hide' if (isLastRow && settings.lastRow === 'hide' && !justificable) { for (i = 0; i < context.buildingRow.entriesBuff.length; i++) { $entry = context.buildingRow.entriesBuff[i]; if (settings.cssAnimation) $entry.removeClass('entry-visible'); else $entry.stop().fadeTo(0, 0); } return -1; } // With lastRow = nojustify, justify if is justificable (the images will not become too big) if (isLastRow && !justificable && settings.lastRow === 'nojustify') justify = false; for (i = 0; i < context.buildingRow.entriesBuff.length; i++) { $image = imgFromEntry(context.buildingRow.entriesBuff[i]); imgAspectRatio = $image.data('jg.imgw') / $image.data('jg.imgh'); if (justify) { newImgW = (i === context.buildingRow.entriesBuff.length - 1) ? availableWidth : rowHeight * imgAspectRatio; newImgH = rowHeight; /* With fixedHeight the newImgH must be greater than rowHeight. In some cases here this is not satisfied (due to the justification). But we comment it, because is better to have a shorter but justified row instead to have a cropped image at the end. */ /*if (settings.fixedHeight && newImgH < settings.rowHeight) { newImgW = settings.rowHeight * imgAspectRatio; newImgH = settings.rowHeight; }*/ } else { newImgW = settings.rowHeight * imgAspectRatio; newImgH = settings.rowHeight; } availableWidth -= Math.round(newImgW); $image.data('jg.jimgw', Math.round(newImgW)); $image.data('jg.jimgh', Math.ceil(newImgH)); if (i === 0 || minHeight > newImgH) minHeight = newImgH; } if (settings.fixedHeight && minHeight > settings.rowHeight) minHeight = settings.rowHeight; return {minHeight: minHeight, justify: justify}; } function rewind(context) { context.lastAnalyzedIndex = -1; context.buildingRow.entriesBuff = []; context.buildingRow.aspectRatio = 0; context.buildingRow.width = 0; context.offY = context.settings.margins; } function flushRow(context, isLastRow) { var settings = context.settings; var $entry, $image, minHeight, buildingRowRes, offX = settings.margins; //DEBUG// console.log('flush (isLastRow: ' + isLastRow + ')'); buildingRowRes = prepareBuildingRow(context, isLastRow); minHeight = buildingRowRes.minHeight; if (isLastRow && settings.lastRow === 'hide' && minHeight === -1) { context.buildingRow.entriesBuff = []; context.buildingRow.aspectRatio = 0; context.buildingRow.width = 0; return; } if (settings.maxRowHeight > 0 && settings.maxRowHeight < minHeight) minHeight = settings.maxRowHeight; else if (settings.maxRowHeight === 0 && (1.5 * settings.rowHeight) < minHeight) minHeight = 1.5 * settings.rowHeight; for (var i = 0; i < context.buildingRow.entriesBuff.length; i++) { $entry = context.buildingRow.entriesBuff[i]; $image = imgFromEntry($entry); displayEntry($entry, offX, context.offY, $image.data('jg.jimgw'), $image.data('jg.jimgh'), minHeight, context); offX += $image.data('jg.jimgw') + settings.margins; } //Gallery Height context.$gallery.height(context.offY + minHeight + settings.margins + (context.spinner.active ? context.spinner.$el.innerHeight() : 0) ); if (!isLastRow || (minHeight <= context.settings.rowHeight && buildingRowRes.justify)) { //Ready for a new row context.offY += minHeight + context.settings.margins; //DEBUG// console.log('minHeight: ' + minHeight + ' offY: ' + context.offY); context.buildingRow.entriesBuff = []; //clear the array creating a new one context.buildingRow.aspectRatio = 0; context.buildingRow.width = 0; context.$gallery.trigger('jg.rowflush'); } } function checkWidth(context) { context.checkWidthIntervalId = setInterval(function () { var galleryWidth = parseInt(context.$gallery.width(), 10); if (context.galleryWidth !== galleryWidth) { //DEBUG// console.log("resize. old: " + context.galleryWidth + " new: " + galleryWidth); context.galleryWidth = galleryWidth; rewind(context); // Restart to analyze startImgAnalyzer(context, true); } }, context.settings.refreshTime); } function startLoadingSpinnerAnimation(spinnerContext) { clearInterval(spinnerContext.intervalId); spinnerContext.intervalId = setInterval(function () { if (spinnerContext.phase < spinnerContext.$points.length) spinnerContext.$points.eq(spinnerContext.phase).fadeTo(spinnerContext.timeslot, 1); else spinnerContext.$points.eq(spinnerContext.phase - spinnerContext.$points.length) .fadeTo(spinnerContext.timeslot, 0); spinnerContext.phase = (spinnerContext.phase + 1) % (spinnerContext.$points.length * 2); }, spinnerContext.timeslot); } function stopLoadingSpinnerAnimation(spinnerContext) { clearInterval(spinnerContext.intervalId); spinnerContext.intervalId = null; } function stopImgAnalyzerStarter(context) { context.yield.flushed = 0; if (context.imgAnalyzerTimeout !== null) clearTimeout(context.imgAnalyzerTimeout); } function startImgAnalyzer(context, isForResize) { stopImgAnalyzerStarter(context); context.imgAnalyzerTimeout = setTimeout(function () { analyzeImages(context, isForResize); }, 0.001); analyzeImages(context, isForResize); } function analyzeImages(context, isForResize) { /* //DEBUG// var rnd = parseInt(Math.random() * 10000, 10); console.log('analyzeImages ' + rnd + ' start'); console.log('images status: '); for (var i = 0; i < context.entries.length; i++) { var $entry = $(context.entries[i]); var $image = imgFromEntry($entry); console.log(i + ' (alt: ' + $image.attr('alt') + 'loaded: ' + $image.data('jg.loaded') + ')'); }*/ /* The first row */ var settings = context.settings; var isLastRow; for (var i = context.lastAnalyzedIndex + 1; i < context.entries.length; i++) { var $entry = $(context.entries[i]); var $image = imgFromEntry($entry); if ($image.data('jg.loaded') === true || $image.data('jg.loaded') === 'skipped') { isLastRow = i >= context.entries.length - 1; var availableWidth = context.galleryWidth - ( (context.buildingRow.entriesBuff.length - 1) * settings.margins); var imgAspectRatio = $image.data('jg.imgw') / $image.data('jg.imgh'); if (availableWidth / (context.buildingRow.aspectRatio + imgAspectRatio) < settings.rowHeight) { flushRow(context, isLastRow); if(++context.yield.flushed >= context.yield.every) { //DEBUG// console.log("yield"); startImgAnalyzer(context, isForResize); return; } } context.buildingRow.entriesBuff.push($entry); context.buildingRow.aspectRatio += imgAspectRatio; context.buildingRow.width += imgAspectRatio * settings.rowHeight; context.lastAnalyzedIndex = i; } else if ($image.data('jg.loaded') !== 'error') { return; } } // Last row flush (the row is not full) if (context.buildingRow.entriesBuff.length > 0) flushRow(context, true); if (context.spinner.active) { context.spinner.active = false; context.$gallery.height(context.$gallery.height() - context.spinner.$el.innerHeight()); context.spinner.$el.detach(); stopLoadingSpinnerAnimation(context.spinner); } /* Stop, if there is, the timeout to start the analyzeImages. This is because an image can be set loaded, and the timeout can be set, but this image can be analyzed yet. */ stopImgAnalyzerStarter(context); //On complete callback if (!isForResize) context.$gallery.trigger('jg.complete'); else context.$gallery.trigger('jg.resize'); //DEBUG// console.log('analyzeImages ' + rnd + ' end'); } function checkSettings (context) { var settings = context.settings; function checkSuffixesRange(range) { if (typeof settings.sizeRangeSuffixes[range] !== 'string') throw 'sizeRangeSuffixes.' + range + ' must be a string'; } function checkOrConvertNumber(parent, settingName) { if (typeof parent[settingName] === 'string') { parent[settingName] = parseFloat(parent[settingName], 10); if (isNaN(parent[settingName])) throw 'invalid number for ' + settingName; } else if (typeof parent[settingName] === 'number') { if (isNaN(parent[settingName])) throw 'invalid number for ' + settingName; } else { throw settingName + ' must be a number'; } } if (typeof settings.sizeRangeSuffixes !== 'object') throw 'sizeRangeSuffixes must be defined and must be an object'; checkSuffixesRange('lt100'); checkSuffixesRange('lt240'); checkSuffixesRange('lt320'); checkSuffixesRange('lt500'); checkSuffixesRange('lt640'); checkSuffixesRange('lt1024'); checkOrConvertNumber(settings, 'rowHeight'); checkOrConvertNumber(settings, 'maxRowHeight'); if (settings.maxRowHeight > 0 && settings.maxRowHeight < settings.rowHeight) { settings.maxRowHeight = settings.rowHeight; } checkOrConvertNumber(settings, 'margins'); if (settings.lastRow !== 'nojustify' && settings.lastRow !== 'justify' && settings.lastRow !== 'hide') { throw 'lastRow must be "nojustify", "justify" or "hide"'; } checkOrConvertNumber(settings, 'justifyThreshold'); if (settings.justifyThreshold < 0 || settings.justifyThreshold > 1) throw 'justifyThreshold must be in the interval [0,1]'; if (typeof settings.cssAnimation !== 'boolean') { throw 'cssAnimation must be a boolean'; } checkOrConvertNumber(settings.captionSettings, 'animationDuration'); checkOrConvertNumber(settings, 'imagesAnimationDuration'); checkOrConvertNumber(settings.captionSettings, 'visibleOpacity'); if (settings.captionSettings.visibleOpacity < 0 || settings.captionSettings.visibleOpacity > 1) throw 'captionSettings.visibleOpacity must be in the interval [0, 1]'; checkOrConvertNumber(settings.captionSettings, 'nonVisibleOpacity'); if (settings.captionSettings.visibleOpacity < 0 || settings.captionSettings.visibleOpacity > 1) throw 'captionSettings.nonVisibleOpacity must be in the interval [0, 1]'; if (typeof settings.fixedHeight !== 'boolean') { throw 'fixedHeight must be a boolean'; } if (typeof settings.captions !== 'boolean') { throw 'captions must be a boolean'; } checkOrConvertNumber(settings, 'refreshTime'); if (typeof settings.randomize !== 'boolean') { throw 'randomize must be a boolean'; } } return this.each(function (index, gallery) { var $gallery = $(gallery); $gallery.addClass('justified-gallery'); var context = $gallery.data('jg.context'); if (typeof context === 'undefined') { if (typeof arg !== 'undefined' && arg !== null && typeof arg !== 'object') throw 'The argument must be an object'; // Spinner init var $spinner = $('<div class="spinner"><span></span><span></span><span></span></div>'); var extendedSettings = $.extend({}, defaults, arg); //Context init context = { settings : extendedSettings, imgAnalyzerTimeout : null, entries : null, buildingRow : { entriesBuff : [], width : 0, aspectRatio : 0 }, lastAnalyzedIndex : -1, yield : { every : 2, /* do a flush every context.yield.every flushes ( * must be greater than 1, else the analyzeImages will loop */ flushed : 0 //flushed rows without a yield }, offY : extendedSettings.margins, spinner : { active : false, phase : 0, timeslot : 150, $el : $spinner, $points : $spinner.find('span'), intervalId : null }, checkWidthIntervalId : null, galleryWidth : $gallery.width(), $gallery : $gallery }; $gallery.data('jg.context', context); } else if (arg === 'norewind') { /* Hide the image of the buildingRow to prevent strange effects when the row will be re-justified again */ for (var i = 0; i < context.buildingRow.entriesBuff.length; i++) { hideImgImmediately(context.buildingRow.entriesBuff[i], context); } // In this case we don't rewind, and analyze all the images } else { context.settings = $.extend({}, context.settings, arg); rewind(context); } checkSettings(context); context.entries = $gallery.find('> a, > div:not(.spinner)').toArray(); if (context.entries.length === 0) return; // Randomize if (context.settings.randomize) { context.entries.sort(function () { return Math.random() * 2 - 1; }); $.each(context.entries, function () { $(this).appendTo($gallery); }); } var imagesToLoad = false; var skippedImages = false; $.each(context.entries, function (index, entry) { var $entry = $(entry); var $image = imgFromEntry($entry); $entry.addClass('jg-entry'); if ($image.data('jg.loaded') !== true && $image.data('jg.loaded') !== 'skipped') { // Link Rel global overwrite if (context.settings.rel !== null) $entry.attr('rel', context.settings.rel); // Link Target global overwrite if (context.settings.target !== null) $entry.attr('target', context.settings.target); // Image src var imageSrc = (typeof $image.data('safe-src') !== 'undefined') ? $image.data('safe-src') : $image.attr('src'); $image.data('jg.originalSrc', imageSrc); $image.attr('src', imageSrc); var width = parseInt($image.attr('width'), 10); var height = parseInt($image.attr('height'), 10); if(context.settings.waitThumbnailsLoad !== true && !isNaN(width) && !isNaN(height)) { $image.data('jg.imgw', width); $image.data('jg.imgh', height); $image.data('jg.loaded', 'skipped'); skippedImages = true; startImgAnalyzer(context, false); return true; } $image.data('jg.loaded', false); imagesToLoad = true; // Spinner start if (context.spinner.active === false) { context.spinner.active = true; $gallery.append(context.spinner.$el); $gallery.height(context.offY + context.spinner.$el.innerHeight()); startLoadingSpinnerAnimation(context.spinner); } /* Check if the image is loaded or not using another image object. We cannot use the 'complete' image property, because some browsers, with a 404 set complete = true */ var loadImg = new Image(); var $loadImg = $(loadImg); $loadImg.one('load', function imgLoaded () { //DEBUG// console.log('img load (alt: ' + $image.attr('alt') + ')'); $image.off('load error'); $image.data('jg.imgw', loadImg.width); $image.data('jg.imgh', loadImg.height); $image.data('jg.loaded', true); startImgAnalyzer(context, false); }); $loadImg.one('error', function imgLoadError () { //DEBUG// console.log('img error (alt: ' + $image.attr('alt') + ')'); $image.off('load error'); $image.data('jg.loaded', 'error'); startImgAnalyzer(context, false); }); loadImg.src = imageSrc; } }); if (!imagesToLoad && !skippedImages) startImgAnalyzer(context, false); checkWidth(context); }); }; }(jQuery));
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'fakeobjects', 'es', { anchor: 'Ancla', flash: 'Animación flash', hiddenfield: 'Campo oculto', iframe: 'IFrame', unknown: 'Objeto desconocido' });
/* Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.md or http://ckeditor.com/license */ CKEDITOR.plugins.setLang( 'contextmenu', 'sq', { options: 'Mundësitë e Menysë së Kontekstit' });
/** * Gumby Fixed */ !function() { 'use strict'; function Fixed($el) { this.$el = $el; this.fixedPoint = ''; this.pinPoint = false; this.offset = 0; this.pinOffset = 0; this.top = 0; this.constrainEl = true; this.state = false; this.measurements = { left: 0, width: 0 }; // set up module based on attributes this.setup(); var scope = this; // monitor scroll and update fixed elements accordingly $(window).on('scroll load', function() { scope.monitorScroll(); }); // reinitialize event listener this.$el.on('gumby.initialize', function() { scope.setup(); }); } // set up module based on attributes Fixed.prototype.setup = function() { var scope = this; this.fixedPoint = this.parseAttrValue(Gumby.selectAttr.apply(this.$el, ['fixed'])); // pin point is optional this.pinPoint = Gumby.selectAttr.apply(this.$el, ['pin']) || false; // offset from fixed point this.offset = Number(Gumby.selectAttr.apply(this.$el, ['offset'])) || 0; // offset from pin point this.pinOffset = Number(Gumby.selectAttr.apply(this.$el, ['pinoffset'])) || 0; // top position when fixed this.top = Number(Gumby.selectAttr.apply(this.$el, ['top'])) || 0; // constrain can be turned off this.constrainEl = Gumby.selectAttr.apply(this.$el, ['constrain']) || true; if(this.constrainEl === 'false') { this.constrainEl = false; } // reference to the parent, row/column this.$parent = this.$el.parents('.columns, .column, .row'); this.$parent = this.$parent.length ? this.$parent.first() : false; this.parentRow = this.$parent ? !!this.$parent.hasClass('row') : false; // if optional pin point set then parse now if(this.pinPoint) { this.pinPoint = this.parseAttrValue(this.pinPoint); } // if we have a parent constrain dimenions if(this.$parent && this.constrainEl) { // measure up this.measure(); // and on resize reset measurement $(window).resize(function() { if(scope.state) { scope.measure(); scope.constrain(); } }); } }; // monitor scroll and trigger changes based on position Fixed.prototype.monitorScroll = function() { var scrollAmount = $(window).scrollTop(), // recalculate selector attributes as position may have changed fixedPoint = this.fixedPoint instanceof jQuery ? this.fixedPoint.offset().top : this.fixedPoint, pinPoint = false; // if a pin point is set recalculate if(this.pinPoint) { pinPoint = this.pinPoint instanceof jQuery ? this.pinPoint.offset().top : this.pinPoint; } // apply offsets if(this.offset) { fixedPoint -= this.offset; } if(this.pinOffset) { pinPoint -= this.pinOffset; } // fix it if((scrollAmount >= fixedPoint) && this.state !== 'fixed') { if(!pinPoint || scrollAmount < pinPoint) { this.fix(); } // unfix it } else if(scrollAmount < fixedPoint && this.state === 'fixed') { this.unfix(); // pin it } else if(pinPoint && scrollAmount >= pinPoint && this.state !== 'pinned') { this.pin(); } }; // fix the element and update state Fixed.prototype.fix = function() { this.state = 'fixed'; this.$el.css({ 'top' : 0 + this.top }).addClass('fixed').removeClass('unfixed pinned').trigger('gumby.onFixed'); // if we have a parent constrain dimenions if(this.$parent) { this.constrain(); } }; // unfix the element and update state Fixed.prototype.unfix = function() { this.state = 'unfixed'; this.$el.addClass('unfixed').removeClass('fixed pinned').trigger('gumby.onUnfixed'); }; // pin the element in position Fixed.prototype.pin = function() { this.state = 'pinned'; this.$el.css({ 'top' : this.$el.offset().top }).addClass('pinned fixed').removeClass('unfixed').trigger('gumby.onPinned'); }; // constrain elements dimensions to match width/height Fixed.prototype.constrain = function() { this.$el.css({ left: this.measurements.left, width: this.measurements.width }); }; // measure up the parent for constraining Fixed.prototype.measure = function() { var offsets = this.$parent.offset(), parentPadding; this.measurements.left = offsets.left; this.measurements.width = this.$parent.width(); // if element has a parent row then need to consider padding if(this.parentRow) { parentPadding = Number(this.$parent.css('paddingLeft').replace(/px/, '')); if(parentPadding) { this.measurements.left += parentPadding; } } }; // parse attribute values, could be px, top, selector Fixed.prototype.parseAttrValue = function(attr) { // px value fixed point if($.isNumeric(attr)) { return Number(attr); // 'top' string fixed point } else if(attr === 'top') { return this.$el.offset().top; // selector specified } else { var $el = $(attr); return $el; } }; // add initialisation Gumby.addInitalisation('fixed', function() { $('[data-fixed],[gumby-fixed],[fixed]').each(function() { var $this = $(this); // this element has already been initialized if($this.data('isFixed')) { return true; } // mark element as initialized $this.data('isFixed', true); new Fixed($this); }); }); // register UI module Gumby.UIModule({ module: 'fixed', events: ['onFixed', 'onUnfixed'], init: function() { Gumby.initialize('fixed'); } }); }();
/* Copyright (c) 2003-2012, CKSource - Frederico Knabben. All rights reserved. For licensing, see LICENSE.html or http://ckeditor.com/license */ CKEDITOR.dialog.add("hiddenfield",function(d){return{title:d.lang.forms.hidden.title,hiddenField:null,minWidth:350,minHeight:110,onShow:function(){delete this.hiddenField;var a=this.getParentEditor(),b=a.getSelection(),c=b.getSelectedElement();c&&(c.data("cke-real-element-type")&&"hiddenfield"==c.data("cke-real-element-type"))&&(this.hiddenField=c,c=a.restoreRealElement(this.hiddenField),this.setupContent(c),b.selectElement(this.hiddenField))},onOk:function(){var a=this.getValueOf("info","_cke_saved_name"); this.getValueOf("info","value");var b=this.getParentEditor(),a=CKEDITOR.env.ie&&!(8<=CKEDITOR.document.$.documentMode)?b.document.createElement('<input name="'+CKEDITOR.tools.htmlEncode(a)+'">'):b.document.createElement("input");a.setAttribute("type","hidden");this.commitContent(a);a=b.createFakeElement(a,"cke_hidden","hiddenfield");this.hiddenField?(a.replace(this.hiddenField),b.getSelection().selectElement(a)):b.insertElement(a);return!0},contents:[{id:"info",label:d.lang.forms.hidden.title,title:d.lang.forms.hidden.title, elements:[{id:"_cke_saved_name",type:"text",label:d.lang.forms.hidden.name,"default":"",accessKey:"N",setup:function(a){this.setValue(a.data("cke-saved-name")||a.getAttribute("name")||"")},commit:function(a){this.getValue()?a.setAttribute("name",this.getValue()):a.removeAttribute("name")}},{id:"value",type:"text",label:d.lang.forms.hidden.value,"default":"",accessKey:"V",setup:function(a){this.setValue(a.getAttribute("value")||"")},commit:function(a){this.getValue()?a.setAttribute("value",this.getValue()): a.removeAttribute("value")}}]}]}});
// Copyright 2008 The Closure Library Authors. All Rights Reserved. // // 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. /** * @fileoverview list of native country and language names. * * Warning: this file is automatically generated from CLDR. * Please contact i18n team or change the script and regenerate data. * Code location: http://go/generate_js_native_names.py * */ /** * Namespace for native country and lanugage names */ goog.provide('goog.locale.nativeNameConstants'); /** * Native country and language names * @type {Object} */ /* ~!@# genmethods.NativeDictAsJson() #@!~ */ goog.locale.nativeNameConstants = { 'COUNTRY': { 'AD': 'Andorra', 'AE': '\u0627\u0644\u0627\u0645\u0627\u0631\u0627\u062a \u0627' + '\u0644\u0639\u0631\u0628\u064a\u0629 \u0627\u0644' + '\u0645\u062a\u062d\u062f\u0629', 'AF': '\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627\u0646', 'AG': 'Antigua and Barbuda', 'AI': 'Anguilla', 'AL': 'Shqip\u00ebria', 'AM': '\u0540\u0561\u0575\u0561\u057d\u057f\u0561\u0576\u056b ' + '\u0540\u0561\u0576\u0580\u0561\u057a\u0565\u057f\u0578' + '\u0582\u0569\u056b\u0582\u0576', 'AN': 'Nederlandse Antillen', 'AO': 'Angola', 'AQ': 'Antarctica', 'AR': 'Argentina', 'AS': 'American Samoa', 'AT': '\u00d6sterreich', 'AU': 'Australia', 'AW': 'Aruba', 'AX': '\u00c5land', 'AZ': 'Az\u0259rbaycan', 'BA': 'Bosna i Hercegovina', 'BB': 'Barbados', 'BD': '\u09ac\u09be\u0982\u09b2\u09be\u09a6\u09c7\u09b6', 'BE': 'Belgi\u00eb', 'BF': 'Burkina Faso', 'BG': '\u0411\u044a\u043b\u0433\u0430\u0440\u0438\u044f', 'BH': '\u0627\u0644\u0628\u062d\u0631\u064a\u0646', 'BI': 'Burundi', 'BJ': 'B\u00e9nin', 'BM': 'Bermuda', 'BN': 'Brunei', 'BO': 'Bolivia', 'BR': 'Brasil', 'BS': 'Bahamas', 'BT': '\u092d\u0942\u091f\u093e\u0928', 'BV': 'Bouvet Island', 'BW': 'Botswana', 'BY': '\u0411\u0435\u043b\u0430\u0440\u0443\u0441\u044c', 'BZ': 'Belize', 'CA': 'Canada', 'CC': 'Cocos (Keeling) Islands', 'CD': 'R\u00e9publique d\u00e9mocratique du Congo', 'CF': 'R\u00e9publique centrafricaine', 'CG': 'Congo', 'CH': 'Schweiz', 'CI': 'C\u00f4te d\u2019Ivoire', 'CK': 'Cook Islands', 'CL': 'Chile', 'CM': 'Cameroun', 'CN': '\u4e2d\u56fd', 'CO': 'Colombia', 'CR': 'Costa Rica', 'CS': 'Serbia and Montenegro', 'CU': 'Cuba', 'CV': 'Cabo Verde', 'CX': 'Christmas Island', 'CY': '\u039a\u03cd\u03c0\u03c1\u03bf\u03c2', 'CZ': '\u010cesk\u00e1 republika', 'DD': 'East Germany', 'DE': 'Deutschland', 'DJ': 'Jabuuti', 'DK': 'Danmark', 'DM': 'Dominica', 'DO': 'Rep\u00fablica Dominicana', 'DZ': '\u0627\u0644\u062c\u0632\u0627\u0626\u0631', 'EC': 'Ecuador', 'EE': 'Eesti', 'EG': '\u0645\u0635\u0631', 'EH': '\u0627\u0644\u0635\u062d\u0631\u0627\u0621 \u0627\u0644' + '\u063a\u0631\u0628\u064a\u0629', 'ER': '\u0627\u0631\u064a\u062a\u0631\u064a\u0627', 'ES': 'Espa\u00f1a', 'ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'FI': 'Suomi', 'FJ': '\u092b\u093f\u091c\u0940', 'FK': 'Falkland Islands', 'FM': 'Micronesia', 'FO': 'F\u00f8royar', 'FR': 'France', 'FX': 'Metropolitan France', 'GA': 'Gabon', 'GB': 'United Kingdom', 'GD': 'Grenada', 'GE': '\u10e1\u10d0\u10e5\u10d0\u10e0\u10d7\u10d5\u10d4\u10da' + '\u10dd', 'GF': 'Guyane fran\u00e7aise', 'GG': 'Guernsey', 'GH': 'Ghana', 'GI': 'Gibraltar', 'GL': 'Kalaallit Nunaat', 'GM': 'Gambia', 'GN': 'Guin\u00e9e', 'GP': 'Guadeloupe', 'GQ': 'Guin\u00e9e \u00e9quatoriale', 'GR': '\u0395\u03bb\u03bb\u03ac\u03b4\u03b1', 'GS': 'South Georgia and the South Sandwich Islands', 'GT': 'Guatemala', 'GU': 'Guam', 'GW': 'Guin\u00e9 Bissau', 'GY': 'Guyana', 'HK': '\u9999\u6e2f', 'HM': 'Heard Island and McDonald Islands', 'HN': 'Honduras', 'HR': 'Hrvatska', 'HT': 'Ha\u00efti', 'HU': 'Magyarorsz\u00e1g', 'ID': 'Indonesia', 'IE': 'Ireland', 'IL': '\u05d9\u05e9\u05e8\u05d0\u05dc', 'IM': 'Isle of Man', 'IN': '\u092d\u093e\u0930\u0924', 'IO': 'British Indian Ocean Territory', 'IQ': '\u0627\u0644\u0639\u0631\u0627\u0642', 'IR': '\u0627\u06cc\u0631\u0627\u0646', 'IS': '\u00cdsland', 'IT': 'Italia', 'JE': 'Jersey', 'JM': 'Jamaica', 'JO': '\u0627\u0644\u0623\u0631\u062f\u0646', 'JP': '\u65e5\u672c', 'KE': 'Kenya', 'KG': '\u041a\u044b\u0440\u0433\u044b\u0437\u0441\u0442\u0430' + '\u043d', 'KH': '\u1780\u1798\u17d2\u1796\u17bb\u1787\u17b6', 'KI': 'Kiribati', 'KM': '\u062c\u0632\u0631 \u0627\u0644\u0642\u0645\u0631', 'KN': 'Saint Kitts and Nevis', 'KP': '\uc870\uc120 \ubbfc\uc8fc\uc8fc\uc758 \uc778\ubbfc ' + '\uacf5\ud654\uad6d', 'KR': '\ub300\ud55c\ubbfc\uad6d', 'KW': '\u0627\u0644\u0643\u0648\u064a\u062a', 'KY': 'Cayman Islands', 'KZ': '\u041a\u0430\u0437\u0430\u0445\u0441\u0442\u0430\u043d', 'LA': '\u0e25\u0e32\u0e27', 'LB': '\u0644\u0628\u0646\u0627\u0646', 'LC': 'Saint Lucia', 'LI': 'Liechtenstein', 'LK': '\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8', 'LR': 'Liberia', 'LS': 'Lesotho', 'LT': 'Lietuva', 'LU': 'Luxembourg', 'LV': 'Latvija', 'LY': '\u0644\u064a\u0628\u064a\u0627', 'MA': '\u0627\u0644\u0645\u063a\u0631\u0628', 'MC': 'Monaco', 'MD': 'Moldova, Republica', 'ME': '\u0426\u0440\u043d\u0430 \u0413\u043e\u0440\u0430', 'MG': 'Madagascar', 'MH': 'Marshall Islands', 'MK': '\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0438\u0458' + '\u0430', 'ML': '\u0645\u0627\u0644\u064a', 'MM': 'Myanmar', 'MN': '\u8499\u53e4', 'MO': '\u6fb3\u95e8', 'MP': 'Northern Mariana Islands', 'MQ': 'Martinique', 'MR': '\u0645\u0648\u0631\u064a\u062a\u0627\u0646\u064a\u0627', 'MS': 'Montserrat', 'MT': 'Malta', 'MU': 'Mauritius', 'MV': 'Maldives', 'MW': 'Malawi', 'MX': 'M\u00e9xico', 'MY': 'Malaysia', 'MZ': 'Mo\u00e7ambique', 'NA': 'Namibia', 'NC': 'Nouvelle-Cal\u00e9donie', 'NE': 'Niger', 'NF': 'Norfolk Island', 'NG': 'Nigeria', 'NI': 'Nicaragua', 'NL': 'Nederland', 'NO': 'Norge', 'NP': '\u0928\u0947\u092a\u093e\u0932', 'NR': 'Nauru', 'NT': 'Neutral Zone', 'NU': 'Niue', 'NZ': 'New Zealand', 'OM': '\u0639\u0645\u0627\u0646', 'PA': 'Panam\u00e1', 'PE': 'Per\u00fa', 'PF': 'Polyn\u00e9sie fran\u00e7aise', 'PG': 'Papua New Guinea', 'PH': 'Philippines', 'PK': '\u067e\u0627\u06a9\u0633\u062a\u0627\u0646', 'PL': 'Polska', 'PM': 'Saint-Pierre-et-Miquelon', 'PN': 'Pitcairn', 'PR': 'Puerto Rico', 'PS': '\u0641\u0644\u0633\u0637\u064a\u0646', 'PT': 'Portugal', 'PW': 'Palau', 'PY': 'Paraguay', 'QA': '\u0642\u0637\u0631', 'QO': 'Outlying Oceania', 'QU': 'European Union', 'RE': 'R\u00e9union', 'RO': 'Rom\u00e2nia', 'RS': '\u0421\u0440\u0431\u0438\u0458\u0430', 'RU': '\u0420\u043e\u0441\u0441\u0438\u044f', 'RW': 'Rwanda', 'SA': '\u0627\u0644\u0645\u0645\u0644\u0643\u0629 \u0627\u0644' + '\u0639\u0631\u0628\u064a\u0629 \u0627\u0644\u0633' + '\u0639\u0648\u062f\u064a\u0629', 'SB': 'Solomon Islands', 'SC': 'Seychelles', 'SD': '\u0627\u0644\u0633\u0648\u062f\u0627\u0646', 'SE': 'Sverige', 'SG': '\u65b0\u52a0\u5761', 'SH': 'Saint Helena', 'SI': 'Slovenija', 'SJ': 'Svalbard og Jan Mayen', 'SK': 'Slovensk\u00e1 republika', 'SL': 'Sierra Leone', 'SM': 'San Marino', 'SN': 'S\u00e9n\u00e9gal', 'SO': 'Somali', 'SR': 'Suriname', 'ST': 'S\u00e3o Tom\u00e9 e Pr\u00edncipe', 'SU': 'Union of Soviet Socialist Republics', 'SV': 'El Salvador', 'SY': '\u0633\u0648\u0631\u064a\u0627', 'SZ': 'Swaziland', 'TC': 'Turks and Caicos Islands', 'TD': '\u062a\u0634\u0627\u062f', 'TF': 'French Southern Territories', 'TG': 'Togo', 'TH': '\u0e1b\u0e23\u0e30\u0e40\u0e17\u0e28\u0e44\u0e17\u0e22', 'TJ': '\u062a\u0627\u062c\u06cc\u06a9\u0633\u062a\u0627\u0646', 'TK': 'Tokelau', 'TL': 'Timor Leste', 'TM': '\u0422\u0443\u0440\u043a\u043c\u0435\u043d\u0438\u0441' + '\u0442\u0430\u043d', 'TN': '\u062a\u0648\u0646\u0633', 'TO': 'Tonga', 'TR': 'T\u00fcrkiye', 'TT': 'Trinidad y Tobago', 'TV': 'Tuvalu', 'TW': '\u53f0\u6e7e', 'TZ': 'Tanzania', 'UA': '\u0423\u043a\u0440\u0430\u0457\u043d\u0430', 'UG': 'Uganda', 'UM': 'United States Minor Outlying Islands', 'US': 'United States', 'UY': 'Uruguay', 'UZ': '\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442\u043e' + '\u043d', 'VA': 'Vaticano', 'VC': 'Saint Vincent and the Grenadines', 'VE': 'Venezuela', 'VG': 'British Virgin Islands', 'VI': 'U.S. Virgin Islands', 'VN': 'Vi\u1ec7t Nam', 'VU': 'Vanuatu', 'WF': 'Wallis-et-Futuna', 'WS': 'Samoa', 'YD': 'People\'s Democratic Republic of Yemen', 'YE': '\u0627\u0644\u064a\u0645\u0646', 'YT': 'Mayotte', 'ZA': 'South Africa', 'ZM': 'Zambia', 'ZW': 'Zimbabwe', 'ZZ': 'Unknown or Invalid Region', 'aa_DJ': 'Jabuuti', 'aa_ER': '\u00c9rythr\u00e9e', 'aa_ER_SAAHO': '\u00c9rythr\u00e9e', 'aa_ET': 'Itoophiyaa', 'af_NA': 'Namibi\u00eb', 'af_ZA': 'Suid-Afrika', 'ak_GH': 'Ghana', 'am_ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'ar_AE': '\u0627\u0644\u0627\u0645\u0627\u0631\u0627\u062a ' + '\u0627\u0644\u0639\u0631\u0628\u064a\u0629 \u0627' + '\u0644\u0645\u062a\u062d\u062f\u0629', 'ar_BH': '\u0627\u0644\u0628\u062d\u0631\u064a\u0646', 'ar_DJ': '\u062c\u064a\u0628\u0648\u062a\u064a', 'ar_DZ': '\u0627\u0644\u062c\u0632\u0627\u0626\u0631', 'ar_EG': '\u0645\u0635\u0631', 'ar_EH': '\u0627\u0644\u0635\u062d\u0631\u0627\u0621 \u0627' + '\u0644\u063a\u0631\u0628\u064a\u0629', 'ar_ER': '\u0627\u0631\u064a\u062a\u0631\u064a\u0627', 'ar_IL': '\u0627\u0633\u0631\u0627\u0626\u064a\u0644', 'ar_IQ': '\u0627\u0644\u0639\u0631\u0627\u0642', 'ar_JO': '\u0627\u0644\u0623\u0631\u062f\u0646', 'ar_KM': '\u062c\u0632\u0631 \u0627\u0644\u0642\u0645\u0631', 'ar_KW': '\u0627\u0644\u0643\u0648\u064a\u062a', 'ar_LB': '\u0644\u0628\u0646\u0627\u0646', 'ar_LY': '\u0644\u064a\u0628\u064a\u0627', 'ar_MA': '\u0627\u0644\u0645\u063a\u0631\u0628', 'ar_MR': '\u0645\u0648\u0631\u064a\u062a\u0627\u0646\u064a' + '\u0627', 'ar_OM': '\u0639\u0645\u0627\u0646', 'ar_PS': '\u0641\u0644\u0633\u0637\u064a\u0646', 'ar_QA': '\u0642\u0637\u0631', 'ar_SA': '\u0627\u0644\u0645\u0645\u0644\u0643\u0629 \u0627' + '\u0644\u0639\u0631\u0628\u064a\u0629 \u0627\u0644' + '\u0633\u0639\u0648\u062f\u064a\u0629', 'ar_SD': '\u0627\u0644\u0633\u0648\u062f\u0627\u0646', 'ar_SY': '\u0633\u0648\u0631\u064a\u0627', 'ar_TD': '\u062a\u0634\u0627\u062f', 'ar_TN': '\u062a\u0648\u0646\u0633', 'ar_YE': '\u0627\u0644\u064a\u0645\u0646', 'as_IN': '\u09ad\u09be\u09f0\u09a4', 'ay_BO': 'Bolivia', 'az_AZ': 'Az\u0259rbaycan', 'az_Cyrl_AZ': '\u0410\u0437\u04d9\u0440\u0431\u0430\u0458' + '\u04b9\u0430\u043d', 'az_Latn_AZ': 'Azerbaycan', 'be_BY': '\u0411\u0435\u043b\u0430\u0440\u0443\u0441\u044c', 'bg_BG': '\u0411\u044a\u043b\u0433\u0430\u0440\u0438\u044f', 'bi_VU': 'Vanuatu', 'bn_BD': '\u09ac\u09be\u0982\u09b2\u09be\u09a6\u09c7\u09b6', 'bn_IN': '\u09ad\u09be\u09b0\u09a4', 'bo_CN': '\u0f62\u0f92\u0fb1\u0f0b\u0f53\u0f42', 'bo_IN': '\u0f62\u0f92\u0fb1\u0f0b\u0f42\u0f62\u0f0b', 'bs_BA': 'Bosna i Hercegovina', 'byn_ER': '\u12a4\u122d\u1275\u122b', 'ca_AD': 'Andorra', 'ca_ES': 'Espanya', 'cch_NG': 'Nigeria', 'ch_GU': 'Guam', 'chk_FM': 'Micronesia', 'cop_Arab_EG': '\u0645\u0635\u0631', 'cop_Arab_US': '\u0627\u0644\u0648\u0644\u0627\u064a\u0627' + '\u062a \u0627\u0644\u0645\u062a\u062d\u062f' + '\u0629 \u0627\u0644\u0623\u0645\u0631\u064a' + '\u0643\u064a\u0629', 'cop_EG': '\u0645\u0635\u0631', 'cop_US': '\u0627\u0644\u0648\u0644\u0627\u064a\u0627\u062a ' + '\u0627\u0644\u0645\u062a\u062d\u062f\u0629 \u0627' + '\u0644\u0623\u0645\u0631\u064a\u0643\u064a\u0629', 'cs_CZ': '\u010cesk\u00e1 republika', 'cy_GB': 'Prydain Fawr', 'da_DK': 'Danmark', 'da_GL': 'Gr\u00f8nland', 'de_AT': '\u00d6sterreich', 'de_BE': 'Belgien', 'de_CH': 'Schweiz', 'de_DE': 'Deutschland', 'de_LI': 'Liechtenstein', 'de_LU': 'Luxemburg', 'dv_MV': 'Maldives', 'dz_BT': 'Bhutan', 'ee_GH': 'Ghana', 'ee_TG': 'Togo', 'efi_NG': 'Nigeria', 'el_CY': '\u039a\u03cd\u03c0\u03c1\u03bf\u03c2', 'el_GR': '\u0395\u03bb\u03bb\u03ac\u03b4\u03b1', 'en_AG': 'Antigua and Barbuda', 'en_AI': 'Anguilla', 'en_AS': 'American Samoa', 'en_AU': 'Australia', 'en_BB': 'Barbados', 'en_BE': 'Belgium', 'en_BM': 'Bermuda', 'en_BS': 'Bahamas', 'en_BW': 'Botswana', 'en_BZ': 'Belize', 'en_CA': 'Canada', 'en_CC': 'Cocos Islands', 'en_CK': 'Cook Islands', 'en_CM': 'Cameroon', 'en_CX': 'Christmas Island', 'en_DM': 'Dominica', 'en_FJ': 'Fiji', 'en_FK': 'Falkland Islands', 'en_FM': 'Micronesia', 'en_GB': 'United Kingdom', 'en_GD': 'Grenada', 'en_GG': 'Guernsey', 'en_GH': 'Ghana', 'en_GI': 'Gibraltar', 'en_GM': 'Gambia', 'en_GU': 'Guam', 'en_GY': 'Guyana', 'en_HK': 'Hong Kong', 'en_HN': 'Honduras', 'en_IE': 'Ireland', 'en_IM': 'Isle of Man', 'en_IN': 'India', 'en_JE': 'Jersey', 'en_JM': 'Jamaica', 'en_KE': 'Kenya', 'en_KI': 'Kiribati', 'en_KN': 'Saint Kitts and Nevis', 'en_KY': 'Cayman Islands', 'en_LC': 'Saint Lucia', 'en_LR': 'Liberia', 'en_LS': 'Lesotho', 'en_MH': 'Marshall Islands', 'en_MP': 'Northern Mariana Islands', 'en_MS': 'Montserrat', 'en_MT': 'Malta', 'en_MU': 'Mauritius', 'en_MW': 'Malawi', 'en_NA': 'Namibia', 'en_NF': 'Norfolk Island', 'en_NG': 'Nigeria', 'en_NR': 'Nauru', 'en_NU': 'Niue', 'en_NZ': 'New Zealand', 'en_PG': 'Papua New Guinea', 'en_PH': 'Philippines', 'en_PK': 'Pakistan', 'en_PN': 'Pitcairn', 'en_PR': 'Puerto Rico', 'en_RW': 'Rwanda', 'en_SB': 'Solomon Islands', 'en_SC': 'Seychelles', 'en_SG': 'Singapore', 'en_SH': 'Saint Helena', 'en_SL': 'Sierra Leone', 'en_SZ': 'Swaziland', 'en_TC': 'Turks and Caicos Islands', 'en_TK': 'Tokelau', 'en_TO': 'Tonga', 'en_TT': 'Trinidad and Tobago', 'en_TV': 'Tuvalu', 'en_TZ': 'Tanzania', 'en_UG': 'Uganda', 'en_UM': 'United States Minor Outlying Islands', 'en_US': 'United States', 'en_US_POSIX': 'United States', 'en_VC': 'Saint Vincent and the Grenadines', 'en_VG': 'British Virgin Islands', 'en_VI': 'U.S. Virgin Islands', 'en_VU': 'Vanuatu', 'en_WS': 'Samoa', 'en_ZA': 'South Africa', 'en_ZM': 'Zambia', 'en_ZW': 'Zimbabwe', 'es_AR': 'Argentina', 'es_BO': 'Bolivia', 'es_CL': 'Chile', 'es_CO': 'Colombia', 'es_CR': 'Costa Rica', 'es_CU': 'Cuba', 'es_DO': 'Rep\u00fablica Dominicana', 'es_EC': 'Ecuador', 'es_ES': 'Espa\u00f1a', 'es_GQ': 'Guinea Ecuatorial', 'es_GT': 'Guatemala', 'es_HN': 'Honduras', 'es_MX': 'M\u00e9xico', 'es_NI': 'Nicaragua', 'es_PA': 'Panam\u00e1', 'es_PE': 'Per\u00fa', 'es_PH': 'Filipinas', 'es_PR': 'Puerto Rico', 'es_PY': 'Paraguay', 'es_SV': 'El Salvador', 'es_US': 'Estados Unidos', 'es_UY': 'Uruguay', 'es_VE': 'Venezuela', 'et_EE': 'Eesti', 'eu_ES': 'Espainia', 'fa_AF': '\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627' + '\u0646', 'fa_IR': '\u0627\u06cc\u0631\u0627\u0646', 'fi_FI': 'Suomi', 'fil_PH': 'Philippines', 'fj_FJ': 'Fiji', 'fo_FO': 'F\u00f8royar', 'fr_BE': 'Belgique', 'fr_BF': 'Burkina Faso', 'fr_BI': 'Burundi', 'fr_BJ': 'B\u00e9nin', 'fr_CA': 'Canada', 'fr_CD': 'R\u00e9publique d\u00e9mocratique du Congo', 'fr_CF': 'R\u00e9publique centrafricaine', 'fr_CG': 'Congo', 'fr_CH': 'Suisse', 'fr_CI': 'C\u00f4te d\u2019Ivoire', 'fr_CM': 'Cameroun', 'fr_DJ': 'Djibouti', 'fr_DZ': 'Alg\u00e9rie', 'fr_FR': 'France', 'fr_GA': 'Gabon', 'fr_GF': 'Guyane fran\u00e7aise', 'fr_GN': 'Guin\u00e9e', 'fr_GP': 'Guadeloupe', 'fr_GQ': 'Guin\u00e9e \u00e9quatoriale', 'fr_HT': 'Ha\u00efti', 'fr_KM': 'Comores', 'fr_LU': 'Luxembourg', 'fr_MA': 'Maroc', 'fr_MC': 'Monaco', 'fr_MG': 'Madagascar', 'fr_ML': 'Mali', 'fr_MQ': 'Martinique', 'fr_MU': 'Maurice', 'fr_NC': 'Nouvelle-Cal\u00e9donie', 'fr_NE': 'Niger', 'fr_PF': 'Polyn\u00e9sie fran\u00e7aise', 'fr_PM': 'Saint-Pierre-et-Miquelon', 'fr_RE': 'R\u00e9union', 'fr_RW': 'Rwanda', 'fr_SC': 'Seychelles', 'fr_SN': 'S\u00e9n\u00e9gal', 'fr_SY': 'Syrie', 'fr_TD': 'Tchad', 'fr_TG': 'Togo', 'fr_TN': 'Tunisie', 'fr_VU': 'Vanuatu', 'fr_WF': 'Wallis-et-Futuna', 'fr_YT': 'Mayotte', 'fur_IT': 'Italia', 'ga_IE': '\u00c9ire', 'gaa_GH': 'Ghana', 'gez_ER': '\u12a4\u122d\u1275\u122b', 'gez_ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'gil_KI': 'Kiribati', 'gl_ES': 'Espa\u00f1a', 'gn_PY': 'Paraguay', 'gu_IN': '\u0aad\u0abe\u0ab0\u0aa4', 'gv_GB': 'Rywvaneth Unys', 'ha_Arab_NG': '\u0646\u064a\u062c\u064a\u0631\u064a\u0627', 'ha_GH': '\u063a\u0627\u0646\u0627', 'ha_Latn_GH': 'Ghana', 'ha_Latn_NE': 'Niger', 'ha_Latn_NG': 'Nig\u00e9ria', 'ha_NE': '\u0627\u0644\u0646\u064a\u062c\u0631', 'ha_NG': '\u0646\u064a\u062c\u064a\u0631\u064a\u0627', 'haw_US': '\u02bbAmelika Hui P\u016b \u02bbIa', 'he_IL': '\u05d9\u05e9\u05e8\u05d0\u05dc', 'hi_IN': '\u092d\u093e\u0930\u0924', 'ho_PG': 'Papua New Guinea', 'hr_BA': 'Bosna i Hercegovina', 'hr_HR': 'Hrvatska', 'ht_HT': 'Ha\u00efti', 'hu_HU': 'Magyarorsz\u00e1g', 'hy_AM': '\u0540\u0561\u0575\u0561\u057d\u057f\u0561\u0576' + '\u056b \u0540\u0561\u0576\u0580\u0561\u057a\u0565' + '\u057f\u0578\u0582\u0569\u056b\u0582\u0576', 'hy_AM_REVISED': '\u0540\u0561\u0575\u0561\u057d\u057f\u0561' + '\u0576\u056b \u0540\u0561\u0576\u0580\u0561' + '\u057a\u0565\u057f\u0578\u0582\u0569\u056b' + '\u0582\u0576', 'id_ID': 'Indonesia', 'ig_NG': 'Nigeria', 'ii_CN': '\ua34f\ua1e9', 'is_IS': '\u00cdsland', 'it_CH': 'Svizzera', 'it_IT': 'Italia', 'it_SM': 'San Marino', 'ja_JP': '\u65e5\u672c', 'ka_GE': '\u10e1\u10d0\u10e5\u10d0\u10e0\u10d7\u10d5\u10d4' + '\u10da\u10dd', 'kaj_NG': 'Nigeria', 'kam_KE': 'Kenya', 'kcg_NG': 'Nigeria', 'kfo_NG': 'Nig\u00e9ria', 'kk_KZ': '\u049a\u0430\u0437\u0430\u049b\u0441\u0442\u0430' + '\u043d', 'kl_GL': 'Kalaallit Nunaat', 'km_KH': '\u1780\u1798\u17d2\u1796\u17bb\u1787\u17b6', 'kn_IN': '\u0cad\u0cbe\u0cb0\u0ca4', 'ko_KP': '\uc870\uc120 \ubbfc\uc8fc\uc8fc\uc758 \uc778\ubbfc ' + '\uacf5\ud654\uad6d', 'ko_KR': '\ub300\ud55c\ubbfc\uad6d', 'kok_IN': '\u092d\u093e\u0930\u0924', 'kos_FM': 'Micronesia', 'kpe_GN': 'Guin\u00e9e', 'kpe_LR': 'Lib\u00e9ria', 'ks_IN': '\u092d\u093e\u0930\u0924', 'ku_IQ': 'Irak', 'ku_IR': '\u0130ran', 'ku_Latn_IQ': 'Irak', 'ku_Latn_IR': '\u0130ran', 'ku_Latn_SY': 'Suriye', 'ku_Latn_TR': 'T\u00fcrkiye', 'ku_SY': 'Suriye', 'ku_TR': 'T\u00fcrkiye', 'kw_GB': 'Rywvaneth Unys', 'ky_Cyrl_KG': '\u041a\u044b\u0440\u0433\u044b\u0437\u0441' + '\u0442\u0430\u043d', 'ky_KG': 'K\u0131rg\u0131zistan', 'la_VA': 'Vaticano', 'lb_LU': 'Luxembourg', 'ln_CD': 'R\u00e9publique d\u00e9mocratique du Congo', 'ln_CG': 'Kongo', 'lo_LA': 'Laos', 'lt_LT': 'Lietuva', 'lv_LV': 'Latvija', 'mg_MG': 'Madagascar', 'mh_MH': 'Marshall Islands', 'mi_NZ': 'New Zealand', 'mk_MK': '\u041c\u0430\u043a\u0435\u0434\u043e\u043d\u0438' + '\u0458\u0430', 'ml_IN': '\u0d07\u0d28\u0d4d\u0d24\u0d4d\u0d2f', 'mn_Cyrl_MN': '\u041c\u043e\u043d\u0433\u043e\u043b\u0438' + '\u044f', 'mn_MN': '\u041c\u043e\u043d\u0433\u043e\u043b\u0438\u044f', 'mr_IN': '\u092d\u093e\u0930\u0924', 'ms_BN': 'Brunei', 'ms_MY': 'Malaysia', 'ms_SG': 'Singapura', 'mt_MT': 'Malta', 'my_MM': 'Myanmar', 'na_NR': 'Nauru', 'nb_NO': 'Norge', 'nb_SJ': 'Svalbard og Jan Mayen', 'ne_NP': '\u0928\u0947\u092a\u093e\u0932', 'niu_NU': 'Niue', 'nl_AN': 'Nederlandse Antillen', 'nl_AW': 'Aruba', 'nl_BE': 'Belgi\u00eb', 'nl_NL': 'Nederland', 'nl_SR': 'Suriname', 'nn_NO': 'Noreg', 'nr_ZA': 'South Africa', 'nso_ZA': 'South Africa', 'ny_MW': 'Malawi', 'om_ET': 'Itoophiyaa', 'om_KE': 'Keeniyaa', 'or_IN': '\u0b2d\u0b3e\u0b30\u0b24', 'pa_Arab_PK': '\u067e\u0627\u06a9\u0633\u062a\u0627\u0646', 'pa_Guru_IN': '\u0a2d\u0a3e\u0a30\u0a24', 'pa_IN': '\u0a2d\u0a3e\u0a30\u0a24', 'pa_PK': '\u067e\u0627\u06a9\u0633\u062a\u0627\u0646', 'pap_AN': 'Nederlandse Antillen', 'pau_PW': 'Palau', 'pl_PL': 'Polska', 'pon_FM': 'Micronesia', 'ps_AF': '\u0627\u0641\u063a\u0627\u0646\u0633\u062a\u0627' + '\u0646', 'pt_AO': 'Angola', 'pt_BR': 'Brasil', 'pt_CV': 'Cabo Verde', 'pt_GW': 'Guin\u00e9 Bissau', 'pt_MZ': 'Mo\u00e7ambique', 'pt_PT': 'Portugal', 'pt_ST': 'S\u00e3o Tom\u00e9 e Pr\u00edncipe', 'pt_TL': 'Timor Leste', 'qu_BO': 'Bolivia', 'qu_PE': 'Per\u00fa', 'rm_CH': 'Schweiz', 'rn_BI': 'Burundi', 'ro_MD': 'Moldova, Republica', 'ro_RO': 'Rom\u00e2nia', 'ru_BY': '\u0411\u0435\u043b\u0430\u0440\u0443\u0441\u044c', 'ru_KG': '\u041a\u044b\u0440\u0433\u044b\u0437\u0441\u0442' + '\u0430\u043d', 'ru_KZ': '\u041a\u0430\u0437\u0430\u0445\u0441\u0442\u0430' + '\u043d', 'ru_RU': '\u0420\u043e\u0441\u0441\u0438\u044f', 'ru_UA': '\u0423\u043a\u0440\u0430\u0438\u043d\u0430', 'rw_RW': 'Rwanda', 'sa_IN': '\u092d\u093e\u0930\u0924', 'sd_Deva_IN': '\u092d\u093e\u0930\u0924', 'sd_IN': '\u092d\u093e\u0930\u0924', 'se_FI': 'Finland', 'se_NO': 'Norge', 'sg_CF': 'R\u00e9publique centrafricaine', 'sh_BA': 'Bosnia and Herzegovina', 'sh_CS': 'Serbia and Montenegro', 'si_LK': 'Sri Lanka', 'sid_ET': 'Itoophiyaa', 'sk_SK': 'Slovensk\u00e1 republika', 'sl_SI': 'Slovenija', 'sm_AS': 'American Samoa', 'sm_WS': 'Samoa', 'so_DJ': 'Jabuuti', 'so_ET': 'Itoobiya', 'so_KE': 'Kiiniya', 'so_SO': 'Soomaaliya', 'sq_AL': 'Shqip\u00ebria', 'sr_BA': '\u0411\u043e\u0441\u043d\u0430 \u0438 \u0425\u0435' + '\u0440\u0446\u0435\u0433\u043e\u0432\u0438\u043d' + '\u0430', 'sr_CS': '\u0421\u0440\u0431\u0438\u0458\u0430 \u0438 \u0426' + '\u0440\u043d\u0430 \u0413\u043e\u0440\u0430', 'sr_Cyrl_BA': '\u0411\u043e\u0441\u043d\u0438\u044f', 'sr_Cyrl_CS': '\u0421\u0435\u0440\u0431\u0438\u044f \u0438 ' + '\u0427\u0435\u0440\u043d\u043e\u0433\u043e' + '\u0440\u0438\u044f', 'sr_Cyrl_ME': '\u0427\u0435\u0440\u043d\u043e\u0433\u043e' + '\u0440\u0438\u044f', 'sr_Cyrl_RS': '\u0421\u0435\u0440\u0431\u0438\u044f', 'sr_Latn_BA': 'Bosna i Hercegovina', 'sr_Latn_CS': 'Srbija i Crna Gora', 'sr_Latn_ME': 'Crna Gora', 'sr_Latn_RS': 'Srbija', 'sr_ME': '\u0426\u0440\u043d\u0430 \u0413\u043e\u0440\u0430', 'sr_RS': '\u0421\u0440\u0431\u0438\u0458\u0430', 'ss_SZ': 'Swaziland', 'ss_ZA': 'South Africa', 'st_LS': 'Lesotho', 'st_ZA': 'South Africa', 'su_ID': 'Indonesia', 'sv_AX': '\u00c5land', 'sv_FI': 'Finland', 'sv_SE': 'Sverige', 'sw_KE': 'Kenya', 'sw_TZ': 'Tanzania', 'sw_UG': 'Uganda', 'swb_KM': '\u062c\u0632\u0631 \u0627\u0644\u0642\u0645\u0631', 'syr_SY': 'Syria', 'ta_IN': '\u0b87\u0ba8\u0bcd\u0ba4\u0bbf\u0baf\u0bbe', 'ta_LK': '\u0b87\u0bb2\u0b99\u0bcd\u0b95\u0bc8', 'ta_SG': '\u0b9a\u0bbf\u0b99\u0bcd\u0b95\u0baa\u0bcd\u0baa' + '\u0bc2\u0bb0\u0bcd', 'te_IN': '\u0c2d\u0c3e\u0c30\u0c24 \u0c26\u0c47\u0c33\u0c02', 'tet_TL': 'Timor Leste', 'tg_Cyrl_TJ': '\u0422\u0430\u0434\u0436\u0438\u043a\u0438' + '\u0441\u0442\u0430\u043d', 'tg_TJ': '\u062a\u0627\u062c\u06a9\u0633\u062a\u0627\u0646', 'th_TH': '\u0e1b\u0e23\u0e30\u0e40\u0e17\u0e28\u0e44\u0e17' + '\u0e22', 'ti_ER': '\u12a4\u122d\u1275\u122b', 'ti_ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'tig_ER': '\u12a4\u122d\u1275\u122b', 'tk_TM': '\u062a\u0631\u06a9\u0645\u0646\u0633\u062a\u0627' + '\u0646', 'tkl_TK': 'Tokelau', 'tn_BW': 'Botswana', 'tn_ZA': 'South Africa', 'to_TO': 'Tonga', 'tpi_PG': 'Papua New Guinea', 'tr_CY': 'G\u00fcney K\u0131br\u0131s Rum Kesimi', 'tr_TR': 'T\u00fcrkiye', 'ts_ZA': 'South Africa', 'tt_RU': '\u0420\u043e\u0441\u0441\u0438\u044f', 'tvl_TV': 'Tuvalu', 'ty_PF': 'Polyn\u00e9sie fran\u00e7aise', 'uk_UA': '\u0423\u043a\u0440\u0430\u0457\u043d\u0430', 'uli_FM': 'Micronesia', 'und_ZZ': 'Unknown or Invalid Region', 'ur_IN': '\u0628\u06be\u0627\u0631\u062a', 'ur_PK': '\u067e\u0627\u06a9\u0633\u062a\u0627\u0646', 'uz_AF': 'Afganistan', 'uz_Arab_AF': '\u0627\u0641\u063a\u0627\u0646\u0633\u062a' + '\u0627\u0646', 'uz_Cyrl_UZ': '\u0423\u0437\u0431\u0435\u043a\u0438\u0441' + '\u0442\u0430\u043d', 'uz_Latn_UZ': 'O\u02bfzbekiston', 'uz_UZ': '\u040e\u0437\u0431\u0435\u043a\u0438\u0441\u0442' + '\u043e\u043d', 've_ZA': 'South Africa', 'vi_VN': 'Vi\u1ec7t Nam', 'wal_ET': '\u12a2\u1275\u12ee\u1335\u12eb', 'wo_Arab_SN': '\u0627\u0644\u0633\u0646\u063a\u0627\u0644', 'wo_Latn_SN': 'S\u00e9n\u00e9gal', 'wo_SN': 'S\u00e9n\u00e9gal', 'xh_ZA': 'South Africa', 'yap_FM': 'Micronesia', 'yo_NG': 'Nigeria', 'zh_CN': '\u4e2d\u56fd', 'zh_HK': '\u9999\u6e2f', 'zh_Hans_CN': '\u4e2d\u56fd', 'zh_Hans_SG': '\u65b0\u52a0\u5761', 'zh_Hant_HK': '\u4e2d\u83ef\u4eba\u6c11\u5171\u548c\u570b' + '\u9999\u6e2f\u7279\u5225\u884c\u653f\u5340', 'zh_Hant_MO': '\u6fb3\u9580', 'zh_Hant_TW': '\u81fa\u7063', 'zh_MO': '\u6fb3\u95e8', 'zh_SG': '\u65b0\u52a0\u5761', 'zh_TW': '\u53f0\u6e7e', 'zu_ZA': 'South Africa' }, 'LANGUAGE': { 'aa': 'afar', 'ab': '\u0430\u0431\u0445\u0430\u0437\u0441\u043a\u0438\u0439', 'ace': 'Aceh', 'ach': 'Acoli', 'ada': 'Adangme', 'ady': '\u0430\u0434\u044b\u0433\u0435\u0439\u0441\u043a' + '\u0438\u0439', 'ae': 'Avestan', 'af': 'Afrikaans', 'afa': 'Afro-Asiatic Language', 'afh': 'Afrihili', 'ain': 'Ainu', 'ak': 'Akan', 'akk': 'Akkadian', 'ale': 'Aleut', 'alg': 'Algonquian Language', 'alt': 'Southern Altai', 'am': '\u12a0\u121b\u122d\u129b', 'an': 'Aragonese', 'ang': 'Old English', 'anp': 'Angika', 'apa': 'Apache Language', 'ar': '\u0627\u0644\u0639\u0631\u0628\u064a\u0629', 'arc': 'Aramaic', 'arn': 'Araucanian', 'arp': 'Arapaho', 'art': 'Artificial Language', 'arw': 'Arawak', 'as': '\u0985\u09b8\u09ae\u09c0\u09af\u09bc\u09be', 'ast': 'asturiano', 'ath': 'Athapascan Language', 'aus': 'Australian Language', 'av': '\u0430\u0432\u0430\u0440\u0441\u043a\u0438\u0439', 'awa': 'Awadhi', 'ay': 'aimara', 'az': 'az\u0259rbaycanca', 'az_Arab': '\u062a\u0631\u06a9\u06cc \u0622\u0630\u0631\u0628' + '\u0627\u06cc\u062c\u0627\u0646\u06cc', 'az_Cyrl': '\u0410\u0437\u04d9\u0440\u0431\u0430\u0458\u04b9' + '\u0430\u043d', 'az_Latn': 'Azerice', 'ba': '\u0431\u0430\u0448\u043a\u0438\u0440\u0441\u043a\u0438' + '\u0439', 'bad': 'Banda', 'bai': 'Bamileke Language', 'bal': '\u0628\u0644\u0648\u0686\u06cc', 'ban': 'Balin', 'bas': 'Basa', 'bat': 'Baltic Language', 'be': '\u0431\u0435\u043b\u0430\u0440\u0443\u0441\u043a\u0430' + '\u044f', 'bej': 'Beja', 'bem': 'Bemba', 'ber': 'Berber', 'bg': '\u0431\u044a\u043b\u0433\u0430\u0440\u0441\u043a\u0438', 'bh': '\u092c\u093f\u0939\u093e\u0930\u0940', 'bho': 'Bhojpuri', 'bi': 'bichelamar ; bislama', 'bik': 'Bikol', 'bin': 'Bini', 'bla': 'Siksika', 'bm': 'bambara', 'bn': '\u09ac\u09be\u0982\u09b2\u09be', 'bnt': 'Bantu', 'bo': '\u0f54\u0f7c\u0f51\u0f0b\u0f66\u0f90\u0f51\u0f0b', 'br': 'breton', 'bra': 'Braj', 'bs': 'Bosanski', 'btk': 'Batak', 'bua': 'Buriat', 'bug': 'Bugis', 'byn': '\u1265\u120a\u1295', 'ca': 'catal\u00e0', 'cad': 'Caddo', 'cai': 'Central American Indian Language', 'car': 'Carib', 'cau': 'Caucasian Language', 'cch': 'Atsam', 'ce': '\u0447\u0435\u0447\u0435\u043d\u0441\u043a\u0438\u0439', 'ceb': 'Cebuano', 'cel': 'Celtic Language', 'ch': 'Chamorro', 'chb': 'Chibcha', 'chg': 'Chagatai', 'chk': 'Chuukese', 'chm': '\u043c\u0430\u0440\u0438\u0439\u0441\u043a\u0438' + '\u0439 (\u0447\u0435\u0440\u0435\u043c\u0438\u0441' + '\u0441\u043a\u0438\u0439)', 'chn': 'Chinook Jargon', 'cho': 'Choctaw', 'chp': 'Chipewyan', 'chr': 'Cherokee', 'chy': 'Cheyenne', 'cmc': 'Chamic Language', 'co': 'corse', 'cop': '\u0642\u0628\u0637\u064a\u0629', 'cop_Arab': '\u0642\u0628\u0637\u064a\u0629', 'cpe': 'English-based Creole or Pidgin', 'cpf': 'French-based Creole or Pidgin', 'cpp': 'Portuguese-based Creole or Pidgin', 'cr': 'Cree', 'crh': 'Crimean Turkish', 'crp': 'Creole or Pidgin', 'cs': '\u010de\u0161tina', 'csb': 'Kashubian', 'cu': 'Church Slavic', 'cus': 'Cushitic Language', 'cv': '\u0447\u0443\u0432\u0430\u0448\u0441\u043a\u0438\u0439', 'cy': 'Cymraeg', 'da': 'dansk', 'dak': 'Dakota', 'dar': '\u0434\u0430\u0440\u0433\u0432\u0430', 'day': 'Dayak', 'de': 'Deutsch', 'del': 'Delaware', 'den': 'Slave', 'dgr': 'Dogrib', 'din': 'Dinka', 'doi': '\u0627\u0644\u062f\u0648\u062c\u0631\u0649', 'dra': 'Dravidian Language', 'dsb': 'Lower Sorbian', 'dua': 'Duala', 'dum': 'Middle Dutch', 'dv': 'Divehi', 'dyu': 'dioula', 'dz': '\u0f62\u0fab\u0f7c\u0f44\u0f0b\u0f41', 'ee': 'Ewe', 'efi': 'Efik', 'egy': 'Ancient Egyptian', 'eka': 'Ekajuk', 'el': '\u0395\u03bb\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac', 'elx': 'Elamite', 'en': 'English', 'enm': 'Middle English', 'eo': 'esperanto', 'es': 'espa\u00f1ol', 'et': 'eesti', 'eu': 'euskara', 'ewo': 'Ewondo', 'fa': '\u0641\u0627\u0631\u0633\u06cc', 'fan': 'fang', 'fat': 'Fanti', 'ff': 'Fulah', 'fi': 'suomi', 'fil': 'Filipino', 'fiu': 'Finno-Ugrian Language', 'fj': 'Fijian', 'fo': 'f\u00f8royskt', 'fon': 'Fon', 'fr': 'fran\u00e7ais', 'frm': 'Middle French', 'fro': 'Old French', 'frr': 'Northern Frisian', 'frs': 'Eastern Frisian', 'fur': 'friulano', 'fy': 'Fries', 'ga': 'Gaeilge', 'gaa': 'Ga', 'gay': 'Gayo', 'gba': 'Gbaya', 'gd': 'Scottish Gaelic', 'gem': 'Germanic Language', 'gez': '\u130d\u12d5\u12dd\u129b', 'gil': 'Gilbertese', 'gl': 'galego', 'gmh': 'Middle High German', 'gn': 'guaran\u00ed', 'goh': 'Old High German', 'gon': 'Gondi', 'gor': 'Gorontalo', 'got': 'Gothic', 'grb': 'Grebo', 'grc': '\u0391\u03c1\u03c7\u03b1\u03af\u03b1 \u0395\u03bb' + '\u03bb\u03b7\u03bd\u03b9\u03ba\u03ac', 'gsw': 'Schweizerdeutsch', 'gu': '\u0a97\u0ac1\u0a9c\u0ab0\u0abe\u0aa4\u0ac0', 'gv': 'Gaelg', 'gwi': 'Gwich\u02bcin', 'ha': '\u0627\u0644\u0647\u0648\u0633\u0627', 'ha_Arab': '\u0627\u0644\u0647\u0648\u0633\u0627', 'ha_Latn': 'haoussa', 'hai': 'Haida', 'haw': '\u02bb\u014dlelo Hawai\u02bbi', 'he': '\u05e2\u05d1\u05e8\u05d9\u05ea', 'hi': '\u0939\u093f\u0902\u0926\u0940', 'hil': 'Hiligaynon', 'him': 'Himachali', 'hit': 'Hittite', 'hmn': 'Hmong', 'ho': 'Hiri Motu', 'hr': 'hrvatski', 'hsb': 'Upper Sorbian', 'ht': 'ha\u00eftien', 'hu': 'magyar', 'hup': 'Hupa', 'hy': '\u0540\u0561\u0575\u0565\u0580\u0567\u0576', 'hz': 'Herero', 'ia': 'interlingvao', 'iba': 'Iban', 'id': 'Bahasa Indonesia', 'ie': 'Interlingue', 'ig': 'Igbo', 'ii': '\ua188\ua320\ua259', 'ijo': 'Ijo', 'ik': 'Inupiaq', 'ilo': 'Iloko', 'inc': 'Indic Language', 'ine': 'Indo-European Language', 'inh': '\u0438\u043d\u0433\u0443\u0448\u0441\u043a\u0438' + '\u0439', 'io': 'Ido', 'ira': 'Iranian Language', 'iro': 'Iroquoian Language', 'is': '\u00edslenska', 'it': 'italiano', 'iu': 'Inuktitut', 'ja': '\u65e5\u672c\u8a9e', 'jbo': 'Lojban', 'jpr': 'Judeo-Persian', 'jrb': 'Judeo-Arabic', 'jv': 'Jawa', 'ka': '\u10e5\u10d0\u10e0\u10d7\u10e3\u10da\u10d8', 'kaa': '\u043a\u0430\u0440\u0430\u043a\u0430\u043b\u043f' + '\u0430\u043a\u0441\u043a\u0438\u0439', 'kab': 'kabyle', 'kac': 'Kachin', 'kaj': 'Jju', 'kam': 'Kamba', 'kar': 'Karen', 'kaw': 'Kawi', 'kbd': '\u043a\u0430\u0431\u0430\u0440\u0434\u0438\u043d' + '\u0441\u043a\u0438\u0439', 'kcg': 'Tyap', 'kfo': 'koro', 'kg': 'Kongo', 'kha': 'Khasi', 'khi': 'Khoisan Language', 'kho': 'Khotanese', 'ki': 'Kikuyu', 'kj': 'Kuanyama', 'kk': '\u049a\u0430\u0437\u0430\u049b', 'kl': 'kalaallisut', 'km': '\u1797\u17b6\u179f\u17b6\u1781\u17d2\u1798\u17c2\u179a', 'kmb': 'quimbundo', 'kn': '\u0c95\u0ca8\u0ccd\u0ca8\u0ca1', 'ko': '\ud55c\uad6d\uc5b4', 'kok': '\u0915\u094b\u0902\u0915\u0923\u0940', 'kos': 'Kosraean', 'kpe': 'kpell\u00e9', 'kr': 'Kanuri', 'krc': '\u043a\u0430\u0440\u0430\u0447\u0430\u0435\u0432' + '\u043e-\u0431\u0430\u043b\u043a\u0430\u0440\u0441' + '\u043a\u0438\u0439', 'krl': '\u043a\u0430\u0440\u0435\u043b\u044c\u0441\u043a' + '\u0438\u0439', 'kro': 'Kru', 'kru': 'Kurukh', 'ks': '\u0915\u093e\u0936\u094d\u092e\u093f\u0930\u0940', 'ku': 'K\u00fcrt\u00e7e', 'ku_Arab': '\u0627\u0644\u0643\u0631\u062f\u064a\u0629', 'ku_Latn': 'K\u00fcrt\u00e7e', 'kum': '\u043a\u0443\u043c\u044b\u043a\u0441\u043a\u0438' + '\u0439', 'kut': 'Kutenai', 'kv': 'Komi', 'kw': 'kernewek', 'ky': 'K\u0131rg\u0131zca', 'ky_Arab': '\u0627\u0644\u0642\u064a\u0631\u063a\u0633\u062a' + '\u0627\u0646\u064a\u0629', 'ky_Cyrl': '\u043a\u0438\u0440\u0433\u0438\u0437\u0441\u043a' + '\u0438\u0439', 'la': 'latino', 'lad': '\u05dc\u05d3\u05d9\u05e0\u05d5', 'lah': '\u0644\u0627\u0647\u0646\u062f\u0627', 'lam': 'Lamba', 'lb': 'luxembourgeois', 'lez': '\u043b\u0435\u0437\u0433\u0438\u043d\u0441\u043a' + '\u0438\u0439', 'lg': 'Ganda', 'li': 'Limburgs', 'ln': 'lingala', 'lo': 'Lao', 'lol': 'mongo', 'loz': 'Lozi', 'lt': 'lietuvi\u0173', 'lu': 'luba-katanga', 'lua': 'luba-lulua', 'lui': 'Luiseno', 'lun': 'Lunda', 'luo': 'Luo', 'lus': 'Lushai', 'lv': 'latvie\u0161u', 'mad': 'Madura', 'mag': 'Magahi', 'mai': 'Maithili', 'mak': 'Makassar', 'man': 'Mandingo', 'map': 'Austronesian', 'mas': 'Masai', 'mdf': '\u043c\u043e\u043a\u0448\u0430', 'mdr': 'Mandar', 'men': 'Mende', 'mg': 'malgache', 'mga': 'Middle Irish', 'mh': 'Marshallese', 'mi': 'Maori', 'mic': 'Micmac', 'min': 'Minangkabau', 'mis': 'Miscellaneous Language', 'mk': '\u043c\u0430\u043a\u0435\u0434\u043e\u043d\u0441\u043a' + '\u0438', 'mkh': 'Mon-Khmer Language', 'ml': '\u0d2e\u0d32\u0d2f\u0d3e\u0d33\u0d02', 'mn': '\u043c\u043e\u043d\u0433\u043e\u043b\u044c\u0441\u043a' + '\u0438\u0439', 'mn_Cyrl': '\u043c\u043e\u043d\u0433\u043e\u043b\u044c\u0441' + '\u043a\u0438\u0439', 'mn_Mong': '\u043c\u043e\u043d\u0433\u043e\u043b\u044c\u0441' + '\u043a\u0438\u0439', 'mnc': 'Manchu', 'mni': 'Manipuri', 'mno': 'Manobo Language', 'mo': 'Moldavian', 'moh': 'Mohawk', 'mos': 'mor\u00e9 ; mossi', 'mr': '\u092e\u0930\u093e\u0920\u0940', 'ms': 'Bahasa Melayu', 'mt': 'Malti', 'mul': 'Multiple Languages', 'mun': 'Munda Language', 'mus': 'Creek', 'mwl': 'Mirandese', 'mwr': 'Marwari', 'my': 'Burmese', 'myn': 'Mayan Language', 'myv': '\u044d\u0440\u0437\u044f', 'na': 'Nauru', 'nah': 'Nahuatl', 'nai': 'North American Indian Language', 'nap': 'napoletano', 'nb': 'norsk bokm\u00e5l', 'nd': 'North Ndebele', 'nds': 'Low German', 'ne': '\u0928\u0947\u092a\u093e\u0932\u0940', 'new': 'Newari', 'ng': 'Ndonga', 'nia': 'Nias', 'nic': 'Niger-Kordofanian Language', 'niu': 'Niuean', 'nl': 'Nederlands', 'nn': 'nynorsk', 'no': 'Norwegian', 'nog': '\u043d\u043e\u0433\u0430\u0439\u0441\u043a\u0438' + '\u0439', 'non': 'Old Norse', 'nqo': 'N\u2019Ko', 'nr': 'South Ndebele', 'nso': 'Northern Sotho', 'nub': 'Nubian Language', 'nv': 'Navajo', 'nwc': 'Classical Newari', 'ny': 'nianja; chicheua; cheua', 'nym': 'Nyamwezi', 'nyn': 'Nyankole', 'nyo': 'Nyoro', 'nzi': 'Nzima', 'oc': 'occitan', 'oj': 'Ojibwa', 'om': 'Oromoo', 'or': '\u0b13\u0b21\u0b3c\u0b3f\u0b06', 'os': '\u043e\u0441\u0435\u0442\u0438\u043d\u0441\u043a\u0438' + '\u0439', 'osa': 'Osage', 'ota': 'Ottoman Turkish', 'oto': 'Otomian Language', 'pa': '\u0a2a\u0a70\u0a1c\u0a3e\u0a2c\u0a40', 'pa_Arab': '\u067e\u0646\u062c\u0627\u0628', 'pa_Guru': '\u0a2a\u0a70\u0a1c\u0a3e\u0a2c\u0a40', 'paa': 'Papuan Language', 'pag': 'Pangasinan', 'pal': 'Pahlavi', 'pam': 'Pampanga', 'pap': 'Papiamento', 'pau': 'Palauan', 'peo': 'Old Persian', 'phi': 'Philippine Language', 'phn': 'Phoenician', 'pi': '\u0e1a\u0e32\u0e25\u0e35', 'pl': 'polski', 'pon': 'Pohnpeian', 'pra': 'Prakrit Language', 'pro': 'Old Proven\u00e7al', 'ps': '\u067e\u069a\u062a\u0648', 'pt': 'portugu\u00eas', 'qu': 'quechua', 'raj': 'Rajasthani', 'rap': 'Rapanui', 'rar': 'Rarotongan', 'rm': 'R\u00e4toromanisch', 'rn': 'roundi', 'ro': 'rom\u00e2n\u0103', 'roa': 'Romance Language', 'rom': 'Romany', 'ru': '\u0440\u0443\u0441\u0441\u043a\u0438\u0439', 'rup': 'Aromanian', 'rw': 'rwanda', 'sa': '\u0938\u0902\u0938\u094d\u0915\u0943\u0924 \u092d' + '\u093e\u0937\u093e', 'sad': 'Sandawe', 'sah': '\u044f\u043a\u0443\u0442\u0441\u043a\u0438\u0439', 'sai': 'South American Indian Language', 'sal': 'Salishan Language', 'sam': '\u05d0\u05e8\u05de\u05d9\u05ea \u05e9\u05d5\u05de' + '\u05e8\u05d5\u05e0\u05d9\u05ea', 'sas': 'Sasak', 'sat': 'Santali', 'sc': 'Sardinian', 'scn': 'siciliano', 'sco': 'Scots', 'sd': '\u0938\u093f\u0928\u094d\u0927\u0940', 'sd_Arab': '\u0633\u0646\u062f\u06cc', 'sd_Deva': '\u0938\u093f\u0928\u094d\u0927\u0940', 'se': 'nordsamiska', 'sel': '\u0441\u0435\u043b\u044c\u043a\u0443\u043f\u0441' + '\u043a\u0438\u0439', 'sem': 'Semitic Language', 'sg': 'sangho', 'sga': 'Old Irish', 'sgn': 'Sign Language', 'sh': 'Serbo-Croatian', 'shn': 'Shan', 'si': 'Sinhalese', 'sid': 'Sidamo', 'sio': 'Siouan Language', 'sit': 'Sino-Tibetan Language', 'sk': 'slovensk\u00fd', 'sl': 'sloven\u0161\u010dina', 'sla': 'Slavic Language', 'sm': 'Samoan', 'sma': 'sydsamiska', 'smi': 'Sami Language', 'smj': 'lulesamiska', 'smn': 'Inari Sami', 'sms': 'Skolt Sami', 'sn': 'Shona', 'snk': 'sonink\u00e9', 'so': 'Soomaali', 'sog': 'Sogdien', 'son': 'Songhai', 'sq': 'shqipe', 'sr': '\u0421\u0440\u043f\u0441\u043a\u0438', 'sr_Cyrl': '\u0441\u0435\u0440\u0431\u0441\u043a\u0438\u0439', 'sr_Latn': 'Srpski', 'srn': 'Sranantongo', 'srr': 's\u00e9r\u00e8re', 'ss': 'Swati', 'ssa': 'Nilo-Saharan Language', 'st': 'Sesotho', 'su': 'Sundan', 'suk': 'Sukuma', 'sus': 'soussou', 'sux': 'Sumerian', 'sv': 'svenska', 'sw': 'Kiswahili', 'syc': 'Classical Syriac', 'syr': 'Syriac', 'ta': '\u0ba4\u0bae\u0bbf\u0bb4\u0bcd', 'tai': 'Tai Language', 'te': '\u0c24\u0c46\u0c32\u0c41\u0c17\u0c41', 'tem': 'Timne', 'ter': 'Tereno', 'tet': 't\u00e9tum', 'tg': '\u062a\u0627\u062c\u06a9', 'tg_Arab': '\u062a\u0627\u062c\u06a9', 'tg_Cyrl': '\u0442\u0430\u0434\u0436\u0438\u043a\u0441\u043a' + '\u0438\u0439', 'th': '\u0e44\u0e17\u0e22', 'ti': '\u1275\u130d\u122d\u129b', 'tig': '\u1275\u130d\u1228', 'tiv': 'Tiv', 'tk': '\u062a\u0631\u06a9\u0645\u0646\u06cc', 'tkl': 'Tokelau', 'tl': 'Tagalog', 'tlh': 'Klingon', 'tli': 'Tlingit', 'tmh': 'tamacheq', 'tn': 'Tswana', 'to': 'Tonga', 'tog': 'Nyasa Tonga', 'tpi': 'Tok Pisin', 'tr': 'T\u00fcrk\u00e7e', 'ts': 'Tsonga', 'tsi': 'Tsimshian', 'tt': '\u0442\u0430\u0442\u0430\u0440\u0441\u043a\u0438\u0439', 'tum': 'Tumbuka', 'tup': 'Tupi Language', 'tut': '\u0430\u043b\u0442\u0430\u0439\u0441\u043a\u0438' + '\u0435 (\u0434\u0440\u0443\u0433\u0438\u0435)', 'tvl': 'Tuvalu', 'tw': 'Twi', 'ty': 'tahitien', 'tyv': '\u0442\u0443\u0432\u0438\u043d\u0441\u043a\u0438' + '\u0439', 'udm': '\u0443\u0434\u043c\u0443\u0440\u0442\u0441\u043a' + '\u0438\u0439', 'ug': '\u0443\u0439\u0433\u0443\u0440\u0441\u043a\u0438\u0439', 'uga': 'Ugaritic', 'uk': '\u0443\u043a\u0440\u0430\u0457\u043d\u0441\u044c\u043a' + '\u0430', 'umb': 'umbundu', 'und': 'English', 'ur': '\u0627\u0631\u062f\u0648', 'uz': '\u040e\u0437\u0431\u0435\u043a', 'uz_Arab': '\u0627\u06c9\u0632\u0628\u06d0\u06a9', 'uz_Cyrl': '\u0443\u0437\u0431\u0435\u043a\u0441\u043a\u0438' + '\u0439', 'uz_Latn': 'o\'zbekcha', 'vai': 'Vai', 've': 'Venda', 'vi': 'Ti\u1ebfng Vi\u1ec7t', 'vo': 'volapuko', 'vot': 'Votic', 'wa': 'Wallonisch', 'wak': 'Wakashan Language', 'wal': 'Walamo', 'war': 'Waray', 'was': 'Washo', 'wen': 'Sorbian Language', 'wo': 'wolof', 'wo_Arab': '\u0627\u0644\u0648\u0644\u0648\u0641', 'wo_Latn': 'wolof', 'xal': '\u043a\u0430\u043b\u043c\u044b\u0446\u043a\u0438' + '\u0439', 'xh': 'Xhosa', 'yao': 'iao', 'yap': 'Yapese', 'yi': '\u05d9\u05d9\u05d3\u05d9\u05e9', 'yo': 'Yoruba', 'ypk': 'Yupik Language', 'za': 'Zhuang', 'zap': 'Zapotec', 'zen': 'Zenaga', 'zh': '\u4e2d\u6587', 'zh_Hans': '\u4e2d\u6587', 'zh_Hant': '\u4e2d\u6587', 'znd': 'Zande', 'zu': 'Zulu', 'zun': 'Zuni', 'zxx': 'No linguistic content', 'zza': 'Zaza' } }; /* ~!@# END #@!~ */
// moment.js language configuration // language : canadian english (en-ca) // author : Jonathan Abourbih : https://github.com/jonbca (function (factory) { if (typeof define === 'function' && define.amd) { define(['moment'], factory); // AMD } else if (typeof exports === 'object') { module.exports = factory(require('../moment')); // Node } else { factory(window.moment); // Browser global } }(function (moment) { return moment.lang('en-ca', { months : "January_February_March_April_May_June_July_August_September_October_November_December".split("_"), monthsShort : "Jan_Feb_Mar_Apr_May_Jun_Jul_Aug_Sep_Oct_Nov_Dec".split("_"), weekdays : "Sunday_Monday_Tuesday_Wednesday_Thursday_Friday_Saturday".split("_"), weekdaysShort : "Sun_Mon_Tue_Wed_Thu_Fri_Sat".split("_"), weekdaysMin : "Su_Mo_Tu_We_Th_Fr_Sa".split("_"), longDateFormat : { LT : "h:mm A", L : "YYYY-MM-DD", LL : "D MMMM, YYYY", LLL : "D MMMM, YYYY LT", LLLL : "dddd, D MMMM, YYYY LT" }, calendar : { sameDay : '[Today at] LT', nextDay : '[Tomorrow at] LT', nextWeek : 'dddd [at] LT', lastDay : '[Yesterday at] LT', lastWeek : '[Last] dddd [at] LT', sameElse : 'L' }, relativeTime : { future : "in %s", past : "%s ago", s : "a few seconds", m : "a minute", mm : "%d minutes", h : "an hour", hh : "%d hours", d : "a day", dd : "%d days", M : "a month", MM : "%d months", y : "a year", yy : "%d years" }, ordinal : function (number) { var b = number % 10, output = (~~ (number % 100 / 10) === 1) ? 'th' : (b === 1) ? 'st' : (b === 2) ? 'nd' : (b === 3) ? 'rd' : 'th'; return number + output; } }); }));
//! moment.js locale configuration //! locale : Punjabi (India) [pa-in] //! author : Harpreet Singh : https://github.com/harpreetkhalsagtbit ;(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' && typeof require === 'function' ? factory(require('../moment')) : typeof define === 'function' && define.amd ? define(['../moment'], factory) : factory(global.moment) }(this, function (moment) { 'use strict'; var symbolMap = { '1': '੧', '2': '੨', '3': '੩', '4': '੪', '5': '੫', '6': '੬', '7': '੭', '8': '੮', '9': '੯', '0': '੦' }, numberMap = { '੧': '1', '੨': '2', '੩': '3', '੪': '4', '੫': '5', '੬': '6', '੭': '7', '੮': '8', '੯': '9', '੦': '0' }; var pa_in = moment.defineLocale('pa-in', { // There are months name as per Nanakshahi Calender but they are not used as rigidly in modern Punjabi. months : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), monthsShort : 'ਜਨਵਰੀ_ਫ਼ਰਵਰੀ_ਮਾਰਚ_ਅਪ੍ਰੈਲ_ਮਈ_ਜੂਨ_ਜੁਲਾਈ_ਅਗਸਤ_ਸਤੰਬਰ_ਅਕਤੂਬਰ_ਨਵੰਬਰ_ਦਸੰਬਰ'.split('_'), weekdays : 'ਐਤਵਾਰ_ਸੋਮਵਾਰ_ਮੰਗਲਵਾਰ_ਬੁਧਵਾਰ_ਵੀਰਵਾਰ_ਸ਼ੁੱਕਰਵਾਰ_ਸ਼ਨੀਚਰਵਾਰ'.split('_'), weekdaysShort : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), weekdaysMin : 'ਐਤ_ਸੋਮ_ਮੰਗਲ_ਬੁਧ_ਵੀਰ_ਸ਼ੁਕਰ_ਸ਼ਨੀ'.split('_'), longDateFormat : { LT : 'A h:mm ਵਜੇ', LTS : 'A h:mm:ss ਵਜੇ', L : 'DD/MM/YYYY', LL : 'D MMMM YYYY', LLL : 'D MMMM YYYY, A h:mm ਵਜੇ', LLLL : 'dddd, D MMMM YYYY, A h:mm ਵਜੇ' }, calendar : { sameDay : '[ਅਜ] LT', nextDay : '[ਕਲ] LT', nextWeek : 'dddd, LT', lastDay : '[ਕਲ] LT', lastWeek : '[ਪਿਛਲੇ] dddd, LT', sameElse : 'L' }, relativeTime : { future : '%s ਵਿੱਚ', past : '%s ਪਿਛਲੇ', s : 'ਕੁਝ ਸਕਿੰਟ', m : 'ਇਕ ਮਿੰਟ', mm : '%d ਮਿੰਟ', h : 'ਇੱਕ ਘੰਟਾ', hh : '%d ਘੰਟੇ', d : 'ਇੱਕ ਦਿਨ', dd : '%d ਦਿਨ', M : 'ਇੱਕ ਮਹੀਨਾ', MM : '%d ਮਹੀਨੇ', y : 'ਇੱਕ ਸਾਲ', yy : '%d ਸਾਲ' }, preparse: function (string) { return string.replace(/[੧੨੩੪੫੬੭੮੯੦]/g, function (match) { return numberMap[match]; }); }, postformat: function (string) { return string.replace(/\d/g, function (match) { return symbolMap[match]; }); }, // Punjabi notation for meridiems are quite fuzzy in practice. While there exists // a rigid notion of a 'Pahar' it is not used as rigidly in modern Punjabi. meridiemParse: /ਰਾਤ|ਸਵੇਰ|ਦੁਪਹਿਰ|ਸ਼ਾਮ/, meridiemHour : function (hour, meridiem) { if (hour === 12) { hour = 0; } if (meridiem === 'ਰਾਤ') { return hour < 4 ? hour : hour + 12; } else if (meridiem === 'ਸਵੇਰ') { return hour; } else if (meridiem === 'ਦੁਪਹਿਰ') { return hour >= 10 ? hour : hour + 12; } else if (meridiem === 'ਸ਼ਾਮ') { return hour + 12; } }, meridiem : function (hour, minute, isLower) { if (hour < 4) { return 'ਰਾਤ'; } else if (hour < 10) { return 'ਸਵੇਰ'; } else if (hour < 17) { return 'ਦੁਪਹਿਰ'; } else if (hour < 20) { return 'ਸ਼ਾਮ'; } else { return 'ਰਾਤ'; } }, week : { dow : 0, // Sunday is the first day of the week. doy : 6 // The week that contains Jan 1st is the first week of the year. } }); return pa_in; }));
/* * tablesorter pager plugin * updated 11/13/2011 */ (function($) { $.extend({tablesorterPager: new function() { // hide arrows at extremes var pagerArrows = function(c) { var a = 'addClass', r = 'removeClass', d = c.cssDisabled; if (c.updateArrows) { c.container[(c.totalRows < c.size) ? a : r](d); $(c.cssFirst + ',' + c.cssPrev, c.container)[(c.page === 0) ? a : r](d); $(c.cssNext + ',' + c.cssLast, c.container)[(c.page === c.totalPages - 1) ? a : r](d); } }, updatePageDisplay = function(table, c) { c.startRow = c.size * (c.page) + 1; c.endRow = Math.min(c.totalRows, c.size * (c.page+1)); var out = $(c.cssPageDisplay, c.container), // form the output string s = c.output.replace(/\{(page|totalPages|startRow|endRow|totalRows)\}/gi, function(m){ return { '{page}' : c.page + 1, '{totalPages}' : c.totalPages, '{startRow}' : c.startRow, '{endRow}' : c.endRow, '{totalRows}' : c.totalRows }[m]; }); if (out[0].tagName === 'INPUT') { out.val(s); } else { out.html(s); } pagerArrows(c); c.container.show(); // added in case the pager is reinitialized after being destroyed. $(table).trigger('pagerComplete', c); }, fixPosition = function(table, c) { var o = $(table); if (!c.pagerPositionSet && c.positionFixed) { if (o.offset) { c.container.css({ top: o.offset().top + o.height() + c.offset + 'px', position: 'absolute' }); } c.pagerPositionSet = true; } }, hideRows = function(table, c){ var i, rows = $('tr', table.tBodies[0]), l = rows.length, s = (c.page * c.size), e = (s + c.size); if (e > l) { e = l; } for (i = 0; i < l; i++){ rows[i].style.display = (i >= s && i < e) ? '' : 'none'; } }, hideRowsSetup = function(table, c){ c.size = parseInt($(c.cssPageSize, c.container).val(), 10); pagerArrows(c); if (!c.removeRows) { hideRows(table, c); $(table).bind('sortEnd.pager', function(){ hideRows(table, c); $(table).trigger("applyWidgets"); }); } }, renderTable = function(table, rows, c) { var i, j, o, tableBody = $(table.tBodies[0]), l = rows.length, s = (c.page * c.size), e = (s + c.size); $(table).trigger('pagerChange', c); if (!c.removeRows) { hideRows(table, c); } else { if (e > rows.length ) { e = rows.length; } // clear the table body $.tablesorter.clearTableBody(table); for (i = s; i < e; i++) { o = rows[i]; l = o.length; for (j = 0; j < l; j++) { tableBody[0].appendChild(o[j]); } } } fixPosition(table, tableBody, c); $(table).trigger("applyWidgets"); if ( c.page >= c.totalPages ) { moveToLastPage(table, c); } updatePageDisplay(table, c); }, showAllRows = function(table, c){ c.lastPage = c.page; c.size = c.totalRows; c.totalPages = 1; renderTable(table, c.rowsCopy, c); }, moveToPage = function(table, c) { if (c.isDisabled) { return; } if (c.page < 0 || c.page > (c.totalPages-1)) { c.page = 0; } renderTable(table, c.rowsCopy, c); }, setPageSize = function(table, size, c) { c.size = size; c.totalPages = Math.ceil(c.totalRows / c.size); c.pagerPositionSet = false; moveToPage(table, c); fixPosition(table, c); }, moveToFirstPage = function(table, c) { c.page = 0; moveToPage(table, c); }, moveToLastPage = function(table, c) { c.page = (c.totalPages-1); moveToPage(table, c); }, moveToNextPage = function(table, c) { c.page++; if (c.page >= (c.totalPages-1)) { c.page = (c.totalPages-1); } moveToPage(table, c); }, moveToPrevPage = function(table, c) { c.page--; if (c.page <= 0) { c.page = 0; } moveToPage(table, c); }, destroyPager = function(table, c){ showAllRows(table, c); c.container.hide(); // hide pager c.appender = null; // remove pager appender function $(table).unbind('destroy.pager sortEnd.pager enable.pager disable.pager'); }, enablePager = function(table, c){ c.isDisabled = false; $('table').trigger('update'); c.page = c.lastPage || 0; c.totalPages = Math.ceil(c.totalRows / c.size); hideRowsSetup(table, c); }; this.appender = function(table, rows) { var c = table.config; c.rowsCopy = rows; c.totalRows = rows.length; c.totalPages = Math.ceil(c.totalRows / c.size); renderTable(table, rows, c); }; this.defaults = { // target the pager markup container: null, // output default: '{page}/{totalPages}' output: '{startRow} to {endRow} of {totalRows} rows', // '{page}/{totalPages}' // apply disabled classname to the pager arrows when the rows at either extreme is visible updateArrows: true, // starting page of the pager (zero based index) page: 0, // Number of visible rows size: 10, // if true, moves the pager below the table at a fixed position; so if only 2 rows showing, the pager remains in the same place positionFixed: true, // offset added to the pager top, but only when "positionFixed" is true offset: 0, // remove rows from the table to speed up the sort of large tables. // setting this to false, only hides the non-visible rows; needed if you plan to add/remove rows with the pager enabled. removeRows: true, // removing rows in larger tables speeds up the sort // css class names of pager arrows cssNext: '.next', // next page arrow cssPrev: '.prev', // previous page arrow cssFirst: '.first', // first page arrow cssLast: '.last', // last page arrow cssPageDisplay: '.pagedisplay', // location of where the "output" is displayed cssPageSize: '.pagesize', // page size selector - select dropdown that sets the "size" option // class added to arrows when at the extremes (i.e. prev/first arrows are "disabled" when on the first page) cssDisabled: 'disabled', // Note there is no period "." in front of this class name // stuff not set by the user totalRows: 0, totalPages: 0, appender: this.appender }; this.construct = function(settings) { return this.each(function() { var c = $.extend(this.config, $.tablesorterPager.defaults, settings), table = this, pager = c.container; $(this).trigger("appendCache"); hideRowsSetup(table, c); $(c.cssFirst,pager).unbind('click.pager').bind('click.pager', function() { moveToFirstPage(table, c); return false; }); $(c.cssNext,pager).unbind('click.pager').bind('click.pager', function() { moveToNextPage(table, c); return false; }); $(c.cssPrev,pager).unbind('click.pager').bind('click.pager', function() { moveToPrevPage(table, c); return false; }); $(c.cssLast,pager).unbind('click.pager').bind('click.pager', function() { moveToLastPage(table, c); return false; }); $(c.cssPageSize,pager).unbind('change.pager').bind('change.pager', function() { setPageSize(table, parseInt($(this).val(), 10), c); return false; }); $(this) .unbind('disable.pager enable.pager destroy.pager') .bind('disable.pager', function(){ c.isDisabled = true; showAllRows(table, c); }) .bind('enable.pager', function(){ enablePager(table, c); }) .bind('destroy.pager', function(){ destroyPager(table, c); }); }); }; } }); // extend plugin scope $.fn.extend({ tablesorterPager: $.tablesorterPager.construct }); })(jQuery);
function(head, req) { var ddoc = this; var Mustache = require("vendor/couchapp/lib/mustache"), path = require("vendor/couchapp/lib/path").init(req), Atom = require("vendor/couchapp/lib/atom"); var templates = ddoc.templates; var assetPath = path.asset(), browsePath = path.list("browse", req.path[req.path.length-1], { startkey: [req.query.startkey[0]], endkey: [req.query.startkey[0], {}], include_docs:true, limit: 10, descending: true}); function sendRow(row) { var doc = row.doc; var summary = ''; if (doc.Summary && doc.Summary.length <= 350) { summary = doc.Summary; } else { summary = (doc.Summary.replace(/<(.|\n)*?>/g, '').substring(0,350) + '...'); } doc.Summary = summary; send(Mustache.to_html(templates.browse.row, { showPath: path.show("report", doc._id), doc: doc })); } provides("html", function() { var firstRow = getRow(), firstKey = firstRow.key, endKey = [], browseKey = req.query.startkey[0], prevKey = req.query.prevKey || [], viewName = req.path[req.path.length-1], limit = req.query.limit || 0; is_graph_date = (viewName == "by_date"); send(Mustache.to_html(templates.browse.header, { assetPath: assetPath, browsePath: browsePath, browseKey: browseKey, is_graph_date: is_graph_date })); if (typeof(prevKey) == "string") { prevKey = JSON.parse(prevKey); } var i = 1; sendRow(firstRow); while (row = getRow()) { sendRow(row); endKey = row.key; if (i < limit) endKey = row.key; i++; } if (i < limit) endKey = []; return Mustache.to_html(templates.browse.footer, { assetPath: assetPath, firstKey: JSON.stringify(firstKey), endKey: JSON.stringify(endKey), browseKey: browseKey, prevKey: JSON.stringify(prevKey), currentView: viewName, is_graph_date: is_graph_date }); }); }
/** Items controller **/ // Load dependencies var Boom = require('boom'); module.exports.get = function(request, reply) { // `this` - is a reference to sensihome scope this.items.get(request.params.id, function(err, items) { if (err) { return reply(err.toBoomError()); } // 200 : Success reply(items); }); }; module.exports.add = function(request, reply) { // `this` - is a reference to sensihome scope this.items.add(request.payload, function(err, item) { if (err) return reply(err.toBoomError()); // 201 : Created reply(item).code(201); }); }; module.exports.update = function(request, reply) { // `this` - is a reference to sensihome scope this.items.update(request.params.id, request.payload, function(err, item) { if (err) return reply(err.toBoomError()); // 200 : Success reply(item).code(200); }); }; module.exports.delete = function(request, reply) { // `this` - is a reference to sensihome scope this.items.delete(request.params.id, function(err) { if (err) return reply(err.toBoomError()); // 204 : No content reply().code(204); }); };
/* eslint-disable max-nested-callbacks */ 'use strict'; // eslint-disable-line const _ = require('lodash'); const assert = require('assert-diff'); const setupAPI = require('./setup-api'); const RippleAPI = require('ripple-api').RippleAPI; const validate = RippleAPI._PRIVATE.validate; const fixtures = require('./fixtures'); const requests = fixtures.requests; const responses = fixtures.responses; const addresses = require('./fixtures/addresses'); const hashes = require('./fixtures/hashes'); const address = addresses.ACCOUNT; const utils = RippleAPI._PRIVATE.ledgerUtils; const ledgerClosed = require('./fixtures/rippled/ledger-close-newer'); const schemaValidator = RippleAPI._PRIVATE.schemaValidator; const binary = require('ripple-binary-codec'); assert.options.strict = true; // how long before each test case times out const TIMEOUT = process.browser ? 25000 : 10000; function unused() { } function closeLedger(connection) { connection._ws.emit('message', JSON.stringify(ledgerClosed)); } function checkResult(expected, schemaName, response) { if (expected.txJSON) { assert(response.txJSON); assert.deepEqual(JSON.parse(response.txJSON), JSON.parse(expected.txJSON)); } assert.deepEqual(_.omit(response, 'txJSON'), _.omit(expected, 'txJSON')); if (schemaName) { schemaValidator.schemaValidate(schemaName, response); } return response; } describe('RippleAPI', function() { this.timeout(TIMEOUT); const instructions = {maxLedgerVersionOffset: 100}; beforeEach(setupAPI.setup); afterEach(setupAPI.teardown); it('error inspect', function() { const error = new this.api.errors.RippleError('mess', {data: 1}); assert.strictEqual(error.inspect(), '[RippleError(mess, { data: 1 })]'); }); describe('preparePayment', function() { it('normal', function() { const localInstructions = _.defaults({ maxFee: '0.000012' }, instructions); return this.api.preparePayment( address, requests.preparePayment.normal, localInstructions).then( _.partial(checkResult, responses.preparePayment.normal, 'prepare')); }); it('preparePayment - min amount xrp', function() { const localInstructions = _.defaults({ maxFee: '0.000012' }, instructions); return this.api.preparePayment( address, requests.preparePayment.minAmountXRP, localInstructions).then( _.partial(checkResult, responses.preparePayment.minAmountXRP, 'prepare')); }); it('preparePayment - min amount xrp2xrp', function() { return this.api.preparePayment( address, requests.preparePayment.minAmount, instructions).then( _.partial(checkResult, responses.preparePayment.minAmountXRPXRP, 'prepare')); }); it('preparePayment - XRP to XRP no partial', function() { assert.throws(() => { this.api.preparePayment(address, requests.preparePayment.wrongPartial); }, /XRP to XRP payments cannot be partial payments/); }); it('preparePayment - address must match payment.source.address', function( ) { assert.throws(() => { this.api.preparePayment(address, requests.preparePayment.wrongAddress); }, /address must match payment.source.address/); }); it('preparePayment - wrong amount', function() { assert.throws(() => { this.api.preparePayment(address, requests.preparePayment.wrongAmount); }, this.api.errors.ValidationError); }); it('preparePayment with all options specified', function() { return this.api.getLedgerVersion().then(ver => { const localInstructions = { maxLedgerVersion: ver + 100, fee: '0.000012' }; return this.api.preparePayment( address, requests.preparePayment.allOptions, localInstructions).then( _.partial(checkResult, responses.preparePayment.allOptions, 'prepare')); }); }); it('preparePayment without counterparty set', function() { const localInstructions = _.defaults({sequence: 23}, instructions); return this.api.preparePayment( address, requests.preparePayment.noCounterparty, localInstructions) .then(_.partial(checkResult, responses.preparePayment.noCounterparty, 'prepare')); }); it('preparePayment - destination.minAmount', function() { return this.api.preparePayment(address, responses.getPaths.sendAll[0], instructions).then(_.partial(checkResult, responses.preparePayment.minAmount, 'prepare')); }); }); it('prepareOrder - buy order', function() { const request = requests.prepareOrder.buy; return this.api.prepareOrder(address, request) .then(_.partial(checkResult, responses.prepareOrder.buy, 'prepare')); }); it('prepareOrder - buy order with expiration', function() { const request = requests.prepareOrder.expiration; const response = responses.prepareOrder.expiration; return this.api.prepareOrder(address, request, instructions) .then(_.partial(checkResult, response, 'prepare')); }); it('prepareOrder - sell order', function() { const request = requests.prepareOrder.sell; return this.api.prepareOrder(address, request, instructions).then( _.partial(checkResult, responses.prepareOrder.sell, 'prepare')); }); it('prepareOrderCancellation', function() { const request = requests.prepareOrderCancellation.simple; return this.api.prepareOrderCancellation(address, request, instructions) .then(_.partial(checkResult, responses.prepareOrderCancellation.normal, 'prepare')); }); it('prepareOrderCancellation - no instructions', function() { const request = requests.prepareOrderCancellation.simple; return this.api.prepareOrderCancellation(address, request) .then(_.partial(checkResult, responses.prepareOrderCancellation.noInstructions, 'prepare')); }); it('prepareOrderCancellation - with memos', function() { const request = requests.prepareOrderCancellation.withMemos; return this.api.prepareOrderCancellation(address, request) .then(_.partial(checkResult, responses.prepareOrderCancellation.withMemos, 'prepare')); }); it('prepareTrustline - simple', function() { return this.api.prepareTrustline( address, requests.prepareTrustline.simple, instructions).then( _.partial(checkResult, responses.prepareTrustline.simple, 'prepare')); }); it('prepareTrustline - frozen', function() { return this.api.prepareTrustline( address, requests.prepareTrustline.frozen).then( _.partial(checkResult, responses.prepareTrustline.frozen, 'prepare')); }); it('prepareTrustline - complex', function() { return this.api.prepareTrustline( address, requests.prepareTrustline.complex, instructions).then( _.partial(checkResult, responses.prepareTrustline.complex, 'prepare')); }); it('prepareSettings', function() { return this.api.prepareSettings( address, requests.prepareSettings.domain, instructions).then( _.partial(checkResult, responses.prepareSettings.flags, 'prepare')); }); it('prepareSettings - no maxLedgerVersion', function() { return this.api.prepareSettings( address, requests.prepareSettings.domain, {maxLedgerVersion: null}).then( _.partial(checkResult, responses.prepareSettings.noMaxLedgerVersion, 'prepare')); }); it('prepareSettings - no instructions', function() { return this.api.prepareSettings( address, requests.prepareSettings.domain).then( _.partial( checkResult, responses.prepareSettings.noInstructions, 'prepare')); }); it('prepareSettings - regularKey', function() { const regularKey = {regularKey: 'rAR8rR8sUkBoCZFawhkWzY4Y5YoyuznwD'}; return this.api.prepareSettings(address, regularKey, instructions).then( _.partial(checkResult, responses.prepareSettings.regularKey, 'prepare')); }); it('prepareSettings - remove regularKey', function() { const regularKey = {regularKey: null}; return this.api.prepareSettings(address, regularKey, instructions).then( _.partial(checkResult, responses.prepareSettings.removeRegularKey, 'prepare')); }); it('prepareSettings - flag set', function() { const settings = {requireDestinationTag: true}; return this.api.prepareSettings(address, settings, instructions).then( _.partial(checkResult, responses.prepareSettings.flagSet, 'prepare')); }); it('prepareSettings - flag clear', function() { const settings = {requireDestinationTag: false}; return this.api.prepareSettings(address, settings, instructions).then( _.partial(checkResult, responses.prepareSettings.flagClear, 'prepare')); }); it('prepareSettings - integer field clear', function() { const settings = {transferRate: null}; return this.api.prepareSettings(address, settings, instructions) .then(data => { assert(data); assert.strictEqual(JSON.parse(data.txJSON).TransferRate, 0); }); }); it('prepareSettings - set transferRate', function() { const settings = {transferRate: 1}; return this.api.prepareSettings(address, settings, instructions).then( _.partial(checkResult, responses.prepareSettings.setTransferRate, 'prepare')); }); it('prepareSettings - set signers', function() { const settings = requests.prepareSettings.signers; return this.api.prepareSettings(address, settings, instructions).then( _.partial(checkResult, responses.prepareSettings.signers, 'prepare')); }); it('prepareSettings - fee for multisign', function() { const localInstructions = _.defaults({ signersCount: 4 }, instructions); return this.api.prepareSettings( address, requests.prepareSettings.domain, localInstructions).then( _.partial(checkResult, responses.prepareSettings.flagsMultisign, 'prepare')); }); it('prepareSuspendedPaymentCreation', function() { const localInstructions = _.defaults({ maxFee: '0.000012' }, instructions); return this.api.prepareSuspendedPaymentCreation( address, requests.prepareSuspendedPaymentCreation.normal, localInstructions).then( _.partial(checkResult, responses.prepareSuspendedPaymentCreation.normal, 'prepare')); }); it('prepareSuspendedPaymentCreation full', function() { return this.api.prepareSuspendedPaymentCreation( address, requests.prepareSuspendedPaymentCreation.full).then( _.partial(checkResult, responses.prepareSuspendedPaymentCreation.full, 'prepare')); }); it('prepareSuspendedPaymentExecution', function() { return this.api.prepareSuspendedPaymentExecution( address, requests.prepareSuspendedPaymentExecution.normal, instructions).then( _.partial(checkResult, responses.prepareSuspendedPaymentExecution.normal, 'prepare')); }); it('prepareSuspendedPaymentExecution - simple', function() { return this.api.prepareSuspendedPaymentExecution( address, requests.prepareSuspendedPaymentExecution.simple).then( _.partial(checkResult, responses.prepareSuspendedPaymentExecution.simple, 'prepare')); }); it('prepareSuspendedPaymentCancellation', function() { return this.api.prepareSuspendedPaymentCancellation( address, requests.prepareSuspendedPaymentCancellation.normal, instructions).then( _.partial(checkResult, responses.prepareSuspendedPaymentCancellation.normal, 'prepare')); }); it('prepareSuspendedPaymentCancellation with memos', function() { return this.api.prepareSuspendedPaymentCancellation( address, requests.prepareSuspendedPaymentCancellation.memos).then( _.partial(checkResult, responses.prepareSuspendedPaymentCancellation.memos, 'prepare')); }); it('sign', function() { const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV'; const result = this.api.sign(requests.sign.normal.txJSON, secret); assert.deepEqual(result, responses.sign.normal); schemaValidator.schemaValidate('sign', result); }); it('sign - already signed', function() { const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV'; const result = this.api.sign(requests.sign.normal.txJSON, secret); assert.throws(() => { const tx = JSON.stringify(binary.decode(result.signedTransaction)); this.api.sign(tx, secret); }, /txJSON must not contain "TxnSignature" or "Signers" properties/); }); it('sign - SuspendedPaymentExecution', function() { const secret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb'; const result = this.api.sign(requests.sign.suspended.txJSON, secret); assert.deepEqual(result, responses.sign.suspended); schemaValidator.schemaValidate('sign', result); }); it('sign - signAs', function() { const txJSON = requests.sign.signAs; const secret = 'snoPBrXtMeMyMHUVTgbuqAfg1SUTb'; const signature = this.api.sign(JSON.stringify(txJSON), secret, {signAs: 'rHb9CJAWyB4rj91VRWn96DkukG4bwdtyTh'}); assert.deepEqual(signature, responses.sign.signAs); }); it('submit', function() { return this.api.submit(responses.sign.normal.signedTransaction).then( _.partial(checkResult, responses.submit, 'submit')); }); it('submit - failure', function() { return this.api.submit('BAD').then(() => { assert(false, 'Should throw RippledError'); }).catch(error => { assert(error instanceof this.api.errors.RippledError); assert.strictEqual(error.data.resultCode, 'temBAD_FEE'); }); }); it('combine', function() { const combined = this.api.combine(requests.combine.setDomain); checkResult(responses.combine.single, 'sign', combined); }); it('combine - different transactions', function() { const request = [requests.combine.setDomain[0]]; const tx = binary.decode(requests.combine.setDomain[0]); tx.Flags = 0; request.push(binary.encode(tx)); assert.throws(() => { this.api.combine(request); }, /txJSON is not the same for all signedTransactions/); }); describe('RippleAPI', function() { it('getBalances', function() { return this.api.getBalances(address).then( _.partial(checkResult, responses.getBalances, 'getBalances')); }); it('getBalances - limit', function() { const options = { limit: 3, ledgerVersion: 123456 }; const expectedResponse = responses.getBalances.slice(0, 3); return this.api.getBalances(address, options).then( _.partial(checkResult, expectedResponse, 'getBalances')); }); it('getBalances - limit & currency', function() { const options = { currency: 'USD', limit: 3 }; const expectedResponse = _.filter(responses.getBalances, item => item.currency === 'USD').slice(0, 3); return this.api.getBalances(address, options).then( _.partial(checkResult, expectedResponse, 'getBalances')); }); it('getBalances - limit & currency & issuer', function() { const options = { currency: 'USD', counterparty: 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B', limit: 3 }; const expectedResponse = _.filter(responses.getBalances, item => item.currency === 'USD' && item.counterparty === 'rvYAfWj5gh67oV6fW32ZzP3Aw4Eubs59B').slice(0, 3); return this.api.getBalances(address, options).then( _.partial(checkResult, expectedResponse, 'getBalances')); }); }); it('getBalanceSheet', function() { return this.api.getBalanceSheet(address).then( _.partial(checkResult, responses.getBalanceSheet, 'getBalanceSheet')); }); it('getBalanceSheet - invalid options', function() { assert.throws(() => { this.api.getBalanceSheet(address, {invalid: 'options'}); }, this.api.errors.ValidationError); }); it('getBalanceSheet - empty', function() { const options = {ledgerVersion: 123456}; return this.api.getBalanceSheet(address, options).then( _.partial(checkResult, {}, 'getBalanceSheet')); }); describe('getTransaction', () => { it('getTransaction - payment', function() { return this.api.getTransaction(hashes.VALID_TRANSACTION_HASH).then( _.partial(checkResult, responses.getTransaction.payment, 'getTransaction')); }); it('getTransaction - settings', function() { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.settings, 'getTransaction')); }); it('getTransaction - order', function() { const hash = '10A6FB4A66EE80BED46AAE4815D7DC43B97E944984CCD5B93BCF3F8538CABC51'; closeLedger(this.api.connection); return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.order, 'getTransaction')); }); it('getTransaction - sell order', function() { const hash = '458101D51051230B1D56E9ACAFAA34451BF65FA000F95DF6F0FF5B3A62D83FC2'; closeLedger(this.api.connection); return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.orderSell, 'getTransaction')); }); it('getTransaction - order cancellation', function() { const hash = '809335DD3B0B333865096217AA2F55A4DF168E0198080B3A090D12D88880FF0E'; closeLedger(this.api.connection); return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.orderCancellation, 'getTransaction')); }); it('getTransaction - order with expiration cancellation', function() { const hash = '097B9491CC76B64831F1FEA82EAA93BCD728106D90B65A072C933888E946C40B'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.orderWithExpirationCancellation, 'getTransaction')); }); it('getTransaction - trustline set', function() { const hash = '635A0769BD94710A1F6A76CDE65A3BC661B20B798807D1BBBDADCEA26420538D'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.trustline, 'getTransaction')); }); it('getTransaction - trustline frozen off', function() { const hash = 'FE72FAD0FA7CA904FB6C633A1666EDF0B9C73B2F5A4555D37EEF2739A78A531B'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.trustlineFrozenOff, 'getTransaction')); }); it('getTransaction - trustline no quality', function() { const hash = 'BAF1C678323C37CCB7735550C379287667D8288C30F83148AD3C1CB019FC9002'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.trustlineNoQuality, 'getTransaction')); }); it('getTransaction - not validated', function() { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA10'; return this.api.getTransaction(hash).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getTransaction - tracking on', function() { const hash = '8925FC8844A1E930E2CC76AD0A15E7665AFCC5425376D548BB1413F484C31B8C'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.trackingOn, 'getTransaction')); }); it('getTransaction - tracking off', function() { const hash = 'C8C5E20DFB1BF533D0D81A2ED23F0A3CBD1EF2EE8A902A1D760500473CC9C582'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.trackingOff, 'getTransaction')); }); it('getTransaction - set regular key', function() { const hash = '278E6687C1C60C6873996210A6523564B63F2844FB1019576C157353B1813E60'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.setRegularKey, 'getTransaction')); }); it('getTransaction - not found in range', function() { const hash = '809335DD3B0B333865096217AA2F55A4DF168E0198080B3A090D12D88880FF0E'; const options = { minLedgerVersion: 32570, maxLedgerVersion: 32571 }; return this.api.getTransaction(hash, options).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getTransaction - not found by hash', function() { const hash = hashes.NOTFOUND_TRANSACTION_HASH; return this.api.getTransaction(hash).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getTransaction - missing ledger history', function() { const hash = hashes.NOTFOUND_TRANSACTION_HASH; // make gaps in history closeLedger(this.api.connection); return this.api.getTransaction(hash).then(() => { assert(false, 'Should throw MissingLedgerHistoryError'); }).catch(error => { assert(error instanceof this.api.errors.MissingLedgerHistoryError); }); }); it('getTransaction - missing ledger history with ledger range', function() { const hash = hashes.NOTFOUND_TRANSACTION_HASH; const options = { minLedgerVersion: 32569, maxLedgerVersion: 32571 }; return this.api.getTransaction(hash, options).then(() => { assert(false, 'Should throw MissingLedgerHistoryError'); }).catch(error => { assert(error instanceof this.api.errors.MissingLedgerHistoryError); }); }); it('getTransaction - not found - future maxLedgerVersion', function() { const hash = hashes.NOTFOUND_TRANSACTION_HASH; const options = { maxLedgerVersion: 99999999999 }; return this.api.getTransaction(hash, options).then(() => { assert(false, 'Should throw PendingLedgerVersionError'); }).catch(error => { assert(error instanceof this.api.errors.PendingLedgerVersionError); }); }); it('getTransaction - ledger_index not found', function() { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11'; return this.api.getTransaction(hash).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); assert(error.message.indexOf('ledger_index') !== -1); }); }); it('getTransaction - transaction ledger not found', function() { const hash = '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA12'; return this.api.getTransaction(hash).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); assert(error.message.indexOf('ledger not found') !== -1); }); }); it('getTransaction - ledger missing close time', function() { const hash = '0F7ED9F40742D8A513AE86029462B7A6768325583DF8EE21B7EC663019DD6A04'; closeLedger(this.api.connection); return this.api.getTransaction(hash).then(() => { assert(false, 'Should throw UnexpectedError'); }).catch(error => { assert(error instanceof this.api.errors.UnexpectedError); }); }); it('getTransaction - SuspendedPaymentCreation', function() { const hash = '144F272380BDB4F1BD92329A2178BABB70C20F59042C495E10BF72EBFB408EE1'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.suspendedPaymentCreation, 'getTransaction')); }); it('getTransaction - SuspendedPaymentCreation iou', function() { const hash = '144F272380BDB4F1BD92329A2178BABB70C20F59042C495E10BF72EBFB408EE2'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.SuspendedPaymentCreationIOU, 'getTransaction')); }); it('getTransaction - SuspendedPaymentCancellation', function() { const hash = 'F346E542FFB7A8398C30A87B952668DAB48B7D421094F8B71776DA19775A3B22'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.suspendedPaymentCancellation, 'getTransaction')); }); it('getTransaction - SuspendedPaymentExecution', function() { const options = { minLedgerVersion: 10, maxLedgerVersion: 15 }; const hash = 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD136993B'; return this.api.getTransaction(hash, options).then( _.partial(checkResult, responses.getTransaction.suspendedPaymentExecution, 'getTransaction')); }); it('getTransaction - SuspendedPaymentExecution simple', function() { const hash = 'CC5277137B3F25EE8B86259C83CB0EAADE818505E4E9BCBF19B1AC6FD1369931'; return this.api.getTransaction(hash).then( _.partial(checkResult, responses.getTransaction.suspendedPaymentExecutionSimple, 'getTransaction')); }); it('getTransaction - no Meta', function() { const hash = 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA1B'; return this.api.getTransaction(hash).then(result => { assert.deepEqual(result, responses.getTransaction.noMeta); }); }); it('getTransaction - Unrecognized transaction type', function() { const hash = 'AFB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA11'; closeLedger(this.api.connection); return this.api.getTransaction(hash).then(() => { assert(false, 'Unrecognized transaction type'); }).catch(error => { assert.strictEqual(error.message, 'Unrecognized transaction type'); }); }); it('getTransaction - amendment', function() { const hash = 'A971B83ABED51D83749B73F3C1AAA627CD965AFF74BE8CD98299512D6FB0658F'; return this.api.getTransaction(hash).then(result => { assert.deepEqual(result, responses.getTransaction.amendment); }); }); it('getTransaction - feeUpdate', function() { const hash = 'C6A40F56127436DCD830B1B35FF939FD05B5747D30D6542572B7A835239817AF'; return this.api.getTransaction(hash).then(result => { assert.deepEqual(result, responses.getTransaction.feeUpdate); }); }); }); it('getTransactions', function() { const options = {types: ['payment', 'order'], initiated: true, limit: 2}; return this.api.getTransactions(address, options).then( _.partial(checkResult, responses.getTransactions.normal, 'getTransactions')); }); it('getTransactions - earliest first', function() { const options = {types: ['payment', 'order'], initiated: true, limit: 2, earliestFirst: true }; const expected = _.cloneDeep(responses.getTransactions.normal) .sort(utils.compareTransactions); return this.api.getTransactions(address, options).then( _.partial(checkResult, expected, 'getTransactions')); }); it('getTransactions - earliest first with start option', function() { const options = {types: ['payment', 'order'], initiated: true, limit: 2, start: hashes.VALID_TRANSACTION_HASH, earliestFirst: true }; return this.api.getTransactions(address, options).then(data => { assert.strictEqual(data.length, 0); }); }); it('getTransactions - gap', function() { const options = {types: ['payment', 'order'], initiated: true, limit: 2, maxLedgerVersion: 348858000 }; return this.api.getTransactions(address, options).then(() => { assert(false, 'Should throw MissingLedgerHistoryError'); }).catch(error => { assert(error instanceof this.api.errors.MissingLedgerHistoryError); }); }); it('getTransactions - tx not found', function() { const options = {types: ['payment', 'order'], initiated: true, limit: 2, start: hashes.NOTFOUND_TRANSACTION_HASH, counterparty: address }; return this.api.getTransactions(address, options).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getTransactions - filters', function() { const options = {types: ['payment', 'order'], initiated: true, limit: 10, excludeFailures: true, counterparty: addresses.ISSUER }; return this.api.getTransactions(address, options).then(data => { assert.strictEqual(data.length, 10); assert(_.every(data, t => t.type === 'payment' || t.type === 'order')); assert(_.every(data, t => t.outcome.result === 'tesSUCCESS')); }); }); it('getTransactions - filters for incoming', function() { const options = {types: ['payment', 'order'], initiated: false, limit: 10, excludeFailures: true, counterparty: addresses.ISSUER }; return this.api.getTransactions(address, options).then(data => { assert.strictEqual(data.length, 10); assert(_.every(data, t => t.type === 'payment' || t.type === 'order')); assert(_.every(data, t => t.outcome.result === 'tesSUCCESS')); }); }); // this is the case where core.RippleError just falls // through the api to the user it('getTransactions - error', function() { const options = {types: ['payment', 'order'], initiated: true, limit: 13}; return this.api.getTransactions(address, options).then(() => { assert(false, 'Should throw RippleError'); }).catch(error => { assert(error instanceof this.api.errors.RippleError); }); }); // TODO: this doesn't test much, just that it doesn't crash it('getTransactions with start option', function() { const options = { start: hashes.VALID_TRANSACTION_HASH, earliestFirst: false, limit: 2 }; return this.api.getTransactions(address, options).then( _.partial(checkResult, responses.getTransactions.normal, 'getTransactions')); }); it('getTransactions - start transaction with zero ledger version', function( ) { const options = { start: '4FB3ADF22F3C605E23FAEFAA185F3BD763C4692CAC490D9819D117CD33BFAA13', limit: 1 }; return this.api.getTransactions(address, options).then( _.partial(checkResult, [], 'getTransactions')); }); it('getTransactions - no options', function() { return this.api.getTransactions(addresses.OTHER_ACCOUNT).then( _.partial(checkResult, responses.getTransactions.one, 'getTransactions')); }); it('getTrustlines - filtered', function() { const options = {currency: 'USD'}; return this.api.getTrustlines(address, options).then( _.partial(checkResult, responses.getTrustlines.filtered, 'getTrustlines')); }); it('getTrustlines - no options', function() { return this.api.getTrustlines(address).then( _.partial(checkResult, responses.getTrustlines.all, 'getTrustlines')); }); it('generateAddress', function() { function random() { return _.fill(Array(16), 0); } assert.deepEqual(this.api.generateAddress({entropy: random()}), responses.generateAddress); }); it('generateAddress invalid', function() { assert.throws(() => { function random() { return _.fill(Array(1), 0); } this.api.generateAddress({entropy: random()}); }, this.api.errors.UnexpectedError); }); it('getSettings', function() { return this.api.getSettings(address).then( _.partial(checkResult, responses.getSettings, 'getSettings')); }); it('getSettings - options undefined', function() { return this.api.getSettings(address, undefined).then( _.partial(checkResult, responses.getSettings, 'getSettings')); }); it('getSettings - invalid options', function() { assert.throws(() => { this.api.getSettings(address, {invalid: 'options'}); }, this.api.errors.ValidationError); }); it('getAccountInfo', function() { return this.api.getAccountInfo(address).then( _.partial(checkResult, responses.getAccountInfo, 'getAccountInfo')); }); it('getAccountInfo - options undefined', function() { return this.api.getAccountInfo(address, undefined).then( _.partial(checkResult, responses.getAccountInfo, 'getAccountInfo')); }); it('getAccountInfo - invalid options', function() { assert.throws(() => { this.api.getAccountInfo(address, {invalid: 'options'}); }, this.api.errors.ValidationError); }); it('getOrders', function() { return this.api.getOrders(address).then( _.partial(checkResult, responses.getOrders, 'getOrders')); }); it('getOrders', function() { return this.api.getOrders(address, undefined).then( _.partial(checkResult, responses.getOrders, 'getOrders')); }); it('getOrders - invalid options', function() { assert.throws(() => { this.api.getOrders(address, {invalid: 'options'}); }, this.api.errors.ValidationError); }); describe('getOrderbook', function() { it('normal', function() { return this.api.getOrderbook(address, requests.getOrderbook.normal, undefined).then( _.partial(checkResult, responses.getOrderbook.normal, 'getOrderbook')); }); it('invalid options', function() { assert.throws(() => { this.api.getOrderbook(address, requests.getOrderbook.normal, {invalid: 'options'}); }, this.api.errors.ValidationError); }); it('with XRP', function() { return this.api.getOrderbook(address, requests.getOrderbook.withXRP).then( _.partial(checkResult, responses.getOrderbook.withXRP, 'getOrderbook')); }); it('sorted so that best deals come first', function() { return this.api.getOrderbook(address, requests.getOrderbook.normal) .then(data => { const bidRates = data.bids.map(bid => bid.properties.makerExchangeRate); const askRates = data.asks.map(ask => ask.properties.makerExchangeRate); // makerExchangeRate = quality = takerPays.value/takerGets.value // so the best deal for the taker is the lowest makerExchangeRate // bids and asks should be sorted so that the best deals come first assert.deepEqual(_.sortBy(bidRates, x => Number(x)), bidRates); assert.deepEqual(_.sortBy(askRates, x => Number(x)), askRates); }); }); it('currency & counterparty are correct', function() { return this.api.getOrderbook(address, requests.getOrderbook.normal) .then(data => { const orders = _.flatten([data.bids, data.asks]); _.forEach(orders, order => { const quantity = order.specification.quantity; const totalPrice = order.specification.totalPrice; const {base, counter} = requests.getOrderbook.normal; assert.strictEqual(quantity.currency, base.currency); assert.strictEqual(quantity.counterparty, base.counterparty); assert.strictEqual(totalPrice.currency, counter.currency); assert.strictEqual(totalPrice.counterparty, counter.counterparty); }); }); }); it('direction is correct for bids and asks', function() { return this.api.getOrderbook(address, requests.getOrderbook.normal) .then(data => { assert( _.every(data.bids, bid => bid.specification.direction === 'buy')); assert( _.every(data.asks, ask => ask.specification.direction === 'sell')); }); }); }); it('getServerInfo', function() { return this.api.getServerInfo().then( _.partial(checkResult, responses.getServerInfo, 'getServerInfo')); }); it('getServerInfo - error', function() { this.api.connection._send(JSON.stringify({ command: 'config', data: {returnErrorOnServerInfo: true} })); return this.api.getServerInfo().then(() => { assert(false, 'Should throw NetworkError'); }).catch(error => { assert(error instanceof this.api.errors.RippledError); assert(_.includes(error.message, 'slowDown')); }); }); it('getServerInfo - no validated ledger', function() { this.api.connection._send(JSON.stringify({ command: 'config', data: {serverInfoWithoutValidated: true} })); return this.api.getServerInfo().then(info => { assert.strictEqual(info.networkLedger, 'waiting'); }).catch(error => { assert(false, 'Should not throw Error, got ' + String(error)); }); }); it('getFee', function() { return this.api.getFee().then(fee => { assert.strictEqual(fee, '0.000012'); }); }); it('getFee default', function() { this.api._feeCushion = undefined; return this.api.getFee().then(fee => { assert.strictEqual(fee, '0.000012'); }); }); it('disconnect & isConnected', function() { assert.strictEqual(this.api.isConnected(), true); return this.api.disconnect().then(() => { assert.strictEqual(this.api.isConnected(), false); }); }); it('getPaths', function() { return this.api.getPaths(requests.getPaths.normal).then( _.partial(checkResult, responses.getPaths.XrpToUsd, 'getPaths')); }); it('getPaths - queuing', function() { return Promise.all([ this.api.getPaths(requests.getPaths.normal), this.api.getPaths(requests.getPaths.UsdToUsd), this.api.getPaths(requests.getPaths.XrpToXrp) ]).then(results => { checkResult(responses.getPaths.XrpToUsd, 'getPaths', results[0]); checkResult(responses.getPaths.UsdToUsd, 'getPaths', results[1]); checkResult(responses.getPaths.XrpToXrp, 'getPaths', results[2]); }); }); // @TODO // need decide what to do with currencies/XRP: // if add 'XRP' in currencies, then there will be exception in // xrpToDrops function (called from toRippledAmount) it('getPaths USD 2 USD', function() { return this.api.getPaths(requests.getPaths.UsdToUsd).then( _.partial(checkResult, responses.getPaths.UsdToUsd, 'getPaths')); }); it('getPaths XRP 2 XRP', function() { return this.api.getPaths(requests.getPaths.XrpToXrp).then( _.partial(checkResult, responses.getPaths.XrpToXrp, 'getPaths')); }); it('getPaths - source with issuer', function() { return this.api.getPaths(requests.getPaths.issuer).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getPaths - XRP 2 XRP - not enough', function() { return this.api.getPaths(requests.getPaths.XrpToXrpNotEnough).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getPaths - invalid PathFind', function() { assert.throws(() => { this.api.getPaths(requests.getPaths.invalid); }, /Cannot specify both source.amount/); }); it('getPaths - does not accept currency', function() { return this.api.getPaths(requests.getPaths.NotAcceptCurrency).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getPaths - no paths', function() { return this.api.getPaths(requests.getPaths.NoPaths).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getPaths - no paths source amount', function() { return this.api.getPaths(requests.getPaths.NoPathsSource).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getPaths - no paths with source currencies', function() { const pathfind = requests.getPaths.NoPathsWithCurrencies; return this.api.getPaths(pathfind).then(() => { assert(false, 'Should throw NotFoundError'); }).catch(error => { assert(error instanceof this.api.errors.NotFoundError); }); }); it('getPaths - error: srcActNotFound', function() { const pathfind = _.assign({}, requests.getPaths.normal, {source: {address: addresses.NOTFOUND}}); return this.api.getPaths(pathfind).catch(error => { assert(error instanceof this.api.errors.RippleError); }); }); it('getPaths - send all', function() { return this.api.getPaths(requests.getPaths.sendAll).then( _.partial(checkResult, responses.getPaths.sendAll, 'getPaths')); }); it('getLedgerVersion', function(done) { this.api.getLedgerVersion().then(ver => { assert.strictEqual(ver, 8819951); done(); }, done); }); it('getLedger', function() { return this.api.getLedger().then( _.partial(checkResult, responses.getLedger.header, 'getLedger')); }); it('getLedger - future ledger version', function() { return this.api.getLedger({ledgerVersion: 14661789}).then(() => { assert(false, 'Should throw LedgerVersionError'); }).catch(error => { assert(error instanceof this.api.errors.LedgerVersionError); }); }); it('getLedger - with state as hashes', function() { const request = { includeTransactions: true, includeAllData: false, includeState: true, ledgerVersion: 6 }; return this.api.getLedger(request).then( _.partial(checkResult, responses.getLedger.withStateAsHashes, 'getLedger')); }); it('getLedger - with settings transaction', function() { const request = { includeTransactions: true, includeAllData: true, ledgerVersion: 4181996 }; return this.api.getLedger(request).then( _.partial(checkResult, responses.getLedger.withSettingsTx, 'getLedger')); }); it('getLedger - full, then computeLedgerHash', function() { const request = { includeTransactions: true, includeState: true, includeAllData: true, ledgerVersion: 38129 }; return this.api.getLedger(request).then( _.partial(checkResult, responses.getLedger.full, 'getLedger')) .then(response => { const ledger = _.assign({}, response, {parentCloseTime: response.closeTime}); const hash = this.api.computeLedgerHash(ledger); assert.strictEqual(hash, 'E6DB7365949BF9814D76BCC730B01818EB9136A89DB224F3F9F5AAE4569D758E'); }); }); it('computeLedgerHash - wrong hash', function() { const request = { includeTransactions: true, includeState: true, includeAllData: true, ledgerVersion: 38129 }; return this.api.getLedger(request).then( _.partial(checkResult, responses.getLedger.full, 'getLedger')) .then(response => { const ledger = _.assign({}, response, { parentCloseTime: response.closeTime, stateHash: 'D9ABF622DA26EEEE48203085D4BC23B0F77DC6F8724AC33D975DA3CA492D2E44'}); assert.throws(() => { const hash = this.api.computeLedgerHash(ledger); unused(hash); }, /does not match computed hash of state/); }); }); it('RippleError with data', function() { const error = new this.api.errors.RippleError('_message_', '_data_'); assert.strictEqual(error.toString(), '[RippleError(_message_, \'_data_\')]'); }); it('NotFoundError default message', function() { const error = new this.api.errors.NotFoundError(); assert.strictEqual(error.toString(), '[NotFoundError(Not found)]'); }); it('common utils - toRippledAmount', function() { const amount = {issuer: 'is', currency: 'c', value: 'v'}; assert.deepEqual(utils.common.toRippledAmount(amount), { issuer: 'is', currency: 'c', value: 'v' }); }); it('ledger utils - renameCounterpartyToIssuerInOrder', function() { const order = {taker_gets: {issuer: '1'}}; const expected = {taker_gets: {issuer: '1'}}; assert.deepEqual(utils.renameCounterpartyToIssuerInOrder(order), expected); }); it('ledger utils - compareTransactions', function() { assert.strictEqual(utils.compareTransactions({}, {}), 0); let first = {outcome: {ledgerVersion: 1, indexInLedger: 100}}; let second = {outcome: {ledgerVersion: 1, indexInLedger: 200}}; assert.strictEqual(utils.compareTransactions(first, second), -1); first = {outcome: {ledgerVersion: 1, indexInLedger: 100}}; second = {outcome: {ledgerVersion: 1, indexInLedger: 100}}; assert.strictEqual(utils.compareTransactions(first, second), 0); first = {outcome: {ledgerVersion: 1, indexInLedger: 200}}; second = {outcome: {ledgerVersion: 1, indexInLedger: 100}}; assert.strictEqual(utils.compareTransactions(first, second), 1); }); it('ledger utils - getRecursive', function() { function getter(marker, limit) { return new Promise((resolve, reject) => { if (marker === undefined) { resolve({marker: 'A', limit: limit, results: [1]}); } else { reject(new Error()); } }); } return utils.getRecursive(getter, 10).then(() => { assert(false, 'Should throw Error'); }).catch(error => { assert(error instanceof Error); }); }); describe('schema-validator', function() { it('valid', function() { assert.doesNotThrow(function() { schemaValidator.schemaValidate('hash256', '0F7ED9F40742D8A513AE86029462B7A6768325583DF8EE21B7EC663019DD6A0F'); }); }); it('invalid', function() { assert.throws(function() { schemaValidator.schemaValidate('hash256', 'invalid'); }, this.api.errors.ValidationError); }); it('invalid - empty value', function() { assert.throws(function() { schemaValidator.schemaValidate('hash256', ''); }, this.api.errors.ValidationError); }); it('schema not found error', function() { assert.throws(function() { schemaValidator.schemaValidate('unexisting', 'anything'); }, /no schema/); }); }); describe('validator', function() { it('validateLedgerRange', function() { const options = { minLedgerVersion: 20000, maxLedgerVersion: 10000 }; const thunk = _.partial(validate.getTransactions, {address, options}); assert.throws(thunk, this.api.errors.ValidationError); assert.throws(thunk, /minLedgerVersion must not be greater than maxLedgerVersion/); }); it('secret', function() { function validateSecret(secret) { validate.sign({txJSON: '', secret}); } assert.doesNotThrow(_.partial(validateSecret, 'shzjfakiK79YQdMjy4h8cGGfQSV6u')); assert.throws(_.partial(validateSecret, 'shzjfakiK79YQdMjy4h8cGGfQSV6v'), this.api.errors.ValidationError); assert.throws(_.partial(validateSecret, 1), this.api.errors.ValidationError); assert.throws(_.partial(validateSecret, ''), this.api.errors.ValidationError); assert.throws(_.partial(validateSecret, 's!!!'), this.api.errors.ValidationError); assert.throws(_.partial(validateSecret, 'passphrase'), this.api.errors.ValidationError); // 32 0s is a valid hex repr of seed bytes const hex = new Array(33).join('0'); assert.throws(_.partial(validateSecret, hex), this.api.errors.ValidationError); }); }); it('ledger event', function(done) { this.api.on('ledger', message => { checkResult(responses.ledgerEvent, 'ledgerEvent', message); done(); }); closeLedger(this.api.connection); }); }); describe('RippleAPI - offline', function() { it('prepareSettings and sign', function() { const api = new RippleAPI(); const secret = 'shsWGZcmZz6YsWWmcnpfr6fLTdtFV'; const settings = requests.prepareSettings.domain; const instructions = { sequence: 23, maxLedgerVersion: 8820051, fee: '0.000012' }; return api.prepareSettings(address, settings, instructions).then(data => { checkResult(responses.prepareSettings.flags, 'prepare', data); assert.deepEqual(api.sign(data.txJSON, secret), responses.prepareSettings.signed); }); }); it('getServerInfo - offline', function() { const api = new RippleAPI(); return api.getServerInfo().then(() => { assert(false, 'Should throw error'); }).catch(error => { assert(error instanceof api.errors.NotConnectedError); }); }); it('computeLedgerHash', function() { const api = new RippleAPI(); const header = requests.computeLedgerHash.header; const ledgerHash = api.computeLedgerHash(header); assert.strictEqual(ledgerHash, 'F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349'); }); it('computeLedgerHash - with transactions', function() { const api = new RippleAPI(); const header = _.omit(requests.computeLedgerHash.header, 'transactionHash'); header.rawTransactions = JSON.stringify( requests.computeLedgerHash.transactions); const ledgerHash = api.computeLedgerHash(header); assert.strictEqual(ledgerHash, 'F4D865D83EB88C1A1911B9E90641919A1314F36E1B099F8E95FE3B7C77BE3349'); }); it('computeLedgerHash - incorrent transaction_hash', function() { const api = new RippleAPI(); const header = _.assign({}, requests.computeLedgerHash.header, {transactionHash: '325EACC5271322539EEEC2D6A5292471EF1B3E72AE7180533EFC3B8F0AD435C9'}); header.rawTransactions = JSON.stringify( requests.computeLedgerHash.transactions); assert.throws(() => api.computeLedgerHash(header)); }); /* eslint-disable no-unused-vars */ it('RippleAPI - implicit server port', function() { const api = new RippleAPI({server: 'wss://s1.ripple.com'}); }); /* eslint-enable no-unused-vars */ it('RippleAPI invalid options', function() { assert.throws(() => new RippleAPI({invalid: true})); }); it('RippleAPI valid options', function() { const api = new RippleAPI({server: 'wss://s:1'}); assert.deepEqual(api.connection._url, 'wss://s:1'); }); it('RippleAPI invalid server uri', function() { assert.throws(() => new RippleAPI({server: 'wss//s:1'})); }); });
let ivm = require('isolated-vm'); let isolate = new ivm.Isolate; let context = isolate.createContextSync(); let global = context.global; function recur1() { return global.getSync('recur2').applySync(undefined, []); } global.setSync('recur1', new ivm.Reference(recur1)); console.log(isolate.compileScriptSync(` function recur2() { return 'pass'; } recur1.applySync(undefined, []); `).runSync(context));
import { t } from '../core/localizer'; import { matcher } from 'name-suggestion-index'; import * as countryCoder from '@ideditor/country-coder'; import { presetManager } from '../presets'; import { fileFetcher } from '../core/file_fetcher'; import { actionChangePreset } from '../actions/change_preset'; import { actionChangeTags } from '../actions/change_tags'; import { actionUpgradeTags } from '../actions/upgrade_tags'; import { osmIsOldMultipolygonOuterMember, osmOldMultipolygonOuterMemberOfRelation } from '../osm/multipolygon'; import { utilDisplayLabel, utilTagDiff } from '../util'; import { validationIssue, validationIssueFix } from '../core/validation'; let _dataDeprecated; let _nsi; export function validationOutdatedTags() { const type = 'outdated_tags'; const nsiKeys = ['amenity', 'shop', 'tourism', 'leisure', 'office']; // A concern here in switching to async data means that `_dataDeprecated` // and `_nsi` will not be available at first, so the data on early tiles // may not have tags validated fully. // initialize deprecated tags array fileFetcher.get('deprecated') .then(d => _dataDeprecated = d) .catch(() => { /* ignore */ }); fileFetcher.get('nsi_brands') .then(d => { _nsi = { brands: d.brands, matcher: matcher(), wikidata: {}, wikipedia: {} }; // initialize name-suggestion-index matcher _nsi.matcher.buildMatchIndex(d.brands); // index all known wikipedia and wikidata tags Object.keys(d.brands).forEach(kvnd => { const brand = d.brands[kvnd]; const wd = brand.tags['brand:wikidata']; const wp = brand.tags['brand:wikipedia']; if (wd) { _nsi.wikidata[wd] = kvnd; } if (wp) { _nsi.wikipedia[wp] = kvnd; } }); return _nsi; }) .catch(() => { /* ignore */ }); function oldTagIssues(entity, graph) { const oldTags = Object.assign({}, entity.tags); // shallow copy let preset = presetManager.match(entity, graph); let subtype = 'deprecated_tags'; if (!preset) return []; // upgrade preset.. if (preset.replacement) { const newPreset = presetManager.item(preset.replacement); graph = actionChangePreset(entity.id, preset, newPreset)(graph); entity = graph.entity(entity.id); preset = newPreset; } // upgrade tags.. if (_dataDeprecated) { const deprecatedTags = entity.deprecatedTags(_dataDeprecated); if (deprecatedTags.length) { deprecatedTags.forEach(tag => { graph = actionUpgradeTags(entity.id, tag.old, tag.replace)(graph); }); entity = graph.entity(entity.id); } } // add missing addTags.. let newTags = Object.assign({}, entity.tags); // shallow copy if (preset.tags !== preset.addTags) { Object.keys(preset.addTags).forEach(k => { if (!newTags[k]) { if (preset.addTags[k] === '*') { newTags[k] = 'yes'; } else { newTags[k] = preset.addTags[k]; } } }); } if (_nsi) { // Do `wikidata` or `wikipedia` identify this entity as a brand? #6416 // If so, these tags can be swapped to `brand:wikidata`/`brand:wikipedia` let isBrand; if (newTags.wikidata) { // try matching `wikidata` isBrand = _nsi.wikidata[newTags.wikidata]; } if (!isBrand && newTags.wikipedia) { // fallback to `wikipedia` isBrand = _nsi.wikipedia[newTags.wikipedia]; } if (isBrand && !newTags.office) { // but avoid doing this for corporate offices if (newTags.wikidata) { newTags['brand:wikidata'] = newTags.wikidata; delete newTags.wikidata; } if (newTags.wikipedia) { newTags['brand:wikipedia'] = newTags.wikipedia; delete newTags.wikipedia; } // I considered setting `name` and other tags here, but they aren't unique per wikidata // (Q2759586 -> in USA "Papa John's", in Russia "Папа Джонс") // So users will really need to use a preset or assign `name` themselves. } // try key/value|name match against name-suggestion-index if (newTags.name) { for (let i = 0; i < nsiKeys.length; i++) { const k = nsiKeys[i]; if (!newTags[k]) continue; const center = entity.extent(graph).center(); const countryCode = countryCoder.iso1A2Code(center); const match = _nsi.matcher.matchKVN(k, newTags[k], newTags.name, countryCode && countryCode.toLowerCase()); if (!match) continue; // for now skip ambiguous matches (like Target~(USA) vs Target~(Australia)) if (match.d) continue; const brand = _nsi.brands[match.kvnd]; if (brand && brand.tags['brand:wikidata'] && brand.tags['brand:wikidata'] !== entity.tags['not:brand:wikidata']) { subtype = 'noncanonical_brand'; const keepTags = ['takeaway'].reduce((acc, k) => { if (newTags[k]) { acc[k] = newTags[k]; } return acc; }, {}); nsiKeys.forEach(k => delete newTags[k]); Object.assign(newTags, brand.tags, keepTags); break; } } } } // determine diff const tagDiff = utilTagDiff(oldTags, newTags); if (!tagDiff.length) return []; const isOnlyAddingTags = tagDiff.every(d => d.type === '+'); let prefix = ''; if (subtype === 'noncanonical_brand') { prefix = 'noncanonical_brand.'; } else if (subtype === 'deprecated_tags' && isOnlyAddingTags) { subtype = 'incomplete_tags'; prefix = 'incomplete.'; } // don't allow autofixing brand tags let autoArgs = subtype !== 'noncanonical_brand' ? [doUpgrade, t('issues.fix.upgrade_tags.annotation')] : null; return [new validationIssue({ type: type, subtype: subtype, severity: 'warning', message: showMessage, reference: showReference, entityIds: [entity.id], hash: JSON.stringify(tagDiff), dynamicFixes: () => { return [ new validationIssueFix({ autoArgs: autoArgs, title: t('issues.fix.upgrade_tags.title'), onClick: (context) => { context.perform(doUpgrade, t('issues.fix.upgrade_tags.annotation')); } }) ]; } })]; function doUpgrade(graph) { const currEntity = graph.hasEntity(entity.id); if (!currEntity) return graph; let newTags = Object.assign({}, currEntity.tags); // shallow copy tagDiff.forEach(diff => { if (diff.type === '-') { delete newTags[diff.key]; } else if (diff.type === '+') { newTags[diff.key] = diff.newVal; } }); return actionChangeTags(currEntity.id, newTags)(graph); } function showMessage(context) { const currEntity = context.hasEntity(entity.id); if (!currEntity) return ''; let messageID = `issues.outdated_tags.${prefix}message`; if (subtype === 'noncanonical_brand' && isOnlyAddingTags) { messageID += '_incomplete'; } return t(messageID, { feature: utilDisplayLabel(currEntity, context.graph()) }); } function showReference(selection) { let enter = selection.selectAll('.issue-reference') .data([0]) .enter(); enter .append('div') .attr('class', 'issue-reference') .text(t(`issues.outdated_tags.${prefix}reference`)); enter .append('strong') .text(t('issues.suggested')); enter .append('table') .attr('class', 'tagDiff-table') .selectAll('.tagDiff-row') .data(tagDiff) .enter() .append('tr') .attr('class', 'tagDiff-row') .append('td') .attr('class', d => { let klass = d.type === '+' ? 'add' : 'remove'; return `tagDiff-cell tagDiff-cell-${klass}`; }) .text(d => d.display); } } function oldMultipolygonIssues(entity, graph) { let multipolygon, outerWay; if (entity.type === 'relation') { outerWay = osmOldMultipolygonOuterMemberOfRelation(entity, graph); multipolygon = entity; } else if (entity.type === 'way') { multipolygon = osmIsOldMultipolygonOuterMember(entity, graph); outerWay = entity; } else { return []; } if (!multipolygon || !outerWay) return []; return [new validationIssue({ type: type, subtype: 'old_multipolygon', severity: 'warning', message: showMessage, reference: showReference, entityIds: [outerWay.id, multipolygon.id], dynamicFixes: () => { return [ new validationIssueFix({ autoArgs: [doUpgrade, t('issues.fix.move_tags.annotation')], title: t('issues.fix.move_tags.title'), onClick: (context) => { context.perform(doUpgrade, t('issues.fix.move_tags.annotation')); } }) ]; } })]; function doUpgrade(graph) { let currMultipolygon = graph.hasEntity(multipolygon.id); let currOuterWay = graph.hasEntity(outerWay.id); if (!currMultipolygon || !currOuterWay) return graph; currMultipolygon = currMultipolygon.mergeTags(currOuterWay.tags); graph = graph.replace(currMultipolygon); return actionChangeTags(currOuterWay.id, {})(graph); } function showMessage(context) { let currMultipolygon = context.hasEntity(multipolygon.id); if (!currMultipolygon) return ''; return t('issues.old_multipolygon.message', { multipolygon: utilDisplayLabel(currMultipolygon, context.graph()) } ); } function showReference(selection) { selection.selectAll('.issue-reference') .data([0]) .enter() .append('div') .attr('class', 'issue-reference') .text(t('issues.old_multipolygon.reference')); } } let validation = function checkOutdatedTags(entity, graph) { let issues = oldMultipolygonIssues(entity, graph); if (!issues.length) issues = oldTagIssues(entity, graph); return issues; }; validation.type = type; return validation; }
var EventEmitter = require('events').EventEmitter, _ = require('lodash'), eventBatch = require('./eventbatch'), dbapi = require('./dbapi'); // pgq.Consumer() module.exports = function(config) { var self = new EventEmitter(); var initialize = function(config) { var requiredParams = { consumerName: 'isString', 'source.database': 'isString', 'source.queue': 'isString', }, optionalParams = { pollingInterval: 'isNumber', afterFailureInterval: 'isNumber', logDebug: 'isBoolean' }, sec = 1000; config = _.cloneDeep(config); // validate that default aprameters exist and have correct type _.forOwn(requiredParams, function(validator, param) { var value = _.get(config, param); if (!value) return paramMissing(param); validateParamValue(validator, param, value); }); // validate if optional parameters have correct type _.forOwn(optionalParams, function(validator, param) { var value = _.get(config, param); if (value) validateParamValue(validator, param, value); }); // set optional parameters to their defaults config.pollingInterval = config.pollingInterval || 1 * sec; config.afterFailureInterval = config.afterFailureInterval || 5 * sec; self.config = config; self.dbapi = dbapi.PgQDatabaseAPI(config.source.database); }; var validateParamValue = function(validator, param, value) { // throws error when value type does not match expectation var isValid = _[validator](value); if (!isValid) return paramWrongType(param, validator); }; var paramMissing = function(paramName) { var errMessage = 'required config parameter: '+paramName+' missing'; throw new Error(errMessage); }; var paramWrongType = function(paramName, expectedType) { var errMessage = 'config parameter ' + paramName + 'has wrong type,'; errMessage += ' expected ' + expectedType; throw new Error(errMessage); }; var emitWhenDone = function(eventToBeEmitted) { var resultHandler = function() { // first argument is error, the rest are results var err = arguments[0], results = [].slice.apply(arguments).slice(1); if (err) { self.emit('error', err); } else { // emit event (eventToBeEmitted, result1, result2, ...) results.unshift(eventToBeEmitted); self.emit.apply(self, results); } }; return resultHandler; }; self.log = function(message) { if (self.config.logDebug) { self.emit('log', message); } }; // step 1 register this consumer for the queue self.connect = function() { self.log('registering consumer in source database'); self.dbapi.registerConsumer( self.config.source.queue, self.config.consumerName, emitWhenDone('connected') ); }; // step 2 - find if there is a new batch ready self.pollBatch = function() { self.log('polling for event batch'); self.dbapi.loadNextBatch({ queueName: self.config.source.queue, consumerName: self.config.consumerName, // minLag etc. is not yet implemented }, emitWhenDone('batchLoaded') ); }; // step 3 - if batch is not empty load events self.loadBatchEventsIfAny = function(batch) { var sleepSec; if (batch.batch_id === null) { sleepSec = (self.config.pollingInterval / 1000); self.log('no batch, sleeping for ' + sleepSec + ' seconds'); setTimeout(emitWhenDone('pollBatch'), self.config.pollingInterval); } else { // build a new eventBatch for this consumer+batch and load events self.log('polling for batch events'); eventBatch(self).load( batch.batch_id, emitWhenDone('batchEventsLoaded') ); } }; // step 4 - emit events to client implementation where they get // handled and acknowledged via ev.tagDone ev.tagRetry self.emitEventsToHandler = function(batchId, batchEvents) { // with empty batch immediately mark it as processed if (batchEvents.length === 0) { self.log('empty batch'); self.dbapi.finishBatch(batchId, emitWhenDone('batchProcessed')); } else { self.log('got ' + batchEvents.length + ' events '); } // at this point we hand the control over to the consumer implementation // once the consumer has marked each and every event in batch with // ev.tagDone ev.tagRetry the batch will try to update it's status // within the database. If it's successful it calls batchProcessed // when an error happens we move to the error handler below that causes // the consumer to sleep and retry after a while. _.each(batchEvents, function(batchEvent) { self.emit('event', batchEvent); }); }; // step 5 - all done self.batchProcessed = function() { // if this looks like a useless step then you are correct // will add statistics to this phase later self.log('batch processed and marked as completed'); // continue work on next batch self.emit('pollBatch'); }; // if error happens during any step then we sleep and go back to square 1 self.handleError = function(err) { self.log('batch failed with error ' + err.message); self.log('sleeping ' + self.config.afterFailureInterval); setTimeout(function() { self.emit('pollBatch'); }, self.config.afterFailureInterval); }; self.on('connected', self.pollBatch); // fist run self.on('pollBatch', self.pollBatch); self.on('batchLoaded', self.loadBatchEventsIfAny); self.on('batchEventsLoaded', self.emitEventsToHandler); self.on('batchProcessed', self.batchProcessed); self.on('error', self.handleError); initialize(config); return self; };
angular.element(document).ready(function() { angular.module( 'ripplecharts', [ 'templates-app', 'templates-common', 'ripplecharts.landing', 'ripplecharts.markets', 'ripplecharts.manage-currencies', 'ripplecharts.manage-gateways', 'ripplecharts.multimarkets', 'ripplecharts.activeAccounts', 'ripplecharts.trade-volume', 'ripplecharts.graph', 'ripplecharts.accounts', 'ripplecharts.value', 'ripplecharts.history', 'ui.state', 'ui.route', 'snap', 'gateways', 'rippleName', 'matrixFactory', 'chordDiagram' ]) .config( function myAppConfig ( $stateProvider, $urlRouterProvider ) { $urlRouterProvider.otherwise('/'); }) .run(function($window, $rootScope) { if (typeof navigator.onLine != 'undefined') { $rootScope.online = navigator.onLine; $window.addEventListener("offline", function () { $rootScope.$apply(function() { $rootScope.online = false; }); }, false); $window.addEventListener("online", function () { $rootScope.$apply(function() { $rootScope.online = true; }); }, false); } }) .controller( 'AppCtrl', function AppCtrl ( $scope, $location ) { $scope.theme = store.get('theme') || Options.theme || 'dark'; $scope.$watch('theme', function(){store.set('theme', $scope.theme)}); $scope.toggleTheme = function(){ if ($scope.theme == 'dark') $scope.theme = 'light'; else $scope.theme = 'dark'; }; $scope.snapOptions = { disable: 'right', maxPosition: 267 } //disable touch drag for desktop devices if (!Modernizr.touch) $scope.snapOptions.touchToDrag = false; $scope.$on('$stateChangeSuccess', function(event, toState, toParams, fromState, fromParams){ mixpanel.track("Page", {"Page Name":toState.name, "Theme":$scope.theme}); if (ga) ga('send', 'pageview', toState.name); if ( angular.isDefined( toState.data.pageTitle ) ) $scope.pageTitle = toState.data.pageTitle + ' | Ripple Charts' ; else $scope.pageTitle = "Ripple Charts" }); //connect to the ripple network; remote = new ripple.Remote(Options.ripple); remote.connect(); //get ledger number and total coins remote.on('ledger_closed', function(x){ $scope.ledgerLabel = "Ledger #:"; $scope.ledgerIndex = commas(parseInt(x.ledger_index,10)); remote.request_ledger('closed', handleLedger); $scope.$apply(); }); function handleLedger(err, obj) { if (obj) { var totalCoins = obj.ledger.total_coins, totalCoinsXrp = [commas(parseInt(totalCoins.slice(0, -6), 10)), totalCoins.slice(-6, -4)].join("."); $scope.ledgerLabel = "Ledger #:"; $scope.ledgerIndex = commas(parseInt(obj.ledger.ledger_index, 10)); $scope.totalCoins = totalCoinsXrp; $scope.totalXRP = parseFloat(totalCoins)/ 1000000.0; $scope.$apply(); } } $scope.ledgerLabel = "connecting..."; remote.request_ledger('closed', handleLedger); //get current ledger; remote.on("disconnect", function(){ $scope.ledgerLabel = "reconnecting..."; $scope.ledgerIndex = ""; $scope.connectionStatus = "disconnected"; $scope.$apply(); }); remote.on("connect", function(){ $scope.ledgerLabel = "connected"; $scope.connectionStatus = "connected"; $scope.$apply(); //setTimeout(function(){remote.disconnect()},5000); //setTimeout(function(){remote.connect()},10000); }); }); angular.bootstrap(document, ['ripplecharts']); }); function commas (number, precision) { if (number===0) return 0; if (!number) return null; var parts = number.toString().split("."); parts[0] = parts[0].replace(/\B(?=(\d{3})+(?!\d))/g, ","); if (precision && parts[1]) { parts[1] = parts[1].substring(0,precision); while(precision>parts[1].length) parts[1] += '0'; } else if (precision===0) return parts[0]; return parts.join("."); }
module.exports = function () { return [ '**.frostcast.net' , 'google.com' ] }
System.config({ defaultJSExtensions: true, transpiler: "babel", babelOptions: { "optional": [ "runtime", "optimisation.modules.system" ] }, paths: { "github:*": "jspm_packages/github/*", "npm:*": "jspm_packages/npm/*" }, map: { "angular2": "npm:angular2@2.0.0-beta.1", "babel": "npm:babel-core@5.8.35", "babel-runtime": "npm:babel-runtime@5.8.35", "core-js": "npm:core-js@1.2.6", "jquery": "npm:jquery@2.2.0", "lodash": "npm:lodash@4.0.0", "reflect-metadata": "npm:reflect-metadata@0.1.3", "velesin/jasmine-jquery": "github:velesin/jasmine-jquery@2.1.1", "zone.js": "npm:zone.js@0.5.10", "github:jspm/nodelibs-assert@0.1.0": { "assert": "npm:assert@1.3.0" }, "github:jspm/nodelibs-buffer@0.1.0": { "buffer": "npm:buffer@3.6.0" }, "github:jspm/nodelibs-constants@0.1.0": { "constants-browserify": "npm:constants-browserify@0.0.1" }, "github:jspm/nodelibs-crypto@0.1.0": { "crypto-browserify": "npm:crypto-browserify@3.11.0" }, "github:jspm/nodelibs-events@0.1.1": { "events": "npm:events@1.0.2" }, "github:jspm/nodelibs-path@0.1.0": { "path-browserify": "npm:path-browserify@0.0.0" }, "github:jspm/nodelibs-process@0.1.2": { "process": "npm:process@0.11.2" }, "github:jspm/nodelibs-stream@0.1.0": { "stream-browserify": "npm:stream-browserify@1.0.0" }, "github:jspm/nodelibs-string_decoder@0.1.0": { "string_decoder": "npm:string_decoder@0.10.31" }, "github:jspm/nodelibs-util@0.1.0": { "util": "npm:util@0.10.3" }, "github:jspm/nodelibs-vm@0.1.0": { "vm-browserify": "npm:vm-browserify@0.0.4" }, "npm:angular2@2.0.0-beta.1": { "crypto": "github:jspm/nodelibs-crypto@0.1.0", "es6-promise": "npm:es6-promise@3.0.2", "es6-shim": "npm:es6-shim@0.33.13", "process": "github:jspm/nodelibs-process@0.1.2", "reflect-metadata": "npm:reflect-metadata@0.1.2", "rxjs": "npm:rxjs@5.0.0-beta.0", "zone.js": "npm:zone.js@0.5.10" }, "npm:asn1.js@4.3.0": { "assert": "github:jspm/nodelibs-assert@0.1.0", "bn.js": "npm:bn.js@4.6.4", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "inherits": "npm:inherits@2.0.1", "minimalistic-assert": "npm:minimalistic-assert@1.0.0", "vm": "github:jspm/nodelibs-vm@0.1.0" }, "npm:assert@1.3.0": { "util": "npm:util@0.10.3" }, "npm:babel-runtime@5.8.35": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:browserify-aes@1.0.6": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "buffer-xor": "npm:buffer-xor@1.0.3", "cipher-base": "npm:cipher-base@1.0.2", "create-hash": "npm:create-hash@1.1.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "evp_bytestokey": "npm:evp_bytestokey@1.0.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "inherits": "npm:inherits@2.0.1", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:browserify-cipher@1.0.0": { "browserify-aes": "npm:browserify-aes@1.0.6", "browserify-des": "npm:browserify-des@1.0.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "evp_bytestokey": "npm:evp_bytestokey@1.0.0" }, "npm:browserify-des@1.0.0": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "cipher-base": "npm:cipher-base@1.0.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "des.js": "npm:des.js@1.0.0", "inherits": "npm:inherits@2.0.1" }, "npm:browserify-rsa@4.0.0": { "bn.js": "npm:bn.js@4.6.4", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "constants": "github:jspm/nodelibs-constants@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "randombytes": "npm:randombytes@2.0.2" }, "npm:browserify-sign@4.0.0": { "bn.js": "npm:bn.js@4.6.4", "browserify-rsa": "npm:browserify-rsa@4.0.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "create-hmac": "npm:create-hmac@1.1.4", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "elliptic": "npm:elliptic@6.1.0", "inherits": "npm:inherits@2.0.1", "parse-asn1": "npm:parse-asn1@5.0.0", "stream": "github:jspm/nodelibs-stream@0.1.0" }, "npm:buffer-xor@1.0.3": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:buffer@3.6.0": { "base64-js": "npm:base64-js@0.0.8", "child_process": "github:jspm/nodelibs-child_process@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "ieee754": "npm:ieee754@1.1.6", "isarray": "npm:isarray@1.0.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:cipher-base@1.0.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "inherits": "npm:inherits@2.0.1", "stream": "github:jspm/nodelibs-stream@0.1.0", "string_decoder": "github:jspm/nodelibs-string_decoder@0.1.0" }, "npm:constants-browserify@0.0.1": { "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:core-js@1.2.6": { "fs": "github:jspm/nodelibs-fs@0.1.2", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:core-util-is@1.0.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0" }, "npm:create-ecdh@4.0.0": { "bn.js": "npm:bn.js@4.6.4", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "elliptic": "npm:elliptic@6.1.0" }, "npm:create-hash@1.1.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "cipher-base": "npm:cipher-base@1.0.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "inherits": "npm:inherits@2.0.1", "ripemd160": "npm:ripemd160@1.0.1", "sha.js": "npm:sha.js@2.4.4" }, "npm:create-hmac@1.1.4": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "inherits": "npm:inherits@2.0.1", "stream": "github:jspm/nodelibs-stream@0.1.0" }, "npm:crypto-browserify@3.11.0": { "browserify-cipher": "npm:browserify-cipher@1.0.0", "browserify-sign": "npm:browserify-sign@4.0.0", "create-ecdh": "npm:create-ecdh@4.0.0", "create-hash": "npm:create-hash@1.1.2", "create-hmac": "npm:create-hmac@1.1.4", "diffie-hellman": "npm:diffie-hellman@5.0.1", "inherits": "npm:inherits@2.0.1", "pbkdf2": "npm:pbkdf2@3.0.4", "public-encrypt": "npm:public-encrypt@4.0.0", "randombytes": "npm:randombytes@2.0.2" }, "npm:des.js@1.0.0": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "inherits": "npm:inherits@2.0.1", "minimalistic-assert": "npm:minimalistic-assert@1.0.0" }, "npm:diffie-hellman@5.0.1": { "bn.js": "npm:bn.js@4.6.4", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "miller-rabin": "npm:miller-rabin@4.0.0", "randombytes": "npm:randombytes@2.0.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:elliptic@6.1.0": { "bn.js": "npm:bn.js@4.6.4", "brorand": "npm:brorand@1.0.5", "hash.js": "npm:hash.js@1.0.3", "inherits": "npm:inherits@2.0.1", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:es6-promise@3.0.2": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:es6-shim@0.33.13": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:evp_bytestokey@1.0.0": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0" }, "npm:hash.js@1.0.3": { "inherits": "npm:inherits@2.0.1" }, "npm:inherits@2.0.1": { "util": "github:jspm/nodelibs-util@0.1.0" }, "npm:lodash@4.0.0": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:miller-rabin@4.0.0": { "bn.js": "npm:bn.js@4.6.4", "brorand": "npm:brorand@1.0.5" }, "npm:parse-asn1@5.0.0": { "asn1.js": "npm:asn1.js@4.3.0", "browserify-aes": "npm:browserify-aes@1.0.6", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "evp_bytestokey": "npm:evp_bytestokey@1.0.0", "pbkdf2": "npm:pbkdf2@3.0.4", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:path-browserify@0.0.0": { "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:pbkdf2@3.0.4": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "child_process": "github:jspm/nodelibs-child_process@0.1.0", "create-hmac": "npm:create-hmac@1.1.4", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "path": "github:jspm/nodelibs-path@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2", "systemjs-json": "github:systemjs/plugin-json@0.1.0" }, "npm:process@0.11.2": { "assert": "github:jspm/nodelibs-assert@0.1.0" }, "npm:public-encrypt@4.0.0": { "bn.js": "npm:bn.js@4.6.4", "browserify-rsa": "npm:browserify-rsa@4.0.0", "buffer": "github:jspm/nodelibs-buffer@0.1.0", "create-hash": "npm:create-hash@1.1.2", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "parse-asn1": "npm:parse-asn1@5.0.0", "randombytes": "npm:randombytes@2.0.2" }, "npm:randombytes@2.0.2": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "crypto": "github:jspm/nodelibs-crypto@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:readable-stream@1.1.13": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "core-util-is": "npm:core-util-is@1.0.2", "events": "github:jspm/nodelibs-events@0.1.1", "inherits": "npm:inherits@2.0.1", "isarray": "npm:isarray@0.0.1", "process": "github:jspm/nodelibs-process@0.1.2", "stream-browserify": "npm:stream-browserify@1.0.0", "string_decoder": "npm:string_decoder@0.10.31" }, "npm:reflect-metadata@0.1.2": { "assert": "github:jspm/nodelibs-assert@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:reflect-metadata@0.1.3": { "assert": "github:jspm/nodelibs-assert@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:ripemd160@1.0.1": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:rxjs@5.0.0-beta.0": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:sha.js@2.4.4": { "buffer": "github:jspm/nodelibs-buffer@0.1.0", "fs": "github:jspm/nodelibs-fs@0.1.2", "inherits": "npm:inherits@2.0.1", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:stream-browserify@1.0.0": { "events": "github:jspm/nodelibs-events@0.1.1", "inherits": "npm:inherits@2.0.1", "readable-stream": "npm:readable-stream@1.1.13" }, "npm:string_decoder@0.10.31": { "buffer": "github:jspm/nodelibs-buffer@0.1.0" }, "npm:util@0.10.3": { "inherits": "npm:inherits@2.0.1", "process": "github:jspm/nodelibs-process@0.1.2" }, "npm:vm-browserify@0.0.4": { "indexof": "npm:indexof@0.0.1" }, "npm:zone.js@0.5.10": { "es6-promise": "npm:es6-promise@3.0.2", "process": "github:jspm/nodelibs-process@0.1.2" } } });
"use strict"; var React = require("react/addons"); describe("Container", function () { var Container = require("../Container"); var container; var pages; var result; var props; beforeEach(function () { container = Object.create(Container); props = container.props = {}; pages = [{ items: [{ id: "foo0", }, { id: "foo1", }, { id: "foo2", }], }, { items: [{ id: "foo3", }, { id: "foo4", }, { id: "foo5", }], }, { items: [{ id: "foo6", }, { id: "foo7", }, { id: "foo8", }], }]; container.page = function () { return pages; }; }); describe(".calculatePageState()", function () { function prepare () { result = container.calculatePageState(pages); } describe("when marker and previous marker are not defined", function () { beforeEach(prepare); it("should return current and previous index as zero", function () { expect(result.index).to.equal(0); expect(result.previousIndex).to.equal(0); }); }); describe("when previous marker is not defined and marker is on second page", function () { beforeEach(function () { props.marker = "foo5"; prepare(); }); it("should return current index as 1 and previous index as 0", function () { expect(result.index).to.equal(1); expect(result.previousIndex).to.equal(0); }); }); describe("when previous marker is not defined and marker is not found", function () { beforeEach(function () { props.marker = "bar2"; prepare(); }); it("should return current and previous index as zero", function () { expect(result.index).to.equal(0); expect(result.previousIndex).to.equal(0); }); }); describe("when looping is enabled", function () { beforeEach(function () { props.loop = true; }); describe("when marker and previous marker are not defined", function () { beforeEach(function () { prepare(); }); it("should return current and previous index as zero", function () { expect(result.index).to.equal(0); expect(result.previousIndex).to.equal(0); }); }); describe("when previous marker is not defined and marker is on second page", function () { beforeEach(function () { props.marker = "foo5"; prepare(); }); it("should return current index as 1 and previous index as 0", function () { expect(result.index).to.equal(1); expect(result.previousIndex).to.equal(0); }); }); describe("when current marker is closer to the next page than the page of the previous marker", function () { beforeEach(function () { props.marker = "foo8"; props.previousMarker = "foo0"; prepare(); }); it("should return current index as -1 and previous index as 3", function () { expect(result.index).to.equal(-1); expect(result.previousIndex).to.equal(0); }); }); describe("when current marker is closer to the previous page than the page of the previous marker", function () { beforeEach(function () { props.marker = "foo0"; props.previousMarker = "foo8"; prepare(); }); it("should return current index as 3 and previous index as 2", function () { expect(result.index).to.equal(3); expect(result.previousIndex).to.equal(2); }); }); }); }); describe(".setPageIndex()", function () { beforeEach(function () { props.onPageChange = sinon.spy(); }); describe("when pages list is empty", function () { beforeEach(function () { pages = []; container.setPageIndex(0); }); it("shouldn't do anything", function () { expect(props.onPageChange.called).to.not.be.ok(); }); }); describe("when not looping", function () { describe("when set above bounds", function () { beforeEach(function () { container.setPageIndex(4); }); it("shouldn't do anything", function () { expect(props.onPageChange.called).to.not.be.ok(); }); }); describe("when set below bounds", function () { beforeEach(function () { container.setPageIndex(-1); }); it("shouldn't do anything", function () { expect(props.onPageChange.called).to.not.be.ok(); }); }); }); describe("when looping", function () { beforeEach(function () { props.loop = true; }); describe("when set above bounds", function () { beforeEach(function () { container.setPageIndex(4); }); it("should normalize the index and find the correct marker", function () { expect(props.onPageChange.lastCall.args[0].marker).to.equal("foo4"); }); }); describe("when set below bounds", function () { beforeEach(function () { container.setPageIndex(-1); }); it("should normalize the index and find the correct marker", function () { expect(props.onPageChange.lastCall.args[0].marker).to.equal("foo7"); }); }); }); }); describe(".isOnFirstPage()", function () { describe("when marker is undefined", function () { beforeEach(function () { result = container.isOnFirstPage(pages); }); it("should return true", function () { expect(result).to.be.ok(); }); }); describe("when on first page", function () { beforeEach(function () { props.marker = "foo1"; result = container.isOnFirstPage(pages); }); it("should return true", function () { expect(result).to.be.ok(); }); }); describe("when on second page", function () { beforeEach(function () { props.marker = "foo3"; result = container.isOnFirstPage(pages); }); it("should return true", function () { expect(result).to.not.be.ok(); }); }); }); describe(".isOnLastPage()", function () { describe("when marker is undefined", function () { beforeEach(function () { result = container.isOnLastPage(pages); }); it("should return false", function () { expect(result).to.not.be.ok(); }); }); describe("when on last page", function () { beforeEach(function () { props.marker = "foo8"; result = container.isOnLastPage(pages); }); it("should return true", function () { expect(result).to.be.ok(); }); }); describe("when on second page", function () { beforeEach(function () { props.marker = "foo3"; result = container.isOnLastPage(pages); }); it("should return false", function () { expect(result).to.not.be.ok(); }); }); }); describe("auto rotation", function () { describe("when the component has mounted", function () { beforeEach(function () { container.startAutoRotate = sinon.spy(); container.componentDidMount(); }); it("should be started", function () { expect(container.startAutoRotate.called).to.equal(true); }); }); describe("when the component will unmount", function () { beforeEach(function () { container.stopAutoRotate = sinon.spy(); container.componentWillUnmount(); }); it("should be stopped", function () { expect(container.stopAutoRotate.called).to.equal(true); }); }); describe("when mouse leaves the container", function () { beforeEach(function () { container.startAutoRotate = sinon.spy(); container.handleMouseLeave(); }); it("should be started", function () { expect(container.startAutoRotate.called).to.equal(true); }); }); describe("when mouse enters the container", function () { beforeEach(function () { container.stopAutoRotate = sinon.spy(); container.handleMouseEnter(); }); it("should be stopped", function () { expect(container.stopAutoRotate.called).to.equal(true); }); }); describe("when started", function () { var delta; beforeEach(function (callback) { props.autoRotate = true; props.autoRotateInterval = 10; var calledTimes = 0; var start; container.rotate = function () { if ( ++calledTimes === 3 ) { delta = Date.now() - start; container.stopAutoRotate(); callback(); } else if ( calledTimes > 3 ) { throw new Error("autorotation didn't stop!"); } }; start = Date.now(); container.startAutoRotate(); }); it("should be called regularly", function () { expect(delta).to.be.above(25); // XXX (jussi-kalliokoski): the intervals can be anything on BrowserStack. :/ expect(delta).to.be.below(1000); }); }); describe("when disabled", function () { beforeEach(function (callback) { props.autoRotate = false; props.autoRotateInterval = 1; container.rotate = sinon.spy(); container.startAutoRotate(); setTimeout(function () { callback(); }, 10); }); it("should not start", function () { expect(container.rotate.called).to.not.be.ok(); }); }); describe("when rotated", function () { beforeEach(function () { props.marker = "foo4"; props.onPageChange = sinon.spy(); }); describe("left", function () { beforeEach(function () { props.autoRotateDirection = "left"; container.rotate(); }); it("should select the previous page", function () { expect(props.onPageChange.lastCall.args[0].marker).to.equal("foo1"); }); }); describe("right", function () { beforeEach(function () { props.autoRotateDirection = "right"; container.rotate(); }); it("should select the previous page", function () { expect(props.onPageChange.lastCall.args[0].marker).to.equal("foo7"); }); }); }); describe("on page changed event from carousel", function () { beforeEach(function () { props.marker = "foo4"; props.onPageChange = sinon.spy(); container.handlePageChange({ pageIndex: 0, }); }); it("should trigger the onPageChange event", function () { expect(props.onPageChange.lastCall.args[0].marker).to.equal("foo1"); }); }); describe("when swiped", function () { beforeEach(function () { props.marker = "foo4"; props.onPageChange = sinon.spy(); }); describe("left", function () { beforeEach(function () { container.handleSwipe({ sign: -1, }); }); it("should select the previous page", function () { expect(props.onPageChange.lastCall.args[0].marker).to.equal("foo1"); }); }); describe("right", function () { beforeEach(function () { container.handleSwipe({ sign: 1, }); }); it("should select the previous page", function () { expect(props.onPageChange.lastCall.args[0].marker).to.equal("foo7"); }); }); }); }); });
/** * Create selectors for news store */ import { createSelector } from 'reselect'; import { isAuthenticatedSelector } from './userSelectors'; import { userBrandsSelector } from './brandSelectors'; const newsStateSelector = state => state.news; export const newsSelector = createSelector( newsStateSelector, userBrandsSelector, isAuthenticatedSelector, (newsState, userBrands, isAuthenticated) => { if (isAuthenticated) { const userBrandNames = userBrands.map(brand => brand.name); return newsState.news.filter((news) => { for (let i = 0; i < news.Brands.length; i++) { if (userBrandNames.indexOf(news.Brands[i].name) < 0) { return false; } } return true; }); } else { return newsState.news; } } ); export const isFetchingAllNewsSelector = createSelector( newsStateSelector, newsState => newsState.isFetchingAllNews ); export const isFetchingOwnNewsSelector = createSelector( newsStateSelector, newsState => newsState.isFetchingOwnNews ); export const newsErrorSelector = createSelector( newsStateSelector, newsState => newsState.error );
var endtime = null; var stepper = null; var defaulttime = (2 * 60 + 30) * 1000; function displayTime(d, func) { var min = 0, sec = 0, ms = 0; if (d > 0) { var dd = d; ms = Math.floor(d % 1000 / 100); d = Math.floor(d / 1000); sec = d % 60; d = Math.floor(d / 60); min = d; d = dd; } else { stopTimer(); } $('#time #min').text(min); $('#time #sec').text((sec < 10 ? '0' : '') + sec); $('#time #ms').text(ms); (func || function(){})(d); } function startTimer(func) { $("#timer").text("Stop").removeClass("btn-default btn-success").addClass("btn-danger"); endtime = Date.now() + defaulttime; stepper = setInterval(function() { displayTime(endtime - Date.now(), func); }, 100); ga("send", "event", "timer", "start"); } function stopTimer(reset) { $("#timer").text("Start").removeClass("btn-default btn-danger").addClass("btn-success"); endtime = null; clearInterval(stepper); stepper = null; if (!reset) ga("send", "event", "timer", "stop", $("#time").text().trim()); } function resetTimer(func) { displayTime(defaulttime, func); stopTimer(true); } function isTimer() { return endtime !== null; }
import Ember from 'ember'; import config from './config/environment'; var Router = Ember.Router.extend({ location: config.locationType }); Router.map(function() { this.route('login', {path: '/'}); this.route('pos'); this.route('error-orders'); this.route('kitchen'); this.route('skara'); }); export default Router;
/** * Disk Adapter */ module.exports = { adapter: require('sails-disk'), connection: { adapter: 'disk' } };
var webpack = require('webpack'); var config = require('./webpack.base.conf'); var ExtractTextPlugin = require('extract-text-webpack-plugin'); var HtmlWebpackPlugin = require('html-webpack-plugin'); config.output.filename = '[name].[chunkhash].js'; config.output.chunkFilename = '[id].[chunkhash].js'; config.devtool = 'source-map'; function generateExtractLoaders(loaders) { return loaders.map(function(loader) { return loader + '-loader?sourceMap'; }).join('!'); } config.vue.loaders = { js: 'babel!jscs', css: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css'])), less: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'less'])), sass: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'sass'])), stylus: ExtractTextPlugin.extract('vue-style-loader', generateExtractLoaders(['css', 'stylus'])), }, config.plugins = (config.plugins || []).concat([ new webpack.DefinePlugin({ 'process.env': { NODE_ENV: '"production"', }, }), new webpack.optimize.UglifyJsPlugin({ compress: { warnings: false, }, }), new webpack.optimize.OccurenceOrderPlugin(), new ExtractTextPlugin('[name].[contenthash].css'), new HtmlWebpackPlugin({ filename: '../index.html', template: 'src/index.html', }), ]); module.exports = config;
var config = { nodeEnv: process.env.NODE_ENV || 'development', database: process.env.MONGODB_URI, database_development: 'mongodb://localhost/dnc-election', googleCaptchaKey: process.env.GOOGLE_CAPTCHA_KEY, paypalUsername: process.env.PAYPAL_USERNAME, paypalPassword: process.env.PAYPAL_PASSWORD, paypalSignature: process.env.PAYPAL_SIGNATURE, paypalClientId: process.env.PAYPAL_CLIENT_ID, paypalClientSecret: process.env.PAYPAL_CLIENT_SECRET, paypalEnv: process.env.PAYPAL_ENV, lobApiKey: process.env.LOB_API_KEY }; module.exports = config;
var express = require("express"); var router = express.Router(); var extend = require('util')._extend; var nodemailer = require("nodemailer"); var transport = nodemailer.createTransport({ service: "Gmail", auth: { user: process.env.EMAIL, pass: process.env.PW } }); var mailOptions = { from : "contact.paulminerichlaw@gmail.com" ,to : "paul@paulminerichlaw.com" ,subject : "Message from contact form on paulminerichlaw.com" ,text : "" } router.get("/vietnamese-translation-available/", function(req, res) { res.render("vietnamese", { title : "Vietnamese Translation Available" ,bread : "vietnamese" }); }); router.all("/", function(req, res) { var email = ""; var errors = []; if(req.body && req.body.email){ email = req.body.email; errors.push("Please enter your name."); errors.push("Please enter a subject."); errors.push("Please answer the security question."); } res.render("contact", { title : "Contact Us" ,bread : "contact" ,errorYellow : true ,hideTitle : true ,email : email ,errors : errors }); }); // TODO : validate email router.post("/submit/", function(req, res) { var errors = []; var renderTemplate = "contact"; var params = extend(req.body, { pageTitle : "Contact Submission" ,hideHead : true ,errors : errors ,hideTitle : true }); if(params.name == null || params.name.length === 0){ params.errors.push("Name is invalid."); }; if(params.email == null || params.email.length === 0){ params.errors.push("Email is invalid."); }; if(params.regarding == null || params.regarding.length === 0){ params.errors.push("Regarding subject is invalid."); }; if(params.securityQuestion == null || params.securityQuestion.length === 0 || params.securityQuestion != 7){ params.errors.push("Security question is invalid."); }; if(params.errors.length === 0){ renderTemplate = "contact-submit"; var mailText = []; var theseMailOptions = extend({}, mailOptions); mailText.push("Name : " + params.name); mailText.push("Email : " + params.email); mailText.push("Regarding : " + params.regarding); mailText.push("Message : " + params.message); theseMailOptions.text = mailText.join("\n"); transport.sendMail(theseMailOptions, function(e){ if(e){ console.log(e); }; }) }; res.render(renderTemplate, params); }); router.get("/privacy/", function(req, res) { res.render("privacy", { hideTitle : true }); }); module.exports = router;
//Generic methods start document.getElementById("loginidsrv").addEventListener("click", login, false); document.getElementById("invoiceapi").addEventListener("click", kcapi, false); document.getElementById("readproductapi").addEventListener("click", readproductapi, false); document.getElementById("writeproductapi").addEventListener("click", writeproductapi, false); document.getElementById("logoutidsrv").addEventListener("click", logout, false); document.getElementById("loginkeycloak").addEventListener("click", loginKeycloak, false); document.getElementById("logoutkeycloak").addEventListener("click", logoutKeycloak, false); //Generic methods end
function getSelectedInformation(txt, element) { txt = txt.toString(); text = jQuery.trim(txt); len = text.length; full = jQuery.trim($(element).text()); field_name = $(element).attr("id"); start = full.indexOf(text)+1; end = start+len-1; return {'from':start, 'to':end, 'text':text, 'field_name':field_name}; } function displayResult(data) { $("#annotation-result").removeClass(); $("#annotation-result").addClass(data.status); $("#annotation-result").text(data.message); $("#annotation-result").fadeIn("slow").fadeTo(2000, 1).fadeOut("slow"); $(".annotation-table:not(:has(a))").hide(); $(".annotation-table:has(a)").show(); bindCurate(); bindRightClicks(); } function getSelectedText() { var txt = ''; if (window.getSelection) { txt = window.getSelection(); // FireFox } else if (document.getSelection) { txt = document.getSelection(); // IE 6/7 } else if (document.selection) { txt = document.selection.createRange().text; } return txt; } function unbindEvents() { $("input[class*='bp_form_complete']").each(function(){ $(this).unbind(); }); } function submit_annotation() { $.post("/annotations", $("#new_annotation input").serialize(), function() { load_curators(); }, "script"); return false; } $(function() { // rightClickMenu(); $("#new_annotation").bind("submit", submit_annotation); $("input#annotation_cancel").bind("click", function(){ $("#new-annotation").hide(); return false; }); $(".dataTable span").contextMenu({ menu: 'annotation-menu' }, function(ontology, el, pos) { var txt = getSelectedText(); if (txt != '') { hash = getSelectedInformation(txt, el); $('#new-annotation').css({top: (pos.docY-125), left: (pos.docX-250)}); ontology_class = "bp_form_complete-"+ontology+"-shortid"; $("input#annotation_ncbo_term_id").removeClass(); $("input#annotation_ncbo_term_id").addClass(ontology_class); unbindEvents(); setup_functions(); $("input#annotation_ncbo_term_id").val(hash.text); $("input#annotation_ncbo_id").val(ontology); $("input#annotation_from").val(hash.from); $("input#annotation_to").val(hash.to); $("input#annotation_field_name").val(hash.field_name); $("#new-annotation").show(); $("input#annotation_ncbo_term_id").focus(); $("input#annotation_ncbo_term_id").keydown(); } return false; }); });
/* Terminal Kit Copyright (c) 2009 - 2021 Cédric Ronvel The MIT License (MIT) Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ "use strict" ; var termkit = require( '../lib/termkit.js' ) ; var term = termkit.terminal ; var ScreenBuffer = termkit.ScreenBuffer ; var Rect = termkit.Rect ; describe( "ScreenBuffer.Rect" , function() { it( "Rect.create( Terminal )" , function() { expect( Rect.create( term ) ).to.be.like( { xmin: 1 , ymin: 1 , xmax: term.width , ymax: term.height , width: term.width , height: term.height , isNull: false } ) ; } ) ; it( "Rect.create( xmin , ymin , xmax , ymax )" , function() { expect( Rect.create( 1 , 2 , 3 , 4 ) ).to.be.like( { xmin: 1 , ymin: 2 , xmax: 3 , ymax: 4 , width: 3 , height: 3 , isNull: false } ) ; } ) ; it( ".clip() should adjust accordingly" , function() { var srcRect , dstRect ; dstRect = Rect.create( { xmin: 0 , ymin: 20 , xmax: 25 , ymax: 45 , isNull: false } ) ; srcRect = Rect.create( { xmin: 10 , ymin: 10 , xmax: 30 , ymax: 40 , isNull: false } ) ; srcRect.clip( dstRect , 0 , 0 , true ) ; expect( dstRect ).to.be.like( { xmin: 10, ymin: 20, xmax: 25, ymax: 40 , width: 16 , height: 21 , isNull: false } ) ; expect( srcRect ).to.be.like( { xmin: 10, ymin: 20, xmax: 25, ymax: 40 , width: 16 , height: 21 , isNull: false } ) ; dstRect = Rect.create( { xmin: 0 , ymin: 20 , xmax: 25 , ymax: 45 } ) ; srcRect = Rect.create( { xmin: 10 , ymin: 10 , xmax: 30 , ymax: 40 } ) ; srcRect.clip( dstRect , 5 , 0 , true ) ; expect( dstRect ).to.be.like( { xmin: 15, ymin: 20, xmax: 25, ymax: 40 , width: 11 , height: 21 , isNull: false } ) ; expect( srcRect ).to.be.like( { xmin: 10, ymin: 20, xmax: 20, ymax: 40 , width: 11 , height: 21 , isNull: false } ) ; dstRect = Rect.create( { xmin: 0 , ymin: 20 , xmax: 25 , ymax: 45 } ) ; srcRect = Rect.create( { xmin: 10 , ymin: 10 , xmax: 30 , ymax: 40 } ) ; srcRect.clip( dstRect , -8 , 0 , true ) ; expect( dstRect ).to.be.like( { xmin: 2, ymin: 20, xmax: 22, ymax: 40 , width: 21 , height: 21 , isNull: false } ) ; expect( srcRect ).to.be.like( { xmin: 10, ymin: 20, xmax: 30, ymax: 40 , width: 21 , height: 21 , isNull: false } ) ; dstRect = Rect.create( { xmin: 0 , ymin: 20 , xmax: 25 , ymax: 45 } ) ; srcRect = Rect.create( { xmin: 10 , ymin: 10 , xmax: 30 , ymax: 40 } ) ; srcRect.clip( dstRect , -31 , 0 , true ) ; expect( dstRect.isNull ).to.be( true ) ; expect( srcRect.isNull ).to.be( true ) ; dstRect = Rect.create( { xmin: 0 , ymin: 20 , xmax: 25 , ymax: 45 } ) ; srcRect = Rect.create( { xmin: 10 , ymin: 10 , xmax: 30 , ymax: 40 } ) ; srcRect.clip( dstRect , -8 , 5 , true ) ; expect( dstRect ).to.be.like( { xmin: 2, ymin: 20, xmax: 22, ymax: 45 , width: 21 , height: 26 , isNull: false } ) ; expect( srcRect ).to.be.like( { xmin: 10, ymin: 15, xmax: 30, ymax: 40 , width: 21 , height: 26 , isNull: false } ) ; dstRect = Rect.create( { xmin: 0 , ymin: 20 , xmax: 25 , ymax: 45 } ) ; srcRect = Rect.create( { xmin: 10 , ymin: 10 , xmax: 30 , ymax: 40 } ) ; srcRect.clip( dstRect , 0 , -21 , true ) ; expect( dstRect.isNull ).to.be( true ) ; expect( srcRect.isNull ).to.be( true ) ; } ) ; } ) ;
'use strict'; var myApp = angular.module('starter', [ 'PhoneGap', 'LocalStorageModule', 'ionic' ]); myApp.config(function($stateProvider, $urlRouterProvider) { $stateProvider .state('home', { url: '/', templateUrl: 'partials/home.html', controller: 'HomeController'}); $urlRouterProvider.otherwise("/"); });
import React, { Component } from 'react'; import { connect } from 'react-redux'; import { createStructuredSelector } from 'reselect'; // containers import ProfilePage from './ProfilePage'; import Collective from './Collective' // components import NotFound from '../components/NotFound'; // actions import fetchProfile from '../actions/profile/fetch_by_slug'; // libs import { canEditUser } from '../lib/admin'; // selectors import { getCurrentCollectiveSelector } from '../selectors/collectives'; import { getCurrentUserProfileSelector } from '../selectors/users'; import { getSessionSelector } from '../selectors/session'; import { getSlugSelector } from '../selectors/router'; export class PublicPage extends Component { componentWillMount() { const { collective, profile, slug, fetchProfile } = this.props; // this means it wasn't server side rendered if (!collective && !profile) { fetchProfile(slug); } } render() { const { collective, profile, session } = this.props; if (collective) { return <Collective /> } else if (profile) { profile.canEditUser = canEditUser(session, profile) return <ProfilePage profile={ profile } /> } else { return <NotFound /> } } } const mapStateToProps = createStructuredSelector({ collective: getCurrentCollectiveSelector, profile: getCurrentUserProfileSelector, session: getSessionSelector, slug: getSlugSelector }); export default connect(mapStateToProps , { fetchProfile })(PublicPage);
require.config({ paths: {   "jquery": "jquery.min", "bootstrap": "bootstrap.min", "TweenMax": "TweenMax.min", // "indicators": "debug.addIndicators", "velocity": "velocity.min", "animationVelocity": "animation.velocity.min", "ScrollMagic": "ScrollMagic.min" }, shim: {   'bootstrap': { deps: ['jquery'], exports: 'bootstrap' }, 'indicators':{ deps: ['ScrollMagic'], exports: 'indicators' }, 'animationVelocity':{ deps: ['ScrollMagic'], exports: 'animationVelocity' } } }); require(['jquery', 'ScrollMagic', 'TweenMax', 'animationVelocity', /*'indicators',*/ 'bootstrap'], function ($, ScrollMagic){ // some code here $(function() { $('[data-toggle="popover"]').popover(); var controller = new ScrollMagic.Controller(); /*var scene = new ScrollMagic.Scene({triggerElement: "#trigger-intro"}) // trigger a velocity opaticy animation .setVelocity(".site-section-title.intro", {opacity: 1}, {duration: 1300}) // .setVelocity(".site-section-title.feature-sub", {opacity: 1}, {duration: 1500}) // .addIndicators() // add indicators (requires plugin) .addTo(controller);*/ /* var scene = new ScrollMagic.Scene({triggerElement: "#trigger-intro"}) // trigger a velocity opaticy animation .setVelocity(".site-section-title.intro-sub", {opacity: 1}, {duration: 1500}) // .addIndicators() // add indicators (requires plugin) .addTo(controller);*/ var scene = new ScrollMagic.Scene({triggerElement: "#trigger-navbar"}) // trigger a velocity opaticy animation .setVelocity("#site-navbar", {backgroundColor: '#1b1d20', backgroundColorAlpha: 0.95}, {duration: 800}) // .addIndicators() // add indicators (requires plugin) .addTo(controller); /*var scene = new ScrollMagic.Scene({triggerElement: "#trigger-whoweare"}) // trigger a velocity opaticy animation .setVelocity(".site-section.whoweare", {opacity: 1}, {duration: 700}) // .addIndicators() // add indicators (requires plugin) .addTo(controller);*/ function scrollToElement(selector, time, verticalOffset) { time = typeof(time) != 'undefined' ? time : 1000; verticalOffset = typeof(verticalOffset) != 'undefined' ? verticalOffset : 0; element = $(selector); offset = element.offset(); offsetTop = offset.top + verticalOffset; console.log($('#navbar').height()); $('html, body').animate({ scrollTop: offsetTop - ($('#navbar').height()/2) }, time); } $('.site-arrow-down').click(function() { scrollToElement('#features'); }); $('a.qq-chat').on('click', function() { $('iframe[allowtransparency="true"]').contents().find('div#launchBtn').click(); }) $('[data-toggle="popover"]').tooltip() }); });
'use strict'; /** * Module dependencies. */ var mongoose = require('mongoose'), errorHandler = require('./errors.server.controller'), Category = mongoose.model('Category'), _ = require('lodash'); /** * Create a Category */ exports.create = function(req, res) { var category = new Category(req.body); category.user = req.user; category.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(category); } }); }; /** * Show the current Category */ exports.read = function(req, res) { res.jsonp(req.category); }; /** * Update a Category */ exports.update = function(req, res) { var category = req.category ; category = _.extend(category , req.body); category.save(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(category); } }); }; /** * Delete an Category */ exports.delete = function(req, res) { var category = req.category ; category.remove(function(err) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(category); } }); }; /** * List of Categories */ exports.list = function(req, res) { Category.find().sort('-created').populate('user', 'displayName').exec(function(err, categories) { if (err) { return res.status(400).send({ message: errorHandler.getErrorMessage(err) }); } else { res.jsonp(categories); } }); }; /** * Category middleware */ exports.categoryByID = function(req, res, next, id) { Category.findById(id).populate('user', 'displayName').exec(function(err, category) { if (err) return next(err); if (! category) return next(new Error('Failed to load Category ' + id)); req.category = category ; next(); }); }; /** * Category authorization middleware */ exports.hasAuthorization = function(req, res, next) { if (req.category.user.id !== req.user.id) { return res.status(403).send({message: 'User is not authorized'}); } next(); };
'use strict'; /** * @ngdoc function * @name yeoAskarApp.controller:MainCtrl * @description * # MainCtrl * Controller of the yeoAskarApp */ angular.module('yeoAskarApp') .controller('MainCtrl', function ($scope) { $scope.awesomeThings = [ 'HTML5 Boilerplate', 'AngularJS', 'Karma' ]; });
var azure = require('azure-storage'); var accountName = 'vscodetest'; var accountKey = 'TVHpH9j2ZQsWdnnoiXe50zfJjezEw4WWRZri9qzN9XE+SroY8XSaUQH31rcxV5w2vdYLyp42uB/BMCxduQcy1A=='; var tableService = azure.createTableService(accountName, accountKey); class Users{ constructor(parameters){ this.parameters = parameters } insert(parameters){ return insertFun(parameters).then(function(response){ return JSON.stringify(response); }).catch(function(error){ console.log(error); return error; }); } delete(parameters){ return deleteFun(parameters).then(function(response){ return JSON.stringify(response); }).catch(function(error){ console.log(error); return error; }); } getOneByIdForPlace(parameters){ return getOneByIdForPlaceFun(parameters).then(function(response){ return JSON.stringify(response); }).catch(function(error){ console.log(error); return error; }); } getAllForPlace(parameters){ return getAllForPlacefun(parameters).then(function(response){ return JSON.stringify(response); }).catch(function(error){ console.log(error); return error; }); } updateOneByIdForPlace(parameters){ return updateOneByIdForPlacefun(parameters).then(function(response){ return JSON.stringify(response); }).catch(function(error){ console.log(error); return error; }); } } module.exports = Users; /* ------------------------------------------------ Funciones operacionales -------------------------------------------------- */ function getAllForPlacefun(parameters){ return new Promise(function(resolve, reject){ var Query = new azure.TableQuery() .where('ID_Pais == ? && Place == ?', parameters.ID_Pais, parameters.Place ); tableService.queryEntities('Users',Query, null, function(error, result, response){ if(!error){ return resolve(result.entries); }else{ return reject(error); } }); }); } function getOneByIdForPlaceFun(parameters){ return new Promise(function(resolve, reject){ var Query = new azure.TableQuery() .where('ID_Pais == ? && Place == ? && ID_Reference == ?', parameters.ID_Pais, parameters.Place, parameters.ID_Reference ); tableService.queryEntities('Users',Query, null, function(error,result,response){ if(error){ return resolve(result.entries); }else{ return reject(error); } }); }); } function insertFun(parameters){ return new Promise(function(resolve, reject){ tableServiceButtons.createTableIfNotExists('Users', function(error,result, response){ if(!error){ tableService.insertEntity('Users', parameters, function(error, result, response){ if(error){ return resolve(result.entries); }else{ return reject(error); } }); } }); }); } function deleteFun(parameters){ return new Promise(function(resolve, reject){ var Query = new azure.TableQuery() .where('ID_Pais == ? && Place == ? && ID_Reference == ?', parameters.ID_Pais, parameters.Place, parameters.ID_Reference ); tableService.deleteEntity('Users',Query, null, function(error,result,response){ if(!error){ return resolve(result.entries); }else{ return reject(error); } }); }); } function updateOneByIdForPlacefun(parameters){ return new Promise(function(resolve, reject){ tableService.replaceEntity('Users',parameters, null, function(error,result,response){ if(!error){ return resolve(result.entries); }else{ return reject(error); } }); }); }
/** * * Store Orders * * Programmer By Emay Komarudin. * 2013 * * **/ Ext.define('App.store.Orders.sCurrency',{ extend : 'Ext.data.Store', model : 'App.model.Orders.mCurrency', proxy: { type: 'rest', url: api_url +'/currency', reader: { type: 'json', root: 'results', successProperty: 'success', totalProperty: 'total' } }, });
"use strict"; var _interopRequireDefault = require("@babel/runtime/helpers/interopRequireDefault"); Object.defineProperty(exports, "__esModule", { value: true }); exports.default = void 0; var _createSvgIcon = _interopRequireDefault(require("./utils/createSvgIcon")); var _jsxRuntime = require("react/jsx-runtime"); var _default = (0, _createSvgIcon.default)( /*#__PURE__*/(0, _jsxRuntime.jsx)("path", { d: "M21 5.47 12 12 7.62 7.62 3 11V8.52L7.83 5l4.38 4.38L21 3v2.47zM21 15h-4.7l-4.17 3.34L6 12.41l-3 2.13V17l2.8-2 6.2 6 5-4h4v-2z" }), 'SsidChartSharp'); exports.default = _default;
export { default } from 'ember-animated-status-label/components/animated-status-label'
/** * Created by ck on 14/05/2017. */ let norm = require('n-orm'); let uuid = require('uuid'); let moment = require('moment'); let UserEntity = require('./erp/UserEntity'); let AccountEntity = require('./erp/AccountEntity'); let ClientEntity = require('./erp/ClientEntity'); let MaterialEntity = require('./erp/MaterialEntity'); let PurchaseEntity = require('./erp/PurchaseEntity'); let PurchaseDetailEntity = require('./erp/PurchaseDetailEntity'); let BarcodeInfoEntity = require('./erp/BarcodeInfoEntity'); let WarehouseEntity = require('./warehouse/WarehouseEntity'); let WarehousePositionEntity = require('./warehouse/WarehousePositionEntity'); let SerialNoEntity = require('./SerialNoEntity'); let SerialTypeEntity = require('./SerialTypeEntity'); let BarCodeDetailEntity = require('./warehouse/BarCodeDetailEntity'); let EntryEntity = require('./warehouse/EntryEntity'); let EntryDetailEntity = require('./warehouse/EntryDetailEntity'); let InventoryEntity = require('./warehouse/InventoryEntity'); let ShelvingEntity = require('./warehouse/ShelvingEntity'); let ShelvingDetailEntity = require('./warehouse/ShelvingDetailEntity'); let MovingEntity = require('./warehouse/MovingEntity'); let MovingDetailEntity = require('./warehouse/MovingDetailEntity'); let DeliveryEntity = require('./warehouse/DeliveryEntity'); let DeliveryDetailEntity = require('./warehouse/DeliveryDetailEntity'); let DeliveryBackDetailEntity = require('./warehouse/DeliveryBackDetailEntity'); let ExWarehouseEntity = require('./erp/ExWarehouseEntity'); let ExWarehouseDetailEntity = require('./erp/ExWarehouseDetailEntity'); let InventoryCheckEntity = require('./warehouse/InventoryCheckEntity'); let InventoryCheckClientEntity = require('./warehouse/InventoryCheckClientEntity'); let InventoryCheckPositionEntity = require('./warehouse/InventoryCheckPositionEntity'); let InventoryCheckDataEntity = require('./warehouse/InventoryCheckDataEntity'); let InventoryCheckFirstEntity = require('./warehouse/InventoryCheckFirstEntity'); let InventoryCheckSecondEntity = require('./warehouse/InventoryCheckSecondEntity'); let InventoryAdjustEntity = require('./warehouse/InventoryAdjustEntity'); let InventoryAdjustOutEntity = require('./warehouse/InventoryAdjustOutEntity'); let InventoryAdjustInEntity = require('./warehouse/InventoryAdjustInEntity'); let InventoryInitializeEntity = require('./warehouse/InventoryInitializeEntity'); let InventoryInitializeDetailEntity = require('./warehouse/InventoryInitializeDetailEntity'); let dbConfig = require('../config/db.json'); module.exports = (app) => { app.use(norm.express(dbConfig)); app.use((req, res, next) => { req.orm.opts({ beforeInsert: (entity) => { if (entity.columns.some((x) => x.name.toLowerCase() == 'creator')) { if (!req.user) req.user = {code: 'system'}; entity['creator'] = req.user.code || entity['creator']; } if (entity.columns.some((x) => x.name.toLowerCase() == 'creationdate')) { entity['creationDate'] = new Date(); } for (let column of entity.columns) { if (column.defaultVal !== undefined) { entity[column.name] = column.defaultVal; if (column.defaultVal === 'uuid') entity[column.name] = uuid.v1(); } } }, beforeUpdate: (entity) => { if (entity.columns.some((x) => x.name.toLowerCase() == 'modifier')) { if (!req.user) req.user = {code: 'system'}; entity['modifier'] = req.user.code || entity['modifier']; } if (entity.columns.some((x) => x.name.toLowerCase() == 'modificationdate')) { entity['modificationDate'] = new Date(); } } }); req.orm.db.config.options = { useUTC: false }; req.orm.db.matchParamType = (value) => { let objectName = Object.prototype.toString.call(value); let paramType = null; switch (objectName) { case '[object Number]': if (Number.isInteger(value)) paramType = req.orm.db.MsSql.BigInt; else paramType = req.orm.db.MsSql.Decimal(16, 4); break; case '[object Date]': paramType = req.orm.db.MsSql.DateTime; break; } return paramType; }; req.orm.defineEntity('User', UserEntity); req.orm.defineEntity('Account', AccountEntity); req.orm.defineEntity('Client', ClientEntity); req.orm.defineEntity('Material', MaterialEntity); req.orm.defineEntity('Purchase', PurchaseEntity); req.orm.defineEntity('PurchaseDetail', PurchaseDetailEntity); req.orm.defineEntity('Warehouse', WarehouseEntity); req.orm.defineEntity('WarehousePosition', WarehousePositionEntity); req.orm.defineEntity('SerialNo', SerialNoEntity); req.orm.defineEntity('SerialType', SerialTypeEntity); req.orm.defineEntity('BarCodeDetail', BarCodeDetailEntity); req.orm.defineEntity('Entry', EntryEntity); req.orm.defineEntity('EntryDetail', EntryDetailEntity); req.orm.defineEntity('Inventory', InventoryEntity); req.orm.defineEntity('Shelving', ShelvingEntity); req.orm.defineEntity('ShelvingDetail', ShelvingDetailEntity); req.orm.defineEntity('Moving', MovingEntity); req.orm.defineEntity('MovingDetail', MovingDetailEntity); req.orm.defineEntity('BarcodeInfo', BarcodeInfoEntity); req.orm.defineEntity('Delivery', DeliveryEntity); req.orm.defineEntity('DeliveryDetail', DeliveryDetailEntity); req.orm.defineEntity('DeliveryBackDetail', DeliveryBackDetailEntity); req.orm.defineEntity('ExWarehouse', ExWarehouseEntity); req.orm.defineEntity('ExWarehouseDetail', ExWarehouseDetailEntity); req.orm.defineEntity('InventoryCheck', InventoryCheckEntity); req.orm.defineEntity('InventoryCheckClient', InventoryCheckClientEntity); req.orm.defineEntity('InventoryCheckPosition', InventoryCheckPositionEntity); req.orm.defineEntity('InventoryCheckData', InventoryCheckDataEntity); req.orm.defineEntity('InventoryCheckFirst', InventoryCheckFirstEntity); req.orm.defineEntity('InventoryCheckSecond', InventoryCheckSecondEntity); req.orm.defineEntity('InventoryAdjust', InventoryAdjustEntity); req.orm.defineEntity('InventoryAdjustOut', InventoryAdjustOutEntity); req.orm.defineEntity('InventoryAdjustIn', InventoryAdjustInEntity); req.orm.defineEntity('InventoryInitialize', InventoryInitializeEntity); req.orm.defineEntity('InventoryInitializeDetail', InventoryInitializeDetailEntity); next(); }); };
import { Dimensions } from 'react-native' export default { cardContainer: { flex: 1, }, container: { flex: 1, }, coverSubtitle: { color: '#FFF', fontSize: 15, fontWeight: '600', }, coverContainer: { marginBottom: 55, position: 'relative', }, coverImage: { height: Dimensions.get('window').width * (3 / 4), width: Dimensions.get('window').width, }, coverMetaContainer: { backgroundColor: 'transparent', paddingBottom: 10, paddingLeft: 10, }, coverName: { color: '#FFF', fontSize: 28, fontWeight: 'bold', paddingBottom: 2, }, coverTitle: { color: '#FFF', fontSize: 24, fontWeight: 'bold', textAlign: 'center', }, coverTitleContainer: { backgroundColor: 'transparent', flex: 1, justifyContent: 'space-between', paddingTop: 45, }, headerContainer: { alignItems: 'center', backgroundColor: '#FFF', }, indicatorTab: { backgroundColor: 'transparent', }, detailsContainer: { alignItems: 'center', flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', marginHorizontal: 10, marginTop: 30, }, commentsContainer: { alignItems: 'center', flexDirection: 'row', flexWrap: 'wrap', justifyContent: 'center', marginHorizontal: 10, marginTop: 30, }, profileImage: { borderColor: '#FFF', borderRadius: 55, borderWidth: 3, height: 110, width: 110, }, profileImageContainer: { bottom: 0, left: 10, position: 'absolute', }, sceneContainer: { marginTop: 10, }, scroll: { backgroundColor: '#FFF', }, tabBar: { backgroundColor: 'transparent', marginBottom: -10, backgroundColor: "#fefefe", }, tabContainer: { flex: 1, marginBottom: 12, marginTop: -55, position: 'relative', zIndex: 10, }, tabRow: { flexWrap: 'wrap', flexDirection: 'column', justifyContent: 'flex-start', alignItems: 'flex-start', flex: 1, }, tabLabelNumber: { color: 'black', fontSize: 14, textAlign: 'left', }, tabLabelText: { color: 'black', fontSize: 22, textAlign: 'center', marginBottom: 2, }, }
/* Copyright (c) 2011 Raphaël Velt * Licensed under the MIT License * Thanks to Vincenzo Cosenza for the italian translation * */ var _nodes = [], _edges = [], _groups = [], _groupVert = [], _overall = [], _sheetID = []; var key = document.location.hash.length > 1 ? document.location.hash.substr(1) : ''; // Namespace var GexfJS = { lensRadius : 200, lensGamma : 0.5, zoneGraphe : { largeur : 0, hauteur : 0, }, oldZoneGraphe : {}, params : { zoomLevel : 0, centreX : 600, centreY : 400, activeNode : -1, currentNode : -1, showEdges : true, useLens : false }, oldParams : {}, minZoom : -3, maxZoom : 10, overviewWidth : 200, overviewHeight : 150, baseWidth : 800, baseHeight : 800, overviewScale : 0.18, totalScroll : 0, autoCompletePosition : 0, i18n : { "fr" : { "search" : "Rechercher un n&oelig;ud", "nodeAttr" : "Attributs", "nodes" : "N&oelig;uds", "inLinks" : "Liens entrants depuis :", "outLinks" : "Liens sortants vers :", "undirLinks" : "Liens non-dirigés avec :", "lensOn" : "Activer le mode loupe", "lensOff" : "Désactiver le mode loupe", "edgeOn" : "Afficher les sommets", "edgeOff" : "Cacher les sommets", "zoomIn" : "S'approcher", "zoomOut" : "S'éloigner", "browserErr" : 'Votre navigateur n\'est malheureusement pas compatible avec les fonctionnalités de ce site<br />Nous vous suggérons d\'utiliser une version récente de <a href="http://www.mozilla.com/" target="_blank">Firefox</a> ou <a href="http://www.google.com/chrome/" target="_blank">Chrome</a>', "modularity_class" : "Classe de modularité", "degree" : "Degr&eacute;", "indegree" : "&frac12; degr&eacute; int&eacute;rieur", "outdegree" : "&frac12; degr&eacute; ext&eacute;rieur", "weighted degree" : "Degr&eacute; pond&eacute;r&eacute;", "weighted indegree" : "&frac12; degr&eacute; int&eacute;rieur pond&eacute;r&eacute;", "weighted outdegree" : "&frac12; degr&eacute; ext&eacute;rieur pond&eacute;r&eacute;", "closnesscentrality" : "Centralit&eacute; de proximit&eacute;", "betweenesscentrality" : "Centralit&eacute; d'interm&eacute;diarit&eacute;", "authority" : "Score d'autorit&eacute; (HITS)", "hub" : "Score de hub (HITS)", "pageranks" : "Score de PageRank" }, "en" : { "search" : "Search nodes", "nodeAttr" : "Attributes", "nodes" : "Nodes", "inLinks" : "Inbound Links from :", "outLinks" : "Outbound Links to :", "undirLinks" : "Undirected links with :", "lensOn" : "Activate lens mode", "lensOff" : "Deactivate lens mode", "edgeOn" : "Show edges", "edgeOff" : "Hide edges", "zoomIn" : "Zoom In", "zoomOut" : "Zoom Out", "browserErr" : 'Your browser cannot properly display this page.<br />We recommend you use the latest <a href="http://www.mozilla.com/" target="_blank">Firefox</a> or <a href="http://www.google.com/chrome/" target="_blank">Chrome</a> version' }, "it" : { "search" : "Cerca i nodi", "nodeAttr" : "Attributi", "nodes" : "Nodi", "inLinks" : "Link in entrata da :", "outLinks" : "Link in uscita verso :", "undirLinks" : "Link non direzionati con :", "lensOn" : "Attiva la lente d'ingrandimento", "lensOff" : "Disattiva la lente d'ingrandimento", "edgeOn" : "Mostra gli spigoli", "edgeOff" : "Nascondi gli spigoli", "zoomIn" : "Zoom in avanti", "zoomOut" : "Zoom indietro", "browserErr" : 'Il tuo browser non pu&ograve; visualizzare correttamente questa pagina.<br />Ti raccomandiamo l\'uso dell\'ultima versione di <a href="http://www.mozilla.com/" target="_blank">Firefox</a> o <a href="http://www.google.com/chrome/" target="_blank">Chrome</a>' } }, lang : "en" } function strLang(_str) { var _l = GexfJS.i18n[GexfJS.lang]; return ( _l[_str] ? _l[_str] : ( GexfJS.i18n["en"][_str] ? GexfJS.i18n["en"][_str] : _str.replace("_"," ") ) ); } function displayNode(_indiceNoeud, _recentre) { GexfJS.params.currentNode = _indiceNoeud; if (_indiceNoeud != -1) { var _d = GexfJS.graph.nodeList[_indiceNoeud], _b = _d.coords.base, _chaine = '', _cG = $("#colonnegauche"); _cG.animate({ "left" : "0px" }, function() { $("#aUnfold").attr("class","leftarrow"); $("#zonecentre").css({ left: _cG.width() + "px" }); }); _chaine += '<h3><div class="largepill" style="background: ' + _d.couleur.base +'"></div>' + _d.label + '</h3>'; _chaine += '<h4>' + ( GexfJS.graph.directed ? strLang("inLinks") : strLang("undirLinks") ) + '</h4><ul>'; for (var i in GexfJS.graph.edgeList) { var _e = GexfJS.graph.edgeList[i] if ( _e.target == _indiceNoeud ) { var _n = GexfJS.graph.nodeList[_e.source]; _chaine += '<li><div class="smallpill" style="background: ' + _n.couleur.base +'"></div><a href="#" onmouseover="GexfJS.params.activeNode = ' + _e.source + '" onclick="displayNode(' + _e.source + ', true); return false;">' + _n.label + '</a></li>'; } } if (GexfJS.graph.directed) _chaine += '</ul><h4>' + strLang("outLinks") + '</h4><ul>'; for (var i in GexfJS.graph.edgeList) { var _e = GexfJS.graph.edgeList[i] if ( _e.source == _indiceNoeud ) { var _n = GexfJS.graph.nodeList[_e.target]; _chaine += '<li><div class="smallpill" style="background: ' + _n.couleur.base +'"></div><a href="#" onmouseover="GexfJS.params.activeNode = ' + _e.target + '" onclick="displayNode(' + _e.target + ', true); return false;">' + _n.label + '</a></li>'; } } _chaine += '</ul>'; _chaine += '<h4>' + strLang("nodeAttr") + '</h4>'; _chaine += '<ul><li><b>id</b> : ' + _d.id + '</li>'; for (var i in _d.attributes) { _chaine += '<li><b>' + strLang(i) + '</b> : ' + _d.attributes[i] + '</li>'; } _chaine += '</ul>'; $("#leftcontent").html(_chaine); if (_recentre) { GexfJS.params.centreX = _b.x; GexfJS.params.centreY = _b.y; } $("#searchinput") .val(_d.label) .removeClass('inputgris'); } } function updateSizes() { // fonction qui met à jour la taille de la zone de travail var _elZC = $("#zonecentre"); var _top = { top : $("#titlebar").height() + "px" } _elZC.css(_top); // ajuste zoneCentre par rapport à la barre $("#colonnegauche").css(_top); GexfJS.zoneGraphe.largeur = _elZC.width(); GexfJS.zoneGraphe.hauteur = _elZC.height(); GexfJS.grapheIdentique = true; // vérifie si GexfJS.zoneGraphe a changé for (var i in GexfJS.zoneGraphe) { GexfJS.grapheIdentique = GexfJS.grapheIdentique && ( GexfJS.zoneGraphe[i] == GexfJS.oldZoneGraphe[i] ); } if (!GexfJS.grapheIdentique) { // S'il y a eu du changement, on change également #carte $("#carte") .attr({ width : GexfJS.zoneGraphe.largeur, height : GexfJS.zoneGraphe.hauteur }) .css({ width : GexfJS.zoneGraphe.largeur + "px", height : GexfJS.zoneGraphe.hauteur + "px" }); // On remet en mémoire zoneGraphe dans oldZoneGraphe for (var i in GexfJS.zoneGraphe) { GexfJS.oldZoneGraphe[i] = GexfJS.zoneGraphe[i]; } } // fin de la fonction updateSizes } function startMove(evt) { evt.preventDefault(); GexfJS.dragOn = true; GexfJS.lastMouse = { x : evt.pageX, y : evt.pageY } GexfJS.sEstDeplace = false; } function endMove(evt) { document.body.style.cursor = "default"; GexfJS.dragOn = false; GexfJS.sEstDeplace = false; } function clicGraphe(evt) { if (!GexfJS.sEstDeplace) { displayNode(GexfJS.params.activeNode); } endMove(); } function deplaceCarte(evt, echelle) { document.body.style.cursor = "move"; var _coord = { x : evt.pageX, y : evt.pageY }; GexfJS.params.centreX += ( GexfJS.lastMouse.x - _coord.x ) / echelle; GexfJS.params.centreY += ( GexfJS.lastMouse.y - _coord.y ) / echelle; GexfJS.lastMouse = _coord; } function moveGraph(evt) { evt.preventDefault(); if (!GexfJS.graph) { return; } GexfJS.mousePosition = { x : evt.pageX - $(this).offset().left, y : evt.pageY - $(this).offset().top } if (GexfJS.dragOn) { deplaceCarte(evt,GexfJS.echelleGenerale); GexfJS.sEstDeplace = true; } else { GexfJS.params.activeNode = getNodeFromPos(GexfJS.mousePosition); document.body.style.cursor = ( GexfJS.params.activeNode != -1 ? "pointer" : "default" ); } } function bougeMini(evt) { if (GexfJS.dragOn) { deplaceCarte(evt,-GexfJS.overviewScale); } } function scrollMap(evt, delta) { GexfJS.totalScroll += delta; if (Math.abs(GexfJS.totalScroll) >= 1) { if (GexfJS.totalScroll < 0) { if (GexfJS.params.zoomLevel > GexfJS.minZoom) { GexfJS.params.zoomLevel--; $("#zoomSlider").slider("value",GexfJS.params.zoomLevel); } } else { if (GexfJS.params.zoomLevel < GexfJS.maxZoom) { GexfJS.params.zoomLevel++; $("#zoomSlider").slider("value",GexfJS.params.zoomLevel); } } GexfJS.totalScroll = 0; } } function initializeMap() { clearInterval(GexfJS.timeRefresh); GexfJS.oldParams = {}; GexfJS.ctxGraphe.clearRect(0, 0, GexfJS.zoneGraphe.largeur, GexfJS.zoneGraphe.hauteur); $("#zoomSlider").slider({ orientation: "vertical", value: GexfJS.params.zoomLevel, min: GexfJS.minZoom, max: GexfJS.maxZoom, range: "min", step: 1, slide: function( event, ui ) { GexfJS.params.zoomLevel = ui.value; } }); $("#overviewzone").css({ width : GexfJS.overviewWidth + "px", height : GexfJS.overviewHeight + "px" }); $("#overview").attr({ width : GexfJS.overviewWidth, height : GexfJS.overviewHeight }); GexfJS.timeRefresh = setInterval(traceMap,60); if (!GexfJS.graph) { chargeGraphe(); } } function chargeGraphe() { var eCols = [], nCols = []; for (i=0; i<_edges.getNumberOfColumns(); i++){ eCols[_edges.getColumnLabel(i)] = i; } for (i=0; i<_nodes.getNumberOfColumns(); i++){ nCols[_nodes.getColumnLabel(i)] = i; } //$.ajax({ // url: ( document.location.hash.length > 1 ? document.location.hash.substr(1) : "default.gexf" ), //dataType: "xml", //success: function(data) { var _s = new Date(); //var _g = $(data).find("graph"), //var _nodes = _g.children().filter("nodes").children(), // _edges = _g.children().filter("edges").children(); GexfJS.graph = { directed : _overall.length > 1 ? _overall.getValue[0,1] : "Directed" , //source : data, nodeList : [], nodeIndexById : [], nodeIndexByLabel : [], edgeList : [] } var _xmin = 1e9, _xmax = -1e9, _ymin = 1e9, _ymax = -1e9; _marge = 30; //$(_nodes).each(function() { for (i=0; i<_nodes.getNumberOfRows(); i++){ //var _n = $(this), //_pos = _n.find("viz\\:position,position"), var _x = _nodes.getValue(i,nCols['X']), _y = _nodes.getValue(i,nCols['Y']); _xmin = Math.min(_x, _xmin); _xmax = Math.max(_x, _xmax); _ymin = Math.min(_y, _ymin); _ymax = Math.max(_y, _ymax); }//); var _echelle = Math.min( ( GexfJS.baseWidth - _marge ) / ( _xmax - _xmin ) , ( GexfJS.baseHeight - _marge ) / ( _ymax - _ymin ) ); var _deltax = ( GexfJS.baseWidth - _echelle * ( _xmin + _xmax ) ) / 2; var _deltay = ( GexfJS.baseHeight - _echelle * ( _ymin + _ymax ) ) / 2; GexfJS.ctxMini.clearRect(0, 0, GexfJS.overviewWidth, GexfJS.overviewHeight); //$(_nodes).each( function() { for (i=0; i<_nodes.getNumberOfRows(); i++){ //var _n = $(this), var _id = _nodes.getValue(i,nCols['Vertex']), _label = _nodes.getValue(i,nCols['Labels Label']); if (_label=="") _label = _id; var _d = { id: _id, label: _label }, //_pos = _n.find("viz\\:position,position"), _x = _nodes.getValue(i,nCols['X']), _y = _nodes.getValue(i,nCols['Y']), _size = _nodes.getValue(i,nCols['Size']), _col = _nodes.getValue(i,nCols['Visual Properties Color']); if (_col.length){ var colS = _col.split(','); } else if(typeof _groups.length == "undefined"){ var colS = getNodeColourByGroup(_id); } else { var colS = [0,0,0]; } var _r = colS[0], _g = colS[1], _b = colS[2]; //_attr = _n.find("attvalue"); _d.coords = { base : { x : _deltax + _echelle * _x + GexfJS.baseWidth/4 , y : _deltay - _echelle * _y + GexfJS.baseHeight , r : _echelle * (_size ? _size : 1 ) * 100 } } _d.couleur = { rgb : { r : _r, g : _g, b : _b }, base : "rgba(" + _r + "," + _g + "," + _b + ",.7)", gris : "rgba(" + Math.floor(84 + .33 * _r) + "," + Math.floor(84 + .33 * _g) + "," + Math.floor(84 + .33 * _b) + ",.5)" } _d.attributes = []; /*$(_attr).each(function() { var _a = $(this), _for = _a.attr("for"); _d.attributes[ _for ? _for : 'attribute_' + _a.attr("id") ] = _a.attr("value"); });*/ for (j in nCols){ _d.attributes[j] = _nodes.getValue(i,nCols[j]); } GexfJS.graph.nodeIndexById.push(_id); GexfJS.graph.nodeIndexByLabel.push(_label); GexfJS.graph.nodeList.push(_d); GexfJS.ctxMini.fillStyle = _d.couleur.base; GexfJS.ctxMini.beginPath(); GexfJS.ctxMini.arc( _d.coords.base.x * GexfJS.overviewScale , _d.coords.base.y * GexfJS.overviewScale , _d.coords.base.r * GexfJS.overviewScale + 1 , 0 , Math.PI*2 , true ); GexfJS.ctxMini.closePath(); GexfJS.ctxMini.fill(); }//); //$(_edges).each(function() { for (i=0; i<_edges.getNumberOfRows(); i++){ //var _e = $(this), var _sid = _edges.getValue(i,eCols['Vertex 1']), _six = GexfJS.graph.nodeIndexById.indexOf(_sid); _tid = _edges.getValue(i,eCols['Vertex 2']), _tix = GexfJS.graph.nodeIndexById.indexOf(_tid); _w = _edges.getValue(i,eCols['Width']); _col = _edges.getValue(i,eCols['Label Text Color']); if (_col.length) { var colS = _col.split(','); var _r = colS[0], _g = colS[1], _b = colS[2]; } else { var _scol = GexfJS.graph.nodeList[_six].couleur.rgb; if (GexfJS.graph.directed) { var _r = _scol.r, _g = _scol.g, _b = _scol.b; } else { var _tcol = GexfJS.graph.nodeList[_tix].couleur.rgb, _r = Math.floor( .5 * _scol.r + .5 * _tcol.r ), _g = Math.floor( .5 * _scol.g + .5 * _tcol.g ), _b = Math.floor( .5 * _scol.b + .5 * _tcol.b ); } } GexfJS.graph.edgeList.push({ source : _six, target : _tix, width : ( _w ? _w : 1 ) * _echelle * 10, couleur : "rgba(" + _r + "," + _g + "," + _b + ",.7)" }); }//); GexfJS.imageMini = GexfJS.ctxMini.getImageData(0, 0, GexfJS.overviewWidth, GexfJS.overviewHeight); $("#loading").hide(); //changeNiveau(0); //} //}); } function getNodeFromPos( _coords ) { for (var i = GexfJS.graph.nodeList.length - 1; i >= 0; i--) { var _d = GexfJS.graph.nodeList[i]; if (_d.visible && _d.dansCadre) { var _c = _d.coords.actuel; _r = Math.sqrt( Math.pow( _c.x - _coords.x , 2) + Math.pow( _c.y - _coords.y , 2 ) ); if ( _r < _c.r ) { return i; } } } return -1; } function calcCoord(x, y, coord) { var _r = Math.sqrt( Math.pow( coord.x - x , 2 ) + Math.pow( coord.y - y , 2 ) ); if ( _r < GexfJS.lensRadius ) { var _cos = ( coord.x - x ) / _r; var _sin = ( coord.y - y ) / _r; var _newr = GexfJS.lensRadius * Math.pow( _r / GexfJS.lensRadius, GexfJS.lensGamma ); var _coeff = ( GexfJS.lensGamma * Math.pow( ( _r + 1 ) / GexfJS.lensRadius, GexfJS.lensGamma - 1 ) ); return { "x" : x + _newr * _cos, "y" : y + _newr * _sin, "r" : _coeff * coord.r } } else { return coord; } } function traceArc(contexte, source, target) { contexte.beginPath(); contexte.moveTo(source.x, source.y); if ( ( source.x == target.x ) && ( source.y == target.y ) ) { var x3 = source.x + 2.8 * source.r; var y3 = source.y - source.r; var x4 = source.x; var y4 = source.y + 2.8 * source.r; contexte.bezierCurveTo(x3,y3,x4,y4,source.x + 1,source.y); } else { var x3 = .3 * target.y - .3 * source.y + .8 * source.x + .2 * target.x; var y3 = .8 * source.y + .2 * target.y - .3 * target.x + .3 * source.x; var x4 = .3 * target.y - .3 * source.y + .2 * source.x + .8 * target.x; var y4 = .2 * source.y + .8 * target.y - .3 * target.x + .3 * source.x; contexte.bezierCurveTo(x3,y3,x4,y4,target.x,target.y); } contexte.stroke(); } function traceMap() { updateSizes(); if (!GexfJS.graph) { return; } var _identique = GexfJS.grapheIdentique; GexfJS.params.mousePosition = ( GexfJS.params.useLens ? ( GexfJS.mousePosition ? ( GexfJS.mousePosition.x + "," + GexfJS.mousePosition.y ) : "out" ) : null ); for (var i in GexfJS.params) { _identique = _identique && ( GexfJS.params[i] == GexfJS.oldParams[i] ); } if (_identique) { return; } else { for (var i in GexfJS.params) { GexfJS.oldParams[i] = GexfJS.params[i]; } } GexfJS.echelleGenerale = Math.pow( Math.sqrt(2), GexfJS.params.zoomLevel ); GexfJS.decalageX = ( GexfJS.zoneGraphe.largeur / 2 ) - ( GexfJS.params.centreX * GexfJS.echelleGenerale ); GexfJS.decalageY = ( GexfJS.zoneGraphe.hauteur / 2 ) - ( GexfJS.params.centreY * GexfJS.echelleGenerale ); var _coefftaille = Math.pow(GexfJS.echelleGenerale, -.15), _coefftxt = 1, _limTxt = 9; GexfJS.ctxGraphe.clearRect(0, 0, GexfJS.zoneGraphe.largeur, GexfJS.zoneGraphe.hauteur); if (GexfJS.params.useLens && GexfJS.mousePosition) { GexfJS.ctxGraphe.fillStyle = "rgba(220,220,250,0.4)"; GexfJS.ctxGraphe.beginPath(); GexfJS.ctxGraphe.arc( GexfJS.mousePosition.x , GexfJS.mousePosition.y , GexfJS.lensRadius , 0 , Math.PI*2 , true ); GexfJS.ctxGraphe.closePath(); GexfJS.ctxGraphe.fill(); } var _noeudCentral = ( ( GexfJS.params.activeNode != -1 ) ? GexfJS.params.activeNode : GexfJS.params.currentNode ); for (var i in GexfJS.graph.nodeList) { var _d = GexfJS.graph.nodeList[i]; _d.coords.actuel = { x : GexfJS.echelleGenerale * _d.coords.base.x + GexfJS.decalageX, y : GexfJS.echelleGenerale * _d.coords.base.y + GexfJS.decalageY, r : GexfJS.echelleGenerale * _d.coords.base.r * _coefftaille } _d.dansCadre = ( ( _d.coords.actuel.x + _d.coords.actuel.r > 0 ) && ( _d.coords.actuel.x - _d.coords.actuel.r < GexfJS.zoneGraphe.largeur ) && ( _d.coords.actuel.y + _d.coords.actuel.r > 0) && (_d.coords.actuel.y - _d.coords.actuel.r < GexfJS.zoneGraphe.hauteur) ); _d.visible = ( GexfJS.params.currentNode == -1 || i == _noeudCentral || GexfJS.params.showEdges ); } var _tagsMisEnValeur = []; if ( _noeudCentral != -1 ) { _tagsMisEnValeur = [ _noeudCentral ]; } var _displayEdges = ( GexfJS.params.showEdges && GexfJS.params.currentNode == -1 ); for (var i in GexfJS.graph.edgeList) { var _d = GexfJS.graph.edgeList[i], _six = _d.source, _tix = _d.target, _ds = GexfJS.graph.nodeList[_six], _dt = GexfJS.graph.nodeList[_tix]; var _lie = false; if (_noeudCentral != -1) { if (_six == _noeudCentral) { _tagsMisEnValeur.push(_tix); _coulTag = _dt.couleur.base; _lie = true; _dt.visible = true; } if (_tix == _noeudCentral) { _tagsMisEnValeur.push(_six); _coulTag = _ds.couleur.base; _lie = true; _ds.visible = true; } } if ( ( _lie || _displayEdges ) && ( _ds.dansCadre || _dt.dansCadre ) && _ds.visible && _dt.visible ) { GexfJS.ctxGraphe.lineWidth = GexfJS.echelleGenerale * _coefftaille * _d.width; var _coords = ( ( GexfJS.params.useLens && GexfJS.mousePosition ) ? calcCoord( GexfJS.mousePosition.x , GexfJS.mousePosition.y , _ds.coords.actuel ) : _ds.coords.actuel ); _coordt = ( (GexfJS.params.useLens && GexfJS.mousePosition) ? calcCoord( GexfJS.mousePosition.x , GexfJS.mousePosition.y , _dt.coords.actuel ) : _dt.coords.actuel ); GexfJS.ctxGraphe.strokeStyle = ( _lie ? _d.couleur : "rgba(100,100,100,0.2)" ); traceArc(GexfJS.ctxGraphe, _coords, _coordt); } } GexfJS.ctxGraphe.lineWidth = 4; GexfJS.ctxGraphe.strokeStyle = "rgba(0,100,0,0.8)"; if (_noeudCentral != -1) { var _dnc = GexfJS.graph.nodeList[_noeudCentral]; _dnc.coords.reel = ( (GexfJS.params.useLens && GexfJS.mousePosition ) ? calcCoord( GexfJS.mousePosition.x , GexfJS.mousePosition.y , _dnc.coords.actuel ) : _dnc.coords.actuel ); } for (var i in GexfJS.graph.nodeList) { var _d = GexfJS.graph.nodeList[i]; if (_d.visible && _d.dansCadre) { if (i != _noeudCentral) { _d.coords.reel = ( ( GexfJS.params.useLens && GexfJS.mousePosition ) ? calcCoord( GexfJS.mousePosition.x , GexfJS.mousePosition.y , _d.coords.actuel ) : _d.coords.actuel ); _d.isTag = ( _tagsMisEnValeur.indexOf(parseInt(i)) != -1 ); GexfJS.ctxGraphe.beginPath(); GexfJS.ctxGraphe.fillStyle = ( ( _tagsMisEnValeur.length && !_d.isTag ) ? _d.couleur.gris : _d.couleur.base ); GexfJS.ctxGraphe.arc( _d.coords.reel.x , _d.coords.reel.y , _d.coords.reel.r , 0 , Math.PI*2 , true ); GexfJS.ctxGraphe.closePath(); GexfJS.ctxGraphe.fill(); } } } for (var i in GexfJS.graph.nodeList) { var _d = GexfJS.graph.nodeList[i]; if (_d.visible && _d.dansCadre) { if (i != _noeudCentral) { var _fs = _d.coords.reel.r * _coefftxt; if (_d.isTag) { if (_noeudCentral != -1) { var _dist = Math.sqrt( Math.pow( _d.coords.reel.x - _dnc.coords.reel.x, 2 ) + Math.pow( _d.coords.reel.y - _dnc.coords.reel.y, 2 ) ); if (_dist > 80) { _fs = Math.max(_limTxt + 2, _fs); } } else { _fs = Math.max(_limTxt + 2, _fs); } } if (_fs > _limTxt) { GexfJS.ctxGraphe.fillStyle = ( ( i != GexfJS.params.activeNode ) && _tagsMisEnValeur.length && ( ( !_d.isTag ) || ( _noeudCentral != -1 ) ) ? "rgba(60,60,60,0.7)" : "rgb(0,0,0)" ); GexfJS.ctxGraphe.font = Math.floor( _fs )+"px Arial"; GexfJS.ctxGraphe.textAlign = "center"; GexfJS.ctxGraphe.textBaseline = "middle"; GexfJS.ctxGraphe.fillText(_d.label, _d.coords.reel.x, _d.coords.reel.y); } } } } if (_noeudCentral != -1) { GexfJS.ctxGraphe.fillStyle = _dnc.couleur.base; GexfJS.ctxGraphe.beginPath(); GexfJS.ctxGraphe.arc( _dnc.coords.reel.x , _dnc.coords.reel.y , _dnc.coords.reel.r , 0 , Math.PI*2 , true ); GexfJS.ctxGraphe.closePath(); GexfJS.ctxGraphe.fill(); GexfJS.ctxGraphe.stroke(); var _fs = Math.max(_limTxt + 2, _dnc.coords.reel.r * _coefftxt) + 2; GexfJS.ctxGraphe.font = "bold " + Math.floor( _fs )+"px Arial"; GexfJS.ctxGraphe.textAlign = "center"; GexfJS.ctxGraphe.textBaseline = "middle"; GexfJS.ctxGraphe.fillStyle = "rgba(255,255,250,0.8)"; GexfJS.ctxGraphe.fillText(_dnc.label, _dnc.coords.reel.x - 2, _dnc.coords.reel.y); GexfJS.ctxGraphe.fillText(_dnc.label, _dnc.coords.reel.x + 2, _dnc.coords.reel.y); GexfJS.ctxGraphe.fillText(_dnc.label, _dnc.coords.reel.x, _dnc.coords.reel.y - 2); GexfJS.ctxGraphe.fillText(_dnc.label, _dnc.coords.reel.x, _dnc.coords.reel.y + 2); GexfJS.ctxGraphe.fillStyle = "rgb(0,0,0)"; GexfJS.ctxGraphe.fillText(_dnc.label, _dnc.coords.reel.x, _dnc.coords.reel.y); } GexfJS.ctxMini.putImageData(GexfJS.imageMini, 0, 0); var _r = GexfJS.overviewScale / GexfJS.echelleGenerale, _x = - _r * GexfJS.decalageX, _y = - _r * GexfJS.decalageY, _w = _r * GexfJS.zoneGraphe.largeur, _h = _r * GexfJS.zoneGraphe.hauteur; GexfJS.ctxMini.strokeStyle = "rgb(220,0,0)"; GexfJS.ctxMini.lineWidth = 3; GexfJS.ctxMini.fillStyle = "rgba(120,120,120,0.2)"; GexfJS.ctxMini.beginPath(); GexfJS.ctxMini.fillRect( _x, _y, _w, _h ); GexfJS.ctxMini.strokeRect( _x, _y, _w, _h ); } function hoverAC() { $("#autocomplete li").removeClass("hover"); $("#liac_"+GexfJS.autoCompletePosition).addClass("hover"); GexfJS.params.activeNode = GexfJS.graph.nodeIndexByLabel.indexOf( $("#liac_"+GexfJS.autoCompletePosition).text() ); } function changePosAC(_n) { GexfJS.autoCompletePosition = _n; hoverAC(); } function updateAutoComplete(_sender) { var _val = new RegExp($(_sender).val(),"ig"); var _ac = $("#autocomplete"); if (_val != GexfJS.dernierAC || _ac.html() == "") { GexfJS.dernierAC = _val; var _chaineAC = "<div><h4>" + strLang("nodes") + "</h4><ul>"; var _n = 0; for (var i in GexfJS.graph.nodeIndexByLabel) { var _l = GexfJS.graph.nodeIndexByLabel[i]; if (_l.search(_val) != -1) { _chaineAC += '<li id="liac_' + _n + '" onmouseover="changePosAC(' + _n + ')"><a href="#" onclick="displayNode(\'' + i + '\', true); return false;"><span>' + GexfJS.graph.nodeList[i].label + '</span></a>'; _n++; } if (_n >= 20) { break; } } GexfJS.autoCompletePosition = 0; _ac.html(_chaineAC + "</ul></div>"); } hoverAC(); _ac.show(); } function updateButtonStates() { $("#lensButton").attr("class",GexfJS.params.useLens?"":"off") .attr("title", strLang( GexfJS.params.showEdges ? "lensOff" : "lensOn" ) ); $("#edgesButton").attr("class",GexfJS.params.showEdges?"":"off") .attr("title", strLang( GexfJS.params.showEdges ? "edgeOff" : "edgeOn" ) ); } function init() { var lang = ( navigator.language ? navigator.language.substr(0,2).toLowerCase() : ( navigator.userLanguage ? navigator.userLanguage.substr(0,2).toLowerCase() : "en" ) ); GexfJS.lang = (GexfJS.i18n[lang] ? lang : "en"); if ( !document.createElement('canvas').getContext ) { $("#bulle").html('<p><b>' + strLang("browserErr") + '</b></p>'); return; } updateButtonStates(); GexfJS.ctxGraphe = document.getElementById('carte').getContext('2d'); GexfJS.ctxMini = document.getElementById('overview').getContext('2d'); updateSizes(); initializeMap(); $("#searchinput") .focus(function() { if ( $(this).is('.inputgris') ) { $(this).val('').removeClass('inputgris'); } }) .keyup(function(evt) { updateAutoComplete(this); }).keydown(function(evt){ var _l = $("#autocomplete li").length; switch (evt.keyCode) { case 40 : if (GexfJS.autoCompletePosition < _l - 1) { GexfJS.autoCompletePosition++; } else { GexfJS.autoCompletePosition = 0; } break; case 38 : if (GexfJS.autoCompletePosition > 0) { GexfJS.autoCompletePosition--; } else { GexfJS.autoCompletePosition = _l - 1; } break; case 27 : $("#autocomplete").slideUp(); break; case 13 : if ($("#autocomplete").is(":visible")) { var _liac = $("#liac_"+GexfJS.autoCompletePosition); if (_liac.length) { $(this).val(_liac.find("span").text()); } } break; default : GexfJS.autoCompletePosition = 0; break; } updateAutoComplete(this); if (evt.keyCode == 38 || evt.keyCode == 40) { return false; } }); $("#recherche").submit(function() { if (GexfJS.graph) { displayNode( GexfJS.graph.nodeIndexByLabel.indexOf($("#searchinput").val()), true); } return false; }); $("#carte") .mousemove(moveGraph) .click(clicGraphe) .mousedown(startMove) .mouseout(function() { GexfJS.mousePosition = null; endMove(); }) .mousewheel(scrollMap); $("#overview") .mousemove(bougeMini) .mousedown(startMove) .mouseup(endMove) .mouseout(endMove) .mousewheel(scrollMap); $("#zoomMinusButton").click(function() { GexfJS.params.zoomLevel = Math.max( GexfJS.minZoom, GexfJS.params.zoomLevel - 1); $("#zoomSlider").slider("value",GexfJS.params.zoomLevel); return false; }) .attr("title", strLang("zoomOut")); $("#zoomPlusButton").click(function() { GexfJS.params.zoomLevel = Math.min( GexfJS.maxZoom, GexfJS.params.zoomLevel + 1); $("#zoomSlider").slider("value",GexfJS.params.zoomLevel); return false; }) .attr("title", strLang("zoomIn")); $(document).click(function(evt) { $("#autocomplete").slideUp(); }); $("#autocomplete").css({ top: ( $("#searchinput").offset().top + $("#searchinput").outerHeight() ) + "px", left: $("#searchinput").offset().left + "px" }); $("#lensButton").click(function () { GexfJS.params.useLens = !GexfJS.params.useLens; return false; }); $("#edgesButton").click(function () { GexfJS.params.showEdges = !GexfJS.params.showEdges; return false; }); $("#helpButton").click(function () { $('#help').dialog('open'); return false; }); $("#help").dialog({modal:true, height:650, width: 750, autoOpen:false, title: "Help"}); $("#aUnfold").click(function() { var _cG = $("#colonnegauche"); if (_cG.offset().left < 0) { _cG.animate({ "left" : "0px" }, function() { $("#aUnfold").attr("class","leftarrow"); $("#zonecentre").css({ left: _cG.width() + "px" }); }); } else { _cG.animate({ "left" : "-" + _cG.width() + "px" }, function() { $("#aUnfold").attr("class","rightarrow"); $("#zonecentre").css({ left: "0" }); }); } return false; }); }//); function buildQueriesforGoogleInit(){ if (key == ""){ $("#loading").hide(); $("#help").dialog({modal:true, height:650, width: 750, autoOpen:true, title: "Help"}); } else { getSheetIDsFromKey(key); var url = 'https://spreadsheets.google.com/tq?key='+key+'&sheet='+_sheetID['Edges']+'&pub=1'; var query = new google.visualization.Query(url); query.send(handleEdgesSelectResponse); } } function handleEdgesSelectResponse(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); } else { _edges = response.getDataTable(); } var url = 'https://spreadsheets.google.com/tq?key='+key+'&sheet='+_sheetID['Vertices']+'&pub=1'; var query = new google.visualization.Query(url); query.send(handleVerticesSelectResponse); } function handleVerticesSelectResponse(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); } else { _nodes = response.getDataTable(); } var url = 'https://spreadsheets.google.com/tq?key='+key+'&sheet='+_sheetID['Groups']+'&pub=1'; var query = new google.visualization.Query(url); query.send(handleGroupsSelectResponse); } function handleGroupsSelectResponse(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); } else { _groups = response.getDataTable(); } var url = 'https://spreadsheets.google.com/tq?key='+key+'&sheet='+_sheetID['Group Vertices']+'&pub=1'; var query = new google.visualization.Query(url); query.send(handleGroupVerticesSelectResponse); } function handleGroupVerticesSelectResponse(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); } else { _groupVertices = response.getDataTable(); } var url = 'https://spreadsheets.google.com/tq?key='+key+'&sheet='+_sheetID['Overall Metrics']+'&pub=1'; var query = new google.visualization.Query(url); query.send(handleOverallMetricsSelectResponse); } function handleOverallMetricsSelectResponse(response) { if (response.isError()) { alert('Error in query: ' + response.getMessage() + ' ' + response.getDetailedMessage()); } else { _overall = response.getDataTable(); } init(); } function getNodeColourByGroup(_label){ var colArr = [0,0,0]; var viewGroupVert = new google.visualization.DataView(_groupVertices); viewGroupVert.setRows(viewGroupVert.getFilteredRows([{column:1, value: _label}])); if (viewGroupVert.getNumberOfRows()>0){ var viewGroups = new google.visualization.DataView(_groups); viewGroups.setRows(viewGroups.getFilteredRows([{column:0, value: viewGroupVert.getValue(0,0)}])); if (viewGroups.getNumberOfRows()>0){ var temp = viewGroups.getValue(0,1); colArr = temp.split(","); } } return colArr; } function getSheetIDsFromKey(key){ var url='https://spreadsheets.google.com/feeds/worksheets/'+key+'/public/basic?alt=json'; $.ajax({ url: url, async: false, dataType: 'json', success: function(json) { for (var u in json['feed']['entry']) { var sheetName = json['feed']['entry'][u]['title']['$t']; if (sheetName == "Edges" || sheetName == "Vertices" ||sheetName == "Groups" || sheetName == "Group Vertices" ||sheetName == "Overall Metrics"){ var sheetQueryString = getQueryVars(json['feed']['entry'][u]['link'][2]['href']); _sheetID[sheetName] = sheetQueryString['sheet']; } } } }); } function getQueryVars(url){ var vars = [], hash; var hashes = url.slice(url.indexOf('?') + 1).split('&'); for(var i = 0; i < hashes.length; i++) { hash = hashes[i].split('='); vars.push(hash[0]); vars[hash[0]] = hash[1]; } return vars; }
import React, { Component } from 'react'; import Home from '../components/Home'; class HomeContainer extends Component { render() { return ( <Home /> ); } }; export default HomeContainer;
function alert(title, message){ var app = [NSApplication sharedApplication]; [app displayDialog:message withTitle:title]; }
/* eslint-disable */ module.exports = { "dirt": { "id": 1, "transform": { "position": [ 0, 0, 0 ], "scale": [ 1, 1, 1 ], "rotation": [ 0, 0, 0, 1 ] }, "name": "Dirt", "block": { "type": "dirt" }, "mesh": { "geometry": "box", "material": "dirt", "visible": true, "mirror": false }, "collision": { "enabled": true, "type": "aabb", "center": [ 0, 0, 0 ], "size": [ 1, 1, 1 ] } }, "grass": { "id": 1, "transform": { "position": [ 0, 0, 0 ], "scale": [ 1, 1, 1 ], "rotation": [ 0, 0, 0, 1 ] }, "block": { "type": "grass" }, "name": "Grass", "mesh": { "geometry": "grass", "material": "blocks", "visible": true, "mirror": false }, "collision": { "enabled": true, "type": "aabb", "center": [ 0, 0, 0 ], "size": [ 1, 1, 1 ] } }, "log": { "id": 1, "transform": { "position": [ 0, 0, 0 ], "scale": [ 1, 1, 1 ], "rotation": [ 0, 0, 0, 1 ] }, "name": "Log", "block": { "type": "log" }, "mesh": { "geometry": "log", "material": "blocks", "visible": true, "mirror": false }, "collision": { "enabled": true, "type": "aabb", "center": [ 0, 0, 0 ], "size": [ 1, 1, 1 ] } }, "leaf": { "id": 1, "transform": { "position": [ 0, 0, 0 ], "scale": [ 1, 1, 1 ], "rotation": [ 0, 0, 0, 1 ] }, "name": "Leaf", "block": { "type": "leaf" }, "mesh": { "geometry": "box", "material": "leaf", "visible": true, "mirror": false }, "collision": { "enabled": true, "type": "aabb", "center": [ 0, 0, 0 ], "size": [ 1, 1, 1 ] } }, "woodPlank": { "id": 1, "transform": { "position": [ 0, 0, 0 ], "scale": [ 1, 1, 1 ], "rotation": [ 0, 0, 0, 1 ] }, "name": "WoodPlank", "block": { "type": "woodPlank" }, "mesh": { "geometry": "box", "material": "woodPlank", "visible": true, "mirror": false }, "collision": { "enabled": true, "type": "aabb", "center": [ 0, 0, 0 ], "size": [ 1, 1, 1 ] } }, "cobble": { "id": 1, "transform": { "position": [ 0, 0, 0 ], "scale": [ 1, 1, 1 ], "rotation": [ 0, 0, 0, 1 ] }, "name": "Cobble", "block": { "type": "cobble" }, "mesh": { "geometry": "box", "material": "cobble", "visible": true, "mirror": false }, "collision": { "enabled": true, "type": "aabb", "center": [ 0, 0, 0 ], "size": [ 1, 1, 1 ] } }, "magicLight": [ { "id": 7, "transform": { "position": [ -1.7061396837234497, 4.111298084259033, 4.590008735656738 ], "scale": [ 1, 1, 1 ], "rotation": [ 0, 0, 0, 1 ] }, "name": "MagicLight", "mesh": { "geometry": "box", "material": "player", "visible": true, "mirror": false }, "block": { "type": "magicLight" }, "collision": { "enabled": true, "type": "aabb", "center": [ 0, 0, 0 ], "size": [ 1, 1, 1 ] } }, { "id": 5, "transform": { "position": [ 0, 0.8620810508728027, 0 ], "scale": [ 1, 1, 1 ], "rotation": [ 0.10015102475881577, 0.8239386081695557, 0.15392374992370605, -0.5360992550849915 ] }, "name": "Light", "light": { "type": "spot", "color": "#ffffff", "ambient": 0.01, "diffuse": 1, "specular": 1, "attenuation": 0.01, "angle": [ 0.9238795325112867, 0.8870108331782217 ], "shadow": true }, "camera": { "type": "persp", "near": 0.3, "far": 30, "fov": 0.9599310885968813, "zoom": 1, "aspect": 0 }, "parent": 0, "animation": { "playing": true, "start": 0, "repeat": 0, "duration": 8, "channels": [ { "channel": "transform.rotation.eulerY", "input": [ 0, 4, 8 ], "output": [ -10, 10, -10 ] } ] } } ], "creeper": require('./creeper.json'), "danceTeapot": require('./danceTeapot.json'), "door": require('./door.json') }
/** * @ngdoc overview * @name ngmNutrition * @description * # ngmNutrition * * Main module of the application. */ angular .module('ngmNutrition', []) .config([ '$routeProvider', '$compileProvider', function ( $routeProvider, $compileProvider) { // https://medium.com/swlh/improving-angular-performance-with-1-line-of-code-a1fb814a6476#.ufea9sjt1 $compileProvider.debugInfoEnabled( false ) // app routes with access rights $routeProvider // nutrition weekly .when( '/nutrition/afghanistan', { templateUrl: '/views/app/dashboard.html', controller: 'DashboardNutritionAssessmentsCtrl', resolve: { access: [ 'ngmAuth', function(ngmAuth) { return ngmAuth.isAuthenticated(); }], } }) // nutrition koboform .when( '/nutrition/afghanistan/form/:mode/:id', { templateUrl: '/views/app/dashboard.html', controller: 'DashboardNutritionKoboFormCtrl', resolve: { access: [ 'ngmAuth', function(ngmAuth) { return ngmAuth.grantPublicAccess(); }], } }) // nutrition koboform edit .when( '/nutrition/afghanistan/form/:mode/:id/:instance_id', { templateUrl: '/views/app/dashboard.html', controller: 'DashboardNutritionKoboFormCtrl', resolve: { access: [ 'ngmAuth', function(ngmAuth) { return ngmAuth.grantPublicAccess(); }], } }) // nutrition weekly dashboard .when( '/nutrition/afghanistan/dashboard', { redirectTo: '/nutrition/afghanistan/dashboard/2018/all/all/all/all/2018-01-01/' + moment().add(1, 'day').startOf('isoWeek').subtract(1, 'day').add(1, 'week').format('YYYY-MM-DD') }) // nutrition weekly dashboard .when( '/nutrition/afghanistan/dashboard/:year/:province/:district/:organization/:week/:start/:end', { templateUrl: '/views/app/dashboard.html', controller: 'DashboardNutritionWeeklyCtrl', resolve: { access: [ 'ngmAuth', function(ngmAuth) { return ngmAuth.isAuthenticated(); }], } }) // nutrition weekly admin .when( '/nutrition/afghanistan/admin', { redirectTo: '/nutrition/afghanistan/admin/2018/all/all/all/all/2018-01-01/' + moment().add(1, 'day').startOf('isoWeek').subtract(1, 'day').add(1, 'week').format('YYYY-MM-DD') }) // nutrition weekly admin .when( '/nutrition/afghanistan/admin/:year/:province/:district/:organization/:week/:start/:end', { templateUrl: '/views/app/dashboard.html', controller: 'DashboardNutritionWeeklyAdminCtrl', resolve: { access: [ 'ngmAuth', function(ngmAuth) { return ngmAuth.isAuthenticated(); }], } }); }]);
var express = require('express'), morgan = require('morgan'), bodyParser = require('body-parser'), compress = require('compression'), methodOverride = require('method-override'), config = require('./config'), path = require('path'); module.exports = function () { var app = express(); app.use(function (req, res, next) { res.locals.url = req.protocol + ':// ' + req.headers.host + req.url; next(); }); app.use(compress({ filter: function (req, res) { return (/json|text/).test(res.getHeader('Content-Type')); }, level: 9 })); // Showing stack errors app.set('showStackError', true); if (process.env.NODE_ENV === 'development') { app.use(morgan('dev')); } else if (process.env.NODE_ENV === 'production') { app.locals.cache = 'memory'; } app.use(bodyParser.json()); // app.use(bodyParser.urlencoded()); app.use(methodOverride()); app.disable('x-powered-by'); app.use(require('cors')()); config.getGlobbedFiles('./**/**/*.route.js').forEach(function (routePath) { require(path.resolve(routePath)).publish(app); }); app.use(function (err, req, res, next) { // If the error object doesn't exists if (!err) return next(); // Log it console.error(err.stack); // Error page res.status(500).json({ error: err.stack }); }); return app; };
// flow-typed signature: cf916fca23433d4bbcb7a75f2604407d // flow-typed version: f821d89401/react-router-dom_v4.x.x/flow_>=v0.53.x declare module "react-router-dom" { declare export class BrowserRouter extends React$Component<{ basename?: string, forceRefresh?: boolean, getUserConfirmation?: GetUserConfirmation, keyLength?: number, children?: React$Node }> {} declare export class HashRouter extends React$Component<{ basename?: string, getUserConfirmation?: GetUserConfirmation, hashType?: "slash" | "noslash" | "hashbang", children?: React$Node }> {} declare export class Link extends React$Component<{ className?: string, to: string | LocationShape, replace?: boolean, children?: React$Node }> {} declare export class NavLink extends React$Component<{ to: string | LocationShape, activeClassName?: string, className?: string, activeStyle?: Object, style?: Object, isActive?: (match: Match, location: Location) => boolean, children?: React$Node, exact?: boolean, strict?: boolean }> {} // NOTE: Below are duplicated from react-router. If updating these, please // update the react-router and react-router-native types as well. declare export type Location = { pathname: string, search: string, hash: string, state?: any, key?: string }; declare export type LocationShape = { pathname?: string, search?: string, hash?: string, state?: any }; declare export type HistoryAction = "PUSH" | "REPLACE" | "POP"; declare export type RouterHistory = { length: number, location: Location, action: HistoryAction, listen( callback: (location: Location, action: HistoryAction) => void ): () => void, push(path: string | LocationShape, state?: any): void, replace(path: string | LocationShape, state?: any): void, go(n: number): void, goBack(): void, goForward(): void, canGo?: (n: number) => boolean, block( callback: (location: Location, action: HistoryAction) => boolean ): void, // createMemoryHistory index?: number, entries?: Array<Location> }; declare export type Match = { params: { [key: string]: ?string }, isExact: boolean, path: string, url: string }; declare export type ContextRouter = {| history: RouterHistory, location: Location, match: Match, staticContext?: StaticRouterContext, |}; declare export type GetUserConfirmation = ( message: string, callback: (confirmed: boolean) => void ) => void; declare type StaticRouterContext = { url?: string }; declare export class StaticRouter extends React$Component<{ basename?: string, location?: string | Location, context: StaticRouterContext, children?: React$Node }> {} declare export class MemoryRouter extends React$Component<{ initialEntries?: Array<LocationShape | string>, initialIndex?: number, getUserConfirmation?: GetUserConfirmation, keyLength?: number, children?: React$Node }> {} declare export class Router extends React$Component<{ history: RouterHistory, children?: React$Node }> {} declare export class Prompt extends React$Component<{ message: string | ((location: Location) => string | boolean), when?: boolean }> {} declare export class Redirect extends React$Component<{ to: string | LocationShape, push?: boolean }> {} declare export class Route extends React$Component<{ component?: React$ComponentType<*>, render?: (router: ContextRouter) => React$Node, children?: React$ComponentType<ContextRouter> | React$Node, path?: string, exact?: boolean, strict?: boolean }> {} declare export class Switch extends React$Component<{ children?: React$Node }> {} declare export function withRouter<P>( Component: React$ComponentType<{| ...ContextRouter, ...P |}> ): React$ComponentType<P>; declare type MatchPathOptions = { path?: string, exact?: boolean, sensitive?: boolean, strict?: boolean }; declare export function matchPath( pathname: string, options?: MatchPathOptions | string ): null | Match; }
import Spinner from './Spinner' it('renders without crashing', () => { const wrapper = shallow(<Spinner />); expect(wrapper).toMatchSnapshot(); });
var searchData= [ ['readline',['readLine',['../class_connection.html#a1df16b436751b686d96c24ca0c498659',1,'Connection']]], ['rearrange',['rearrange',['../class_graph_viewer.html#a3009a66958686ccb7e78b68e37c3c423',1,'GraphViewer']]], ['red',['RED',['../graphviewer_8h.html#a8d23feea868a983c8c2b661e1e16972f',1,'graphviewer.h']]], ['removeedge',['removeEdge',['../class_graph_viewer.html#a9a8ee68c7c12b373affbe4069dd95d72',1,'GraphViewer']]], ['removenode',['removeNode',['../class_graph_viewer.html#a0c418639bb911eb827cabf895915f775',1,'GraphViewer']]] ];
var sp = require('./suppose-process') var ss = require('./suppose-stream') function suppose() { if(typeof arguments[0] === 'string') return sp.apply(null, arguments) return ss.apply(null, arguments) } suppose.process = sp suppose.stream = ss module.exports = suppose
(function () { 'use strict'; angular.module('sidenav.module') .controller('sidenavController', SidenavController); SidenavController.$inject = ['$window', 'currentUser', '$state', '$mdSidenav']; function SidenavController($window, currentUser, $state, $mdSidenav) { var vm = this; vm.user = angular.copy(currentUser.getUser()); vm.dynamicHeight = dynamicHeight; //TODO refactor the navigation functionality to become DRY vm.nav_one = nav_one; vm.nav_two = nav_two; vm.nav_three = nav_three; vm.signOut = signOut; vm.close = close; function close() { $mdSidenav('left').close(); } function signOut() { currentUser.setCurrentUser(null); $state.go('start.welcome'); close(); } function nav_one() { $state.go('app.home'); close(); } function nav_two() { $state.go('app.home.second'); close(); } function nav_three() { $state.go('app.home.three'); close(); } function dynamicHeight() { var height; height = $window.innerHeight; return 'height: ' + height + 'px;' } } }) ();
({ baseUrl: ".", name: "noodles", out: "./../browser-build/noodles.js", deps:function(){ var Config = require.nodeRequire(__dirname + '/../../../lib/noodles').Config, plugins = Config.coretags, languages = Config.languages, files = [], l2 = languages.length, t,plugin; for(var i = 0, l = plugins.length; i < l; i++){ plugin = plugins[i]; files.push('./../plugins/' + plugin + '/' + plugin + '.js'); for(t = 0; t < l2; t++) files.push('./../plugins/'+ plugin + '/' + plugin + '_globalization.' + languages[t] + '.js'); } return files; }() })
Items = new Meteor.Collection('items'); Router.map(function () { this.route('home', { path: '/' }); this.route('items', { controller: 'ItemsController', action: 'customAction' }); }); if (Meteor.isServer) { var seed = function () { Items.remove({}); for (var i = 0; i < 100; i++) { Items.insert({body: 'Item ' + i}); } }; Meteor.startup(seed); var Future = Npm.require('fibers/future'); Meteor.publish('items', function () { var future = new Future; // simulate high latency publish function Meteor.setTimeout(function () { future.return(Items.find()); }, 2000); return future.wait(); }); } if (Meteor.isClient) { Router.configure({ layout: 'layout', notFoundTemplate: 'notFound', loadingTemplate: 'loading' }); Subscriptions = { items: Meteor.subscribe('items') }; ItemsController = RouteController.extend({ template: 'items', /* * During rendering, wait on the items subscription and show the loading * template while the subscription is not ready. This can also be a function * that returns on subscription handle or an array of subscription handles. */ waitOn: Subscriptions['items'], /* * The data function will be called after the subscrition is ready, at * render time. */ data: function () { // we can return anything here, but since I don't want to use 'this' in // as the each parameter, I'm just returning an object here with a named // property. return { items: Items.find() }; }, /* * By default the router will call the *run* method which will render the * controller's template (or the template with the same name as the route) * to the main yield area {{yield}}. But you can provide your own action * methods as well. */ customAction: function () { /* render customController into the main yield */ this.render('items'); /* * You can call render multiple times. You can even pass an object of * template names (keys) to render options (values). Typically, the * options object would include a *to* property specifiying the named * yield to render to. * */ this.render({ itemsAside: { to: 'aside', waitOn: false, data: false }, itemsFooter: { to: 'footer', waitOn: false, data: false } }); } }); }
import {__} from 'embark-i18n'; import {dappPath} from 'embark-utils'; import * as fs from 'fs-extra'; const async = require('async'); const path = require('path'); const os = require('os'); const semver = require('semver'); const constants = require('embark-core/constants'); const DEFAULTS = { "BIN": "parity", "VERSIONS_SUPPORTED": ">=2.2.1", "NETWORK_TYPE": "dev", "NETWORK_ID": 17, "RPC_API": ["web3", "eth", "pubsub", "net", "parity", "private", "parity_pubsub", "traces", "rpc", "shh", "shh_pubsub"], "WS_API": ["web3", "eth", "pubsub", "net", "parity", "private", "parity_pubsub", "traces", "rpc", "shh", "shh_pubsub"], "DEV_WS_API": ["web3", "eth", "pubsub", "net", "parity", "private", "parity_pubsub", "traces", "rpc", "shh", "shh_pubsub", "personal"], "TARGET_GAS_LIMIT": 8000000, "DEV_ACCOUNT": "0x00a329c0648769a73afac7f9381e08fb43dbea72", "DEV_WALLET": { "id": "d9460e00-6895-8f58-f40c-bb57aebe6c00", "version": 3, "crypto": { "cipher": "aes-128-ctr", "cipherparams": {"iv": "74245f453143f9d06a095c6e6e309d5d"}, "ciphertext": "2fa611c4aa66452ef81bd1bd288f9d1ed14edf61aa68fc518093f97c791cf719", "kdf": "pbkdf2", "kdfparams": {"c": 10240, "dklen": 32, "prf": "hmac-sha256", "salt": "73b74e437a1144eb9a775e196f450a23ab415ce2c17083c225ddbb725f279b98"}, "mac": "f5882ae121e4597bd133136bf15dcbcc1bb2417a25ad205041a50c59def812a8" }, "address": "00a329c0648769a73afac7f9381e08fb43dbea72", "name": "Development Account", "meta": "{\"description\":\"Never use this account outside of development chain!\",\"passwordHint\":\"Password is empty string\"}" } }; const safePush = function (set, value) { if (set.indexOf(value) === -1) { set.push(value); } }; class ParityClient { static get DEFAULTS() { return DEFAULTS; } constructor(options) { this.config = options && options.hasOwnProperty('config') ? options.config : {}; this.env = options && options.hasOwnProperty('env') ? options.env : 'development'; this.isDev = options && options.hasOwnProperty('isDev') ? options.isDev : (this.env === 'development'); this.name = constants.blockchain.clients.parity; this.prettyName = "Parity-Ethereum (https://github.com/paritytech/parity-ethereum)"; this.bin = this.config.ethereumClientBin || DEFAULTS.BIN; this.versSupported = DEFAULTS.VERSIONS_SUPPORTED; } isReady(data) { return data.indexOf('Public node URL') > -1; } /** * Check if the client needs some sort of 'keep alive' transactions to avoid freezing by inactivity * @returns {boolean} if keep alive is needed */ needKeepAlive() { return false; } commonOptions() { let config = this.config; let cmd = []; cmd.push(this.determineNetworkType(config)); if (config.networkId) { cmd.push(`--network-id=${config.networkId}`); } if (config.datadir) { cmd.push(`--base-path=${config.datadir}`); } if (config.syncMode === 'light') { cmd.push("--light"); } else if (config.syncMode === 'fast') { cmd.push("--pruning=fast"); } else if (config.syncMode === 'full') { cmd.push("--pruning=archive"); } // In dev mode we store all users passwords in the devPassword file, so Parity can unlock all users from the start if (this.isDev) cmd.push(`--password=${config.account.devPassword}`); else if (config.account && config.account.password) { cmd.push(`--password=${config.account.password}`); } if (Number.isInteger(config.verbosity) && config.verbosity >= 0 && config.verbosity <= 5) { switch (config.verbosity) { case 0: // No option to silent Parity, go to less verbose case 1: cmd.push("--logging=error"); break; case 2: cmd.push("--logging=warn"); break; case 3: cmd.push("--logging=info"); break; case 4: // Debug is the max verbosity for Parity case 5: cmd.push("--logging=debug"); break; default: cmd.push("--logging=info"); break; } } if (this.runAsArchival(config)) { cmd.push("--pruning=archive"); } return cmd; } getMiner() { console.warn(__("Miner requested, but Parity does not embed a miner! Use Geth or install ethminer (https://github.com/ethereum-mining/ethminer)").yellow); return; } getBinaryPath() { return this.bin; } determineVersionCommand() { return this.bin + " --version"; } parseVersion(rawVersionOutput) { let parsed; const match = rawVersionOutput.match(/version Parity(?:-Ethereum)?\/(.*?)\//); if (match) { parsed = match[1].trim(); } return parsed; } runAsArchival(config) { return config.networkId === 1337 || config.archivalMode; } isSupportedVersion(parsedVersion) { let test; try { let v = semver(parsedVersion); v = `${v.major}.${v.minor}.${v.patch}`; test = semver.Range(this.versSupported).test(semver(v)); if (typeof test !== 'boolean') { test = undefined; } } finally { // eslint-disable-next-line no-unsafe-finally return test; } } determineNetworkType(config) { if (this.isDev) { return "--chain=dev"; } if (config.networkType === 'rinkeby') { console.warn(__('Parity does not support the Rinkeby PoA network, switching to Kovan PoA network')); config.networkType = 'kovan'; } else if (config.networkType === 'testnet') { console.warn(__('Parity "testnet" corresponds to Kovan network, switching to Ropsten to be compliant with Geth parameters')); config.networkType = "ropsten"; } if (config.genesisBlock) { config.networkType = config.genesisBlock; } return "--chain=" + config.networkType; } newAccountCommand() { return this.bin + " " + this.commonOptions().join(' ') + " account new "; } parseNewAccountCommandResultToAddress(data = "") { return data.replace(/^\n|\n$/g, ""); } listAccountsCommand() { return this.bin + " " + this.commonOptions().join(' ') + " account list "; } parseListAccountsCommandResultToAddress(data = "") { return data.replace(/^\n|\n$/g, "").split('\n')[0]; } parseListAccountsCommandResultToAddressList(data = "") { const list = data.split('\n'); return list.filter(acc => acc); } parseListAccountsCommandResultToAddressCount(data = "") { const count = this.parseListAccountsCommandResultToAddressList(data).length; return (count > 0 ? count : 0); } determineRpcOptions(config) { let cmd = []; cmd.push("--port=" + config.port); cmd.push("--jsonrpc-port=" + config.rpcPort); cmd.push("--jsonrpc-interface=" + (config.rpcHost === 'localhost' ? 'local' : config.rpcHost)); if (config.rpcCorsDomain) { if (config.rpcCorsDomain === '*') { console.warn('=================================='); console.warn(__('rpcCorsDomain set to "all"')); console.warn(__('make sure you know what you are doing')); console.warn('=================================='); } cmd.push("--jsonrpc-cors=" + (config.rpcCorsDomain === '*' ? 'all' : config.rpcCorsDomain)); } else { console.warn('=================================='); console.warn(__('warning: cors is not set')); console.warn('=================================='); } cmd.push("--jsonrpc-hosts=all"); return cmd; } determineWsOptions(config) { let cmd = []; if (config.wsRPC) { cmd.push("--ws-port=" + config.wsPort); cmd.push("--ws-interface=" + (config.wsHost === 'localhost' ? 'local' : config.wsHost)); if (config.wsOrigins) { const origins = config.wsOrigins.split(','); if (origins.includes('*') || origins.includes("all")) { console.warn('=================================='); console.warn(__('wsOrigins set to "all"')); console.warn(__('make sure you know what you are doing')); console.warn('=================================='); cmd.push("--ws-origins=all"); } else { cmd.push("--ws-origins=" + config.wsOrigins); } } else { console.warn('=================================='); console.warn(__('warning: wsOrigins is not set')); console.warn('=================================='); } cmd.push("--ws-hosts=all"); } return cmd; } initDevChain(datadir, callback) { // Parity requires specific initialization also for the dev chain const self = this; const keysDataDir = datadir + '/keys/DevelopmentChain'; async.waterfall([ function makeDir(next) { fs.mkdirp(keysDataDir, (err, _result) => { next(err); }); }, function createDevAccount(next) { self.createDevAccount(keysDataDir, next); }, function mkDevPasswordDir(next) { fs.mkdirp(path.dirname(self.config.account.devPassword), (err, _result) => { next(err); }); }, function getText(next) { if (!self.config.account.password) { return next(null, os.EOL + 'dev_password'); } fs.readFile(dappPath(self.config.account.password), {encoding: 'utf8'}, (err, content) => { next(err, os.EOL + content); }); }, function updatePasswordFile(passwordList, next) { fs.writeFile(self.config.account.devPassword, passwordList, next); } ], (err) => { callback(err); }); } createDevAccount(keysDataDir, cb) { const devAccountWallet = keysDataDir + '/dev.wallet'; fs.writeFile(devAccountWallet, JSON.stringify(DEFAULTS.DEV_WALLET), function (err) { if (err) { return cb(err); } cb(); }); } mainCommand(address, done) { let self = this; let config = this.config; let rpc_api = this.config.rpcApi; let ws_api = this.config.wsApi; let args = []; async.series([ function commonOptions(callback) { let cmd = self.commonOptions(); args = args.concat(cmd); callback(null, cmd); }, function rpcOptions(callback) { let cmd = self.determineRpcOptions(self.config); args = args.concat(cmd); callback(null, cmd); }, function wsOptions(callback) { let cmd = self.determineWsOptions(self.config); args = args.concat(cmd); callback(null, cmd); }, function dontGetPeers(callback) { if (config.nodiscover) { args.push("--no-discovery"); return callback(null, "--no-discovery"); } callback(null, ""); }, function vmDebug(callback) { if (config.vmdebug) { args.push("--tracing on"); return callback(null, "--tracing on"); } callback(null, ""); }, function maxPeers(callback) { let cmd = "--max-peers=" + config.maxpeers; args.push(cmd); callback(null, cmd); }, function bootnodes(callback) { if (config.bootnodes && config.bootnodes !== "" && config.bootnodes !== []) { args.push("--bootnodes=" + config.bootnodes); return callback(null, "--bootnodes=" + config.bootnodes); } callback(""); }, function whisper(callback) { if (config.whisper) { safePush(rpc_api, 'shh'); safePush(rpc_api, 'shh_pubsub'); safePush(ws_api, 'shh'); safePush(ws_api, 'shh_pubsub'); args.push("--whisper"); return callback(null, "--whisper"); } callback(""); }, function rpcApi(callback) { args.push('--jsonrpc-apis=' + rpc_api.join(',')); callback(null, '--jsonrpc-apis=' + rpc_api.join(',')); }, function wsApi(callback) { args.push('--ws-apis=' + ws_api.join(',')); callback(null, '--ws-apis=' + ws_api.join(',')); }, function accountToUnlock(callback) { if (self.isDev) { let unlockAddressList = self.config.unlockAddressList ? self.config.unlockAddressList : DEFAULTS.DEV_ACCOUNT; args.push("--unlock=" + unlockAddressList); return callback(null, "--unlock=" + unlockAddressList); } let accountAddress = ""; if (config.account && config.account.address) { accountAddress = config.account.address; } else { accountAddress = address; } if (accountAddress && !self.isDev) { args.push("--unlock=" + accountAddress); return callback(null, "--unlock=" + accountAddress); } callback(null, ""); }, function gasLimit(callback) { if (config.targetGasLimit) { args.push("--gas-floor-target=" + config.targetGasLimit); return callback(null, "--gas-floor-target=" + config.targetGasLimit); } // Default Parity gas limit is 4700000: let's set to the geth default args.push("--gas-floor-target=" + DEFAULTS.TARGET_GAS_LIMIT); return callback(null, "--gas-floor-target=" + DEFAULTS.TARGET_GAS_LIMIT); }, function customOptions(callback) { if (config.customOptions) { if (Array.isArray(config.customOptions)) { config.customOptions = config.customOptions.join(' '); } args.push(config.customOptions); return callback(null, config.customOptions); } callback(null, ''); } ], function (err) { if (err) { throw new Error(err.message); } return done(self.bin, args); }); } } module.exports = ParityClient;
import React from 'react' import PropTypes from 'prop-types' import { Menu, Icon, Popover } from 'antd' import { Link } from 'dva/router' import uri from 'utils/uri' import { l } from 'utils/localization' import styles from './Header.less' import { classnames } from 'utils' function createMenu(items, handleClick, mode = 'horizontal') { let current = uri.current().split('/')[1] return ( <Menu onClick={handleClick} selectedKeys={[current]} mode={mode}> {items.map(item => (<Menu.Item key={item.path.split('/')[1]}><Link to={item.path}><Icon type={item.icon || 'appstore-o'} /><span>{l(item.name)}</span></Link></Menu.Item>))} </Menu> ) } const HeaderNav = React.createClass({ getInitialState() { return { current: uri.current().split('/')[1], } }, handleClick(e) { this.setState({ current: e.key, }) }, render() { return (<div> <div className={styles.headerNavItems}> {createMenu(this.props.items, this.handleClick)} </div> <Popover content={createMenu(this.props.items, this.handleClick, 'inline')} trigger="click" overlayClassName={styles.headerNavMenus}> <div className={classnames(styles.headerNavDropdown, this.props.barClassName)}> <Icon type="bars" /> </div> </Popover> </div> ) }, }) export default HeaderNav
// vendor dependencies var expect = require('chai').expect var rewire = require('rewire') var path = require('path') // local dependencies var enduro = require(ENDURO_FOLDER + '/index') var babel = require(global.ENDURO_FOLDER + '/libs/babel/babel') var request = require('request-promise') var theme_manager = require(ENDURO_FOLDER + '/libs/theme_manager/theme_manager') describe('Theme manager server endpoints', function () { before(function () { enduro.silent() }) it('should fetch list of all themes', function () { return theme_manager.get_all_themes() .then((theme_list) => { theme_list = JSON.parse(theme_list) expect(theme_list).to.be.an('array') }) }) it('should fetch info for the \'mirror\' theme', function () { return theme_manager.fetch_theme_info_by_name('mirror', { stealth: true }) .then((theme_info) => { expect(theme_info).to.be.an.object expect(theme_info.name).to.equal('mirror') }) }) })
import mongoose from 'mongoose'; const { Schema }=mongoose; const CommentSchema = new Schema({ content: { type: String, required: true }, author: { type: String, required: true } }); if (!CommentSchema.options.toJSON) CommentSchema.options.toJSON = {}; CommentSchema.options.toJSON.transform = function (doc, ret, options) { ret.id = ret._id; delete ret._id; delete ret.__v; return ret; }; const Comment = mongoose.model('comment', CommentSchema); export default Comment;
$(function() { return $('.modal-link').click(function() { var resource; resource = $(this).attr('data-resource'); return $.post(resource.replace(/_/g, "/"), { id: $(this).attr('data-id') }, function(data) { var form, messages, submit; $('#modal').html(data); $('#' + resource).modal('show'); form = $('#' + resource + '_form'); submit = $('#' + resource + '_submit'); messages = $('#' + resource + '_messages'); submit.click(function() { return form.submit(); }); return form.submit(function() { $.post(form.attr('action'), form.serialize(), function(data) { messages.html(data.messages); if (data.status === "OK") { $('#' + resource).modal('hide'); return window.location.reload(); } }, "json"); return false; }); }); }); });
/** * * app.js * * This is the entry file for the application, mostly just setup and boilerplate * code. Routes are configured at the end of this file! * */ // Load the ServiceWorker, the Cache polyfill, the manifest.json file and the .htaccess file import 'file?name=[name].[ext]!../serviceworker.js'; import 'file?name=[name].[ext]!../manifest.json'; import 'file?name=[name].[ext]!../.htaccess'; // Check for ServiceWorker support before trying to install it if ('serviceWorker' in navigator) { navigator.serviceWorker.register('/serviceworker.js').then(() => { // Registration was successful }).catch(() => { // Registration failed }); } else { // No ServiceWorker Support } // Import all the third party stuff import React from 'react'; import ReactDOM from 'react-dom'; import { Provider } from 'react-redux'; import { Router, Route } from 'react-router'; import { createStore, applyMiddleware } from 'redux'; import thunk from 'redux-thunk'; import FontFaceObserver from 'fontfaceobserver'; import createHistory from 'history/lib/createBrowserHistory'; import injectTapEventPlugin from 'react-tap-event-plugin'; // Needed for onTouchTap // http://stackoverflow.com/a/34015469/988941 injectTapEventPlugin(); // Observer loading of Open Sans (to remove open sans, remove the <link> tag in the index.html file and this observer) const openSansObserver = new FontFaceObserver('Open Sans', {}); // When Open Sans is loaded, add the js-open-sans-loaded class to the body openSansObserver.check().then(() => { document.body.classList.add('js-open-sans-loaded'); }, () => { document.body.classList.remove('js-open-sans-loaded'); }); // Import the pages import App from './components/App.react'; import Home from './components/pages/Home'; import Auth from './components/pages/Auth'; import ReadmePage from './components/pages/ReadmePage.react'; import NotFoundPage from './components/pages/NotFound.react'; // Import the CSS file, which HtmlWebpackPlugin transfers to the build folder import '../css/main.css'; // Create the store with the redux-thunk middleware, which allows us // to do asynchronous things in the actions import rootReducer from './reducers/rootReducer'; const createStoreWithMiddleware = applyMiddleware(thunk)(createStore); const store = createStoreWithMiddleware(rootReducer); // Make reducers hot reloadable, see http://stackoverflow.com/questions/34243684/make-redux-reducers-and-other-non-components-hot-loadable if (module.hot) { module.hot.accept('./reducers/rootReducer', () => { const nextRootReducer = require('./reducers/rootReducer').default; store.replaceReducer(nextRootReducer); }); } // Mostly boilerplate, except for the Routes. These are the pages you can go to, // which are all wrapped in the App component, which contains the navigation etc ReactDOM.render( <Provider store={store}> <Router history={createHistory()}> <Route component={App}> <Route path="/" component={Home} /> <Route path="auth" component={Auth} /> <Route path="/readme" component={ReadmePage} /> <Route path="*" component={NotFoundPage} /> </Route> </Router> </Provider>, document.getElementById('app') );
function AddRemoveElements(arr){ let data = []; for(let i = 0; i < arr.length; i++){ let splitted = arr[i] .split(' '); let num = Number(splitted[1]); switch(splitted[0]){ case "add": data.push(num); break; case "remove": if(typeof data[num] !== 'undefined') data.splice(num, 1); break; } } for(let i = 0; i < data.length; i++){ console.log(data[i]); } }
import React from "react"; import PropTypes from "prop-types"; import { color } from "utils"; import CountUp from "react-countup"; import { LineChart, Line, XAxis, YAxis, CartesianGrid, ResponsiveContainer } from "recharts"; import styles from "./cpu.less"; const countUpProps = { start: 0, duration: 2.75, useEasing: true, useGrouping: true, separator: ",", }; function Cpu({ usage, space, cpu, data }) { return (<div className={styles.cpu}> <div className={styles.number}> <div className={styles.item}> <p>usage</p> <p><CountUp end={usage} suffix="GB" {...countUpProps} /></p> </div> <div className={styles.item}> <p>space</p> <p><CountUp end={space} suffix="GB" {...countUpProps} /></p> </div> <div className={styles.item}> <p>cpu</p> <p><CountUp end={cpu} suffix="%" {...countUpProps} /></p> </div> </div> <ResponsiveContainer minHeight={300}> <LineChart data={data} margin={{ left: -40 }}> <XAxis dataKey="name" axisLine={{ stroke: color.borderBase, strokeWidth: 1 }} tickLine={false} /> <YAxis axisLine={false} tickLine={false} /> <CartesianGrid vertical={false} stroke={color.borderBase} strokeDasharray="3 3" /> <Line type="monotone" connectNulls dataKey="cpu" stroke={color.blue} fill={color.blue} /> </LineChart> </ResponsiveContainer> </div>); } Cpu.propTypes = { data: PropTypes.array, usage: PropTypes.number, space: PropTypes.number, cpu: PropTypes.number, }; export default Cpu;
jsonp_handler({ "version": "1", "build": 804, "title": "kage-glyph-sample", "minruntime": 1, "baseurl": "http://rawgit.com/ksanaforge/kage-glyph-sample/master/", "description": "", "browserify": { "external": [ "react", "react-dom", "react-addons-update", "react-addons-pure-render-mixin", "bootstrap", "ksana-jsonrom", "ksana-analyzer", "ksana-database", "ksana-search", "ksana-simple-api" ] }, "files": [ "index.html", "index.css", "react-bundle.js", "ksana-bundle.js", "bundle.js", "ksana.js" ], "filesizes": [ 547, 84, 671592, 136638, 354004, 861 ], "filedates": [ "2015-11-05T10:01:21.203Z", "2015-09-26T14:20:45.107Z", "2015-10-15T10:26:00.967Z", "2015-10-15T10:25:56.627Z", "2015-11-19T09:38:59.184Z", "2015-11-19T09:25:40.856Z" ], "date": "2015-11-19T09:39:00.175Z" })
//remember signatures that have occured within a time. module.exports = function (time) { time = time || 1000 var keys = {} var hist = [] function cleanup() { var n = Date.now() while(hist.length) { var item = hist[0] if(keys[item] > n) return hist.shift() delete keys[item] } } return { add: function (item) { keys[item] = Date.now() + time hist.push(item) }, check: function (item) { var t = keys[item] > Date.now() cleanup() return t } } }