diff --git a/dist/base.js b/dist/base.js index 207e87976..0929c3d6d 100644 --- a/dist/base.js +++ b/dist/base.js @@ -1,4 +1,4 @@ -/*! +/* ! * jQuery Mousewheel 3.1.13 * * Copyright jQuery Foundation and other contributors @@ -7,10 +7,10 @@ */ (function (factory) { - if ( typeof define === 'function' && define.amd ) { + if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. - define(['../core/jquery'], factory); - } else if (typeof exports === 'object') { + define(["../core/jquery"], factory); + } else if (typeof exports === "object") { // Node/CommonJS style for Browserify module.exports = factory; } else { @@ -19,9 +19,9 @@ } }(function ($) { - var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], - toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? - ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], + var toFix = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], + toBind = ( "onwheel" in document || document.documentMode >= 9 ) ? + ["wheel"] : ["mousewheel", "DomMouseScroll", "MozMousePixelScroll"], slice = Array.prototype.slice, nullLowestDeltaTimeout, lowestDelta; @@ -32,9 +32,9 @@ } var special = $.event.special.mousewheel = { - version: '3.1.12', + version: "3.1.12", - setup: function() { + setup: function () { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); @@ -44,7 +44,7 @@ } }, - teardown: function() { + teardown: function () { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); @@ -61,17 +61,17 @@ }; $.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); + mousewheel: function (fn) { + return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, - unmousewheel: function(fn) { - return this.unbind('mousewheel', fn); + unmousewheel: function (fn) { + return this.unbind("mousewheel", fn); } }); - function handler(event) { + function handler (event) { var orgEvent = event || window.event, args = slice.call(arguments, 1), delta = 0, @@ -81,16 +81,16 @@ offsetX = 0, offsetY = 0; event = $.event.fix(orgEvent); - event.type = 'mousewheel'; + event.type = "mousewheel"; // Old school scrollwheel delta - if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } - if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } - if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } - if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } + if ( "detail" in orgEvent ) { deltaY = orgEvent.detail * -1; } + if ( "wheelDelta" in orgEvent ) { deltaY = orgEvent.wheelDelta; } + if ( "wheelDeltaY" in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } + if ( "wheelDeltaX" in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event - if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { + if ( "axis" in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaX = deltaY * -1; deltaY = 0; } @@ -99,11 +99,11 @@ delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) - if ( 'deltaY' in orgEvent ) { + if ( "deltaY" in orgEvent ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } - if ( 'deltaX' in orgEvent ) { + if ( "deltaX" in orgEvent ) { deltaX = orgEvent.deltaX; if ( deltaY === 0 ) { delta = deltaX * -1; } } @@ -149,9 +149,9 @@ } // Get a whole, normalized value for the deltas - delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); - deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); - deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); + delta = Math[ delta >= 1 ? "floor" : "ceil" ](delta / lowestDelta); + deltaX = Math[ deltaX >= 1 ? "floor" : "ceil" ](deltaX / lowestDelta); + deltaY = Math[ deltaY >= 1 ? "floor" : "ceil" ](deltaY / lowestDelta); // Normalise offsetX and offsetY properties if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { @@ -184,11 +184,11 @@ return ($.event.dispatch || $.event.handle).apply(this, args); } - function nullLowestDelta() { + function nullLowestDelta () { lowestDelta = null; } - function shouldAdjustOldDeltas(orgEvent, absDelta) { + function shouldAdjustOldDeltas (orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas @@ -196,15 +196,15 @@ // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. - return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; + return special.settings.adjustOldDeltas && orgEvent.type === "mousewheel" && absDelta % 120 === 0; } }));/** * Created by User on 2017/3/21. */ -BI.FormulaCollections = ["abs","ABS","acos","ACOS","acosh","ACOSH","add2array","ADD2ARRAY","and","AND","array","ARRAY","asin","ASIN","asinh","ASINH","atan","ATAN","atan2","ATAN2","atanh","ATANH","average","AVERAGE","bitnot","BITNOT","bitoperation","BITOPERATION","ceiling","CEILING","char","CHAR","circular","CIRCULAR","class","CLASS","cnmoney","CNMONEY","code","CODE","col","COL","colcount","COLCOUNT","colname","COLNAME","combin","COMBIN","concatenate","CONCATENATE","correl","CORREL","cos","COS","cosh","COSH","count","COUNT","crosslayertotal","CROSSLAYERTOTAL","date","DATE","datedelta","DATEDELTA","datedif","DATEDIF","dateinmonth","DATEINMONTH","dateinquarter","DATEINQUARTER","dateinweek","DATEINWEEK","dateinyear","DATEINYEAR","datesubdate","DATESUBDATE","datetime","DATETIME","datetonumber","DATETONUMBER","day","DAY","days360","DAYS360","daysofmonth","DAYSOFMONTH","daysofquarter","DAYSOFQUARTER","daysofyear","DAYSOFYEAR","dayvalue","DAYVALUE","decimal","DECIMAL","decode","DECODE","degrees","DEGREES","encode","ENCODE","endwith","ENDWITH","enmoney","ENMONEY","ennumber","ENNUMBER","eval","EVAL","even","EVEN","exact","EXACT","exp","EXP","fact","FACT","fields","FIELDS","filename","FILENAME","filesize","FILESIZE","filetype","FILETYPE","find","FIND","floor","FLOOR","format","FORMAT","getuserdepartments","GETUSERDEPARTMENTS","getuserjobtitles","GETUSERJOBTITLES","greparray","GREPARRAY","hierarchy","HIERARCHY","hour","HOUR","i18n","I18N","if","IF","inarray","INARRAY","index","INDEX","indexof","INDEXOF","indexofarray","INDEXOFARRAY","int","INT","isnull","ISNULL","joinarray","JOINARRAY","jvm","JVM","layertotal","LAYERTOTAL","left","LEFT","len","LEN","let","LET","ln","LN","log","LOG","log10","LOG10","lower","LOWER","lunar","LUNAR","map","MAP","maparray","MAPARRAY","max","MAX","median","MEDIAN","mid","MID","min","MIN","minute","MINUTE","mod","MOD","mom","MOM","month","MONTH","monthdelta","MONTHDELTA","now","NOW","numto","NUMTO","nvl","NVL","odd","ODD","or","OR","pi","PI","power","POWER","product","PRODUCT","promotion","PROMOTION","proper","PROPER","proportion","PROPORTION","radians","RADIANS","rand","RAND","randbetween","RANDBETWEEN","range","RANGE","rank","RANK","records","RECORDS","regexp","REGEXP","removearray","REMOVEARRAY","repeat","REPEAT","replace","REPLACE","reverse","REVERSE","reversearray","REVERSEARRAY","right","RIGHT","round","ROUND","round5","ROUND5","rounddown","ROUNDDOWN","roundup","ROUNDUP","row","ROW","rowcount","ROWCOUNT","second","SECOND","seq","SEQ","sign","SIGN","sin","SIN","sinh","SINH","slicearray","SLICEARRAY","sort","SORT","sortarray","SORTARRAY","split","SPLIT","sql","SQL","sqrt","SQRT","startwith","STARTWITH","stdev","STDEV","substitute","SUBSTITUTE","sum","SUM","sumsq","SUMSQ","switch","SWITCH","tabledatafields","TABLEDATAFIELDS","tabledatas","TABLEDATAS","tables","TABLES","tan","TAN","tanh","TANH","time","TIME","tobigdecimal","TOBIGDECIMAL","tobinary","TOBINARY","todate","TODATE","today","TODAY","todouble","TODOUBLE","tohex","TOHEX","toimage","TOIMAGE","tointeger","TOINTEGER","tooctal","TOOCTAL","totext","TOTEXT","treelayer","TREELAYER","trim","TRIM","trunc","TRUNC","uniquearray","UNIQUEARRAY","upper","UPPER","uuid","UUID","value","VALUE","webimage","WEBIMAGE","week","WEEK","weekdate","WEEKDATE","weekday","WEEKDAY","weightedaverage","WEIGHTEDAVERAGE","year","YEAR","yeardelta","YEARDELTA"]; +BI.FormulaCollections = ["abs", "ABS", "acos", "ACOS", "acosh", "ACOSH", "add2array", "ADD2ARRAY", "and", "AND", "array", "ARRAY", "asin", "ASIN", "asinh", "ASINH", "atan", "ATAN", "atan2", "ATAN2", "atanh", "ATANH", "average", "AVERAGE", "bitnot", "BITNOT", "bitoperation", "BITOPERATION", "ceiling", "CEILING", "char", "CHAR", "circular", "CIRCULAR", "class", "CLASS", "cnmoney", "CNMONEY", "code", "CODE", "col", "COL", "colcount", "COLCOUNT", "colname", "COLNAME", "combin", "COMBIN", "concatenate", "CONCATENATE", "correl", "CORREL", "cos", "COS", "cosh", "COSH", "count", "COUNT", "crosslayertotal", "CROSSLAYERTOTAL", "date", "DATE", "datedelta", "DATEDELTA", "datedif", "DATEDIF", "dateinmonth", "DATEINMONTH", "dateinquarter", "DATEINQUARTER", "dateinweek", "DATEINWEEK", "dateinyear", "DATEINYEAR", "datesubdate", "DATESUBDATE", "datetime", "DATETIME", "datetonumber", "DATETONUMBER", "day", "DAY", "days360", "DAYS360", "daysofmonth", "DAYSOFMONTH", "daysofquarter", "DAYSOFQUARTER", "daysofyear", "DAYSOFYEAR", "dayvalue", "DAYVALUE", "decimal", "DECIMAL", "decode", "DECODE", "degrees", "DEGREES", "encode", "ENCODE", "endwith", "ENDWITH", "enmoney", "ENMONEY", "ennumber", "ENNUMBER", "eval", "EVAL", "even", "EVEN", "exact", "EXACT", "exp", "EXP", "fact", "FACT", "fields", "FIELDS", "filename", "FILENAME", "filesize", "FILESIZE", "filetype", "FILETYPE", "find", "FIND", "floor", "FLOOR", "format", "FORMAT", "getuserdepartments", "GETUSERDEPARTMENTS", "getuserjobtitles", "GETUSERJOBTITLES", "greparray", "GREPARRAY", "hierarchy", "HIERARCHY", "hour", "HOUR", "i18n", "I18N", "if", "IF", "inarray", "INARRAY", "index", "INDEX", "indexof", "INDEXOF", "indexofarray", "INDEXOFARRAY", "int", "INT", "isnull", "ISNULL", "joinarray", "JOINARRAY", "jvm", "JVM", "layertotal", "LAYERTOTAL", "left", "LEFT", "len", "LEN", "let", "LET", "ln", "LN", "log", "LOG", "log10", "LOG10", "lower", "LOWER", "lunar", "LUNAR", "map", "MAP", "maparray", "MAPARRAY", "max", "MAX", "median", "MEDIAN", "mid", "MID", "min", "MIN", "minute", "MINUTE", "mod", "MOD", "mom", "MOM", "month", "MONTH", "monthdelta", "MONTHDELTA", "now", "NOW", "numto", "NUMTO", "nvl", "NVL", "odd", "ODD", "or", "OR", "pi", "PI", "power", "POWER", "product", "PRODUCT", "promotion", "PROMOTION", "proper", "PROPER", "proportion", "PROPORTION", "radians", "RADIANS", "rand", "RAND", "randbetween", "RANDBETWEEN", "range", "RANGE", "rank", "RANK", "records", "RECORDS", "regexp", "REGEXP", "removearray", "REMOVEARRAY", "repeat", "REPEAT", "replace", "REPLACE", "reverse", "REVERSE", "reversearray", "REVERSEARRAY", "right", "RIGHT", "round", "ROUND", "round5", "ROUND5", "rounddown", "ROUNDDOWN", "roundup", "ROUNDUP", "row", "ROW", "rowcount", "ROWCOUNT", "second", "SECOND", "seq", "SEQ", "sign", "SIGN", "sin", "SIN", "sinh", "SINH", "slicearray", "SLICEARRAY", "sort", "SORT", "sortarray", "SORTARRAY", "split", "SPLIT", "sql", "SQL", "sqrt", "SQRT", "startwith", "STARTWITH", "stdev", "STDEV", "substitute", "SUBSTITUTE", "sum", "SUM", "sumsq", "SUMSQ", "switch", "SWITCH", "tabledatafields", "TABLEDATAFIELDS", "tabledatas", "TABLEDATAS", "tables", "TABLES", "tan", "TAN", "tanh", "TANH", "time", "TIME", "tobigdecimal", "TOBIGDECIMAL", "tobinary", "TOBINARY", "todate", "TODATE", "today", "TODAY", "todouble", "TODOUBLE", "tohex", "TOHEX", "toimage", "TOIMAGE", "tointeger", "TOINTEGER", "tooctal", "TOOCTAL", "totext", "TOTEXT", "treelayer", "TREELAYER", "trim", "TRIM", "trunc", "TRUNC", "uniquearray", "UNIQUEARRAY", "upper", "UPPER", "uuid", "UUID", "value", "VALUE", "webimage", "WEBIMAGE", "week", "WEEK", "weekdate", "WEEKDATE", "weekday", "WEEKDAY", "weightedaverage", "WEIGHTEDAVERAGE", "year", "YEAR", "yeardelta", "YEARDELTA"]; -BI.FormulaJson = [{"def":"MONTH:(serial_number)返回日期中的月。月是介于1和12之间的一个数。\nSerial_number:含有所求的月的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nMONTH(\"2000/1/1\")等于1。\nMONTH(\"2006/05/05\")等于5。\nMONTH(\"1997/04/20\")等于4。\nMONTH(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nMONTH(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nMONTH(\"1997-04-20\", \"yyyy-MM-dd\")等于4。\nMONTH(35796)等于1。","name":"MONTH","type":"DATETIME"},{"def":"ROWCOUNT(tableData)返回tableData的行数。\ntableData:TableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是tableData的行数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nROWCOUNT(\"ds1\")等于20。","name":"ROWCOUNT","type":"REPORT"},{"def":"RAND(): 返回均匀分布的随机数。每计算一次工作表,函数都会返回一个新的随机数值。\n备注:\n 要生成一个位于a和b之间的随机数,可以使用以下的公式: C=RAND()*(b-a)+a。\n 如果要使一个随机产生的数值不随单元格的重计算而改变,可以在编辑框中输入=RAND()并保持编辑状态,然后按F9,将公式永久性地改为随机数。\n示例:\n假如需要生成一个大于等于0,小于60的随机数,使用公式: =RAND()*60。\n假如需要生成一个大于等于0,小于19的随机数,使用公式: =RAND()*19。\n假如需要生成一个大于等于0,小于50的随机数,使用公式: =RAND()*50。","name":"RAND","type":"MATH"},{"def":"GETUSERDEPARTMENTS():返回角色部门\n示例:\nGETUSERDEPARTMENTS():返回角色所有部门,若多个部门则数组\nGETUSERDEPARTMENTS(3,2):返回角色该部门的第三层和第二层名字,\n若多个部门则返回数组,若没有第三层则只显示第二层","name":"GETUSERDEPARTMENTS","type":"OTHER"},{"def":"FORMAT(object,format) : 返回object的format格式。\nobject 需要被格式化对象,可以是String,数字,Object(常用的有Date, Time)。\nformat 格式化的样式。\n示例\nFORMAT(1234.5, \"#,##0.00\") => 1234.50\nFORMAT(1234.5, \"#,##0\") => 1234\nFORMAT(1234.5, \"¥#,##0.00\") => ¥1234.50\nFORMAT(1.5, \"0%\") => 150%\nFORMAT(1.5, \"0.000%\") => 150.000%\nFORMAT(6789, \"##0.0E0\") => 6.789E3\nFORMAT(6789, \"0.00E00\") => 6.79E03\nFORMAT(date(2007,1,1), \"EEEEE, MMMMM dd, yyyy\") => 星期一,一月 01,2007\nFORMAT(date(2007,1,13), \"MM/dd/yyyy\") => 01/13/2007\nFORMAT(date(2007,1,13), \"M-d-yy\") => 1-13-07\nFORMAT(time(16,23,56), \"h:mm:ss a\") => 4:23:56 下午","name":"FORMAT","type":"TEXT"},{"def":"TRIM(text): 清除文本中所有空格,单词间的单个空格除外,也可用于带有不规则空格的文本。\nText:需要清除空格的文本。\n示例:\nTRIM(\" Monthly Report\")等于Monthly Report。","name":"TRIM","type":"TEXT"},{"def":"SQRT(number): 返回一个正数的平方根。\nNumber:要求其平方根的任一正数。\n备注:\nNumber必须是一个正数,否则函数返回错误信息*NUM!。\n示例:\nSQRT(64)等于8。\nSQRT(-64)返回*NUM!。","name":"SQRT","type":"MATH"},{"def":"DAYSOFYEAR(year):返回某年包含的天数。\n示例:\nDAYSOFYEAR(2008)等于365,等价于DAYSOFYEAR(\"2008-01-01\")。","name":"DAYSOFYEAR","type":"DATETIME"},{"def":"RANK(number,ref,order): 返回一个数在一个数组中的秩。(如果把这个数组排序,该数的秩即为它在数组中的序号。)\nNumber 所求秩的数。(可以是Boolean型,true=1,false=0)\nRef 可以是数组,引用,或一系列数,非实数的值被忽略处理(接受Boolean型,true=1,false=0)。\nOrder 指定求秩的参数,非零为升序,零为降序\n\n备注\n1. RANK对重复的数返回相同的秩,但重复的数影响后面的数的秩,比如,在一组升序排列的整数中,如果5出现了2次,并且秩为3,那么6的秩为5 (没有数的秩是4).\n\n示例\nA1:A5 = 6, 4.5, 4.5, 2, 4\nRANK(A1,A1:A5,1) 即 6 的秩为 5.\n\nRANK(3,1,2,\"go\",3,4,1) = 3, \"go\"被忽略。","name":"RANK","type":"OTHER"},{"def":"ODD(number):返回对指定数值进行舍入后的奇数。\nnumber:是要舍入求奇的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是奇数,则不须进行任何舍入处理。\n示例:\nODD(1.5) 等于 3\nODD(3) 等于 3\nODD(2) 等于 3\nODD(-1) 等于 -1","name":"ODD","type":"MATH"},{"def":"COLCOUNT(tableData):返回tableData中列的个数。\ntableData:tableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是第一个查找到的tableData中列数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nCOLCOUNT(\"ds1\")等于6。\n","name":"COLCOUNT","type":"REPORT"},{"def":"ENDWITH(str1,str2):判断字符串str1是否以str2结束。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nENDWITH(\"FineReport\",\"Report\")等于true。\nENDWITH(\"FineReport\",\"Fine\")等于false。\nENDWITH(\"FineReport\",\"report\")等于false。","name":"ENDWITH","type":"TEXT"},{"def":"LOG10(number):返回以 10 为底的对数。\nnumber: 用于常用对数计算的正实数。\n示例:\nLOG10(86) 等于 1.934498451\nLOG10(10) 等于 1\nLOG10(1E5) 等于 5\n","name":"LOG10","type":"MATH"},{"def":"MAPARRAY(array, fn):把一个数组中的项目转换到另一个数组中。\narray (Array): 要转换的数组 \nfn (Function): 处理数组项目的函数 \n示例:\nMAPARRAY([3,4,2,3,6,8,7], item != 3)等于[false,true,true,false,true,true,true].","name":"MAPARRAY","type":"ARRAY"},{"def":"FLOOR(number): 将参数number沿绝对值减小的方向去尾舍入。\nNumber:待舍入的数值。\n示例:\nFLOOR(-2.5)等于-2。\nFLOOR(2.5)等于2。\n","name":"FLOOR","type":"MATH"},{"def":"NUMTO(number,bool)或NUMTO(number):返回number的中文表示。其中bool用于选择中文表示的方式,当没有bool时采用默认方式显示。\n示例:NUMTO(2345,true)等于二三四五。\n示例:NUMTO(2345,false)等于二千三百四十五。\n示例:NUMTO(2345)等于二千三百四十五。","name":"NUMTO","type":"TEXT"},{"def":"ATANH(number): 返回数字的反双曲正切值,该函数的参数值即为反双曲正切值的双曲正切值。\nNumber:指介于-1~1之间的任意实数。\n备注:\n 指定的number必须介于-1~1之间(不包括-1,1)。\n ATANH(TANH(number))=number,例如,ATANH(TANH(8))=8。\n示例:\nATANH(-0.5)等于-0.549306144。\nATANH(0)等于0。\nATANH(0.7)等于0.867300528。","name":"ATANH","type":"MATH"},{"def":"YEAR:(serial_number)返回日期中的年。Year是介于1900和9999之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nYEAR(\"2000/1/1\")等于2000。\nYEAR(\"2006/05/05\")等于2006。\nYEAR(\"1997/04/20\")等于1997。\nYEAR(\"2000-1-1\", \"yyyy-MM-dd\")等于2000。\nYEAR(\"2006-05-05\", \"yyyy-MM-dd\")等于2006。\nYEAR(\"1997-04-20\", \"yyyy-MM-dd\")等于1997。\nYEAR(35796)等于1998。","name":"YEAR","type":"DATETIME"},{"def":"SLICEARRAY(array, start, end):返回数组从第start个到第end个元素(包括第end个元素)。\n示例:\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3, 6)返回[4, 5, 1, 5].\n当不使用end参数时,返回从start开始到数组结束之间的元素。\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3)返回[4, 5, 1, 5, 7].","name":"SLICEARRAY","type":"ARRAY"},{"def":"","name":"DECODE","type":"OTHER"},{"def":"ENMONEY(value):将给定的BigDemical类型的数字转换成英文金额字符串。\n示例:\nENMONEY(23.49)等于TWENTY THREE AND CENTS FORTY NINE","name":"ENMONEY","type":"TEXT"},{"def":"IF(boolean,number1/string1,number2/string2):判断函数,boolean为true时返回第二个参数,为false时返回第三个。\nboolean: 用于判断的布尔值,true或者false。\nnumber1/string1: 第一个参数,如果boolean为ture,返回这个值。\nnumber2/string2: 第二个参数,如果boolean为false,返回这个值。\n示例:\nIF(true,2,8)等于2\nIF(false,\"first\",\"second\")等于second\nIF(true,\"first\",7)等于first","name":"IF","type":"LOGIC"},{"def":"DATEINWEEK(date, number):函数返回在某一个星期当中第几天的日期。\n示例:\ndateInWeek(\"2008-08-28\", 2)等于2008-08-26。\ndateInWeek(\"2008-08-28\", -1)等于2008-08-31。\n如果最后一个参数为-1,返回该日期所在星期的最后一天\n","name":"DATEINWEEK","type":"DATETIME"},{"def":"MONTHDELTA(date,delta):返回指定日期date后delta个月的日期。\n示例:\nMONTHDELTA(\"2008-08-08\", 4)等于2008-12-08。","name":"MONTHDELTA","type":"DATETIME"},{"def":"FIELDS(connectionName,tableName):返回tableName这个表中的所有字段名。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么FIELDS(\"BASE\",\"task\")等于[name,start,end].","name":"FIELDS","type":"REPORT"},{"def":"DATEDIF(start_date,end_date,unit):返回两个指定日期间的天数、月数或年数。\nStart_date:代表所指定时间段的初始日期。\nEnd_date:代表所指定时间段的终止日期。\nUnit:函数返回信息的类型。\n若unit=“Y”,则DATEDIF返回指定时间段的年差数。\n若unit=“M”,则DATEDIF返回指定时间段的月差数。\n若unit=“D”,则DATEDIF返回指定时间段的日差数。\n若unit=“MD”,则DATEDIF忽略年和月,返回指定时间段的日差数。\n若unit=“YM”,则DATEDIF忽略年和日,返回指定时间段的月差数。\n若unit=“YD”,则DATEDIF忽略年,返回指定时间段的日差数。\n示例:\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"Y\")等于3,即在2001年2月28日与2004年3月20日之间有3个整年。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"M\")等于37,即在2001年2月28日与2004年3月20日之间有36个整月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"D\")等于1116,即在2001年2月28日与2004年3月20日之间有1116个整天。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"MD\")等于8,即忽略月和年后,2001年2月28日与2004年3月20日的差为8天。\nDATEDIF(\"2001/1/28\",\"2004/3/20\",\"YM\")等于2,即忽略日和年后,2001年1月28日与2004年3月20日的差为2个月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"YD\")等于21,即忽略年后,2001年2月28日与2004年3月20日的差为21天。","name":"DATEDIF","type":"DATETIME"},{"def":"TOIMAGE(path):显示指定路径下的图片。此处默认开启了图片缓存功能以加速报表的生成.\n如不需要缓存,请在参数后面追加值FALSE,例如:TOIMAGE(\"D:/fr.png\",false).\n如需要指定图片大小,拉伸显示, 则需要添加参数,TOIMAGE(patch, true, width, height).\n示例:=toimage(\"d:/1.jpg\", true, \"50%\", 300), 第三个参数为指定宽度, 第四个参数为指定高度.\n如果参数为整数, 则直接写数字, 如果为百分比, 则需要加上引号, 如\"300%\"","name":"TOIMAGE","type":"OTHER"},{"def":"LEFT(text,num_chars): 根据指定的字符数返回文本串中的第一个或前几个字符。\nText:包含需要选取字符的文本串或单元格引用。\nNum_chars:指定返回的字符串长度。\n备注:\n Num_chars的值必须等于或大于0。\n 如果num_chars大于整个文本的长度,LEFT函数将返回所有的文本。\n 如果省略num_chars,则默认值为1。\n示例:\nLEFT(\"Fine software\",8)等于“Fine sof”。\nLEFT(\"Fine software\")等于“F”。\n如果单元格A3中含有“China”,则LEFT(A3,2)等于“Ch”。","name":"LEFT","type":"TEXT"},{"def":"SUBSTITUTE(text,old_text,new_text,instance_num): 用new_text替换文本串中的old_text。\nText:需要被替换字符的文本,或含有文本的单元格引用。\nOld_text:需要被替换的部分文本。\nNew_text:用于替换old_text的文本。\nInstance_num:指定用new_text来替换第几次出现的old_text。如果指定了instance_num,则只有指定位置上的old_text被替换,否则文字串中出现的所有old_text都被new_text替换。\n备注:\n 如果需要替换文本串中的指定文本,则使用SUBSTITUTE函数;如果需要替换文本串中指定位置上的任意文本,则使用REPLACE函数。\n示例:\nSUBSTITUTE(\"data base\",\"base\",\"model\")等于“data model”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",1)等于“July 18, 2000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\")等于“July 18, 1000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",2)等于“July 28, 1000”。 ","name":"SUBSTITUTE","type":"TEXT"},{"def":"LOG(number,base): 按指定的任意底数,返回数值的对数。\nNumber:需要求对数的正实数。\nBase:对数的底数。如果省略底数,默认值为10。\n示例:\nLOG(16,2)等于4。\nLOG(10)等于1。\nLOG(24,3)等于2.892789261。","name":"LOG","type":"MATH"},{"def":"SORTARRAY(array):返回数组array排过序的数组。\n示例:\nSORTARRAY([3, 4, 4, 5, 1, 5, 7])返回[1, 3, 4, 4, 5, 5, 7].\n注意:数组array的元素类型必须一样,并且要可比较。","name":"SORTARRAY","type":"ARRAY"},{"def":"DATEDELTA(date, deltadays):返回一个日期??date后deltadays的日期。\ndeltaDays可以为正值,负值,零。\n示例:\nDATEDELTA(\"2008-08-08\", -10)等于2008-07-29。\nDATEDELTA(\"2008-08-08\", 10)等于2008-08-18。","name":"DATEDELTA","type":"DATETIME"},{"def":"MID(text,start_num,num_chars): 返回文本串中从指定位置开始的一定数目的字符,该数目由用户指定。\nText:包含要提取字符的文本串。\nStart_num:文本中需要提取字符的起始位置。文本中第一个字符的start_num为1,依此类推。\nNum_chars:返回字符的长度。\n备注:\n 如果start_num大于文本长度,MID函数返回“”(空文本)。\n 如果start_num小于文本长度,并且start_num加上num_chars大于文本长度,MID函数将从start_num指定的起始字符直至文本末的所有字符。\n 如果start_num小于1,MID函数返回错误信息*VALUE!。\n 如果num_chars是负数,MID函数返回错误信息*VALUE!。\n示例:\nMID(\"Finemore software\",10,8)返回“software”。\nMID(\"Finemore software\",30,5)返回“”(空文本)。\nMID(\"Finemore software\",0,8)返回*VALUE!。\nMID(\"Finemore software\",5,-1)返回*VALUE!。","name":"MID","type":"TEXT"},{"def":"ATAN2(x_num,y_num): 返回x、y坐标的反正切值。返回角度为x轴与过(x_num,y_num)与坐标原点(0,0)的一条直线形成的角度。该角度以弧度显示。\nX_num:指定点的x坐标。\nY_num:指定点的y坐标。\n备注:\n 正值表示从x轴开始以逆时针方式所得的角度;负值表示从x轴开始以顺时针方式所得的角度。\na > 0,b > 0 or a > 0, b < 0时,公式直接成立;\na < 0,b > 0, ATAN2(a,b)=PI()-ABS(ATAN(b/a))\na < 0,b < 0, ATAN2(a,b)=ABS(ATAN(b/a))-PI()\n 当x_num与y_num都为0时,ATAN2返回错误信息*DIV/0!。\n 用角度制显示返回数值时,把返回数值乘以180/PI()。\n 返回值以弧度表示(返回值大于-pi且小于等于pi)。\n示例:\nATAN2(-2,2)等于2.356194490192345(弧度制的3*pi/4)。\nATAN2(2,2)等于0.785398163(弧度制的pi/4)。\nATAN2(-2,2)*180/PI()等于135(角度制)。","name":"ATAN2","type":"MATH"},{"def":"SUM(number1,number2,…): 求一个指定单元格区域中所有数字之和。\nNumber1,number2,…:1到30个参数或指定单元格区域中所有数字。\n备注:\n 函数将直接键入参数中的数值、逻辑值及文本表达式计算在内。\n 若参数是数组或引用,则只有数组或单元格引用中的数值进行计算。\n示例:\nSUM(70,80)等于150。\nSUM(\"70\",80,TRUE)等于151,逻辑值“TRUE”作为1来计算;“FALSE”作为0计算;文本“70”作为70来计算。","name":"SUM","type":"MATH"},{"def":"EXACT(text1,text2): 检测两组文本是否相同。如果完全相同,EXACT函数返回TRUE;否则,返回FALSE。EXACT函数可以区分大小写,但忽略格式的不同。同时也可以利用EXACT函数来检测输入文档的文字。\nText1:需要比较的第一组文本。\nText2:需要比较的第二组文本。\n示例:\nEXACT(\"Spreadsheet\",\"Spreadsheet\")等于TRUE。\nEXACT(\"Spreadsheet\",\"S preadsheet\")等于FALSE。\nEXACT(\"Spreadsheet\",\"spreadsheet\")等于FALSE。","name":"EXACT","type":"TEXT"},{"def":"TOINTEGER(text): 将文本转换成Integer对象。\nText:需要转换的文本。\n示例:\nTOINTEGER(\"123\")等于 new Integer(123)。","name":"TOINTEGER","type":"TEXT"},{"def":"ACOSH(number): 返回给定数值的反双曲余弦。\nNumber:返回值的双曲余弦。\n备注:\n 参数number的值必须大于或等于1。\n ACOSH(COSH(number))=number。\n示例:\nACOSH(1)等于0。\nACOSH(8)等于2.768659383。\nACOSH(5.5)等于2.389526435。","name":"ACOSH","type":"MATH"},{"def":"weekdate(year,month,weekOfMonth,dayOfWeek): 返回指定年月的指定周的周几的具体日期。\n示例:\nweekdate(2009,10,2,1)\n返回的是2009年的10月的第二个周的第一天即星期天的日期,返回的是2009-10-04\n最后一个参数dayOfWeek为-1时,表示这个周的最后一天\n示例:\nweekdate(2009,12,1,-1)\n返回的是2009年的12月的第一个周的最后一天即星期六的日期,返回的是2009-12-05\n","name":"WEEKDATE","type":"DATETIME"},{"def":"MIN(number1,number2,…): 返回参数列表中的最小值。\nNumber1,number2,…:1到30个需要找出最小值的参数。\n备注:\n 若参数中没有数字,函数MIN将返回0。\n 参数应为数字、空白单元格、逻辑值或是表示数值的文本串。如果参数是错误值时,MIN将返回错误信息。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n示例:\n如果B1:B4包含3,6,9,12,则:\nMIN(B1:B4)等于3。\nMIN(B1:B4,0)等于0。","name":"MIN","type":"MATH"},{"def":"STARTWITH(str1,str2):判断字符串str1是否以str2开始。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nSTARTWITH(\"FineReport\",\"Fine\")等于true。\nSTARTWITH(\"FineReport\",\"Report\")等于false。\nSTARTWITH(\"FineReport\",\"fine\")等于false。","name":"STARTWITH","type":"TEXT"},{"def":"COMBIN(number,number_chosen): 返回若干个指定对象的组合数。该函数与数学表达式为Cnk功能相同。\nNumber或数学表达式中的“n”指对象总数。\nNumber_chosen或数学表达式中的“k”指在对象总数中某一组合的数量。\n备注:\n Number必须是正整数,number_chosen必须是非负整数。\n 如果number和number_chosen小于0或number小于number_chosen,函数返回错误信息*NUM!。\n 对象组合是对象的子集。与排列不同的是,组合不涉及对象内部的先后顺序,而顺序对排列是非常重要的。\n 假设number=n,number_chosen=k,则: COMBIN(n,k)=Cnk=n!/(k!(n-k)!)。\n示例:\nCOMBIN(5,6)等于*NUM!。\nCOMBIN(5,2)等于10。","name":"COMBIN","type":"MATH"},{"def":"EVEN(number):返回沿绝对值增大方向取整后最接近的偶数。使用该函数可以处理那些成对出现的对象。\nnumber:所要取整的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是偶数,则不须进行任何舍入处理。\n示例:\nEVEN(1.5) 等于 2\nEVEN(3) 等于 4\nEVEN(2) 等于 2\nEVEN(-1) 等于 -2","name":"EVEN","type":"MATH"},{"def":"COUNT(value1,value2,…): 计算数组或数据区域中所含项的个数。\nValue1,value2,…:可包含任何类型数据的参数。","name":"COUNT","type":"MATH"},{"def":"INDEXOFARRAY(array, index):返回数组array的第index个元素。\n示例:\nINDEXOFARRAY([\"第一个\", \"第二个\", \"第三个\"], 2)返回\"第二个\"。","name":"INDEXOFARRAY","type":"ARRAY"},{"def":"MAP(object, string, int, int):四个参数分别是索引值,数据集的名字,索引值所在列序号,返回值所在列序号。\n提醒:后两个参数也可以写列名代替。\n根据数据集的名字,找到对应的数据集,找到其中索引列的值为key所对应的返回值。\n数据集的查找方式是依次从报表数据集找到服务器数据集。\n索引列序号与返回值序列号的初始值为1示例:\nMAP(1001, \"employee\", 1, 2)返回employee数据集,第1列中值为1001那条记录中第2列的值。\nMAP(1001, \"employee\", \"name\", \"address\")返回employee数据集,name列中值为1001那条记录中address列的值。","name":"MAP","type":"REPORT"},{"def":"SEQ(): 返回数值,在整个报表执行过程中,返回该函数被第几次执行了。\n示例:\nSEQ()在第一次执行时,结果为1。\nSEQ()在第二次执行时,结果为2。","name":"SEQ","type":"OTHER"},{"def":"i18n为本软件内置的国际化公式,可以对一些常用的词语进行国际化.\n示例:i18n('File'), 则会在中文语言环境下显示为: 文件, 而在英文语言环境下显示为: File","name":"I18N","type":"REPORT"},{"def":"层次坐标简写, 等同于=A1[A1:-1], 若需=B1[A1:-1]则HIERARCHY(A1, B1).\n若为横向, 偏移量为-2, 则写成HIERARCHY(A1, B1, -2, false), 等同于=B1[;A1:-1].\n公式中最后一个参数表示横纵向, 默认不传递, 表示纵向扩展, 若横向扩展, 则需要加上最后一个参数FALSE来区分. ","name":"HIERARCHY","type":"HA"},{"def":"","name":"ENCODE","type":"OTHER"},{"def":"DATEINMONTH(date, number):函数返回在某一个月当中第几天的日期。\n示例:\nDATEINMONTH(\"2008-08-08\", 20) 等于2008-08-20。\nDATEINMONTH(\"2008-08-08\", -1) 等于2008-08-31。","name":"DATEINMONTH","type":"DATETIME"},{"def":"TOOCTAL(int): 将一个十进制整型数转换成八进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOOCTAL(10)等于 \"12\"。\nTOOCTAL(20)等于 \"24\"。","name":"TOOCTAL","type":"MATH"},{"def":"REPEAT(text,number_times): 根据指定的次数重复显示文本。REPEAT函数可用来显示同一字符串,并对单元格进行填充。\nText:需要重复显示的文本或包含文本的单元格引用。\nNumber_times:指定文本重复的次数,且为正数。如果number_times为0,REPEAT函数将返回“”(空文本)。如果number_times不是整数,将被取整。REPEAT函数的最终结果通常不大于32767个字符。\n备注:\n 该函数可被用于在工作表中创建简单的直方图。\n示例:\nREPEAT(\"$\",4)等于“$$$$”。\n如果单元格B10的内容为“你好”,REPEAT(B10,3)等于“你好你好你好”。","name":"REPEAT","type":"TEXT"},{"def":"GREPARRAY(array,fn):函数(返回true或者false)是条件,过滤此数组,最后形成一个新数组。\n示例:\nGREPARRAY([3,4,2,3,6,8,7], item != 3)等于[4,2,6,8,7].\n","name":"GREPARRAY","type":"ARRAY"},{"def":"MAX(number1,number2,…): 返回参数列表中的最大值。\nNumber1,number2,…:1到30个需要找出最大值的参数。\n备注:\n 参数可以是数字、空白单元格、逻辑值或数字的文本表达式。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n 如果参数中没有任何数字,MAX将返回0。\n示例:\nMAX(0.1,0,1.2)等于1.2。","name":"MAX","type":"MATH"},{"def":"CHAR(number): 根据指定数字返回对应的字符。CHAR函数可将计算机其他类型的数字代码转换为字符。\nNumber:用于指定字符的数字,介于1~65535之间(包括1和65535)。\n示例:\nCHAR(88)等于“X”。\nCHAR(45)等于“-”。","name":"CHAR","type":"TEXT"},{"def":"TRUNC(number,num_digits):将数字的小数部分截去,返回整数。\nnumber:需要截尾取整的数字。\nnum_digits:用于指定取整精度的数字。\n示例:\nTRUNC(8.9) 等于 8\nTRUNC(-8.9) 等于 -8\nTRUNC(PI()) 等于 3\n","name":"TRUNC","type":"MATH"},{"def":"FACT(number):返回数的阶乘,一个数的阶乘等于 1*2*3*...*该数。\nnumber:要计算其阶乘的非负数。如果输入的 number 不是整数,则截尾取整。\n示例:\nFACT(1) 等于 1\nFACT(1.9) 等于 FACT(1) 等于 1\nFACT(0) 等于 1\nFACT(5) 等于 1*2*3*4*5 等于 120\n","name":"FACT","type":"MATH"},{"def":"STDEV(array1): 计算数据系列的标准偏差(与Excel的同名函数作用相同)。\n\n示例:\nSTDEV([1,2,3])=1。\n","name":"STDEV","type":"OTHER"},{"def":"SPLIT(String1,String2):返回由String2分割String1组成的字符串数组。\nString1:以双引号表示的字符串。\nString2:以双引号表示的分隔符。例如逗号\",\"\n示例:\nSPLIT(\"hello,world,yes\",\",\") = [\"hello\",\"world\",\"yes\"]。\nSPLIT(\"this is very good\",\" \") = [\"this\",\"is\",\"very\",\"good\"]。\n备注:\n如果只有一个参数,则返回一个错误。\n如果有多个参数,则只有前两个起作用。","name":"SPLIT","type":"TEXT"},{"def":"INARRAY(co, array):返回co在数组array中的位置,如果co不在array中,则返回0.\n示例:\nString[] arr = {\"a\",\"b\",\"c\",\"d\"}\n那么INARRAY(\"b\", arr)等于2.","name":"INARRAY","type":"ARRAY"},{"def":"REVERSEARRAY(array):返回数组array的倒序数组。\n示例:\nREVERSEARRAY([\"第一个\", \"第二个\", \"第三个\"])返回[\"第三个\", \"第二个\", \"第一个\"].","name":"REVERSEARRAY","type":"ARRAY"},{"def":"RANDBETWEEN(value1,value2):返回value1和value2之间的一个随机整数。\n示例:\nRANDBETWEEN(12.333, 13.233)只会返回13。\nRANDBETWEEN(11.2, 13.3)有可能返回12或者13。","name":"RANDBETWEEN","type":"MATH"},{"def":"UPPER(text): 将文本中所有的字符转化为大写。\nText:需要转化为大写字符的文本,或是包含文本的单元格引用。\n示例:\nUPPER(\"notes\")等于“NOTES”。\n如果单元格E5的值为“Examples”,则UPPER(E5)等于“EXAMPLES”。","name":"UPPER","type":"TEXT"},{"def":"ABS(number): 返回指定数字的绝对值。绝对值是指没有正负符号的数值。\nNumber:需要求出绝对值的任意实数。\n示例:\nABS(-1.5)等于1.5。\nABS(0)等于0。\nABS(2.5)等于2.5。","name":"ABS","type":"MATH"},{"def":"RIGHT(text,num_chars): 根据指定的字符数从右开始返回文本串中的最后一个或几个字符。\nText:包含需要提取字符的文本串或单元格引用。\nNum_chars:指定RIGHT函数从文本串中提取的字符数。Num_chars不能小于0。如果num_chars大于文本串长度,RIGHT函数将返回整个文本。如果不指定num_chars,则默认值为1。\n示例:\nRIGHT(\"It is interesting\",6)等于“esting”。\nRIGHT(\"Share Holder\")等于“r”。\nRIGHT(\"Huge sale\",4)等于“sale”。","name":"RIGHT","type":"TEXT"},{"def":"MEDIAN(array1): 返回数据系列的中值(与Excel的同名函数作用相同)。\n\n示例:\nMEDIAN([1,2,3])=2。\n","name":"MEDIAN","type":"OTHER"},{"def":"TABLEDATAFIELDS(tableData):返回tableData中所有的字段名。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的列名组成的数组。\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nTABLEDATAFIELDS(\"ds1\")等于\nCUSTOMERID,CUSTOMERAME,CITY,COUNTRY,TEL,DISTRICT。","name":"TABLEDATAFIELDS","type":"REPORT"},{"def":"占比公式, =PROPORTION(A1)等同于=A1/sum(A1[!0])","name":"PROPORTION","type":"HA"},{"def":"COL()返回当前单元格的列号,必须使用于条件属性中\n示例:\n如果当前单元格是A5,在A5中写入\"=col()\"则返回1。\n如果当前单元格是C6,在C6中写入\"=col()\"则返回3。","name":"COL","type":"REPORT"},{"def":"TOHEX(int): 将一个十进制整型数转换成十六进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOHEX(15)等于 \"f\"。\nTOHEX(20)等于 \"14\"。","name":"TOHEX","type":"MATH"},{"def":"COS(number): 返回一个角度的余弦值。\nNumber:以弧度表示的需要求余弦值的角度。\n备注:\n 要把一个角度转换成弧度值,将角度乘于PI()/180。\n COS(n*2*PI()+number)=COS(number)(其中n为整数,number从-pi到pi)。\n示例:\nCOS(0.5)等于0.877582562。\nCOS(30*PI()/180)等于0.866025404。","name":"COS","type":"MATH"},{"def":"跨层累计, =CROSSLAYERTOTAL(A1, B1, C1, D1)等同于=IF(&B1 >1, D1[B1:-1] + C1, D1[A1:-1,B1:!-1] + C1), 如需横向, 则传递第五个参数false","name":"CROSSLAYERTOTAL","type":"HA"},{"def":"POWER(number,power): 返回指定数字的乘幂。\nNumber:底数,可以为任意实数。\nPower:指数。参数number按照该指数次幂乘方。\n备注:\n 可以使用符号“^”代替POWER,如: POWER(5,2)等于5^2。\n示例:\nPOWER(6,2)等于36。\nPOWER(14,5)等于537824。\nPOWER(4,2/3)等于2.519842100。\nPOWER(3,-2.3)等于0.079913677。","name":"POWER","type":"MATH"},{"def":"DAYS360(start_date,end_date,method):按照一年 360 天的算法(每个月以 30 天计,一年共计 12 个月),\n返回两日期间相差的天数,这在会计计算中将会用到。如果财务系统是基于一年 12 个月,每月 30 天,\n可用此函数帮助计算支付款项。\nStart_date 和 end_date :是用于计算期间天数的起止日期。\nMethod : 它指定了在计算中是采用欧洲方法还是美国方法。\nMethod 定义 :\nFALSE或忽略 美国方法 (NASD)。如果起始日期是一个月的 31 号,则等于同月的 30 号。如果终止日期是一个月的\n31号,并且起始日期早于 30 号,则终止日期等于下一个月的 1 号,否则,终止日期等于本月的 30 号。\nTRUE 欧洲方法。无论是起始日期还是终止日期为一个月的 31 号,都将等于本月的 30 号。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAYS360(\"1998/1/30\", \"1998/2/1\") 等于 1","name":"DAYS360","type":"DATETIME"},{"def":"filetype(file)获取文件的类型。\n当file为单文件时,返回文件类型字符串,当file为多文件时,返回文件类型的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.txt },则filetype(B2)返回值为[“doc”, “xls”, “txt”]。","name":"FILETYPE","type":"OTHER"},{"def":"ADDARRAY(array, insertArray, start):在数组第start个位置插入insertArray中的所有元素,再返回该数组。\n示例:\nADDARRAY([3, 4, 1, 5, 7], [23, 43, 22], 3)返回[3, 4, 23, 43, 22, 1, 5, 7].\nADDARRAY([3, 4, 1, 5, 7], \"测试\", 3)返回[3, 4, \"测试\", 1, 5, 7].\n注意:如果start为小于1的数或者不写start参数,则默认从数组的第一位开始插入数组元素。","name":"ADD2ARRAY","type":"ARRAY"},{"def":"BITNOT(int):将一个十进制整数进行二进制取反运算。\nint:需要进行转换的十进制数。\n示例:\nBITNOT(3)等于-4。\nBITNOT(12)等于-13。","name":"BITNOT","type":"LOGIC"},{"def":"TABLEAS(connectionName):返回名为connectionName的数据库中的所有表名。\n示例:\n假设在FRDemo这个数据库中,有3个表:a,b,c;\n那么TABLES(\"FRDemo\")等于[a,b,c].","name":"TABLES","type":"REPORT"},{"def":"SUMSQ(number1,number2, ...):返回所有参数的平方和。\nnumber1, number2, ...:为 1 到 30 个需要求平方和的参数,也可以使用数组或对数组的引用来代替以逗号分隔的参数。\n示例:\nSUMSQ(3, 4) 等于 25\n","name":"SUMSQ","type":"MATH"},{"def":"RECORDS(connection, table,field):返回数据库表table中字段名field下的所有元素。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么RECORDS(\"BASE\",\"task\",\"end\")等于[2009,2012].\n\nRECORDS(connection, table,field,row)返回table中field字段下的第row行的记录,field可以为列名也可以为列号。\n RECORDS(\"BASE\",\"task\",\"end\",2)等于2012.\n RECORDS(\"BASE\",\"task\",2,2)等于2009.","name":"RECORDS","type":"REPORT"},{"def":"","name":"TOBIGDECIMAL","type":"DELETE"},{"def":"TODOUBLE(text): 将文本转换成Double对象。\nText:需要转换的文本。\n示例:\nTODOUBLE(\"123.21\")等于 new Double(123.21)。","name":"TODOUBLE","type":"TEXT"},{"def":"TODATE()函数可以将各种日期形式的参数转换为日期类型。\n它有三种参数的形式:\n1 参数是一个日期型的参数,那么直接将这个参数返回。\n示例:\nTODATE(DATE(2007,12,12))返回2007年12月12日组成的日期。\n2 参数是以从1970年1月1日0时0分0秒开始的毫秒数,返回对应的时间。\n示例:\nTODATE(1023542354746)返回2002年6月8日。\n3 参数是日期格式的文本,那么返回这个文本对应的日期。\n示例:\nTODATE(\"2007/10/15\")返回2007年10月5日组成的日期。\nTODATE(\"2007-6-8\")返回2007年6月8日组成的日期。\n4 有两个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式。\n示例:\nTODATE(\"1/15/07\",\"mm/dd/yy\")返回07年1月15日组成的日期。\n特别的,\"yyyyMMdd\"是用来解析形如“20081230”之类的日期格式的。比如TODATE(\"20110830\",\"yyyyMMdd\")返回11年08月30日组成的日期\n5 有三个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式,第三个参数为解析日期的语言,如:zh(中文),en(英文)。\n示例:\nTODATE(\"星期三 1/15/07\",\"EEE mm/dd/yy\", \"zh\")返回07年1月15日组成的日期,使用“zh(中文)”才能够正常解析“星期三”这个字符串。","name":"TODATE","type":"DATETIME"},{"def":"PROPER(text): 将文本中的第一个字母和所有非字母字符后的第一个字母转化成大写,其他字母变为小写。\nText:需要转化为文本的公式、由双引号引用的文本串或是单元格引用。\n示例:\nPROPER(\"Finemore Integrated Office\")等于“Finemore Integrated Office”。\nPROPER(\"100 percent\")等于“100 Percent”。\nPROPER(\"SpreaDSheEt\")等于“Spreadsheet”。","name":"PROPER","type":"TEXT"},{"def":"DAY:(serial_number)返回日期中的日。DAY是介于1和31之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAY(\"2000/1/1\")等于1。\nDAY(\"2006/05/05\")等于5。\nDAY(\"1997/04/20\")等于20。\nDAY(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nDAY(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nDAY(\"1997-04-20\", \"yyyy-MM-dd\")等于20。\nDAY(35796)等于1。","name":"DAY","type":"DATETIME"},{"def":"LUNAR(year,day,month): 返回当前日期对应的农历时间。\nyear,month,day:分别对应年月日。\n示例:\n如果需要查询2011年7月21日对应的农历时间,则只需输入LUNAR(2011,7,21)结果将显示为:辛卯年六月廿一\n同样,如输入LUNAR(2001,7,21),则显示:辛巳年六月初一 。本公式支持的时间段为1900-2100年。","name":"LUNAR","type":"DATETIME"},{"def":"TABLEDATAS():返回报表数据集和服务器数据集名字。\n示例:\n服务器数据集有:ds1,ds2,ds3;报表数据集有dsr1,dsr2.\nTABLEDATAS()等于[dsr1,dsr2,ds1,ds2,ds3].\n而TABLEDATAS(0)返回服务器数据集名字;TABLEDATAS(1)返回报表数据集名字;\nTABLEDATAS(0)等于[ds1,ds2,ds3];TABLEDATAS(1)等于[dsr1,dsr2].","name":"TABLEDATAS","type":"REPORT"},{"def":"TAN(number): 返回指定角度的正切值。\nNumber:待求正切值的角度,以弧度表示。如果参数是以度为单位的,乘以Pi()/180后转换为弧度。\n示例:\nTAN(0.8)等于1.029638557。\nTAN(45*Pi()/180)等于1。","name":"TAN","type":"MATH"},{"def":"","name":"JVM","type":"DELETE"},{"def":"LN(number):返回一个数的自然对数。自然对数以常数项 e(2.71828182845904)为底。\nnumber:是用于计算其自然对数的正实数。\n示例:\nLN(86) 等于 4.45437\nLN(2.7182818) 等于 1\nLN(EXP(3)) 等于 3\nEXP(LN(4)) 等于 4\n","name":"LN","type":"MATH"},{"def":"ARRAY(arg1,arg2...):返回一个由arg1,arg2,...组成的数组.\narg1,arg2,...:字符串或者数字.\n示例:\nARRAY(\"hello\") = [\"hello\"].\nARRAY(\"hello\",\"world\") = [\"hello\",\"world\"].\nARRAY(\"hello\",98) = [\"hello\",98].\nARRAY(67,98) = [67,98].","name":"ARRAY","type":"ARRAY"},{"def":"TOBINARY(int): 将一个十进制整型数转换成二进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOBINARY(10)等于 \"1010\"。\nTOBINARY(20)等于 \"10100\"。","name":"TOBINARY","type":"MATH"},{"def":"NVL(value1,value2,value3,...):在所有参数中返回第一个不是null的值value1:可以为任意数,也可以为null。\nvalue2:可以为任意数,也可以为null。\n当字符串长度为0时, 返回也为null\n示例:\nNVL(12,20)等于12。\nNVL(null,12)等于12。\nNVL(null,null)等于null。\nNVL(20,null)等于20。\nNVL(null,null,10)等于10。","name":"NVL","type":"OTHER"},{"def":"CORREL(array1,array2): 求两个相同长度数据系列的相关系数(与Excel的同名函数作用相同)。\n如果数组或引用参数包含文本、逻辑值或空白单元格,则这些值将被忽略;但包含零值的单元格将计算在内。\n函数计算结果出现负数表示负相关。相关系数的取值范围是[-1,1]之间的数。相关系数的绝对值越大,表示误差越小。 Array1 和 Array2 的数据点的个数必须相同,例如:\nCORREL([1,2,3],[2,4,6])=1。\n","name":"CORREL","type":"OTHER"},{"def":"COLNAME(tableData,colIndex)返回的是tableData中列序号colIndex的列名。\ntableData:表示TableData的名字,字符串形式。\ncolIndex:表示列序号。\n备注:\n TableData先从私有数据源中查找,再从公有数据源中查找。\n示例:\nCOLNAME(\"Check\",3)等于AcceName。\nCOLNAME(\"country\",4)等于Area。","name":"COLNAME","type":"REPORT"},{"def":"DECIMAL(number): 返回number的大数类型,常用于精确计算。","name":"DECIMAL","type":"MATH"},{"def":"CLASS(object):返回object对象的所属的类。","name":"CLASS","type":"OTHER"},{"def":"VALUE(tableData,col,row)返回tableData中列号为col的值, 行号为row。\ntableData:tableData的名字,字符串形式的。\nrow:行号。\ncol:列号。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的行数。\n示例:\nVALUE(\"country\",5,3)等于South America。\nVALUE(\"Simple\",8,3)等于jonnason。\n示例:VALUE(\"country\",5,\"大陆\")等于South America。\n\nVALUE(tableData,col)返回tableData中列号为col的一列值。\nVALUE(tableData,targetCol, orgCol, element)返回tableData中第targetCol列中的元素,这些元素对应的第orgCol列的值为element。\n示例:\ntableData : co\n国家 省份\n\n中国 江苏\n中国 浙江\n中国 北京\n美国 纽约\n美国 新泽西\nVALUE(\"co\",2, 1, \"中国\")等于[\"江苏\", \"浙江\", \"北京\"]。\n特别说明:列号也可以写为列名。\nVALUE(tableData,targetCol, orgCol, element, idx)返回VALUE(tableData,targetCol, orgCol, element)数组的第idx个值。\n特别说明:idx的值小于0时,会取数组的第一个值,idx的值大于数组长度时,会取数组的最后一个值。\n","name":"VALUE","type":"REPORT"},{"def":"JOINARRAY(array,sepa):返回一个由sepa作为分隔符的字符串.\narray:[arg1,arg2...]格式的数组;\nsepa:分隔符。\n示例:\nJOINARRAY([1,2],\";\") = [1;2].\nJOINARRAY([hello,world],\"-\") = [hello-world].","name":"JOINARRAY","type":"ARRAY"},{"def":"DATETONUMBER(date):返回自 1970 年 1 月 1 日 00:00:00 GMT 经过的毫秒数。\n示例:\nDATETONUMBER(\"2008-08-08\")等于1218124800000。","name":"DATETONUMBER","type":"DATETIME"},{"def":"INDEXOF(str1,index):返回字符串str1在index位置上的字符。\n备注:\n index是从0开始计数的。\n示例:\nINDEXOF(\"FineReport\",0)等于'F'。\nINDEXOF(\"FineReport\",2)等于'n'。\nINDEXOF(\"FineReport\",9)等于't'。\n\nINDEXOF(array, index):返回数组在index位置上的元素。\n备注:\n index是从1开始计数的。\n示例:\nString[] array = {\"a\", \"b\", \"c\"}\nINDEXOF(array, 1)等于\"a\".\n","name":"INDEXOF","type":"TEXT"},{"def":"PRODUCT(number1,number2, ...):将所有以参数形式给出的数字相乘,并返回乘积值。\nnumber1, number2, ...:为 1 到 30 个需要相乘的数字参数。\n示例:\nPRODUCT(3,4) 等于 12\nPRODUCT(3,4,5) 等于 60\n\n","name":"PRODUCT","type":"MATH"},{"def":"ACOS(number): 返回指定数值的反余弦值。反余弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的余弦值。\n备注:\n 函数的参数必须在-1和1之间,包括-1和1。\n 返回的角度值在0和Pi之间。\n 如果要把返回的角度用度数来表示,用180/PI()乘返回值即可。\n示例:\nACOS(1)等于0(弧度)。\nACOS(0.5)等于1.047197551(Pi/3弧度)。\nACOS(0.5)*180/PI()等于60(度)。","name":"ACOS","type":"MATH"},{"def":"FIND(find_text,within_text,start_num):从指定的索引(start_num)处开始,返回第一次出现的指定子字符串(find_text)在此字符串(within_text)中的索引。\nFind_text:需要查找的文本或包含文本的单元格引用。\nWithin_text:包含需要查找文本的文本或单元格引用。\nStart_num:指定进行查找字符的索引位置。within_text里的索引从1开始。如果省略start_num,则假设值为1。\n备注:\n 如果find_text不在within_text中,FIND函数返回值为0。\n 如果start_num不大于0,FIND函数返回错误信息*VALUE!。\n 如果start_num大于within_text的长度,FIND函数返回值为0。\n 如果find_text是空白文本,FIND函数将在搜索串中匹配第一个字符(即编号为start_num或1的字符)。\n示例:\nFIND(\"I\",\"Information\")等于1。\nFIND(\"i\",\"Information\")等于9。\nFIND(\"o\",\"Information\",2)等于4。\nFIND(\"o\",\"Information\",12)等于0。\nFIND(\"o\",\"Information\",-1)等于*VALUE!。","name":"FIND","type":"TEXT"},{"def":"MINUTE(serial_number):返回某一指定时间的分钟数,其值是介于0与59之间的一个整数。\nserial_number:包含所求分钟数的时间。\n示例:\nMINUTE(\"15:36:25\")等于36。\nMINUTE(\"15:36:25\", \"HH:mm:ss\")等于36。","name":"MINUTE","type":"DATETIME"},{"def":"SIGN(number):返回数字的符号。当数字为正数时返回 1,为零时返回 0,为负数时返回 -1。\nNumber:为任意实数。\n示例:\nSIGN(10) 等于 1\nSIGN(4-4) 等于 0\nSIGN(-0.00001) 等于 -1\n","name":"SIGN","type":"MATH"},{"def":"INDEX(key,val1,val2,...):返回key在val1,val2,...所组成的序列中的位置,不存在于序列中则返回参数的个数.\n备注:\n key和valn可以是任意类型\n示例:\nINDEX(2,2)等于1。\nINDEX(2,1,2)等于2。\nINDEX(2,4,5,6)等于4。\nINDEX(\"b\",\"b\",\"o\",\"y\")等于1。","name":"INDEX","type":"OTHER"},{"def":"REVERSE(value):返回与value相反的逻辑值。\n示例:\nREVERSE(true)等于false。","name":"REVERSE","type":"LOGIC"},{"def":"REPLACE(text, texttoreplace, replacetext):根据指定字符串,用其他文本来代替原始文本中的内容。\ntext:需要被替换部分字符的文本或单元格引用。\ntexttoreplace:指定的字符串或正则表达式。\nreplacetext:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"abcd\", \"a\", \"re\")等于\"rebcd\"。\nREPLACE(\"a**d\", \"**d\", \"rose\")等于\"arose\"。\nREPLACE(old_text,start_num,num_chars,new_text): 根据指定的字符数,用其他文本串来替换某个文本串中的部分内容。\nOld_text:需要被替换部分字符的文本或单元格引用。\nStart_num:需要用new_text来替换old_text中字符的起始位置。\nNum_chars:需要用new_text来替换old_text中字符的个数。\nNew_text:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"0123456789\",5,4,\"*\")等于“0123*89”。\nREPLACE(\"1980\",3,2,\"99\")等于“1999”。","name":"REPLACE","type":"TEXT"},{"def":"UUID():返回随机的UUID。\n示例:UUID()返回36位随机机器数。\n UUID(32)返回32位随机机器数。","name":"UUID","type":"OTHER"},{"def":"DATESUBDATE(date1, date2, op):返回两个日期之间的时间差。\nop表示返回的时间单位:\n\"s\",以秒为单位。\n\"m\",以分钟为单位。\n\"h\",以小时为单位。\n\"d\",以天为单位。\n\"w\",以周为单位。\n示例:\nDATESUBDATE(\"2008-08-08\", \"2008-06-06\",\"h\")等于1512。","name":"DATESUBDATE","type":"DATETIME"},{"def":"CONCATENATE(text1,text2,...): 将数个字符串合并成一个字符串。\nText1,text2,...:需要合并成单个文本的文本项,可以是字符,数字或是单元格引用。\n示例:\nCONCATENATE(\"Average \",\"Price\")等于“Average Price”。\nCONCATENATE(\"1\",\"2\")等于12。","name":"CONCATENATE","type":"TEXT"},{"def":"filesize(file)获取文件的大小,单位为Kb。\n当file为单文件时,返回文件大小,当file为多文件时,返回文件大小的数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了两个大小分别为100字节和10240字节的文件,则filename(B2)返回值为[0.098, 10.0]。","name":"FILESIZE","type":"OTHER"},{"def":"DAYSOFMONTH(date):返回从1900年1月后某年某月包含的天数。\n示例:\nDAYSOFMONTH(\"1900-02-01\")等于28。\nDAYSOFMONTH(\"2008/04/04\")等于30。","name":"DAYSOFMONTH","type":"DATETIME"},{"def":"DATEINQUARTER(date, number): 函数返回在某一个季度当中第几天的日期。\n示例:\nDATEINQUARTER(\"2009-05-05\", 20)等于 2009-04-20。","name":"DATEINQUARTER","type":"DATETIME"},{"def":"逐层累计, =LAYERTOTAL(B1, C1, D1)等同于=D1[B1:-1] + C1, 如需横向, 则传递第四个参数false.如LAYERTOTAL(B1, C1, D1, false)","name":"LAYERTOTAL","type":"HA"},{"def":"CNMONEY(number,unit)返回人民币大写。\nnumber:需要转换的数值型的数。\nunit:单位,\"s\",\"b\",\"q\",\"w\",\"sw\",\"bw\",\"qw\",\"y\",\"sy\",\"by\",\"qy\",\"wy\"分别代表“拾”,“佰”,“仟”,“万”,“拾万”,“佰万”,“仟万”,“亿”,“拾亿”,“佰亿”,“仟亿”,“万亿”。\n备注:\n 单位可以为空,如果为空,则直接将number转换为人民币大写,否则先将number与单位的进制相乘,然后再将相乘的结果转换为人民币大写。\n示例:\nCNMONEY(1200)等于壹仟贰佰圆整。\nCNMONEY(12.5,\"w\")等于壹拾贰万伍仟圆整。\nCNMONEY(56.3478,\"bw\")等于伍仟陆佰叁拾肆万柒仟捌佰圆整。\nCNMONEY(3.4567,\"y\")等于叁亿肆仟伍佰陆拾柒万圆整。","name":"CNMONEY","type":"TEXT"},{"def":"DAYVALUE(date):返回1900年至 date日期所经历的天数。\n示例:\nDAYVALUE(\"2008/08/08\")等于39668。","name":"DAYVALUE","type":"DATETIME"},{"def":"SQL(connectionName,sql,columnIndex,rowIndex)返回通过sql语句从connectionName中获得数据表的第columnIndex列第rowIndex行所对应的元素。\nconnectionName:数据库库的名字,字符串形式;\nsql:SQL语句,字符串形式;\ncolumnIndex:列序号,整形;\nrowIndex:行序号,整形。\n备注:行序号可以不写,这样返回值为数据列。\n示例:\n以我们提供的数据源HSQL为例\nSQL(\"HSQL\",\"SELECT * FROM CUSTOMER\",2,2)等于王先生。","name":"SQL","type":"REPORT"},{"def":"DATE(year,month,day): 返回一个表示某一特定日期的系列数。\nYear:代表年,可为一到四位数。\nMonth:代表月份。\n若1 month 12,则函数把参数值作为月。\n若month>12,则函数从年的一月份开始往上累加。例如: DATE(2000,25,2)等于2002年1月2日的系列数。\nDay:代表日。\n若日期小于等于某指定月的天数,则函数将此参数值作为日。\n若日期大于某指定月的天数,则函数从指定月份的第一天开始往上累加。若日期大于两个或多个月的总天数,则函数把减去两个月或多个月的余数加到第三或第四个月上,依此类推。例如:DATE(2000,3,35)等于2000年4月4日的系列数。\n备注:\n 若需要处理公式中日期的一部分,如年或月等,则可用此公式。\n 若年,月和日是函数而不是函数中的常量,则此公式最能体现其作用。\n示例:\nDATE(1978, 9, 19) 等于1978-09-19.\nDATE(1211, 12, 1) 等于1211-12-01. ","name":"DATE","type":"DATETIME"},{"def":"BITOPERATIOIN(int,int,op) 位运算,返回两个整数根据op进行位运算后的结果。\nint:十进制整数。\nop:位运算操作符,支持\"&\"(与),\"|\"(或),\"^\"(异或),\"<<\"(左移),\">>\"(右移)。\n示例:\nBITOPERATION(4,2,\"&\")表示4与2进行\"与\"运算,结果等于0。\nBITOPERATION(4,2,\"|\")表示4与2进行\"或\"运算,结果等于6。\nBITOPERATION(4,2,\"^\")表示4与2进行\"异或\"运算,结果等于6。\nBITOPERATION(4,2,\"<<\")表示4按位左移2位,结果等于16。\nBITOPERATION(4,2,\">>\")表示4按位右移2位,结果等于1。\nBITOPERATION(4,2,\"^~\")表示4与2进行\"同或\"运算,结果为-7。","name":"BITOPERATION","type":"LOGIC"},{"def":"LOWER(text): 将所有的大写字母转化为小写字母。\nText:需要转化为小写字母的文本串。LOWER函数不转化文本串中非字母的字符。\n示例:\nLOWER(\"A.M.10:30\")等于“a.m.10:30”。\nLOWER(\"China\")等于“china”。","name":"LOWER","type":"TEXT"},{"def":"CEILING(number): 将参数number沿绝对值增大的方向,舍入为最接近的整数\nNumber:指待舍入的数值。\nCEILING(-2.5)等于-3。\nCEILING(0.5)等于1。","name":"CEILING","type":"MATH"},{"def":"SINH(number):返回某一数字的双曲正弦值。\nnumber:为任意实数。\n示例:\nSINH(1) 等于 1.175201194\nSINH(-1) 等于 -1.175201194","name":"SINH","type":"MATH"},{"def":"AND(logical1,logical2,…): 当所有参数的值为真时,返回TRUE;当任意参数的值为假时,返回FALSE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nAND(1+7=8,5+7=12)等于TRUE。\nAND(1+7=8,5+7=11)等于FALSE。\n如果单元格A1到A4的值分别为TRUE、TRUE、FALSE和TRUE,则:\nAND(A1:A4)等于FALSE。\n如果单元格A5的值在0~50之间,则: AND(0 $A1}) + 1, 默认升序排列, 如需要降序, 则传递参数false,\n =SORT(A1, false)等同于=COUNT(A1[!0]{A1 < $A1}) + 1.","name":"SORT","type":"HA"},{"def":"SIN(number): 计算给定角度的正弦值。\nNumber:待求正弦值的以弧度表示的角度。\n备注:\n 如果参数的单位是度,将其乘以PI()/180即可转换成弧度。\n示例:\nSIN(10)等于-0.5440211108893698。\nSIN(45*PI()/180)等于0.707106781。","name":"SIN","type":"MATH"},{"def":"switch(表达式, 值1, 结果1, 值2, 结果2, ...)\n如果表达式的结果是值1,整个函数返回结果1\n如果表达式的结果是值2,整个函数返回结果2\n如果表达式的结果是值3,整个函数返回结果3\n等等\n","name":"SWITCH","type":"LOGIC"},{"def":"ROW()返回当前单元格的行号,必须使用于条件属性中\n示例:\n如果当前单元格为A5,在A5中写入\"=ROW()\"则返回5。\n如果当前单元格为B8,在B8中写入\"=ROW()\"则返回8。","name":"ROW","type":"REPORT"},{"def":"EVAL(exp)返回表达式exp计算后的结果。\nexp:一个表达式形式字符串。\n备注:\n 只要EVAL中的参数exp最终可以转化成一表达式形式的字符串,比如\"sum(2,4)\",\"2+7\"等等,那么它就可以被计算。\nEVAL(\"2+5\")等于7。\nEVAL(\"count(2,3)\")等于2。\nEVAL(\"sum\"+\"(2,3,5)\")等于10。\nEVAL(IF(true, \"sum\", \"count\") + \"(1,2,3,4)\")等于10。\nEVAL(IF(false, \"sum\", \"count\") + \"(1,2,3,4)\")等于4。","name":"EVAL","type":"OTHER"},{"def":"ATAN(number): 计算指定数值的反正切值。指定数值是返回角度的正切值,返回角度以弧度形式表示。\nNumber:返回角度的正切。\n备注:\n 返回角度在-pi/2到pi/2之间。\n 如果返回角度等于-pi/2或pi/2,ATAN将返回错误信息*NUM!。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nATAN(-1)等于-0.785398163(-pi/4弧度)。\nATAN(0)等于0(弧度)。\nATAN(2)*180/PI()等于63.43494882(度)。","name":"ATAN","type":"MATH"},{"def":"RANGE(from,to,step)函数表示从整数from开始,以step为每一步的大小,直到整数to的一个数字序列。\n例如:\nRANGE(1,5,1)表示从1开始,直到5(包括5),每一步大小为1,那么它返回一个数字序列为[1,2,3,4,5]。\nRANGE(-1,6,2)表示从-1开始,直到6(包括6),每一步大小为2,那么它返回一个数字序列为[-1,1,3,5]。\n备注:RANGE函数有三种参数形式:\n1 RANGE(to),默认的from为1,step为1,例如:\n RANGE(4)返回[1,2,3,4]。\n RANGE(-5)返回[]。\n2 RANGE(from,to),默认的step为1,例如:\n RANGE(-1,3)返回[-1,0,1,2,3]。\n RANGE(0,5)返回[0,1,2,3,4,5]。\n3 RANGE(from,to,step),三个参数的情况参照上面的注释,例如:\n RANGE(6,-1,-2)返回[6,4,2,0]。\n RANGE(4,1,1)返回[]。","name":"RANGE","type":"ARRAY"},{"def":"TANH(number):返回某一数字的双曲正切值。\nnumber:为任意实数。\n双曲正切的计算公式如下:\n示例:\nTANH(-2) 等于 -0.96403\nTANH(0) 等于 0\nTANH(0.5) 等于 0.462117\n","name":"TANH","type":"MATH"},{"def":"ROUNDDOWN(number,num_digits):靠近零值,向下(绝对值减小的方向)舍入数字。\nnumber:为需要向下舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDDOWN 和函数 ROUND 功能相似,不同之处在于函数 ROUNDDOWN 总是向下舍入数字。\n示例:\nROUNDDOWN(3.2, 0) 等于 3\nROUNDDOWN(76.9,0) 等于 76\nROUNDDOWN(3.14159, 3) 等于 3.141\nROUNDDOWN(-3.14159, 1) 等于 -3.1\nROUNDDOWN(31415.92654, -2) 等于 31,400\n","name":"ROUNDDOWN","type":"MATH"},{"def":"循环引用, =CIRCULAR(A1, B1, C1, D1)等同于=IF(&A1 = 1, 0, B1[A1:-1] + C1[A1:-1] – D1[A1:-1]),如需横向, 则传递第五个参数false","name":"CIRCULAR","type":"HA"},{"def":"HOUR(serial_number):返回某一指定时间的小时数。函数指定HOUR为0(0:00)到23(23:00)之间的一个整数。\nSerial_number:包含所求小时的时间。\n示例:\nHOUR(\"11:32:40\")等于11。\nHOUR(\"11:32:40\", \"HH:mm:ss\")等于11。","name":"HOUR","type":"DATETIME"},{"def":"ROUND(number,num_digits):返回某个数字按指定位数舍入后的数字。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND(2.15, 1) 等于 2.2\nROUND(2.149, 1) 等于 2.1\nROUND(-1.475, 2) 等于 -1.48\nROUND(21.5, -1) 等于 20\n因浮点数存在精度计算丢失问题, 导致计算结果里可能带上9999, 0000这些, \n因此加入第三个参数来控制是否需要去除9999. true表示需要过滤9999, 0000这些数据.","name":"ROUND","type":"MATH"},{"def":"YEARDELTA(date, delta):返回指定日期后delta年的日期。\n示例:\nYEARDELTA(\"2008-10-10\",10)等于2018-10-10。","name":"YEARDELTA","type":"DATETIME"},{"def":"DATEINYEAR(date, number):函数返回在一年当中第几天的日期。\n示例:\nDATEINYEAR(2008,100)等于2008-04-09,等价于DATEINYEAR(\"2008-08-08\",100),也返回2008-04-09.\nDATEINYEAR(2008,-1)等于2008-12-31,等价于DATEINYEAR(\"2008-08-08\",-1),也返回2008-12-31.","name":"DATEINYEAR","type":"DATETIME"},{"def":"WEIGHTEDAVERAGE(A1:A4,B1:B4): 返回指定数据的加权平均值。\n加权平均数是不同比重数据的平均数,加权平均数就是把原始数据按照合理的比例来计算。\nA1:A4,B1:B4:用于计算平均值的参数,A1~A4为数据,B1~B4为权值。\n示例:\n如果A1:A4为10,9,8,7,B1:B4为0.2,0.1,0.3,0.4则:\nWEIGHTEDAVERAGE(A1:A4,B1:B4)等于8.1。","name":"WEIGHTEDAVERAGE","type":"MATH"},{"def":"ASIN(number): 返回指定数值的反正弦值。反正弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的正弦值。\n备注:\n 指定数值必须在-1到1之间(含1与-1)。\n 返回角度在-pi/2到pi/2之间(含-pi/2与pi/2)。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nASIN(0.5)等于0.523598776(pi/6弧度)。\nASIN(1)等于1.570796327(pi/2弧度)。\nASIN(0.5)*180/PI()等于30(度)。","name":"ASIN","type":"MATH"},{"def":"INT(number): 返回数字下舍入(数值减小的方向)后最接近的整数值。\nNumber:需要下舍入为整数的实数。\n示例:\nINT(4.8)等于4。\nINT(-4.8)等于-5。\nINT(4.3)等于4。\nINT(-4.3)等于-5。\n公式INT(A1)将返回A1单元格中的一个正实数的整数数部分。","name":"INT","type":"MATH"},{"def":"GETUSERJOBTITLES():返回角色职务\n示例:\nGETUSERDEPARTMENTS():返回角色所有职务,若多个部门职务则返回职务数组","name":"GETUSERJOBTITLES","type":"OTHER"},{"def":"REGEXP(str, pattern):字符串str是否与正则表达式pattern相匹配。\n示例:\nREGEXP(\"aaaaac\",\"a*c\")等于true。\nREGEXP(\"abc\",\"a*c\")等于false。\n\nREGEXP(str, pattern, intNumber):字符串str是否与具有给定模式 intNumber的正则表达式pattern相匹配。\n示例:\nCASE_INSENSITIVE = 0 启用不区分大小写的匹配。 默认情况下,不区分大小写的匹配假定仅匹配 US-ASCII 字符集中的字符。可以通过指 定 UNICODE_CASE 标志连同此标志来启用 Unicode 感知的、不区分大小写的匹配。 \nMULTILINE = 1 启用多行模式。\nDOTALL = 2 启用 dotall 模式。在 dotall 模式中,表达式 . 可以匹配任何字符,包括行结束符。默认情况下,此表达式不匹配行 结束符。\nUNICODE_CASE = 3 启用 Unicode 感知的大小写折叠。指定此标志后,由 CASE_INSENSITIVE 标志启用时,不区分大小写的匹配将以 符合 Unicode Standard 的方式完成。\nCANON_EQ = 4 启用规范等价。 指定此标志后,当且仅当其完整规范分解匹配时,两个字符才可视为匹配。\nUNIX_LINES = 5 启用 Unix 行模式。 在此模式中,.、^ 和 $ 的行为中仅识别 '\\n' 行结束符。\nLITERAL = 6 启用模式的字面值解析。 指定此标志后,指定模式的输入字符串就会作为字面值字符序列来对待。输入序列中的 元字符或转义序列不具有任何特殊意义。 标志 CASE_INSENSITIVE 和 UNICODE_CASE 在与此标志一起使用时将 对匹配产生影响。其他标志都变得多余了。\nCOMMENTS = 7 模式中允许空白和注释。 此模式将忽略空白和在结束行之前以 # 开头的嵌入式注释。\n \nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 3)等于true。\nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 1)等于false。\n\n","name":"REGEXP","type":"TEXT"},{"def":"DAYSOFQUARTER(date): 返回从1900年1月后某年某季度的天数。\n示例:\nDAYSOFQUARTER(\"2009-02-01\")等于90。\nDAYSOFQUARTER(\"2009/05/05\")等于91。","name":"DAYSOFQUARTER","type":"DATETIME"},{"def":"AVERAGE(number1,number2,…,countstring): 返回指定数据的平均值。\nNumber1,number2…:用于计算平均值的参数; countString:文字、逻辑值是否参与计数。\n备注:\n 参数必须是数字,或是含有数字的名称,数组或引用。\n 如果数组或引用参数中含有文字,逻辑值,默认参与计数,countString为false则不参与计数;\n 空单元格始终不参与计数,但是,单元格中的零值参与。\n示例:\n如果A1:A6被命名为“ages”,分别等于10,23,文字,29,33及25,则:\nAVERAGE(A1:A6)等于20。\nAVERAGE(A1:A6, false)等于24。\nAVERAGE(ages)等于20。\n如果还有一个年龄为27的,求所有年龄的平均值为: AVERAGE(A1:A6,27)等于21。","name":"AVERAGE","type":"MATH"},{"def":"RADIANS(angle): 将角度转换成弧度。\nAngle:需要转换为弧度的角度。\n示例:\nRADIANS(90)等于1.570796327(π/2弧度)。","name":"RADIANS","type":"MATH"},{"def":"REMOVEARRAY(array, start, deleteCount):从数组array中删除从第start个元素开始的deleteCount个数组元素,并返回删除后的数组。\n示例:\nREMOVEARRAY([3, 4, 4, 2, 6, 7, 87], 4, 2)返回[3, 4, 4, 7, 87].\n","name":"REMOVEARRAY","type":"ARRAY"},{"def":"WEBIMAGE(path):在web页面上显示指定路径下的图片。","name":"WEBIMAGE","type":"OTHER"},{"def":"WEEK(serial_num):返回一个代表一年中的第几周的数字。\nSerial_num:表示输入的日期。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nWEEK(\"2010/1/1\")等于52。\nWEEK(\"2010/1/6\")等于1。\nWEEK(35796)等于1。","name":"WEEK","type":"DATETIME"},{"def":"filename(file)获取文件的文件名。\n当file为单文件时,返回文件名字符串,当file为多文件时,返回文件名的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.cpt },则filename(B2)返回值为[“A.doc”, “C.xls”, “B.cpt”]。","name":"FILENAME","type":"OTHER"},{"def":"COSH(number): 返回一个数值的双曲线余弦值。\nNumber:需要求其双曲线余弦值的一个实数。\n备注:\n 双曲线余弦值计算公式为: ,其中e是自然对数的底,e=2.71828182845904。\n示例:\nCOSH(3)等于10.06766200。\nCOSH(5)等于74.20994852。\nCOSH(6)等于201.7156361。","name":"COSH","type":"MATH"},{"def":"WEEKDAY(Serial_number):获取日期并返回星期数。返回值为介于0到6之间的某一整数,分别代表星期中的某一天(从星期日到星期六)。\nSerial_number:输入的日期\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n举例:\nWEEKDAY(\"2005/9/10\")等于6(星期六)。\nWEEKDAY(\"2005/9/11\")等于0(星期日)。\nWEEKDAY(35796)等于4(星期四)。\n","name":"WEEKDAY","type":"DATETIME"},{"def":"OR(logical1,logical2,…): 当所有参数的值为假时,返回FALSE;当任意参数的值为真时,返回TRUE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nOR(1+7=9,5+7=11)等于FALSE。\nOR(1+7=8,5+7=11)等于TRUE。","name":"OR","type":"LOGIC"},{"def":"MOD(number,divisor):返回两数相除的余数。结果的正负号与除数相同。\nnumber:为被除数。\ndivisor:为除数。\n示例:\nMOD(3, 2) 等于 1\nMOD(-3, 2) 等于 1\nMOD(3, -2) 等于 -1\nMOD(-3, -2) 等于 -1\n","name":"MOD","type":"MATH"},{"def":"TODAY():获取当前日期。\n示例:\n如果系统日期是2005年9月10日\n则TODAY()等于2005-9-10。","name":"TODAY","type":"DATETIME"},{"def":"ROUNDUP(number,num_digits):远离零值,向上(绝对值增大的方向)舍入数字。\nnumber:为需要向上舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDUP 和函数 ROUND 功能相似,不同之处在于函数 ROUNDUP 总是向上舍入数字。\n示例:\nROUNDUP(3.2,0) 等于 4\nROUNDUP(76.9,0) 等于 77\nROUNDUP(3.14159, 3) 等于 3.142\nROUNDUP(-3.14159, 1) 等于 -3.2\nROUNDUP(31415.92654, -2) 等于 31,500\n\n","name":"ROUNDUP","type":"MATH"},{"def":"ROUND5(number,num_digits):这个是四舍五入,奇进偶不进。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND5(2.125, 2) 等于 2.12\nROUND5(2.135, 2) 等于 2.14\n","name":"ROUND5","type":"MATH"},{"def":"TIME(hour,minute,second): 返回代表指定时间的小数。介于0:00:00(12:00:00 A.M.)与23:59:59(11:59:59 P.M.)之间的时间可返回0到0.99999999之间的对应数值。\nHour:介于0到23之间的数。\nMinute:介于0到59之间的数。\nSecond:介于0到59之间的数。\n示例:\nTIME(14,40,0)等于2:40 PM。\nTIME(19,43,24)等于7:43 PM。","name":"TIME","type":"DATETIME"},{"def":"环比公式, =MOM(A1, B1)等同于=IF(&A1 > 1, B1 / B1[A1:-1],0), 其中如果需要指定偏移量x, 则传递第三个参数x, 第四个参数表示横纵向.\n如=MOM(A1, B1, -2, false)等同于=IF(&A1 > 1, B1 / B1[;A1:-2], 0)","name":"MOM","type":"HA"},{"def":"ASINH(number): 返回指定数值的反双曲正弦值。反双曲正弦值的双曲正弦等于指定数值。即: ASINH(SINH(number))=number。\nNumber:任意实数。\n示例:\nASINH(-5)等于-2.312438341。\nASINH(8)等于2.776472281。\nASINH(16)等于3.466711038。","name":"ASINH","type":"MATH"},{"def":"EENNUMBER(value):将给定的BigDecimal类型的数字(100以内)取整后转化成英文金额的字符串。\n示例:\nENNUMBER(23.49)等于TWENTY THREE。\n注:若出现结果为空,需要将数字强制转换为BigDecimal类型,例如:ENNUMBER(TOBIGDECIMAL(80))","name":"ENNUMBER","type":"TEXT"},{"def":"CODE(text): 计算文本串中第一个字符的数字代码。返回的代码对应于计算机使用的字符集。\nText:需要计算第一个字符代码的文本或单元格引用。\n示例:\nCODE(\"S\")等于83。\nCODE(\"Spreadsheet\")等于83。","name":"CODE","type":"TEXT"},{"def":"DEGREES(angle): 将弧度转化为度。\nangle:待转换的弧度角。\n示例:\nDEGREES(PI()/2)等于90。\nDEGREES(3.1415926)等于179.9999969。","name":"DEGREES","type":"MATH"},{"def":"LEN(args): 返回文本串中的字符数或者数组的长度。\n需要注意的是:参数args为文本串时,空格也计为字符。\n参数args为数组时,直接返回数组长度。\n示例:\nLEN(\"Evermore software\")等于17。\nLEN(\" \")等于1。\nLEN(['a','b'])等于2。\n","name":"LEN","type":"TEXT"},{"def":"DATETIME():获取当前日期和时间。\n示例:\n如果系统时间是2005年9月10日 15点18分38秒\n则DATETIME()等于2005-9-10 15:18:36。","name":"DATETIME","type":"DELETE"},{"def":"UNIQUEARRAY(array):去掉数组array中的重复元素。\n示例:\nUNIQUEARRAY([14, 2, 3, 4, 3, 2, 5, 6, 2, 7, 9, 12, 3])返回[14, 2, 3, 4, 5, 6, 7, 9, 12].","name":"UNIQUEARRAY","type":"ARRAY"},{"def":"PROMOTION(value1,value2):返回value2在value1上提升的比例。\n示例:\nPROMOTION(12, 14)等于0.166666666,即提升了16.6666666%.\nPROMOTION(-12, 14)等于2.166666666,即提升了216.6666666%.","name":"PROMOTION","type":"MATH"},{"def":"PI(number): 是一个数学常量函数,当number为空时,函数返回精确到15位的数值3.141592653589793;当参数不为空时,number表示PI的倍数。\n示例:\nSIN(PI()/2)等于1。\n计算圆的面积的公式: S=PI()*(r^2),其中S为圆的面积,R为圆的半径。\nPI(3)等于9.42477796076938。","name":"PI","type":"MATH"},{"def":"ISNULL(object):判断对象中所有的值是否全部都是NULL或者为空字符串。","name":"ISNULL","type":"OTHER"},{"def":"LET(变量名,变量值,变量名,变量值,..., 表达式):局部变量赋值函数,参数的个数N必须为奇数, 最后一个是表达式,前面是N-1(偶数)为局部变量赋值对。\n变量名: 必须是合法的变量名,以字母开头,可以包括字母,数字和下划线\n表达式: 根据前面的N-1个参数赋值后计算出来的结果,这些变量赋值只在这个表达式内部有效\n示例:\nLET(a, 5,b, 6, a+b)等于11\n","name":"LET","type":"OTHER"},{"def":"SECOND(serial_number):返回某一指定时间的秒数,其值是介于0与59之间的一个整数。\nSerial_number:包含所求秒数的时间。\n示例:\nSECOND(\"15:36:25\")等于25。\nSECOND(\"15:36:25\", \"HH:mm:ss\")等于25。","name":"SECOND","type":"DATETIME"},{"def":"EXP(number): 返回e的n次幂。常数e为自然对数的底数,等于2.71828182845904。\nNumber:为任意实数,作为常数e的指数。\n备注:\n 如果要返回其他常数作为底数的幂,可以使用指数运算符(^)。例如: 在4^2中,4是底数,而2是指数。\n EXP函数与LN函数互为反函数。\n示例:\nEXP(0)等于1。\nEXP(3)等于20.08553692。\nEXP(LN(2))等于2。","name":"EXP","type":"MATH"},{"def":"treelayer(TreeObject, Int, Boolean, String):\n返回tree对象第n层的值,并且可以设置返回值类型及分隔符。\nTreeObject:tree对象,如$tree。\nInt:想要获得层级的数值,最上层为1,第二层为2,依此类推,若无则返回最底层\n。Boolean:返回值类型为字符串还是数组,默认false,返回数组;为true时返回字符串。\nString:当Boolean为true返回字符串时的分隔符,以双引号表示,默认为逗号\",\",如\";\"。\n示例:\n假设$tree勾选的值为中国-江苏-南京,中国-浙江-杭州,则treelayer($tree, true, ”\\’,\\’”):返回”’,’”分割的所选中节点字符串”南京’,’杭州”treelayer($tree, 2):以数组形式返回第二层[“江苏”,”浙江”]。treelayer($tree, 2, true, ”\\’,\\’”):返回”’,’”分割的字符串江苏’,’浙江。","name":"TREELAYER","type":"OTHER"},{"def":"读取配置文件","name":"TOTEXT","type":"DELETE"}]; +BI.FormulaJson = [{def: "MONTH:(serial_number)返回日期中的月。月是介于1和12之间的一个数。\nSerial_number:含有所求的月的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nMONTH(\"2000/1/1\")等于1。\nMONTH(\"2006/05/05\")等于5。\nMONTH(\"1997/04/20\")等于4。\nMONTH(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nMONTH(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nMONTH(\"1997-04-20\", \"yyyy-MM-dd\")等于4。\nMONTH(35796)等于1。", name: "MONTH", type: "DATETIME"}, {def: "ROWCOUNT(tableData)返回tableData的行数。\ntableData:TableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是tableData的行数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nROWCOUNT(\"ds1\")等于20。", name: "ROWCOUNT", type: "REPORT"}, {def: "RAND(): 返回均匀分布的随机数。每计算一次工作表,函数都会返回一个新的随机数值。\n备注:\n 要生成一个位于a和b之间的随机数,可以使用以下的公式: C=RAND()*(b-a)+a。\n 如果要使一个随机产生的数值不随单元格的重计算而改变,可以在编辑框中输入=RAND()并保持编辑状态,然后按F9,将公式永久性地改为随机数。\n示例:\n假如需要生成一个大于等于0,小于60的随机数,使用公式: =RAND()*60。\n假如需要生成一个大于等于0,小于19的随机数,使用公式: =RAND()*19。\n假如需要生成一个大于等于0,小于50的随机数,使用公式: =RAND()*50。", name: "RAND", type: "MATH"}, {def: "GETUSERDEPARTMENTS():返回角色部门\n示例:\nGETUSERDEPARTMENTS():返回角色所有部门,若多个部门则数组\nGETUSERDEPARTMENTS(3,2):返回角色该部门的第三层和第二层名字,\n若多个部门则返回数组,若没有第三层则只显示第二层", name: "GETUSERDEPARTMENTS", type: "OTHER"}, {def: "FORMAT(object,format) : 返回object的format格式。\nobject 需要被格式化对象,可以是String,数字,Object(常用的有Date, Time)。\nformat 格式化的样式。\n示例\nFORMAT(1234.5, \"#,##0.00\") => 1234.50\nFORMAT(1234.5, \"#,##0\") => 1234\nFORMAT(1234.5, \"¥#,##0.00\") => ¥1234.50\nFORMAT(1.5, \"0%\") => 150%\nFORMAT(1.5, \"0.000%\") => 150.000%\nFORMAT(6789, \"##0.0E0\") => 6.789E3\nFORMAT(6789, \"0.00E00\") => 6.79E03\nFORMAT(date(2007,1,1), \"EEEEE, MMMMM dd, yyyy\") => 星期一,一月 01,2007\nFORMAT(date(2007,1,13), \"MM/dd/yyyy\") => 01/13/2007\nFORMAT(date(2007,1,13), \"M-d-yy\") => 1-13-07\nFORMAT(time(16,23,56), \"h:mm:ss a\") => 4:23:56 下午", name: "FORMAT", type: "TEXT"}, {def: "TRIM(text): 清除文本中所有空格,单词间的单个空格除外,也可用于带有不规则空格的文本。\nText:需要清除空格的文本。\n示例:\nTRIM(\" Monthly Report\")等于Monthly Report。", name: "TRIM", type: "TEXT"}, {def: "SQRT(number): 返回一个正数的平方根。\nNumber:要求其平方根的任一正数。\n备注:\nNumber必须是一个正数,否则函数返回错误信息*NUM!。\n示例:\nSQRT(64)等于8。\nSQRT(-64)返回*NUM!。", name: "SQRT", type: "MATH"}, {def: "DAYSOFYEAR(year):返回某年包含的天数。\n示例:\nDAYSOFYEAR(2008)等于365,等价于DAYSOFYEAR(\"2008-01-01\")。", name: "DAYSOFYEAR", type: "DATETIME"}, {def: "RANK(number,ref,order): 返回一个数在一个数组中的秩。(如果把这个数组排序,该数的秩即为它在数组中的序号。)\nNumber 所求秩的数。(可以是Boolean型,true=1,false=0)\nRef 可以是数组,引用,或一系列数,非实数的值被忽略处理(接受Boolean型,true=1,false=0)。\nOrder 指定求秩的参数,非零为升序,零为降序\n\n备注\n1. RANK对重复的数返回相同的秩,但重复的数影响后面的数的秩,比如,在一组升序排列的整数中,如果5出现了2次,并且秩为3,那么6的秩为5 (没有数的秩是4).\n\n示例\nA1:A5 = 6, 4.5, 4.5, 2, 4\nRANK(A1,A1:A5,1) 即 6 的秩为 5.\n\nRANK(3,1,2,\"go\",3,4,1) = 3, \"go\"被忽略。", name: "RANK", type: "OTHER"}, {def: "ODD(number):返回对指定数值进行舍入后的奇数。\nnumber:是要舍入求奇的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是奇数,则不须进行任何舍入处理。\n示例:\nODD(1.5) 等于 3\nODD(3) 等于 3\nODD(2) 等于 3\nODD(-1) 等于 -1", name: "ODD", type: "MATH"}, {def: "COLCOUNT(tableData):返回tableData中列的个数。\ntableData:tableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是第一个查找到的tableData中列数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nCOLCOUNT(\"ds1\")等于6。\n", name: "COLCOUNT", type: "REPORT"}, {def: "ENDWITH(str1,str2):判断字符串str1是否以str2结束。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nENDWITH(\"FineReport\",\"Report\")等于true。\nENDWITH(\"FineReport\",\"Fine\")等于false。\nENDWITH(\"FineReport\",\"report\")等于false。", name: "ENDWITH", type: "TEXT"}, {def: "LOG10(number):返回以 10 为底的对数。\nnumber: 用于常用对数计算的正实数。\n示例:\nLOG10(86) 等于 1.934498451\nLOG10(10) 等于 1\nLOG10(1E5) 等于 5\n", name: "LOG10", type: "MATH"}, {def: "MAPARRAY(array, fn):把一个数组中的项目转换到另一个数组中。\narray (Array): 要转换的数组 \nfn (Function): 处理数组项目的函数 \n示例:\nMAPARRAY([3,4,2,3,6,8,7], item != 3)等于[false,true,true,false,true,true,true].", name: "MAPARRAY", type: "ARRAY"}, {def: "FLOOR(number): 将参数number沿绝对值减小的方向去尾舍入。\nNumber:待舍入的数值。\n示例:\nFLOOR(-2.5)等于-2。\nFLOOR(2.5)等于2。\n", name: "FLOOR", type: "MATH"}, {def: "NUMTO(number,bool)或NUMTO(number):返回number的中文表示。其中bool用于选择中文表示的方式,当没有bool时采用默认方式显示。\n示例:NUMTO(2345,true)等于二三四五。\n示例:NUMTO(2345,false)等于二千三百四十五。\n示例:NUMTO(2345)等于二千三百四十五。", name: "NUMTO", type: "TEXT"}, {def: "ATANH(number): 返回数字的反双曲正切值,该函数的参数值即为反双曲正切值的双曲正切值。\nNumber:指介于-1~1之间的任意实数。\n备注:\n 指定的number必须介于-1~1之间(不包括-1,1)。\n ATANH(TANH(number))=number,例如,ATANH(TANH(8))=8。\n示例:\nATANH(-0.5)等于-0.549306144。\nATANH(0)等于0。\nATANH(0.7)等于0.867300528。", name: "ATANH", type: "MATH"}, {def: "YEAR:(serial_number)返回日期中的年。Year是介于1900和9999之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nYEAR(\"2000/1/1\")等于2000。\nYEAR(\"2006/05/05\")等于2006。\nYEAR(\"1997/04/20\")等于1997。\nYEAR(\"2000-1-1\", \"yyyy-MM-dd\")等于2000。\nYEAR(\"2006-05-05\", \"yyyy-MM-dd\")等于2006。\nYEAR(\"1997-04-20\", \"yyyy-MM-dd\")等于1997。\nYEAR(35796)等于1998。", name: "YEAR", type: "DATETIME"}, {def: "SLICEARRAY(array, start, end):返回数组从第start个到第end个元素(包括第end个元素)。\n示例:\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3, 6)返回[4, 5, 1, 5].\n当不使用end参数时,返回从start开始到数组结束之间的元素。\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3)返回[4, 5, 1, 5, 7].", name: "SLICEARRAY", type: "ARRAY"}, {def: "", name: "DECODE", type: "OTHER"}, {def: "ENMONEY(value):将给定的BigDemical类型的数字转换成英文金额字符串。\n示例:\nENMONEY(23.49)等于TWENTY THREE AND CENTS FORTY NINE", name: "ENMONEY", type: "TEXT"}, {def: "IF(boolean,number1/string1,number2/string2):判断函数,boolean为true时返回第二个参数,为false时返回第三个。\nboolean: 用于判断的布尔值,true或者false。\nnumber1/string1: 第一个参数,如果boolean为ture,返回这个值。\nnumber2/string2: 第二个参数,如果boolean为false,返回这个值。\n示例:\nIF(true,2,8)等于2\nIF(false,\"first\",\"second\")等于second\nIF(true,\"first\",7)等于first", name: "IF", type: "LOGIC"}, {def: "DATEINWEEK(date, number):函数返回在某一个星期当中第几天的日期。\n示例:\ndateInWeek(\"2008-08-28\", 2)等于2008-08-26。\ndateInWeek(\"2008-08-28\", -1)等于2008-08-31。\n如果最后一个参数为-1,返回该日期所在星期的最后一天\n", name: "DATEINWEEK", type: "DATETIME"}, {def: "MONTHDELTA(date,delta):返回指定日期date后delta个月的日期。\n示例:\nMONTHDELTA(\"2008-08-08\", 4)等于2008-12-08。", name: "MONTHDELTA", type: "DATETIME"}, {def: "FIELDS(connectionName,tableName):返回tableName这个表中的所有字段名。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么FIELDS(\"BASE\",\"task\")等于[name,start,end].", name: "FIELDS", type: "REPORT"}, {def: "DATEDIF(start_date,end_date,unit):返回两个指定日期间的天数、月数或年数。\nStart_date:代表所指定时间段的初始日期。\nEnd_date:代表所指定时间段的终止日期。\nUnit:函数返回信息的类型。\n若unit=“Y”,则DATEDIF返回指定时间段的年差数。\n若unit=“M”,则DATEDIF返回指定时间段的月差数。\n若unit=“D”,则DATEDIF返回指定时间段的日差数。\n若unit=“MD”,则DATEDIF忽略年和月,返回指定时间段的日差数。\n若unit=“YM”,则DATEDIF忽略年和日,返回指定时间段的月差数。\n若unit=“YD”,则DATEDIF忽略年,返回指定时间段的日差数。\n示例:\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"Y\")等于3,即在2001年2月28日与2004年3月20日之间有3个整年。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"M\")等于37,即在2001年2月28日与2004年3月20日之间有36个整月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"D\")等于1116,即在2001年2月28日与2004年3月20日之间有1116个整天。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"MD\")等于8,即忽略月和年后,2001年2月28日与2004年3月20日的差为8天。\nDATEDIF(\"2001/1/28\",\"2004/3/20\",\"YM\")等于2,即忽略日和年后,2001年1月28日与2004年3月20日的差为2个月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"YD\")等于21,即忽略年后,2001年2月28日与2004年3月20日的差为21天。", name: "DATEDIF", type: "DATETIME"}, {def: "TOIMAGE(path):显示指定路径下的图片。此处默认开启了图片缓存功能以加速报表的生成.\n如不需要缓存,请在参数后面追加值FALSE,例如:TOIMAGE(\"D:/fr.png\",false).\n如需要指定图片大小,拉伸显示, 则需要添加参数,TOIMAGE(patch, true, width, height).\n示例:=toimage(\"d:/1.jpg\", true, \"50%\", 300), 第三个参数为指定宽度, 第四个参数为指定高度.\n如果参数为整数, 则直接写数字, 如果为百分比, 则需要加上引号, 如\"300%\"", name: "TOIMAGE", type: "OTHER"}, {def: "LEFT(text,num_chars): 根据指定的字符数返回文本串中的第一个或前几个字符。\nText:包含需要选取字符的文本串或单元格引用。\nNum_chars:指定返回的字符串长度。\n备注:\n Num_chars的值必须等于或大于0。\n 如果num_chars大于整个文本的长度,LEFT函数将返回所有的文本。\n 如果省略num_chars,则默认值为1。\n示例:\nLEFT(\"Fine software\",8)等于“Fine sof”。\nLEFT(\"Fine software\")等于“F”。\n如果单元格A3中含有“China”,则LEFT(A3,2)等于“Ch”。", name: "LEFT", type: "TEXT"}, {def: "SUBSTITUTE(text,old_text,new_text,instance_num): 用new_text替换文本串中的old_text。\nText:需要被替换字符的文本,或含有文本的单元格引用。\nOld_text:需要被替换的部分文本。\nNew_text:用于替换old_text的文本。\nInstance_num:指定用new_text来替换第几次出现的old_text。如果指定了instance_num,则只有指定位置上的old_text被替换,否则文字串中出现的所有old_text都被new_text替换。\n备注:\n 如果需要替换文本串中的指定文本,则使用SUBSTITUTE函数;如果需要替换文本串中指定位置上的任意文本,则使用REPLACE函数。\n示例:\nSUBSTITUTE(\"data base\",\"base\",\"model\")等于“data model”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",1)等于“July 18, 2000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\")等于“July 18, 1000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",2)等于“July 28, 1000”。 ", name: "SUBSTITUTE", type: "TEXT"}, {def: "LOG(number,base): 按指定的任意底数,返回数值的对数。\nNumber:需要求对数的正实数。\nBase:对数的底数。如果省略底数,默认值为10。\n示例:\nLOG(16,2)等于4。\nLOG(10)等于1。\nLOG(24,3)等于2.892789261。", name: "LOG", type: "MATH"}, {def: "SORTARRAY(array):返回数组array排过序的数组。\n示例:\nSORTARRAY([3, 4, 4, 5, 1, 5, 7])返回[1, 3, 4, 4, 5, 5, 7].\n注意:数组array的元素类型必须一样,并且要可比较。", name: "SORTARRAY", type: "ARRAY"}, {def: "DATEDELTA(date, deltadays):返回一个日期??date后deltadays的日期。\ndeltaDays可以为正值,负值,零。\n示例:\nDATEDELTA(\"2008-08-08\", -10)等于2008-07-29。\nDATEDELTA(\"2008-08-08\", 10)等于2008-08-18。", name: "DATEDELTA", type: "DATETIME"}, {def: "MID(text,start_num,num_chars): 返回文本串中从指定位置开始的一定数目的字符,该数目由用户指定。\nText:包含要提取字符的文本串。\nStart_num:文本中需要提取字符的起始位置。文本中第一个字符的start_num为1,依此类推。\nNum_chars:返回字符的长度。\n备注:\n 如果start_num大于文本长度,MID函数返回“”(空文本)。\n 如果start_num小于文本长度,并且start_num加上num_chars大于文本长度,MID函数将从start_num指定的起始字符直至文本末的所有字符。\n 如果start_num小于1,MID函数返回错误信息*VALUE!。\n 如果num_chars是负数,MID函数返回错误信息*VALUE!。\n示例:\nMID(\"Finemore software\",10,8)返回“software”。\nMID(\"Finemore software\",30,5)返回“”(空文本)。\nMID(\"Finemore software\",0,8)返回*VALUE!。\nMID(\"Finemore software\",5,-1)返回*VALUE!。", name: "MID", type: "TEXT"}, {def: "ATAN2(x_num,y_num): 返回x、y坐标的反正切值。返回角度为x轴与过(x_num,y_num)与坐标原点(0,0)的一条直线形成的角度。该角度以弧度显示。\nX_num:指定点的x坐标。\nY_num:指定点的y坐标。\n备注:\n 正值表示从x轴开始以逆时针方式所得的角度;负值表示从x轴开始以顺时针方式所得的角度。\na > 0,b > 0 or a > 0, b < 0时,公式直接成立;\na < 0,b > 0, ATAN2(a,b)=PI()-ABS(ATAN(b/a))\na < 0,b < 0, ATAN2(a,b)=ABS(ATAN(b/a))-PI()\n 当x_num与y_num都为0时,ATAN2返回错误信息*DIV/0!。\n 用角度制显示返回数值时,把返回数值乘以180/PI()。\n 返回值以弧度表示(返回值大于-pi且小于等于pi)。\n示例:\nATAN2(-2,2)等于2.356194490192345(弧度制的3*pi/4)。\nATAN2(2,2)等于0.785398163(弧度制的pi/4)。\nATAN2(-2,2)*180/PI()等于135(角度制)。", name: "ATAN2", type: "MATH"}, {def: "SUM(number1,number2,…): 求一个指定单元格区域中所有数字之和。\nNumber1,number2,…:1到30个参数或指定单元格区域中所有数字。\n备注:\n 函数将直接键入参数中的数值、逻辑值及文本表达式计算在内。\n 若参数是数组或引用,则只有数组或单元格引用中的数值进行计算。\n示例:\nSUM(70,80)等于150。\nSUM(\"70\",80,TRUE)等于151,逻辑值“TRUE”作为1来计算;“FALSE”作为0计算;文本“70”作为70来计算。", name: "SUM", type: "MATH"}, {def: "EXACT(text1,text2): 检测两组文本是否相同。如果完全相同,EXACT函数返回TRUE;否则,返回FALSE。EXACT函数可以区分大小写,但忽略格式的不同。同时也可以利用EXACT函数来检测输入文档的文字。\nText1:需要比较的第一组文本。\nText2:需要比较的第二组文本。\n示例:\nEXACT(\"Spreadsheet\",\"Spreadsheet\")等于TRUE。\nEXACT(\"Spreadsheet\",\"S preadsheet\")等于FALSE。\nEXACT(\"Spreadsheet\",\"spreadsheet\")等于FALSE。", name: "EXACT", type: "TEXT"}, {def: "TOINTEGER(text): 将文本转换成Integer对象。\nText:需要转换的文本。\n示例:\nTOINTEGER(\"123\")等于 new Integer(123)。", name: "TOINTEGER", type: "TEXT"}, {def: "ACOSH(number): 返回给定数值的反双曲余弦。\nNumber:返回值的双曲余弦。\n备注:\n 参数number的值必须大于或等于1。\n ACOSH(COSH(number))=number。\n示例:\nACOSH(1)等于0。\nACOSH(8)等于2.768659383。\nACOSH(5.5)等于2.389526435。", name: "ACOSH", type: "MATH"}, {def: "weekdate(year,month,weekOfMonth,dayOfWeek): 返回指定年月的指定周的周几的具体日期。\n示例:\nweekdate(2009,10,2,1)\n返回的是2009年的10月的第二个周的第一天即星期天的日期,返回的是2009-10-04\n最后一个参数dayOfWeek为-1时,表示这个周的最后一天\n示例:\nweekdate(2009,12,1,-1)\n返回的是2009年的12月的第一个周的最后一天即星期六的日期,返回的是2009-12-05\n", name: "WEEKDATE", type: "DATETIME"}, {def: "MIN(number1,number2,…): 返回参数列表中的最小值。\nNumber1,number2,…:1到30个需要找出最小值的参数。\n备注:\n 若参数中没有数字,函数MIN将返回0。\n 参数应为数字、空白单元格、逻辑值或是表示数值的文本串。如果参数是错误值时,MIN将返回错误信息。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n示例:\n如果B1:B4包含3,6,9,12,则:\nMIN(B1:B4)等于3。\nMIN(B1:B4,0)等于0。", name: "MIN", type: "MATH"}, {def: "STARTWITH(str1,str2):判断字符串str1是否以str2开始。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nSTARTWITH(\"FineReport\",\"Fine\")等于true。\nSTARTWITH(\"FineReport\",\"Report\")等于false。\nSTARTWITH(\"FineReport\",\"fine\")等于false。", name: "STARTWITH", type: "TEXT"}, {def: "COMBIN(number,number_chosen): 返回若干个指定对象的组合数。该函数与数学表达式为Cnk功能相同。\nNumber或数学表达式中的“n”指对象总数。\nNumber_chosen或数学表达式中的“k”指在对象总数中某一组合的数量。\n备注:\n Number必须是正整数,number_chosen必须是非负整数。\n 如果number和number_chosen小于0或number小于number_chosen,函数返回错误信息*NUM!。\n 对象组合是对象的子集。与排列不同的是,组合不涉及对象内部的先后顺序,而顺序对排列是非常重要的。\n 假设number=n,number_chosen=k,则: COMBIN(n,k)=Cnk=n!/(k!(n-k)!)。\n示例:\nCOMBIN(5,6)等于*NUM!。\nCOMBIN(5,2)等于10。", name: "COMBIN", type: "MATH"}, {def: "EVEN(number):返回沿绝对值增大方向取整后最接近的偶数。使用该函数可以处理那些成对出现的对象。\nnumber:所要取整的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是偶数,则不须进行任何舍入处理。\n示例:\nEVEN(1.5) 等于 2\nEVEN(3) 等于 4\nEVEN(2) 等于 2\nEVEN(-1) 等于 -2", name: "EVEN", type: "MATH"}, {def: "COUNT(value1,value2,…): 计算数组或数据区域中所含项的个数。\nValue1,value2,…:可包含任何类型数据的参数。", name: "COUNT", type: "MATH"}, {def: "INDEXOFARRAY(array, index):返回数组array的第index个元素。\n示例:\nINDEXOFARRAY([\"第一个\", \"第二个\", \"第三个\"], 2)返回\"第二个\"。", name: "INDEXOFARRAY", type: "ARRAY"}, {def: "MAP(object, string, int, int):四个参数分别是索引值,数据集的名字,索引值所在列序号,返回值所在列序号。\n提醒:后两个参数也可以写列名代替。\n根据数据集的名字,找到对应的数据集,找到其中索引列的值为key所对应的返回值。\n数据集的查找方式是依次从报表数据集找到服务器数据集。\n索引列序号与返回值序列号的初始值为1示例:\nMAP(1001, \"employee\", 1, 2)返回employee数据集,第1列中值为1001那条记录中第2列的值。\nMAP(1001, \"employee\", \"name\", \"address\")返回employee数据集,name列中值为1001那条记录中address列的值。", name: "MAP", type: "REPORT"}, {def: "SEQ(): 返回数值,在整个报表执行过程中,返回该函数被第几次执行了。\n示例:\nSEQ()在第一次执行时,结果为1。\nSEQ()在第二次执行时,结果为2。", name: "SEQ", type: "OTHER"}, {def: "i18n为本软件内置的国际化公式,可以对一些常用的词语进行国际化.\n示例:i18n('File'), 则会在中文语言环境下显示为: 文件, 而在英文语言环境下显示为: File", name: "I18N", type: "REPORT"}, {def: "层次坐标简写, 等同于=A1[A1:-1], 若需=B1[A1:-1]则HIERARCHY(A1, B1).\n若为横向, 偏移量为-2, 则写成HIERARCHY(A1, B1, -2, false), 等同于=B1[;A1:-1].\n公式中最后一个参数表示横纵向, 默认不传递, 表示纵向扩展, 若横向扩展, 则需要加上最后一个参数FALSE来区分. ", name: "HIERARCHY", type: "HA"}, {def: "", name: "ENCODE", type: "OTHER"}, {def: "DATEINMONTH(date, number):函数返回在某一个月当中第几天的日期。\n示例:\nDATEINMONTH(\"2008-08-08\", 20) 等于2008-08-20。\nDATEINMONTH(\"2008-08-08\", -1) 等于2008-08-31。", name: "DATEINMONTH", type: "DATETIME"}, {def: "TOOCTAL(int): 将一个十进制整型数转换成八进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOOCTAL(10)等于 \"12\"。\nTOOCTAL(20)等于 \"24\"。", name: "TOOCTAL", type: "MATH"}, {def: "REPEAT(text,number_times): 根据指定的次数重复显示文本。REPEAT函数可用来显示同一字符串,并对单元格进行填充。\nText:需要重复显示的文本或包含文本的单元格引用。\nNumber_times:指定文本重复的次数,且为正数。如果number_times为0,REPEAT函数将返回“”(空文本)。如果number_times不是整数,将被取整。REPEAT函数的最终结果通常不大于32767个字符。\n备注:\n 该函数可被用于在工作表中创建简单的直方图。\n示例:\nREPEAT(\"$\",4)等于“$$$$”。\n如果单元格B10的内容为“你好”,REPEAT(B10,3)等于“你好你好你好”。", name: "REPEAT", type: "TEXT"}, {def: "GREPARRAY(array,fn):函数(返回true或者false)是条件,过滤此数组,最后形成一个新数组。\n示例:\nGREPARRAY([3,4,2,3,6,8,7], item != 3)等于[4,2,6,8,7].\n", name: "GREPARRAY", type: "ARRAY"}, {def: "MAX(number1,number2,…): 返回参数列表中的最大值。\nNumber1,number2,…:1到30个需要找出最大值的参数。\n备注:\n 参数可以是数字、空白单元格、逻辑值或数字的文本表达式。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n 如果参数中没有任何数字,MAX将返回0。\n示例:\nMAX(0.1,0,1.2)等于1.2。", name: "MAX", type: "MATH"}, {def: "CHAR(number): 根据指定数字返回对应的字符。CHAR函数可将计算机其他类型的数字代码转换为字符。\nNumber:用于指定字符的数字,介于1~65535之间(包括1和65535)。\n示例:\nCHAR(88)等于“X”。\nCHAR(45)等于“-”。", name: "CHAR", type: "TEXT"}, {def: "TRUNC(number,num_digits):将数字的小数部分截去,返回整数。\nnumber:需要截尾取整的数字。\nnum_digits:用于指定取整精度的数字。\n示例:\nTRUNC(8.9) 等于 8\nTRUNC(-8.9) 等于 -8\nTRUNC(PI()) 等于 3\n", name: "TRUNC", type: "MATH"}, {def: "FACT(number):返回数的阶乘,一个数的阶乘等于 1*2*3*...*该数。\nnumber:要计算其阶乘的非负数。如果输入的 number 不是整数,则截尾取整。\n示例:\nFACT(1) 等于 1\nFACT(1.9) 等于 FACT(1) 等于 1\nFACT(0) 等于 1\nFACT(5) 等于 1*2*3*4*5 等于 120\n", name: "FACT", type: "MATH"}, {def: "STDEV(array1): 计算数据系列的标准偏差(与Excel的同名函数作用相同)。\n\n示例:\nSTDEV([1,2,3])=1。\n", name: "STDEV", type: "OTHER"}, {def: "SPLIT(String1,String2):返回由String2分割String1组成的字符串数组。\nString1:以双引号表示的字符串。\nString2:以双引号表示的分隔符。例如逗号\",\"\n示例:\nSPLIT(\"hello,world,yes\",\",\") = [\"hello\",\"world\",\"yes\"]。\nSPLIT(\"this is very good\",\" \") = [\"this\",\"is\",\"very\",\"good\"]。\n备注:\n如果只有一个参数,则返回一个错误。\n如果有多个参数,则只有前两个起作用。", name: "SPLIT", type: "TEXT"}, {def: "INARRAY(co, array):返回co在数组array中的位置,如果co不在array中,则返回0.\n示例:\nString[] arr = {\"a\",\"b\",\"c\",\"d\"}\n那么INARRAY(\"b\", arr)等于2.", name: "INARRAY", type: "ARRAY"}, {def: "REVERSEARRAY(array):返回数组array的倒序数组。\n示例:\nREVERSEARRAY([\"第一个\", \"第二个\", \"第三个\"])返回[\"第三个\", \"第二个\", \"第一个\"].", name: "REVERSEARRAY", type: "ARRAY"}, {def: "RANDBETWEEN(value1,value2):返回value1和value2之间的一个随机整数。\n示例:\nRANDBETWEEN(12.333, 13.233)只会返回13。\nRANDBETWEEN(11.2, 13.3)有可能返回12或者13。", name: "RANDBETWEEN", type: "MATH"}, {def: "UPPER(text): 将文本中所有的字符转化为大写。\nText:需要转化为大写字符的文本,或是包含文本的单元格引用。\n示例:\nUPPER(\"notes\")等于“NOTES”。\n如果单元格E5的值为“Examples”,则UPPER(E5)等于“EXAMPLES”。", name: "UPPER", type: "TEXT"}, {def: "ABS(number): 返回指定数字的绝对值。绝对值是指没有正负符号的数值。\nNumber:需要求出绝对值的任意实数。\n示例:\nABS(-1.5)等于1.5。\nABS(0)等于0。\nABS(2.5)等于2.5。", name: "ABS", type: "MATH"}, {def: "RIGHT(text,num_chars): 根据指定的字符数从右开始返回文本串中的最后一个或几个字符。\nText:包含需要提取字符的文本串或单元格引用。\nNum_chars:指定RIGHT函数从文本串中提取的字符数。Num_chars不能小于0。如果num_chars大于文本串长度,RIGHT函数将返回整个文本。如果不指定num_chars,则默认值为1。\n示例:\nRIGHT(\"It is interesting\",6)等于“esting”。\nRIGHT(\"Share Holder\")等于“r”。\nRIGHT(\"Huge sale\",4)等于“sale”。", name: "RIGHT", type: "TEXT"}, {def: "MEDIAN(array1): 返回数据系列的中值(与Excel的同名函数作用相同)。\n\n示例:\nMEDIAN([1,2,3])=2。\n", name: "MEDIAN", type: "OTHER"}, {def: "TABLEDATAFIELDS(tableData):返回tableData中所有的字段名。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的列名组成的数组。\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nTABLEDATAFIELDS(\"ds1\")等于\nCUSTOMERID,CUSTOMERAME,CITY,COUNTRY,TEL,DISTRICT。", name: "TABLEDATAFIELDS", type: "REPORT"}, {def: "占比公式, =PROPORTION(A1)等同于=A1/sum(A1[!0])", name: "PROPORTION", type: "HA"}, {def: "COL()返回当前单元格的列号,必须使用于条件属性中\n示例:\n如果当前单元格是A5,在A5中写入\"=col()\"则返回1。\n如果当前单元格是C6,在C6中写入\"=col()\"则返回3。", name: "COL", type: "REPORT"}, {def: "TOHEX(int): 将一个十进制整型数转换成十六进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOHEX(15)等于 \"f\"。\nTOHEX(20)等于 \"14\"。", name: "TOHEX", type: "MATH"}, {def: "COS(number): 返回一个角度的余弦值。\nNumber:以弧度表示的需要求余弦值的角度。\n备注:\n 要把一个角度转换成弧度值,将角度乘于PI()/180。\n COS(n*2*PI()+number)=COS(number)(其中n为整数,number从-pi到pi)。\n示例:\nCOS(0.5)等于0.877582562。\nCOS(30*PI()/180)等于0.866025404。", name: "COS", type: "MATH"}, {def: "跨层累计, =CROSSLAYERTOTAL(A1, B1, C1, D1)等同于=IF(&B1 >1, D1[B1:-1] + C1, D1[A1:-1,B1:!-1] + C1), 如需横向, 则传递第五个参数false", name: "CROSSLAYERTOTAL", type: "HA"}, {def: "POWER(number,power): 返回指定数字的乘幂。\nNumber:底数,可以为任意实数。\nPower:指数。参数number按照该指数次幂乘方。\n备注:\n 可以使用符号“^”代替POWER,如: POWER(5,2)等于5^2。\n示例:\nPOWER(6,2)等于36。\nPOWER(14,5)等于537824。\nPOWER(4,2/3)等于2.519842100。\nPOWER(3,-2.3)等于0.079913677。", name: "POWER", type: "MATH"}, {def: "DAYS360(start_date,end_date,method):按照一年 360 天的算法(每个月以 30 天计,一年共计 12 个月),\n返回两日期间相差的天数,这在会计计算中将会用到。如果财务系统是基于一年 12 个月,每月 30 天,\n可用此函数帮助计算支付款项。\nStart_date 和 end_date :是用于计算期间天数的起止日期。\nMethod : 它指定了在计算中是采用欧洲方法还是美国方法。\nMethod 定义 :\nFALSE或忽略 美国方法 (NASD)。如果起始日期是一个月的 31 号,则等于同月的 30 号。如果终止日期是一个月的\n31号,并且起始日期早于 30 号,则终止日期等于下一个月的 1 号,否则,终止日期等于本月的 30 号。\nTRUE 欧洲方法。无论是起始日期还是终止日期为一个月的 31 号,都将等于本月的 30 号。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAYS360(\"1998/1/30\", \"1998/2/1\") 等于 1", name: "DAYS360", type: "DATETIME"}, {def: "filetype(file)获取文件的类型。\n当file为单文件时,返回文件类型字符串,当file为多文件时,返回文件类型的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.txt },则filetype(B2)返回值为[“doc”, “xls”, “txt”]。", name: "FILETYPE", type: "OTHER"}, {def: "ADDARRAY(array, insertArray, start):在数组第start个位置插入insertArray中的所有元素,再返回该数组。\n示例:\nADDARRAY([3, 4, 1, 5, 7], [23, 43, 22], 3)返回[3, 4, 23, 43, 22, 1, 5, 7].\nADDARRAY([3, 4, 1, 5, 7], \"测试\", 3)返回[3, 4, \"测试\", 1, 5, 7].\n注意:如果start为小于1的数或者不写start参数,则默认从数组的第一位开始插入数组元素。", name: "ADD2ARRAY", type: "ARRAY"}, {def: "BITNOT(int):将一个十进制整数进行二进制取反运算。\nint:需要进行转换的十进制数。\n示例:\nBITNOT(3)等于-4。\nBITNOT(12)等于-13。", name: "BITNOT", type: "LOGIC"}, {def: "TABLEAS(connectionName):返回名为connectionName的数据库中的所有表名。\n示例:\n假设在FRDemo这个数据库中,有3个表:a,b,c;\n那么TABLES(\"FRDemo\")等于[a,b,c].", name: "TABLES", type: "REPORT"}, {def: "SUMSQ(number1,number2, ...):返回所有参数的平方和。\nnumber1, number2, ...:为 1 到 30 个需要求平方和的参数,也可以使用数组或对数组的引用来代替以逗号分隔的参数。\n示例:\nSUMSQ(3, 4) 等于 25\n", name: "SUMSQ", type: "MATH"}, {def: "RECORDS(connection, table,field):返回数据库表table中字段名field下的所有元素。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么RECORDS(\"BASE\",\"task\",\"end\")等于[2009,2012].\n\nRECORDS(connection, table,field,row)返回table中field字段下的第row行的记录,field可以为列名也可以为列号。\n RECORDS(\"BASE\",\"task\",\"end\",2)等于2012.\n RECORDS(\"BASE\",\"task\",2,2)等于2009.", name: "RECORDS", type: "REPORT"}, {def: "", name: "TOBIGDECIMAL", type: "DELETE"}, {def: "TODOUBLE(text): 将文本转换成Double对象。\nText:需要转换的文本。\n示例:\nTODOUBLE(\"123.21\")等于 new Double(123.21)。", name: "TODOUBLE", type: "TEXT"}, {def: "TODATE()函数可以将各种日期形式的参数转换为日期类型。\n它有三种参数的形式:\n1 参数是一个日期型的参数,那么直接将这个参数返回。\n示例:\nTODATE(DATE(2007,12,12))返回2007年12月12日组成的日期。\n2 参数是以从1970年1月1日0时0分0秒开始的毫秒数,返回对应的时间。\n示例:\nTODATE(1023542354746)返回2002年6月8日。\n3 参数是日期格式的文本,那么返回这个文本对应的日期。\n示例:\nTODATE(\"2007/10/15\")返回2007年10月5日组成的日期。\nTODATE(\"2007-6-8\")返回2007年6月8日组成的日期。\n4 有两个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式。\n示例:\nTODATE(\"1/15/07\",\"mm/dd/yy\")返回07年1月15日组成的日期。\n特别的,\"yyyyMMdd\"是用来解析形如“20081230”之类的日期格式的。比如TODATE(\"20110830\",\"yyyyMMdd\")返回11年08月30日组成的日期\n5 有三个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式,第三个参数为解析日期的语言,如:zh(中文),en(英文)。\n示例:\nTODATE(\"星期三 1/15/07\",\"EEE mm/dd/yy\", \"zh\")返回07年1月15日组成的日期,使用“zh(中文)”才能够正常解析“星期三”这个字符串。", name: "TODATE", type: "DATETIME"}, {def: "PROPER(text): 将文本中的第一个字母和所有非字母字符后的第一个字母转化成大写,其他字母变为小写。\nText:需要转化为文本的公式、由双引号引用的文本串或是单元格引用。\n示例:\nPROPER(\"Finemore Integrated Office\")等于“Finemore Integrated Office”。\nPROPER(\"100 percent\")等于“100 Percent”。\nPROPER(\"SpreaDSheEt\")等于“Spreadsheet”。", name: "PROPER", type: "TEXT"}, {def: "DAY:(serial_number)返回日期中的日。DAY是介于1和31之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAY(\"2000/1/1\")等于1。\nDAY(\"2006/05/05\")等于5。\nDAY(\"1997/04/20\")等于20。\nDAY(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nDAY(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nDAY(\"1997-04-20\", \"yyyy-MM-dd\")等于20。\nDAY(35796)等于1。", name: "DAY", type: "DATETIME"}, {def: "LUNAR(year,day,month): 返回当前日期对应的农历时间。\nyear,month,day:分别对应年月日。\n示例:\n如果需要查询2011年7月21日对应的农历时间,则只需输入LUNAR(2011,7,21)结果将显示为:辛卯年六月廿一\n同样,如输入LUNAR(2001,7,21),则显示:辛巳年六月初一 。本公式支持的时间段为1900-2100年。", name: "LUNAR", type: "DATETIME"}, {def: "TABLEDATAS():返回报表数据集和服务器数据集名字。\n示例:\n服务器数据集有:ds1,ds2,ds3;报表数据集有dsr1,dsr2.\nTABLEDATAS()等于[dsr1,dsr2,ds1,ds2,ds3].\n而TABLEDATAS(0)返回服务器数据集名字;TABLEDATAS(1)返回报表数据集名字;\nTABLEDATAS(0)等于[ds1,ds2,ds3];TABLEDATAS(1)等于[dsr1,dsr2].", name: "TABLEDATAS", type: "REPORT"}, {def: "TAN(number): 返回指定角度的正切值。\nNumber:待求正切值的角度,以弧度表示。如果参数是以度为单位的,乘以Pi()/180后转换为弧度。\n示例:\nTAN(0.8)等于1.029638557。\nTAN(45*Pi()/180)等于1。", name: "TAN", type: "MATH"}, {def: "", name: "JVM", type: "DELETE"}, {def: "LN(number):返回一个数的自然对数。自然对数以常数项 e(2.71828182845904)为底。\nnumber:是用于计算其自然对数的正实数。\n示例:\nLN(86) 等于 4.45437\nLN(2.7182818) 等于 1\nLN(EXP(3)) 等于 3\nEXP(LN(4)) 等于 4\n", name: "LN", type: "MATH"}, {def: "ARRAY(arg1,arg2...):返回一个由arg1,arg2,...组成的数组.\narg1,arg2,...:字符串或者数字.\n示例:\nARRAY(\"hello\") = [\"hello\"].\nARRAY(\"hello\",\"world\") = [\"hello\",\"world\"].\nARRAY(\"hello\",98) = [\"hello\",98].\nARRAY(67,98) = [67,98].", name: "ARRAY", type: "ARRAY"}, {def: "TOBINARY(int): 将一个十进制整型数转换成二进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOBINARY(10)等于 \"1010\"。\nTOBINARY(20)等于 \"10100\"。", name: "TOBINARY", type: "MATH"}, {def: "NVL(value1,value2,value3,...):在所有参数中返回第一个不是null的值value1:可以为任意数,也可以为null。\nvalue2:可以为任意数,也可以为null。\n当字符串长度为0时, 返回也为null\n示例:\nNVL(12,20)等于12。\nNVL(null,12)等于12。\nNVL(null,null)等于null。\nNVL(20,null)等于20。\nNVL(null,null,10)等于10。", name: "NVL", type: "OTHER"}, {def: "CORREL(array1,array2): 求两个相同长度数据系列的相关系数(与Excel的同名函数作用相同)。\n如果数组或引用参数包含文本、逻辑值或空白单元格,则这些值将被忽略;但包含零值的单元格将计算在内。\n函数计算结果出现负数表示负相关。相关系数的取值范围是[-1,1]之间的数。相关系数的绝对值越大,表示误差越小。 Array1 和 Array2 的数据点的个数必须相同,例如:\nCORREL([1,2,3],[2,4,6])=1。\n", name: "CORREL", type: "OTHER"}, {def: "COLNAME(tableData,colIndex)返回的是tableData中列序号colIndex的列名。\ntableData:表示TableData的名字,字符串形式。\ncolIndex:表示列序号。\n备注:\n TableData先从私有数据源中查找,再从公有数据源中查找。\n示例:\nCOLNAME(\"Check\",3)等于AcceName。\nCOLNAME(\"country\",4)等于Area。", name: "COLNAME", type: "REPORT"}, {def: "DECIMAL(number): 返回number的大数类型,常用于精确计算。", name: "DECIMAL", type: "MATH"}, {def: "CLASS(object):返回object对象的所属的类。", name: "CLASS", type: "OTHER"}, {def: "VALUE(tableData,col,row)返回tableData中列号为col的值, 行号为row。\ntableData:tableData的名字,字符串形式的。\nrow:行号。\ncol:列号。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的行数。\n示例:\nVALUE(\"country\",5,3)等于South America。\nVALUE(\"Simple\",8,3)等于jonnason。\n示例:VALUE(\"country\",5,\"大陆\")等于South America。\n\nVALUE(tableData,col)返回tableData中列号为col的一列值。\nVALUE(tableData,targetCol, orgCol, element)返回tableData中第targetCol列中的元素,这些元素对应的第orgCol列的值为element。\n示例:\ntableData : co\n国家 省份\n\n中国 江苏\n中国 浙江\n中国 北京\n美国 纽约\n美国 新泽西\nVALUE(\"co\",2, 1, \"中国\")等于[\"江苏\", \"浙江\", \"北京\"]。\n特别说明:列号也可以写为列名。\nVALUE(tableData,targetCol, orgCol, element, idx)返回VALUE(tableData,targetCol, orgCol, element)数组的第idx个值。\n特别说明:idx的值小于0时,会取数组的第一个值,idx的值大于数组长度时,会取数组的最后一个值。\n", name: "VALUE", type: "REPORT"}, {def: "JOINARRAY(array,sepa):返回一个由sepa作为分隔符的字符串.\narray:[arg1,arg2...]格式的数组;\nsepa:分隔符。\n示例:\nJOINARRAY([1,2],\";\") = [1;2].\nJOINARRAY([hello,world],\"-\") = [hello-world].", name: "JOINARRAY", type: "ARRAY"}, {def: "DATETONUMBER(date):返回自 1970 年 1 月 1 日 00:00:00 GMT 经过的毫秒数。\n示例:\nDATETONUMBER(\"2008-08-08\")等于1218124800000。", name: "DATETONUMBER", type: "DATETIME"}, {def: "INDEXOF(str1,index):返回字符串str1在index位置上的字符。\n备注:\n index是从0开始计数的。\n示例:\nINDEXOF(\"FineReport\",0)等于'F'。\nINDEXOF(\"FineReport\",2)等于'n'。\nINDEXOF(\"FineReport\",9)等于't'。\n\nINDEXOF(array, index):返回数组在index位置上的元素。\n备注:\n index是从1开始计数的。\n示例:\nString[] array = {\"a\", \"b\", \"c\"}\nINDEXOF(array, 1)等于\"a\".\n", name: "INDEXOF", type: "TEXT"}, {def: "PRODUCT(number1,number2, ...):将所有以参数形式给出的数字相乘,并返回乘积值。\nnumber1, number2, ...:为 1 到 30 个需要相乘的数字参数。\n示例:\nPRODUCT(3,4) 等于 12\nPRODUCT(3,4,5) 等于 60\n\n", name: "PRODUCT", type: "MATH"}, {def: "ACOS(number): 返回指定数值的反余弦值。反余弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的余弦值。\n备注:\n 函数的参数必须在-1和1之间,包括-1和1。\n 返回的角度值在0和Pi之间。\n 如果要把返回的角度用度数来表示,用180/PI()乘返回值即可。\n示例:\nACOS(1)等于0(弧度)。\nACOS(0.5)等于1.047197551(Pi/3弧度)。\nACOS(0.5)*180/PI()等于60(度)。", name: "ACOS", type: "MATH"}, {def: "FIND(find_text,within_text,start_num):从指定的索引(start_num)处开始,返回第一次出现的指定子字符串(find_text)在此字符串(within_text)中的索引。\nFind_text:需要查找的文本或包含文本的单元格引用。\nWithin_text:包含需要查找文本的文本或单元格引用。\nStart_num:指定进行查找字符的索引位置。within_text里的索引从1开始。如果省略start_num,则假设值为1。\n备注:\n 如果find_text不在within_text中,FIND函数返回值为0。\n 如果start_num不大于0,FIND函数返回错误信息*VALUE!。\n 如果start_num大于within_text的长度,FIND函数返回值为0。\n 如果find_text是空白文本,FIND函数将在搜索串中匹配第一个字符(即编号为start_num或1的字符)。\n示例:\nFIND(\"I\",\"Information\")等于1。\nFIND(\"i\",\"Information\")等于9。\nFIND(\"o\",\"Information\",2)等于4。\nFIND(\"o\",\"Information\",12)等于0。\nFIND(\"o\",\"Information\",-1)等于*VALUE!。", name: "FIND", type: "TEXT"}, {def: "MINUTE(serial_number):返回某一指定时间的分钟数,其值是介于0与59之间的一个整数。\nserial_number:包含所求分钟数的时间。\n示例:\nMINUTE(\"15:36:25\")等于36。\nMINUTE(\"15:36:25\", \"HH:mm:ss\")等于36。", name: "MINUTE", type: "DATETIME"}, {def: "SIGN(number):返回数字的符号。当数字为正数时返回 1,为零时返回 0,为负数时返回 -1。\nNumber:为任意实数。\n示例:\nSIGN(10) 等于 1\nSIGN(4-4) 等于 0\nSIGN(-0.00001) 等于 -1\n", name: "SIGN", type: "MATH"}, {def: "INDEX(key,val1,val2,...):返回key在val1,val2,...所组成的序列中的位置,不存在于序列中则返回参数的个数.\n备注:\n key和valn可以是任意类型\n示例:\nINDEX(2,2)等于1。\nINDEX(2,1,2)等于2。\nINDEX(2,4,5,6)等于4。\nINDEX(\"b\",\"b\",\"o\",\"y\")等于1。", name: "INDEX", type: "OTHER"}, {def: "REVERSE(value):返回与value相反的逻辑值。\n示例:\nREVERSE(true)等于false。", name: "REVERSE", type: "LOGIC"}, {def: "REPLACE(text, texttoreplace, replacetext):根据指定字符串,用其他文本来代替原始文本中的内容。\ntext:需要被替换部分字符的文本或单元格引用。\ntexttoreplace:指定的字符串或正则表达式。\nreplacetext:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"abcd\", \"a\", \"re\")等于\"rebcd\"。\nREPLACE(\"a**d\", \"**d\", \"rose\")等于\"arose\"。\nREPLACE(old_text,start_num,num_chars,new_text): 根据指定的字符数,用其他文本串来替换某个文本串中的部分内容。\nOld_text:需要被替换部分字符的文本或单元格引用。\nStart_num:需要用new_text来替换old_text中字符的起始位置。\nNum_chars:需要用new_text来替换old_text中字符的个数。\nNew_text:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"0123456789\",5,4,\"*\")等于“0123*89”。\nREPLACE(\"1980\",3,2,\"99\")等于“1999”。", name: "REPLACE", type: "TEXT"}, {def: "UUID():返回随机的UUID。\n示例:UUID()返回36位随机机器数。\n UUID(32)返回32位随机机器数。", name: "UUID", type: "OTHER"}, {def: "DATESUBDATE(date1, date2, op):返回两个日期之间的时间差。\nop表示返回的时间单位:\n\"s\",以秒为单位。\n\"m\",以分钟为单位。\n\"h\",以小时为单位。\n\"d\",以天为单位。\n\"w\",以周为单位。\n示例:\nDATESUBDATE(\"2008-08-08\", \"2008-06-06\",\"h\")等于1512。", name: "DATESUBDATE", type: "DATETIME"}, {def: "CONCATENATE(text1,text2,...): 将数个字符串合并成一个字符串。\nText1,text2,...:需要合并成单个文本的文本项,可以是字符,数字或是单元格引用。\n示例:\nCONCATENATE(\"Average \",\"Price\")等于“Average Price”。\nCONCATENATE(\"1\",\"2\")等于12。", name: "CONCATENATE", type: "TEXT"}, {def: "filesize(file)获取文件的大小,单位为Kb。\n当file为单文件时,返回文件大小,当file为多文件时,返回文件大小的数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了两个大小分别为100字节和10240字节的文件,则filename(B2)返回值为[0.098, 10.0]。", name: "FILESIZE", type: "OTHER"}, {def: "DAYSOFMONTH(date):返回从1900年1月后某年某月包含的天数。\n示例:\nDAYSOFMONTH(\"1900-02-01\")等于28。\nDAYSOFMONTH(\"2008/04/04\")等于30。", name: "DAYSOFMONTH", type: "DATETIME"}, {def: "DATEINQUARTER(date, number): 函数返回在某一个季度当中第几天的日期。\n示例:\nDATEINQUARTER(\"2009-05-05\", 20)等于 2009-04-20。", name: "DATEINQUARTER", type: "DATETIME"}, {def: "逐层累计, =LAYERTOTAL(B1, C1, D1)等同于=D1[B1:-1] + C1, 如需横向, 则传递第四个参数false.如LAYERTOTAL(B1, C1, D1, false)", name: "LAYERTOTAL", type: "HA"}, {def: "CNMONEY(number,unit)返回人民币大写。\nnumber:需要转换的数值型的数。\nunit:单位,\"s\",\"b\",\"q\",\"w\",\"sw\",\"bw\",\"qw\",\"y\",\"sy\",\"by\",\"qy\",\"wy\"分别代表“拾”,“佰”,“仟”,“万”,“拾万”,“佰万”,“仟万”,“亿”,“拾亿”,“佰亿”,“仟亿”,“万亿”。\n备注:\n 单位可以为空,如果为空,则直接将number转换为人民币大写,否则先将number与单位的进制相乘,然后再将相乘的结果转换为人民币大写。\n示例:\nCNMONEY(1200)等于壹仟贰佰圆整。\nCNMONEY(12.5,\"w\")等于壹拾贰万伍仟圆整。\nCNMONEY(56.3478,\"bw\")等于伍仟陆佰叁拾肆万柒仟捌佰圆整。\nCNMONEY(3.4567,\"y\")等于叁亿肆仟伍佰陆拾柒万圆整。", name: "CNMONEY", type: "TEXT"}, {def: "DAYVALUE(date):返回1900年至 date日期所经历的天数。\n示例:\nDAYVALUE(\"2008/08/08\")等于39668。", name: "DAYVALUE", type: "DATETIME"}, {def: "SQL(connectionName,sql,columnIndex,rowIndex)返回通过sql语句从connectionName中获得数据表的第columnIndex列第rowIndex行所对应的元素。\nconnectionName:数据库库的名字,字符串形式;\nsql:SQL语句,字符串形式;\ncolumnIndex:列序号,整形;\nrowIndex:行序号,整形。\n备注:行序号可以不写,这样返回值为数据列。\n示例:\n以我们提供的数据源HSQL为例\nSQL(\"HSQL\",\"SELECT * FROM CUSTOMER\",2,2)等于王先生。", name: "SQL", type: "REPORT"}, {def: "DATE(year,month,day): 返回一个表示某一特定日期的系列数。\nYear:代表年,可为一到四位数。\nMonth:代表月份。\n若1 month 12,则函数把参数值作为月。\n若month>12,则函数从年的一月份开始往上累加。例如: DATE(2000,25,2)等于2002年1月2日的系列数。\nDay:代表日。\n若日期小于等于某指定月的天数,则函数将此参数值作为日。\n若日期大于某指定月的天数,则函数从指定月份的第一天开始往上累加。若日期大于两个或多个月的总天数,则函数把减去两个月或多个月的余数加到第三或第四个月上,依此类推。例如:DATE(2000,3,35)等于2000年4月4日的系列数。\n备注:\n 若需要处理公式中日期的一部分,如年或月等,则可用此公式。\n 若年,月和日是函数而不是函数中的常量,则此公式最能体现其作用。\n示例:\nDATE(1978, 9, 19) 等于1978-09-19.\nDATE(1211, 12, 1) 等于1211-12-01. ", name: "DATE", type: "DATETIME"}, {def: "BITOPERATIOIN(int,int,op) 位运算,返回两个整数根据op进行位运算后的结果。\nint:十进制整数。\nop:位运算操作符,支持\"&\"(与),\"|\"(或),\"^\"(异或),\"<<\"(左移),\">>\"(右移)。\n示例:\nBITOPERATION(4,2,\"&\")表示4与2进行\"与\"运算,结果等于0。\nBITOPERATION(4,2,\"|\")表示4与2进行\"或\"运算,结果等于6。\nBITOPERATION(4,2,\"^\")表示4与2进行\"异或\"运算,结果等于6。\nBITOPERATION(4,2,\"<<\")表示4按位左移2位,结果等于16。\nBITOPERATION(4,2,\">>\")表示4按位右移2位,结果等于1。\nBITOPERATION(4,2,\"^~\")表示4与2进行\"同或\"运算,结果为-7。", name: "BITOPERATION", type: "LOGIC"}, {def: "LOWER(text): 将所有的大写字母转化为小写字母。\nText:需要转化为小写字母的文本串。LOWER函数不转化文本串中非字母的字符。\n示例:\nLOWER(\"A.M.10:30\")等于“a.m.10:30”。\nLOWER(\"China\")等于“china”。", name: "LOWER", type: "TEXT"}, {def: "CEILING(number): 将参数number沿绝对值增大的方向,舍入为最接近的整数\nNumber:指待舍入的数值。\nCEILING(-2.5)等于-3。\nCEILING(0.5)等于1。", name: "CEILING", type: "MATH"}, {def: "SINH(number):返回某一数字的双曲正弦值。\nnumber:为任意实数。\n示例:\nSINH(1) 等于 1.175201194\nSINH(-1) 等于 -1.175201194", name: "SINH", type: "MATH"}, {def: "AND(logical1,logical2,…): 当所有参数的值为真时,返回TRUE;当任意参数的值为假时,返回FALSE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nAND(1+7=8,5+7=12)等于TRUE。\nAND(1+7=8,5+7=11)等于FALSE。\n如果单元格A1到A4的值分别为TRUE、TRUE、FALSE和TRUE,则:\nAND(A1:A4)等于FALSE。\n如果单元格A5的值在0~50之间,则: AND(0 $A1}) + 1, 默认升序排列, 如需要降序, 则传递参数false,\n =SORT(A1, false)等同于=COUNT(A1[!0]{A1 < $A1}) + 1.", name: "SORT", type: "HA"}, {def: "SIN(number): 计算给定角度的正弦值。\nNumber:待求正弦值的以弧度表示的角度。\n备注:\n 如果参数的单位是度,将其乘以PI()/180即可转换成弧度。\n示例:\nSIN(10)等于-0.5440211108893698。\nSIN(45*PI()/180)等于0.707106781。", name: "SIN", type: "MATH"}, {def: "switch(表达式, 值1, 结果1, 值2, 结果2, ...)\n如果表达式的结果是值1,整个函数返回结果1\n如果表达式的结果是值2,整个函数返回结果2\n如果表达式的结果是值3,整个函数返回结果3\n等等\n", name: "SWITCH", type: "LOGIC"}, {def: "ROW()返回当前单元格的行号,必须使用于条件属性中\n示例:\n如果当前单元格为A5,在A5中写入\"=ROW()\"则返回5。\n如果当前单元格为B8,在B8中写入\"=ROW()\"则返回8。", name: "ROW", type: "REPORT"}, {def: "EVAL(exp)返回表达式exp计算后的结果。\nexp:一个表达式形式字符串。\n备注:\n 只要EVAL中的参数exp最终可以转化成一表达式形式的字符串,比如\"sum(2,4)\",\"2+7\"等等,那么它就可以被计算。\nEVAL(\"2+5\")等于7。\nEVAL(\"count(2,3)\")等于2。\nEVAL(\"sum\"+\"(2,3,5)\")等于10。\nEVAL(IF(true, \"sum\", \"count\") + \"(1,2,3,4)\")等于10。\nEVAL(IF(false, \"sum\", \"count\") + \"(1,2,3,4)\")等于4。", name: "EVAL", type: "OTHER"}, {def: "ATAN(number): 计算指定数值的反正切值。指定数值是返回角度的正切值,返回角度以弧度形式表示。\nNumber:返回角度的正切。\n备注:\n 返回角度在-pi/2到pi/2之间。\n 如果返回角度等于-pi/2或pi/2,ATAN将返回错误信息*NUM!。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nATAN(-1)等于-0.785398163(-pi/4弧度)。\nATAN(0)等于0(弧度)。\nATAN(2)*180/PI()等于63.43494882(度)。", name: "ATAN", type: "MATH"}, {def: "RANGE(from,to,step)函数表示从整数from开始,以step为每一步的大小,直到整数to的一个数字序列。\n例如:\nRANGE(1,5,1)表示从1开始,直到5(包括5),每一步大小为1,那么它返回一个数字序列为[1,2,3,4,5]。\nRANGE(-1,6,2)表示从-1开始,直到6(包括6),每一步大小为2,那么它返回一个数字序列为[-1,1,3,5]。\n备注:RANGE函数有三种参数形式:\n1 RANGE(to),默认的from为1,step为1,例如:\n RANGE(4)返回[1,2,3,4]。\n RANGE(-5)返回[]。\n2 RANGE(from,to),默认的step为1,例如:\n RANGE(-1,3)返回[-1,0,1,2,3]。\n RANGE(0,5)返回[0,1,2,3,4,5]。\n3 RANGE(from,to,step),三个参数的情况参照上面的注释,例如:\n RANGE(6,-1,-2)返回[6,4,2,0]。\n RANGE(4,1,1)返回[]。", name: "RANGE", type: "ARRAY"}, {def: "TANH(number):返回某一数字的双曲正切值。\nnumber:为任意实数。\n双曲正切的计算公式如下:\n示例:\nTANH(-2) 等于 -0.96403\nTANH(0) 等于 0\nTANH(0.5) 等于 0.462117\n", name: "TANH", type: "MATH"}, {def: "ROUNDDOWN(number,num_digits):靠近零值,向下(绝对值减小的方向)舍入数字。\nnumber:为需要向下舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDDOWN 和函数 ROUND 功能相似,不同之处在于函数 ROUNDDOWN 总是向下舍入数字。\n示例:\nROUNDDOWN(3.2, 0) 等于 3\nROUNDDOWN(76.9,0) 等于 76\nROUNDDOWN(3.14159, 3) 等于 3.141\nROUNDDOWN(-3.14159, 1) 等于 -3.1\nROUNDDOWN(31415.92654, -2) 等于 31,400\n", name: "ROUNDDOWN", type: "MATH"}, {def: "循环引用, =CIRCULAR(A1, B1, C1, D1)等同于=IF(&A1 = 1, 0, B1[A1:-1] + C1[A1:-1] – D1[A1:-1]),如需横向, 则传递第五个参数false", name: "CIRCULAR", type: "HA"}, {def: "HOUR(serial_number):返回某一指定时间的小时数。函数指定HOUR为0(0:00)到23(23:00)之间的一个整数。\nSerial_number:包含所求小时的时间。\n示例:\nHOUR(\"11:32:40\")等于11。\nHOUR(\"11:32:40\", \"HH:mm:ss\")等于11。", name: "HOUR", type: "DATETIME"}, {def: "ROUND(number,num_digits):返回某个数字按指定位数舍入后的数字。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND(2.15, 1) 等于 2.2\nROUND(2.149, 1) 等于 2.1\nROUND(-1.475, 2) 等于 -1.48\nROUND(21.5, -1) 等于 20\n因浮点数存在精度计算丢失问题, 导致计算结果里可能带上9999, 0000这些, \n因此加入第三个参数来控制是否需要去除9999. true表示需要过滤9999, 0000这些数据.", name: "ROUND", type: "MATH"}, {def: "YEARDELTA(date, delta):返回指定日期后delta年的日期。\n示例:\nYEARDELTA(\"2008-10-10\",10)等于2018-10-10。", name: "YEARDELTA", type: "DATETIME"}, {def: "DATEINYEAR(date, number):函数返回在一年当中第几天的日期。\n示例:\nDATEINYEAR(2008,100)等于2008-04-09,等价于DATEINYEAR(\"2008-08-08\",100),也返回2008-04-09.\nDATEINYEAR(2008,-1)等于2008-12-31,等价于DATEINYEAR(\"2008-08-08\",-1),也返回2008-12-31.", name: "DATEINYEAR", type: "DATETIME"}, {def: "WEIGHTEDAVERAGE(A1:A4,B1:B4): 返回指定数据的加权平均值。\n加权平均数是不同比重数据的平均数,加权平均数就是把原始数据按照合理的比例来计算。\nA1:A4,B1:B4:用于计算平均值的参数,A1~A4为数据,B1~B4为权值。\n示例:\n如果A1:A4为10,9,8,7,B1:B4为0.2,0.1,0.3,0.4则:\nWEIGHTEDAVERAGE(A1:A4,B1:B4)等于8.1。", name: "WEIGHTEDAVERAGE", type: "MATH"}, {def: "ASIN(number): 返回指定数值的反正弦值。反正弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的正弦值。\n备注:\n 指定数值必须在-1到1之间(含1与-1)。\n 返回角度在-pi/2到pi/2之间(含-pi/2与pi/2)。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nASIN(0.5)等于0.523598776(pi/6弧度)。\nASIN(1)等于1.570796327(pi/2弧度)。\nASIN(0.5)*180/PI()等于30(度)。", name: "ASIN", type: "MATH"}, {def: "INT(number): 返回数字下舍入(数值减小的方向)后最接近的整数值。\nNumber:需要下舍入为整数的实数。\n示例:\nINT(4.8)等于4。\nINT(-4.8)等于-5。\nINT(4.3)等于4。\nINT(-4.3)等于-5。\n公式INT(A1)将返回A1单元格中的一个正实数的整数数部分。", name: "INT", type: "MATH"}, {def: "GETUSERJOBTITLES():返回角色职务\n示例:\nGETUSERDEPARTMENTS():返回角色所有职务,若多个部门职务则返回职务数组", name: "GETUSERJOBTITLES", type: "OTHER"}, {def: "REGEXP(str, pattern):字符串str是否与正则表达式pattern相匹配。\n示例:\nREGEXP(\"aaaaac\",\"a*c\")等于true。\nREGEXP(\"abc\",\"a*c\")等于false。\n\nREGEXP(str, pattern, intNumber):字符串str是否与具有给定模式 intNumber的正则表达式pattern相匹配。\n示例:\nCASE_INSENSITIVE = 0 启用不区分大小写的匹配。 默认情况下,不区分大小写的匹配假定仅匹配 US-ASCII 字符集中的字符。可以通过指 定 UNICODE_CASE 标志连同此标志来启用 Unicode 感知的、不区分大小写的匹配。 \nMULTILINE = 1 启用多行模式。\nDOTALL = 2 启用 dotall 模式。在 dotall 模式中,表达式 . 可以匹配任何字符,包括行结束符。默认情况下,此表达式不匹配行 结束符。\nUNICODE_CASE = 3 启用 Unicode 感知的大小写折叠。指定此标志后,由 CASE_INSENSITIVE 标志启用时,不区分大小写的匹配将以 符合 Unicode Standard 的方式完成。\nCANON_EQ = 4 启用规范等价。 指定此标志后,当且仅当其完整规范分解匹配时,两个字符才可视为匹配。\nUNIX_LINES = 5 启用 Unix 行模式。 在此模式中,.、^ 和 $ 的行为中仅识别 '\\n' 行结束符。\nLITERAL = 6 启用模式的字面值解析。 指定此标志后,指定模式的输入字符串就会作为字面值字符序列来对待。输入序列中的 元字符或转义序列不具有任何特殊意义。 标志 CASE_INSENSITIVE 和 UNICODE_CASE 在与此标志一起使用时将 对匹配产生影响。其他标志都变得多余了。\nCOMMENTS = 7 模式中允许空白和注释。 此模式将忽略空白和在结束行之前以 # 开头的嵌入式注释。\n \nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 3)等于true。\nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 1)等于false。\n\n", name: "REGEXP", type: "TEXT"}, {def: "DAYSOFQUARTER(date): 返回从1900年1月后某年某季度的天数。\n示例:\nDAYSOFQUARTER(\"2009-02-01\")等于90。\nDAYSOFQUARTER(\"2009/05/05\")等于91。", name: "DAYSOFQUARTER", type: "DATETIME"}, {def: "AVERAGE(number1,number2,…,countstring): 返回指定数据的平均值。\nNumber1,number2…:用于计算平均值的参数; countString:文字、逻辑值是否参与计数。\n备注:\n 参数必须是数字,或是含有数字的名称,数组或引用。\n 如果数组或引用参数中含有文字,逻辑值,默认参与计数,countString为false则不参与计数;\n 空单元格始终不参与计数,但是,单元格中的零值参与。\n示例:\n如果A1:A6被命名为“ages”,分别等于10,23,文字,29,33及25,则:\nAVERAGE(A1:A6)等于20。\nAVERAGE(A1:A6, false)等于24。\nAVERAGE(ages)等于20。\n如果还有一个年龄为27的,求所有年龄的平均值为: AVERAGE(A1:A6,27)等于21。", name: "AVERAGE", type: "MATH"}, {def: "RADIANS(angle): 将角度转换成弧度。\nAngle:需要转换为弧度的角度。\n示例:\nRADIANS(90)等于1.570796327(π/2弧度)。", name: "RADIANS", type: "MATH"}, {def: "REMOVEARRAY(array, start, deleteCount):从数组array中删除从第start个元素开始的deleteCount个数组元素,并返回删除后的数组。\n示例:\nREMOVEARRAY([3, 4, 4, 2, 6, 7, 87], 4, 2)返回[3, 4, 4, 7, 87].\n", name: "REMOVEARRAY", type: "ARRAY"}, {def: "WEBIMAGE(path):在web页面上显示指定路径下的图片。", name: "WEBIMAGE", type: "OTHER"}, {def: "WEEK(serial_num):返回一个代表一年中的第几周的数字。\nSerial_num:表示输入的日期。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nWEEK(\"2010/1/1\")等于52。\nWEEK(\"2010/1/6\")等于1。\nWEEK(35796)等于1。", name: "WEEK", type: "DATETIME"}, {def: "filename(file)获取文件的文件名。\n当file为单文件时,返回文件名字符串,当file为多文件时,返回文件名的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.cpt },则filename(B2)返回值为[“A.doc”, “C.xls”, “B.cpt”]。", name: "FILENAME", type: "OTHER"}, {def: "COSH(number): 返回一个数值的双曲线余弦值。\nNumber:需要求其双曲线余弦值的一个实数。\n备注:\n 双曲线余弦值计算公式为: ,其中e是自然对数的底,e=2.71828182845904。\n示例:\nCOSH(3)等于10.06766200。\nCOSH(5)等于74.20994852。\nCOSH(6)等于201.7156361。", name: "COSH", type: "MATH"}, {def: "WEEKDAY(Serial_number):获取日期并返回星期数。返回值为介于0到6之间的某一整数,分别代表星期中的某一天(从星期日到星期六)。\nSerial_number:输入的日期\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n举例:\nWEEKDAY(\"2005/9/10\")等于6(星期六)。\nWEEKDAY(\"2005/9/11\")等于0(星期日)。\nWEEKDAY(35796)等于4(星期四)。\n", name: "WEEKDAY", type: "DATETIME"}, {def: "OR(logical1,logical2,…): 当所有参数的值为假时,返回FALSE;当任意参数的值为真时,返回TRUE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nOR(1+7=9,5+7=11)等于FALSE。\nOR(1+7=8,5+7=11)等于TRUE。", name: "OR", type: "LOGIC"}, {def: "MOD(number,divisor):返回两数相除的余数。结果的正负号与除数相同。\nnumber:为被除数。\ndivisor:为除数。\n示例:\nMOD(3, 2) 等于 1\nMOD(-3, 2) 等于 1\nMOD(3, -2) 等于 -1\nMOD(-3, -2) 等于 -1\n", name: "MOD", type: "MATH"}, {def: "TODAY():获取当前日期。\n示例:\n如果系统日期是2005年9月10日\n则TODAY()等于2005-9-10。", name: "TODAY", type: "DATETIME"}, {def: "ROUNDUP(number,num_digits):远离零值,向上(绝对值增大的方向)舍入数字。\nnumber:为需要向上舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDUP 和函数 ROUND 功能相似,不同之处在于函数 ROUNDUP 总是向上舍入数字。\n示例:\nROUNDUP(3.2,0) 等于 4\nROUNDUP(76.9,0) 等于 77\nROUNDUP(3.14159, 3) 等于 3.142\nROUNDUP(-3.14159, 1) 等于 -3.2\nROUNDUP(31415.92654, -2) 等于 31,500\n\n", name: "ROUNDUP", type: "MATH"}, {def: "ROUND5(number,num_digits):这个是四舍五入,奇进偶不进。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND5(2.125, 2) 等于 2.12\nROUND5(2.135, 2) 等于 2.14\n", name: "ROUND5", type: "MATH"}, {def: "TIME(hour,minute,second): 返回代表指定时间的小数。介于0:00:00(12:00:00 A.M.)与23:59:59(11:59:59 P.M.)之间的时间可返回0到0.99999999之间的对应数值。\nHour:介于0到23之间的数。\nMinute:介于0到59之间的数。\nSecond:介于0到59之间的数。\n示例:\nTIME(14,40,0)等于2:40 PM。\nTIME(19,43,24)等于7:43 PM。", name: "TIME", type: "DATETIME"}, {def: "环比公式, =MOM(A1, B1)等同于=IF(&A1 > 1, B1 / B1[A1:-1],0), 其中如果需要指定偏移量x, 则传递第三个参数x, 第四个参数表示横纵向.\n如=MOM(A1, B1, -2, false)等同于=IF(&A1 > 1, B1 / B1[;A1:-2], 0)", name: "MOM", type: "HA"}, {def: "ASINH(number): 返回指定数值的反双曲正弦值。反双曲正弦值的双曲正弦等于指定数值。即: ASINH(SINH(number))=number。\nNumber:任意实数。\n示例:\nASINH(-5)等于-2.312438341。\nASINH(8)等于2.776472281。\nASINH(16)等于3.466711038。", name: "ASINH", type: "MATH"}, {def: "EENNUMBER(value):将给定的BigDecimal类型的数字(100以内)取整后转化成英文金额的字符串。\n示例:\nENNUMBER(23.49)等于TWENTY THREE。\n注:若出现结果为空,需要将数字强制转换为BigDecimal类型,例如:ENNUMBER(TOBIGDECIMAL(80))", name: "ENNUMBER", type: "TEXT"}, {def: "CODE(text): 计算文本串中第一个字符的数字代码。返回的代码对应于计算机使用的字符集。\nText:需要计算第一个字符代码的文本或单元格引用。\n示例:\nCODE(\"S\")等于83。\nCODE(\"Spreadsheet\")等于83。", name: "CODE", type: "TEXT"}, {def: "DEGREES(angle): 将弧度转化为度。\nangle:待转换的弧度角。\n示例:\nDEGREES(PI()/2)等于90。\nDEGREES(3.1415926)等于179.9999969。", name: "DEGREES", type: "MATH"}, {def: "LEN(args): 返回文本串中的字符数或者数组的长度。\n需要注意的是:参数args为文本串时,空格也计为字符。\n参数args为数组时,直接返回数组长度。\n示例:\nLEN(\"Evermore software\")等于17。\nLEN(\" \")等于1。\nLEN(['a','b'])等于2。\n", name: "LEN", type: "TEXT"}, {def: "DATETIME():获取当前日期和时间。\n示例:\n如果系统时间是2005年9月10日 15点18分38秒\n则DATETIME()等于2005-9-10 15:18:36。", name: "DATETIME", type: "DELETE"}, {def: "UNIQUEARRAY(array):去掉数组array中的重复元素。\n示例:\nUNIQUEARRAY([14, 2, 3, 4, 3, 2, 5, 6, 2, 7, 9, 12, 3])返回[14, 2, 3, 4, 5, 6, 7, 9, 12].", name: "UNIQUEARRAY", type: "ARRAY"}, {def: "PROMOTION(value1,value2):返回value2在value1上提升的比例。\n示例:\nPROMOTION(12, 14)等于0.166666666,即提升了16.6666666%.\nPROMOTION(-12, 14)等于2.166666666,即提升了216.6666666%.", name: "PROMOTION", type: "MATH"}, {def: "PI(number): 是一个数学常量函数,当number为空时,函数返回精确到15位的数值3.141592653589793;当参数不为空时,number表示PI的倍数。\n示例:\nSIN(PI()/2)等于1。\n计算圆的面积的公式: S=PI()*(r^2),其中S为圆的面积,R为圆的半径。\nPI(3)等于9.42477796076938。", name: "PI", type: "MATH"}, {def: "ISNULL(object):判断对象中所有的值是否全部都是NULL或者为空字符串。", name: "ISNULL", type: "OTHER"}, {def: "LET(变量名,变量值,变量名,变量值,..., 表达式):局部变量赋值函数,参数的个数N必须为奇数, 最后一个是表达式,前面是N-1(偶数)为局部变量赋值对。\n变量名: 必须是合法的变量名,以字母开头,可以包括字母,数字和下划线\n表达式: 根据前面的N-1个参数赋值后计算出来的结果,这些变量赋值只在这个表达式内部有效\n示例:\nLET(a, 5,b, 6, a+b)等于11\n", name: "LET", type: "OTHER"}, {def: "SECOND(serial_number):返回某一指定时间的秒数,其值是介于0与59之间的一个整数。\nSerial_number:包含所求秒数的时间。\n示例:\nSECOND(\"15:36:25\")等于25。\nSECOND(\"15:36:25\", \"HH:mm:ss\")等于25。", name: "SECOND", type: "DATETIME"}, {def: "EXP(number): 返回e的n次幂。常数e为自然对数的底数,等于2.71828182845904。\nNumber:为任意实数,作为常数e的指数。\n备注:\n 如果要返回其他常数作为底数的幂,可以使用指数运算符(^)。例如: 在4^2中,4是底数,而2是指数。\n EXP函数与LN函数互为反函数。\n示例:\nEXP(0)等于1。\nEXP(3)等于20.08553692。\nEXP(LN(2))等于2。", name: "EXP", type: "MATH"}, {def: "treelayer(TreeObject, Int, Boolean, String):\n返回tree对象第n层的值,并且可以设置返回值类型及分隔符。\nTreeObject:tree对象,如$tree。\nInt:想要获得层级的数值,最上层为1,第二层为2,依此类推,若无则返回最底层\n。Boolean:返回值类型为字符串还是数组,默认false,返回数组;为true时返回字符串。\nString:当Boolean为true返回字符串时的分隔符,以双引号表示,默认为逗号\",\",如\";\"。\n示例:\n假设$tree勾选的值为中国-江苏-南京,中国-浙江-杭州,则treelayer($tree, true, ”\\’,\\’”):返回”’,’”分割的所选中节点字符串”南京’,’杭州”treelayer($tree, 2):以数组形式返回第二层[“江苏”,”浙江”]。treelayer($tree, 2, true, ”\\’,\\’”):返回”’,’”分割的字符串江苏’,’浙江。", name: "TREELAYER", type: "OTHER"}, {def: "读取配置文件", name: "TOTEXT", type: "DELETE"}]; /** * 当没有元素时有提示信息的view * @@ -221,7 +221,7 @@ BI.Pane = BI.inherit(BI.Widget, { tipText: BI.i18nText("BI-No_Selected_Item"), overlap: true, onLoaded: BI.emptyFn - }) + }); }, _init: function () { @@ -251,7 +251,7 @@ BI.Pane = BI.inherit(BI.Widget, { if (o.overlap === true) { if (!BI.Layers.has(this.getName())) { BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", items: [{ el: { type: "bi.layout", @@ -279,7 +279,7 @@ BI.Pane = BI.inherit(BI.Widget, { right: 0, top: 0 }] - }) + }); } }, @@ -335,7 +335,7 @@ BI.Single = BI.inherit(BI.Widget, { warningTitle: null, tipType: null, // success或warning value: null - }) + }); }, _showToolTip: function (e, opt) { @@ -404,7 +404,7 @@ BI.Single = BI.inherit(BI.Widget, { }, disabledHover: function () { - //取消hover事件 + // 取消hover事件 if (BI.isNotNull(this.timeout)) { clearTimeout(this.timeout); } @@ -419,7 +419,7 @@ BI.Single = BI.inherit(BI.Widget, { this.items = items || []; }, - //opt: {container: '', belowMouse: false} + // opt: {container: '', belowMouse: false} setTitle: function (title, opt) { this.options.title = title; if (BI.isKey(title)) { @@ -484,7 +484,7 @@ BI.Text = BI.inherit(BI.Single, { textAlign: "left", whiteSpace: "normal", lineHeight: null, - handler: null,//如果传入handler,表示处理文字的点击事件,不是区域的 + handler: null, // 如果传入handler,表示处理文字的点击事件,不是区域的 hgap: 0, vgap: 0, lgap: 0, @@ -493,7 +493,7 @@ BI.Text = BI.inherit(BI.Single, { bgap: 0, text: "", py: "" - }) + }); }, _init: function () { @@ -502,37 +502,37 @@ BI.Text = BI.inherit(BI.Single, { if (o.hgap + o.lgap > 0) { this.element.css({ "padding-left": o.hgap + o.lgap + "px" - }) + }); } if (o.hgap + o.rgap > 0) { this.element.css({ "padding-right": o.hgap + o.rgap + "px" - }) + }); } if (o.vgap + o.tgap > 0) { this.element.css({ "padding-top": o.vgap + o.tgap + "px" - }) + }); } if (o.vgap + o.bgap > 0) { this.element.css({ "padding-bottom": o.vgap + o.bgap + "px" - }) + }); } if (BI.isNumber(o.height)) { - this.element.css({"lineHeight": o.height + "px"}); + this.element.css({lineHeight: o.height + "px"}); } if (BI.isNumber(o.lineHeight)) { - this.element.css({"lineHeight": o.lineHeight + "px"}); + this.element.css({lineHeight: o.lineHeight + "px"}); } this.element.css({ - "textAlign": o.textAlign, - "whiteSpace": o.whiteSpace + textAlign: o.textAlign, + whiteSpace: o.whiteSpace }); if (o.handler) { this.text = BI.createWidget({ type: "bi.layout", - tagName: 'span' + tagName: "span" }); this.text.element.click(function () { o.handler(self.getValue()); @@ -581,7 +581,7 @@ BI.Text = BI.inherit(BI.Single, { }, setStyle: function (css) { - this.text.element.css(css) + this.text.element.css(css); }, setText: function (text) { @@ -608,16 +608,16 @@ BI.BasicButton = BI.inherit(BI.Single, { stopEvent: false, stopPropagation: false, selected: false, - once: false, //点击一次选中有效,再点无效 - forceSelected: false, //点击即选中, 选中了就不会被取消,与once的区别是forceSelected不影响事件的触发 - forceNotSelected: false, //无论怎么点击都不会被选中 - disableSelected: false, //使能选中 + once: false, // 点击一次选中有效,再点无效 + forceSelected: false, // 点击即选中, 选中了就不会被取消,与once的区别是forceSelected不影响事件的触发 + forceNotSelected: false, // 无论怎么点击都不会被选中 + disableSelected: false, // 使能选中 shadow: false, - isShadowShowingOnSelected: false, //选中状态下是否显示阴影 + isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 trigger: null, handler: BI.emptyFn - }) + }); }, _init: function () { BI.BasicButton.superclass._init.apply(this, arguments); @@ -788,10 +788,10 @@ BI.BasicButton = BI.inherit(BI.Single, { } }); - //之后的300ms点击无效 + // 之后的300ms点击无效 var onClick = BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, true); - function ev(e) { + function ev (e) { if (o.stopEvent) { e.stopEvent(); } @@ -800,7 +800,7 @@ BI.BasicButton = BI.inherit(BI.Single, { } } - function clk(e) { + function clk (e) { ev(e); if (!self.isEnabled() || (self.isOnce() && self.isSelected())) { return; @@ -941,47 +941,47 @@ BI.BasicButton.EVENT_CHANGE = "BasicButton.EVENT_CHANGE";/** * @abstract */ BI.NodeButton = BI.inherit(BI.BasicButton, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.NodeButton.superclass._defaultConfig.apply(this, arguments); return BI.extend( conf, { baseCls: (conf.baseCls || "") + " bi-node", open: false - }) + }); }, - _init:function() { + _init: function () { BI.NodeButton.superclass._init.apply(this, arguments); var self = this; - BI.nextTick(function(){ + BI.nextTick(function () { self.setOpened(self.isOpened()); - }) + }); }, - doClick: function(){ + doClick: function () { BI.NodeButton.superclass.doClick.apply(this, arguments); this.setOpened(!this.isOpened()); }, - isOnce: function(){ + isOnce: function () { return false; }, - isOpened: function(){ + isOpened: function () { return !!this.options.open; }, - setOpened: function(b){ + setOpened: function (b) { this.options.open = !!b; }, - triggerCollapse: function(){ + triggerCollapse: function () { if(this.isOpened()) { this.setOpened(false); this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, this.getValue(), this); } }, - triggerExpand: function(){ + triggerExpand: function () { if(!this.isOpened()) { this.setOpened(true); this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, this.getValue(), this); @@ -996,17 +996,17 @@ BI.NodeButton = BI.inherit(BI.BasicButton, { * @abstract */ BI.Tip = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Link.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-tip", zIndex: BI.zIndex_tip - }) + }); }, - _init : function() { + _init: function () { BI.Tip.superclass._init.apply(this, arguments); - this.element.css({"zIndex": this.options.zIndex}); + this.element.css({zIndex: this.options.zIndex}); } });/** * Created by GUY on 2015/6/26. @@ -1026,7 +1026,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { hgap: 0, vgap: 0 }] - }) + }); }, _init: function () { @@ -1035,7 +1035,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { BI.each(this.options.behaviors, function (key, rule) { behaviors[key] = BI.BehaviorFactory.createBehavior(key, { rule: rule - }) + }); }); this.behaviors = behaviors; this.populate(this.options.items); @@ -1075,7 +1075,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { }); btn.on(BI.Events.DESTROY, function () { BI.remove(self.buttons, btn); - }) + }); }); return buttons; @@ -1091,8 +1091,8 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { el: it }) ] - }) - }) + }); + }); } return btns; }, @@ -1105,8 +1105,8 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { } return BI.extend({}, item, { el: btns[i] - }) - }) + }); + }); }, _packageItems: function (items, packBtns) { @@ -1124,10 +1124,10 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { return layout; }, - //如果是一个简单的layout + // 如果是一个简单的layout _isSimpleLayout: function () { var o = this.options; - return o.layouts.length === 1 && !BI.isArray(o.items[0]) + return o.layouts.length === 1 && !BI.isArray(o.items[0]); }, doBehavior: function () { @@ -1135,7 +1135,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { args.unshift(this.buttons); BI.each(this.behaviors, function (i, behavior) { behavior.doBehavior.apply(behavior, args); - }) + }); }, prependItems: function (items) { @@ -1157,7 +1157,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { var btns = this._btnsCreator.apply(this, arguments); this.buttons = BI.concat(this.buttons, btns); - //如果是一个简单的layout + // 如果是一个简单的layout if (this._isSimpleLayout() && this.layouts && this.layouts.addItems) { this.layouts.addItems(btns); return; @@ -1342,7 +1342,7 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { _defaultConfig: function () { return BI.extend(BI.ButtonTree.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-button-tree" - }) + }); }, _init: function () { @@ -1450,7 +1450,7 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { return btns; }, - //获取所有的叶子节点 + // 获取所有的叶子节点 getAllLeaves: function () { var leaves = []; BI.each(this.buttons, function (i, item) { @@ -1525,7 +1525,7 @@ BI.TreeView = BI.inherit(BI.Pane, { baseCls: "bi-tree", paras: {}, itemsCreator: BI.emptyFn - }) + }); }, _init: function () { BI.TreeView.superclass._init.apply(this, arguments); @@ -1566,13 +1566,13 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //选择节点触发方法 + // 选择节点触发方法 _selectTreeNode: function (treeId, treeNode) { this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, treeNode, this); this.fireEvent(BI.TreeView.EVENT_CHANGE, treeNode, this); }, - //配置属性 + // 配置属性 _configSetting: function () { var paras = this.options.paras; var self = this; @@ -1614,11 +1614,11 @@ BI.TreeView = BI.inherit(BI.Pane, { }; var className = "dark", perTime = 100; - function onClick(event, treeId, treeNode) { + function onClick (event, treeId, treeNode) { self.nodes.checkNode(treeNode, !treeNode.checked, true, true); } - function getUrl(treeId, treeNode) { + function getUrl (treeId, treeNode) { var parentNode = self._getParentValues(treeNode); treeNode.times = treeNode.times || 1; var param = "id=" + treeNode.id @@ -1626,23 +1626,23 @@ BI.TreeView = BI.inherit(BI.Pane, { + "&parentValues= " + window.encodeURIComponent(BI.jsonEncode(parentNode)) + "&checkState=" + window.encodeURIComponent(BI.jsonEncode(treeNode.getCheckStatus())); - return BI.servletURL + '?op=' + self.options.op + '&cmd=' + self.options.cmd + "&" + param; + return BI.servletURL + "?op=" + self.options.op + "&cmd=" + self.options.cmd + "&" + param; } - function beforeExpand(treeId, treeNode) { + function beforeExpand (treeId, treeNode) { if (!treeNode.isAjaxing) { if (!treeNode.children) { treeNode.times = 1; ajaxGetNodes(treeNode, "refresh"); } return true; - } else { - BI.Msg.toast("Please Wait。", "warning"); - return false; } + BI.Msg.toast("Please Wait。", "warning"); + return false; + } - function onAsyncSuccess(event, treeId, treeNode, msg) { + function onAsyncSuccess (event, treeId, treeNode, msg) { treeNode.halfCheck = false; if (!msg || msg.length === 0 || /^[\s,\S]*<\/html>$/gi.test(msg) || self._stop) { return; @@ -1650,7 +1650,7 @@ BI.TreeView = BI.inherit(BI.Pane, { var zTree = self.nodes; var totalCount = treeNode.count || 0; - //尝试去获取下一组节点,若获取值为空数组,表示获取完成 + // 尝试去获取下一组节点,若获取值为空数组,表示获取完成 // TODO by GUY if (treeNode.children.length > totalCount) { treeNode.count = treeNode.children.length; @@ -1658,41 +1658,41 @@ BI.TreeView = BI.inherit(BI.Pane, { ajaxGetNodes(treeNode); }, perTime); } else { - //treeNode.icon = ""; + // treeNode.icon = ""; zTree.updateNode(treeNode); zTree.selectNode(treeNode.children[0]); - //className = (className === "dark" ? "":"dark"); + // className = (className === "dark" ? "":"dark"); } } - function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { + function onAsyncError (event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { var zTree = self.nodes; BI.Msg.toast("Error!", "warning"); - //treeNode.icon = ""; - //zTree.updateNode(treeNode); + // treeNode.icon = ""; + // zTree.updateNode(treeNode); } - function ajaxGetNodes(treeNode, reloadType) { + function ajaxGetNodes (treeNode, reloadType) { var zTree = self.nodes; if (reloadType == "refresh") { - //treeNode.icon = BI.servletURL +"?op=resource&resource=/com/fr/bi/web/css/base/third/ztree/img/loading.gif"; + // treeNode.icon = BI.servletURL +"?op=resource&resource=/com/fr/bi/web/css/base/third/ztree/img/loading.gif"; zTree.updateNode(treeNode); } zTree.reAsyncChildNodes(treeNode, reloadType, true); } - function beforeCheck(treeId, treeNode) { + function beforeCheck (treeId, treeNode) { treeNode.halfCheck = false; if (treeNode.checked === true) { - //将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy - //所有的半选状态都需要取消halfCheck=true的情况 - function track(children) { + // 将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy + // 所有的半选状态都需要取消halfCheck=true的情况 + function track (children) { BI.each(children, function (i, ch) { if (ch.halfCheck === true) { ch.halfCheck = false; track(ch.children); } - }) + }); } track(treeNode.children); @@ -1700,19 +1700,19 @@ BI.TreeView = BI.inherit(BI.Pane, { var nodes = treeObj.getSelectedNodes(); $.each(nodes, function (index, node) { node.halfCheck = false; - }) + }); } } - function onCheck(event, treeId, treeNode) { + function onCheck (event, treeId, treeNode) { self._selectTreeNode(treeId, treeNode); } - function onExpand(event, treeId, treeNode) { + function onExpand (event, treeId, treeNode) { treeNode.halfCheck = false; } - function onCollapse(event, treeId, treeNode) { + function onCollapse (event, treeId, treeNode) { } return setting; @@ -1729,19 +1729,19 @@ BI.TreeView = BI.inherit(BI.Pane, { }, _getNodeValue: function (node) { - //去除标红 + // 去除标红 return node.value == null ? node.text.replace(/<[^>]+>/g, "").replaceAll(" ", " ") : node.value; }, - //获取半选框值 + // 获取半选框值 _getHalfSelectedValues: function (map, node) { var self = this; var checkState = node.getCheckStatus(); - //将未选的去掉 + // 将未选的去掉 if (checkState.checked === false && checkState.half === false) { return; } - //如果节点已展开,并且是半选 + // 如果节点已展开,并且是半选 if (BI.isNotEmptyArray(node.children) && checkState.half === true) { var children = node.children; BI.each(children, function (i, ch) { @@ -1782,7 +1782,7 @@ BI.TreeView = BI.inherit(BI.Pane, { cur[key] = value; }, - //构造树节点 + // 构造树节点 _buildTree: function (map, values) { var cur = map; BI.each(values, function (i, value) { @@ -1790,16 +1790,16 @@ BI.TreeView = BI.inherit(BI.Pane, { cur[value] = {}; } cur = cur[value]; - }) + }); }, - //获取选中的值 + // 获取选中的值 _getSelectedValues: function () { var self = this; var hashMap = {}; var rootNoots = this.nodes.getNodes(); track(rootNoots); - function track(nodes) { + function track (nodes) { BI.each(nodes, function (i, node) { var checkState = node.getCheckStatus(); if (checkState.checked === true || checkState.half === true) { @@ -1811,19 +1811,19 @@ BI.TreeView = BI.inherit(BI.Pane, { self._buildTree(hashMap, values); } } - }) + }); } return hashMap; }, - //处理节点 + // 处理节点 _dealWidthNodes: function (nodes) { var self = this, o = this.options; var ns = BI.Tree.arrayFormat(nodes); BI.each(ns, function (i, n) { n.title = n.title || n.text || n.value; - //处理标红 + // 处理标红 if (BI.isKey(o.paras.keyword)) { n.text = $("
").__textKeywordMarked__(n.text, o.paras.keyword, n.py).html(); } else { @@ -1856,7 +1856,7 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //生成树内部方法 + // 生成树内部方法 _initTree: function (setting) { var self = this, o = this.options; self.fireEvent(BI.Events.INIT); @@ -1894,31 +1894,31 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes, setting) { var setting = setting || { - async: { - enable: false - }, - check: { - enable: false - }, - data: { - key: { - title: "title", - name: "text" - }, - simpleData: { - enable: true - } - }, - view: { - showIcon: false, - expandSpeed: "", - nameIsHTML: true + async: { + enable: false + }, + check: { + enable: false + }, + data: { + key: { + title: "title", + name: "text" }, - callback: {} - }; + simpleData: { + enable: true + } + }, + view: { + showIcon: false, + expandSpeed: "", + nameIsHTML: true + }, + callback: {} + }; this.nodes = $.fn.zTree.init(this.tree.element, setting, nodes); }, @@ -1930,7 +1930,7 @@ BI.TreeView = BI.inherit(BI.Pane, { this._stop = true; }, - //生成树方法 + // 生成树方法 stroke: function (config) { delete this.options.keyword; BI.extend(this.options.paras, config); @@ -1950,7 +1950,7 @@ BI.TreeView = BI.inherit(BI.Pane, { }, checkAll: function (checked) { - function setNode(children) { + function setNode (children) { BI.each(children, function (i, child) { child.halfCheck = false; setNode(child.children); @@ -1968,7 +1968,7 @@ BI.TreeView = BI.inherit(BI.Pane, { this.nodes && this.nodes.expandAll(flag); }, - //设置树节点的状态 + // 设置树节点的状态 setValue: function (value, param) { this.checkAll(false); this.updateValue(value, param); @@ -1990,7 +1990,7 @@ BI.TreeView = BI.inherit(BI.Pane, { BI.each(nodes, function (j, node) { BI.extend(node, {checked: true}, op); treeObj.updateNode(node); - }) + }); }); }, @@ -2237,7 +2237,7 @@ BI.shortcut("bi.async_tree", BI.AsyncTree);/** */ BI.PartTree = BI.inherit(BI.AsyncTree, { _defaultConfig: function () { - return BI.extend(BI.PartTree.superclass._defaultConfig.apply(this, arguments), {}) + return BI.extend(BI.PartTree.superclass._defaultConfig.apply(this, arguments), {}); }, _init: function () { @@ -2275,7 +2275,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { if (treeNode.checked === true) { BI.AsyncTree.superclass._selectTreeNode.apply(self, arguments); } else { - //如果选中的值中不存在该值不处理 + // 如果选中的值中不存在该值不处理 var t = this.options.paras.selectedValues; var p = parentValues.concat(name); for (var i = 0, len = p.length; i < len; i++) { @@ -2303,19 +2303,19 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { var hashMap = {}; var rootNoots = this.nodes.getNodes(); track(rootNoots); - function track(nodes) { + function track (nodes) { BI.each(nodes, function (i, node) { var checkState = node.getCheckStatus(); if (checkState.checked === false) { return true; } var parentValues = node.parentValues || self._getParentValues(node); - //把文字中的html去掉,其实就是把文字颜色去掉 + // 把文字中的html去掉,其实就是把文字颜色去掉 var values = parentValues.concat([self._getNodeValue(node)]); self._buildTree(hashMap, values); -// if(checkState.checked === true && checkState.half === false && nodes[i].flag === true){ -// continue; -// } + // if(checkState.checked === true && checkState.half === false && nodes[i].flag === true){ + // continue; + // } if (BI.isNotEmptyArray(node.children)) { track(node.children); return true; @@ -2323,7 +2323,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { if (checkState.half === true) { self._getHalfSelectedValues(hashMap, node); } - }) + }); } return hashMap; @@ -2359,7 +2359,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { self.fireEvent(BI.Events.AFTERINIT); }; - function callback(nodes) { + function callback (nodes) { if (self._stop === true) { return; } @@ -2383,7 +2383,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { return result; }, - //生成树方法 + // 生成树方法 stroke: function (config) { var o = this.options; delete o.paras.keyword; @@ -2413,14 +2413,14 @@ BI.Canvas = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Canvas.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-canvas" - }) + }); }, _init: function () { BI.Canvas.superclass._init.apply(this, arguments); var self = this, o = this.options; var canvas = document.createElement("canvas"); - if (!document.createElement('canvas').getContext) { + if (!document.createElement("canvas").getContext) { canvas = window.G_vmlCanvasManager.initElement(canvas); } this.element.append(canvas); @@ -2438,7 +2438,7 @@ BI.Canvas = BI.inherit(BI.Widget, { _getContext: function () { if (!this.ctx) { - this.ctx = this.canvas.getContext('2d'); + this.ctx = this.canvas.getContext("2d"); } return this.ctx; }, @@ -2522,7 +2522,7 @@ BI.Canvas = BI.inherit(BI.Widget, { stroke: function () { var ctx = this._getContext(); - if(!ctx){ + if(!ctx) { return false; } BI.each(this._queue, function (i, q) { @@ -2637,7 +2637,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { _cellRenderers: function (height, width, x, y) { this._lastRenderedCellIndices = this._sectionManager.getCellIndices(height, width, x, y); - return this._cellGroupRenderer() + return this._cellGroupRenderer(); }, _cellGroupRenderer: function () { @@ -2659,13 +2659,13 @@ BI.CollectionView = BI.inherit(BI.Widget, { var right = Math.min(this._width, scrollLeft + o.width + o.horizontalOverscanSize); var bottom = Math.min(this._height, scrollTop + o.height + o.verticalOverscanSize); if (right > 0 && bottom > 0) { - //如果滚动的区间并没有超出渲染的范围 + // 如果滚动的区间并没有超出渲染的范围 if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { return; } var childrenToDisplay = this._cellRenderers(bottom - top, right - left, left, top); var renderedCells = [], renderedKeys = {}, renderedWidgets = {}; - //存储所有的left和top + // 存储所有的left和top var lefts = {}, tops = {}; for (var i = 0, len = childrenToDisplay.length; i < len; i++) { var datum = childrenToDisplay[i]; @@ -2678,7 +2678,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { tops = BI.toArray(tops); var leftMap = BI.invert(lefts); var topMap = BI.invert(tops); - //存储上下左右四个边界 + // 存储上下左右四个边界 var leftBorder = {}, rightBorder = {}, topBorder = {}, bottomBorder = {}; var assertMinBorder = function (border, offset) { if (border[offset] == null) { @@ -2752,7 +2752,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { renderedKeys[datum.index] = [datum.index, i]; renderedWidgets[i] = child; } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (self.renderedKeys[i]) { @@ -2771,21 +2771,21 @@ BI.CollectionView = BI.inherit(BI.Widget, { deleteArray.push(key[1]); }); BI.each(deleteArray, function (i, index) { - //性能优化,不调用destroy方法防止触发destroy事件 + // 性能优化,不调用destroy方法防止触发destroy事件 self.renderedCells[index].el._destroy(); }); var addedItems = []; BI.each(addSet, function (index, key) { - addedItems.push(renderedCells[key[1]]) + addedItems.push(renderedCells[key[1]]); }); this.container.addItems(addedItems); - //拦截父子级关系 + // 拦截父子级关系 this.container._children = renderedWidgets; this.container.attr("items", renderedCells); this.renderedCells = renderedCells; this.renderedKeys = renderedKeys; - //Todo 左右比较特殊 + // Todo 左右比较特殊 var minX = BI.min(leftBorder); var maxX = BI.max(rightBorder); @@ -2816,7 +2816,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { this.container.setHeight(this._height); this._calculateChildrenToRender(); - //元素未挂载时不能设置scrollTop + // 元素未挂载时不能设置scrollTop try { this.element.scrollTop(o.scrollTop); this.element.scrollLeft(o.scrollLeft); @@ -2852,7 +2852,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; BI.nextTick(function () { - self.element.css({overflowX: !!b ? "auto" : "hidden"}); + self.element.css({overflowX: b ? "auto" : "hidden"}); }); } }, @@ -2862,7 +2862,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; BI.nextTick(function () { - self.element.css({overflowY: !!b ? "auto" : "hidden"}); + self.element.css({overflowY: b ? "auto" : "hidden"}); }); } }, @@ -2883,7 +2883,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { return this._getMaxScrollTop(); }, - //重新计算children + // 重新计算children _reRange: function () { this.renderRange = {}; }, @@ -2912,7 +2912,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { } }); BI.CollectionView.EVENT_SCROLL = "EVENT_SCROLL"; -BI.shortcut('bi.collection_view', BI.CollectionView);/** +BI.shortcut("bi.collection_view", BI.CollectionView);/** * @class BI.Combo * @extends BI.Widget */ @@ -2923,24 +2923,24 @@ BI.Combo = BI.inherit(BI.Widget, { baseCls: (conf.baseCls || "") + " bi-combo", trigger: "click", toggle: true, - direction: "bottom", //top||bottom||left||right||top,left||top,right||bottom,left||bottom,right - container: null,//popupview放置的容器,默认为this.element + direction: "bottom", // top||bottom||left||right||top,left||top,right||bottom,left||bottom,right + container: null, // popupview放置的容器,默认为this.element isDefaultInit: false, destroyWhenHide: false, - isNeedAdjustHeight: true,//是否需要高度调整 + isNeedAdjustHeight: true, // 是否需要高度调整 isNeedAdjustWidth: true, stopEvent: false, stopPropagation: false, - adjustLength: 0,//调整的距离 + adjustLength: 0, // 调整的距离 adjustXOffset: 0, adjustYOffset: 0, hideChecker: BI.emptyFn, - offsetStyle: "left", //left,right,center + offsetStyle: "left", // left,right,center el: {}, popup: {}, comboClass: "bi-combo-popup", hoverClass: "bi-combo-hover" - }) + }); }, _init: function () { @@ -3022,7 +3022,7 @@ BI.Combo = BI.inherit(BI.Widget, { var enterPopup = false; - function hide() { + function hide () { if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid() && o.toggle === true) { self._hideView(); self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.combo); @@ -3165,8 +3165,8 @@ BI.Combo = BI.inherit(BI.Widget, { // if (this.element.__isMouseInBounds__(e) || (this.popupView && this.popupView.element.__isMouseInBounds__(e))) { // return; // } - //BI-10290 公式combo双击公式内容会收起 - if (this.element.find(e.target).length > 0 || e.target.className === "CodeMirror-cursor" || $(e.target).closest(".CodeMirror-hints").length > 0) {//BI-9887 CodeMirror的公式弹框需要特殊处理下 + // BI-10290 公式combo双击公式内容会收起 + if (this.element.find(e.target).length > 0 || e.target.className === "CodeMirror-cursor" || $(e.target).closest(".CodeMirror-hints").length > 0) {// BI-9887 CodeMirror的公式弹框需要特殊处理下 return; } var isHide = this.options.hideChecker.apply(this, [e]); @@ -3233,31 +3233,31 @@ BI.Combo = BI.inherit(BI.Widget, { switch (o.direction) { case "bottom": case "bottom,right": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['bottom', 'top', 'right', 'left'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["bottom", "top", "right", "left"], o.offsetStyle); break; case "top": case "top,right": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['top', 'bottom', 'right', 'left'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["top", "bottom", "right", "left"], o.offsetStyle); break; case "left": case "left,bottom": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['left', 'right', 'bottom', 'top'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["left", "right", "bottom", "top"], o.offsetStyle); break; case "right": case "right,bottom": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['right', 'left', 'bottom', 'top'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "bottom", "top"], o.offsetStyle); break; case "top,left": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['top', 'bottom', 'left', 'right'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["top", "bottom", "left", "right"], o.offsetStyle); break; case "bottom,left": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['bottom', 'top', 'left', 'right'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["bottom", "top", "left", "right"], o.offsetStyle); break; case "left,top": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['left', 'right', 'top', 'bottom'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["left", "right", "top", "bottom"], o.offsetStyle); break; case "right,top": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['right', 'left', 'top', 'bottom'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "top", "bottom"], o.offsetStyle); break; case "top,custom": case "custom,top": @@ -3282,7 +3282,7 @@ BI.Combo = BI.inherit(BI.Widget, { } if ("adaptHeight" in p) { - this.resetListHeight(p['adaptHeight']); + this.resetListHeight(p["adaptHeight"]); } if ("left" in p) { this.popupView.element.css({ @@ -3393,13 +3393,13 @@ BI.Expander = BI.inherit(BI.Widget, { baseCls: "bi-expander", trigger: "click", toggle: true, - //direction: "bottom", //top,bottom四个方向 - isDefaultInit: false, //是否默认初始化子节点 + // direction: "bottom", //top,bottom四个方向 + isDefaultInit: false, // 是否默认初始化子节点 el: {}, popup: {}, expanderClass: "bi-expander-popup", hoverClass: "bi-expander-hover" - }) + }); }, _init: function () { @@ -3473,13 +3473,13 @@ BI.Expander = BI.inherit(BI.Widget, { self.element[e](function (e) { if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { self._popupView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); self.fireEvent(BI.Expander.EVENT_EXPAND); } }, function () { if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid() && o.toggle) { self._hideView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); self.fireEvent(BI.Expander.EVENT_COLLAPSE); } }); @@ -3494,7 +3494,7 @@ BI.Expander = BI.inherit(BI.Widget, { self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); self.fireEvent(BI.Expander.EVENT_EXPAND); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); self.fireEvent(BI.Expander.EVENT_COLLAPSE); } } @@ -3503,7 +3503,7 @@ BI.Expander = BI.inherit(BI.Widget, { } break; } - }) + }); }, _initExpander: function () { @@ -3525,7 +3525,7 @@ BI.Expander = BI.inherit(BI.Widget, { this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); if (type === BI.Events.CLICK) { - //self.setValue(self.getValue()); + // self.setValue(self.getValue()); self.fireEvent(BI.Expander.EVENT_CHANGE, value, obj); } }); @@ -3572,7 +3572,7 @@ BI.Expander = BI.inherit(BI.Widget, { }, populate: function (items) { - //this._assertPopupView(); + // this._assertPopupView(); this.popupView && this.popupView.populate.apply(this.popupView, arguments); this.expander.populate.apply(this.expander, arguments); }, @@ -3584,13 +3584,13 @@ BI.Expander = BI.inherit(BI.Widget, { }, setValue: function (v) { - //this._assertPopupView(); + // this._assertPopupView(); this.expander.setValue(v); this.popupView && this.popupView.setValue(v); }, getValue: function () { - //this._assertPopupView(); + // this._assertPopupView(); return this.popupView ? this.popupView.getValue() : []; }, @@ -3659,7 +3659,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { return BI.extend(BI.ComboGroup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-combo-group bi-list-item", - //以下这些属性对每一个combo都是公用的 + // 以下这些属性对每一个combo都是公用的 trigger: "click,hover", direction: "right", adjustLength: 0, @@ -3679,7 +3679,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { }] } } - }) + }); }, _init: function () { @@ -3709,7 +3709,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { ch.adjustLength = o.adjustLength; ch.popup = o.popup; } - }) + }); this.combo = BI.createWidget({ type: "bi.combo", element: this, @@ -3726,13 +3726,13 @@ BI.ComboGroup = BI.inherit(BI.Widget, { items: children }, o.popup.el) }) - }) + }); this.combo.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); if (type === BI.Events.CLICK) { self.fireEvent(BI.ComboGroup.EVENT_CHANGE, obj); } - }) + }); }, getValue: function () { @@ -3755,7 +3755,7 @@ BI.shortcut("bi.combo_group", BI.ComboGroup);BI.VirtualGroup = BI.inherit(BI.Wid hgap: 0, vgap: 0 }] - }) + }); }, render: function () { @@ -3773,8 +3773,8 @@ BI.shortcut("bi.combo_group", BI.ComboGroup);BI.VirtualGroup = BI.inherit(BI.Wid el: BI.stripEL(it) }) ] - }) - }) + }); + }); } return items; }, @@ -3837,13 +3837,13 @@ BI.Loader = BI.inherit(BI.Widget, { baseCls: "bi-loader", direction: "top", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 logic: { dynamic: true, scrolly: true }, - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -3852,13 +3852,13 @@ BI.Loader = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, prev: false, next: {}, hasPrev: BI.emptyFn, hasNext: BI.emptyFn - }) + }); }, _prevLoad: function () { @@ -3921,7 +3921,7 @@ BI.Loader = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self._nextLoad(); } - }) + }); } BI.createWidget(BI.extend({ @@ -3948,7 +3948,7 @@ BI.Loader = BI.inherit(BI.Widget, { return !!o.hasPrev.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, hasNext: function () { @@ -3959,7 +3959,7 @@ BI.Loader = BI.inherit(BI.Widget, { return !!o.hasNext.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, prependItems: function (items) { @@ -4084,7 +4084,7 @@ BI.shortcut("bi.loader", BI.Loader);/** BI.Navigation = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Navigation.superclass._defaultConfig.apply(this, arguments), { - direction: "bottom",//top, bottom, left, right, custom + direction: "bottom", // top, bottom, left, right, custom logic: { dynamic: false }, @@ -4097,7 +4097,7 @@ BI.Navigation = BI.inherit(BI.Widget, { afterCardCreated: BI.emptyFn, afterCardShow: BI.emptyFn - }) + }); }, render: function () { @@ -4254,13 +4254,13 @@ BI.Searcher = BI.inherit(BI.Widget, { hgap: 0, isDefaultInit: false, - isAutoSearch: true, //是否自动搜索 - isAutoSync: true, //是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一 + isAutoSearch: true, // 是否自动搜索 + isAutoSync: true, // 是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一 chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, - //isAutoSearch为false时启用 + // isAutoSearch为false时启用 onSearch: function (op, callback) { - callback([]) + callback([]); }, el: { @@ -4272,10 +4272,10 @@ BI.Searcher = BI.inherit(BI.Widget, { }, adapter: null, - masker: { //masker层 + masker: { // masker层 offset: {} } - }) + }); }, _init: function () { @@ -4315,7 +4315,7 @@ BI.Searcher = BI.inherit(BI.Widget, { self._pauseSearch(); break; } - }) + }); }, _assertPopupView: function () { @@ -4365,7 +4365,7 @@ BI.Searcher = BI.inherit(BI.Widget, { this._isSearching = true; this.fireEvent(BI.Searcher.EVENT_START); this.popupView.startSearch && this.popupView.startSearch(); - //搜索前先清空dom + // 搜索前先清空dom // BI.Maskers.get(this.getName()).empty(); BI.nextTick(function (name) { BI.Maskers.show(name); @@ -4442,8 +4442,8 @@ BI.Searcher = BI.inherit(BI.Widget, { }, stopSearch: function () { - this._stopSearch();//先停止搜索,然后再去设置editor为空 - //important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) + this._stopSearch();// 先停止搜索,然后再去设置editor为空 + // important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) try { this.editor.blur(); } catch (e) { @@ -4504,9 +4504,9 @@ BI.Searcher = BI.inherit(BI.Widget, { return this.popupView.getValue(); } else if (o.adapter && o.adapter.getValue) { return o.adapter.getValue(); - } else { - return this.popupView.getValue(); } + return this.popupView.getValue(); + }, populate: function (result, searchResult, keyword) { @@ -4555,7 +4555,7 @@ BI.Switcher = BI.inherit(BI.Widget, { masker: {}, switcherClass: "bi-switcher-popup", hoverClass: "bi-switcher-hover" - }) + }); }, _init: function () { @@ -4625,13 +4625,13 @@ BI.Switcher = BI.inherit(BI.Widget, { self.element[e](function (e) { if (self.isEnabled() && self.switcher.isEnabled()) { self._popupView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_EXPAND); } }, function () { if (self.isEnabled() && self.switcher.isEnabled() && o.toggle) { self._hideView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_COLLAPSE); } }); @@ -4643,10 +4643,10 @@ BI.Switcher = BI.inherit(BI.Widget, { if (self.isEnabled() && self.switcher.isEnabled()) { o.toggle ? self._toggle() : self._popupView(); if (self.isExpanded()) { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_EXPAND); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_COLLAPSE); } } @@ -4655,7 +4655,7 @@ BI.Switcher = BI.inherit(BI.Widget, { } break; } - }) + }); }, _initSwitcher: function () { @@ -4821,8 +4821,8 @@ BI.Tab = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Tab.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-tab", - direction: "top",//top, bottom, left, right, custom - single: false, //是不是单页面 + direction: "top", // top, bottom, left, right, custom + single: false, // 是不是单页面 logic: { dynamic: false }, @@ -4831,7 +4831,7 @@ BI.Tab = BI.inherit(BI.Widget, { cardCreator: function (v) { return BI.createWidget(); } - }) + }); }, render: function () { @@ -4840,7 +4840,7 @@ BI.Tab = BI.inherit(BI.Widget, { this.tab = BI.createWidget(this.options.tab, {type: "bi.button_group"}); this.tab.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); } this.cardMap = {}; this.layout = BI.createWidget({ @@ -4991,7 +4991,7 @@ BI.EL = BI.inherit(BI.Widget, { }); this.ele.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); }, setValue: function (v) { @@ -5006,7 +5006,7 @@ BI.EL = BI.inherit(BI.Widget, { this.ele.populate.apply(this, arguments); } }); -BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and others +BI.shortcut("bi.el", BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // This is CodeMirror (http://codemirror.net), a code editor @@ -5015,9513 +5015,9290 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . -(function(mod) { +(function (mod) { this.CodeMirror = mod(); -})(function() { - "use strict"; - - // BROWSER SNIFFING - - // Kludges for bugs and behavior differences that can't be feature - // detected are enabled based on userAgent etc sniffing. - - var gecko = /gecko\/\d/i.test(navigator.userAgent); - var ie_upto10 = /MSIE \d/.test(navigator.userAgent); - var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); - var ie = ie_upto10 || ie_11up; - var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); - var webkit = /WebKit\//.test(navigator.userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); - var chrome = /Chrome\//.test(navigator.userAgent); - var presto = /Opera\//.test(navigator.userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); - var phantom = /PhantomJS/.test(navigator.userAgent); - - var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); - // This is woefully incomplete. Suggestions for alternative methods welcome. - var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); - var mac = ios || /Mac/.test(navigator.platform); - var windows = /win/i.test(navigator.platform); - - var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); - if (presto_version) presto_version = Number(presto_version[1]); - if (presto_version && presto_version >= 15) { presto = false; webkit = true; } - // Some browsers use the wrong event properties to signal cmd/ctrl on OS X - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || (ie && ie_version >= 9); - - // Optimize some code when these features are not used. - var sawReadOnlySpans = false, sawCollapsedSpans = false; - - // EDITOR CONSTRUCTOR - - // A CodeMirror instance represents an editor. This is the object - // that user code is usually dealing with. - - function CodeMirror(place, options) { - if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); - - this.options = options = options ? copyObj(options) : {}; - // Determine effective options based on given values and defaults. - copyObj(defaults, options, false); - setGuttersForLineNumbers(options); - - var doc = options.value; - if (typeof doc == "string") doc = new Doc(doc, options.mode); - this.doc = doc; - - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input); - display.wrapper.CodeMirror = this; - updateGutters(this); - themeChanged(this); - if (options.lineWrapping) - this.display.wrapper.className += " CodeMirror-wrap"; - if (options.autofocus && !mobile) display.input.focus(); - initScrollbars(this); - - this.state = { - keyMaps: [], // stores maps added by addKeyMap - overlays: [], // highlighting overlays, as added by addOverlay - modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, // used to disable editing during key handlers when in readOnly mode - pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll - draggingText: false, - highlight: new Delayed(), // stores highlight worker timeout - keySeq: null, // Unfinished key sequence - specialChars: null - }; +})(function () { + "use strict"; - var cm = this; - - // Override magic textarea content restore that IE sometimes does - // on our hidden textarea on reload - if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20); - - registerEventHandlers(this); - ensureGlobalHandlers(); - - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - - if ((options.autofocus && !mobile) || cm.hasFocus()) - setTimeout(bind(onFocus, this), 20); - else - onBlur(this); - - for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) - optionHandlers[opt](this, options[opt], Init); - maybeUpdateLineNumberWidth(this); - if (options.finishInit) options.finishInit(this); - for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); - endOperation(this); - // Suppress optimizelegibility in Webkit, since it breaks text - // measuring on line wrapping boundaries. - if (webkit && options.lineWrapping && - getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") - display.lineDiv.style.textRendering = "auto"; - } - - // DISPLAY CONSTRUCTOR - - // The display handles the DOM integration, both for input reading - // and content drawing. It holds references to DOM nodes and - // display-related state. - - function Display(place, doc, input) { - var d = this; - this.input = input; - - // Covers bottom-right square when both scrollbars are present. - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - // Covers bottom of gutter when coverGutterNextToScrollbar is on - // and h scrollbar is present. - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - // Will contain the actual code, positioned to cover the viewport. - d.lineDiv = elt("div", null, "CodeMirror-code"); - // Elements are added to these to represent selection and cursors. - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - // A visibility: hidden element used to find the size of things. - d.measure = elt("div", null, "CodeMirror-measure"); - // When lines outside of the viewport are measured, they are drawn in this. - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - // Wraps everything that needs to exist inside the vertically-padded coordinate system - d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], - null, "position: relative; outline: none"); - // Moved around its parent to cover visible view. - d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); - // Set to the height of the document, allowing scrolling. - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - // Behavior of elts with overflow: auto and padding is - // inconsistent across browsers. This is used to ensure the - // scrollable area is big enough. - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - // Will contain the gutters, if any. - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - // Actual scrollable element. - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - - // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) - if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } - if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; - - if (place) { - if (place.appendChild) place.appendChild(d.wrapper); - else place(d.wrapper); - } - - // Current rendered range (may be bigger than the view window). - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - // Information about the rendered lines. - d.view = []; - d.renderedView = null; - // Holds info about a single rendered line when it was rendered - // for measurement, while not in view. - d.externalMeasured = null; - // Empty space (in pixels) above the view - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - - // Used to only resize the line number gutter when necessary (when - // the amount of lines crosses a boundary that makes its width change) - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - // Set to true when a non-horizontal-scrolling line widget is - // added. As an optimization, line widget aligning is skipped when - // this is false. - d.alignWidgets = false; - - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - // True when shift is held down. - d.shift = false; - - // Used to track whether anything happened since the context menu - // was opened. - d.selForContextMenu = null; - - d.activeTouch = null; - - input.init(d); - } - - // STATE UPDATES - - // Used to get the editor into a consistent state again when options change. - - function loadMode(cm) { - cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - - function resetModeState(cm) { - cm.doc.iter(function(line) { - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - }); - cm.doc.frontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) regChange(cm); - } - - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; - } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function(){updateScrollbars(cm);}, 100); - } - - // Returns a function that estimates the height of a line, to use as - // first approximation until the line becomes visible (and is thus - // properly measurable). - function estimateHeight(cm) { - var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function(line) { - if (lineIsHidden(cm.doc, line)) return 0; - - var widgetsHeight = 0; - if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { - if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; - } - - if (wrapping) - return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; - else - return widgetsHeight + th; - }; - } + // BROWSER SNIFFING + + // Kludges for bugs and behavior differences that can't be feature + // detected are enabled based on userAgent etc sniffing. + + var gecko = /gecko\/\d/i.test(navigator.userAgent); + var ie_upto10 = /MSIE \d/.test(navigator.userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + var ie = ie_upto10 || ie_11up; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); + var webkit = /WebKit\//.test(navigator.userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); + var chrome = /Chrome\//.test(navigator.userAgent); + var presto = /Opera\//.test(navigator.userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); + var phantom = /PhantomJS/.test(navigator.userAgent); + + var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); + var mac = ios || /Mac/.test(navigator.platform); + var windows = /win/i.test(navigator.platform); + + var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) presto_version = Number(presto_version[1]); + if (presto_version && presto_version >= 15) { presto = false; webkit = true; } + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || (ie && ie_version >= 9); + + // Optimize some code when these features are not used. + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + // EDITOR CONSTRUCTOR + + // A CodeMirror instance represents an editor. This is the object + // that user code is usually dealing with. + + function CodeMirror (place, options) { + if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + setGuttersForLineNumbers(options); + + var doc = options.value; + if (typeof doc === "string") doc = new Doc(doc, options.mode); + this.doc = doc; + + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input); + display.wrapper.CodeMirror = this; + updateGutters(this); + themeChanged(this); + if (options.lineWrapping) {this.display.wrapper.className += " CodeMirror-wrap";} + if (options.autofocus && !mobile) display.input.focus(); + initScrollbars(this); + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + }; - function estimateLineHeights(cm) { - var doc = cm.doc, est = estimateHeight(cm); - doc.iter(function(line) { - var estHeight = est(line); - if (estHeight != line.height) updateLineHeight(line, estHeight); - }); - } + var cm = this; + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) setTimeout(function () { cm.display.input.reset(true); }, 20); + + registerEventHandlers(this); + ensureGlobalHandlers(); + + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + + if ((options.autofocus && !mobile) || cm.hasFocus()) {setTimeout(bind(onFocus, this), 20);} else {onBlur(this);} + + for (var opt in optionHandlers) { + if (optionHandlers.hasOwnProperty(opt)) {optionHandlers[opt](this, options[opt], Init);} + } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) options.finishInit(this); + for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); + endOperation(this); + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") {display.lineDiv.style.textRendering = "auto";} + } + + // DISPLAY CONSTRUCTOR + + // The display handles the DOM integration, both for input reading + // and content drawing. It holds references to DOM nodes and + // display-related state. + + function Display (place, doc, input) { + var d = this; + this.input = input; + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = elt("div", null, "CodeMirror-code"); + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure"); + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none"); + // Moved around its parent to cover visible view. + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; + + if (place) { + if (place.appendChild) place.appendChild(d.wrapper); + else place(d.wrapper); + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + // Information about the rendered lines. + d.view = []; + d.renderedView = null; + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null; + // Empty space (in pixels) above the view + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false; + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + // True when shift is held down. + d.shift = false; + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null; + + d.activeTouch = null; + + input.init(d); + } + + // STATE UPDATES + + // Used to get the editor into a consistent state again when options change. + + function loadMode (cm) { + cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + + function resetModeState (cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + }); + cm.doc.frontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) regChange(cm); + } + + function wrappingChanged (cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function () {updateScrollbars(cm);}, 100); + } + + // Returns a function that estimates the height of a line, to use as + // first approximation until the line becomes visible (and is thus + // properly measurable). + function estimateHeight (cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function (line) { + if (lineIsHidden(cm.doc, line)) return 0; + + var widgetsHeight = 0; + if (line.widgets) { + for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; + } + } + + if (wrapping) {return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;} + return widgetsHeight + th; + }; + } + + function estimateLineHeights (cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function (line) { + var estHeight = est(line); + if (estHeight != line.height) updateLineHeight(line, estHeight); + }); + } - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + function themeChanged (cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); - } - - function guttersChanged(cm) { - updateGutters(cm); - regChange(cm); - setTimeout(function(){alignHorizontally(cm);}, 20); - } - - // Rebuild the gutter elements, ensure the margin to the left of the - // code matches their width. - function updateGutters(cm) { - var gutters = cm.display.gutters, specs = cm.options.gutters; - removeChildren(gutters); - for (var i = 0; i < specs.length; ++i) { - var gutterClass = specs[i]; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); - if (gutterClass == "CodeMirror-linenumbers") { - cm.display.lineGutter = gElt; - gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = i ? "" : "none"; - updateGutterSpace(cm); - } - - function updateGutterSpace(cm) { - var width = cm.display.gutters.offsetWidth; - cm.display.sizer.style.marginLeft = width + "px"; - } - - // Compute the character length of a line, taking into account - // collapsed ranges (see markText) that might hide parts, and join - // other lines onto it. - function lineLength(line) { - if (line.height == 0) return 0; - var len = line.text.length, merged, cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found = merged.find(0, true); - len -= cur.text.length - found.from.ch; - cur = found.to.line; - len += cur.text.length - found.to.ch; - } - return len; - } - - // Find the longest line in the document. - function findMaxLine(cm) { - var d = cm.display, doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function(line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - - // Make sure the gutters options contains the element - // "CodeMirror-linenumbers" when the lineNumbers option is true. - function setGuttersForLineNumbers(options) { - var found = indexOf(options.gutters, "CodeMirror-linenumbers"); - if (found == -1 && options.lineNumbers) { - options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); - } else if (found > -1 && !options.lineNumbers) { - options.gutters = options.gutters.slice(0); - options.gutters.splice(found, 1); - } - } - - // SCROLLBARS - - // Prepare DOM reads needed to update the scrollbars. Done in one - // shot to minimize update/measure roundtrips. - function measureForScrollbars(cm) { - var d = cm.display, gutterW = d.gutters.offsetWidth; - var docH = Math.round(cm.doc.height + paddingVert(cm.display)); - return { - clientHeight: d.scroller.clientHeight, - viewHeight: d.wrapper.clientHeight, - scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, - viewWidth: d.wrapper.clientWidth, - barLeft: cm.options.fixedGutter ? gutterW : 0, - docHeight: docH, - scrollHeight: docH + scrollGap(cm) + d.barHeight, - nativeBarWidth: d.nativeBarWidth, - gutterWidth: gutterW - }; - } + clearCaches(cm); + } - function NativeScrollbars(place, scroll, cm) { - this.cm = cm; - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - place(vert); place(horiz); + function guttersChanged (cm) { + updateGutters(cm); + regChange(cm); + setTimeout(function () {alignHorizontally(cm);}, 20); + } - on(vert, "scroll", function() { - if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); - }); - on(horiz, "scroll", function() { - if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); - }); + // Rebuild the gutter elements, ensure the margin to the left of the + // code matches their width. + function updateGutters (cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters; + removeChildren(gutters); + for (var i = 0; i < specs.length; ++i) { + var gutterClass = specs[i]; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt; + gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = i ? "" : "none"; + updateGutterSpace(cm); + } - this.checkedOverlay = false; - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; - } - - NativeScrollbars.prototype = copyObj({ - update: function(measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - // A bug in IE8 can cause this value to be negative, so guard it. - this.vert.firstChild.style.height = - Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; - } else { - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; - } - - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = - (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; - } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; - } - - if (!this.checkedOverlay && measure.clientHeight > 0) { - if (sWidth == 0) this.overlayHack(); - this.checkedOverlay = true; - } - - return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; - }, - setScrollLeft: function(pos) { - if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; - }, - setScrollTop: function(pos) { - if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; - }, - overlayHack: function() { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.minHeight = this.vert.style.minWidth = w; - var self = this; - var barMouseDown = function(e) { - if (e_target(e) != self.vert && e_target(e) != self.horiz) - operation(self.cm, onMouseDown)(e); - }; - on(this.vert, "mousedown", barMouseDown); - on(this.horiz, "mousedown", barMouseDown); - }, - clear: function() { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - } - }, NativeScrollbars.prototype); - - function NullScrollbars() {} - - NullScrollbars.prototype = copyObj({ - update: function() { return {bottom: 0, right: 0}; }, - setScrollLeft: function() {}, - setScrollTop: function() {}, - clear: function() {} - }, NullScrollbars.prototype); - - CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; - - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) - rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - - cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - // Prevent clicks in the scrollbars from killing focus - on(node, "mousedown", function() { - if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0); - }); - node.setAttribute("cm-not-content", "true"); - }, function(pos, axis) { - if (axis == "horizontal") setScrollLeft(cm, pos); - else setScrollTop(cm, pos); - }, cm); - if (cm.display.scrollbars.addClass) - addClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - - function updateScrollbars(cm, measure) { - if (!measure) measure = measureForScrollbars(cm); - var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; - updateScrollbarsInner(cm, measure); - for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) - updateHeightsInViewport(cm); - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; - } - } - - // Re-synchronize the fake scrollbars with the actual size of the - // content. - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var sizes = d.scrollbars.update(measure); - - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; - - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else d.scrollbarFiller.style.display = ""; - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = sizes.bottom + "px"; - d.gutterFiller.style.width = measure.gutterWidth + "px"; - } else d.gutterFiller.style.display = ""; - } - - // Compute the lines that are visible in a given viewport (defaults - // the the current scroll position). viewport may contain top, - // height, and ensure (see op.scrollToPos) properties. - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - - var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); - // Ensure is a {from: {line, ch}, to: {line, ch}} object, and - // forces those lines into the viewport (if possible). - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; - } - } - return {from: from, to: Math.max(to, from + 1)}; - } - - // LINE NUMBERS - - // Re-align line numbers and gutter marks to compensate for - // horizontal scrolling. - function alignHorizontally(cm) { - var display = cm.display, view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, left = comp + "px"; - for (var i = 0; i < view.length; i++) if (!view[i].hidden) { - if (cm.options.fixedGutter && view[i].gutter) - view[i].gutter.style.left = left; - var align = view[i].alignable; - if (align) for (var j = 0; j < align.length; j++) - align[j].style.left = left; - } - if (cm.options.fixedGutter) - display.gutters.style.left = (comp + gutterW) + "px"; - } - - // Used to ensure that the line number gutter is still the right - // size for the current document size. Returns true when an update - // is needed. - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) return false; - var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], - "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm); - return true; - } - return false; - } - - function lineNumberFor(options, i) { - return String(options.lineNumberFormatter(i + options.firstLineNumber)); - } - - // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, - // but using getBoundingClientRect to get a sub-pixel-accurate - // result. - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; - } - - // DISPLAY DRAWING - - function DisplayUpdate(cm, viewport, force) { - var display = cm.display; - - this.viewport = viewport; - // Store some values that we'll need later (but don't want to force a relayout for) - this.visible = visibleLines(display, cm.doc, viewport); - this.editorIsHidden = !display.wrapper.offsetWidth; - this.wrapperHeight = display.wrapper.clientHeight; - this.wrapperWidth = display.wrapper.clientWidth; - this.oldDisplayWidth = displayWidth(cm); - this.force = force; - this.dims = getDimensions(cm); - this.events = []; - } - - DisplayUpdate.prototype.signal = function(emitter, type) { - if (hasHandler(emitter, type)) - this.events.push(arguments); - }; - DisplayUpdate.prototype.finish = function() { - for (var i = 0; i < this.events.length; i++) - signal.apply(null, this.events[i]); - }; - - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!display.scrollbarsClipped && display.scroller.offsetWidth) { - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; - display.heightForcer.style.height = scrollGap(cm) + "px"; - display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; - display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; - display.scrollbarsClipped = true; - } - } - - // Does the actual updating of the line display. Bails out - // (returning false) when there is nothing to be done and forced is - // false. - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, doc = cm.doc; - - if (update.editorIsHidden) { - resetView(cm); - return false; - } - - // Bail out if the visible area is already rendered and nothing changed. - if (!update.force && - update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && - display.renderedView == display.view && countDirtyView(cm) == 0) - return false; + function updateGutterSpace (cm) { + var width = cm.display.gutters.offsetWidth; + cm.display.sizer.style.marginLeft = width + "px"; + } - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); + // Compute the character length of a line, taking into account + // collapsed ranges (see markText) that might hide parts, and join + // other lines onto it. + function lineLength (line) { + if (line.height == 0) return 0; + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found = merged.find(0, true); + len -= cur.text.length - found.from.ch; + cur = found.to.line; + len += cur.text.length - found.to.ch; + } + return len; } - // Compute a suitable new viewport (from & to) - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); - if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); + // Find the longest line in the document. + function findMaxLine (cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function (line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); } - var different = from != display.viewFrom || to != display.viewTo || - display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - // Position the mover div to align with the current scroll position - cm.display.mover.style.top = display.viewOffset + "px"; - - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) - return false; - - // For big changes, we hide the enclosing element during the - // update, since that speeds up the operations on most browsers. - var focused = activeElt(); - if (toUpdate > 4) display.lineDiv.style.display = "none"; - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) display.lineDiv.style.display = ""; - display.renderedView = display.view; - // There might have been a widget with a focused element that got - // hidden or updated, if so re-focus it. - if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); - - // Prevent selection and cursors from interfering with the scroll - // width and height. - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = 0; - - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - - display.updateLineNumbers = null; - - return true; - } - - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - // Clip forced viewport to actual scrollable area. - if (viewport && viewport.top != null) - viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; - // Updated line heights might result in the drawn area not - // actually covering the viewport. Keep looping until it does. - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) - break; - } - if (!updateDisplayIfNeeded(cm, update)) break; - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - setDocumentHeight(cm, barMeasure); - updateScrollbars(cm, barMeasure); - } - - update.signal(cm, "update", cm); - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); - cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; - } - } - - function updateDisplaySimple(cm, viewport) { - var update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - setDocumentHeight(cm, barMeasure); - updateScrollbars(cm, barMeasure); - update.finish(); - } - } - - function setDocumentHeight(cm, measure) { - cm.display.sizer.style.minHeight = measure.docHeight + "px"; - var total = measure.docHeight + cm.display.barHeight; - cm.display.heightForcer.style.top = total + "px"; - cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px"; - } - - // Read the actual heights of the rendered lines, and update their - // stored heights to match. - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - for (var i = 0; i < display.view.length; i++) { - var cur = display.view[i], height; - if (cur.hidden) continue; - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; - } - var diff = cur.line.height - height; - if (height < 2) height = textHeight(display); - if (diff > .001 || diff < -.001) { - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) for (var j = 0; j < cur.rest.length; j++) - updateWidgetHeight(cur.rest[j]); - } - } - } - - // Read and store the height of line widgets associated with the - // given line. - function updateWidgetHeight(line) { - if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) - line.widgets[i].height = line.widgets[i].node.offsetHeight; - } - - // Do a bulk-read of the DOM positions and sizes needed to draw the - // view, so that we don't interleave reading and writing to the DOM. - function getDimensions(cm) { - var d = cm.display, left = {}, width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { - left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; - width[cm.options.gutters[i]] = n.clientWidth; - } - return {fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth}; - } - - // Sync the actual display DOM structure with display.view, removing - // nodes for lines that are no longer in view, and creating the ones - // that are not there yet, and updating the ones that are out of - // date. - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, cur = container.firstChild; - - function rm(node) { - var next = node.nextSibling; - // Works around a throw-scroll bug in OS X Webkit - if (webkit && mac && cm.display.currentWheelTarget == node) - node.style.display = "none"; - else - node.parentNode.removeChild(node); - return next; - } - - var view = display.view, lineN = display.viewFrom; - // Loop over the elements in the view, syncing cur (the DOM nodes - // in display.lineDiv) with the view as we go. - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (lineView.hidden) { - } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { // Already drawn - while (cur != lineView.node) cur = rm(cur); - var updateNumber = lineNumbers && updateNumbersFrom != null && - updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; - updateLineForChanges(cm, lineView, lineN, dims); - } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); - } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) cur = rm(cur); - } - - // When an aspect of a line changes, a string is added to - // lineView.changes. This updates the relevant part of the line's - // DOM structure. - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") updateLineText(cm, lineView); - else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); - else if (type == "class") updateLineClasses(lineView); - else if (type == "widget") updateLineWidgets(cm, lineView, dims); - } - lineView.changes = null; - } - - // Lines with gutter elements, widgets or a background class need to - // be wrapped, and have the extra elements added to the wrapper div - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) - lineView.text.parentNode.replaceChild(lineView.node, lineView.text); - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) lineView.node.style.zIndex = 2; - } - return lineView.node; - } - - function updateLineBackground(lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) cls += " CodeMirror-linebackground"; - if (lineView.background) { - if (cls) lineView.background.className = cls; - else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - } - } - - // Wrapper around buildLineContent which will reuse the structure - // in display.externalMeasured when possible. - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built; - } - return buildLineContent(cm, lineView); - } - - // Redraw the line's text. Interacts with the background and text - // classes because the mode may output tokens that influence these - // classes. - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) lineView.node = built.pre; - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - - function updateLineClasses(lineView) { - updateLineBackground(lineView); - if (lineView.line.wrapClass) - ensureLineWrapped(lineView).className = lineView.line.wrapClass; - else if (lineView.node != lineView.text) - lineView.node.className = ""; - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + - (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + - "px; width: " + dims.gutterTotalWidth + "px"); - cm.display.input.setUneditable(gutterWrap); - wrap.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) - gutterWrap.className += " " + lineView.line.gutterClass; - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) - lineView.lineNumber = gutterWrap.appendChild( - elt("div", lineNumberFor(cm.options, lineN), - "CodeMirror-linenumber CodeMirror-gutter-elt", - "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " - + cm.display.lineNumInnerWidth + "px")); - if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { - var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; - if (found) - gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + - dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); - } - } - } - - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) lineView.alignable = null; - for (var node = lineView.node.firstChild, next; node; node = next) { - var next = node.nextSibling; - if (node.className == "CodeMirror-linewidget") - lineView.node.removeChild(node); - } - insertLineWidgets(cm, lineView, dims); - } - - // Build a line's DOM representation from scratch - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) lineView.bgClass = built.bgClass; - if (built.textClass) lineView.textClass = built.textClass; - - updateLineClasses(lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node; - } - - // A lineView may contain multiple logical lines (when merged by - // collapsed spans). The widgets for all of them need to be drawn. - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) - insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); - } - - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) return; - var wrap = ensureLineWrapped(lineView); - for (var i = 0, ws = line.widgets; i < ws.length; ++i) { - var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); - if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) - wrap.insertBefore(node, lineView.gutter || lineView.text); - else - wrap.appendChild(node); - signalLater(widget, "redraw"); - } - } - - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; - } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; - } - } - - // POSITION OBJECT - - // A Pos instance represents a position within the text. - var Pos = CodeMirror.Pos = function(line, ch) { - if (!(this instanceof Pos)) return new Pos(line, ch); - this.line = line; this.ch = ch; - }; - - // Compare two positions, return 0 if they are the same, a negative - // number when a is less, and a positive number otherwise. - var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; - - function copyPos(x) {return Pos(x.line, x.ch);} - function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } - function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } - - // INPUT HANDLING - - function ensureFocus(cm) { - if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } - } - - function isReadOnly(cm) { - return cm.options.readOnly || cm.doc.cantEdit; - } - - // This will be set to an array of strings when copying, so that, - // when pasting, we know what kind of selections the copied text - // was made out of. - var lastCopied = null; - - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) sel = doc.sel; - - var paste = cm.state.pasteIncoming || origin == "paste"; - var textLines = splitLines(inserted), multiPaste = null; - // When pasing N lines into N selections, insert one line per selection - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.join("\n") == inserted) - multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines); - else if (textLines.length == sel.ranges.length) - multiPaste = map(textLines, function(l) { return [l]; }); - } - - // Normal behavior is to insert the new text into every selection - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - var from = range.from(), to = range.to(); - if (range.empty()) { - if (deleted && deleted > 0) // Handle deletion - from = Pos(from.line, from.ch - deleted); - else if (cm.state.overwrite && !paste) // Handle overwrite - to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); - } - var updateInput = cm.curOp.updateInput; - var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); - } - if (inserted && !paste) - triggerElectric(cm, inserted); - - ensureCursorVisible(cm); - cm.curOp.updateInput = updateInput; - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = false; - } - - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); - if (pasted) { - e.preventDefault(); - runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); - return true; - } - } - - function triggerElectric(cm, inserted) { - // When an 'electric' character is inserted, immediately trigger a reindent - if (!cm.options.electricChars || !cm.options.smartIndent) return; - var sel = cm.doc.sel; - - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; - var mode = cm.getModeAt(range.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) - if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range.head.line, "smart"); - break; - } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) - indented = indentLine(cm, range.head.line, "smart"); - } - if (indented) signalLater(cm, "electricInput", cm, range.head.line); - } - } - - function copyableRanges(cm) { - var text = [], ranges = []; - for (var i = 0; i < cm.doc.sel.ranges.length; i++) { - var line = cm.doc.sel.ranges[i].head.line; - var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return {text: text, ranges: ranges}; - } - - function disableBrowserMagic(field) { - field.setAttribute("autocorrect", "off"); - field.setAttribute("autocapitalize", "off"); - field.setAttribute("spellcheck", "false"); - } - - // TEXTAREA INPUT STYLE - - function TextareaInput(cm) { - this.cm = cm; - // See input.poll and input.reset - this.prevInput = ""; - - // Flag that indicates whether we expect input to appear real soon - // now (after some event like 'keypress' or 'input') and are - // polling intensively. - this.pollingFast = false; - // Self-resetting timeout for the poller - this.polling = new Delayed(); - // Tracks when input.reset has punted to just putting a short - // string into the textarea instead of the full selection. - this.inaccurateSelection = false; - // Used to work around IE issue with selection being forgotten when focus moves away from textarea - this.hasSelection = false; - this.composing = null; - }; - - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The textarea is kept positioned near the cursor to prevent the - // fact that it'll be scrolled into view on input from scrolling - // our fake cursor out of view. On webkit, when wrap=off, paste is - // very slow. So make the area wide instead. - if (webkit) te.style.width = "1000px"; - else te.setAttribute("wrap", "off"); - // If border: 0; -- iOS fails to open keyboard (issue #1287) - if (ios) te.style.border = "1px solid black"; - disableBrowserMagic(te); - return div; - } - - TextareaInput.prototype = copyObj({ - init: function(display) { - var input = this, cm = this.cm; - - // Wraps and hides input textarea - var div = this.wrapper = hiddenTextarea(); - // The semihidden textarea that is focused when the editor is - // focused, and receives input. - var te = this.textarea = div.firstChild; - display.wrapper.insertBefore(div, display.wrapper.firstChild); - - // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) - if (ios) te.style.width = "0px"; - - on(te, "input", function() { - if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; - input.poll(); - }); - - on(te, "paste", function(e) { - if (handlePaste(e, cm)) return true; - - cm.state.pasteIncoming = true; - input.fastPoll(); - }); - - function prepareCopyCut(e) { - if (cm.somethingSelected()) { - lastCopied = cm.getSelections(); - if (input.inaccurateSelection) { - input.prevInput = ""; - input.inaccurateSelection = false; - te.value = lastCopied.join("\n"); - selectInput(te); - } - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - lastCopied = ranges.text; - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } - } - if (e.type == "cut") cm.state.cutIncoming = true; - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - - on(display.scroller, "paste", function(e) { - if (eventInWidget(display, e)) return; - cm.state.pasteIncoming = true; - input.focus(); - }); - - // Prevent normal selection in the editor (we handle our own) - on(display.lineSpace, "selectstart", function(e) { - if (!eventInWidget(display, e)) e_preventDefault(e); - }); - - on(te, "compositionstart", function() { - var start = cm.getCursor("from"); - input.composing = { - start: start, - range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + // Make sure the gutters options contains the element + // "CodeMirror-linenumbers" when the lineNumbers option is true. + function setGuttersForLineNumbers (options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers"); + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0); + options.gutters.splice(found, 1); + } + } + + // SCROLLBARS + + // Prepare DOM reads needed to update the scrollbars. Done in one + // shot to minimize update/measure roundtrips. + function measureForScrollbars (cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW }; - }); - on(te, "compositionend", function() { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }, - - prepareSelection: function() { - // Redraw the selection and/or cursor - var cm = this.cm, display = cm.display, doc = cm.doc; - var result = prepareSelection(cm); - - // Move the hidden textarea near the cursor to prevent scrolling artifacts - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, - headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, - headPos.left + lineOff.left - wrapOff.left)); - } - - return result; - }, - - showSelection: function(drawn) { - var cm = this.cm, display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } - }, - - // Reset the input to correspond to the selection (or to be empty, - // when not typing and nothing is selected) - reset: function(typing) { - if (this.contextMenuPending) return; - var minimal, selected, cm = this.cm, doc = cm.doc; - if (cm.somethingSelected()) { - this.prevInput = ""; - var range = doc.sel.primary(); - minimal = hasCopyEvent && - (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); - var content = minimal ? "-" : selected || cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) selectInput(this.textarea); - if (ie && ie_version >= 9) this.hasSelection = content; - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) this.hasSelection = null; - } - this.inaccurateSelection = minimal; - }, - - getField: function() { return this.textarea; }, - - supportsTouch: function() { return false; }, - - focus: function() { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { this.textarea.focus(); } - catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM - } - }, - - blur: function() { this.textarea.blur(); }, - - resetPosition: function() { - this.wrapper.style.top = this.wrapper.style.left = 0; - }, - - receivedFocus: function() { this.slowPoll(); }, - - // Poll for input changes, using the normal rate of polling. This - // runs as long as the editor is focused. - slowPoll: function() { - var input = this; - if (input.pollingFast) return; - input.polling.set(this.cm.options.pollInterval, function() { - input.poll(); - if (input.cm.state.focused) input.slowPoll(); - }); - }, - - // When an event has just come in that is likely to add or change - // something in the input textarea, we poll faster, to ensure that - // the change appears on the screen quickly. - fastPoll: function() { - var missed = false, input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) {missed = true; input.polling.set(60, p);} - else {input.pollingFast = false; input.slowPoll();} - } - input.polling.set(20, p); - }, - - // Read input from the textarea, and update the document to match. - // When something is selected, it is present in the textarea, and - // selected (unless it is huge, in which case a placeholder is - // used). When nothing is selected, the cursor sits after previously - // seen text (can be empty), which is stored in prevInput (we must - // not reset the textarea when typing, because that breaks IME). - poll: function() { - var cm = this.cm, input = this.textarea, prevInput = this.prevInput; - // Since this is called a *lot*, try to bail out as cheaply as - // possible when it is clear that nothing happened. hasSelection - // will be the case when there is a lot of text in the textarea, - // in which case reading its value would be expensive. - if (this.contextMenuPending || !cm.state.focused || - (hasSelection(input) && !prevInput) || - isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq) - return false; + } - var text = input.value; - // If nothing changed, bail. - if (text == prevInput && !cm.somethingSelected()) return false; - // Work around nonsensical selection resetting in IE9/10, and - // inexplicable appearance of private area unicode characters on - // some key combos in Mac (#2689). - if (ie && ie_version >= 9 && this.hasSelection === text || - mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false; - } + function NativeScrollbars (place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + place(vert); place(horiz); + + on(vert, "scroll", function () { + if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); + }); + on(horiz, "scroll", function () { + if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); + }); - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 0x200b && !prevInput) prevInput = "\u200b"; - if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } - } - // Find the part of the input that is actually new - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; + this.checkedOverlay = false; + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; + } + + NativeScrollbars.prototype = copyObj({ + update: function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; + + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } - var self = this; - runInOp(cm, function() { - applyTextInput(cm, text.slice(same), prevInput.length - same, - null, self.composing ? "*compose" : null); + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } - // Don't leave long text in the textarea, since it makes further polling slow - if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; - else self.prevInput = text; + if (!this.checkedOverlay && measure.clientHeight > 0) { + if (sWidth == 0) this.overlayHack(); + this.checkedOverlay = true; + } - if (self.composing) { - self.composing.range.clear(); - self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), - {className: "CodeMirror-composing"}); + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; + }, + setScrollLeft: function (pos) { + if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; + }, + setScrollTop: function (pos) { + if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; + }, + overlayHack: function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.minHeight = this.vert.style.minWidth = w; + var self = this; + var barMouseDown = function (e) { + if (e_target(e) != self.vert && e_target(e) != self.horiz) {operation(self.cm, onMouseDown)(e);} + }; + on(this.vert, "mousedown", barMouseDown); + on(this.horiz, "mousedown", barMouseDown); + }, + clear: function () { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); } - }); - return true; - }, + }, NativeScrollbars.prototype); - ensurePolled: function() { - if (this.pollingFast && this.poll()) this.pollingFast = false; - }, + function NullScrollbars () {} - onKeyPress: function() { - if (ie && ie_version >= 9) this.hasSelection = null; - this.fastPoll(); - }, + NullScrollbars.prototype = copyObj({ + update: function () { return {bottom: 0, right: 0}; }, + setScrollLeft: function () {}, + setScrollTop: function () {}, + clear: function () {} + }, NullScrollbars.prototype); - onContextMenu: function(e) { - var input = this, cm = input.cm, display = cm.display, te = input.textarea; - var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; - if (!pos || presto) return; // Opera is difficult. + CodeMirror.scrollbarModel = {native: NativeScrollbars, null: NullScrollbars}; - // Reset the current text selection only if the click is done outside of the selection - // and 'resetSelectionOnContextMenu' option is true. - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) - operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + function initScrollbars (cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) {rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);} + } - var oldCSS = te.style.cssText; - input.wrapper.style.position = "absolute"; - te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + - "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + - (ie ? "rgba(255, 255, 255, .05)" : "transparent") + - "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) - display.input.focus(); - if (webkit) window.scrollTo(null, oldScrollY); - display.input.reset(); - // Adds "Select all" to context menu in FF - if (!cm.somethingSelected()) te.value = input.prevInput = " "; - input.contextMenuPending = true; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - - // Select-all will be greyed out if there's nothing to select, so - // this adds a zero-width space so that we can later check whether - // it got selected. - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "\u200b" + (selected ? te.value : ""); - te.value = "\u21da"; // Used to catch context-menu undo - te.value = extval; - input.prevInput = selected ? "" : "\u200b"; - te.selectionStart = 1; te.selectionEnd = extval.length; - // Re-set this, in case some other handler touched the - // selection in the meantime. - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - input.contextMenuPending = false; - input.wrapper.style.position = "relative"; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); - - // Try to detect the user choosing select-all - if (te.selectionStart != null) { - if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); - var i = 0, poll = function() { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && - te.selectionEnd > 0 && input.prevInput == "\u200b") - operation(cm, commands.selectAll)(cm); - else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); - else display.input.reset(); - }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } - - if (ie && ie_version >= 9) prepareSelectAllHack(); - if (captureRightClick) { - e_stop(e); - var mouseup = function() { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); - } else { - setTimeout(rehide, 50); - } - }, - - setUneditable: nothing, - - needsContentAttribute: false - }, TextareaInput.prototype); - - // CONTENTEDITABLE INPUT STYLE - - function ContentEditableInput(cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.gracePeriod = false; - } - - ContentEditableInput.prototype = copyObj({ - init: function(display) { - var input = this, cm = input.cm; - var div = input.div = display.lineDiv; - div.contentEditable = "true"; - disableBrowserMagic(div); - - on(div, "paste", function(e) { handlePaste(e, cm); }) - - on(div, "compositionstart", function(e) { - var data = e.data; - input.composing = {sel: cm.doc.sel, data: data, startData: data}; - if (!data) return; - var prim = cm.doc.sel.primary(); - var line = cm.getLine(prim.head.line); - var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); - if (found > -1 && found <= prim.head.ch) - input.composing.sel = simpleSelection(Pos(prim.head.line, found), - Pos(prim.head.line, found + data.length)); - }); - on(div, "compositionupdate", function(e) { - input.composing.data = e.data; - }); - on(div, "compositionend", function(e) { - var ours = input.composing; - if (!ours) return; - if (e.data != ours.startData && !/\u200b/.test(e.data)) - ours.data = e.data; - // Need a small delay to prevent other code (input event, - // selection polling) from doing damage when fired right after - // compositionend. - setTimeout(function() { - if (!ours.handled) - input.applyComposition(ours); - if (input.composing == ours) - input.composing = null; - }, 50); - }); - - on(div, "touchstart", function() { - input.forceCompositionEnd(); - }); - - on(div, "input", function() { - if (input.composing) return; - if (!input.pollContent()) - runInOp(input.cm, function() {regChange(cm);}); - }); - - function onCopyCut(e) { - if (cm.somethingSelected()) { - lastCopied = cm.getSelections(); - if (e.type == "cut") cm.replaceSelection("", null, "cut"); - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - lastCopied = ranges.text; - if (e.type == "cut") { - cm.operation(function() { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); + cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) setTimeout(function () { cm.display.input.focus(); }, 0); }); - } + node.setAttribute("cm-not-content", "true"); + }, function (pos, axis) { + if (axis == "horizontal") setScrollLeft(cm, pos); + else setScrollTop(cm, pos); + }, cm); + if (cm.display.scrollbars.addClass) {addClass(cm.display.wrapper, cm.display.scrollbars.addClass);} + } + + function updateScrollbars (cm, measure) { + if (!measure) measure = measureForScrollbars(cm); + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) {updateHeightsInViewport(cm);} + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; + } + } + + // Re-synchronize the fake scrollbars with the actual size of the + // content. + function updateScrollbarsInner (cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else d.scrollbarFiller.style.display = ""; + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else d.gutterFiller.style.display = ""; + } + + // Compute the lines that are visible in a given viewport (defaults + // the the current scroll position). viewport may contain top, + // height, and ensure (see op.scrollToPos) properties. + function visibleLines (display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return {from: from, to: Math.max(to, from + 1)}; + } + + // LINE NUMBERS + + // Re-align line numbers and gutter marks to compensate for + // horizontal scrolling. + function alignHorizontally (cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; + for (var i = 0; i < view.length; i++) { + if (!view[i].hidden) { + if (cm.options.fixedGutter && view[i].gutter) {view[i].gutter.style.left = left;} + var align = view[i].alignable; + if (align) { + for (var j = 0; j < align.length; j++) {align[j].style.left = left;} + } + } + } + if (cm.options.fixedGutter) {display.gutters.style.left = (comp + gutterW) + "px";} + } + + // Used to ensure that the line number gutter is still the right + // size for the current document size. Returns true when an update + // is needed. + function maybeUpdateLineNumberWidth (cm) { + if (!cm.options.lineNumbers) return false; + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm); + return true; } - // iOS exposes the clipboard API, but seems to discard content inserted into it - if (e.clipboardData && !ios) { - e.preventDefault(); - e.clipboardData.clearData(); - e.clipboardData.setData("text/plain", lastCopied.join("\n")); - } else { - // Old-fashioned briefly-focus-a-textarea hack - var kludge = hiddenTextarea(), te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.join("\n"); - var hadFocus = document.activeElement; - selectInput(te); - setTimeout(function() { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - }, 50); - } - } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }, - - prepareSelection: function() { - var result = prepareSelection(this.cm, false); - result.focus = this.cm.state.focused; - return result; - }, - - showSelection: function(info) { - if (!info || !this.cm.display.view.length) return; - if (info.focus) this.showPrimarySelection(); - this.showMultipleSelections(info); - }, - - showPrimarySelection: function() { - var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); - var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && - cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && - cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) - return; + return false; + } - var start = posToDOM(this.cm, prim.from()); - var end = posToDOM(this.cm, prim.to()); - if (!start && !end) return; + function lineNumberFor (options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)); + } - var view = this.cm.display.view; - var old = sel.rangeCount && sel.getRangeAt(0); - if (!start) { - start = {node: view[0].measure.map[2], offset: 0}; - } else if (!end) { // FIXME dangerously hacky - var measure = view[view.length - 1].measure; - var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; - } + // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, + // but using getBoundingClientRect to get a sub-pixel-accurate + // result. + function compensateForHScroll (display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; + } - try { var rng = range(start.node, start.offset, end.offset, end.node); } - catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible - if (rng) { - sel.removeAllRanges(); - sel.addRange(rng); - if (old && sel.anchorNode == null) sel.addRange(old); - else if (gecko) this.startGracePeriod(); - } - this.rememberSelection(); - }, + // DISPLAY DRAWING - startGracePeriod: function() { - var input = this; - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function() { - input.gracePeriod = false; - if (input.selectionChanged()) - input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); - }, 20); - }, + function DisplayUpdate (cm, viewport, force) { + var display = cm.display; - showMultipleSelections: function(info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); - }, + this.viewport = viewport; + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; + } - rememberSelection: function() { - var sel = window.getSelection(); - this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; - }, + DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) {this.events.push(arguments);} + }; + DisplayUpdate.prototype.finish = function () { + for (var i = 0; i < this.events.length; i++) {signal.apply(null, this.events[i]);} + }; - selectionInEditor: function() { - var sel = window.getSelection(); - if (!sel.rangeCount) return false; - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node); - }, + function maybeClipScrollbars (cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } + } - focus: function() { - if (this.cm.options.readOnly != "nocursor") this.div.focus(); - }, - blur: function() { this.div.blur(); }, - getField: function() { return this.div; }, + // Does the actual updating of the line display. Bails out + // (returning false) when there is nothing to be done and forced is + // false. + function updateDisplayIfNeeded (cm, update) { + var display = cm.display, doc = cm.doc; - supportsTouch: function() { return true; }, + if (update.editorIsHidden) { + resetView(cm); + return false; + } - receivedFocus: function() { - var input = this; - if (this.selectionInEditor()) - this.pollSelection(); - else - runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) {return false;} - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); } - } - this.polling.set(this.cm.options.pollInterval, poll); - }, - selectionChanged: function() { - var sel = window.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || - sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; - }, + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); + if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } - pollSelection: function() { - if (!this.composing && !this.gracePeriod && this.selectionChanged()) { - var sel = window.getSelection(), cm = this.cm; - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) runInOp(cm, function() { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; - }); - } - }, - - pollContent: function() { - var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); - var from = sel.from(), to = sel.to(); - if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; - - var fromIndex; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - var fromLine = lineNo(display.view[0].line); - var fromNode = display.view[0].node; - } else { - var fromLine = lineNo(display.view[fromIndex].line); - var fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - if (toIndex == display.view.length - 1) { - var toLine = display.viewTo - 1; - var toNode = display.lineDiv.lastChild; - } else { - var toLine = lineNo(display.view[toIndex + 1].line) - 1; - var toNode = display.view[toIndex + 1].node.previousSibling; - } - - var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } - else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } - else break; - } - - var cutFront = 0, cutEnd = 0; - var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) - ++cutFront; - var newBot = lst(newText), oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), - oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) - ++cutEnd; - - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); - newText[0] = newText[0].slice(cutFront); - - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true; - } - }, + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); - ensurePolled: function() { - this.forceCompositionEnd(); - }, - reset: function() { - this.forceCompositionEnd(); - }, - forceCompositionEnd: function() { - if (!this.composing || this.composing.handled) return; - this.applyComposition(this.composing); - this.composing.handled = true; - this.div.blur(); - this.div.focus(); - }, - applyComposition: function(composing) { - if (composing.data && composing.data != composing.startData) - operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); - }, + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px"; - setUneditable: function(node) { - node.setAttribute("contenteditable", "false"); - }, + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) {return false;} - onKeyPress: function(e) { - e.preventDefault(); - operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); - }, + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt(); + if (toUpdate > 4) display.lineDiv.style.display = "none"; + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) display.lineDiv.style.display = ""; + display.renderedView = display.view; + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); - onContextMenu: nothing, - resetPosition: nothing, + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = 0; - needsContentAttribute: true - }, ContentEditableInput.prototype); + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) return null; - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); + display.updateLineNumbers = null; - var order = getOrder(line), side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; + return true; } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result; - } - function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } - - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); - node = null; offset = 0; - } else { - for (lineNode = node;; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) return null; - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; - } - } - for (var i = 0; i < cm.display.view.length; i++) { - var lineView = cm.display.view[i]; - if (lineView.node == lineNode) - return locateNodeInLineView(lineView, node, offset); - } - } - - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, bad = false; - if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad); - } - } - - var textNode = node.nodeType == 3 ? node : null, topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) offset = textNode.nodeValue.length; - } - while (topNode.parentNode != wrapper) topNode = topNode.parentNode; - var measure = lineView.measure, maps = measure.maps; - - function find(textNode, topNode, offset) { - for (var i = -1; i < (maps ? maps.length : 0); i++) { - var map = i < 0 ? measure.map : maps[i]; - for (var j = 0; j < map.length; j += 3) { - var curNode = map[j + 2]; - if (curNode == textNode || curNode == topNode) { - var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); - var ch = map[j] + offset; - if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; - return Pos(line, ch); - } - } - } - } - var found = find(textNode, topNode, offset); - if (found) return badPos(found, bad); - - // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) - return badPos(Pos(found.line, found.ch - dist), bad); - else - dist += after.textContent.length; - } - for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) - return badPos(Pos(found.line, found.ch + dist), bad); - else - dist += after.textContent.length; - } - } - - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", closing = false; - function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText != null) { - if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); - text += cmText; - return; - } - var markerID = node.getAttribute("cm-marker"), range; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range = found[0].find())) - text += getBetween(cm.doc, range.from, range.to).join("\n"); - return; - } - if (node.getAttribute("contenteditable") == "false") return; - for (var i = 0; i < node.childNodes.length; i++) - walk(node.childNodes[i]); - if (/^(pre|div|p)$/i.test(node.nodeName)) - closing = true; - } else if (node.nodeType == 3) { - var val = node.nodeValue; - if (!val) return; - if (closing) { - text += "\n"; - closing = false; - } - text += val; - } - } - for (;;) { - walk(from); - if (from == to) break; - from = from.nextSibling; - } - return text; - } - - CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; - - // SELECTION / CURSOR - - // Selection objects are immutable. A new one is created every time - // the selection changes. A selection is one or more non-overlapping - // (and non-touching) ranges, sorted, and an integer that indicates - // which one is the primary selection (the one that's scrolled into - // view, that getCursor returns, etc). - function Selection(ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; - } - - Selection.prototype = { - primary: function() { return this.ranges[this.primIndex]; }, - equals: function(other) { - if (other == this) return true; - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; - for (var i = 0; i < this.ranges.length; i++) { - var here = this.ranges[i], there = other.ranges[i]; - if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; - } - return true; - }, - deepCopy: function() { - for (var out = [], i = 0; i < this.ranges.length; i++) - out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); - return new Selection(out, this.primIndex); - }, - somethingSelected: function() { - for (var i = 0; i < this.ranges.length; i++) - if (!this.ranges[i].empty()) return true; - return false; - }, - contains: function(pos, end) { - if (!end) end = pos; - for (var i = 0; i < this.ranges.length; i++) { - var range = this.ranges[i]; - if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) - return i; - } - return -1; - } - }; - - function Range(anchor, head) { - this.anchor = anchor; this.head = head; - } - - Range.prototype = { - from: function() { return minPos(this.anchor, this.head); }, - to: function() { return maxPos(this.anchor, this.head); }, - empty: function() { - return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; - } - }; - - // Take an unsorted, potentially overlapping set of ranges, and - // build a selection out of it. 'Consumes' ranges array (modifying - // it). - function normalizeSelection(ranges, primIndex) { - var prim = ranges[primIndex]; - ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); - primIndex = indexOf(ranges, prim); - for (var i = 1; i < ranges.length; i++) { - var cur = ranges[i], prev = ranges[i - 1]; - if (cmp(prev.to(), cur.from()) >= 0) { - var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i <= primIndex) --primIndex; - ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); - } - } - return new Selection(ranges, primIndex); - } - - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0); - } - - // Most of the external API clips given positions to make sure they - // actually exist within the document. - function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} - function clipPos(doc, pos) { - if (pos.line < doc.first) return Pos(doc.first, 0); - var last = doc.first + doc.size - 1; - if (pos.line > last) return Pos(last, getLine(doc, last).text.length); - return clipToLen(pos, getLine(doc, pos.line).text.length); - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) return Pos(pos.line, linelen); - else if (ch < 0) return Pos(pos.line, 0); - else return pos; - } - function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} - function clipPosArray(doc, array) { - for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); - return out; - } - - // SELECTION UPDATES - - // The 'scroll' parameter given to many of these indicated whether - // the new cursor position should be scrolled into view after - // modifying the selection. - - // If shift is held or the extend flag is set, extends a range to - // include a given position (and optionally a second position). - // Otherwise, simply returns the range between the given positions. - // Used for cursor motion and such. - function extendRange(doc, range, head, other) { - if (doc.cm && doc.cm.display.shift || doc.extend) { - var anchor = range.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != (cmp(other, anchor) < 0)) { - anchor = head; - head = other; - } else if (posBefore != (cmp(head, other) < 0)) { - head = other; - } - } - return new Range(anchor, head); - } else { - return new Range(other || head, head); - } - } - - // Extend the primary selection range, discard the rest. - function extendSelection(doc, head, other, options) { - setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); - } - - // Extend all selections (pos is an array of selections with length - // equal the number of selections) - function extendSelections(doc, heads, options) { - for (var out = [], i = 0; i < doc.sel.ranges.length; i++) - out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); - var newSel = normalizeSelection(out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - - // Updates a single range in the selection. - function replaceOneSelection(doc, i, range, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i] = range; - setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); - } - - // Reset the selection to a single range. - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - - // Give beforeSelectionChange handlers a change to influence a - // selection update. - function filterSelectionChange(doc, sel) { - var obj = { - ranges: sel.ranges, - update: function(ranges) { - this.ranges = []; - for (var i = 0; i < ranges.length; i++) - this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), - clipPos(doc, ranges[i].head)); - } - }; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); - if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); - else return sel; - } - - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); - } else { - setSelection(doc, sel, options); + function postUpdateDisplay (cm, update) { + var viewport = update.viewport; + for (var first = true; ; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) {viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};} + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) {break;} + } + if (!updateDisplayIfNeeded(cm, update)) break; + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + } + + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; + } + } + + function updateDisplaySimple (cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + update.finish(); + } + } + + function setDocumentHeight (cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + var total = measure.docHeight + cm.display.barHeight; + cm.display.heightForcer.style.top = total + "px"; + cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px"; + } + + // Read the actual heights of the rendered lines, and update their + // stored heights to match. + function updateHeightsInViewport (cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height; + if (cur.hidden) continue; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + } + var diff = cur.line.height - height; + if (height < 2) height = textHeight(display); + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { + for (var j = 0; j < cur.rest.length; j++) {updateWidgetHeight(cur.rest[j]);} + } + } + } } - } - // Set a new selection. - function setSelection(doc, sel, options) { - setSelectionNoUndo(doc, sel, options); - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); - } - - function setSelectionNoUndo(doc, sel, options) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) - sel = filterSelectionChange(doc, sel); + // Read and store the height of line widgets associated with the + // given line. + function updateWidgetHeight (line) { + if (line.widgets) { + for (var i = 0; i < line.widgets.length; ++i) {line.widgets[i].height = line.widgets[i].node.offsetHeight;} + } + } - var bias = options && options.bias || - (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); - - if (!(options && options.scroll === false) && doc.cm) - ensureCursorVisible(doc.cm); - } - - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) return; - - doc.sel = sel; - - if (doc.cm) { - doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - - // Verify that the selection does not partially select any atomic - // marked ranges. - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); - } - - // Return a selection that does not partially select any atomic - // ranges. - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range.head, bias, mayClear); - if (out || newAnchor != range.anchor || newHead != range.head) { - if (!out) out = sel.ranges.slice(0, i); - out[i] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(out, sel.primIndex) : sel; - } - - // Ensure a given position is not inside an atomic range. - function skipAtomic(doc, pos, bias, mayClear) { - var flipped = false, curPos = pos; - var dir = bias || 1; - doc.cantEdit = false; - search: for (;;) { - var line = getLine(doc, curPos.line); - if (line.markedSpans) { - for (var i = 0; i < line.markedSpans.length; ++i) { - var sp = line.markedSpans[i], m = sp.marker; - if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && - (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) break; - else {--i; continue;} - } - } - if (!m.atomic) continue; - var newPos = m.find(dir < 0 ? -1 : 1); - if (cmp(newPos, curPos) == 0) { - newPos.ch += dir; - if (newPos.ch < 0) { - if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); - else newPos = null; - } else if (newPos.ch > line.text.length) { - if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); - else newPos = null; - } - if (!newPos) { - if (flipped) { - // Driven in a corner -- no valid cursor position found at all - // -- try again *with* clearing, if we didn't already - if (!mayClear) return skipAtomic(doc, pos, bias, true); - // Otherwise, turn off editing until further notice, and return the start of the doc - doc.cantEdit = true; - return Pos(doc.first, 0); - } - flipped = true; newPos = pos; dir = -dir; - } - } - curPos = newPos; - continue search; - } - } - } - return curPos; - } - } - - // SELECTION DRAWING - - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - - function prepareSelection(cm, primary) { - var doc = cm.doc, result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - - for (var i = 0; i < doc.sel.ranges.length; i++) { - if (primary === false && i == doc.sel.primIndex) continue; - var range = doc.sel.ranges[i]; - var collapsed = range.empty(); - if (collapsed || cm.options.showCursorWhenSelecting) - drawSelectionCursor(cm, range, curFragment); - if (!collapsed) - drawSelectionRange(cm, range, selFragment); - } - return result; - } - - // Draws a cursor for the given range - function drawSelectionCursor(cm, range, output) { - var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine); - - var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - - if (pos.other) { - // Secondary cursor, shown when on a 'jump' in bi-directional text - var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; - } - } - - // Draws the given range as a highlighted selection - function drawSelectionRange(cm, range, output) { - var display = cm.display, doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - - function add(left, top, width, bottom) { - if (top < 0) top = 0; - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + - "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + - "px; height: " + (bottom - top) + "px")); + // Do a bulk-read of the DOM positions and sizes needed to draw the + // view, so that we don't interleave reading and writing to the DOM. + function getDimensions (cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; + width[cm.options.gutters[i]] = n.clientWidth; + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth}; } - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias); - } + // Sync the actual display DOM structure with display.view, removing + // nodes for lines that are no longer in view, and creating the ones + // that are not there yet, and updating the ones that are out of + // date. + function patchDisplay (cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; - iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { - var leftPos = coords(from, "left"), rightPos, left, right; - if (from == to) { - rightPos = leftPos; - left = right = leftPos.left; - } else { - rightPos = coords(to - 1, "right"); - if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } - left = leftPos.left; - right = rightPos.right; - } - if (fromArg == null && from == 0) left = leftSide; - if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part - add(left, leftPos.top, null, leftPos.bottom); - left = leftSide; - if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); - } - if (toArg == null && to == lineLen) right = rightSide; - if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) - start = leftPos; - if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) - end = rightPos; - if (left < leftSide + 1) left = leftSide; - add(left, rightPos.top, right - left, rightPos.bottom); - }); - return {start: start, end: end}; - } - - var sFrom = range.from(), sTo = range.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); - } - } - if (leftEnd.bottom < rightStart.top) - add(leftSide, leftEnd.bottom, null, rightStart.top); - } - - output.appendChild(fragment); - } - - // Cursor-blinking - function restartBlink(cm) { - if (!cm.state.focused) return; - var display = cm.display; - clearInterval(display.blinker); - var on = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) - display.blinker = setInterval(function() { - display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; - }, cm.options.cursorBlinkRate); - else if (cm.options.cursorBlinkRate < 0) - display.cursorDiv.style.visibility = "hidden"; - } - - // HIGHLIGHT WORKER - - function startWorker(cm, time) { - if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) - cm.state.highlight.set(time, bind(highlightWorker, cm)); - } - - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.frontier < doc.first) doc.frontier = doc.first; - if (doc.frontier >= cm.display.viewTo) return; - var end = +new Date + cm.options.workTime; - var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); - var changedLines = []; - - doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { - if (doc.frontier >= cm.display.viewFrom) { // Visible - var oldStyles = line.styles; - var highlighted = highlightLine(cm, line, state, true); - line.styles = highlighted.styles; - var oldCls = line.styleClasses, newCls = highlighted.classes; - if (newCls) line.styleClasses = newCls; - else if (oldCls) line.styleClasses = null; - var ischange = !oldStyles || oldStyles.length != line.styles.length || - oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; - if (ischange) changedLines.push(doc.frontier); - line.stateAfter = copyState(doc.mode, state); - } else { - processLine(cm, line.text, state); - line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; - } - ++doc.frontier; - if (+new Date > end) { - startWorker(cm, cm.options.workDelay); - return true; - } - }); - if (changedLines.length) runInOp(cm, function() { - for (var i = 0; i < changedLines.length; i++) - regLineChange(cm, changedLines[i], "text"); - }); - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(cm, n, precise) { - var minindent, minline, doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) return doc.first; - var line = getLine(doc, search - 1); - if (line.stateAfter && (!precise || search <= doc.frontier)) return search; - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline; - } - - function getStateBefore(cm, n, precise) { - var doc = cm.doc, display = cm.display; - if (!doc.mode.startState) return true; - var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; - if (!state) state = startState(doc.mode); - else state = copyState(doc.mode, state); - doc.iter(pos, n, function(line) { - processLine(cm, line.text, state); - var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; - line.stateAfter = save ? copyState(doc.mode, state) : null; - ++pos; - }); - if (precise) doc.frontier = pos; - return state; - } - - // POSITION MEASUREMENT - - function paddingTop(display) {return display.lineSpace.offsetTop;} - function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} - function paddingH(display) { - if (display.cachedPaddingH) return display.cachedPaddingH; - var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; - if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; - return data; - } - - function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; } - function displayWidth(cm) { - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; - } - function displayHeight(cm) { - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; - } - - // Ensure the lineView.wrapping.heights array is populated. This is - // an array of bottom offsets for the lines that make up a drawn - // line. When lineWrapping is on, there might be more than one - // height. - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i = 0; i < rects.length - 1; i++) { - var cur = rects[i], next = rects[i + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) - heights.push((cur.bottom + next.top) / 2 - rect.top); - } - } - heights.push(rect.bottom - rect.top); - } - } - - // Find a line map (mapping character offsets to text nodes) and a - // measurement cache for the given line number. (A line view might - // contain multiple lines when collapsed ranges are present.) - function mapFromLineView(lineView, line, lineN) { - if (lineView.line == line) - return {map: lineView.measure.map, cache: lineView.measure.cache}; - for (var i = 0; i < lineView.rest.length; i++) - if (lineView.rest[i] == line) - return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; - for (var i = 0; i < lineView.rest.length; i++) - if (lineNo(lineView.rest[i]) > lineN) - return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; - } - - // Render a line into the hidden node display.externalMeasured. Used - // when measurement is needed for a line that's not in the viewport. - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view; - } - - // Get a {top, bottom, left, right} box (in line-local coordinates) - // for a given character. - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); - } - - // Find a line view that corresponds to the given line number. - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) - return cm.display.view[findViewIndex(cm, lineN)]; - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) - return ext; - } - - // Measurement can be split in two steps, the set-up work that - // applies to the whole line, and the measurement of the actual - // character. Functions like coordsChar, that need to do a lot of - // measurements in a row, can thus ensure that the set-up work is - // only done once. - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) - view = null; - else if (view && view.changes) - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - if (!view) - view = updateExternalMeasurement(cm, line); - - var info = mapFromLineView(view, line, lineN); - return { - line: line, view: view, rect: null, - map: info.map, cache: info.cache, before: info.before, - hasHeights: false - }; - } - - // Given a prepared measurement object, measures the position of an - // actual character (or fetches it from the cache). - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) ch = -1; - var key = ch + (bias || ""), found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) - prepared.rect = prepared.view.text.getBoundingClientRect(); - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) prepared.cache[key] = found; - } - return {left: found.left, right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom}; - } - - var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; - - function nodeAndOffsetInLineMap(map, ch, bias) { - var node, start, end, collapse; - // First, search the line map for the text node corresponding to, - // or closest to, the target character. - for (var i = 0; i < map.length; i += 3) { - var mStart = map[i], mEnd = map[i + 1]; - if (ch < mStart) { - start = 0; end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) collapse = "right"; - } - if (start != null) { - node = map[i + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) - collapse = bias; - if (bias == "left" && start == 0) - while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { - node = map[(i -= 3) + 2]; - collapse = "left"; - } - if (bias == "right" && start == mEnd - mStart) - while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { - node = map[(i += 3) + 2]; - collapse = "right"; - } - break; - } - } - return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; - } - - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, start = place.start, end = place.end, collapse = place.collapse; - - var rect; - if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. - for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { - rect = node.parentNode.getBoundingClientRect(); - } else if (ie && cm.options.lineWrapping) { - var rects = range(node, start, end).getClientRects(); - if (rects.length) - rect = rects[bias == "right" ? rects.length - 1 : 0]; - else - rect = nullRect; - } else { - rect = range(node, start, end).getBoundingClientRect() || nullRect; - } - if (rect.left || rect.right || start == 0) break; - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); - } else { // If it is a widget, simply get the box for the whole widget. - if (start > 0) collapse = bias = "right"; - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) - rect = rects[bias == "right" ? rects.length - 1 : 0]; - else - rect = node.getBoundingClientRect(); - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) - rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; - else - rect = nullRect; - } - - var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - for (var i = 0; i < heights.length - 1; i++) - if (mid < heights[i]) break; - var top = i ? heights[i - 1] : 0, bot = heights[i]; - var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top: top, bottom: bot}; - if (!rect.left && !rect.right) result.bogus = true; - if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } - - return result; - } - - // Work around problem with bounding client rects on ranges being - // returned incorrectly when zoomed on IE10 and below. - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || - screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) - return rect; - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return {left: rect.left * scaleX, right: rect.right * scaleX, - top: rect.top * scaleY, bottom: rect.bottom * scaleY}; - } - - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) - lineView.measure.caches[i] = {}; - } - } - - function clearLineMeasurementCache(cm) { - cm.display.externalMeasure = null; - removeChildren(cm.display.lineMeasure); - for (var i = 0; i < cm.display.view.length; i++) - clearLineMeasurementCacheFor(cm.display.view[i]); - } - - function clearCaches(cm) { - clearLineMeasurementCache(cm); - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; - if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; - cm.display.lineNumChars = null; - } - - function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } - function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } - - // Converts a {top, bottom, left, right} box from line-local - // coordinates into another coordinate system. Context may be one of - // "line", "div" (display.lineDiv), "local"/null (editor), "window", - // or "page". - function intoCoordSystem(cm, lineObj, rect, context) { - if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { - var size = widgetHeight(lineObj.widgets[i]); - rect.top += size; rect.bottom += size; - } - if (context == "line") return rect; - if (!context) context = "local"; - var yOff = heightAtLine(lineObj); - if (context == "local") yOff += paddingTop(cm.display); - else yOff -= cm.display.viewOffset; - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; rect.right += xOff; - } - rect.top += yOff; rect.bottom += yOff; - return rect; - } - - // Coverts a box from "div" coords to another coordinate system. - // Context may be "window", "page", "div", or "local"/null. - function fromCoordSystem(cm, coords, context) { - if (context == "div") return coords; - var left = coords.left, top = coords.top; - // First move into "page" coordinate system - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; - } - - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) lineObj = getLine(cm.doc, pos.line); - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); - } - - // Returns a box for a given cursor position, which may have an - // 'other' property containing the position of the secondary cursor - // on a bidi boundary. - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); - function get(ch, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); - if (right) m.left = m.right; else m.right = m.left; - return intoCoordSystem(cm, lineObj, m, context); - } - function getBidi(ch, partPos) { - var part = order[partPos], right = part.level % 2; - if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { - part = order[--partPos]; - ch = bidiRight(part) - (part.level % 2 ? 0 : 1); - right = true; - } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { - part = order[++partPos]; - ch = bidiLeft(part) - part.level % 2; - right = false; - } - if (right && ch == part.to && ch > part.from) return get(ch - 1); - return get(ch, right); - } - var order = getOrder(lineObj), ch = pos.ch; - if (!order) return get(ch); - var partPos = getBidiPartAt(order, ch); - var val = getBidi(ch, partPos); - if (bidiOther != null) val.other = getBidi(ch, bidiOther); - return val; - } - - // Used to cheaply estimate the coordinates for a position. Used for - // intermediate scroll updates. - function estimateCoords(cm, pos) { - var left = 0, pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return {left: left, right: left, top: top, bottom: top + lineObj.height}; - } - - // Positions returned by coordsChar contain some extra information. - // xRel is the relative x position of the input coordinates compared - // to the found position (so xRel > 0 means the coordinates are to - // the right of the character position, for example). When outside - // is true, that means the coordinates lie outside the line's - // vertical range. - function PosWithInfo(line, ch, outside, xRel) { - var pos = Pos(line, ch); - pos.xRel = xRel; - if (outside) pos.outside = true; - return pos; - } - - // Compute the character position closest to the given coordinates. - // Input must be lineSpace-local ("div" coordinate system). - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) return PosWithInfo(doc.first, 0, true, -1); - var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; - if (lineN > last) - return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); - if (x < 0) x = 0; - - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var merged = collapsedSpanAtEnd(lineObj); - var mergedPos = merged && merged.find(0, true); - if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) - lineN = lineNo(lineObj = mergedPos.to.line); - else - return found; + function rm (node) { + var next = node.nextSibling; + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) {node.style.display = "none";} else {node.parentNode.removeChild(node);} + return next; + } + + var view = display.view, lineN = display.viewFrom; + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { // Already drawn + while (cur != lineView.node) cur = rm(cur); + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) cur = rm(cur); } - } - - function coordsCharInner(cm, lineObj, lineNo, x, y) { - var innerOff = y - heightAtLine(lineObj); - var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - - function getX(ch) { - var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); - wrongLine = true; - if (innerOff > sp.bottom) return sp.left - adjust; - else if (innerOff < sp.top) return sp.left + adjust; - else wrongLine = false; - return sp.left; - } - - var bidi = getOrder(lineObj), dist = lineObj.text.length; - var from = lineLeft(lineObj), to = lineRight(lineObj); - var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; - - if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); - // Do a binary search between these bounds. - for (;;) { - if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { - var ch = x < fromX || x - fromX <= toX - x ? from : to; - var xDiff = x - (ch == from ? fromX : toX); - while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; - var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, - xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); - return pos; - } - var step = Math.ceil(dist / 2), middle = from + step; - if (bidi) { - middle = from; - for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); - } - var middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} - else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} - } - } - - var measureText; - // Compute the default text height. - function textHeight(display) { - if (display.cachedTextHeight != null) return display.cachedTextHeight; - if (measureText == null) { - measureText = elt("pre"); - // Measure a bunch of lines, for browsers that compute - // fractional heights. - for (var i = 0; i < 49; ++i) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) display.cachedTextHeight = height; - removeChildren(display.measure); - return height || 1; - } - - // Compute the default character width. - function charWidth(display) { - if (display.cachedCharWidth != null) return display.cachedCharWidth; - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor]); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; - if (width > 2) display.cachedCharWidth = width; - return width || 10; - } - - // OPERATIONS - - // Operations are used to wrap a series of changes to the editor - // state in such a way that each change won't have to update the - // cursor and display (which would be awkward, slow, and - // error-prone). Instead, display updates are batched and then all - // combined and executed at once. - - var operationGroup = null; - - var nextOpId = 0; - // Start a new operation. - function startOperation(cm) { - cm.curOp = { - cm: cm, - viewChanged: false, // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, // Used to detect need to update scrollbar - forceUpdate: false, // Used to force a redraw - updateInput: null, // Whether to reset the input textarea - typing: false, // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, // Accumulated changes, for firing change events - cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already - selectionChanged: false, // Whether the selection needs to be redrawn - updateMaxLine: false, // Set when the widest line needs to be determined anew - scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, // Used to scroll to a specific position - focus: false, - id: ++nextOpId // Unique ID - }; - if (operationGroup) { - operationGroup.ops.push(cm.curOp); - } else { - cm.curOp.ownsGroup = operationGroup = { - ops: [cm.curOp], - delayedCallbacks: [] - }; + + // When an aspect of a line changes, a string is added to + // lineView.changes. This updates the relevant part of the line's + // DOM structure. + function updateLineForChanges (cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") updateLineText(cm, lineView); + else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); + else if (type == "class") updateLineClasses(lineView); + else if (type == "widget") updateLineWidgets(cm, lineView, dims); + } + lineView.changes = null; } - } - function fireCallbacksForOps(group) { - // Calls delayed callbacks and cursorActivity handlers until no - // new ones appear - var callbacks = group.delayedCallbacks, i = 0; - do { - for (; i < callbacks.length; i++) - callbacks[i](); - for (var j = 0; j < group.ops.length; j++) { - var op = group.ops[j]; - if (op.cursorActivityHandlers) - while (op.cursorActivityCalled < op.cursorActivityHandlers.length) - op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm); - } - } while (i < callbacks.length); - } - - // Finish an operation, updating the display and signalling delayed events - function endOperation(cm) { - var op = cm.curOp, group = op.ownsGroup; - if (!group) return; - - try { fireCallbacksForOps(group); } - finally { - operationGroup = null; - for (var i = 0; i < group.ops.length; i++) - group.ops[i].cm.curOp = null; - endOperations(group); - } - } - - // The DOM updates done when an operation finishes are batched so - // that the minimum number of relayouts are required. - function endOperations(group) { - var ops = group.ops; - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_R1(ops[i]); - for (var i = 0; i < ops.length; i++) // Write DOM (maybe) - endOperation_W1(ops[i]); - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_R2(ops[i]); - for (var i = 0; i < ops.length; i++) // Write DOM (maybe) - endOperation_W2(ops[i]); - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_finish(ops[i]); - } - - function endOperation_R1(op) { - var cm = op.cm, display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) findMaxLine(cm); - - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || - op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || - op.scrollToPos.to.line >= display.viewTo) || - display.maxLineChanged && cm.options.lineWrapping; - op.update = op.mustUpdate && - new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); - } + // Lines with gutter elements, widgets or a background class need to + // be wrapped, and have the extra elements added to the wrapper div + function ensureLineWrapped (lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) {lineView.text.parentNode.replaceChild(lineView.node, lineView.text);} + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) lineView.node.style.zIndex = 2; + } + return lineView.node; + } - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } + function updateLineBackground (lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) cls += " CodeMirror-linebackground"; + if (lineView.background) { + if (cls) lineView.background.className = cls; + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + } + } - function endOperation_R2(op) { - var cm = op.cm, display = cm.display; - if (op.updatedDisplay) updateHeightsInViewport(cm); + // Wrapper around buildLineContent which will reuse the structure + // in display.externalMeasured when possible. + function getLineContent (cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } - op.barMeasure = measureForScrollbars(cm); + // Redraw the line's text. Interacts with the background and text + // classes because the mode may output tokens that influence these + // classes. + function updateLineText (cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) lineView.node = built.pre; + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(lineView); + } else if (cls) { + lineView.text.className = cls; + } + } - // If the max line changed since it was last measured, measure it, - // and ensure the document's width matches it. - // updateDisplay_W2 will use these properties to do the actual resizing - if (display.maxLineChanged && !cm.options.lineWrapping) { - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; - cm.display.sizerWidth = op.adjustWidthTo; - op.barMeasure.scrollWidth = - Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); - } - - if (op.updatedDisplay || op.selectionChanged) - op.preparedSelection = display.input.prepareSelection(); - } - - function endOperation_W2(op) { - var cm = op.cm; - - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) - setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); - cm.display.maxLineChanged = false; - } - - if (op.preparedSelection) - cm.display.input.showSelection(op.preparedSelection); - if (op.updatedDisplay) - setDocumentHeight(cm, op.barMeasure); - if (op.updatedDisplay || op.startHeight != cm.doc.height) - updateScrollbars(cm, op.barMeasure); - - if (op.selectionChanged) restartBlink(cm); - - if (cm.state.focused && op.updateInput) - cm.display.input.reset(op.typing); - if (op.focus && op.focus == activeElt()) ensureFocus(op.cm); - } - - function endOperation_finish(op) { - var cm = op.cm, display = cm.display, doc = cm.doc; - - if (op.updatedDisplay) postUpdateDisplay(cm, op.update); - - // Abort mouse wheel delta measurement, when scrolling explicitly - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) - display.wheelStartX = display.wheelStartY = null; - - // Propagate the scroll position to the actual DOM scroller - if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { - doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); - display.scrollbars.setScrollTop(doc.scrollTop); - display.scroller.scrollTop = doc.scrollTop; - } - if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { - doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft)); - display.scrollbars.setScrollLeft(doc.scrollLeft); - display.scroller.scrollLeft = doc.scrollLeft; - alignHorizontally(cm); - } - // If we need to scroll a specific position into view, do so. - if (op.scrollToPos) { - var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), - clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); - } - - // Fire events for markers that are hidden/unidden by editing or - // undoing - var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; - if (hidden) for (var i = 0; i < hidden.length; ++i) - if (!hidden[i].lines.length) signal(hidden[i], "hide"); - if (unhidden) for (var i = 0; i < unhidden.length; ++i) - if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); - - if (display.wrapper.offsetHeight) - doc.scrollTop = cm.display.scroller.scrollTop; - - // Fire change events, and delayed event handlers - if (op.changeObjs) - signal(cm, "changes", cm, op.changeObjs); - if (op.update) - op.update.finish(); - } - - // Run the given function in an operation - function runInOp(cm, f) { - if (cm.curOp) return f(); - startOperation(cm); - try { return f(); } - finally { endOperation(cm); } - } - // Wraps a function in an operation. Returns the wrapped function. - function operation(cm, f) { - return function() { - if (cm.curOp) return f.apply(cm, arguments); - startOperation(cm); - try { return f.apply(cm, arguments); } - finally { endOperation(cm); } - }; - } - // Used to add methods to editor and doc instances, wrapping them in - // operations. - function methodOp(f) { - return function() { - if (this.curOp) return f.apply(this, arguments); - startOperation(this); - try { return f.apply(this, arguments); } - finally { endOperation(this); } - }; - } - function docMethodOp(f) { - return function() { - var cm = this.cm; - if (!cm || cm.curOp) return f.apply(this, arguments); - startOperation(cm); - try { return f.apply(this, arguments); } - finally { endOperation(cm); } - }; - } + function updateLineClasses (lineView) { + updateLineBackground(lineView); + if (lineView.line.wrapClass) {ensureLineWrapped(lineView).className = lineView.line.wrapClass;} else if (lineView.node != lineView.text) {lineView.node.className = "";} + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } - // VIEW TRACKING + function updateLineGutter (cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + + "px; width: " + dims.gutterTotalWidth + "px"); + cm.display.input.setUneditable(gutterWrap); + wrap.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) {gutterWrap.className += " " + lineView.line.gutterClass;} + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { + lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + + cm.display.lineNumInnerWidth + "px")); + } + if (markers) { + for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; + if (found) { + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + } + } + } + } + } - // These objects are used to represent the visible (currently drawn) - // part of the document. A LineView may correspond to multiple - // logical lines, if those are connected by collapsed ranges. - function LineView(doc, line, lineN) { - // The starting line - this.line = line; - // Continuing lines, if any - this.rest = visualLineContinued(line); - // Number of logical lines in this visual line - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - - // Create a range of LineView objects for the given lines. - function buildViewArray(cm, from, to) { - var array = [], nextPos; - for (var pos = from; pos < to; pos = nextPos) { - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); - nextPos = pos + view.size; - array.push(view); - } - return array; - } - - // Updates the display.view data structure for a given change to the - // document. From and to are in pre-change coordinates. Lendiff is - // the amount of lines added or subtracted by the change. This is - // used for changes that span multiple lines, or change the way - // lines are divided into visual lines. regLineChange (below) - // registers single-line changes. - function regChange(cm, from, to, lendiff) { - if (from == null) from = cm.doc.first; - if (to == null) to = cm.doc.first + cm.doc.size; - if (!lendiff) lendiff = 0; - - var display = cm.display; - if (lendiff && to < display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers > from)) - display.updateLineNumbers = from; - - cm.curOp.viewChanged = true; - - if (from >= display.viewTo) { // Change after - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) - resetView(cm); - } else if (to <= display.viewFrom) { // Change before - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap - resetView(cm); - } else if (from <= display.viewFrom) { // Top overlap - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { // Bottom overlap - var cut = viewCuttingPoint(cm, from, from, -1); - if (cut) { - display.view = display.view.slice(0, cut.index); - display.viewTo = cut.lineN; - } else { - resetView(cm); - } - } else { // Gap in the middle - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index) - .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) - .concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); - } - } - - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) - ext.lineN += lendiff; - else if (from < ext.lineN + ext.size) - display.externalMeasured = null; - } - } - - // Register a change to a single line. Type must be one of "text", - // "gutter", "class", "widget" - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) - display.externalMeasured = null; - - if (line < display.viewFrom || line >= display.viewTo) return; - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) return; - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) arr.push(type); - } - - // Clear the view. - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - - // Find the view element corresponding to a given line. Return null - // when the line isn't visible. - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) return null; - n -= cm.display.viewFrom; - if (n < 0) return null; - var view = cm.display.view; - for (var i = 0; i < view.length; i++) { - n -= view[i].size; - if (n < 0) return i; - } - } - - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), diff, view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) - return {index: index, lineN: newN}; - for (var i = 0, n = cm.display.viewFrom; i < index; i++) - n += view[i].size; - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) return null; - diff = (n + view[index].size) - oldN; - index++; - } else { - diff = n - oldN; - } - oldN += diff; newN += diff; - } - while (visualLineNo(cm.doc, newN) != newN) { - if (index == (dir < 0 ? 0 : view.length - 1)) return null; - newN += dir * view[index - (dir < 0 ? 1 : 0)].size; - index += dir; - } - return {index: index, lineN: newN}; - } - - // Force the view to cover a given range, adding empty view element - // or clipping off existing ones as needed. - function adjustView(cm, from, to) { - var display = cm.display, view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) - display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); - else if (display.viewFrom < from) - display.view = display.view.slice(findViewIndex(cm, from)); - display.viewFrom = from; - if (display.viewTo < to) - display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); - else if (display.viewTo > to) - display.view = display.view.slice(0, findViewIndex(cm, to)); - } - display.viewTo = to; - } - - // Count the number of lines in the view whose DOM representation is - // out of date (or nonexistent). - function countDirtyView(cm) { - var view = cm.display.view, dirty = 0; - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; - } - return dirty; - } - - // EVENT HANDLERS - - // Attach the necessary event handlers when initializing the editor - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - // Older IE's will not fire a second mousedown for a double click - if (ie && ie_version < 11) - on(d.scroller, "dblclick", operation(cm, function(e) { - if (signalDOMEvent(cm, e)) return; - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); - else - on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); - // Some browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for these browsers. - if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); - - // Used to suppress mouse event handling when a touch happens - var touchFinished, prevTouch = {end: 0}; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); - prevTouch = d.activeTouch; - prevTouch.end = +new Date; - } - }; - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) return false; - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1; - } - function farAway(touch, other) { - if (other.left == null) return true; - var dx = other.left - touch.left, dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20; - } - on(d.scroller, "touchstart", function(e) { - if (!isMouseLikeTouchEvent(e)) { - clearTimeout(touchFinished); - var now = +new Date; - d.activeTouch = {start: now, moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null}; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; - } - } - }); - on(d.scroller, "touchmove", function() { - if (d.activeTouch) d.activeTouch.moved = true; - }); - on(d.scroller, "touchend", function(e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && - !touch.moved && new Date - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), range; - if (!touch.prev || farAway(touch, touch.prev)) // Single tap - range = new Range(pos, pos); - else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap - range = cm.findWordAt(pos); - else // Triple tap - range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); - cm.setSelection(range.anchor, range.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - - // Sync scrolling between fake scrollbars and real scrollable - // area, ensure viewport is updated when scrolling. - on(d.scroller, "scroll", function() { - if (d.scroller.clientHeight) { - setScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); + function updateLineWidgets (cm, lineView, dims) { + if (lineView.alignable) lineView.alignable = null; + for (var node = lineView.node.firstChild, next; node; node = next) { + var next = node.nextSibling; + if (node.className == "CodeMirror-linewidget") {lineView.node.removeChild(node);} + } + insertLineWidgets(cm, lineView, dims); + } - // Listen to wheel events in order to try and update the viewport on time. - on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); - on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); + // Build a line's DOM representation from scratch + function buildLineElement (cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) lineView.bgClass = built.bgClass; + if (built.textClass) lineView.textClass = built.textClass; - // Prevent wrapper from ever scrolling - on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + updateLineClasses(lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } - d.dragFunctions = { - simple: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, - start: function(e){onDragStart(cm, e);}, - drop: operation(cm, onDrop) - }; + // A lineView may contain multiple logical lines (when merged by + // collapsed spans). The widgets for all of them need to be drawn. + function insertLineWidgets (cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { + for (var i = 0; i < lineView.rest.length; i++) {insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);} + } + } - var inp = d.input.getField(); - on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", bind(onFocus, cm)); - on(inp, "blur", bind(onBlur, cm)); - } - - function dragDropChanged(cm, value, old) { - var wasOn = old && old != CodeMirror.Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.simple); - toggle(cm.display.scroller, "dragover", funcs.simple); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - - // Called when the window resizes - function onResize(cm) { - var d = cm.display; - if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) - return; - // Might be a text scaling operation, clear size caches. - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - - // MOUSE EVENTS - - // Return true when the given mouse event happened in a widget - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || - (n.parentNode == display.sizer && n != display.mover)) - return true; + function insertLineWidgetsFor (cm, line, lineView, dims, allowAbove) { + if (!line.widgets) return; + var wrap = ensureLineWrapped(lineView); + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); + if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) {wrap.insertBefore(node, lineView.gutter || lineView.text);} else {wrap.appendChild(node);} + signalLater(widget, "redraw"); + } } - } - - // Given a mouse event, find the corresponding position. If liberal - // is false, it checks whether a gutter or scrollbar was clicked, - // and returns null if it was. forRect is used by rectangular - // selections, and tries to estimate a character position even for - // coordinates beyond the right of the text. - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; - - var x, y, space = display.lineSpace.getBoundingClientRect(); - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX - space.left; y = e.clientY - space.top; } - catch (e) { return null; } - var coords = coordsChar(cm, x, y), line; - if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords; - } - - // A mouse down can be a single click, double click, triple click, - // start of selection drag, start of text drag, new cursor - // (ctrl-click), rectangle drag (alt-drag), or xwin - // middle-click-paste. Or it might be a click on something we should - // not interfere with, such as a scrollbar or widget. - function onMouseDown(e) { - var cm = this, display = cm.display; - if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return; - display.shift = e.shiftKey; - - if (eventInWidget(display, e)) { - if (!webkit) { - // Briefly turn off draggability, to allow widgets to do - // normal dragging things. - display.scroller.draggable = false; - setTimeout(function(){display.scroller.draggable = true;}, 100); - } - return; - } - if (clickInGutter(cm, e)) return; - var start = posFromMouse(cm, e); - window.focus(); - - switch (e_button(e)) { - case 1: - if (start) - leftButtonDown(cm, e, start); - else if (e_target(e) == display.scroller) - e_preventDefault(e); - break; - case 2: - if (webkit) cm.state.lastMiddleDown = +new Date; - if (start) extendSelection(cm.doc, start); - setTimeout(function() {display.input.focus();}, 20); - e_preventDefault(e); - break; - case 3: - if (captureRightClick) onContextMenu(cm, e); - else delayBlurEvent(cm); - break; - } - } - - var lastClick, lastDoubleClick; - function leftButtonDown(cm, e, start) { - if (ie) setTimeout(bind(ensureFocus, cm), 0); - else cm.curOp.focus = activeElt(); - - var now = +new Date, type; - if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { - type = "triple"; - } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { - type = "double"; - lastDoubleClick = {time: now, pos: start}; - } else { - type = "single"; - lastClick = {time: now, pos: start}; + + function positionLineWidget (widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } } - var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; - if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && - type == "single" && (contained = sel.contains(start)) > -1 && - (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && - (cmp(contained.to(), start) > 0 || start.xRel < 0)) - leftButtonStartDrag(cm, e, start, modifier); - else - leftButtonSelect(cm, e, start, type, modifier); - } - - // Start a text drag. When it ends, see if any dragging actually - // happen, and treat as a click if it didn't. - function leftButtonStartDrag(cm, e, start, modifier) { - var display = cm.display, startTime = +new Date; - var dragEnd = operation(cm, function(e2) { - if (webkit) display.scroller.draggable = false; - cm.state.draggingText = false; - off(document, "mouseup", dragEnd); - off(display.scroller, "drop", dragEnd); - if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { - e_preventDefault(e2); - if (!modifier && +new Date - 200 < startTime) - extendSelection(cm.doc, start); - // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) - if (webkit || ie && ie_version == 9) - setTimeout(function() {document.body.focus(); display.input.focus();}, 20); - else - display.input.focus(); - } - }); - // Let the drag handler handle this. - if (webkit) display.scroller.draggable = true; - cm.state.draggingText = dragEnd; - // IE's approach to draggable - if (display.scroller.dragDrop) display.scroller.dragDrop(); - on(document, "mouseup", dragEnd); - on(display.scroller, "drop", dragEnd); - } - - // Normal selection, as opposed to text dragging. - function leftButtonSelect(cm, e, start, type, addNew) { - var display = cm.display, doc = cm.doc; - e_preventDefault(e); - - var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; - if (addNew && !e.shiftKey) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) - ourRange = ranges[ourIndex]; - else - ourRange = new Range(start, start); - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - - if (e.altKey) { - type = "rect"; - if (!addNew) ourRange = new Range(start, start); - start = posFromMouse(cm, e, true, true); - ourIndex = -1; - } else if (type == "double") { - var word = cm.findWordAt(start); - if (cm.display.shift || doc.extend) - ourRange = extendRange(doc, ourRange, word.anchor, word.head); - else - ourRange = word; - } else if (type == "triple") { - var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); - if (cm.display.shift || doc.extend) - ourRange = extendRange(doc, ourRange, line.anchor, line.head); - else - ourRange = line; - } else { - ourRange = extendRange(doc, ourRange, start); - } - - if (!addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), - {scroll: false, origin: "*mouse"}); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { - setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0)); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) return; - lastPos = pos; - - if (type == "rect") { - var ranges = [], tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); - line <= end; line++) { - var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); - if (left == right) - ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); - else if (text.length > leftPos) - ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); - } - if (!ranges.length) ranges.push(new Range(start, start)); - setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), - {origin: "*mouse", scroll: false}); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var anchor = oldRange.anchor, head = pos; - if (type != "single") { - if (type == "double") - var range = cm.findWordAt(pos); - else - var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); - if (cmp(range.anchor, anchor) > 0) { - head = range.head; - anchor = minPos(oldRange.from(), range.anchor); - } else { - head = range.anchor; - anchor = maxPos(oldRange.to(), range.head); - } - } - var ranges = startSel.ranges.slice(0); - ranges[ourIndex] = new Range(clipPos(doc, anchor), head); - setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); - } - } - - var editorSize = display.wrapper.getBoundingClientRect(); - // Used to ensure timeout re-tries don't fire when another extend - // happened in the meantime (clearTimeout isn't reliable -- at - // least on Chrome, the timeouts still happen even when cleared, - // if the clear happens after their scheduled firing time). - var counter = 0; - - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, type == "rect"); - if (!cur) return; - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) - setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) setTimeout(operation(cm, function() { - if (counter != curCount) return; - display.scroller.scrollTop += outside; - extend(e); - }), 50); - } - } - - function done(e) { - counter = Infinity; - e_preventDefault(e); - display.input.focus(); - off(document, "mousemove", move); - off(document, "mouseup", up); - doc.history.lastSelOrigin = null; - } - - var move = operation(cm, function(e) { - if (!e_button(e)) done(e); - else extend(e); - }); - var up = operation(cm, done); - on(document, "mousemove", move); - on(document, "mouseup", up); - } - - // Determines whether an event happened in the gutter, and fires the - // handlers for the corresponding event. - function gutterEvent(cm, e, type, prevent, signalfn) { - try { var mX = e.clientX, mY = e.clientY; } - catch(e) { return false; } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; - if (prevent) e_preventDefault(e); - - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - - if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); - mY -= lineBox.top - display.viewOffset; - - for (var i = 0; i < cm.options.gutters.length; ++i) { - var g = display.gutters.childNodes[i]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.options.gutters[i]; - signalfn(cm, type, cm, line, gutter, e); - return e_defaultPrevented(e); - } - } - } - - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true, signalLater); - } - - // Kludge to work around strange IE behavior where it'll sometimes - // re-fire a series of drag-related events right after the drop (#1551) - var lastDrop = 0; - - function onDrop(e) { - var cm = this; - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) - return; - e_preventDefault(e); - if (ie) lastDrop = +new Date; - var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; - if (!pos || isReadOnly(cm)) return; - // Might be a file drop, in which case we simply extract the text - // and insert it. - if (files && files.length && window.FileReader && window.File) { - var n = files.length, text = Array(n), read = 0; - var loadFile = function(file, i) { - var reader = new FileReader; - reader.onload = operation(cm, function() { - text[i] = reader.result; - if (++read == n) { - pos = clipPos(cm.doc, pos); - var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); - } - }); - reader.readAsText(file); - }; - for (var i = 0; i < n; ++i) loadFile(files[i], i); - } else { // Normal drop - // Don't do a replace if the drop happened inside of the selected text. - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - // Ensure the editor is re-focused - setTimeout(function() {cm.display.input.focus();}, 20); - return; - } - try { - var text = e.dataTransfer.getData("Text"); - if (text) { - if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) - var selected = cm.listSelections(); - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) for (var i = 0; i < selected.length; ++i) - replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); - cm.replaceSelection(text, "around", "paste"); - cm.display.input.focus(); - } - } - catch(e){} - } - } - - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; - - e.dataTransfer.setData("Text", cm.getSelection()); - - // Use dummy image instead of default browsers image. - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - // Force a relayout, or Opera won't use our image for some obscure reason - img._top = img.offsetTop; - } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) img.parentNode.removeChild(img); - } - } - - // SCROLL EVENTS - - // Sync the scrollable area and scrollbars, ensure the viewport - // covers the visible area. - function setScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) return; - cm.doc.scrollTop = val; - if (!gecko) updateDisplaySimple(cm, {top: val}); - if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (gecko) updateDisplaySimple(cm); - startWorker(cm, 100); - } - // Sync scroller and scrollbar, ensure the gutter elements are - // aligned. - function setScrollLeft(cm, val, isScroller) { - if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; - val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; - cm.display.scrollbars.setScrollLeft(val); - } - - // Since the delta values reported on mouse wheel events are - // unstandardized between browsers and even browser versions, and - // generally horribly unpredictable, this code starts by measuring - // the scroll effect that the first few mouse wheel events have, - // and, from that, detects the way it can convert deltas to pixel - // offsets afterwards. - // - // The reason we want to know the amount a wheel event will scroll - // is that it gives us a chance to update the display before the - // actual scrolling happens, reducing flickering. - - var wheelSamples = 0, wheelPixelsPerUnit = null; - // Fill in a browser-detected starting value on browsers where we - // know one. These don't have to be accurate -- the result of them - // being wrong would just be a slight flicker on the first wheel - // scroll (if it is large enough). - if (ie) wheelPixelsPerUnit = -.53; - else if (gecko) wheelPixelsPerUnit = 15; - else if (chrome) wheelPixelsPerUnit = -.7; - else if (safari) wheelPixelsPerUnit = -1/3; - - var wheelEventDelta = function(e) { - var dx = e.wheelDeltaX, dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; - else if (dy == null) dy = e.wheelDelta; - return {x: dx, y: dy}; - }; - CodeMirror.wheelEventPixels = function(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta; - }; - - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; - - var display = cm.display, scroll = display.scroller; - // Quit if there's nothing to scroll here - if (!(dx && scroll.scrollWidth > scroll.clientWidth || - dy && scroll.scrollHeight > scroll.clientHeight)) return; + // POSITION OBJECT - // Webkit browsers on OS X abort momentum scrolls when the target - // of the scroll event is removed from the scrollable element. - // This hack (see related code in patchDisplay) makes sure the - // element is kept around. - if (dy && mac && webkit) { - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { - for (var i = 0; i < view.length; i++) { - if (view[i].node == cur) { - cm.display.currentWheelTarget = cur; - break outer; - } - } - } - } - - // On some browsers, horizontal scrolling will cause redraws to - // happen before the gutter has been realigned, causing it to - // wriggle around in a most unseemly way. When we have an - // estimated pixels/delta value, we just handle horizontal - // scrolling entirely here. It'll be slightly off from native, but - // better than glitching out. - if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { - if (dy) - setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); - setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); - e_preventDefault(e); - display.wheelStartX = null; // Abort measurement, if in progress - return; - } - - // 'Project' the visible viewport to cover the area that is being - // scrolled into view (if we know enough to estimate it). - if (dy && wheelPixelsPerUnit != null) { - var pixels = dy * wheelPixelsPerUnit; - var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; - if (pixels < 0) top = Math.max(0, top + pixels - 50); - else bot = Math.min(cm.doc.height, bot + pixels + 50); - updateDisplaySimple(cm, {top: top, bottom: bot}); - } - - if (wheelSamples < 20) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; display.wheelDY = dy; - setTimeout(function() { - if (display.wheelStartX == null) return; - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || - (movedX && display.wheelDX && movedX / display.wheelDX); - display.wheelStartX = display.wheelStartY = null; - if (!sample) return; - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; display.wheelDY += dy; - } - } - } - - // KEY EVENTS - - // Run a handler that was bound to a key. - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) return false; - } - // Ensure previous input has been read, so that the handler sees a - // consistent view of the document - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, done = false; - try { - if (isReadOnly(cm)) cm.state.suppressEdits = true; - if (dropShift) cm.display.shift = false; - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; - } - return done; - } - - function lookupKeyForEditor(cm, name, handle) { - for (var i = 0; i < cm.state.keyMaps.length; i++) { - var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); - if (result) return result; - } - return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) - || lookupKey(name, cm.options.keyMap, handle, cm); - } - - var stopSeq = new Delayed; - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) return "handled"; - stopSeq.set(50, function() { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); - name = seq + " " + name; - } - var result = lookupKeyForEditor(cm, name, handle); - - if (result == "multi") - cm.state.keySeq = name; - if (result == "handled") - signalLater(cm, "keyHandled", cm, name, e); - - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - - if (seq && !result && /\'$/.test(name)) { - e_preventDefault(e); - return true; - } - return !!result; - } - - // Handle a key from the keydown event. - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) return false; - - if (e.shiftKey && !cm.state.keySeq) { - // First try to resolve full name (including 'Shift-'). Failing - // that, see if there is a cursor-motion command (starting with - // 'go') bound to the keyname without 'Shift-'. - return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) - || dispatchKey(cm, name, e, function(b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) - return doHandleBinding(cm, b); - }); - } else { - return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); - } - } - - // Handle a key from the keypress event - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, - function(b) { return doHandleBinding(cm, b, true); }); - } - - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) return; - // IE does strange things with escape. - if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) - cm.replaceSelection("", null, "cut"); - } - - // Turn mouse into crosshair when Alt is held on Mac. - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) - showCrossHair(cm); - } - - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); - } - - function onKeyUp(e) { - if (e.keyCode == 16) this.doc.sel.shift = false; - signalDOMEvent(this, e); - } - - function onKeyPress(e) { - var cm = this; - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; - var keyCode = e.keyCode, charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} - if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (handleCharBinding(cm, e, ch)) return; - cm.display.input.onKeyPress(e); - } - - // FOCUS/BLUR EVENTS - - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function() { - if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - onBlur(cm); - } - }, 100); - } - - function onFocus(cm) { - if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; - - if (cm.options.readOnly == "nocursor") return; - if (!cm.state.focused) { - signal(cm, "focus", cm); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - // This test prevents this from firing when a context - // menu is closed (since the input reset would kill the - // select-all detection hack) - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 - } - cm.display.input.receivedFocus(); - } - restartBlink(cm); - } - function onBlur(cm) { - if (cm.state.delayingBlurEvent) return; - - if (cm.state.focused) { - signal(cm, "blur", cm); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); - } - clearInterval(cm.display.blinker); - setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); - } - - // CONTEXT MENU HANDLING - - // To make the context menu work, we need to briefly unhide the - // textarea (making it as unobtrusive as possible) to let the - // right-click take effect on it. - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; - cm.display.input.onContextMenu(e); - } - - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) return false; - return gutterEvent(cm, e, "gutterContextMenu", false, signal); - } - - // UPDATING - - // Compute the position of the end of a change (its 'to' property - // refers to the pre-change end). - var changeEnd = CodeMirror.changeEnd = function(change) { - if (!change.text) return change.to; - return Pos(change.from.line + change.text.length - 1, - lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); - }; - - // Adjust a position to refer to the post-change position of the - // same text, or the end of the change if the change covers it. - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) return pos; - if (cmp(pos, change.to) <= 0) return changeEnd(change); - - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; - if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; - return Pos(line, ch); - } - - function computeSelAfterChange(doc, change) { - var out = []; - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - out.push(new Range(adjustForChange(range.anchor, change), - adjustForChange(range.head, change))); - } - return normalizeSelection(out, doc.sel.primIndex); - } - - function offsetPos(pos, old, nw) { - if (pos.line == old.line) - return Pos(nw.line, pos.ch - old.ch + nw.ch); - else - return Pos(nw.line + (pos.line - old.line), pos.ch); - } - - // Used by replaceSelections to allow moving the selection to the - // start or around the replaced test. Hint may be "start" or "around". - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; - out[i] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i] = new Range(from, from); - } - } - return new Selection(out, doc.sel.primIndex); - } - - // Allow "beforeChange" event handlers to influence a change - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function() { this.canceled = true; } - }; - if (update) obj.update = function(from, to, text, origin) { - if (from) this.from = clipPos(doc, from); - if (to) this.to = clipPos(doc, to); - if (text) this.text = text; - if (origin !== undefined) this.origin = origin; + // A Pos instance represents a position within the text. + var Pos = CodeMirror.Pos = function (line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; }; - signal(doc, "beforeChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); - if (obj.canceled) return null; - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; - } + // Compare two positions, return 0 if they are the same, a negative + // number when a is less, and a positive number otherwise. + var cmp = CodeMirror.cmpPos = function (a, b) { return a.line - b.line || a.ch - b.ch; }; - // Apply a change to a document, and add it to the document's - // history, and propagating it to all linked documents. - function makeChange(doc, change, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); - if (doc.cm.state.suppressEdits) return; - } + function copyPos (x) {return Pos(x.line, x.ch);} + function maxPos (a, b) { return cmp(a, b) < 0 ? b : a; } + function minPos (a, b) { return cmp(a, b) < 0 ? a : b; } - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) return; - } + // INPUT HANDLING - // Possibly split or suppress the update based on the presence - // of read-only spans in its range. - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i = split.length - 1; i >= 0; --i) - makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); - } else { - makeChangeInner(doc, change); + function ensureFocus (cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } } - } - - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; - - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); - }); - } - - // Revert a change stored in a document's history. - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - if (doc.cm && doc.cm.state.suppressEdits) return; - - var hist = doc.history, event, selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; - - // Verify that there is a useable event (so that ctrl-z won't - // needlessly clear selection events) - for (var i = 0; i < source.length; i++) { - event = source[i]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) - break; - } - if (i == source.length) return; - hist.lastOrigin = hist.lastSelOrigin = null; - - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, {clearRedo: false}); - return; - } - selAfter = event; - } - else break; - } - - // Build up a reverse change object to add to the opposite history - // stack (redo when undoing, and vice versa). - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({changes: antiChanges, generation: hist.generation}); - hist.generation = event.generation || ++hist.maxGeneration; - - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - - for (var i = event.changes.length - 1; i >= 0; --i) { - var change = event.changes[i]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return; - } - - antiChanges.push(historyChangeFromChange(doc, change)); - - var after = i ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); - var rebased = []; - - // Propagate to the linked documents - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); - }); - } - } - - // Sub-views need their line numbers shifted when text is added - // above or below them in the parent document. - function shiftDoc(doc, distance) { - if (distance == 0) return; - doc.first += distance; - doc.sel = new Selection(map(doc.sel.ranges, function(range) { - return new Range(Pos(range.anchor.line + distance, range.anchor.ch), - Pos(range.head.line + distance, range.head.ch)); - }), doc.sel.primIndex); - if (doc.cm) { - regChange(doc.cm, doc.first, doc.first - distance, distance); - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) - regLineChange(doc.cm, l, "gutter"); - } - } - - // More lower-level change function, handling only a single document - // (not linked ones). - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) - return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); - - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return; - } - if (change.from.line > doc.lastLine()) return; - - // Clip the change to the size of this doc - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], origin: change.origin}; + function isReadOnly (cm) { + return cm.options.readOnly || cm.doc.cantEdit; } - var last = doc.lastLine(); - if (change.to.line > last) { - change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], origin: change.origin}; - } - - change.removed = getBetween(doc, change.from, change.to); - - if (!selAfter) selAfter = computeSelAfterChange(doc, change); - if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); - else updateDoc(doc, change, spans); - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - } - - // Handle the interaction of a change to a document with the editor - // that this document is part of. - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, display = cm.display, from = change.from, to = change.to; - - var recomputeMaxLength = false, checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function(line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true; - } - }); - } - - if (doc.sel.contains(change.from, change.to) > -1) - signalCursorActivity(cm); - - updateDoc(doc, change, spans, estimateHeight(cm)); - - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function(line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) cm.curOp.updateMaxLine = true; - } - - // Adjust frontier, schedule worker - doc.frontier = Math.min(doc.frontier, from.line); - startWorker(cm, 400); - - var lendiff = change.text.length - (to.line - from.line) - 1; - // Remember that these lines changed, for updating the display - if (change.full) - regChange(cm); - else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) - regLineChange(cm, from.line, "text"); - else - regChange(cm, from.line, to.line + 1, lendiff); - - var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from: from, to: to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) signalLater(cm, "change", cm, obj); - if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); - } - cm.display.selForContextMenu = null; - } - - function replaceRange(doc, code, from, to, origin) { - if (!to) to = from; - if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } - if (typeof code == "string") code = splitLines(code); - makeChange(doc, {from: from, to: to, text: code, origin: origin}); - } - - // SCROLLING THINGS INTO VIEW - - // If an editor sits on the top or bottom of the window, partially - // scrolled out of view, this ensures that the cursor is visible. - function maybeScrollWindow(cm, coords) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) return; - - var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; - if (coords.top + box.top < 0) doScroll = true; - else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + - (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + - (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + - coords.left + "px; width: 2px;"); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); - } - } - - // Scroll a given position into view (immediately), verifying that - // it actually became visible (as line heights are accurately - // measured, the position of something may 'drift' during drawing). - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) margin = 0; - for (var limit = 0; limit < 5; limit++) { - var changed = false, coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), - Math.min(coords.top, endCoords.top) - margin, - Math.max(coords.left, endCoords.left), - Math.max(coords.bottom, endCoords.bottom) + margin); - var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - setScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; - } - if (!changed) break; - } - return coords; - } - - // Scroll a given set of coordinates into view (immediately). - function scrollIntoView(cm, x1, y1, x2, y2) { - var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); - if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); - if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); - } - - // Calculate a new scroll position needed to scroll the given - // rectangle into view. Returns an object with scrollTop and - // scrollLeft properties. When these are undefined, the - // vertical/horizontal position does not need to be adjusted. - function calculateScrollPos(cm, x1, y1, x2, y2) { - var display = cm.display, snapMargin = textHeight(cm.display); - if (y1 < 0) y1 = 0; - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen = displayHeight(cm), result = {}; - if (y2 - y1 > screen) y2 = y1 + screen; - var docBottom = cm.doc.height + paddingVert(display); - var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; - if (y1 < screentop) { - result.scrollTop = atTop ? 0 : y1; - } else if (y2 > screentop + screen) { - var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); - if (newTop != screentop) result.scrollTop = newTop; - } - - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; - var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); - var tooWide = x2 - x1 > screenw; - if (tooWide) x2 = x1 + screenw; - if (x1 < 10) - result.scrollLeft = 0; - else if (x1 < screenleft) - result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); - else if (x2 > screenw + screenleft - 3) - result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; - return result; - } - - // Store a relative adjustment to the scroll position in the current - // operation (to be applied when the operation finishes). - function addToScrollPos(cm, left, top) { - if (left != null || top != null) resolveScrollToPos(cm); - if (left != null) - cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; - if (top != null) - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - - // Make sure that at the end of the operation the current cursor is - // shown. - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(), from = cur, to = cur; - if (!cm.options.lineWrapping) { - from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; - to = Pos(cur.line, cur.ch + 1); - } - cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; - } - - // When an operation has its scrollToPos property set, and another - // scroll action is applied before the end of the operation, this - // 'simulates' scrolling that position into view in a cheap way, so - // that the effect of intermediate scroll commands is not ignored. - function resolveScrollToPos(cm) { - var range = cm.curOp.scrollToPos; - if (range) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); - var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), - Math.min(from.top, to.top) - range.margin, - Math.max(from.right, to.right), - Math.max(from.bottom, to.bottom) + range.margin); - cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); - } - } - - // API UTILITIES - - // Indent the given line. The how parameter can be "smart", - // "add"/null, "subtract", or "prev". When aggressive is false - // (typically set to true for forced single-line indents), empty - // lines are not indented, and places where the mode returns Pass - // are left alone. - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, state; - if (how == null) how = "add"; - if (how == "smart") { - // Fall back to "prev" when the mode doesn't have an indentation - // method. - if (!doc.mode.indent) how = "prev"; - else state = getStateBefore(cm, n); - } - - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) line.stateAfter = null; - var curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) return; - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); - else indentation = 0; - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - - var indentString = "", pos = 0; - if (cm.options.indentWithTabs) - for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} - if (pos < indentation) indentString += spaceStr(indentation - pos); - - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true; - } else { - // Ensure that, if the cursor was in the whitespace at the start - // of the line, it is moved to the end of that space. - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - if (range.head.line == n && range.head.ch < curSpaceString.length) { - var pos = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i, new Range(pos, pos)); - break; - } - } - } - } - - // Utility for applying a change to a line by handle or number, - // returning the number and optionally registering the line as - // changed. - function changeLine(doc, handle, changeType, op) { - var no = handle, line = handle; - if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); - else no = lineNo(handle); - if (no == null) return null; - if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); - return line; - } - - // Helper for deleting text near the selection(s), used to implement - // backspace, delete, and similar functionality. - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, kill = []; - // Build up a set of ranges to kill first, merging overlapping - // ranges. - for (var i = 0; i < ranges.length; i++) { - var toKill = compute(ranges[i]); - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { - var replaced = kill.pop(); - if (cmp(replaced.from, toKill.from) < 0) { - toKill.from = replaced.from; - break; - } - } - kill.push(toKill); - } - // Next, remove those actual ranges. - runInOp(cm, function() { - for (var i = kill.length - 1; i >= 0; i--) - replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); - ensureCursorVisible(cm); - }); - } - - // Used for horizontal relative motion. Dir is -1 or 1 (left or - // right), unit can be "char", "column" (like char, but doesn't - // cross line boundaries), "word" (across next word), or "group" (to - // the start of next group of word or non-word-non-whitespace - // chars). The visually param controls whether, in right-to-left - // text, direction 1 means to move towards the next index in the - // string, or towards the character to the right of the current - // position. The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosH(doc, pos, dir, unit, visually) { - var line = pos.line, ch = pos.ch, origDir = dir; - var lineObj = getLine(doc, line); - var possible = true; - function findNextLine() { - var l = line + dir; - if (l < doc.first || l >= doc.first + doc.size) return (possible = false); - line = l; - return lineObj = getLine(doc, l); - } - function moveOnce(boundToLine) { - var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); - if (next == null) { - if (!boundToLine && findNextLine()) { - if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); - else ch = dir < 0 ? lineObj.text.length : 0; - } else return (possible = false); - } else ch = next; - return true; - } - - if (unit == "char") moveOnce(); - else if (unit == "column") moveOnce(true); - else if (unit == "word" || unit == "group") { - var sawType = null, group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) break; - var cur = lineObj.text.charAt(ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" - : group && cur == "\n" ? "n" - : !group || /\s/.test(cur) ? null - : "p"; - if (group && !first && !type) type = "s"; - if (sawType && sawType != type) { - if (dir < 0) {dir = 1; moveOnce();} - break; - } - - if (type) sawType = type; - if (dir > 0 && !moveOnce(!first)) break; - } - } - var result = skipAtomic(doc, Pos(line, ch), origDir, true); - if (!possible) result.hitSide = true; - return result; - } - - // For relative vertical movement. Dir may be -1 or 1. Unit can be - // "page" or "line". The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, x = pos.left, y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - for (;;) { - var target = coordsChar(cm, x, y); - if (!target.outside) break; - if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } - y += dir * 5; - } - return target; - } - - // EDITOR METHODS - - // The publicly visible API. Note that methodOp(f) means - // 'wrap f in an operation, performed on its `this` parameter'. - - // This is not the complete set of editor methods. Most of the - // methods defined on the Doc type are also injected into - // CodeMirror.prototype, for backwards compatibility and - // convenience. - - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function(){window.focus(); this.display.input.focus();}, - - setOption: function(option, value) { - var options = this.options, old = options[option]; - if (options[option] == value && option != "mode") return; - options[option] = value; - if (optionHandlers.hasOwnProperty(option)) - operation(this, optionHandlers[option])(this, value, old); - }, - - getOption: function(option) {return this.options[option];}, - getDoc: function() {return this.doc;}, - - addKeyMap: function(map, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); - }, - removeKeyMap: function(map) { - var maps = this.state.keyMaps; - for (var i = 0; i < maps.length; ++i) - if (maps[i] == map || maps[i].name == map) { - maps.splice(i, 1); - return true; - } - }, - - addOverlay: methodOp(function(spec, options) { - var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); - if (mode.startState) throw new Error("Overlays may not be stateful."); - this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function(spec) { - var overlays = this.state.overlays; - for (var i = 0; i < overlays.length; ++i) { - var cur = overlays[i].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i, 1); - this.state.modeGen++; - regChange(this); - return; - } - } - }), - - indentLine: methodOp(function(n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; - else dir = dir ? "add" : "subtract"; - } - if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); - }), - indentSelection: methodOp(function(how) { - var ranges = this.doc.sel.ranges, end = -1; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (!range.empty()) { - var from = range.from(), to = range.to(); - var start = Math.max(end, from.line); - end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) - indentLine(this, j, how); - var newRanges = this.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) - replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); - } else if (range.head.line > end) { - indentLine(this, range.head.line, how, true); - end = range.head.line; - if (i == this.doc.sel.primIndex) ensureCursorVisible(this); - } - } - }), - - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(pos, precise) { - return takeToken(this, pos, precise); - }, - - getLineTokens: function(line, precise) { - return takeToken(this, Pos(line), precise, true); - }, - - getTokenTypeAt: function(pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; - var type; - if (ch == 0) type = styles[2]; - else for (;;) { - var mid = (before + after) >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; - else if (styles[mid * 2 + 1] < ch) before = mid + 1; - else { type = styles[mid * 2 + 2]; break; } - } - var cut = type ? type.indexOf("cm-overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); - }, - - getModeAt: function(pos) { - var mode = this.doc.mode; - if (!mode.innerMode) return mode; - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; - }, - - getHelper: function(pos, type) { - return this.getHelpers(pos, type)[0]; - }, - - getHelpers: function(pos, type) { - var found = []; - if (!helpers.hasOwnProperty(type)) return found; - var help = helpers[type], mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) found.push(help[mode[type]]); - } else if (mode[type]) { - for (var i = 0; i < mode[type].length; i++) { - var val = help[mode[type][i]]; - if (val) found.push(val); - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i = 0; i < help._global.length; i++) { - var cur = help._global[i]; - if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) - found.push(cur.val); - } - return found; - }, - - getStateAfter: function(line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); - return getStateBefore(this, line + 1, precise); - }, - - cursorCoords: function(start, mode) { - var pos, range = this.doc.sel.primary(); - if (start == null) pos = range.head; - else if (typeof start == "object") pos = clipPos(this.doc, start); - else pos = start ? range.from() : range.to(); - return cursorCoords(this, pos, mode || "page"); - }, - - charCoords: function(pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page"); - }, - - coordsChar: function(coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); - }, - - lineAtHeight: function(height, mode) { - height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset); - }, - heightAtLine: function(line, mode) { - var end = false, lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) line = this.doc.first; - else if (line > last) { line = last; end = true; } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + - (end ? this.doc.height - heightAtLine(lineObj) : 0); - }, - defaultTextHeight: function() { return textHeight(this.display); }, - defaultCharWidth: function() { return charWidth(this.display); }, + // This will be set to an array of strings when copying, so that, + // when pasting, we know what kind of selections the copied text + // was made out of. + var lastCopied = null; - setGutterMarker: methodOp(function(line, gutterID, value) { - return changeLine(this.doc, line, "gutter", function(line) { - var markers = line.gutterMarkers || (line.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) line.gutterMarkers = null; - return true; - }); - }), - - clearGutter: methodOp(function(gutterID) { - var cm = this, doc = cm.doc, i = doc.first; - doc.iter(function(line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - line.gutterMarkers[gutterID] = null; - regLineChange(cm, i, "gutter"); - if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; - } - ++i; - }); - }), - - lineInfo: function(line) { - if (typeof line == "number") { - if (!isLine(this.doc, line)) return null; - var n = line; - line = getLine(this.doc, line); - if (!line) return null; - } else { - var n = lineNo(line); - if (n == null) return null; - } - return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, - textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, - widgets: line.widgets}; - }, - - getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, - - addWidget: function(pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - // Default to positioning above (if specified and possible); otherwise default to positioning below - if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) - top = pos.top - node.offsetHeight; - else if (pos.bottom + node.offsetHeight <= vspace) - top = pos.bottom; - if (left + node.offsetWidth > hspace) - left = hspace - node.offsetWidth; - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") left = 0; - else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; - node.style.left = left + "px"; - } - if (scroll) - scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); - }, - - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - - execCommand: function(cmd) { - if (commands.hasOwnProperty(cmd)) - return commands[cmd](this); - }, - - triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), - - findPosH: function(from, amount, unit, visually) { - var dir = 1; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) break; - } - return cur; - }, - - moveH: methodOp(function(dir, unit) { - var cm = this; - cm.extendSelectionsBy(function(range) { - if (cm.display.shift || cm.doc.extend || range.empty()) - return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); - else - return dir < 0 ? range.from() : range.to(); - }, sel_move); - }), - - deleteH: methodOp(function(dir, unit) { - var sel = this.doc.sel, doc = this.doc; - if (sel.somethingSelected()) - doc.replaceSelection("", null, "+delete"); - else - deleteNearSelection(this, function(range) { - var other = findPosH(doc, range.head, dir, unit, false); - return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; - }); - }), - - findPosV: function(from, amount, unit, goalColumn) { - var dir = 1, x = goalColumn; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) x = coords.left; - else coords.left = x; - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) break; - } - return cur; - }, - - moveV: methodOp(function(dir, unit) { - var cm = this, doc = this.doc, goals = []; - var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function(range) { - if (collapse) - return dir < 0 ? range.from() : range.to(); - var headPos = cursorCoords(cm, range.head, "div"); - if (range.goalColumn != null) headPos.left = range.goalColumn; - goals.push(headPos.left); - var pos = findPosV(cm, headPos, dir, unit); - if (unit == "page" && range == doc.sel.primary()) - addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); - return pos; - }, sel_move); - if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) - doc.sel.ranges[i].goalColumn = goals[i]; - }), - - // Find the word at the given position (as returned by coordsChar). - findWordAt: function(pos) { - var doc = this.doc, line = getLine(doc, pos.line).text; - var start = pos.ch, end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) - ? function(ch) { return isWordChar(ch, helper); } - : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} - : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; - while (start > 0 && check(line.charAt(start - 1))) --start; - while (end < line.length && check(line.charAt(end))) ++end; - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)); - }, - - toggleOverwrite: function(value) { - if (value != null && value == this.state.overwrite) return; - if (this.state.overwrite = !this.state.overwrite) - addClass(this.display.cursorDiv, "CodeMirror-overwrite"); - else - rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); - - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function() { return this.display.input.getField() == activeElt(); }, - - scrollTo: methodOp(function(x, y) { - if (x != null || y != null) resolveScrollToPos(this); - if (x != null) this.curOp.scrollLeft = x; - if (y != null) this.curOp.scrollTop = y; - }), - getScrollInfo: function() { - var scroller = this.display.scroller; - return {left: scroller.scrollLeft, top: scroller.scrollTop, - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, - clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; - }, - - scrollIntoView: methodOp(function(range, margin) { - if (range == null) { - range = {from: this.doc.sel.primary().head, to: null}; - if (margin == null) margin = this.options.cursorScrollMargin; - } else if (typeof range == "number") { - range = {from: Pos(range, 0), to: null}; - } else if (range.from == null) { - range = {from: range, to: null}; - } - if (!range.to) range.to = range.from; - range.margin = margin || 0; - - if (range.from.line != null) { - resolveScrollToPos(this); - this.curOp.scrollToPos = range; - } else { - var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), - Math.min(range.from.top, range.to.top) - range.margin, - Math.max(range.from.right, range.to.right), - Math.max(range.from.bottom, range.to.bottom) + range.margin); - this.scrollTo(sPos.scrollLeft, sPos.scrollTop); - } - }), - - setSize: methodOp(function(width, height) { - var cm = this; - function interpret(val) { - return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; - } - if (width != null) cm.display.wrapper.style.width = interpret(width); - if (height != null) cm.display.wrapper.style.height = interpret(height); - if (cm.options.lineWrapping) clearLineMeasurementCache(this); - var lineNo = cm.display.viewFrom; - cm.doc.iter(lineNo, cm.display.viewTo, function(line) { - if (line.widgets) for (var i = 0; i < line.widgets.length; i++) - if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } - ++lineNo; - }); - cm.curOp.forceUpdate = true; - signal(cm, "refresh", this); - }), - - operation: function(f){return runInOp(this, f);}, - - refresh: methodOp(function() { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) - estimateLineHeights(this); - signal(this, "refresh", this); - }), - - swapDoc: methodOp(function(doc) { - var old = this.doc; - old.cm = null; - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - this.scrollTo(doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old; - }), - - getInputField: function(){return this.display.input.getField();}, - getWrapperElement: function(){return this.display.wrapper;}, - getScrollerElement: function(){return this.display.scroller;}, - getGutterElement: function(){return this.display.gutters;} - }; - eventMixin(CodeMirror); - - // OPTION DEFAULTS - - // The default configuration options. - var defaults = CodeMirror.defaults = {}; - // Functions to run when options are changed. - var optionHandlers = CodeMirror.optionHandlers = {}; - - function option(name, deflt, handle, notOnInit) { - CodeMirror.defaults[name] = deflt; - if (handle) optionHandlers[name] = - notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; - } - - // Passed to option handlers when there is no old value. - var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; - - // These two are, on init, called from the constructor because they - // have to be initialized before the editor can start at all. - option("value", "", function(cm, val) { - cm.setValue(val); - }, true); - option("mode", null, function(cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function(cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); - if (old != CodeMirror.Init) cm.refresh(); - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function() { - throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME - }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - - option("theme", "default", function(cm) { - themeChanged(cm); - guttersChanged(cm); - }, true); - option("keyMap", "default", function(cm, val, old) { - var next = getKeyMap(val); - var prev = old != CodeMirror.Init && getKeyMap(old); - if (prev && prev.detach) prev.detach(cm, next); - if (next.attach) next.attach(cm, prev || null); - }); - option("extraKeys", null); - - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("fixedGutter", true, function(cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); - option("scrollbarStyle", "native", function(cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("firstLineNumber", 1, guttersChanged, true); - option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); - option("showCursorWhenSelecting", false, updateSelection, true); - - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - - option("readOnly", false, function(cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - cm.display.disabled = true; - } else { - cm.display.disabled = false; - if (!val) cm.display.input.reset(); - } - }); - option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); - option("dragDrop", true, dragDropChanged); - - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function(cm){cm.refresh();}, true); - option("maxHighlightLength", 10000, resetModeState, true); - option("moveInputWithCursor", true, function(cm, val) { - if (!val) cm.display.input.resetPosition(); - }); - - option("tabindex", null, function(cm, val) { - cm.display.input.getField().tabIndex = val || ""; - }); - option("autofocus", null); - - // MODE DEFINITION AND QUERYING - - // Known modes, by name and by MIME - var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - CodeMirror.defineMode = function(name, mode) { - if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; - if (arguments.length > 2) - mode.dependencies = Array.prototype.slice.call(arguments, 2); - modes[name] = mode; - }; - - CodeMirror.defineMIME = function(mime, spec) { - mimeModes[mime] = spec; - }; - - // Given a MIME type, a {name, ...options} config object, or a name - // string, return a mode config object. - CodeMirror.resolveMode = function(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") found = {name: found}; - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return CodeMirror.resolveMode("application/xml"); - } - if (typeof spec == "string") return {name: spec}; - else return spec || {name: "null"}; - }; - - // Given a mode spec (anything that resolveMode accepts), find and - // initialize an actual mode object. - CodeMirror.getMode = function(options, spec) { - var spec = CodeMirror.resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) return CodeMirror.getMode(options, "text/plain"); - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop in exts) { - if (!exts.hasOwnProperty(prop)) continue; - if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; - modeObj[prop] = exts[prop]; - } - } - modeObj.name = spec.name; - if (spec.helperType) modeObj.helperType = spec.helperType; - if (spec.modeProps) for (var prop in spec.modeProps) - modeObj[prop] = spec.modeProps[prop]; - - return modeObj; - }; - - // Minimal default mode. - CodeMirror.defineMode("null", function() { - return {token: function(stream) {stream.skipToEnd();}}; - }); - CodeMirror.defineMIME("text/plain", "null"); - - // This can be used to attach properties to mode objects from - // outside the actual mode definition. - var modeExtensions = CodeMirror.modeExtensions = {}; - CodeMirror.extendMode = function(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); - copyObj(properties, exts); - }; - - // EXTENSIONS - - CodeMirror.defineExtension = function(name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function(name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.defineOption = option; - - var initHooks = []; - CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; - - var helpers = CodeMirror.helpers = {}; - CodeMirror.registerHelper = function(type, name, value) { - if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; - helpers[type][name] = value; - }; - CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { - CodeMirror.registerHelper(type, name, value); - helpers[type]._global.push({pred: predicate, val: value}); - }; - - // MODE STATE HANDLING - - // Utility functions for working with state. Exported because nested - // modes need to do this for their inner modes. - - var copyState = CodeMirror.copyState = function(mode, state) { - if (state === true) return state; - if (mode.copyState) return mode.copyState(state); - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) val = val.concat([]); - nstate[n] = val; - } - return nstate; - }; - - var startState = CodeMirror.startState = function(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - }; - - // Given a mode and a state (for that mode), find the inner mode and - // state at the position that the state refers to. - CodeMirror.innerMode = function(mode, state) { - while (mode.innerMode) { - var info = mode.innerMode(state); - if (!info || info.mode == mode) break; - state = info.state; - mode = info.mode; - } - return info || {mode: mode, state: state}; - }; - - // STANDARD COMMANDS - - // Commands are parameter-less actions that can be performed on an - // editor, mostly used for keybindings. - var commands = CodeMirror.commands = { - selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, - singleSelection: function(cm) { - cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); - }, - killLine: function(cm) { - deleteNearSelection(cm, function(range) { - if (range.empty()) { - var len = getLine(cm.doc, range.head.line).text.length; - if (range.head.ch == len && range.head.line < cm.lastLine()) - return {from: range.head, to: Pos(range.head.line + 1, 0)}; - else - return {from: range.head, to: Pos(range.head.line, len)}; - } else { - return {from: range.from(), to: range.to()}; - } - }); - }, - deleteLine: function(cm) { - deleteNearSelection(cm, function(range) { - return {from: Pos(range.from().line, 0), - to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; - }); - }, - delLineLeft: function(cm) { - deleteNearSelection(cm, function(range) { - return {from: Pos(range.from().line, 0), to: range.from()}; - }); - }, - delWrappedLineLeft: function(cm) { - deleteNearSelection(cm, function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var leftPos = cm.coordsChar({left: 0, top: top}, "div"); - return {from: leftPos, to: range.from()}; - }); - }, - delWrappedLineRight: function(cm) { - deleteNearSelection(cm, function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - return {from: range.from(), to: rightPos }; - }); - }, - undo: function(cm) {cm.undo();}, - redo: function(cm) {cm.redo();}, - undoSelection: function(cm) {cm.undoSelection();}, - redoSelection: function(cm) {cm.redoSelection();}, - goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, - goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, - goLineStart: function(cm) { - cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, - {origin: "+move", bias: 1}); - }, - goLineStartSmart: function(cm) { - cm.extendSelectionsBy(function(range) { - return lineStartSmart(cm, range.head); - }, {origin: "+move", bias: 1}); - }, - goLineEnd: function(cm) { - cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, - {origin: "+move", bias: -1}); - }, - goLineRight: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - }, sel_move); - }, - goLineLeft: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - return cm.coordsChar({left: 0, top: top}, "div"); - }, sel_move); - }, - goLineLeftSmart: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var pos = cm.coordsChar({left: 0, top: top}, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); - return pos; - }, sel_move); - }, - goLineUp: function(cm) {cm.moveV(-1, "line");}, - goLineDown: function(cm) {cm.moveV(1, "line");}, - goPageUp: function(cm) {cm.moveV(-1, "page");}, - goPageDown: function(cm) {cm.moveV(1, "page");}, - goCharLeft: function(cm) {cm.moveH(-1, "char");}, - goCharRight: function(cm) {cm.moveH(1, "char");}, - goColumnLeft: function(cm) {cm.moveH(-1, "column");}, - goColumnRight: function(cm) {cm.moveH(1, "column");}, - goWordLeft: function(cm) {cm.moveH(-1, "word");}, - goGroupRight: function(cm) {cm.moveH(1, "group");}, - goGroupLeft: function(cm) {cm.moveH(-1, "group");}, - goWordRight: function(cm) {cm.moveH(1, "word");}, - delCharBefore: function(cm) {cm.deleteH(-1, "char");}, - delCharAfter: function(cm) {cm.deleteH(1, "char");}, - delWordBefore: function(cm) {cm.deleteH(-1, "word");}, - delWordAfter: function(cm) {cm.deleteH(1, "word");}, - delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, - delGroupAfter: function(cm) {cm.deleteH(1, "group");}, - indentAuto: function(cm) {cm.indentSelection("smart");}, - indentMore: function(cm) {cm.indentSelection("add");}, - indentLess: function(cm) {cm.indentSelection("subtract");}, - insertTab: function(cm) {cm.replaceSelection("\t");}, - insertSoftTab: function(cm) { - var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; - for (var i = 0; i < ranges.length; i++) { - var pos = ranges[i].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); - } - cm.replaceSelections(spaces); - }, - defaultTab: function(cm) { - if (cm.somethingSelected()) cm.indentSelection("add"); - else cm.execCommand("insertTab"); - }, - transposeChars: function(cm) { - runInOp(cm, function() { - var ranges = cm.listSelections(), newSel = []; - for (var i = 0; i < ranges.length; i++) { - var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); - if (cur.ch > 0) { - cur = new Pos(cur.line, cur.ch + 1); - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), - Pos(cur.line, cur.ch - 2), cur, "+transpose"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) - cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1), - Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); - } - } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); - }, - newlineAndIndent: function(cm) { - runInOp(cm, function() { - var len = cm.listSelections().length; - for (var i = 0; i < len; i++) { - var range = cm.listSelections()[i]; - cm.replaceRange("\n", range.anchor, range.head, "+input"); - cm.indentLine(range.from().line + 1, null, true); - ensureCursorVisible(cm); - } - }); - }, - toggleOverwrite: function(cm) {cm.toggleOverwrite();} - }; - - - // STANDARD KEYMAPS - - var keyMap = CodeMirror.keyMap = {}; - - keyMap.basic = { - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", - "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", - "Esc": "singleSelection" - }; - // Note that the save and find-related commands aren't defined by - // default. User code or addons can define them. Unknown commands - // are simply ignored. - keyMap.pcDefault = { - "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", - "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", - "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", - "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", - fallthrough: "basic" - }; - // Very basic readline/emacs-style bindings, which are standard on Mac. - keyMap.emacsy = { - "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", - "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", - "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", - "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", - "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", - "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", - fallthrough: ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - - // KEYMAP DISPATCH - - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i = 0; i < parts.length - 1; i++) { - var mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; - else if (/^a(lt)?$/i.test(mod)) alt = true; - else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; - else if (/^s(hift)$/i.test(mod)) shift = true; - else throw new Error("Unrecognized modifier name: " + mod); - } - if (alt) name = "Alt-" + name; - if (ctrl) name = "Ctrl-" + name; - if (cmd) name = "Cmd-" + name; - if (shift) name = "Shift-" + name; - return name; - } - - // This is a kludge to keep keymaps mostly working as raw objects - // (backwards compatibility) while at the same time support features - // like normalization and multi-stroke key bindings. It compiles a - // new normalized keymap, and then updates the old object to reflect - // this. - CodeMirror.normalizeKeyMap = function(keymap) { - var copy = {}; - for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; - if (value == "...") { delete keymap[keyname]; continue; } - - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i = 0; i < keys.length; i++) { - var val, name; - if (i == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) copy[name] = val; - else if (prev != val) throw new Error("Inconsistent bindings for " + name); - } - delete keymap[keyname]; - } - for (var prop in copy) keymap[prop] = copy[prop]; - return keymap; - }; - - var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { - map = getKeyMap(map); - var found = map.call ? map.call(key, context) : map[key]; - if (found === false) return "nothing"; - if (found === "...") return "multi"; - if (found != null && handle(found)) return "handled"; - - if (map.fallthrough) { - if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") - return lookupKey(key, map.fallthrough, handle, context); - for (var i = 0; i < map.fallthrough.length; i++) { - var result = lookupKey(key, map.fallthrough[i], handle, context); - if (result) return result; - } - } - }; - - // Modifier key presses don't count as 'real' key presses for the - // purpose of keymap fallthrough. - var isModifierKey = CodeMirror.isModifierKey = function(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - }; - - // Look up the name of a key as indicated by an event object. - var keyName = CodeMirror.keyName = function(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) return false; - var base = keyNames[event.keyCode], name = base; - if (name == null || event.altGraphKey) return false; - if (event.altKey && base != "Alt") name = "Alt-" + name; - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; - if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; - return name; - }; - - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val; - } - - // FROMTEXTAREA - - CodeMirror.fromTextArea = function(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) - options.tabindex = textarea.tabIndex; - if (!options.placeholder && textarea.placeholder) - options.placeholder = textarea.placeholder; - // Set autofocus to true if this textarea is focused, or if it has - // autofocus and no other element is focused. - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || - textarea.getAttribute("autofocus") != null && hasFocus == document.body; - } + function applyTextInput (cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) sel = doc.sel; - function save() {textarea.value = cm.getValue();} - if (textarea.form) { - on(textarea.form, "submit", save); - // Deplorable hack to make the submit method do the right thing. - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form, realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function() { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch(e) {} - } - } - - options.finishInit = function(cm) { - cm.save = save; - cm.getTextArea = function() { return textarea; }; - cm.toTextArea = function() { - cm.toTextArea = isNaN; // Prevent this from being ran twice - save(); - textarea.parentNode.removeChild(cm.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (typeof textarea.form.submit == "function") - textarea.form.submit = realSubmit; + var paste = cm.state.pasteIncoming || origin == "paste"; + var textLines = splitLines(inserted), multiPaste = null; + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.join("\n") == inserted) {multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);} else if (textLines.length == sel.ranges.length) {multiPaste = map(textLines, function (l) { return [l]; });} } - }; - }; - textarea.style.display = "none"; - var cm = CodeMirror(function(node) { - textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - return cm; - }; - - // STRING STREAM - - // Fed to the mode parsers, provides helper functions to make - // parsers more succinct. - - var StringStream = CodeMirror.StringStream = function(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - }; - - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == this.lineStart;}, - peek: function() {return this.string.charAt(this.pos) || undefined;}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }, - indentation: function() { - return countColumn(this.string, null, this.tabSize) - - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) this.pos += pattern.length; - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) return null; - if (match && consume !== false) this.pos += match[0].length; - return match; - } - }, - current: function(){return this.string.slice(this.start, this.pos);}, - hideFirstChars: function(n, inner) { - this.lineStart += n; - try { return inner(); } - finally { this.lineStart -= n; } - } - }; - - // TEXTMARKERS - - // Created with markText and setBookmark methods. A TextMarker is a - // handle that can be used to clear or find a marked position in the - // document. Line objects hold arrays (markedSpans) containing - // {from, to, marker} object pointing to such marker objects, and - // indicating that such a marker is present on that line. Multiple - // lines may point to the same marker when it spans across lines. - // The spans will have null for their from/to properties when the - // marker continues beyond the start/end of the line. Markers have - // links back to the lines they currently touch. - - var nextMarkerId = 0; - - var TextMarker = CodeMirror.TextMarker = function(doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - eventMixin(TextMarker); - - // Clear the marker. - TextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - var cm = this.doc.cm, withOp = cm && !cm.curOp; - if (withOp) startOperation(cm); - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) signalLater(this, "clear", found.from, found.to); - } - var min = null, max = null; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); - else if (cm) { - if (span.to != null) max = lineNo(line); - if (span.from != null) min = lineNo(line); - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) - updateLineHeight(line, textHeight(cm.display)); - } - if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { - var visual = visualLine(this.lines[i]), len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } - - if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) reCheckSelection(cm.doc); - } - if (cm) signalLater(cm, "markerCleared", cm, this); - if (withOp) endOperation(cm); - if (this.parent) this.parent.clear(); - }; - - // Find the position of the marker in the document. Returns a {from, - // to} object by default. Side can be passed to get a specific side - // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the - // Pos objects returned contain a line object, rather than a line - // number (used to prevent looking up the same line twice). - TextMarker.prototype.find = function(side, lineObj) { - if (side == null && this.type == "bookmark") side = 1; - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) return from; - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) return to; - } - } - return from && {from: from, to: to}; - }; - - // Signals that the marker's widget changed, and surrounding layout - // should be recomputed. - TextMarker.prototype.changed = function() { - var pos = this.find(-1, true), widget = this, cm = this.doc.cm; - if (!pos || !cm) return; - runInOp(cm, function() { - var line = pos.line, lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) - updateLineHeight(line, line.height + dHeight); - } - }); - }; - - TextMarker.prototype.attachLine = function(line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) - (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); - } - this.lines.push(line); - }; - TextMarker.prototype.detachLine = function(line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - - // Collapsed markers have unique ids, in order to be able to order - // them, which is needed for uniquely determining an outer marker - // when they overlap (they may nest, but not partially overlap). - var nextMarkerId = 0; - - // Create a marker, wire it up to the right lines, and - function markText(doc, from, to, options, type) { - // Shared markers (across linked documents) are handled separately - // (markTextShared will call out to this again, once per - // document). - if (options && options.shared) return markTextShared(doc, from, to, options, type); - // Ensure we are in an operation. - if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); - - var marker = new TextMarker(doc, type), diff = cmp(from, to); - if (options) copyObj(options, marker, false); - // Don't connect empty markers unless clearWhenEmpty is false - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) - return marker; - if (marker.replacedWith) { - // Showing up as a widget implies collapsed (widget replaces text) - marker.collapsed = true; - marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); - if (options.insertLeft) marker.widgetNode.insertLeft = true; - } - if (marker.collapsed) { - if (conflictingCollapsedRange(doc, from.line, from, to, marker) || - from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) - throw new Error("Inserting collapsed marker partially overlapping an existing one"); - sawCollapsedSpans = true; - } - - if (marker.addToHistory) - addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); - - var curLine = from.line, cm = doc.cm, updateMaxLine; - doc.iter(curLine, to.line + 1, function(line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) - updateMaxLine = true; - if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); - addMarkedSpan(line, new MarkedSpan(marker, - curLine == from.line ? from.ch : null, - curLine == to.line ? to.ch : null)); - ++curLine; - }); - // lineIsHidden depends on the presence of the spans, so needs a second pass - if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { - if (lineIsHidden(doc, line)) updateLineHeight(line, 0); - }); + // Normal behavior is to insert the new text into every selection + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + var from = range.from(), to = range.to(); + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + {from = Pos(from.line, from.ch - deleted);} else if (cm.state.overwrite && !paste) // Handle overwrite + {to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));} + } + var updateInput = cm.curOp.updateInput; + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) {triggerElectric(cm, inserted);} - if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); - - if (marker.readOnly) { - sawReadOnlySpans = true; - if (doc.history.done.length || doc.history.undone.length) - doc.clearHistory(); - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - // Sync editor state - if (updateMaxLine) cm.curOp.updateMaxLine = true; - if (marker.collapsed) - regChange(cm, from.line, to.line + 1); - else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) - for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); - if (marker.atomic) reCheckSelection(cm.doc); - signalLater(cm, "markerAdded", cm, marker); - } - return marker; - } - - // SHARED TEXTMARKERS - - // A shared marker spans multiple linked documents. It is - // implemented as a meta-marker-object controlling multiple normal - // markers. - var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { - this.markers = markers; - this.primary = primary; - for (var i = 0; i < markers.length; ++i) - markers[i].parent = this; - }; - eventMixin(SharedTextMarker); - - SharedTextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - this.explicitlyCleared = true; - for (var i = 0; i < this.markers.length; ++i) - this.markers[i].clear(); - signalLater(this, "clear"); - }; - SharedTextMarker.prototype.find = function(side, lineObj) { - return this.primary.find(side, lineObj); - }; - - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function(doc) { - if (widget) options.widgetNode = widget.cloneNode(true); - markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); - for (var i = 0; i < doc.linked.length; ++i) - if (doc.linked[i].isParent) return; - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary); - } - - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), - function(m) { return m.parent; }); - } - - function copySharedMarkers(doc, markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], pos = marker.find(); - var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; - } - } - } - - function detachSharedMarkers(markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], linked = [marker.primary.doc];; - linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } - } - } - } - - // TEXTMARKER SPANS - - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; this.to = to; - } - - // Search an array of spans for a span matching the given marker. - function getMarkedSpanFor(spans, marker) { - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.marker == marker) return span; - } - } - // Remove a span from an array, returning undefined if no spans are - // left (we don't store arrays for lines without spans). - function removeMarkedSpan(spans, span) { - for (var r, i = 0; i < spans.length; ++i) - if (spans[i] != span) (r || (r = [])).push(spans[i]); - return r; - } - // Add a span to a line. - function addMarkedSpan(line, span) { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - span.marker.attachLine(line); - } - - // Used for the algorithm that adjusts markers for a change in the - // document. These functions cut an array of spans at a given - // character position, returning an array of remaining chunks (or - // undefined if nothing remains). - function markedSpansBefore(old, startCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); - } - } - return nw; - } - function markedSpansAfter(old, endCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, - span.to == null ? null : span.to - endCh)); - } - } - return nw; - } - - // Given a change object, compute the new set of marker spans that - // cover the line in which the change took place. Removes spans - // entirely within the change, reconnects spans belonging to the - // same marker that appear on both sides of the change, and cuts off - // spans partially within the change. Returns an array of span - // arrays with one element for each line in (after) the change. - function stretchSpansOverChange(doc, change) { - if (change.full) return null; - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) return null; - - var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - - // Next, merge those two ends - var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - // Fix up .to properties of first - for (var i = 0; i < first.length; ++i) { - var span = first[i]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) span.to = startCh; - else if (sameLine) span.to = found.to == null ? null : found.to + offset; - } - } - } - if (last) { - // Fix up .from in last (or move them into first in case of sameLine) - for (var i = 0; i < last.length; ++i) { - var span = last[i]; - if (span.to != null) span.to += offset; - if (span.from == null) { - var found = getMarkedSpanFor(first, span.marker); - if (!found) { - span.from = offset; - if (sameLine) (first || (first = [])).push(span); - } - } else { - span.from += offset; - if (sameLine) (first || (first = [])).push(span); - } - } - } - // Make sure we didn't create any zero-length spans - if (first) first = clearEmptySpans(first); - if (last && last != first) last = clearEmptySpans(last); - - var newMarkers = [first]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = change.text.length - 2, gapMarkers; - if (gap > 0 && first) - for (var i = 0; i < first.length; ++i) - if (first[i].to == null) - (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); - for (var i = 0; i < gap; ++i) - newMarkers.push(gapMarkers); - newMarkers.push(last); - } - return newMarkers; - } - - // Remove spans that are empty and don't have a clearWhenEmpty - // option of false. - function clearEmptySpans(spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) - spans.splice(i--, 1); - } - if (!spans.length) return null; - return spans; - } - - // Used for un/re-doing changes from the history. Combines the - // result of computing the existing spans with the set of spans that - // existed in the history (so that deleting around a span and then - // undoing brings back the span). - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) return stretched; - if (!stretched) return old; - - for (var i = 0; i < old.length; ++i) { - var oldCur = old[i], stretchCur = stretched[i]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) - if (oldCur[k].marker == span.marker) continue spans; - oldCur.push(span); - } - } else if (stretchCur) { - old[i] = stretchCur; - } - } - return old; - } - - // Used to 'clip' out readOnly ranges when making a change. - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function(line) { - if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { - var mark = line.markedSpans[i].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) - (markers || (markers = [])).push(mark); - } - }); - if (!markers) return null; - var parts = [{from: from, to: to}]; - for (var i = 0; i < markers.length; ++i) { - var mk = markers[i], m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; - var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) - newParts.push({from: p.from, to: m.from}); - if (dto > 0 || !mk.inclusiveRight && !dto) - newParts.push({from: m.to, to: p.to}); - parts.splice.apply(parts, newParts); - j += newParts.length - 1; - } - } - return parts; - } - - // Connect or disconnect spans from a line. - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.detachLine(line); - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.attachLine(line); - line.markedSpans = spans; - } - - // Helpers used when computing which overlapping collapsed span - // counts as the larger one. - function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } - function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } - - // Returns a number indicating which of two overlapping collapsed - // spans is larger (and thus includes the other). Falls back to - // comparing ids when the spans cover exactly the same range. - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) return lenDiff; - var aPos = a.find(), bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) return -fromCmp; - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) return toCmp; - return b.id - a.id; - } - - // Find out whether a line ends or starts in a collapsed span. If - // so, return the marker for that span. - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) - found = sp.marker; - } - return found; - } - function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } - function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } - - // Test whether there exists a collapsed span that partially - // overlaps (covers the start or end, but not both) of a new span. - // Such overlap is not allowed. - function conflictingCollapsedRange(doc, lineNo, from, to, marker) { - var line = getLine(doc, lineNo); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (!sp.marker.collapsed) continue; - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; - if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || - fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) - return true; + ensureCursorVisible(cm); + cm.curOp.updateInput = updateInput; + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = false; } - } - - // A visual line is a line as drawn on the screen. Folding, for - // example, can cause multiple logical lines to appear on the same - // visual line. This finds the start of the visual line that the - // given line is part of (usually that is the line itself). - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) - line = merged.find(-1, true).line; - return line; - } - - // Returns an array of logical lines that continue the visual line - // started by the argument, or undefined if there are no such lines. - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - (lines || (lines = [])).push(line); - } - return lines; - } - - // Get the line number of the start of the visual line that the - // given line number is part of. - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), vis = visualLine(line); - if (line == vis) return lineN; - return lineNo(vis); - } - // Get the line number of the start of the next visual line after - // the given line. - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) return lineN; - var line = getLine(doc, lineN), merged; - if (!lineIsHidden(doc, line)) return lineN; - while (merged = collapsedSpanAtEnd(line)) - line = merged.find(1, true).line; - return lineNo(line) + 1; - } - - // Compute whether a line is hidden. Lines count as hidden when they - // are part of a visual line that starts with another line, or when - // they are entirely covered by collapsed, non-widget span. - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) continue; - if (sp.from == null) return true; - if (sp.marker.widgetNode) continue; - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) - return true; + + function handlePaste (e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); + if (pasted) { + e.preventDefault(); + runInOp(cm, function () { applyTextInput(cm, pasted, 0, null, "paste"); }); + return true; + } } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); - } - if (span.marker.inclusiveRight && span.to == line.text.length) - return true; - for (var sp, i = 0; i < line.markedSpans.length; ++i) { - sp = line.markedSpans[i]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && - (sp.to == null || sp.to != span.from) && - (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && - lineIsHiddenInner(doc, line, sp)) return true; + + function triggerElectric (cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) return; + var sel = cm.doc.sel; + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; + var mode = cm.getModeAt(range.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) { + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart"); + break; + } + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) {indented = indentLine(cm, range.head.line, "smart");} + } + if (indented) signalLater(cm, "electricInput", cm, range.head.line); + } } - } - - // LINE WIDGETS - - // Line widgets are block elements displayed above or below a line. - - var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { - if (options) for (var opt in options) if (options.hasOwnProperty(opt)) - this[opt] = options[opt]; - this.doc = doc; - this.node = node; - }; - eventMixin(LineWidget); - - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) - addToScrollPos(cm, null, diff); - } - - LineWidget.prototype.clear = function() { - var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); - if (no == null || !ws) return; - for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); - if (!ws.length) line.widgets = null; - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) runInOp(cm, function() { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - }; - LineWidget.prototype.changed = function() { - var oldH = this.height, cm = this.doc.cm, line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) return; - updateLineHeight(line, line.height + diff); - if (cm) runInOp(cm, function() { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - }); - }; - - function widgetHeight(widget) { - if (widget.height != null) return widget.height; - var cm = widget.doc.cm; - if (!cm) return 0; - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) - parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; - if (widget.noHScroll) - parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); - } - return widget.height = widget.node.offsetHeight; - } - - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) cm.display.alignWidgets = true; - changeLine(doc, handle, "widget", function(line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) widgets.push(widget); - else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) addToScrollPos(cm, null, widget.height); - cm.curOp.forceUpdate = true; - } - return true; - }); - return widget; - } - - // LINE DATA STRUCTURE - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight ? estimateHeight(this) : 1; - }; - eventMixin(Line); - Line.prototype.lineNo = function() { return lineNo(this); }; - - // Change the content (text, markers) of a line. Automatically - // invalidates cached information and tries to re-estimate the - // line's height. - function updateLine(line, text, markedSpans, estimateHeight) { - line.text = text; - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - if (line.order != null) line.order = null; - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight ? estimateHeight(line) : 1; - if (estHeight != line.height) updateLineHeight(line, estHeight); - } - - // Detach a line from the document tree and its markers. - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - - function extractLineClasses(type, output) { - if (type) for (;;) { - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); - if (!lineClass) break; - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); - var prop = lineClass[1] ? "bgClass" : "textClass"; - if (output[prop] == null) - output[prop] = lineClass[2]; - else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) - output[prop] += " " + lineClass[2]; - } - return type; - } - - function callBlankLine(mode, state) { - if (mode.blankLine) return mode.blankLine(state); - if (!mode.innerMode) return; - var inner = CodeMirror.innerMode(mode, state); - if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); - } - - function readToken(mode, stream, state, inner) { - for (var i = 0; i < 10; i++) { - if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; - var style = mode.token(stream, state); - if (stream.pos > stream.start) return style; - } - throw new Error("Mode " + mode.name + " failed to advance stream."); - } - - // Utility for getTokenAt and getLineTokens - function takeToken(cm, pos, precise, asArray) { - function getObj(copy) { - return {start: stream.start, end: stream.pos, - string: stream.current(), - type: style || null, - state: copy ? copyState(doc.mode, state) : state}; - } - - var doc = cm.doc, mode = doc.mode, style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize), tokens; - if (asArray) tokens = []; - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, state); - if (asArray) tokens.push(getObj(true)); - } - return asArray ? tokens : getObj(); - } - - // Run the given mode's parser over a line, calling f for each token. - function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; - var curStart = 0, curStyle = null; - var stream = new StringStream(text, cm.options.tabSize), style; - var inner = cm.options.addModeClass && [null]; - if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) processLine(cm, text, state, stream.pos); - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); - } - if (inner) { - var mName = inner[0].name; - if (mName) style = "m-" + (style ? mName + " " + style : mName); - } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 50000); - f(curStart, curStyle); - } - curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - // Webkit seems to refuse to render text nodes longer than 57444 characters - var pos = Math.min(stream.pos, curStart + 50000); - f(pos, curStyle); - curStart = pos; - } - } - - // Compute a style array (an array starting with a mode generation - // -- for invalidation -- followed by pairs of end positions and - // style strings), which is used to highlight the tokens on the - // line. - function highlightLine(cm, line, state, forceToEnd) { - // A styles array always starts with a number identifying the - // mode/overlays that it is based on (for easy invalidation). - var st = [cm.state.modeGen], lineClasses = {}; - // Compute the base array of styles - runMode(cm, line.text, cm.doc.mode, state, function(end, style) { - st.push(end, style); - }, lineClasses, forceToEnd); - - // Run overlays, adjust style array. - for (var o = 0; o < cm.state.overlays.length; ++o) { - var overlay = cm.state.overlays[o], i = 1, at = 0; - runMode(cm, line.text, overlay.mode, true, function(end, style) { - var start = i; - // Ensure there's a token end at the current position, and that i points at it - while (at < end) { - var i_end = st[i]; - if (i_end > end) - st.splice(i, 1, end, st[i+1], i_end); - i += 2; - at = Math.min(end, i_end); - } - if (!style) return; - if (overlay.opaque) { - st.splice(start, i - start, end, "cm-overlay " + style); - i = start + 2; - } else { - for (; start < i; start += 2) { - var cur = st[start+1]; - st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; - } - } - }, lineClasses); - } - - return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; - } - - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); - line.styles = result.styles; - if (result.classes) line.styleClasses = result.classes; - else if (line.styleClasses) line.styleClasses = null; - if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; - } - return line.styles; - } - - // Lightweight form of highlight -- proceed over this line and - // update state, but don't save a style array. Used for lines that - // aren't currently visible. - function processLine(cm, text, state, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize); - stream.start = stream.pos = startAt || 0; - if (text == "") callBlankLine(mode, state); - while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { - readToken(mode, stream, state); - stream.start = stream.pos; - } - } - - // Convert a style as returned by a mode (either null, or a string - // containing one or more styles) to a CSS style. This is cached, - // and also looks for line-wide styles. - var styleToClassCache = {}, styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) return null; - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || - (cache[style] = style.replace(/\S+/g, "cm-$&")); - } - - // Render the DOM representation of the text of a line. Also builds - // up a 'line map', which points at the DOM nodes that represent - // specific stretches of text, and is used by the measuring code. - // The returned object contains the DOM node, this map, and - // information about line-wide styles that were set by the mode. - function buildLineContent(cm, lineView) { - // The padding-right forces the element to have a 'border', which - // is needed on Webkit to be able to get line-level bounding - // rectangles for it (in measureChar). - var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, - col: 0, pos: 0, cm: cm, - splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; - lineView.measure = {}; - - // Iterate over the logical lines that make up this visual line. - for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { - var line = i ? lineView.rest[i - 1] : lineView.line, order; - builder.pos = 0; - builder.addToken = buildToken; - // Optionally wire in some hacks into the token-rendering - // algorithm, to deal with browser quirks. - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) - builder.addToken = buildTokenBadBidi(builder.addToken, order); - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) - builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); - if (line.styleClasses.textClass) - builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); - } - - // Ensure at least a single node is present, for measuring. - if (builder.map.length == 0) - builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); - - // Store the map and a cache object for the current logical line - if (i == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); - (lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - - // See issue #2901 - if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className)) - builder.content.className = "cm-tab-wrap-hack"; - - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) - builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); - - return builder; - } - - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token; - } - - // Build up the DOM representation for a single token, and add it to - // the line map. Takes care to render special characters separately. - function buildToken(builder, text, style, startStyle, endStyle, title, css) { - if (!text) return; - var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; - var special = builder.cm.state.specialChars, mustWrap = false; - if (!special.test(text)) { - builder.col += text.length; - var content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) mustWrap = true; - builder.pos += text.length; - } else { - var content = document.createDocumentFragment(), pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); - else content.appendChild(txt); - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) break; - pos += skipped + 1; - if (m[0] == "\t") { - var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; - var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt.setAttribute("role", "presentation"); - txt.setAttribute("cm-text", "\t"); - builder.col += tabWidth; - } else { - var txt = builder.cm.options.specialCharPlaceholder(m[0]); - txt.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); - else content.appendChild(txt); - builder.col += 1; - } - builder.map.push(builder.pos, builder.pos + 1, txt); - builder.pos++; - } - } - if (style || startStyle || endStyle || mustWrap || css) { - var fullStyle = style || ""; - if (startStyle) fullStyle += startStyle; - if (endStyle) fullStyle += endStyle; - var token = elt("span", [content], fullStyle, css); - if (title) token.title = title; - return builder.content.appendChild(token); - } - builder.content.appendChild(content); - } - - function splitSpaces(old) { - var out = " "; - for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; - out += " "; - return out; - } - - // Work around nonsense dimensions being reported for stretches of - // right-to-left text. - function buildTokenBadBidi(inner, order) { - return function(builder, text, style, startStyle, endStyle, title, css) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, end = start + text.length; - for (;;) { - // Find the part that overlaps with the start of this text - for (var i = 0; i < order.length; i++) { - var part = order[i]; - if (part.to > start && part.from <= start) break; - } - if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); - inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - }; - } - - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) builder.map.push(builder.pos, builder.pos + size, widget); - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) - widget = builder.content.appendChild(document.createElement("span")); - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - } - - // Outputs a number of spans to make up a line, taking highlighting - // and marked text into account. - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, allText = line.text, at = 0; - if (!spans) { - for (var i = 1; i < styles.length; i+=2) - builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); - return; - } - - var len = allText.length, pos = 0, i = 1, text = "", style, css; - var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; - for (;;) { - if (nextChange == pos) { // Update current marker set - spanStyle = spanEndStyle = spanStartStyle = title = css = ""; - collapsed = null; nextChange = Infinity; - var foundBookmarks = []; - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) spanStyle += " " + m.className; - if (m.css) css = m.css; - if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; - if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; - if (m.title && !title) title = m.title; - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) - collapsed = sp; - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, - collapsed.marker, collapsed.from == null); - if (collapsed.to == null) return; - if (collapsed.to == pos) collapsed = false; - } - if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) - buildCollapsedSpan(builder, 0, foundBookmarks[j]); - } - if (pos >= len) break; - - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, - spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); - } - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i++]); - style = interpretTokenStyle(styles[i++], builder.cm.options); - } - } - } - - // DOCUMENT DATA STRUCTURE - - // By default, updates that start and end at the beginning of a line - // are treated specially, in order to make the association of line - // widgets and marker elements with the text behave more intuitive. - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && - (!doc.cm || doc.cm.options.wholeLineUpdateBefore); - } - - // Perform a change on the document data structure. - function updateDoc(doc, change, markedSpans, estimateHeight) { - function spansFor(n) {return markedSpans ? markedSpans[n] : null;} - function update(line, text, spans) { - updateLine(line, text, spans, estimateHeight); - signalLater(line, "change", line, change); - } - function linesFor(start, end) { - for (var i = start, result = []; i < end; ++i) - result.push(new Line(text[i], spansFor(i), estimateHeight)); - return result; - } - - var from = change.from, to = change.to, text = change.text; - var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); - var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; - - // Adjust the line structure - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) doc.remove(from.line, nlines); - if (added.length) doc.insert(from.line, added); - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added = linesFor(1, text.length - 1); - added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added = linesFor(1, text.length - 1); - if (nlines > 1) doc.remove(from.line + 1, nlines - 1); - doc.insert(from.line + 1, added); - } - - signalLater(doc, "change", doc, change); - } - - // The document is represented as a BTree consisting of leaves, with - // chunk of lines in them, and branches, with up to ten leaves or - // other branch nodes below them. The top node is always a branch - // node, and is the document object itself (meaning it has - // additional methods and properties). - // - // All nodes have parent links. The tree is used both to go from - // line numbers to line objects, and to go from objects to numbers. - // It also indexes by height, and is used to convert between height - // and line object, and to find the total height of the document. - // - // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html - - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - for (var i = 0, height = 0; i < lines.length; ++i) { - lines[i].parent = this; - height += lines[i].height; - } - this.height = height; - } - - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length; }, - // Remove the n lines at offset 'at'. - removeInner: function(at, n) { - for (var i = at, e = at + n; i < e; ++i) { - var line = this.lines[i]; - this.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - // Helper used to collapse a small branch into a single leaf. - collapse: function(lines) { - lines.push.apply(lines, this.lines); - }, - // Insert the given array of lines at offset 'at', count them as - // having the given height. - insertInner: function(at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0; i < lines.length; ++i) lines[i].parent = this; - }, - // Used to iterate over a part of the tree. - iterN: function(at, n, op) { - for (var e = at + n; at < e; ++at) - if (op(this.lines[at])) return true; - } - }; - - function BranchChunk(children) { - this.children = children; - var size = 0, height = 0; - for (var i = 0; i < children.length; ++i) { - var ch = children[i]; - size += ch.chunkSize(); height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - - BranchChunk.prototype = { - chunkSize: function() { return this.size; }, - removeInner: function(at, n) { - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), oldHeight = child.height; - child.removeInner(at, rm); - this.height -= oldHeight - child.height; - if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) break; - at = 0; - } else at -= sz; - } - // If the result is smaller than 25 lines, ensure that it is a - // single leaf node. - if (this.size - n < 25 && - (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function(lines) { - for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); - }, - insertInner: function(at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - while (child.lines.length > 50) { - var spilled = child.lines.splice(child.lines.length - 25, 25); - var newleaf = new LeafChunk(spilled); - child.height -= newleaf.height; - this.children.splice(i + 1, 0, newleaf); - newleaf.parent = this; - } - this.maybeSpill(); - } - break; - } - at -= sz; - } - }, - // When a node has grown, check whether it should be split. - maybeSpill: function() { - if (this.children.length <= 10) return; - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - me.parent.maybeSpill(); - }, - iterN: function(at, n, op) { - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) return true; - if ((n -= used) == 0) break; - at = 0; - } else at -= sz; - } - } - }; - - var nextDocId = 0; - var Doc = CodeMirror.Doc = function(text, mode, firstLine) { - if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); - if (firstLine == null) firstLine = 0; - - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.frontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - - if (typeof text == "string") text = splitLines(text); - updateDoc(this, {from: start, to: start, text: text}); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function(from, to, op) { - if (op) this.iterN(from - this.first, to - from, op); - else this.iterN(this.first, this.first + this.size, from); - }, - - // Non-public interface for adding and removing lines. - insert: function(at, lines) { - var height = 0; - for (var i = 0; i < lines.length; ++i) height += lines[i].height; - this.insertInner(at - this.first, lines, height); - }, - remove: function(at, n) { this.removeInner(at - this.first, n); }, - - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - - getValue: function(lineSep, lineFilter) { - var lines = getLines(this, this.first, this.first + this.size, lineFilter); - if (lineSep === false) return lines; - return lines.join(lineSep || "\n"); - }, - setValue: docMethodOp(function(code) { - var top = Pos(this.first, 0), last = this.first + this.size - 1; - makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), - text: splitLines(code), origin: "setValue", full: true}, true); - setSelection(this, simpleSelection(top)); - }), - replaceRange: function(code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function(from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) return lines; - return lines.join(lineSep || "\n"); - }, - - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, - - getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, - getLineNumber: function(line) {return lineNo(line);}, - - getLineHandleVisualStart: function(line) { - if (typeof line == "number") line = getLine(this, line); - return visualLine(line); - }, - - lineCount: function() {return this.size;}, - firstLine: function() {return this.first;}, - lastLine: function() {return this.first + this.size - 1;}, - - clipPos: function(pos) {return clipPos(this, pos);}, - - getCursor: function(start) { - var range = this.sel.primary(), pos; - if (start == null || start == "head") pos = range.head; - else if (start == "anchor") pos = range.anchor; - else if (start == "end" || start == "to" || start === false) pos = range.to(); - else pos = range.from(); - return pos; - }, - listSelections: function() { return this.sel.ranges; }, - somethingSelected: function() {return this.sel.somethingSelected();}, - - setCursor: docMethodOp(function(line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); - }), - setSelection: docMethodOp(function(anchor, head, options) { - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); - }), - extendSelection: docMethodOp(function(head, other, options) { - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); - }), - extendSelections: docMethodOp(function(heads, options) { - extendSelections(this, clipPosArray(this, heads, options)); - }), - extendSelectionsBy: docMethodOp(function(f, options) { - extendSelections(this, map(this.sel.ranges, f), options); - }), - setSelections: docMethodOp(function(ranges, primary, options) { - if (!ranges.length) return; - for (var i = 0, out = []; i < ranges.length; i++) - out[i] = new Range(clipPos(this, ranges[i].anchor), - clipPos(this, ranges[i].head)); - if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); - setSelection(this, normalizeSelection(out, primary), options); - }), - addSelection: docMethodOp(function(anchor, head, options) { - var ranges = this.sel.ranges.slice(0); - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); - setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); - }), - - getSelection: function(lineSep) { - var ranges = this.sel.ranges, lines; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) return lines; - else return lines.join(lineSep || "\n"); - }, - getSelections: function(lineSep) { - var parts = [], ranges = this.sel.ranges; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - if (lineSep !== false) sel = sel.join(lineSep || "\n"); - parts[i] = sel; - } - return parts; - }, - replaceSelection: function(code, collapse, origin) { - var dup = []; - for (var i = 0; i < this.sel.ranges.length; i++) - dup[i] = code; - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function(code, collapse, origin) { - var changes = [], sel = this.sel; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin}; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i = changes.length - 1; i >= 0; i--) - makeChange(this, changes[i]); - if (newSel) setSelectionReplaceHistory(this, newSel); - else if (this.cm) ensureCursorVisible(this.cm); - }), - undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), - redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), - undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), - redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), - - setExtending: function(val) {this.extend = val;}, - getExtending: function() {return this.extend;}, - - historySize: function() { - var hist = this.history, done = 0, undone = 0; - for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; - for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; - return {undo: done, redo: undone}; - }, - clearHistory: function() {this.history = new History(this.history.maxGeneration);}, - - markClean: function() { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function(forceSplit) { - if (forceSplit) - this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; - return this.history.generation; - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration); - }, - - getHistory: function() { - return {done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone)}; - }, - setHistory: function(histData) { - var hist = this.history = new History(this.history.maxGeneration); - hist.done = copyHistoryArray(histData.done.slice(0), null, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - - addLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop]) line[prop] = cls; - else if (classTest(cls).test(line[prop])) return false; - else line[prop] += " " + cls; - return true; - }); - }), - removeLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop]; - if (!cur) return false; - else if (cls == null) line[prop] = null; - else { - var found = cur.match(classTest(cls)); - if (!found) return false; - var end = found.index + found[0].length; - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + + function copyableRanges (cm) { + var text = [], ranges = []; + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line; + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); } - return true; - }); - }), - - addLineWidget: docMethodOp(function(handle, node, options) { - return addLineWidget(this, handle, node, options); - }), - removeLineWidget: function(widget) { widget.clear(); }, - - markText: function(from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); - }, - setBookmark: function(pos, options) { - var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents}; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark"); - }, - findMarksAt: function(pos) { - pos = clipPos(this, pos); - var markers = [], spans = getLine(this, pos.line).markedSpans; - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if ((span.from == null || span.from <= pos.ch) && - (span.to == null || span.to >= pos.ch)) - markers.push(span.marker.parent || span.marker); - } - return markers; - }, - findMarks: function(from, to, filter) { - from = clipPos(this, from); to = clipPos(this, to); - var found = [], lineNo = from.line; - this.iter(from.line, to.line + 1, function(line) { - var spans = line.markedSpans; - if (spans) for (var i = 0; i < spans.length; i++) { - var span = spans[i]; - if (!(lineNo == from.line && from.ch > span.to || - span.from == null && lineNo != from.line|| - lineNo == to.line && span.from > to.ch) && - (!filter || filter(span.marker))) - found.push(span.marker.parent || span.marker); - } - ++lineNo; - }); - return found; - }, - getAllMarks: function() { - var markers = []; - this.iter(function(line) { - var sps = line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) - if (sps[i].from != null) markers.push(sps[i].marker); - }); - return markers; - }, - - posFromIndex: function(off) { - var ch, lineNo = this.first; - this.iter(function(line) { - var sz = line.text.length + 1; - if (sz > off) { ch = off; return true; } - off -= sz; - ++lineNo; - }); - return clipPos(this, Pos(lineNo, ch)); - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) return 0; - this.iter(this.first, coords.line, function (line) { - index += line.text.length + 1; - }); - return index; - }, - - copy: function(copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); - doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc; - }, - - linkedDoc: function(options) { - if (!options) options = {}; - var from = this.first, to = this.first + this.size; - if (options.from != null && options.from > from) from = options.from; - if (options.to != null && options.to < to) to = options.to; - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); - if (options.sharedHist) copy.history = this.history; - (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); - copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy; - }, - unlinkDoc: function(other) { - if (other instanceof CodeMirror) other = other.doc; - if (this.linked) for (var i = 0; i < this.linked.length; ++i) { - var link = this.linked[i]; - if (link.doc != other) continue; - this.linked.splice(i, 1); - other.unlinkDoc(this); - detachSharedMarkers(findSharedMarkers(this)); - break; - } - // If the histories were shared, split them again - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); - other.history = new History(null); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function(f) {linkedDocs(this, f);}, - - getMode: function() {return this.mode;}, - getEditor: function() {return this.cm;} - }); - - // Public alias. - Doc.prototype.eachLine = Doc.prototype.iter; - - // Set up methods on CodeMirror's prototype to redirect to the editor's document. - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) - CodeMirror.prototype[prop] = (function(method) { - return function() {return method.apply(this.doc, arguments);}; - })(Doc.prototype[prop]); - - eventMixin(Doc); - - // Call f for all linked documents. - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc, skip, sharedHist) { - if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { - var rel = doc.linked[i]; - if (rel.doc == skip) continue; - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) continue; - f(rel.doc, shared); - propagate(rel.doc, doc, shared); - } - } - propagate(doc, null, true); - } - - // Attach a document to an editor. - function attachDoc(cm, doc) { - if (doc.cm) throw new Error("This document is already in use."); - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - if (!cm.options.lineWrapping) findMaxLine(cm); - cm.options.mode = doc.modeOption; - regChange(cm); - } - - // LINE UTILITIES - - // Find the line object corresponding to the given line number. - function getLine(doc, n) { - n -= doc.first; - if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); - for (var chunk = doc; !chunk.lines;) { - for (var i = 0;; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; break; } - n -= sz; - } - } - return chunk.lines[n]; - } - - // Get the part of a document between two positions, as an array of - // strings. - function getBetween(doc, start, end) { - var out = [], n = start.line; - doc.iter(start.line, end.line + 1, function(line) { - var text = line.text; - if (n == end.line) text = text.slice(0, end.ch); - if (n == start.line) text = text.slice(start.ch); - out.push(text); - ++n; - }); - return out; - } - // Get the lines between from and to, as array of strings. - function getLines(doc, from, to, lineFilter) { - var out = []; - doc.iter(from, to, function(line) { - var text = line.text; - if(lineFilter){ - text = lineFilter(line); - } - out.push(text); - }); - return out; - } - - // Update the height of a line, propagating the height change - // upwards to parent nodes. - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) for (var n = line; n; n = n.parent) n.height += diff; - } - - // Given a line object, find its line number by walking up through - // its parent links. - function lineNo(line) { - if (line.parent == null) return null; - var cur = line.parent, no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0;; ++i) { - if (chunk.children[i] == cur) break; - no += chunk.children[i].chunkSize(); - } - } - return no + cur.first; - } - - // Find the line at the given vertical position, using the height - // information in the document tree. - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i = 0; i < chunk.children.length; ++i) { - var child = chunk.children[i], ch = child.height; - if (h < ch) { chunk = child; continue outer; } - h -= ch; - n += child.chunkSize(); - } - return n; - } while (!chunk.lines); - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i], lh = line.height; - if (h < lh) break; - h -= lh; - } - return n + i; - } - - - // Find the height above the given line. - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - - var h = 0, chunk = lineObj.parent; - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i]; - if (line == lineObj) break; - else h += line.height; - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i = 0; i < p.children.length; ++i) { - var cur = p.children[i]; - if (cur == chunk) break; - else h += cur.height; - } - } - return h; - } - - // Get the bidi ordering for the given line (and cache it). Returns - // false for lines that are fully left-to-right, and an array of - // BidiSpan objects otherwise. - function getOrder(line) { - var order = line.order; - if (order == null) order = line.order = bidiOrdering(line.text); - return order; - } - - // HISTORY - - function History(startGen) { - // Arrays of change events and selections. Doing something adds an - // event to done and clears undo. Undoing moves events from done - // to undone, redoing moves them in the other direction. - this.done = []; this.undone = []; - this.undoDepth = Infinity; - // Used to track when changes can be merged into a single undo - // event - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - // Used by the isClean() method - this.generation = this.maxGeneration = startGen || 1; - } - - // Create a history change event from an updateDoc-style change - // object. - function historyChangeFromChange(doc, change) { - var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); - return histChange; - } - - // Pop all selection events off the end of a history array. Stop at - // a change event. - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) array.pop(); - else break; - } - } - - // Find the top change event in the history. Pop off selection - // events that are in the way. - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done); - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done); - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done); - } - } - - // Register a change in the history. Merges changes that are within - // a single operation, ore are close together with an origin that - // allows merging (starting with "+") into a single event. - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = +new Date, cur; - - if ((hist.lastOp == opId || - hist.lastOrigin == change.origin && change.origin && - ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || - change.origin.charAt(0) == "*")) && - (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - // Merge this change into the last event - var last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - // Optimized case for simple insertion -- don't want to add - // new changesets for every character typed - last.to = changeEnd(change); - } else { - // Add new sub-event - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - // Can not be merged, start a new event. - var before = lst(hist.done); - if (!before || !before.ranges) - pushSelectionToHistory(doc.sel, hist.done); - cur = {changes: [historyChangeFromChange(doc, change)], - generation: hist.generation}; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!hist.done[0].ranges) hist.done.shift(); - } - } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - - if (!last) signal(doc, "historyAdded"); - } - - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || - ch == "+" && - prev.ranges.length == sel.ranges.length && - prev.somethingSelected() == sel.somethingSelected() && - new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); - } - - // Called whenever the selection changes, sets the new selection as - // the pending selection in the history, and pushes the old pending - // selection into the 'done' array when it was significantly - // different (in number of selected ranges, emptiness, or time). - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, origin = options && options.origin; - - // A new event is started when the previous origin does not match - // the current, or the origins don't allow matching. Origins - // starting with * are always merged, those starting with + are - // merged when similar and close together in time. - if (opId == hist.lastSelOp || - (origin && hist.lastSelOrigin == origin && - (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || - selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) - hist.done[hist.done.length - 1] = sel; - else - pushSelectionToHistory(sel, hist.done); - - hist.lastSelTime = +new Date; - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) - clearSelectionEvents(hist.undone); - } - - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) - dest.push(sel); - } - - // Used to store marked span information in the history. - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { - if (line.markedSpans) - (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; - ++n; - }); - } - - // When un/re-doing restores text containing marked spans, those - // that have been explicitly cleared should not be restored. - function removeClearedSpans(spans) { - if (!spans) return null; - for (var i = 0, out; i < spans.length; ++i) { - if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } - else if (out) out.push(spans[i]); - } - return !out ? spans : out.length ? out : null; - } - - // Retrieve and filter the old marked spans stored in a change event. - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) return null; - for (var i = 0, nw = []; i < change.text.length; ++i) - nw.push(removeClearedSpans(found[i])); - return nw; - } - - // Used both to provide a JSON-safe object in .getHistory, and, when - // detaching a document, to split the history in two - function copyHistoryArray(events, newGroup, instantiateSel) { - for (var i = 0, copy = []; i < events.length; ++i) { - var event = events[i]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue; - } - var changes = event.changes, newChanges = []; - copy.push({changes: newChanges}); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], m; - newChanges.push({from: change.from, to: change.to, text: change.text}); - if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop] = change[prop]; - delete change[prop]; - } - } - } - } - return copy; - } - - // Rebasing/resetting history to deal with externally-sourced changes - - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - - // Tries to rebase an array of history events given a change in the - // document. If the change touches the same lines as the event, the - // event, and everything 'behind' it, is discarded. If the change is - // before the event, the event's positions are updated. Uses a - // copy-on-write scheme for the positions, to avoid having to - // reallocate them all on every rebase, but also avoid problems with - // shared position objects being unsafely updated. - function rebaseHistArray(array, from, to, diff) { - for (var i = 0; i < array.length; ++i) { - var sub = array[i], ok = true; - if (sub.ranges) { - if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } - for (var j = 0; j < sub.ranges.length; j++) { - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); - } - continue; - } - for (var j = 0; j < sub.changes.length; ++j) { - var cur = sub.changes[j]; - if (to < cur.from.line) { - cur.from = Pos(cur.from.line + diff, cur.from.ch); - cur.to = Pos(cur.to.line + diff, cur.to.ch); - } else if (from <= cur.to.line) { - ok = false; - break; - } - } - if (!ok) { - array.splice(0, i + 1); - i = 0; - } - } - } - - function rebaseHist(hist, change) { - var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - - // EVENT UTILITIES - - // Due to the fact that we still support jurassic IE versions, some - // compatibility wrappers are needed. - - var e_preventDefault = CodeMirror.e_preventDefault = function(e) { - if (e.preventDefault) e.preventDefault(); - else e.returnValue = false; - }; - var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { - if (e.stopPropagation) e.stopPropagation(); - else e.cancelBubble = true; - }; - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; - } - var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; - - function e_target(e) {return e.target || e.srcElement;} - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) b = 1; - else if (e.button & 2) b = 3; - else if (e.button & 4) b = 2; - } - if (mac && e.ctrlKey && b == 1) b = 3; - return b; - } - - // EVENT HANDLING - - // Lightweight event framework. on/off also work on DOM nodes, - // registering native DOM handlers. - - var on = CodeMirror.on = function(emitter, type, f) { - if (emitter.addEventListener) - emitter.addEventListener(type, f, false); - else if (emitter.attachEvent) - emitter.attachEvent("on" + type, f); - else { - var map = emitter._handlers || (emitter._handlers = {}); - var arr = map[type] || (map[type] = []); - arr.push(f); - } - }; - - var off = CodeMirror.off = function(emitter, type, f) { - if (emitter.removeEventListener) - emitter.removeEventListener(type, f, false); - else if (emitter.detachEvent) - emitter.detachEvent("on" + type, f); - else { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - for (var i = 0; i < arr.length; ++i) - if (arr[i] == f) { arr.splice(i, 1); break; } - } - }; - - var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - var args = Array.prototype.slice.call(arguments, 2); - for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); - }; - - var orphanDelayedCallbacks = null; - - // Often, we want to signal events at a point where we are in the - // middle of some work, but don't want the handler to start calling - // other methods on the editor, which might be in an inconsistent - // state or simply not expect any other events to happen. - // signalLater looks whether there are any handlers, and schedules - // them to be executed when the last operation ends, or, if no - // operation is active, when a timeout fires. - function signalLater(emitter, type /*, values...*/) { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - var args = Array.prototype.slice.call(arguments, 2), list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - function bnd(f) {return function(){f.apply(null, args);};}; - for (var i = 0; i < arr.length; ++i) - list.push(bnd(arr[i])); - } - - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) delayed[i](); - } - - // The DOM events that CodeMirror handles can be overridden by - // registering a (non-DOM) handler on the editor for the event name, - // and preventDefault-ing the event in that handler. - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") - e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore; - } - - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) return; - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) - set.push(arr[i]); - } - - function hasHandler(emitter, type) { - var arr = emitter._handlers && emitter._handlers[type]; - return arr && arr.length > 0; - } - - // Add on and off methods to a constructor's prototype, to make - // registering events on such objects more convenient. - function eventMixin(ctor) { - ctor.prototype.on = function(type, f) {on(this, type, f);}; - ctor.prototype.off = function(type, f) {off(this, type, f);}; - } - - // MISC UTILITIES - - // Number of pixels added to scroller and sizer to hide scrollbar - var scrollerGap = 30; - - // Returned or thrown by various protocols to signal 'I'm not - // handling this'. - var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; - - // Reused option objects for setSelection & friends - var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; - - function Delayed() {this.id = null;} - Delayed.prototype.set = function(ms, f) { - clearTimeout(this.id); - this.id = setTimeout(f, ms); - }; - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) end = string.length; - } - for (var i = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf("\t", i); - if (nextTab < 0 || nextTab >= end) - return n + (end - i); - n += nextTab - i; - n += tabSize - (n % tabSize); - i = nextTab + 1; - } - }; - - // The inverse of countColumn -- find the offset that corresponds to - // a particular column. - function findColumn(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf("\t", pos); - if (nextTab == -1) nextTab = string.length; - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) - return pos + Math.min(skipped, goal - col); - col += nextTab - pos; - col += tabSize - (col % tabSize); - pos = nextTab + 1; - if (col >= goal) return pos; - } - } - - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) - spaceStrs.push(lst(spaceStrs) + " "); - return spaceStrs[n]; - } - - function lst(arr) { return arr[arr.length-1]; } - - var selectInput = function(node) { node.select(); }; - if (ios) // Mobile Safari apparently has a bug where select() is broken. - selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; - else if (ie) // Suppress mysterious IE10 errors - selectInput = function(node) { try { node.select(); } catch(_e) {} }; - - function indexOf(array, elt) { - for (var i = 0; i < array.length; ++i) - if (array[i] == elt) return i; - return -1; - } - function map(array, f) { - var out = []; - for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); - return out; - } - - function nothing() {} - - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) copyObj(props, inst); - return inst; - }; - - function copyObj(obj, target, overwrite) { - if (!target) target = {}; - for (var prop in obj) - if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) - target[prop] = obj[prop]; - return target; - } - - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function(){return f.apply(null, args);}; - } - - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - var isWordCharBasic = CodeMirror.isWordChar = function(ch) { - return /\w/.test(ch) || ch > "\x80" && - (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); - }; - function isWordChar(ch, helper) { - if (!helper) return isWordCharBasic(ch); - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; - return helper.test(ch); - } - - function isEmpty(obj) { - for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; - return true; - } - - // Extending unicode characters. A series of a non-extending char + - // any number of extending chars is treated as a single unit as far - // as editing and measuring is concerned. This is not fully correct, - // since some scripts/font/browsers also treat other configurations - // of code points as a group. - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; - function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } - - // DOM UTILITIES - - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) e.className = className; - if (style) e.style.cssText = style; - if (typeof content == "string") e.appendChild(document.createTextNode(content)); - else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); - return e; - } - - var range; - if (document.createRange) range = function(node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r; - }; - else range = function(node, start, end) { - var r = document.body.createTextRange(); - try { r.moveToElementText(node.parentNode); } - catch(e) { return r; } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r; - }; - - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) - e.removeChild(e.firstChild); - return e; - } - - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e); - } - - var contains = CodeMirror.contains = function(parent, child) { - if (child.nodeType == 3) // Android browser always returns false when child is a textnode - child = child.parentNode; - if (parent.contains) - return parent.contains(child); - do { - if (child.nodeType == 11) child = child.host; - if (child == parent) return true; - } while (child = child.parentNode); - }; - - function activeElt() { return document.activeElement; } - // Older versions of IE throws unspecified error when touching - // document.activeElement in some cases (during loading, in iframe) - if (ie && ie_version < 11) activeElt = function() { - try { return document.activeElement; } - catch(e) { return document.body; } - }; - - function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } - var rmClass = CodeMirror.rmClass = function(node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - var addClass = CodeMirror.addClass = function(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; - }; - function joinClasses(a, b) { - var as = a.split(" "); - for (var i = 0; i < as.length; i++) - if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; - return b; - } - - // WINDOW-WIDE EVENTS - - // These must be handled carefully, because naively registering a - // handler for each editor will cause the editors to never be - // garbage collected. - - function forEachCodeMirror(f) { - if (!document.body.getElementsByClassName) return; - var byClass = document.body.getElementsByClassName("CodeMirror"); - for (var i = 0; i < byClass.length; i++) { - var cm = byClass[i].CodeMirror; - if (cm) f(cm); - } - } - - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) return; - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { - // When the window resizes, we need to refresh active editors. - var resizeTimer; - on(window, "resize", function() { - if (resizeTimer == null) resizeTimer = setTimeout(function() { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); - }); - // When the window loses focus, we want to show the editor as blurred - on(window, "blur", function() { - forEachCodeMirror(onBlur); - }); - } + return {text: text, ranges: ranges}; + } - // FEATURE DETECTION + function disableBrowserMagic (field) { + field.setAttribute("autocorrect", "off"); + field.setAttribute("autocapitalize", "off"); + field.setAttribute("spellcheck", "false"); + } - // Detect drag-and-drop - var dragAndDrop = function() { - // There is *some* kind of drag-and-drop support in IE6-8, but I - // couldn't get it to work yet. - if (ie && ie_version < 9) return false; - var div = elt('div'); - return "draggable" in div || "dragDrop" in div; - }(); - - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "\u200b"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) - zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); - } - var node = zwspSupported ? elt("span", "\u200b") : - elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node; - } - - // Feature-detect IE's crummy client rect reporting for bidi text - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) return badBidiRects; - var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) - var r1 = range(txt, 1, 2).getBoundingClientRect(); - return badBidiRects = (r1.right - r0.right < 3); - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { - var pos = 0, result = [], l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) nl = string.length; - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result; - } : function(string){return string.split(/\r\n?|\n/);}; - - var hasSelection = window.getSelection ? function(te) { - try { return te.selectionStart != te.selectionEnd; } - catch(e) { return false; } - } : function(te) { - try {var range = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range || range.parentElement() != te) return false; - return range.compareEndPoints("StartToEnd", range) != 0; - }; - - var hasCopyEvent = (function() { - var e = elt("div"); - if ("oncopy" in e) return true; - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function"; - })(); - - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) return badZoomedRects; - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; - } - - // KEY NAMES - - var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", - 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", - 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", - 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", - 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", - 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", - 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; - CodeMirror.keyNames = keyNames; - (function() { - // Number keys - for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); - // Alphabetic keys - for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); - // Function keys - for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; - })(); - - // BIDI HELPERS - - function iterateBidiSections(order, from, to, f) { - if (!order) return f(from, to, "ltr"); - var found = false; - for (var i = 0; i < order.length; ++i) { - var part = order[i]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); - found = true; - } - } - if (!found) f(from, to, "ltr"); - } - - function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } - function bidiRight(part) { return part.level % 2 ? part.from : part.to; } - - function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } - function lineRight(line) { - var order = getOrder(line); - if (!order) return line.text.length; - return bidiRight(lst(order)); - } - - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) lineN = lineNo(visual); - var order = getOrder(visual); - var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); - return Pos(lineN, ch); - } - function lineEnd(cm, lineN) { - var merged, line = getLine(cm.doc, lineN); - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - lineN = null; - } - var order = getOrder(line); - var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); - return Pos(lineN == null ? lineNo(line) : lineN, ch); - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(0, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS); - } - return start; - } - - function compareBidiLevel(order, a, b) { - var linedir = order[0].level; - if (a == linedir) return true; - if (b == linedir) return false; - return a < b; - } - var bidiOther; - function getBidiPartAt(order, pos) { - bidiOther = null; - for (var i = 0, found; i < order.length; ++i) { - var cur = order[i]; - if (cur.from < pos && cur.to > pos) return i; - if ((cur.from == pos || cur.to == pos)) { - if (found == null) { - found = i; - } else if (compareBidiLevel(order, cur.level, order[found].level)) { - if (cur.from != cur.to) bidiOther = found; - return i; - } else { - if (cur.from != cur.to) bidiOther = i; - return found; - } - } - } - return found; - } - - function moveInLine(line, pos, dir, byUnit) { - if (!byUnit) return pos + dir; - do pos += dir; - while (pos > 0 && isExtendingChar(line.text.charAt(pos))); - return pos; - } - - // This is needed in order to move 'visually' through bi-directional - // text -- i.e., pressing left should make the cursor go left, even - // when in RTL text. The tricky part is the 'jumps', where RTL and - // LTR text touch each other. This often requires the cursor offset - // to move more than one unit, in order to visually move one unit. - function moveVisually(line, start, dir, byUnit) { - var bidi = getOrder(line); - if (!bidi) return moveLogically(line, start, dir, byUnit); - var pos = getBidiPartAt(bidi, start), part = bidi[pos]; - var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); - - for (;;) { - if (target > part.from && target < part.to) return target; - if (target == part.from || target == part.to) { - if (getBidiPartAt(bidi, target) == pos) return target; - part = bidi[pos += dir]; - return (dir > 0) == part.level % 2 ? part.to : part.from; - } else { - part = bidi[pos += dir]; - if (!part) return null; - if ((dir > 0) == part.level % 2) - target = moveInLine(line, part.to, -1, byUnit); - else - target = moveInLine(line, part.from, 1, byUnit); - } - } - } - - function moveLogically(line, start, dir, byUnit) { - var target = start + dir; - if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; - return target < 0 || target > line.text.length ? null : target; - } - - // Bidirectional ordering algorithm - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm - // that this (partially) implements. - - // One-char codes used for character types: - // L (L): Left-to-Right - // R (R): Right-to-Left - // r (AL): Right-to-Left Arabic - // 1 (EN): European Number - // + (ES): European Number Separator - // % (ET): European Number Terminator - // n (AN): Arabic Number - // , (CS): Common Number Separator - // m (NSM): Non-Spacing Mark - // b (BN): Boundary Neutral - // s (B): Paragraph Separator - // t (S): Segment Separator - // w (WS): Whitespace - // N (ON): Other Neutrals - - // Returns null if characters are ordered as they appear - // (left-to-right), or an array of sections ({from, to, level} - // objects) in the order in which they occur visually. - var bidiOrdering = (function() { - // Character types for codepoints 0 to 0xff - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - // Character types for codepoints 0x600 to 0x6ff - var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; - function charType(code) { - if (code <= 0xf7) return lowTypes.charAt(code); - else if (0x590 <= code && code <= 0x5f4) return "R"; - else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); - else if (0x6ee <= code && code <= 0x8ac) return "r"; - else if (0x2000 <= code && code <= 0x200b) return "w"; - else if (code == 0x200c) return "b"; - else return "L"; - } - - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; - // Browsers seem to always treat the boundaries of block elements as being L. - var outerType = "L"; - - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; this.to = to; - } - - return function(str) { - if (!bidiRE.test(str)) return false; - var len = str.length, types = []; - for (var i = 0, type; i < len; ++i) - types.push(type = charType(str.charCodeAt(i))); - - // W1. Examine each non-spacing mark (NSM) in the level run, and - // change the type of the NSM to the type of the previous - // character. If the NSM is at the start of the level run, it will - // get the type of sor. - for (var i = 0, prev = outerType; i < len; ++i) { - var type = types[i]; - if (type == "m") types[i] = prev; - else prev = type; - } - - // W2. Search backwards from each instance of a European number - // until the first strong type (R, L, AL, or sor) is found. If an - // AL is found, change the type of the European number to Arabic - // number. - // W3. Change all ALs to R. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (type == "1" && cur == "r") types[i] = "n"; - else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } - } - - // W4. A single European separator between two European numbers - // changes to a European number. A single common separator between - // two numbers of the same type changes to that type. - for (var i = 1, prev = types[0]; i < len - 1; ++i) { - var type = types[i]; - if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; - else if (type == "," && prev == types[i+1] && - (prev == "1" || prev == "n")) types[i] = prev; - prev = type; - } - - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - for (var i = 0; i < len; ++i) { - var type = types[i]; - if (type == ",") types[i] = "N"; - else if (type == "%") { - for (var end = i + 1; end < len && types[end] == "%"; ++end) {} - var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // W7. Search backwards from each instance of a European number - // until the first strong type (R, L, or sor) is found. If an L is - // found, then change the type of the European number to L. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (cur == "L" && type == "1") types[i] = "L"; - else if (isStrong.test(type)) cur = type; - } - - // N1. A sequence of neutrals takes the direction of the - // surrounding strong text if the text on both sides has the same - // direction. European and Arabic numbers act as if they were R in - // terms of their influence on neutrals. Start-of-level-run (sor) - // and end-of-level-run (eor) are used at level run boundaries. - // N2. Any remaining neutrals take the embedding direction. - for (var i = 0; i < len; ++i) { - if (isNeutral.test(types[i])) { - for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} - var before = (i ? types[i-1] : outerType) == "L"; - var after = (end < len ? types[end] : outerType) == "L"; - var replace = before || after ? "L" : "R"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - var order = [], m; - for (var i = 0; i < len;) { - if (countsAsLeft.test(types[i])) { - var start = i; - for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} - order.push(new BidiSpan(0, start, i)); - } else { - var pos = i, at = order.length; - for (++i; i < len && types[i] != "L"; ++i) {} - for (var j = pos; j < i;) { - if (countsAsNum.test(types[j])) { - if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); - var nstart = j; - for (++j; j < i && countsAsNum.test(types[j]); ++j) {} - order.splice(at, 0, new BidiSpan(2, nstart, j)); - pos = j; - } else ++j; - } - if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); - } - } - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); - } - if (order[0].level == 2) - order.unshift(new BidiSpan(1, order[0].to, order[0].to)); - if (order[0].level != lst(order).level) - order.push(new BidiSpan(order[0].level, len, len)); - - return order; - }; - })(); + // TEXTAREA INPUT STYLE - // THE END + function TextareaInput (cm) { + this.cm = cm; + // See input.poll and input.reset + this.prevInput = ""; - CodeMirror.version = "5.4.1"; + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false; + // Self-resetting timeout for the poller + this.polling = new Delayed(); + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false; + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false; + this.composing = null; + } + + function hiddenTextarea () { + var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) te.style.width = "1000px"; + else te.setAttribute("wrap", "off"); + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) te.style.border = "1px solid black"; + disableBrowserMagic(te); + return div; + } + + TextareaInput.prototype = copyObj({ + init: function (display) { + var input = this, cm = this.cm; + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild; + display.wrapper.insertBefore(div, display.wrapper.firstChild); + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) te.style.width = "0px"; + + on(te, "input", function () { + if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; + input.poll(); + }); - return CodeMirror; -});(function (mod) { - mod(CodeMirror); -})(function (CodeMirror) { - var Pos = CodeMirror.Pos; + on(te, "paste", function (e) { + if (handlePaste(e, cm)) return true; - function forEach(arr, f) { - for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); - } + cm.state.pasteIncoming = true; + input.fastPoll(); + }); - function arrayContains(arr, item) { - if (!Array.prototype.indexOf) { - var i = arr.length; - while (i--) { - if (arr[i] === item) { - return true; + function prepareCopyCut (e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (input.inaccurateSelection) { + input.prevInput = ""; + input.inaccurateSelection = false; + te.value = lastCopied.join("\n"); + selectInput(te); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } } + if (e.type == "cut") cm.state.cutIncoming = true; } - return false; - } - return arr.indexOf(item) != -1; - } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); - function scriptHint(editor, keywords, getToken, options) { - // Find the token at the cursor - var cur = editor.getCursor(), token = getToken(editor, cur); - if (/\b(?:string)\b/.test(token.type)) { - return; - } - token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e)) return; + cm.state.pasteIncoming = true; + input.focus(); + }); - if (!/^[\w$_]*$/.test(token.string)) { - token = { - start: cur.ch, end: cur.ch, string: "", state: token.state, - type: token.string == "." ? "property" : null - }; - } else if (token.end > cur.ch) { - token.end = cur.ch; - token.string = token.string.slice(0, cur.ch - token.start); - } + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) e_preventDefault(e); + }); - var tprop = token; - // If it is a property, find out what it is a property of. - while (tprop.type == "property") { - tprop = getToken(editor, Pos(cur.line, tprop.start)); - if (tprop.string != ".") return; - tprop = getToken(editor, Pos(cur.line, tprop.start)); - if (!context) var context = []; - context.push(tprop); - } - return { - list: getCompletions(token, context, keywords, options), - from: Pos(cur.line, token.start), - to: Pos(cur.line, token.end) - }; - } + on(te, "compositionstart", function () { + var start = cm.getCursor("from"); + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + }; + }); + on(te, "compositionend", function () { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }, - function getFormulaKeywords() { - return BI.FormulaCollections; - } + prepareSelection: function () { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc; + var result = prepareSelection(cm); - function formulaHint(editor, options) { - return scriptHint(editor, getFormulaKeywords(), - function (e, cur) { - return e.getTokenAt(cur); - }, - options); - }; - CodeMirror.registerHelper("hint", "formula", formulaHint); + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)); + } - function getCompletions(token, context, keywords, options) { - var found = [], start = token.string; - if (!start) { - return found; - } - function maybeAdd(str) { - if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) { - found.push(str); + return result; + }, + + showSelection: function (drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; } - } + }, - if (context && context.length) { - context.pop(); - } else { - forEach(keywords, maybeAdd); - } - return found; - } -});(function (mod) { - mod(CodeMirror); -})(function (CodeMirror) { - "use strict"; + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + reset: function (typing) { + if (this.contextMenuPending) return; + var minimal, selected, cm = this.cm, doc = cm.doc; + if (cm.somethingSelected()) { + this.prevInput = ""; + var range = doc.sel.primary(); + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); + var content = minimal ? "-" : selected || cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) selectInput(this.textarea); + if (ie && ie_version >= 9) this.hasSelection = content; + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) this.hasSelection = null; + } + this.inaccurateSelection = minimal; + }, - CodeMirror.defineMode('formula', function () { - function wordObj(words) { - var o = {}; - for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; - return o; - } + getField: function () { return this.textarea; }, - var atoms = wordObj(['false', 'true']); - var keywords = wordObj(BI.FormulaCollections); + supportsTouch: function () { return false; }, - function tokenBase(stream, state) { - if (stream.eatSpace()) { - return null; + focus: function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus(); } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM } - var ch = stream.next(); + }, - if (ch === '"' || ch === '\'') { - nextUntilUnescaped(stream, ch); - return "string"; - } - if (ch === '\u200b') { - nextUntilUnescaped(stream, ch); - return "field"; - } - if (/[\[\],\(\)]/.test(ch)) { - return 'bracket'; - } + blur: function () { this.textarea.blur(); }, - // richie:暂时不需要解析操作符号 - //if (/[+\-*\/=<>!&|]/.test(ch)) { - // return 'operator'; - //} - //if (/\d|\d./.test(ch)) { - // stream.eatWhile(/\d|\./); - // if (stream.eol() || !/\w/.test(stream.peek())) { - // return 'number'; - // } - //} + resetPosition: function () { + this.wrapper.style.top = this.wrapper.style.left = 0; + }, + receivedFocus: function () { this.slowPoll(); }, + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + slowPoll: function () { + var input = this; + if (input.pollingFast) return; + input.polling.set(this.cm.options.pollInterval, function () { + input.poll(); + if (input.cm.state.focused) input.slowPoll(); + }); + }, + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + fastPoll: function () { + var missed = false, input = this; + input.pollingFast = true; + function p () { + var changed = input.poll(); + if (!changed && !missed) {missed = true; input.polling.set(60, p);} else {input.pollingFast = false; input.slowPoll();} + } + input.polling.set(20, p); + }, - stream.eatWhile(/[\w-]/); - var word = stream.current(); - if (atoms.hasOwnProperty(word)) { - return "atom"; + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + poll: function () { + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput) || + isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq) {return false;} + + var text = input.value; + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) return false; + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false; } - if (keywords.hasOwnProperty(word)) { - return "keyword"; + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 0x200b && !prevInput) prevInput = "\u200b"; + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } } - return null; - } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; - function nextUntilUnescaped(stream, end) { - var escaped = false, next; - while ((next = stream.next()) != null) { - if (next === end && !escaped) { - return false; + var self = this; + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, self.composing ? "*compose" : null); + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; + else self.prevInput = text; + + if (self.composing) { + self.composing.range.clear(); + self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}); } - escaped = !escaped && next === "\\"; - } - return escaped; - } + }); + return true; + }, - function tokenize(stream, state) { - return (state.tokens[0] || tokenBase)(stream, state); - } + ensurePolled: function () { + if (this.pollingFast && this.poll()) this.pollingFast = false; + }, - return { - startState: function () { - return {tokens: []}; - }, - token: function (stream, state) { - return tokenize(stream, state); - }, - fold: "brace" - }; - }); - CodeMirror.defineMIME("text/fx-formula", "formula"); -});// CodeMirror, copyright (c) by Marijn Haverbeke and others -// Distributed under an MIT license: http://codemirror.net/LICENSE + onKeyPress: function () { + if (ie && ie_version >= 9) this.hasSelection = null; + this.fastPoll(); + }, -(function (mod) { - mod(CodeMirror); -})(function (CodeMirror) { - "use strict"; + onContextMenu: function (e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) return; // Opera is difficult. - var HINT_ELEMENT_CLASS = "CodeMirror-hint"; - var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) {operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);} - // This is the old interface, kept around for now to stay - // backwards-compatible. - CodeMirror.showHint = function (cm, getHints, options) { - if (!getHints) return cm.showHint(options); - if (options && options.async) getHints.async = true; - var newOpts = {hint: getHints}; - if (options) for (var prop in options) newOpts[prop] = options[prop]; - return cm.showHint(newOpts); - }; + var oldCSS = te.style.cssText; + input.wrapper.style.position = "absolute"; + te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + + "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) + display.input.focus(); + if (webkit) window.scrollTo(null, oldScrollY); + display.input.reset(); + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) te.value = input.prevInput = " "; + input.contextMenuPending = true; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack () { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "\u200b" + (selected ? te.value : ""); + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval; + input.prevInput = selected ? "" : "\u200b"; + te.selectionStart = 1; te.selectionEnd = extval.length; + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel; + } + } + function rehide () { + input.contextMenuPending = false; + input.wrapper.style.position = "relative"; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") {operation(cm, commands.selectAll)(cm);} else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); + else display.input.reset(); + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } - CodeMirror.defineExtension("showHint", function (options) { - // We want a single cursor position. - if (this.listSelections().length > 1 || this.somethingSelected()) return; + if (ie && ie_version >= 9) prepareSelectAllHack(); + if (captureRightClick) { + e_stop(e); + var mouseup = function () { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }, - if (this.state.completionActive) this.state.completionActive.close(); - var completion = this.state.completionActive = new Completion(this, options); - if (!completion.options.hint) return; + setUneditable: nothing, - CodeMirror.signal(this, "startCompletion", this); - completion.update(true); - }); + needsContentAttribute: false + }, TextareaInput.prototype); + + // CONTENTEDITABLE INPUT STYLE - function Completion(cm, options) { + function ContentEditableInput (cm) { this.cm = cm; - this.options = this.buildOptions(options); - this.widget = null; - this.debounce = 0; - this.tick = 0; - this.startPos = this.cm.getCursor(); - this.startLen = this.cm.getLine(this.startPos.line).length; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.gracePeriod = false; + } + + ContentEditableInput.prototype = copyObj({ + init: function (display) { + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + div.contentEditable = "true"; + disableBrowserMagic(div); + + on(div, "paste", function (e) { handlePaste(e, cm); }); + + on(div, "compositionstart", function (e) { + var data = e.data; + input.composing = {sel: cm.doc.sel, data: data, startData: data}; + if (!data) return; + var prim = cm.doc.sel.primary(); + var line = cm.getLine(prim.head.line); + var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); + if (found > -1 && found <= prim.head.ch) { + input.composing.sel = simpleSelection(Pos(prim.head.line, found), + Pos(prim.head.line, found + data.length)); + } + }); + on(div, "compositionupdate", function (e) { + input.composing.data = e.data; + }); + on(div, "compositionend", function (e) { + var ours = input.composing; + if (!ours) return; + if (e.data != ours.startData && !/\u200b/.test(e.data)) {ours.data = e.data;} + // Need a small delay to prevent other code (input event, + // selection polling) from doing damage when fired right after + // compositionend. + setTimeout(function () { + if (!ours.handled) {input.applyComposition(ours);} + if (input.composing == ours) {input.composing = null;} + }, 50); + }); - var self = this; - cm.on("cursorActivity", this.activityFunc = function () { - self.cursorActivity(); - }); - } + on(div, "touchstart", function () { + input.forceCompositionEnd(); + }); - var requestAnimationFrame = window.requestAnimationFrame || function (fn) { - return setTimeout(fn, 1000 / 60); - }; - var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; + on(div, "input", function () { + if (input.composing) return; + if (!input.pollContent()) {runInOp(input.cm, function () {regChange(cm);});} + }); - Completion.prototype = { - close: function () { - if (!this.active()) return; - this.cm.state.completionActive = null; - this.tick = null; - this.cm.off("cursorActivity", this.activityFunc); + function onCopyCut (e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (e.type == "cut") cm.replaceSelection("", null, "cut"); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + // iOS exposes the clipboard API, but seems to discard content inserted into it + if (e.clipboardData && !ios) { + e.preventDefault(); + e.clipboardData.clearData(); + e.clipboardData.setData("text/plain", lastCopied.join("\n")); + } else { + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.join("\n"); + var hadFocus = document.activeElement; + selectInput(te); + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + }, 50); + } + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }, - if (this.widget && this.data) CodeMirror.signal(this.data, "close"); - if (this.widget) this.widget.close(); - CodeMirror.signal(this.cm, "endCompletion", this.cm); + prepareSelection: function () { + var result = prepareSelection(this.cm, false); + result.focus = this.cm.state.focused; + return result; }, - active: function () { - return this.cm.state.completionActive == this; + showSelection: function (info) { + if (!info || !this.cm.display.view.length) return; + if (info.focus) this.showPrimarySelection(); + this.showMultipleSelections(info); }, - pick: function (data, i) { - var completion = data.list[i]; - if (completion.hint) completion.hint(this.cm, data, completion); - else { - this.cm.replaceRange(getText(completion), completion.from || data.from, - completion.to || data.to, "complete"); - if(completion.isKeyword === true){ - }else{ - var to = this.cm.getCursor(); - this.cm.markText(completion.from || data.from, to, {className: "#function", atomic: true}); - this.cm.replaceSelection("() "); - to = this.cm.getCursor(); - to.ch = to.ch - 2; - this.cm.setCursor(to); - this.cm.focus(); - } - } - CodeMirror.signal(data, "pick", completion); - this.close(); + showPrimarySelection: function () { + var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); + var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && + cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) {return;} + + var start = posToDOM(this.cm, prim.from()); + var end = posToDOM(this.cm, prim.to()); + if (!start && !end) return; + + var view = this.cm.display.view; + var old = sel.rangeCount && sel.getRangeAt(0); + if (!start) { + start = {node: view[0].measure.map[2], offset: 0}; + } else if (!end) { // FIXME dangerously hacky + var measure = view[view.length - 1].measure; + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; + } + + try { var rng = range(start.node, start.offset, end.offset, end.node); } catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + sel.removeAllRanges(); + sel.addRange(rng); + if (old && sel.anchorNode == null) sel.addRange(old); + else if (gecko) this.startGracePeriod(); + } + this.rememberSelection(); }, - cursorActivity: function () { - if (this.debounce) { - cancelAnimationFrame(this.debounce); - this.debounce = 0; - } + startGracePeriod: function () { + var input = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function () { + input.gracePeriod = false; + if (input.selectionChanged()) {input.cm.operation(function () { input.cm.curOp.selectionChanged = true; });} + }, 20); + }, - var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line); - if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || - pos.ch < this.startPos.ch || this.cm.somethingSelected() || - (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) { - this.close(); - } else { - var self = this; - this.debounce = requestAnimationFrame(function () { - self.update(); - }); - if (this.widget) this.widget.disable(); - } + showMultipleSelections: function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); }, - update: function (first) { - if (this.tick == null) return; - if (this.data) CodeMirror.signal(this.data, "update"); - if (!this.options.hint.async) { - this.finishUpdate(this.options.hint(this.cm, this.options), first); - } else { - var myTick = ++this.tick, self = this; - this.options.hint(this.cm, function (data) { - if (self.tick == myTick) self.finishUpdate(data, first); - }, this.options); + rememberSelection: function () { + var sel = window.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; + }, + + selectionInEditor: function () { + var sel = window.getSelection(); + if (!sel.rangeCount) return false; + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }, + + focus: function () { + if (this.cm.options.readOnly != "nocursor") this.div.focus(); + }, + blur: function () { this.div.blur(); }, + getField: function () { return this.div; }, + + supportsTouch: function () { return true; }, + + receivedFocus: function () { + var input = this; + if (this.selectionInEditor()) {this.pollSelection();} else {runInOp(this.cm, function () { input.cm.curOp.selectionChanged = true; });} + + function poll () { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } } + this.polling.set(this.cm.options.pollInterval, poll); }, - finishUpdate: function (data, first) { - this.data = data; + selectionChanged: function () { + var sel = window.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; + }, - var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle); - if (this.widget) this.widget.close(); - if (data && data.list.length) { - if (picked && data.list.length == 1) { - this.pick(data, 0); - } else { - this.widget = new Widget(this, data); - CodeMirror.signal(data, "shown"); + pollSelection: function () { + if (!this.composing && !this.gracePeriod && this.selectionChanged()) { + var sel = window.getSelection(), cm = this.cm; + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { + runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; + }); } } }, - buildOptions: function (options) { - var editor = this.cm.options.hintOptions; - var out = {}; - for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; - if (editor) for (var prop in editor) - if (editor[prop] !== undefined) out[prop] = editor[prop]; - if (options) for (var prop in options) - if (options[prop] !== undefined) out[prop] = options[prop]; - return out; - } - }; + pollContent: function () { + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; - function getText(completion) { - if (typeof completion == "string") return completion; - else return completion.text; - } + var fromIndex; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + var fromLine = lineNo(display.view[0].line); + var fromNode = display.view[0].node; + } else { + var fromLine = lineNo(display.view[fromIndex].line); + var fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + if (toIndex == display.view.length - 1) { + var toLine = display.viewTo - 1; + var toNode = display.lineDiv.lastChild; + } else { + var toLine = lineNo(display.view[toIndex + 1].line) - 1; + var toNode = display.view[toIndex + 1].node.previousSibling; + } - function buildKeyMap(completion, handle) { - var baseMap = { - Up: function () { - handle.moveFocus(-1); - }, - Down: function () { - handle.moveFocus(1); - }, - PageUp: function () { - handle.moveFocus(-handle.menuSize() + 1, true); - }, - PageDown: function () { - handle.moveFocus(handle.menuSize() - 1, true); - }, - Home: function () { - handle.setFocus(0); - }, - End: function () { - handle.setFocus(handle.length - 1); - }, - Enter: handle.pick, - Tab: handle.pick, - Esc: handle.close - }; - var custom = completion.options.customKeys; - var ourMap = custom ? {} : baseMap; + var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } else break; + } - function addBinding(key, val) { - var bound; - if (typeof val != "string") - bound = function (cm) { - return val(cm, handle); - }; - // This mechanism is deprecated - else if (baseMap.hasOwnProperty(val)) - bound = baseMap[val]; - else - bound = val; - ourMap[key] = bound; - } + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) {++cutFront;} + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {++cutEnd;} - if (custom) - for (var key in custom) if (custom.hasOwnProperty(key)) - addBinding(key, custom[key]); - var extra = completion.options.extraKeys; - if (extra) - for (var key in extra) if (extra.hasOwnProperty(key)) - addBinding(key, extra[key]); - return ourMap; + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); + newText[0] = newText[0].slice(cutFront); + + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; + } + }, + + ensurePolled: function () { + this.forceCompositionEnd(); + }, + reset: function () { + this.forceCompositionEnd(); + }, + forceCompositionEnd: function () { + if (!this.composing || this.composing.handled) return; + this.applyComposition(this.composing); + this.composing.handled = true; + this.div.blur(); + this.div.focus(); + }, + applyComposition: function (composing) { + if (composing.data && composing.data != composing.startData) {operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);} + }, + + setUneditable: function (node) { + node.setAttribute("contenteditable", "false"); + }, + + onKeyPress: function (e) { + e.preventDefault(); + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + }, + + onContextMenu: nothing, + resetPosition: nothing, + + needsContentAttribute: true + }, ContentEditableInput.prototype); + + function posToDOM (cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) return null; + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + + var order = getOrder(line), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; } - function getHintElement(hintsElement, el) { - while (el && el != hintsElement) { - if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; - el = el.parentNode; + function badPos (pos, bad) { if (bad) pos.bad = true; return pos; } + + function domToPos (cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + node = null; offset = 0; + } else { + for (lineNode = node; ; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) return null; + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i]; + if (lineView.node == lineNode) {return locateNodeInLineView(lineView, node, offset);} } } - function Widget(completion, data) { - this.completion = completion; - this.data = data; - this.picked = false; - var widget = this, cm = completion.cm; - - var hints = this.hints = document.createElement("ul"); - hints.className = "CodeMirror-hints"; - this.selectedHint = data.selectedHint || 0; + function locateNodeInLineView (lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) offset = textNode.nodeValue.length; + } + while (topNode.parentNode != wrapper) topNode = topNode.parentNode; + var measure = lineView.measure, maps = measure.maps; + + function find (textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i]; + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2]; + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); + var ch = map[j] + offset; + if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; + return Pos(line, ch); + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) return badPos(found, bad); - var completions = data.list; - for (var i = 0; i < completions.length; ++i) { - var elt = hints.appendChild(document.createElement("li")), cur = completions[i]; - var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); - if (cur.className != null) className = cur.className + " " + className; - elt.className = className; - if (cur.render) cur.render(elt, data, cur); - else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); - elt.hintId = i; + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) {return badPos(Pos(found.line, found.ch - dist), bad);} + dist += after.textContent.length; + } + for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) {return badPos(Pos(found.line, found.ch + dist), bad);} + dist += after.textContent.length; } + } - var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); - var left = pos.left, top = pos.bottom, below = true; - hints.style.left = left + "px"; - hints.style.top = top + "px"; - // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. - var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); - var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); - (completion.options.container || document.body).appendChild(hints); - var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH; - if (overlapY > 0) { - var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top); - if (curTop - height > 0) { // Fits above cursor - hints.style.top = (top = pos.top - height) + "px"; - below = false; - } else if (height > winH) { - hints.style.height = (winH - 5) + "px"; - hints.style.top = (top = pos.bottom - box.top) + "px"; - var cursor = cm.getCursor(); - if (data.from.ch != cursor.ch) { - pos = cm.cursorCoords(cursor); - hints.style.left = (left = pos.left) + "px"; - box = hints.getBoundingClientRect(); + function domTextBetween (cm, from, to, fromLine, toLine) { + var text = "", closing = false; + function recognizeMarker (id) { return function (marker) { return marker.id == id; }; } + function walk (node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText != null) { + if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); + text += cmText; + return; + } + var markerID = node.getAttribute("cm-marker"), range; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range = found[0].find())) {text += getBetween(cm.doc, range.from, range.to).join("\n");} + return; } + if (node.getAttribute("contenteditable") == "false") return; + for (var i = 0; i < node.childNodes.length; i++) {walk(node.childNodes[i]);} + if (/^(pre|div|p)$/i.test(node.nodeName)) {closing = true;} + } else if (node.nodeType == 3) { + var val = node.nodeValue; + if (!val) return; + if (closing) { + text += "\n"; + closing = false; + } + text += val; } } - var overlapX = box.right - winW; - if (overlapX > 0) { - if (box.right - box.left > winW) { - hints.style.width = (winW - 5) + "px"; - overlapX -= (box.right - box.left) - winW; + for (;;) { + walk(from); + if (from == to) break; + from = from.nextSibling; + } + return text; + } + + CodeMirror.inputStyles = {textarea: TextareaInput, contenteditable: ContentEditableInput}; + + // SELECTION / CURSOR + + // Selection objects are immutable. A new one is created every time + // the selection changes. A selection is one or more non-overlapping + // (and non-touching) ranges, sorted, and an integer that indicates + // which one is the primary selection (the one that's scrolled into + // view, that getCursor returns, etc). + function Selection (ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + } + + Selection.prototype = { + primary: function () { return this.ranges[this.primIndex]; }, + equals: function (other) { + if (other == this) return true; + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; + for (var i = 0; i < this.ranges.length; i++) { + var here = this.ranges[i], there = other.ranges[i]; + if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; } - hints.style.left = (left = pos.left - overlapX) + "px"; + return true; + }, + deepCopy: function () { + for (var out = [], i = 0; i < this.ranges.length; i++) {out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));} + return new Selection(out, this.primIndex); + }, + somethingSelected: function () { + for (var i = 0; i < this.ranges.length; i++) {if (!this.ranges[i].empty()) return true;} + return false; + }, + contains: function (pos, end) { + if (!end) end = pos; + for (var i = 0; i < this.ranges.length; i++) { + var range = this.ranges[i]; + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) {return i;} + } + return -1; } + }; - cm.addKeyMap(this.keyMap = buildKeyMap(completion, { - moveFocus: function (n, avoidWrap) { - widget.changeActive(widget.selectedHint + n, avoidWrap); - }, - setFocus: function (n) { - widget.changeActive(n); - }, - menuSize: function () { - return widget.screenAmount(); - }, - length: completions.length, - close: function () { - completion.close(); - }, - pick: function () { - widget.pick(); - }, - data: data - })); + function Range (anchor, head) { + this.anchor = anchor; this.head = head; + } - if (completion.options.closeOnUnfocus) { - var closingOnBlur; - cm.on("blur", this.onBlur = function () { - closingOnBlur = setTimeout(function () { - completion.close(); - }, 100); - }); - cm.on("focus", this.onFocus = function () { - clearTimeout(closingOnBlur); - }); + Range.prototype = { + from: function () { return minPos(this.anchor, this.head); }, + to: function () { return maxPos(this.anchor, this.head); }, + empty: function () { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; } + }; - var startScroll = cm.getScrollInfo(); - cm.on("scroll", this.onScroll = function () { - var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); - var newTop = top + startScroll.top - curScroll.top; - var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); - if (!below) point += hints.offsetHeight; - if (point <= editor.top || point >= editor.bottom) return completion.close(); - hints.style.top = newTop + "px"; - hints.style.left = (left + startScroll.left - curScroll.left) + "px"; - }); + // Take an unsorted, potentially overlapping set of ranges, and + // build a selection out of it. 'Consumes' ranges array (modifying + // it). + function normalizeSelection (ranges, primIndex) { + var prim = ranges[primIndex]; + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); + primIndex = indexOf(ranges, prim); + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1]; + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i <= primIndex) --primIndex; + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex); + } + + function simpleSelection (anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + + // Most of the external API clips given positions to make sure they + // actually exist within the document. + function clipLine (doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} + function clipPos (doc, pos) { + if (pos.line < doc.first) return Pos(doc.first, 0); + var last = doc.first + doc.size - 1; + if (pos.line > last) return Pos(last, getLine(doc, last).text.length); + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen (pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) return Pos(pos.line, linelen); + else if (ch < 0) return Pos(pos.line, 0); + return pos; + } + function isLine (doc, l) {return l >= doc.first && l < doc.first + doc.size;} + function clipPosArray (doc, array) { + for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); + return out; + } - CodeMirror.on(hints, "dblclick", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - widget.pick(); - } - }); + // SELECTION UPDATES - CodeMirror.on(hints, "click", function (e) { - var t = getHintElement(hints, e.target || e.srcElement); - if (t && t.hintId != null) { - widget.changeActive(t.hintId); - if (completion.options.completeOnSingleClick) widget.pick(); + // The 'scroll' parameter given to many of these indicated whether + // the new cursor position should be scrolled into view after + // modifying the selection. + + // If shift is held or the extend flag is set, extends a range to + // include a given position (and optionally a second position). + // Otherwise, simply returns the range between the given positions. + // Used for cursor motion and such. + function extendRange (doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head; + head = other; + } else if (posBefore != (cmp(head, other) < 0)) { + head = other; + } } - }); + return new Range(anchor, head); + } + return new Range(other || head, head); + + } - CodeMirror.on(hints, "mousedown", function () { - setTimeout(function () { - cm.focus(); - }, 20); - }); + // Extend the primary selection range, discard the rest. + function extendSelection (doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); + } - CodeMirror.signal(data, "select", completions[0], hints.firstChild); - return true; + // Extend all selections (pos is an array of selections with length + // equal the number of selections) + function extendSelections (doc, heads, options) { + for (var out = [], i = 0; i < doc.sel.ranges.length; i++) {out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);} + var newSel = normalizeSelection(out, doc.sel.primIndex); + setSelection(doc, newSel, options); } - Widget.prototype = { - close: function () { - if (this.completion.widget != this) return; - this.completion.widget = null; - this.hints.parentNode.removeChild(this.hints); - this.completion.cm.removeKeyMap(this.keyMap); + // Updates a single range in the selection. + function replaceOneSelection (doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i] = range; + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); + } - var cm = this.completion.cm; - if (this.completion.options.closeOnUnfocus) { - cm.off("blur", this.onBlur); - cm.off("focus", this.onFocus); - } - cm.off("scroll", this.onScroll); - }, + // Reset the selection to a single range. + function setSimpleSelection (doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } - disable: function () { - this.completion.cm.removeKeyMap(this.keyMap); - var widget = this; - this.keyMap = { - Enter: function () { - widget.picked = true; + // Give beforeSelectionChange handlers a change to influence a + // selection update. + function filterSelectionChange (doc, sel) { + var obj = { + ranges: sel.ranges, + update: function (ranges) { + this.ranges = []; + for (var i = 0; i < ranges.length; i++) { + this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)); } - }; - this.completion.cm.addKeyMap(this.keyMap); - }, + } + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); + return sel; + } - pick: function () { - this.completion.pick(this.data, this.selectedHint); - }, + function setSelectionReplaceHistory (doc, sel, options) { + var done = doc.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } - changeActive: function (i, avoidWrap) { - if (i >= this.data.list.length) - i = avoidWrap ? this.data.list.length - 1 : 0; - else if (i < 0) - i = avoidWrap ? 0 : this.data.list.length - 1; - if (this.selectedHint == i) return; - var node = this.hints.childNodes[this.selectedHint]; - node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); - node = this.hints.childNodes[this.selectedHint = i]; - node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; - if (node.offsetTop < this.hints.scrollTop) - this.hints.scrollTop = node.offsetTop - 3; - else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) - this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; - CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); - }, + // Set a new selection. + function setSelection (doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } - screenAmount: function () { - return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; + function setSelectionNoUndo (doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {sel = filterSelectionChange(doc, sel);} + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + + if (!(options && options.scroll === false) && doc.cm) {ensureCursorVisible(doc.cm);} + } + + function setSelectionInner (doc, sel) { + if (sel.equals(doc.sel)) return; + + doc.sel = sel; + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); } - }; + signalLater(doc, "cursorActivity", doc); + } - CodeMirror.registerHelper("hint", "auto", function (cm, options) { - var helpers = cm.getHelpers(cm.getCursor(), "hint"), words; - if (helpers.length) { - for (var i = 0; i < helpers.length; i++) { - var cur = helpers[i](cm, options); - if (cur && cur.list.length) return cur; + // Verify that the selection does not partially select any atomic + // marked ranges. + function reCheckSelection (doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); + } + + // Return a selection that does not partially select any atomic + // ranges. + function skipAtomicInSelection (doc, sel, bias, mayClear) { + var out; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range.head, bias, mayClear); + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) out = sel.ranges.slice(0, i); + out[i] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel; + } + + // Ensure a given position is not inside an atomic range. + function skipAtomic (doc, pos, bias, mayClear) { + var flipped = false, curPos = pos; + var dir = bias || 1; + doc.cantEdit = false; + search: for (;;) { + var line = getLine(doc, curPos.line); + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) break; + else {--i; continue;} + } + } + if (!m.atomic) continue; + var newPos = m.find(dir < 0 ? -1 : 1); + if (cmp(newPos, curPos) == 0) { + newPos.ch += dir; + if (newPos.ch < 0) { + if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); + else newPos = null; + } else if (newPos.ch > line.text.length) { + if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); + else newPos = null; + } + if (!newPos) { + if (flipped) { + // Driven in a corner -- no valid cursor position found at all + // -- try again *with* clearing, if we didn't already + if (!mayClear) return skipAtomic(doc, pos, bias, true); + // Otherwise, turn off editing until further notice, and return the start of the doc + doc.cantEdit = true; + return Pos(doc.first, 0); + } + flipped = true; newPos = pos; dir = -dir; + } + } + curPos = newPos; + continue search; + } + } } - } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { - if (words) return CodeMirror.hint.fromList(cm, {words: words}); - } else if (CodeMirror.hint.anyword) { - return CodeMirror.hint.anyword(cm, options); + return curPos; } - }); + } - CodeMirror.registerHelper("hint", "fromList", function (cm, options) { - var cur = cm.getCursor(), token = cm.getTokenAt(cur); - var found = []; - for (var i = 0; i < options.words.length; i++) { - var word = options.words[i]; - if (word.slice(0, token.string.length) == token.string) - found.push(word); - } + // SELECTION DRAWING - if (found.length) return { - list: found, - from: CodeMirror.Pos(cur.line, token.start), - to: CodeMirror.Pos(cur.line, token.end) - }; - }); + function updateSelection (cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } - CodeMirror.commands.autocomplete = CodeMirror.showHint; + function prepareSelection (cm, primary) { + var doc = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); - var defaultOptions = { - hint: CodeMirror.hint.auto, - completeSingle: true, - alignWithWord: true, - closeCharacters: /[\s()\[\]{};:>,]/, - closeOnUnfocus: true, - completeOnSingleClick: true, - container: null, - customKeys: null, - extraKeys: null - }; + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) continue; + var range = doc.sel.ranges[i]; + var collapsed = range.empty(); + if (collapsed || cm.options.showCursorWhenSelecting) {drawSelectionCursor(cm, range, curFragment);} + if (!collapsed) {drawSelectionRange(cm, range, selFragment);} + } + return result; + } - CodeMirror.defineOption("hintOptions", null); -});/** - * 公式编辑控件 - * @class BI.FormulaEditor - * @extends BI.Widget - */ -BI.FormulaEditor = BI.inherit(BI.Single, { - _defaultConfig: function () { - return $.extend(BI.FormulaEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-formula-editor bi-card', - watermark: '', - value: '', - fieldTextValueMap: {}, - showHint: true, - lineHeight: 2 - }); - }, - _init: function () { - BI.FormulaEditor.superclass._init.apply(this, arguments); - var o = this.options, self = this; - this.editor = CodeMirror(this.element[0], { - textWrapping: true, - lineWrapping: true, - lineNumbers: false, - mode: 'formula', - //解决插入字段由括号或其他特殊字符包围时分裂的bug - specialChars: /[\u0000-\u001f\u007f\u00ad\u200c-\u200f\u2028\u2029\ufeff]/ - }); - o.lineHeight === 1 ? this.element.addClass("codemirror-low-line-height") : this.element.addClass("codemirror-high-line-height"); - this.editor.on("change", function (cm, change) { - self._checkWaterMark(); - if (o.showHint) { - CodeMirror.showHint(cm, CodeMirror.formulaHint, {completeSingle: false}); - } - BI.nextTick(function () { - self.fireEvent(BI.FormulaEditor.EVENT_CHANGE) - }); - }); + // Draws a cursor for the given range + function drawSelectionCursor (cm, range, output) { + var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine); - this.editor.on("focus", function () { - self._checkWaterMark(); - self.fireEvent(BI.FormulaEditor.EVENT_FOCUS); - }); + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - this.editor.on("blur", function () { - self.fireEvent(BI.FormulaEditor.EVENT_BLUR); - }); + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } + } + // Draws the given range as a highlighted selection + function drawSelectionRange (cm, range, output) { + var display = cm.display, doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - if (BI.isKey(o.value)) { - self.setValue(o.value); + function add (left, top, width, bottom) { + if (top < 0) top = 0; + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + + "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + + "px; height: " + (bottom - top) + "px")); } - if (BI.isKey(this.options.watermark)) { - var self = this; - this.watermark = BI.createWidget({ - type: "bi.label", - cls: "bi-water-mark", - text: this.options.watermark, - whiteSpace: "nowrap", - textAlign: "left" - }); - BI.createWidget({ - type: "bi.absolute", - element: self, - items: [{ - el: self.watermark, - left: 0, - top: 0 - }] - }); + function drawForLine (line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords (ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } - this.watermark.element.bind( - "mousedown", function (e) { - self.insertString(""); - self.editor.focus(); - e.stopEvent(); - } - ); - this.watermark.element.bind("click", function (e) { - self.editor.focus(); - e.stopEvent(); - }); - this.watermark.element.css({ - position: "absolute", - left: 3, - right: 3, - top: 6, - bottom: 0 + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right; + if (from == to) { + rightPos = leftPos; + left = right = leftPos.left; + } else { + rightPos = coords(to - 1, "right"); + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } + left = leftPos.left; + right = rightPos.right; + } + if (fromArg == null && from == 0) left = leftSide; + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom); + left = leftSide; + if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); + } + if (toArg == null && to == lineLen) right = rightSide; + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) {start = leftPos;} + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) {end = rightPos;} + if (left < leftSide + 1) left = leftSide; + add(left, rightPos.top, right - left, rightPos.bottom); }); + return {start: start, end: end}; } - }, - _checkWaterMark: function () { - var o = this.options; - if (!this.disabledWaterMark && BI.isEmptyString(this.editor.getValue()) && BI.isKey(o.watermark)) { - this.watermark && this.watermark.visible(); + var sFrom = range.from(), sTo = range.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); } else { - this.watermark && this.watermark.invisible(); + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) {add(leftSide, leftEnd.bottom, null, rightStart.top);} } - }, - disableWaterMark: function () { - this.disabledWaterMark = true; - this._checkWaterMark(); - }, + output.appendChild(fragment); + } - focus: function () { - this.editor.focus(); - }, + // Cursor-blinking + function restartBlink (cm) { + if (!cm.state.focused) return; + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) { + display.blinker = setInterval(function () { + display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + } else if (cm.options.cursorBlinkRate < 0) {display.cursorDiv.style.visibility = "hidden";} + } - /** - * 添加字段 - * @param field - */ - insertField: function (field) { - var from = this.editor.getCursor(); - //解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 - this.editor.replaceSelection('\u200b' + field + '\u200b'); - var to = this.editor.getCursor(); - this.editor.markText(from, to, {className: 'fieldName', atomic: true, startStyle: "start", endStyle: "end"}); - this.editor.replaceSelection(" "); - this.editor.focus(); - }, + // HIGHLIGHT WORKER - insertFunction: function (fn) { - var from = this.editor.getCursor(); - this.editor.replaceSelection(fn); - var to = this.editor.getCursor(); - this.editor.markText(from, to, {className: "#function", atomic: true}); - this.editor.replaceSelection("() "); - to = this.editor.getCursor(); - to.ch = to.ch - 2; - this.editor.setCursor(to); - this.editor.focus(); - }, - insertOperator: function (op) { - var from = this.editor.getCursor(); - this.editor.replaceSelection(op); - var to = this.editor.getCursor(); - this.editor.markText(from, to, {className: "%operator", atomic: true}); - this.editor.replaceSelection(" "); - this.editor.focus(); - }, + function startWorker (cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) {cm.state.highlight.set(time, bind(highlightWorker, cm));} + } - setFunction: function (v) { - var from = this.editor.getCursor(); - this.editor.replaceSelection(v); - var to = this.editor.getCursor(); - this.editor.markText(from, to, {className: "#function", atomic: true}); - }, + function highlightWorker (cm) { + var doc = cm.doc; + if (doc.frontier < doc.first) doc.frontier = doc.first; + if (doc.frontier >= cm.display.viewTo) return; + var end = +new Date + cm.options.workTime; + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); + var changedLines = []; - insertString: function (str) { - this.editor.replaceSelection(str); - this.editor.focus(); - }, + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles; + var highlighted = highlightLine(cm, line, state, true); + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) line.styleClasses = newCls; + else if (oldCls) line.styleClasses = null; + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; + if (ischange) changedLines.push(doc.frontier); + line.stateAfter = copyState(doc.mode, state); + } else { + processLine(cm, line.text, state); + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; + } + ++doc.frontier; + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + if (changedLines.length) { + runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) {regLineChange(cm, changedLines[i], "text");} + }); + } + } - getFormulaString: function () { - return this.editor.getValue(); - }, + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine (cm, n, precise) { + var minindent, minline, doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) return doc.first; + var line = getLine(doc, search - 1); + if (line.stateAfter && (!precise || search <= doc.frontier)) return search; + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + + function getStateBefore (cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) return true; + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos - 1).stateAfter; + if (!state) state = startState(doc.mode); + else state = copyState(doc.mode, state); + doc.iter(pos, n, function (line) { + processLine(cm, line.text, state); + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; + line.stateAfter = save ? copyState(doc.mode, state) : null; + ++pos; + }); + if (precise) doc.frontier = pos; + return state; + } + + // POSITION MEASUREMENT + + function paddingTop (display) {return display.lineSpace.offsetTop;} + function paddingVert (display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} + function paddingH (display) { + if (display.cachedPaddingH) return display.cachedPaddingH; + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; + if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; + return data; + } - getUsedFields: function () { - var fieldMap = this.options.fieldTextValueMap; - var fields = []; - this.editor.getValue(true, function (line) { - var value = line.text; - _.forEach(line.markedSpans, function (i, ms) { - switch (i.marker.className) { - case "fieldName": - //因为插入字段的时候首尾加了不可见字符,所以首尾缩进一个字符 - var dId = fieldMap[value.substr(i.from + 1, i.to - i.from - 2)]; - if (!fields.contains(dId)) { - fields.push(dId); - } + function scrollGap (cm) { return scrollerGap - cm.display.nativeBarWidth; } + function displayWidth (cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight (cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + // Ensure the lineView.wrapping.heights array is populated. This is + // an array of bottom offsets for the lines that make up a drawn + // line. When lineWrapping is on, there might be more than one + // height. + function ensureLineHeights (cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) {heights.push((cur.bottom + next.top) / 2 - rect.top);} } - }); - }); + } + heights.push(rect.bottom - rect.top); + } + } + + // Find a line map (mapping character offsets to text nodes) and a + // measurement cache for the given line number. (A line view might + // contain multiple lines when collapsed ranges are present.) + function mapFromLineView (lineView, line, lineN) { + if (lineView.line == line) {return {map: lineView.measure.map, cache: lineView.measure.cache};} + for (var i = 0; i < lineView.rest.length; i++) { + if (lineView.rest[i] == line) {return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};} + } + for (var i = 0; i < lineView.rest.length; i++) { + if (lineNo(lineView.rest[i]) > lineN) {return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};} + } + } + + // Render a line into the hidden node display.externalMeasured. Used + // when measurement is needed for a line that's not in the viewport. + function updateExternalMeasurement (cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + + // Get a {top, bottom, left, right} box (in line-local coordinates) + // for a given character. + function measureChar (cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + + // Find a line view that corresponds to the given line number. + function findViewForLine (cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) {return cm.display.view[findViewIndex(cm, lineN)];} + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) {return ext;} + } + + // Measurement can be split in two steps, the set-up work that + // applies to the whole line, and the measurement of the actual + // character. Functions like coordsChar, that need to do a lot of + // measurements in a row, can thus ensure that the set-up work is + // only done once. + function prepareMeasureForLine (cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) {view = null;} else if (view && view.changes) {updateLineForChanges(cm, view, lineN, getDimensions(cm));} + if (!view) {view = updateExternalMeasurement(cm, line);} + + var info = mapFromLineView(view, line, lineN); + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + }; + } + + // Given a prepared measurement object, measures the position of an + // actual character (or fetches it from the cache). + function measureCharPrepared (cm, prepared, ch, bias, varHeight) { + if (prepared.before) ch = -1; + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) {prepared.rect = prepared.view.text.getBoundingClientRect();} + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) prepared.cache[key] = found; + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom}; + } + + var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; + + function nodeAndOffsetInLineMap (map, ch, bias) { + var node, start, end, collapse; + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + var mStart = map[i], mEnd = map[i + 1]; + if (ch < mStart) { + start = 0; end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) collapse = "right"; + } + if (start != null) { + node = map[i + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) {collapse = bias;} + if (bias == "left" && start == 0) { + while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2]; + collapse = "left"; + } + } + if (bias == "right" && start == mEnd - mStart) { + while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2]; + collapse = "right"; + } + } + break; + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; + } + + function measureCharInner (cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + + var rect; + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); + } else if (ie && cm.options.lineWrapping) { + var rects = range(node, start, end).getClientRects(); + if (rects.length) {rect = rects[bias == "right" ? rects.length - 1 : 0];} else {rect = nullRect;} + } else { + rect = range(node, start, end).getBoundingClientRect() || nullRect; + } + if (rect.left || rect.right || start == 0) break; + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) collapse = bias = "right"; + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) {rect = rects[bias == "right" ? rects.length - 1 : 0];} else {rect = node.getBoundingClientRect();} + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) {rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};} else {rect = nullRect;} + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + for (var i = 0; i < heights.length - 1; i++) {if (mid < heights[i]) break;} + var top = i ? heights[i - 1] : 0, bot = heights[i]; + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot}; + if (!rect.left && !rect.right) result.bogus = true; + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } + + return result; + } + + // Work around problem with bounding client rects on ranges being + // returned incorrectly when zoomed on IE10 and below. + function maybeUpdateRectForZooming (measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) {return rect;} + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY}; + } + + function clearLineMeasurementCacheFor (lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { + for (var i = 0; i < lineView.rest.length; i++) {lineView.measure.caches[i] = {};} + } + } + } + + function clearLineMeasurementCache (cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i = 0; i < cm.display.view.length; i++) {clearLineMeasurementCacheFor(cm.display.view[i]);} + } + + function clearCaches (cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; + cm.display.lineNumChars = null; + } + + function pageScrollX () { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } + function pageScrollY () { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } + + // Converts a {top, bottom, left, right} box from line-local + // coordinates into another coordinate system. Context may be one of + // "line", "div" (display.lineDiv), "local"/null (editor), "window", + // or "page". + function intoCoordSystem (cm, lineObj, rect, context) { + if (lineObj.widgets) { + for (var i = 0; i < lineObj.widgets.length; ++i) { + if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]); + rect.top += size; rect.bottom += size; + } + } + } + if (context == "line") return rect; + if (!context) context = "local"; + var yOff = heightAtLine(lineObj); + if (context == "local") yOff += paddingTop(cm.display); + else yOff -= cm.display.viewOffset; + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect; + } + + // Coverts a box from "div" coords to another coordinate system. + // Context may be "window", "page", "div", or "local"/null. + function fromCoordSystem (cm, coords, context) { + if (context == "div") return coords; + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; + } + + function charCoords (cm, pos, context, lineObj, bias) { + if (!lineObj) lineObj = getLine(cm.doc, pos.line); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + + // Returns a box for a given cursor position, which may have an + // 'other' property containing the position of the secondary cursor + // on a bidi boundary. + function cursorCoords (cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); + function get (ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); + if (right) m.left = m.right; else m.right = m.left; + return intoCoordSystem(cm, lineObj, m, context); + } + function getBidi (ch, partPos) { + var part = order[partPos], right = part.level % 2; + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos]; + ch = bidiRight(part) - (part.level % 2 ? 0 : 1); + right = true; + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos]; + ch = bidiLeft(part) - part.level % 2; + right = false; + } + if (right && ch == part.to && ch > part.from) return get(ch - 1); + return get(ch, right); + } + var order = getOrder(lineObj), ch = pos.ch; + if (!order) return get(ch); + var partPos = getBidiPartAt(order, ch); + var val = getBidi(ch, partPos); + if (bidiOther != null) val.other = getBidi(ch, bidiOther); + return val; + } + + // Used to cheaply estimate the coordinates for a position. Used for + // intermediate scroll updates. + function estimateCoords (cm, pos) { + var left = 0, pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return {left: left, right: left, top: top, bottom: top + lineObj.height}; + } + + // Positions returned by coordsChar contain some extra information. + // xRel is the relative x position of the input coordinates compared + // to the found position (so xRel > 0 means the coordinates are to + // the right of the character position, for example). When outside + // is true, that means the coordinates lie outside the line's + // vertical range. + function PosWithInfo (line, ch, outside, xRel) { + var pos = Pos(line, ch); + pos.xRel = xRel; + if (outside) pos.outside = true; + return pos; + } + + // Compute the character position closest to the given coordinates. + // Input must be lineSpace-local ("div" coordinate system). + function coordsChar (cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) return PosWithInfo(doc.first, 0, true, -1); + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineN > last) {return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);} + if (x < 0) x = 0; + + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var merged = collapsedSpanAtEnd(lineObj); + var mergedPos = merged && merged.find(0, true); + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) {lineN = lineNo(lineObj = mergedPos.to.line);} else {return found;} + } + } + + function coordsCharInner (cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(lineObj); + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + + function getX (ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); + wrongLine = true; + if (innerOff > sp.bottom) return sp.left - adjust; + else if (innerOff < sp.top) return sp.left + adjust; + wrongLine = false; + return sp.left; + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length; + var from = lineLeft(lineObj), to = lineRight(lineObj); + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; + + if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to; + var xDiff = x - (ch == from ? fromX : toX); + while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; + var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, + xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); + return pos; + } + var step = Math.ceil(dist / 2), middle = from + step; + if (bidi) { + middle = from; + for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); + } + var middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} + } + } + + var measureText; + // Compute the default text height. + function textHeight (display) { + if (display.cachedTextHeight != null) return display.cachedTextHeight; + if (measureText == null) { + measureText = elt("pre"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) display.cachedTextHeight = height; + removeChildren(display.measure); + return height || 1; + } + + // Compute the default character width. + function charWidth (display) { + if (display.cachedCharWidth != null) return display.cachedCharWidth; + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) display.cachedCharWidth = width; + return width || 10; + } + + // OPERATIONS + + // Operations are used to wrap a series of changes to the editor + // state in such a way that each change won't have to update the + // cursor and display (which would be awkward, slow, and + // error-prone). Instead, display updates are batched and then all + // combined and executed at once. + + var operationGroup = null; + + var nextOpId = 0; + // Start a new operation. + function startOperation (cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + }; + if (operationGroup) { + operationGroup.ops.push(cm.curOp); + } else { + cm.curOp.ownsGroup = operationGroup = { + ops: [cm.curOp], + delayedCallbacks: [] + }; + } + } + + function fireCallbacksForOps (group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0; + do { + for (; i < callbacks.length; i++) {callbacks[i]();} + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) { + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) {op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);} + } + } + } while (i < callbacks.length); + } + + // Finish an operation, updating the display and signalling delayed events + function endOperation (cm) { + var op = cm.curOp, group = op.ownsGroup; + if (!group) return; + + try { fireCallbacksForOps(group); } finally { + operationGroup = null; + for (var i = 0; i < group.ops.length; i++) {group.ops[i].cm.curOp = null;} + endOperations(group); + } + } + + // The DOM updates done when an operation finishes are batched so + // that the minimum number of relayouts are required. + function endOperations (group) { + var ops = group.ops; + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_R1(ops[i]);} + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + {endOperation_W1(ops[i]);} + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_R2(ops[i]);} + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + {endOperation_W2(ops[i]);} + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_finish(ops[i]);} + } + + function endOperation_R1 (op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) findMaxLine(cm); + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); + } + + function endOperation_W1 (op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + + function endOperation_R2 (op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) updateHeightsInViewport(cm); + + op.barMeasure = measureForScrollbars(cm); + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + + if (op.updatedDisplay || op.selectionChanged) {op.preparedSelection = display.input.prepareSelection();} + } + + function endOperation_W2 (op) { + var cm = op.cm; + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) {setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);} + cm.display.maxLineChanged = false; + } + + if (op.preparedSelection) {cm.display.input.showSelection(op.preparedSelection);} + if (op.updatedDisplay) {setDocumentHeight(cm, op.barMeasure);} + if (op.updatedDisplay || op.startHeight != cm.doc.height) {updateScrollbars(cm, op.barMeasure);} + + if (op.selectionChanged) restartBlink(cm); + + if (cm.state.focused && op.updateInput) {cm.display.input.reset(op.typing);} + if (op.focus && op.focus == activeElt()) ensureFocus(op.cm); + } + + function endOperation_finish (op) { + var cm = op.cm, display = cm.display, doc = cm.doc; + + if (op.updatedDisplay) postUpdateDisplay(cm, op.update); + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) {display.wheelStartX = display.wheelStartY = null;} + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); + display.scrollbars.setScrollTop(doc.scrollTop); + display.scroller.scrollTop = doc.scrollTop; + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft)); + display.scrollbars.setScrollLeft(doc.scrollLeft); + display.scroller.scrollLeft = doc.scrollLeft; + alignHorizontally(cm); + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) { + for (var i = 0; i < hidden.length; ++i) {if (!hidden[i].lines.length) signal(hidden[i], "hide");} + } + if (unhidden) { + for (var i = 0; i < unhidden.length; ++i) {if (unhidden[i].lines.length) signal(unhidden[i], "unhide");} + } + + if (display.wrapper.offsetHeight) {doc.scrollTop = cm.display.scroller.scrollTop;} + + // Fire change events, and delayed event handlers + if (op.changeObjs) {signal(cm, "changes", cm, op.changeObjs);} + if (op.update) {op.update.finish();} + } + + // Run the given function in an operation + function runInOp (cm, f) { + if (cm.curOp) return f(); + startOperation(cm); + try { return f(); } finally { endOperation(cm); } + } + // Wraps a function in an operation. Returns the wrapped function. + function operation (cm, f) { + return function () { + if (cm.curOp) return f.apply(cm, arguments); + startOperation(cm); + try { return f.apply(cm, arguments); } finally { endOperation(cm); } + }; + } + // Used to add methods to editor and doc instances, wrapping them in + // operations. + function methodOp (f) { + return function () { + if (this.curOp) return f.apply(this, arguments); + startOperation(this); + try { return f.apply(this, arguments); } finally { endOperation(this); } + }; + } + function docMethodOp (f) { + return function () { + var cm = this.cm; + if (!cm || cm.curOp) return f.apply(this, arguments); + startOperation(cm); + try { return f.apply(this, arguments); } finally { endOperation(cm); } + }; + } + + // VIEW TRACKING + + // These objects are used to represent the visible (currently drawn) + // part of the document. A LineView may correspond to multiple + // logical lines, if those are connected by collapsed ranges. + function LineView (doc, line, lineN) { + // The starting line + this.line = line; + // Continuing lines, if any + this.rest = visualLineContinued(line); + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + + // Create a range of LineView objects for the given lines. + function buildViewArray (cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + + // Updates the display.view data structure for a given change to the + // document. From and to are in pre-change coordinates. Lendiff is + // the amount of lines added or subtracted by the change. This is + // used for changes that span multiple lines, or change the way + // lines are divided into visual lines. regLineChange (below) + // registers single-line changes. + function regChange (cm, from, to, lendiff) { + if (from == null) from = cm.doc.first; + if (to == null) to = cm.doc.first + cm.doc.size; + if (!lendiff) lendiff = 0; + + var display = cm.display; + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) {display.updateLineNumbers = from;} + + cm.curOp.viewChanged = true; + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) {resetView(cm);} + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm); + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut = viewCuttingPoint(cm, from, from, -1); + if (cut) { + display.view = display.view.slice(0, cut.index); + display.viewTo = cut.lineN; + } else { + resetView(cm); + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) {ext.lineN += lendiff;} else if (from < ext.lineN + ext.size) {display.externalMeasured = null;} + } + } + + // Register a change to a single line. Type must be one of "text", + // "gutter", "class", "widget" + function regLineChange (cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) {display.externalMeasured = null;} + + if (line < display.viewFrom || line >= display.viewTo) return; + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) return; + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) arr.push(type); + } + + // Clear the view. + function resetView (cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + + // Find the view element corresponding to a given line. Return null + // when the line isn't visible. + function findViewIndex (cm, n) { + if (n >= cm.display.viewTo) return null; + n -= cm.display.viewFrom; + if (n < 0) return null; + var view = cm.display.view; + for (var i = 0; i < view.length; i++) { + n -= view[i].size; + if (n < 0) return i; + } + } + + function viewCuttingPoint (cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) {return {index: index, lineN: newN};} + for (var i = 0, n = cm.display.viewFrom; i < index; i++) {n += view[i].size;} + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) return null; + diff = (n + view[index].size) - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) return null; + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return {index: index, lineN: newN}; + } + + // Force the view to cover a given range, adding empty view element + // or clipping off existing ones as needed. + function adjustView (cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) {display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);} else if (display.viewFrom < from) {display.view = display.view.slice(findViewIndex(cm, from));} + display.viewFrom = from; + if (display.viewTo < to) {display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));} else if (display.viewTo > to) {display.view = display.view.slice(0, findViewIndex(cm, to));} + } + display.viewTo = to; + } + + // Count the number of lines in the view whose DOM representation is + // out of date (or nonexistent). + function countDirtyView (cm) { + var view = cm.display.view, dirty = 0; + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; + } + return dirty; + } + + // EVENT HANDLERS + + // Attach the necessary event handlers when initializing the editor + function registerEventHandlers (cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) { + on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) return; + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); + } else {on(d.scroller, "dblclick", function (e) { signalDOMEvent(cm, e) || e_preventDefault(e); });} + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) on(d.scroller, "contextmenu", function (e) {onContextMenu(cm, e);}); + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0}; + function finishTouch () { + if (d.activeTouch) { + touchFinished = setTimeout(function () {d.activeTouch = null;}, 1000); + prevTouch = d.activeTouch; + prevTouch.end = +new Date; + } + } + function isMouseLikeTouchEvent (e) { + if (e.touches.length != 1) return false; + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway (touch, other) { + if (other.left == null) return true; + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function (e) { + if (!isMouseLikeTouchEvent(e)) { + clearTimeout(touchFinished); + var now = +new Date; + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null}; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function () { + if (d.activeTouch) d.activeTouch.moved = true; + }); + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range; + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + {range = new Range(pos, pos);} else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + {range = cm.findWordAt(pos);} else // Triple tap + {range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));} + cm.setSelection(range.anchor, range.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) {onScrollWheel(cm, e);}); + on(d.scroller, "DOMMouseScroll", function (e) {onScrollWheel(cm, e);}); + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + d.dragFunctions = { + simple: function (e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, + start: function (e) {onDragStart(cm, e);}, + drop: operation(cm, onDrop) + }; + + var inp = d.input.getField(); + on(inp, "keyup", function (e) { onKeyUp.call(cm, e); }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", bind(onFocus, cm)); + on(inp, "blur", bind(onBlur, cm)); + } + + function dragDropChanged (cm, value, old) { + var wasOn = old && old != CodeMirror.Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.simple); + toggle(cm.display.scroller, "dragover", funcs.simple); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + + // Called when the window resizes + function onResize (cm) { + var d = cm.display; + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) {return;} + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + + // MOUSE EVENTS + + // Return true when the given mouse event happened in a widget + function eventInWidget (display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) {return true;} + } + } + + // Given a mouse event, find the corresponding position. If liberal + // is false, it checks whether a gutter or scrollbar was clicked, + // and returns null if it was. forRect is used by rectangular + // selections, and tries to estimate a character position even for + // coordinates beyond the right of the text. + function posFromMouse (cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; + + var x, y, space = display.lineSpace.getBoundingClientRect(); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top; } catch (e) { return null; } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords; + } + + // A mouse down can be a single click, double click, triple click, + // start of selection drag, start of text drag, new cursor + // (ctrl-click), rectangle drag (alt-drag), or xwin + // middle-click-paste. Or it might be a click on something we should + // not interfere with, such as a scrollbar or widget. + function onMouseDown (e) { + var cm = this, display = cm.display; + if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return; + display.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false; + setTimeout(function () {display.scroller.draggable = true;}, 100); + } + return; + } + if (clickInGutter(cm, e)) return; + var start = posFromMouse(cm, e); + window.focus(); + + switch (e_button(e)) { + case 1: + if (start) {leftButtonDown(cm, e, start);} else if (e_target(e) == display.scroller) {e_preventDefault(e);} + break; + case 2: + if (webkit) cm.state.lastMiddleDown = +new Date; + if (start) extendSelection(cm.doc, start); + setTimeout(function () {display.input.focus();}, 20); + e_preventDefault(e); + break; + case 3: + if (captureRightClick) onContextMenu(cm, e); + else delayBlurEvent(cm); + break; + } + } + + var lastClick, lastDoubleClick; + function leftButtonDown (cm, e, start) { + if (ie) setTimeout(bind(ensureFocus, cm), 0); + else cm.curOp.focus = activeElt(); + + var now = +new Date, type; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple"; + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double"; + lastDoubleClick = {time: now, pos: start}; + } else { + type = "single"; + lastClick = {time: now, pos: start}; + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; + if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) {leftButtonStartDrag(cm, e, start, modifier);} else {leftButtonSelect(cm, e, start, type, modifier);} + } + + // Start a text drag. When it ends, see if any dragging actually + // happen, and treat as a click if it didn't. + function leftButtonStartDrag (cm, e, start, modifier) { + var display = cm.display, startTime = +new Date; + var dragEnd = operation(cm, function (e2) { + if (webkit) display.scroller.draggable = false; + cm.state.draggingText = false; + off(document, "mouseup", dragEnd); + off(display.scroller, "drop", dragEnd); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + if (!modifier && +new Date - 200 < startTime) {extendSelection(cm.doc, start);} + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) {setTimeout(function () {document.body.focus(); display.input.focus();}, 20);} else {display.input.focus();} + } + }); + // Let the drag handler handle this. + if (webkit) display.scroller.draggable = true; + cm.state.draggingText = dragEnd; + // IE's approach to draggable + if (display.scroller.dragDrop) display.scroller.dragDrop(); + on(document, "mouseup", dragEnd); + on(display.scroller, "drop", dragEnd); + } + + // Normal selection, as opposed to text dragging. + function leftButtonSelect (cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc; + e_preventDefault(e); + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) {ourRange = ranges[ourIndex];} else {ourRange = new Range(start, start);} + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + + if (e.altKey) { + type = "rect"; + if (!addNew) ourRange = new Range(start, start); + start = posFromMouse(cm, e, true, true); + ourIndex = -1; + } else if (type == "double") { + var word = cm.findWordAt(start); + if (cm.display.shift || doc.extend) {ourRange = extendRange(doc, ourRange, word.anchor, word.head);} else {ourRange = word;} + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); + if (cm.display.shift || doc.extend) {ourRange = extendRange(doc, ourRange, line.anchor, line.head);} else {ourRange = line;} + } else { + ourRange = extendRange(doc, ourRange, start); + } + + if (!addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0)); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + + var lastPos = start; + function extendTo (pos) { + if (cmp(lastPos, pos) == 0) return; + lastPos = pos; + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) {ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));} else if (text.length > leftPos) {ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));} + } + if (!ranges.length) ranges.push(new Range(start, start)); + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var anchor = oldRange.anchor, head = pos; + if (type != "single") { + if (type == "double") {var range = cm.findWordAt(pos);} else {var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));} + if (cmp(range.anchor, anchor) > 0) { + head = range.head; + anchor = minPos(oldRange.from(), range.anchor); + } else { + head = range.anchor; + anchor = maxPos(oldRange.to(), range.head); + } + } + var ranges = startSel.ranges.slice(0); + ranges[ourIndex] = new Range(clipPos(doc, anchor), head); + setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend (e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, type == "rect"); + if (!cur) return; + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) {setTimeout(operation(cm, function () {if (counter == curCount) extend(e);}), 150);} + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) { + setTimeout(operation(cm, function () { + if (counter != curCount) return; + display.scroller.scrollTop += outside; + extend(e); + }), 50); + } + } + } + + function done (e) { + counter = Infinity; + e_preventDefault(e); + display.input.focus(); + off(document, "mousemove", move); + off(document, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function (e) { + if (!e_button(e)) done(e); + else extend(e); + }); + var up = operation(cm, done); + on(document, "mousemove", move); + on(document, "mouseup", up); + } + + // Determines whether an event happened in the gutter, and fires the + // handlers for the corresponding event. + function gutterEvent (cm, e, type, prevent, signalfn) { + try { var mX = e.clientX, mY = e.clientY; } catch(e) { return false; } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; + if (prevent) e_preventDefault(e); + + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + + if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.options.gutters[i]; + signalfn(cm, type, cm, line, gutter, e); + return e_defaultPrevented(e); + } + } + } + + function clickInGutter (cm, e) { + return gutterEvent(cm, e, "gutterClick", true, signalLater); + } + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop (e) { + var cm = this; + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {return;} + e_preventDefault(e); + if (ie) lastDrop = +new Date; + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || isReadOnly(cm)) return; + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function (file, i) { + var reader = new FileReader; + reader.onload = operation(cm, function () { + text[i] = reader.result; + if (++read == n) { + pos = clipPos(cm.doc, pos); + var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); + } + }); + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(function () {cm.display.input.focus();}, 20); + return; + } + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) {var selected = cm.listSelections();} + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { + for (var i = 0; i < selected.length; ++i) {replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");} + } + cm.replaceSelection(text, "around", "paste"); + cm.display.input.focus(); + } + } catch(e) {} + } + } + + function onDragStart (cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; + + e.dataTransfer.setData("Text", cm.getSelection()); + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) img.parentNode.removeChild(img); + } + } + + // SCROLL EVENTS + + // Sync the scrollable area and scrollbars, ensure the viewport + // covers the visible area. + function setScrollTop (cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) return; + cm.doc.scrollTop = val; + if (!gecko) updateDisplaySimple(cm, {top: val}); + if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (gecko) updateDisplaySimple(cm); + startWorker(cm, 100); + } + // Sync scroller and scrollbar, ensure the gutter elements are + // aligned. + function setScrollLeft (cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; + cm.display.scrollbars.setScrollLeft(val); + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) wheelPixelsPerUnit = -.53; + else if (gecko) wheelPixelsPerUnit = 15; + else if (chrome) wheelPixelsPerUnit = -.7; + else if (safari) wheelPixelsPerUnit = -1 / 3; + + var wheelEventDelta = function (e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; + else if (dy == null) dy = e.wheelDelta; + return {x: dx, y: dy}; + }; + CodeMirror.wheelEventPixels = function (e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + }; + + function onScrollWheel (cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + if (!(dx && scroll.scrollWidth > scroll.clientWidth || + dy && scroll.scrollHeight > scroll.clientHeight)) return; + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy) {setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));} + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); + e_preventDefault(e); + display.wheelStartX = null; // Abort measurement, if in progress + return; + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) top = Math.max(0, top + pixels - 50); + else bot = Math.min(cm.doc.height, bot + pixels + 50); + updateDisplaySimple(cm, {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function () { + if (display.wheelStartX == null) return; + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) return; + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + // KEY EVENTS + + // Run a handler that was bound to a key. + function doHandleBinding (cm, bound, dropShift) { + if (typeof bound === "string") { + bound = commands[bound]; + if (!bound) return false; + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (isReadOnly(cm)) cm.state.suppressEdits = true; + if (dropShift) cm.display.shift = false; + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + + function lookupKeyForEditor (cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); + if (result) return result; + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm); + } + + var stopSeq = new Delayed; + function dispatchKey (cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) return "handled"; + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + name = seq + " " + name; + } + var result = lookupKeyForEditor(cm, name, handle); + + if (result == "multi") {cm.state.keySeq = name;} + if (result == "handled") {signalLater(cm, "keyHandled", cm, name, e);} + + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e); + return true; + } + return !!result; + } + + // Handle a key from the keydown event. + function handleKeyBinding (cm, e) { + var name = keyName(e, true); + if (!name) return false; + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) {return doHandleBinding(cm, b, true);}) + || dispatchKey(cm, name, e, function (b) { + if (typeof b === "string" ? /^go[A-Z]/.test(b) : b.motion) {return doHandleBinding(cm, b);} + }); + } + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }); + + } + + // Handle a key from the keypress event + function handleCharBinding (cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, + function (b) { return doHandleBinding(cm, b, true); }); + } + + var lastStoppedKey = null; + function onKeyDown (e) { + var cm = this; + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) return; + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) {cm.replaceSelection("", null, "cut");} + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) {showCrossHair(cm);} + } + + function showCrossHair (cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + + function up (e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + + function onKeyUp (e) { + if (e.keyCode == 16) this.doc.sel.shift = false; + signalDOMEvent(this, e); + } + + function onKeyPress (e) { + var cm = this; + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (handleCharBinding(cm, e, ch)) return; + cm.display.input.onKeyPress(e); + } + + // FOCUS/BLUR EVENTS + + function delayBlurEvent (cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function () { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + onBlur(cm); + } + }, 100); + } + + function onFocus (cm) { + if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; + + if (cm.options.readOnly == "nocursor") return; + if (!cm.state.focused) { + signal(cm, "focus", cm); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) setTimeout(function () { cm.display.input.reset(true); }, 20); // Issue #1730 + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur (cm) { + if (cm.state.delayingBlurEvent) return; + + if (cm.state.focused) { + signal(cm, "blur", cm); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function () {if (!cm.state.focused) cm.display.shift = false;}, 150); + } + + // CONTEXT MENU HANDLING + + // To make the context menu work, we need to briefly unhide the + // textarea (making it as unobtrusive as possible) to let the + // right-click take effect on it. + function onContextMenu (cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; + cm.display.input.onContextMenu(e); + } + + function contextMenuInGutter (cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) return false; + return gutterEvent(cm, e, "gutterContextMenu", false, signal); + } + + // UPDATING + + // Compute the position of the end of a change (its 'to' property + // refers to the pre-change end). + var changeEnd = CodeMirror.changeEnd = function (change) { + if (!change.text) return change.to; + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); + }; + + // Adjust a position to refer to the post-change position of the + // same text, or the end of the change if the change covers it. + function adjustForChange (pos, change) { + if (cmp(pos, change.from) < 0) return pos; + if (cmp(pos, change.to) <= 0) return changeEnd(change); + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; + return Pos(line, ch); + } + + function computeSelAfterChange (doc, change) { + var out = []; + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))); + } + return normalizeSelection(out, doc.sel.primIndex); + } + + function offsetPos (pos, old, nw) { + if (pos.line == old.line) {return Pos(nw.line, pos.ch - old.ch + nw.ch);} + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + + // Used by replaceSelections to allow moving the selection to the + // start or around the replaced test. Hint may be "start" or "around". + function computeReplacedSel (doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; + out[i] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex); + } + + // Allow "beforeChange" event handlers to influence a change + function filterChange (doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { this.canceled = true; } + }; + if (update) { + obj.update = function (from, to, text, origin) { + if (from) this.from = clipPos(doc, from); + if (to) this.to = clipPos(doc, to); + if (text) this.text = text; + if (origin !== undefined) this.origin = origin; + }; + } + signal(doc, "beforeChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); + + if (obj.canceled) return null; + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; + } + + // Apply a change to a document, and add it to the document's + // history, and propagating it to all linked documents. + function makeChange (doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); + if (doc.cm.state.suppressEdits) return; + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) return; + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 0; --i) {makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});} + } else { + makeChangeInner(doc, change); + } + } + + function makeChangeInner (doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + // Revert a change stored in a document's history. + function makeChangeFromHistory (doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits) return; + + var hist = doc.history, event, selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + for (var i = 0; i < source.length; i++) { + event = source[i]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) {break;} + } + if (i == source.length) return; + hist.lastOrigin = hist.lastSelOrigin = null; + + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}); + return; + } + selAfter = event; + } else break; + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({changes: antiChanges, generation: hist.generation}); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + for (var i = event.changes.length - 1; i >= 0; --i) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return; + } + + antiChanges.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); + var rebased = []; + + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + } + } + + // Sub-views need their line numbers shifted when text is added + // above or below them in the parent document. + function shiftDoc (doc, distance) { + if (distance == 0) return; + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function (range) { + return new Range(Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch)); + }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) {regLineChange(doc.cm, l, "gutter");} + } + } + + // More lower-level change function, handling only a single document + // (not linked ones). + function makeChangeSingleDoc (doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) {return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);} + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) return; + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) selAfter = computeSelAfterChange(doc, change); + if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); + else updateDoc(doc, change, spans); + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + } + + // Handle the interaction of a change to a document with the editor + // that this document is part of. + function makeChangeSingleDocInEditor (cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + + if (doc.sel.contains(change.from, change.to) > -1) {signalCursorActivity(cm);} + + updateDoc(doc, change, spans, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) cm.curOp.updateMaxLine = true; + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + if (change.full) {regChange(cm);} else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) {regLineChange(cm, from.line, "text");} else {regChange(cm, from.line, to.line + 1, lendiff);} + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) signalLater(cm, "change", cm, obj); + if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); + } + cm.display.selForContextMenu = null; + } + + function replaceRange (doc, code, from, to, origin) { + if (!to) to = from; + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } + if (typeof code === "string") code = splitLines(code); + makeChange(doc, {from: from, to: to, text: code, origin: origin}); + } + + // SCROLLING THINGS INTO VIEW + + // If an editor sits on the top or bottom of the window, partially + // scrolled out of view, this ensures that the cursor is visible. + function maybeScrollWindow (cm, coords) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) return; + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + if (coords.top + box.top < 0) doScroll = true; + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + + coords.left + "px; width: 2px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + + // Scroll a given position into view (immediately), verifying that + // it actually became visible (as line heights are accurately + // measured, the position of something may 'drift' during drawing). + function scrollPosIntoView (cm, pos, end, margin) { + if (margin == null) margin = 0; + for (var limit = 0; limit < 5; limit++) { + var changed = false, coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), + Math.min(coords.top, endCoords.top) - margin, + Math.max(coords.left, endCoords.left), + Math.max(coords.bottom, endCoords.bottom) + margin); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; + } + if (!changed) break; + } + return coords; + } + + // Scroll a given set of coordinates into view (immediately). + function scrollIntoView (cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); + if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); + if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); + } + + // Calculate a new scroll position needed to scroll the given + // rectangle into view. Returns an object with scrollTop and + // scrollLeft properties. When these are undefined, the + // vertical/horizontal position does not need to be adjusted. + function calculateScrollPos (cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (y1 < 0) y1 = 0; + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen = displayHeight(cm), result = {}; + if (y2 - y1 > screen) y2 = y1 + screen; + var docBottom = cm.doc.height + paddingVert(display); + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1; + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); + if (newTop != screentop) result.scrollTop = newTop; + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); + var tooWide = x2 - x1 > screenw; + if (tooWide) x2 = x1 + screenw; + if (x1 < 10) {result.scrollLeft = 0;} else if (x1 < screenleft) {result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));} else if (x2 > screenw + screenleft - 3) {result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;} + return result; + } + + // Store a relative adjustment to the scroll position in the current + // operation (to be applied when the operation finishes). + function addToScrollPos (cm, left, top) { + if (left != null || top != null) resolveScrollToPos(cm); + if (left != null) {cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;} + if (top != null) {cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;} + } + + // Make sure that at the end of the operation the current cursor is + // shown. + function ensureCursorVisible (cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(), from = cur, to = cur; + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; + to = Pos(cur.line, cur.ch + 1); + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; + } + + // When an operation has its scrollToPos property set, and another + // scroll action is applied before the end of the operation, this + // 'simulates' scrolling that position into view in a cheap way, so + // that the effect of intermediate scroll commands is not ignored. + function resolveScrollToPos (cm) { + var range = cm.curOp.scrollToPos; + if (range) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); + var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), + Math.min(from.top, to.top) - range.margin, + Math.max(from.right, to.right), + Math.max(from.bottom, to.bottom) + range.margin); + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + } + + // API UTILITIES + + // Indent the given line. The how parameter can be "smart", + // "add"/null, "subtract", or "prev". When aggressive is false + // (typically set to true for forced single-line indents), empty + // lines are not indented, and places where the mode returns Pass + // are left alone. + function indentLine (cm, n, how, aggressive) { + var doc = cm.doc, state; + if (how == null) how = "add"; + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) how = "prev"; + else state = getStateBefore(cm, n); + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) line.stateAfter = null; + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) return; + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); + else indentation = 0; + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how === "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) {for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}} + if (pos < indentation) indentString += spaceStr(indentation - pos); + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i, new Range(pos, pos)); + break; + } + } + + } + + // Utility for applying a change to a line by handle or number, + // returning the number and optionally registering the line as + // changed. + function changeLine (doc, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle === "number") line = getLine(doc, clipLine(doc, handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); + return line; + } + + // Helper for deleting text near the selection(s), used to implement + // backspace, delete, and similar functionality. + function deleteNearSelection (cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } + } + kill.push(toKill); + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) {replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");} + ensureCursorVisible(cm); + }); + } + + // Used for horizontal relative motion. Dir is -1 or 1 (left or + // right), unit can be "char", "column" (like char, but doesn't + // cross line boundaries), "word" (across next word), or "group" (to + // the start of next group of word or non-word-non-whitespace + // chars). The visually param controls whether, in right-to-left + // text, direction 1 means to move towards the next index in the + // string, or towards the character to the right of the current + // position. The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosH (doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir; + var lineObj = getLine(doc, line); + var possible = true; + function findNextLine () { + var l = line + dir; + if (l < doc.first || l >= doc.first + doc.size) return (possible = false); + line = l; + return lineObj = getLine(doc, l); + } + function moveOnce (boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); + else ch = dir < 0 ? lineObj.text.length : 0; + } else return (possible = false); + } else ch = next; + return true; + } + + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true; ; first = false) { + if (dir < 0 && !moveOnce(!first)) break; + var cur = lineObj.text.charAt(ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p"; + if (group && !first && !type) type = "s"; + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce();} + break; + } + + if (type) sawType = type; + if (dir > 0 && !moveOnce(!first)) break; + } + } + var result = skipAtomic(doc, Pos(line, ch), origDir, true); + if (!possible) result.hitSide = true; + return result; + } + + // For relative vertical movement. Dir may be -1 or 1. Unit can be + // "page" or "line". The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosV (cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + for (;;) { + var target = coordsChar(cm, x, y); + if (!target.outside) break; + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } + y += dir * 5; + } + return target; + } + + // EDITOR METHODS + + // The publicly visible API. Note that methodOp(f) means + // 'wrap f in an operation, performed on its `this` parameter'. + + // This is not the complete set of editor methods. Most of the + // methods defined on the Doc type are also injected into + // CodeMirror.prototype, for backwards compatibility and + // convenience. + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function () {window.focus(); this.display.input.focus();}, + + setOption: function (option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") return; + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) {operation(this, optionHandlers[option])(this, value, old);} + }, + + getOption: function (option) {return this.options[option];}, + getDoc: function () {return this.doc;}, + + addKeyMap: function (map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); + }, + removeKeyMap: function (map) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) { + if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1); + return true; + } + } + }, + + addOverlay: methodOp(function (spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) throw new Error("Overlays may not be stateful."); + this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function (spec) { + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec === "string" && cur.name == spec) { + overlays.splice(i, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + + indentLine: methodOp(function (n, dir, aggressive) { + if (typeof dir !== "string" && typeof dir !== "number") { + if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); + }), + indentSelection: methodOp(function (how) { + var ranges = this.doc.sel.ranges, end = -1; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (!range.empty()) { + var from = range.from(), to = range.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) {indentLine(this, j, how);} + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) {replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);} + } else if (range.head.line > end) { + indentLine(this, range.head.line, how, true); + end = range.head.line; + if (i == this.doc.sel.primIndex) ensureCursorVisible(this); + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function (pos, precise) { + return takeToken(this, pos, precise); + }, + + getLineTokens: function (line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + + getTokenTypeAt: function (pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) type = styles[2]; + else { + for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; + else if (styles[mid * 2 + 1] < ch) before = mid + 1; + else { type = styles[mid * 2 + 2]; break; } + } + } + var cut = type ? type.indexOf("cm-overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + + getModeAt: function (pos) { + var mode = this.doc.mode; + if (!mode.innerMode) return mode; + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + + getHelper: function (pos, type) { + return this.getHelpers(pos, type)[0]; + }, + + getHelpers: function (pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) return found; + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] === "string") { + if (help[mode[type]]) found.push(help[mode[type]]); + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]]; + if (val) found.push(val); + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i = 0; i < help._global.length; i++) { + var cur = help._global[i]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) {found.push(cur.val);} + } + return found; + }, + + getStateAfter: function (line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line); + return getStateBefore(this, line + 1, precise); + }, + + cursorCoords: function (start, mode) { + var pos, range = this.doc.sel.primary(); + if (start == null) pos = range.head; + else if (typeof start === "object") pos = clipPos(this.doc, start); + else pos = start ? range.from() : range.to(); + return cursorCoords(this, pos, mode || "page"); + }, + + charCoords: function (pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + + coordsChar: function (coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + + lineAtHeight: function (height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function (line, mode) { + var end = false, lineObj; + if (typeof line === "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) line = this.doc.first; + else if (line > last) { line = last; end = true; } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + + defaultTextHeight: function () { return textHeight(this.display); }, + defaultCharWidth: function () { return charWidth(this.display); }, + + setGutterMarker: methodOp(function (line, gutterID, value) { + return changeLine(this.doc, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) line.gutterMarkers = null; + return true; + }); + }), + + clearGutter: methodOp(function (gutterID) { + var cm = this, doc = cm.doc, i = doc.first; + doc.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + line.gutterMarkers[gutterID] = null; + regLineChange(cm, i, "gutter"); + if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; + } + ++i; + }); + }), + + lineInfo: function (line) { + if (typeof line === "number") { + if (!isLine(this.doc, line)) return null; + var n = line; + line = getLine(this.doc, line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets}; + }, + + getViewport: function () { return {from: this.display.viewFrom, to: this.display.viewTo};}, + + addWidget: function (pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) {top = pos.top - node.offsetHeight;} else if (pos.bottom + node.offsetHeight <= vspace) {top = pos.bottom;} + if (left + node.offsetWidth > hspace) {left = hspace - node.offsetWidth;} + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = left + "px"; + } + if (scroll) {scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);} + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + + execCommand: function (cmd) { + if (commands.hasOwnProperty(cmd)) {return commands[cmd](this);} + }, + + triggerElectric: methodOp(function (text) { triggerElectric(this, text); }), + + findPosH: function (from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) break; + } + return cur; + }, + + moveH: methodOp(function (dir, unit) { + var cm = this; + cm.extendSelectionsBy(function (range) { + if (cm.display.shift || cm.doc.extend || range.empty()) {return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);} + return dir < 0 ? range.from() : range.to(); + }, sel_move); + }), + + deleteH: methodOp(function (dir, unit) { + var sel = this.doc.sel, doc = this.doc; + if (sel.somethingSelected()) {doc.replaceSelection("", null, "+delete");} else { + deleteNearSelection(this, function (range) { + var other = findPosH(doc, range.head, dir, unit, false); + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; + }); + } + }), + + findPosV: function (from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) x = coords.left; + else coords.left = x; + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) break; + } + return cur; + }, + + moveV: methodOp(function (dir, unit) { + var cm = this, doc = this.doc, goals = []; + var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function (range) { + if (collapse) {return dir < 0 ? range.from() : range.to();} + var headPos = cursorCoords(cm, range.head, "div"); + if (range.goalColumn != null) headPos.left = range.goalColumn; + goals.push(headPos.left); + var pos = findPosV(cm, headPos, dir, unit); + if (unit == "page" && range == doc.sel.primary()) {addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);} + return pos; + }, sel_move); + if (goals.length) { + for (var i = 0; i < doc.sel.ranges.length; i++) {doc.sel.ranges[i].goalColumn = goals[i];} + } + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function (pos) { + var doc = this.doc, line = getLine(doc, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function (ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function (ch) {return /\s/.test(ch);} + : function (ch) {return !/\s/.test(ch) && !isWordChar(ch);}; + while (start > 0 && check(line.charAt(start - 1))) --start; + while (end < line.length && check(line.charAt(end))) ++end; + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + + toggleOverwrite: function (value) { + if (value != null && value == this.state.overwrite) return; + if (this.state.overwrite = !this.state.overwrite) {addClass(this.display.cursorDiv, "CodeMirror-overwrite");} else {rmClass(this.display.cursorDiv, "CodeMirror-overwrite");} + + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function () { return this.display.input.getField() == activeElt(); }, + + scrollTo: methodOp(function (x, y) { + if (x != null || y != null) resolveScrollToPos(this); + if (x != null) this.curOp.scrollLeft = x; + if (y != null) this.curOp.scrollTop = y; + }), + getScrollInfo: function () { + var scroller = this.display.scroller; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; + }, + + scrollIntoView: methodOp(function (range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null}; + if (margin == null) margin = this.options.cursorScrollMargin; + } else if (typeof range === "number") { + range = {from: Pos(range, 0), to: null}; + } else if (range.from == null) { + range = {from: range, to: null}; + } + if (!range.to) range.to = range.from; + range.margin = margin || 0; + + if (range.from.line != null) { + resolveScrollToPos(this); + this.curOp.scrollToPos = range; + } else { + var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), + Math.min(range.from.top, range.to.top) - range.margin, + Math.max(range.from.right, range.to.right), + Math.max(range.from.bottom, range.to.bottom) + range.margin); + this.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + }), + + setSize: methodOp(function (width, height) { + var cm = this; + function interpret (val) { + return typeof val === "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + } + if (width != null) cm.display.wrapper.style.width = interpret(width); + if (height != null) cm.display.wrapper.style.height = interpret(height); + if (cm.options.lineWrapping) clearLineMeasurementCache(this); + var lineNo = cm.display.viewFrom; + cm.doc.iter(lineNo, cm.display.viewTo, function (line) { + if (line.widgets) { + for (var i = 0; i < line.widgets.length; i++) {if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }} + } + ++lineNo; + }); + cm.curOp.forceUpdate = true; + signal(cm, "refresh", this); + }), + + operation: function (f) {return runInOp(this, f);}, + + refresh: methodOp(function () { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) {estimateLineHeights(this);} + signal(this, "refresh", this); + }), + + swapDoc: methodOp(function (doc) { + var old = this.doc; + old.cm = null; + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + this.scrollTo(doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + + getInputField: function () {return this.display.input.getField();}, + getWrapperElement: function () {return this.display.wrapper;}, + getScrollerElement: function () {return this.display.scroller;}, + getGutterElement: function () {return this.display.gutters;} + }; + eventMixin(CodeMirror); + + // OPTION DEFAULTS + + // The default configuration options. + var defaults = CodeMirror.defaults = {}; + // Functions to run when options are changed. + var optionHandlers = CodeMirror.optionHandlers = {}; + + function option (name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) { + optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; + } + } + + // Passed to option handlers when there is no old value. + var Init = CodeMirror.Init = {toString: function () {return "CodeMirror.Init";}}; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { + cm.setValue(val); + }, true); + option("mode", null, function (cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function (cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); + if (old != CodeMirror.Init) cm.refresh(); + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) {cm.refresh();}, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function (cm) { + themeChanged(cm); + guttersChanged(cm); + }, true); + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val); + var prev = old != CodeMirror.Init && getKeyMap(old); + if (prev && prev.detach) prev.detach(cm, next); + if (next.attach) next.attach(cm, prev || null); + }); + option("extraKeys", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function (cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function (cm) {updateScrollbars(cm);}, true); + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function (cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("firstLineNumber", 1, guttersChanged, true); + option("lineNumberFormatter", function (integer) {return integer;}, guttersChanged, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + cm.display.disabled = true; + } else { + cm.display.disabled = false; + if (!val) cm.display.input.reset(); + } + }); + option("disableInput", false, function (cm, val) {if (!val) cm.display.input.reset();}, true); + option("dragDrop", true, dragDropChanged); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function (cm, val) {cm.doc.history.undoDepth = val;}); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function (cm) {cm.refresh();}, true); + option("maxHighlightLength", 10000, resetModeState, true); + option("moveInputWithCursor", true, function (cm, val) { + if (!val) cm.display.input.resetPosition(); + }); + + option("tabindex", null, function (cm, val) { + cm.display.input.getField().tabIndex = val || ""; + }); + option("autofocus", null); + + // MODE DEFINITION AND QUERYING + + // Known modes, by name and by MIME + var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + CodeMirror.defineMode = function (name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) {mode.dependencies = Array.prototype.slice.call(arguments, 2);} + modes[name] = mode; + }; + + CodeMirror.defineMIME = function (mime, spec) { + mimeModes[mime] = spec; + }; + + // Given a MIME type, a {name, ...options} config object, or a name + // string, return a mode config object. + CodeMirror.resolveMode = function (spec) { + if (typeof spec === "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name === "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found === "string") found = {name: found}; + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec === "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return CodeMirror.resolveMode("application/xml"); + } + if (typeof spec === "string") return {name: spec}; + return spec || {name: "null"}; + }; + + // Given a mode spec (anything that resolveMode accepts), find and + // initialize an actual mode object. + CodeMirror.getMode = function (options, spec) { + var spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return CodeMirror.getMode(options, "text/plain"); + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) continue; + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) modeObj.helperType = spec.helperType; + if (spec.modeProps) { + for (var prop in spec.modeProps) {modeObj[prop] = spec.modeProps[prop];} + } + + return modeObj; + }; + + // Minimal default mode. + CodeMirror.defineMode("null", function () { + return {token: function (stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + // This can be used to attach properties to mode objects from + // outside the actual mode definition. + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function (mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + }; + + // EXTENSIONS + + CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.defineOption = option; + + var initHooks = []; + CodeMirror.defineInitHook = function (f) {initHooks.push(f);}; + + var helpers = CodeMirror.helpers = {}; + CodeMirror.registerHelper = function (type, name, value) { + if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; + helpers[type][name] = value; + }; + CodeMirror.registerGlobalHelper = function (type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value); + helpers[type]._global.push({pred: predicate, val: value}); + }; + + // MODE STATE HANDLING + + // Utility functions for working with state. Exported because nested + // modes need to do this for their inner modes. + + var copyState = CodeMirror.copyState = function (mode, state) { + if (state === true) return state; + if (mode.copyState) return mode.copyState(state); + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) val = val.concat([]); + nstate[n] = val; + } + return nstate; + }; + + var startState = CodeMirror.startState = function (mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + }; + + // Given a mode and a state (for that mode), find the inner mode and + // state at the position that the state refers to. + CodeMirror.innerMode = function (mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + if (!info || info.mode == mode) break; + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // STANDARD COMMANDS + + // Commands are parameter-less actions that can be performed on an + // editor, mostly used for keybindings. + var commands = CodeMirror.commands = { + selectAll: function (cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, + singleSelection: function (cm) { + cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function (cm) { + deleteNearSelection(cm, function (range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length; + if (range.head.ch == len && range.head.line < cm.lastLine()) {return {from: range.head, to: Pos(range.head.line + 1, 0)};} + return {from: range.head, to: Pos(range.head.line, len)}; + } + return {from: range.from(), to: range.to()}; + + }); + }, + deleteLine: function (cm) { + deleteNearSelection(cm, function (range) { + return {from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; + }); + }, + delLineLeft: function (cm) { + deleteNearSelection(cm, function (range) { + return {from: Pos(range.from().line, 0), to: range.from()}; + }); + }, + delWrappedLineLeft: function (cm) { + deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var leftPos = cm.coordsChar({left: 0, top: top}, "div"); + return {from: leftPos, to: range.from()}; + }); + }, + delWrappedLineRight: function (cm) { + deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + return {from: range.from(), to: rightPos }; + }); + }, + undo: function (cm) {cm.undo();}, + redo: function (cm) {cm.redo();}, + undoSelection: function (cm) {cm.undoSelection();}, + redoSelection: function (cm) {cm.redoSelection();}, + goDocStart: function (cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, + goDocEnd: function (cm) {cm.extendSelection(Pos(cm.lastLine()));}, + goLineStart: function (cm) { + cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1}); + }, + goLineStartSmart: function (cm) { + cm.extendSelectionsBy(function (range) { + return lineStartSmart(cm, range.head); + }, {origin: "+move", bias: 1}); + }, + goLineEnd: function (cm) { + cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1}); + }, + goLineRight: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + }, sel_move); + }, + goLineLeft: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: 0, top: top}, "div"); + }, sel_move); + }, + goLineLeftSmart: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var pos = cm.coordsChar({left: 0, top: top}, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); + return pos; + }, sel_move); + }, + goLineUp: function (cm) {cm.moveV(-1, "line");}, + goLineDown: function (cm) {cm.moveV(1, "line");}, + goPageUp: function (cm) {cm.moveV(-1, "page");}, + goPageDown: function (cm) {cm.moveV(1, "page");}, + goCharLeft: function (cm) {cm.moveH(-1, "char");}, + goCharRight: function (cm) {cm.moveH(1, "char");}, + goColumnLeft: function (cm) {cm.moveH(-1, "column");}, + goColumnRight: function (cm) {cm.moveH(1, "column");}, + goWordLeft: function (cm) {cm.moveH(-1, "word");}, + goGroupRight: function (cm) {cm.moveH(1, "group");}, + goGroupLeft: function (cm) {cm.moveH(-1, "group");}, + goWordRight: function (cm) {cm.moveH(1, "word");}, + delCharBefore: function (cm) {cm.deleteH(-1, "char");}, + delCharAfter: function (cm) {cm.deleteH(1, "char");}, + delWordBefore: function (cm) {cm.deleteH(-1, "word");}, + delWordAfter: function (cm) {cm.deleteH(1, "word");}, + delGroupBefore: function (cm) {cm.deleteH(-1, "group");}, + delGroupAfter: function (cm) {cm.deleteH(1, "group");}, + indentAuto: function (cm) {cm.indentSelection("smart");}, + indentMore: function (cm) {cm.indentSelection("add");}, + indentLess: function (cm) {cm.indentSelection("subtract");}, + insertTab: function (cm) {cm.replaceSelection("\t");}, + insertSoftTab: function (cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); + } + cm.replaceSelections(spaces); + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.execCommand("insertTab"); + }, + transposeChars: function (cm) { + runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = []; + for (var i = 0; i < ranges.length; i++) { + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); + } + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function (cm) { + runInOp(cm, function () { + var len = cm.listSelections().length; + for (var i = 0; i < len; i++) { + var range = cm.listSelections()[i]; + cm.replaceRange("\n", range.anchor, range.head, "+input"); + cm.indentLine(range.from().line + 1, null, true); + ensureCursorVisible(cm); + } + }); + }, + toggleOverwrite: function (cm) {cm.toggleOverwrite();} + }; + + + // STANDARD KEYMAPS + + var keyMap = CodeMirror.keyMap = {}; + + keyMap.basic = { + Left: "goCharLeft", Right: "goCharRight", Up: "goLineUp", Down: "goLineDown", + End: "goLineEnd", Home: "goLineStartSmart", PageUp: "goPageUp", PageDown: "goPageDown", + Delete: "delCharAfter", Backspace: "delCharBefore", "Shift-Backspace": "delCharBefore", + Tab: "defaultTab", "Shift-Tab": "indentAuto", + Enter: "newlineAndIndent", Insert: "toggleOverwrite", + Esc: "singleSelection" + }; + // Note that the save and find-related commands aren't defined by + // default. User code or addons can define them. Unknown commands + // are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" + }; + // Very basic readline/emacs-style bindings, which are standard on Mac. + keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + + // KEYMAP DISPATCH + + function normalizeKeyName (name) { + var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; + else if (/^a(lt)?$/i.test(mod)) alt = true; + else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; + else if (/^s(hift)$/i.test(mod)) shift = true; + else throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) name = "Alt-" + name; + if (ctrl) name = "Ctrl-" + name; + if (cmd) name = "Cmd-" + name; + if (shift) name = "Shift-" + name; + return name; + } + + // This is a kludge to keep keymaps mostly working as raw objects + // (backwards compatibility) while at the same time support features + // like normalization and multi-stroke key bindings. It compiles a + // new normalized keymap, and then updates the old object to reflect + // this. + CodeMirror.normalizeKeyMap = function (keymap) { + var copy = {}; + for (var keyname in keymap) { + if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; + if (value == "...") { delete keymap[keyname]; continue; } + + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i = 0; i < keys.length; i++) { + var val, name; + if (i == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) copy[name] = val; + else if (prev != val) throw new Error("Inconsistent bindings for " + name); + } + delete keymap[keyname]; + } + } + for (var prop in copy) keymap[prop] = copy[prop]; + return keymap; + }; + + var lookupKey = CodeMirror.lookupKey = function (key, map, handle, context) { + map = getKeyMap(map); + var found = map.call ? map.call(key, context) : map[key]; + if (found === false) return "nothing"; + if (found === "...") return "multi"; + if (found != null && handle(found)) return "handled"; + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") {return lookupKey(key, map.fallthrough, handle, context);} + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context); + if (result) return result; + } + } + }; + + // Modifier key presses don't count as 'real' key presses for the + // purpose of keymap fallthrough. + var isModifierKey = CodeMirror.isModifierKey = function (value) { + var name = typeof value === "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + }; + + // Look up the name of a key as indicated by an event object. + var keyName = CodeMirror.keyName = function (event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) return false; + var base = keyNames[event.keyCode], name = base; + if (name == null || event.altGraphKey) return false; + if (event.altKey && base != "Alt") name = "Alt-" + name; + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; + if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; + return name; + }; + + function getKeyMap (val) { + return typeof val === "string" ? keyMap[val] : val; + } + + // FROMTEXTAREA + + CodeMirror.fromTextArea = function (textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) {options.tabindex = textarea.tabIndex;} + if (!options.placeholder && textarea.placeholder) {options.placeholder = textarea.placeholder;} + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save () {textarea.value = cm.getValue();} + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form, realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function () { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + options.finishInit = function (cm) { + cm.save = save; + cm.getTextArea = function () { return textarea; }; + cm.toTextArea = function () { + cm.toTextArea = isNaN; // Prevent this from being ran twice + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (typeof textarea.form.submit === "function") {textarea.form.submit = realSubmit;} + } + }; + }; + + textarea.style.display = "none"; + var cm = CodeMirror(function (node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + return cm; + }; + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + var StringStream = CodeMirror.StringStream = function (string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + }; + + StringStream.prototype = { + eol: function () {return this.pos >= this.string.length;}, + sol: function () {return this.pos == this.lineStart;}, + peek: function () {return this.string.charAt(this.pos) || undefined;}, + next: function () { + if (this.pos < this.string.length) {return this.string.charAt(this.pos++);} + }, + eat: function (match) { + var ch = this.string.charAt(this.pos); + if (typeof match === "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function (match) { + var start = this.pos; + while (this.eat(match)) {} + return this.pos > start; + }, + eatSpace: function () { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function () {this.pos = this.string.length;}, + skipTo: function (ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function (n) {this.pos -= n;}, + column: function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + indentation: function () { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + match: function (pattern, consume, caseInsensitive) { + if (typeof pattern === "string") { + var cased = function (str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function () {return this.string.slice(this.start, this.pos);}, + hideFirstChars: function (n, inner) { + this.lineStart += n; + try { return inner(); } finally { this.lineStart -= n; } + } + }; + + // TEXTMARKERS + + // Created with markText and setBookmark methods. A TextMarker is a + // handle that can be used to clear or find a marked position in the + // document. Line objects hold arrays (markedSpans) containing + // {from, to, marker} object pointing to such marker objects, and + // indicating that such a marker is present on that line. Multiple + // lines may point to the same marker when it spans across lines. + // The spans will have null for their from/to properties when the + // marker continues beyond the start/end of the line. Markers have + // links back to the lines they currently touch. + + var nextMarkerId = 0; + + var TextMarker = CodeMirror.TextMarker = function (doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + eventMixin(TextMarker); + + // Clear the marker. + TextMarker.prototype.clear = function () { + if (this.explicitlyCleared) return; + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) startOperation(cm); + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) signalLater(this, "clear", found.from, found.to); + } + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); + else if (cm) { + if (span.to != null) max = lineNo(line); + if (span.from != null) min = lineNo(line); + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) {updateLineHeight(line, textHeight(cm.display));} + } + if (cm && this.collapsed && !cm.options.lineWrapping) { + for (var i = 0; i < this.lines.length; ++i) { + var visual = visualLine(this.lines[i]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + } + + if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) reCheckSelection(cm.doc); + } + if (cm) signalLater(cm, "markerCleared", cm, this); + if (withOp) endOperation(cm); + if (this.parent) this.parent.clear(); + }; + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + TextMarker.prototype.find = function (side, lineObj) { + if (side == null && this.type == "bookmark") side = 1; + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) return from; + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) return to; + } + } + return from && {from: from, to: to}; + }; + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + TextMarker.prototype.changed = function () { + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) return; + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) {updateLineHeight(line, line.height + dHeight);} + } + }); + }; + + TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) {(op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);} + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + + // Collapsed markers have unique ids, in order to be able to order + // them, which is needed for uniquely determining an outer marker + // when they overlap (they may nest, but not partially overlap). + var nextMarkerId = 0; + + // Create a marker, wire it up to the right lines, and + function markText (doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) return markTextShared(doc, from, to, options, type); + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); + + var marker = new TextMarker(doc, type), diff = cmp(from, to); + if (options) copyObj(options, marker, false); + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) {return marker;} + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true; + marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); + if (options.insertLeft) marker.widgetNode.insertLeft = true; + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) {throw new Error("Inserting collapsed marker partially overlapping an existing one");} + sawCollapsedSpans = true; + } + + if (marker.addToHistory) {addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);} + + var curLine = from.line, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) {updateMaxLine = true;} + if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)); + ++curLine; + }); + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { + doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) updateLineHeight(line, 0); + }); + } + + if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function () { marker.clear(); }); + + if (marker.readOnly) { + sawReadOnlySpans = true; + if (doc.history.done.length || doc.history.undone.length) {doc.clearHistory();} + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + // Sync editor state + if (updateMaxLine) cm.curOp.updateMaxLine = true; + if (marker.collapsed) {regChange(cm, from.line, to.line + 1);} else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) {for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");} + if (marker.atomic) reCheckSelection(cm.doc); + signalLater(cm, "markerAdded", cm, marker); + } + return marker; + } + + // SHARED TEXTMARKERS + + // A shared marker spans multiple linked documents. It is + // implemented as a meta-marker-object controlling multiple normal + // markers. + var SharedTextMarker = CodeMirror.SharedTextMarker = function (markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i = 0; i < markers.length; ++i) {markers[i].parent = this;} + }; + eventMixin(SharedTextMarker); + + SharedTextMarker.prototype.clear = function () { + if (this.explicitlyCleared) return; + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) {this.markers[i].clear();} + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj); + }; + + function markTextShared (doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function (doc) { + if (widget) options.widgetNode = widget.cloneNode(true); + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) {if (doc.linked[i].isParent) return;} + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + + function findSharedMarkers (doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), + function (m) { return m.parent; }); + } + + function copySharedMarkers (doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find(); + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + + function detachSharedMarkers (markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function (d) { linked.push(d); }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + } + } + + // TEXTMARKER SPANS + + function MarkedSpan (marker, from, to) { + this.marker = marker; + this.from = from; this.to = to; + } + + // Search an array of spans for a span matching the given marker. + function getMarkedSpanFor (spans, marker) { + if (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) return span; + } + } + } + // Remove a span from an array, returning undefined if no spans are + // left (we don't store arrays for lines without spans). + function removeMarkedSpan (spans, span) { + for (var r, i = 0; i < spans.length; ++i) {if (spans[i] != span) (r || (r = [])).push(spans[i]);} + return r; + } + // Add a span to a line. + function addMarkedSpan (line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + span.marker.attachLine(line); + } + + // Used for the algorithm that adjusts markers for a change in the + // document. These functions cut an array of spans at a given + // character position, returning an array of remaining chunks (or + // undefined if nothing remains). + function markedSpansBefore (old, startCh, isInsert) { + if (old) { + for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } + } + return nw; + } + function markedSpansAfter (old, endCh, isInsert) { + if (old) { + for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)); + } + } + } + return nw; + } + + // Given a change object, compute the new set of marker spans that + // cover the line in which the change took place. Removes spans + // entirely within the change, reconnects spans belonging to the + // same marker that appear on both sides of the change, and cuts off + // spans partially within the change. Returns an array of span + // arrays with one element for each line in (after) the change. + function stretchSpansOverChange (doc, change) { + if (change.full) return null; + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) return null; + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) span.to = startCh; + else if (sameLine) span.to = found.to == null ? null : found.to + offset; + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i = 0; i < last.length; ++i) { + var span = last[i]; + if (span.to != null) span.to += offset; + if (span.from == null) { + var found = getMarkedSpanFor(first, span.marker); + if (!found) { + span.from = offset; + if (sameLine) (first || (first = [])).push(span); + } + } else { + span.from += offset; + if (sameLine) (first || (first = [])).push(span); + } + } + } + // Make sure we didn't create any zero-length spans + if (first) first = clearEmptySpans(first); + if (last && last != first) last = clearEmptySpans(last); + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) { + for (var i = 0; i < first.length; ++i) { + if (first[i].to == null) {(gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));} + } + } + for (var i = 0; i < gap; ++i) {newMarkers.push(gapMarkers);} + newMarkers.push(last); + } + return newMarkers; + } + + // Remove spans that are empty and don't have a clearWhenEmpty + // option of false. + function clearEmptySpans (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) {spans.splice(i--, 1);} + } + if (!spans.length) return null; + return spans; + } + + // Used for un/re-doing changes from the history. Combines the + // result of computing the existing spans with the set of spans that + // existed in the history (so that deleting around a span and then + // undoing brings back the span). + function mergeOldSpans (doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) return stretched; + if (!stretched) return old; + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) {if (oldCur[k].marker == span.marker) continue spans;} + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old; + } + + // Used to 'clip' out readOnly ranges when making a change. + function removeReadOnlyRanges (doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) {(markers || (markers = [])).push(mark);} + } + } + }); + if (!markers) return null; + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) {newParts.push({from: p.from, to: m.from});} + if (dto > 0 || !mk.inclusiveRight && !dto) {newParts.push({from: m.to, to: p.to});} + parts.splice.apply(parts, newParts); + j += newParts.length - 1; + } + } + return parts; + } + + // Connect or disconnect spans from a line. + function detachMarkedSpans (line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) {spans[i].marker.detachLine(line);} + line.markedSpans = null; + } + function attachMarkedSpans (line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) {spans[i].marker.attachLine(line);} + line.markedSpans = spans; + } + + // Helpers used when computing which overlapping collapsed span + // counts as the larger one. + function extraLeft (marker) { return marker.inclusiveLeft ? -1 : 0; } + function extraRight (marker) { return marker.inclusiveRight ? 1 : 0; } + + // Returns a number indicating which of two overlapping collapsed + // spans is larger (and thus includes the other). Falls back to + // comparing ids when the spans cover exactly the same range. + function compareCollapsedMarkers (a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) return lenDiff; + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) return -fromCmp; + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) return toCmp; + return b.id - a.id; + } + + // Find out whether a line ends or starts in a collapsed span. If + // so, return the marker for that span. + function collapsedSpanAtSide (line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { + for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {found = sp.marker;} + } + } + return found; + } + function collapsedSpanAtStart (line) { return collapsedSpanAtSide(line, true); } + function collapsedSpanAtEnd (line) { return collapsedSpanAtSide(line, false); } + + // Test whether there exists a collapsed span that partially + // overlaps (covers the start or end, but not both) of a new span. + // Such overlap is not allowed. + function conflictingCollapsedRange (doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (!sp.marker.collapsed) continue; + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; + if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || + fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) {return true;} + } + } + } + + // A visual line is a line as drawn on the screen. Folding, for + // example, can cause multiple logical lines to appear on the same + // visual line. This finds the start of the visual line that the + // given line is part of (usually that is the line itself). + function visualLine (line) { + var merged; + while (merged = collapsedSpanAtStart(line)) {line = merged.find(-1, true).line;} + return line; + } + + // Returns an array of logical lines that continue the visual line + // started by the argument, or undefined if there are no such lines. + function visualLineContinued (line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + + // Get the line number of the start of the visual line that the + // given line number is part of. + function visualLineNo (doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line); + if (line == vis) return lineN; + return lineNo(vis); + } + // Get the line number of the start of the next visual line after + // the given line. + function visualLineEndNo (doc, lineN) { + if (lineN > doc.lastLine()) return lineN; + var line = getLine(doc, lineN), merged; + if (!lineIsHidden(doc, line)) return lineN; + while (merged = collapsedSpanAtEnd(line)) {line = merged.find(1, true).line;} + return lineNo(line) + 1; + } + + // Compute whether a line is hidden. Lines count as hidden when they + // are part of a visual line that starts with another line, or when + // they are entirely covered by collapsed, non-widget span. + function lineIsHidden (doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) continue; + if (sp.from == null) return true; + if (sp.marker.widgetNode) continue; + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) {return true;} + } + } + } + function lineIsHiddenInner (doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) {return true;} + for (var sp, i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) return true; + } + } + + // LINE WIDGETS + + // Line widgets are block elements displayed above or below a line. + + var LineWidget = CodeMirror.LineWidget = function (doc, node, options) { + if (options) { + for (var opt in options) { + if (options.hasOwnProperty(opt)) {this[opt] = options[opt];} + } + } + this.doc = doc; + this.node = node; + }; + eventMixin(LineWidget); + + function adjustScrollWhenAboveVisible (cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) {addToScrollPos(cm, null, diff);} + } + + LineWidget.prototype.clear = function () { + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) return; + for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); + if (!ws.length) line.widgets = null; + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + } + }; + LineWidget.prototype.changed = function () { + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) return; + updateLineHeight(line, line.height + diff); + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + }); + } + }; + + function widgetHeight (widget) { + if (widget.height != null) return widget.height; + var cm = widget.doc.cm; + if (!cm) return 0; + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) {parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";} + if (widget.noHScroll) {parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";} + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.offsetHeight; + } + + function addLineWidget (doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) cm.display.alignWidgets = true; + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) widgets.push(widget); + else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) addToScrollPos(cm, null, widget.height); + cm.curOp.forceUpdate = true; + } + return true; + }); + return widget; + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + var Line = CodeMirror.Line = function (text, markedSpans, estimateHeight) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight ? estimateHeight(this) : 1; + }; + eventMixin(Line); + Line.prototype.lineNo = function () { return lineNo(this); }; + + // Change the content (text, markers) of a line. Automatically + // invalidates cached information and tries to re-estimate the + // line's height. + function updateLine (line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + if (line.order != null) line.order = null; + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) updateLineHeight(line, estHeight); + } + + // Detach a line from the document tree and its markers. + function cleanUpLine (line) { + line.parent = null; + detachMarkedSpans(line); + } + + function extractLineClasses (type, output) { + if (type) { + for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) break; + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop] == null) {output[prop] = lineClass[2];} else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) {output[prop] += " " + lineClass[2];} + } + } + return type; + } + + function callBlankLine (mode, state) { + if (mode.blankLine) return mode.blankLine(state); + if (!mode.innerMode) return; + var inner = CodeMirror.innerMode(mode, state); + if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); + } + + function readToken (mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; + var style = mode.token(stream, state); + if (stream.pos > stream.start) return style; + } + throw new Error("Mode " + mode.name + " failed to advance stream."); + } + + // Utility for getTokenAt and getLineTokens + function takeToken (cm, pos, precise, asArray) { + function getObj (copy) { + return {start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state}; + } + + var doc = cm.doc, mode = doc.mode, style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize), tokens; + if (asArray) tokens = []; + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, state); + if (asArray) tokens.push(getObj(true)); + } + return asArray ? tokens : getObj(); + } + + // Run the given mode's parser over a line, calling f for each token. + function runMode (cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) processLine(cm, text, state, stream.pos); + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) style = "m-" + (style ? mName + " " + style : mName); + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 50000); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 characters + var pos = Math.min(stream.pos, curStart + 50000); + f(pos, curStyle); + curStart = pos; + } + } + + // Compute a style array (an array starting with a mode generation + // -- for invalidation -- followed by pairs of end positions and + // style strings), which is used to highlight the tokens on the + // line. + function highlightLine (cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {}; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function (end, style) { + st.push(end, style); + }, lineClasses, forceToEnd); + + // Run overlays, adjust style array. + for (var o = 0; o < cm.state.overlays.length; ++o) { + var overlay = cm.state.overlays[o], i = 1, at = 0; + runMode(cm, line.text, overlay.mode, true, function (end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) {st.splice(i, 1, end, st[i + 1], i_end);} + i += 2; + at = Math.min(end, i_end); + } + if (!style) return; + if (overlay.opaque) { + st.splice(start, i - start, end, "cm-overlay " + style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start + 1]; + st[start + 1] = (cur ? cur + " " : "") + "cm-overlay " + style; + } + } + }, lineClasses); + } + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; + } + + function getLineStyles (cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); + line.styles = result.styles; + if (result.classes) line.styleClasses = result.classes; + else if (line.styleClasses) line.styleClasses = null; + if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; + } + return line.styles; + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. Used for lines that + // aren't currently visible. + function processLine (cm, text, state, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize); + stream.start = stream.pos = startAt || 0; + if (text == "") callBlankLine(mode, state); + while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { + readToken(mode, stream, state); + stream.start = stream.pos; + } + } + + // Convert a style as returned by a mode (either null, or a string + // containing one or more styles) to a CSS style. This is cached, + // and also looks for line-wide styles. + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle (style, options) { + if (!style || /^\s*$/.test(style)) return null; + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + + // Render the DOM representation of the text of a line. Also builds + // up a 'line map', which points at the DOM nodes that represent + // specific stretches of text, and is used by the measuring code. + // The returned object contains the DOM node, this map, and + // information about line-wide styles that were set by the mode. + function buildLineContent (cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; + lineView.measure = {}; + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order; + builder.pos = 0; + builder.addToken = buildToken; + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) {builder.addToken = buildTokenBadBidi(builder.addToken, order);} + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) {builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");} + if (line.styleClasses.textClass) {builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");} + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) {builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));} + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + + // See issue #2901 + if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className)) {builder.content.className = "cm-tab-wrap-hack";} + + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) {builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");} + + return builder; + } + + function defaultSpecialCharPlaceholder (ch) { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + + // Build up the DOM representation for a single token, and add it to + // the line map. Takes care to render special characters separately. + function buildToken (builder, text, style, startStyle, endStyle, title, css) { + if (!text) return; + var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + if (!special.test(text)) { + builder.col += text.length; + var content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) mustWrap = true; + builder.pos += text.length; + } else { + var content = document.createDocumentFragment(), pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt.setAttribute("role", "presentation"); + txt.setAttribute("cm-text", "\t"); + builder.col += tabWidth; + } else { + var txt = builder.cm.options.specialCharPlaceholder(m[0]); + txt.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt); + builder.pos++; + } + } + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || ""; + if (startStyle) fullStyle += startStyle; + if (endStyle) fullStyle += endStyle; + var token = elt("span", [content], fullStyle, css); + if (title) token.title = title; + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + + function splitSpaces (old) { + var out = " "; + for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; + out += " "; + return out; + } + + // Work around nonsense dimensions being reported for stretches of + // right-to-left text. + function buildTokenBadBidi (inner, order) { + return function (builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (;;) { + // Find the part that overlaps with the start of this text + for (var i = 0; i < order.length; i++) { + var part = order[i]; + if (part.to > start && part.from <= start) break; + } + if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + }; + } + + function buildCollapsedSpan (builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) builder.map.push(builder.pos, builder.pos + size, widget); + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) {widget = builder.content.appendChild(document.createElement("span"));} + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent (line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i = 1; i < styles.length; i += 2) {builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i + 1], builder.cm.options));} + return; + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = ""; + collapsed = null; nextChange = Infinity; + var foundBookmarks = []; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) spanStyle += " " + m.className; + if (m.css) css = m.css; + if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; + if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; + if (m.title && !title) title = m.title; + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) {collapsed = sp;} + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null); + if (collapsed.to == null) return; + if (collapsed.to == pos) collapsed = false; + } + if (!collapsed && foundBookmarks.length) { + for (var j = 0; j < foundBookmarks.length; ++j) {buildCollapsedSpan(builder, 0, foundBookmarks[j]);} + } + } + if (pos >= len) break; + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = interpretTokenStyle(styles[i++], builder.cm.options); + } + } + } + + // DOCUMENT DATA STRUCTURE + + // By default, updates that start and end at the beginning of a line + // are treated specially, in order to make the association of line + // widgets and marker elements with the text behave more intuitive. + function isWholeLineUpdate (doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore); + } + + // Perform a change on the document data structure. + function updateDoc (doc, change, markedSpans, estimateHeight) { + function spansFor (n) {return markedSpans ? markedSpans[n] : null;} + function update (line, text, spans) { + updateLine(line, text, spans, estimateHeight); + signalLater(line, "change", line, change); + } + function linesFor (start, end) { + for (var i = start, result = []; i < end; ++i) {result.push(new Line(text[i], spansFor(i), estimateHeight));} + return result; + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) doc.remove(from.line, nlines); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added = linesFor(1, text.length - 1); + added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added = linesFor(1, text.length - 1); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1); + doc.insert(from.line + 1, added); + } + + signalLater(doc, "change", doc, change); + } + + // The document is represented as a BTree consisting of leaves, with + // chunk of lines in them, and branches, with up to ten leaves or + // other branch nodes below them. The top node is always a branch + // node, and is the document object itself (meaning it has + // additional methods and properties). + // + // All nodes have parent links. The tree is used both to go from + // line numbers to line objects, and to go from objects to numbers. + // It also indexes by height, and is used to convert between height + // and line object, and to find the total height of the document. + // + // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + + function LeafChunk (lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, height = 0; i < lines.length; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function () { return this.lines.length; }, + // Remove the n lines at offset 'at'. + removeInner: function (at, n) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function (lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function (at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0; i < lines.length; ++i) lines[i].parent = this; + }, + // Used to iterate over a part of the tree. + iterN: function (at, n, op) { + for (var e = at + n; at < e; ++at) {if (op(this.lines[at])) return true;} + } + }; + + function BranchChunk (children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0; i < children.length; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function () { return this.size; }, + removeInner: function (at, n) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) break; + at = 0; + } else at -= sz; + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function (lines) { + for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); + }, + insertInner: function (at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + while (child.lines.length > 50) { + var spilled = child.lines.splice(child.lines.length - 25, 25); + var newleaf = new LeafChunk(spilled); + child.height -= newleaf.height; + this.children.splice(i + 1, 0, newleaf); + newleaf.parent = this; + } + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function () { + if (this.children.length <= 10) return; + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function (at, n, op) { + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) return true; + if ((n -= used) == 0) break; + at = 0; + } else at -= sz; + } + } + }; + + var nextDocId = 0; + var Doc = CodeMirror.Doc = function (text, mode, firstLine) { + if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); + if (firstLine == null) firstLine = 0; + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.frontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + + if (typeof text === "string") text = splitLines(text); + updateDoc(this, {from: start, to: start, text: text}); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function (from, to, op) { + if (op) this.iterN(from - this.first, to - from, op); + else this.iterN(this.first, this.first + this.size, from); + }, + + // Non-public interface for adding and removing lines. + insert: function (at, lines) { + var height = 0; + for (var i = 0; i < lines.length; ++i) height += lines[i].height; + this.insertInner(at - this.first, lines, height); + }, + remove: function (at, n) { this.removeInner(at - this.first, n); }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function (lineSep, lineFilter) { + var lines = getLines(this, this.first, this.first + this.size, lineFilter); + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + setValue: docMethodOp(function (code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: splitLines(code), origin: "setValue", full: true}, true); + setSelection(this, simpleSelection(top)); + }), + replaceRange: function (code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function (from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + + getLine: function (line) {var l = this.getLineHandle(line); return l && l.text;}, + + getLineHandle: function (line) {if (isLine(this, line)) return getLine(this, line);}, + getLineNumber: function (line) {return lineNo(line);}, + + getLineHandleVisualStart: function (line) { + if (typeof line === "number") line = getLine(this, line); + return visualLine(line); + }, + + lineCount: function () {return this.size;}, + firstLine: function () {return this.first;}, + lastLine: function () {return this.first + this.size - 1;}, + + clipPos: function (pos) {return clipPos(this, pos);}, + + getCursor: function (start) { + var range = this.sel.primary(), pos; + if (start == null || start == "head") pos = range.head; + else if (start == "anchor") pos = range.anchor; + else if (start == "end" || start == "to" || start === false) pos = range.to(); + else pos = range.from(); + return pos; + }, + listSelections: function () { return this.sel.ranges; }, + somethingSelected: function () {return this.sel.somethingSelected();}, + + setCursor: docMethodOp(function (line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line === "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function (anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function (head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function (heads, options) { + extendSelections(this, clipPosArray(this, heads, options)); + }), + extendSelectionsBy: docMethodOp(function (f, options) { + extendSelections(this, map(this.sel.ranges, f), options); + }), + setSelections: docMethodOp(function (ranges, primary, options) { + if (!ranges.length) return; + for (var i = 0, out = []; i < ranges.length; i++) { + out[i] = new Range(clipPos(this, ranges[i].anchor), + clipPos(this, ranges[i].head)); + } + if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); + setSelection(this, normalizeSelection(out, primary), options); + }), + addSelection: docMethodOp(function (anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); + }), + + getSelection: function (lineSep) { + var ranges = this.sel.ranges, lines; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + getSelections: function (lineSep) { + var parts = [], ranges = this.sel.ranges; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + if (lineSep !== false) sel = sel.join(lineSep || "\n"); + parts[i] = sel; + } + return parts; + }, + replaceSelection: function (code, collapse, origin) { + var dup = []; + for (var i = 0; i < this.sel.ranges.length; i++) {dup[i] = code;} + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function (code, collapse, origin) { + var changes = [], sel = this.sel; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin}; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i = changes.length - 1; i >= 0; i--) {makeChange(this, changes[i]);} + if (newSel) setSelectionReplaceHistory(this, newSel); + else if (this.cm) ensureCursorVisible(this.cm); + }), + undo: docMethodOp(function () {makeChangeFromHistory(this, "undo");}), + redo: docMethodOp(function () {makeChangeFromHistory(this, "redo");}), + undoSelection: docMethodOp(function () {makeChangeFromHistory(this, "undo", true);}), + redoSelection: docMethodOp(function () {makeChangeFromHistory(this, "redo", true);}), + + setExtending: function (val) {this.extend = val;}, + getExtending: function () {return this.extend;}, + + historySize: function () { + var hist = this.history, done = 0, undone = 0; + for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; + for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; + return {undo: done, redo: undone}; + }, + clearHistory: function () {this.history = new History(this.history.maxGeneration);}, + + markClean: function () { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function (forceSplit) { + if (forceSplit) {this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;} + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + + getHistory: function () { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)}; + }, + setHistory: function (histData) { + var hist = this.history = new History(this.history.maxGeneration); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + + addLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop]) line[prop] = cls; + else if (classTest(cls).test(line[prop])) return false; + else line[prop] += " " + cls; + return true; + }); + }), + removeLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) return false; + else if (cls == null) line[prop] = null; + else { + var found = cur.match(classTest(cls)); + if (!found) return false; + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + + addLineWidget: docMethodOp(function (handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function (widget) { widget.clear(); }, + + markText: function (from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); + }, + setBookmark: function (pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function (pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) {markers.push(span.marker.parent || span.marker);} + } + } + return markers; + }, + findMarks: function (from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to); + var found = [], lineNo = from.line; + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans; + if (spans) { + for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + if (!(lineNo == from.line && from.ch > span.to || + span.from == null && lineNo != from.line || + lineNo == to.line && span.from > to.ch) && + (!filter || filter(span.marker))) {found.push(span.marker.parent || span.marker);} + } + } + ++lineNo; + }); + return found; + }, + getAllMarks: function () { + var markers = []; + this.iter(function (line) { + var sps = line.markedSpans; + if (sps) { + for (var i = 0; i < sps.length; ++i) {if (sps[i].from != null) markers.push(sps[i].marker);} + } + }); + return markers; + }, + + posFromIndex: function (off) { + var ch, lineNo = this.first; + this.iter(function (line) { + var sz = line.text.length + 1; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos(this, Pos(lineNo, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) return 0; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + 1; + }); + return index; + }, + + copy: function (copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + + linkedDoc: function (options) { + if (!options) options = {}; + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) from = options.from; + if (options.to != null && options.to < to) to = options.to; + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); + if (options.sharedHist) copy.history = this.history; + (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function (other) { + if (other instanceof CodeMirror) other = other.doc; + if (this.linked) { + for (var i = 0; i < this.linked.length; ++i) { + var link = this.linked[i]; + if (link.doc != other) continue; + this.linked.splice(i, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } + } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function (doc) {splitIds.push(doc.id);}, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function (f) {linkedDocs(this, f);}, + + getMode: function () {return this.mode;}, + getEditor: function () {return this.cm;} + }); + + // Public alias. + Doc.prototype.eachLine = Doc.prototype.iter; + + // Set up methods on CodeMirror's prototype to redirect to the editor's document. + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { + if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { + CodeMirror.prototype[prop] = (function (method) { + return function () {return method.apply(this.doc, arguments);}; + })(Doc.prototype[prop]); + } + } + + eventMixin(Doc); + + // Call f for all linked documents. + function linkedDocs (doc, f, sharedHistOnly) { + function propagate (doc, skip, sharedHist) { + if (doc.linked) { + for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) continue; + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) continue; + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } + } + } + propagate(doc, null, true); + } + + // Attach a document to an editor. + function attachDoc (cm, doc) { + if (doc.cm) throw new Error("This document is already in use."); + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + if (!cm.options.lineWrapping) findMaxLine(cm); + cm.options.mode = doc.modeOption; + regChange(cm); + } + + // LINE UTILITIES + + // Find the line object corresponding to the given line number. + function getLine (doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); + for (var chunk = doc; !chunk.lines;) { + for (var i = 0; ; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break; } + n -= sz; + } + } + return chunk.lines[n]; + } + + // Get the part of a document between two positions, as an array of + // strings. + function getBetween (doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text; + if (n == end.line) text = text.slice(0, end.ch); + if (n == start.line) text = text.slice(start.ch); + out.push(text); + ++n; + }); + return out; + } + // Get the lines between from and to, as array of strings. + function getLines (doc, from, to, lineFilter) { + var out = []; + doc.iter(from, to, function (line) { + var text = line.text; + if(lineFilter) { + text = lineFilter(line); + } + out.push(text); + }); + return out; + } + + // Update the height of a line, propagating the height change + // upwards to parent nodes. + function updateLineHeight (line, height) { + var diff = height - line.height; + if (diff) for (var n = line; n; n = n.parent) n.height += diff; + } + + // Given a line object, find its line number by walking up through + // its parent links. + function lineNo (line) { + if (line.parent == null) return null; + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0; ; ++i) { + if (chunk.children[i] == cur) break; + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first; + } + + // Find the line at the given vertical position, using the height + // information in the document tree. + function lineAtHeight (chunk, h) { + var n = chunk.first; + outer: do { + for (var i = 0; i < chunk.children.length; ++i) { + var child = chunk.children[i], ch = child.height; + if (h < ch) { chunk = child; continue outer; } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + + + // Find the height above the given line. + function heightAtLine (lineObj) { + lineObj = visualLine(lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) break; + else h += line.height; + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i = 0; i < p.children.length; ++i) { + var cur = p.children[i]; + if (cur == chunk) break; + else h += cur.height; + } + } + return h; + } + + // Get the bidi ordering for the given line (and cache it). Returns + // false for lines that are fully left-to-right, and an array of + // BidiSpan objects otherwise. + function getOrder (line) { + var order = line.order; + if (order == null) order = line.order = bidiOrdering(line.text); + return order; + } + + // HISTORY + + function History (startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = []; + this.undoDepth = Infinity; + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1; + } + + // Create a history change event from an updateDoc-style change + // object. + function historyChangeFromChange (doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function (doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); + return histChange; + } + + // Pop all selection events off the end of a history array. Stop at + // a change event. + function clearSelectionEvents (array) { + while (array.length) { + var last = lst(array); + if (last.ranges) array.pop(); + else break; + } + } + + // Find the top change event in the history. Pop off selection + // events that are in the way. + function lastChangeEvent (hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + + // Register a change in the history. Merges changes that are within + // a single operation, ore are close together with an origin that + // allows merging (starting with "+") into a single event. + function addChangeToHistory (doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur; + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + var last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done); + if (!before || !before.ranges) {pushSelectionToHistory(doc.sel, hist.done);} + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation}; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) hist.done.shift(); + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + + if (!last) signal(doc, "historyAdded"); + } + + function selectionEventCanBeMerged (doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); + } + + // Called whenever the selection changes, sets the new selection as + // the pending selection in the history, and pushes the old pending + // selection into the 'done' array when it was significantly + // different (in number of selected ranges, emptiness, or time). + function addSelectionToHistory (doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin; + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) {hist.done[hist.done.length - 1] = sel;} else {pushSelectionToHistory(sel, hist.done);} + + hist.lastSelTime = +new Date; + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) {clearSelectionEvents(hist.undone);} + } + + function pushSelectionToHistory (sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) {dest.push(sel);} + } + + // Used to store marked span information in the history. + function attachLocalSpans (doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) {(existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;} + ++n; + }); + } + + // When un/re-doing restores text containing marked spans, those + // that have been explicitly cleared should not be restored. + function removeClearedSpans (spans) { + if (!spans) return null; + for (var i = 0, out; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } else if (out) out.push(spans[i]); + } + return !out ? spans : out.length ? out : null; + } + + // Retrieve and filter the old marked spans stored in a change event. + function getOldSpans (doc, change) { + var found = change["spans_" + doc.id]; + if (!found) return null; + for (var i = 0, nw = []; i < change.text.length; ++i) {nw.push(removeClearedSpans(found[i]));} + return nw; + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray (events, newGroup, instantiateSel) { + for (var i = 0, copy = []; i < events.length; ++i) { + var event = events[i]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, newChanges = []; + copy.push({changes: newChanges}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m; + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) { + for (var prop in change) { + if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } + } + } + } + } + return copy; + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSelSingle (pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray (array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue; + } + for (var j = 0; j < sub.changes.length; ++j) { + var cur = sub.changes[j]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } + } + } + + function rebaseHist (hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // EVENT UTILITIES + + // Due to the fact that we still support jurassic IE versions, some + // compatibility wrappers are needed. + + var e_preventDefault = CodeMirror.e_preventDefault = function (e) { + if (e.preventDefault) e.preventDefault(); + else e.returnValue = false; + }; + var e_stopPropagation = CodeMirror.e_stopPropagation = function (e) { + if (e.stopPropagation) e.stopPropagation(); + else e.cancelBubble = true; + }; + function e_defaultPrevented (e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + var e_stop = CodeMirror.e_stop = function (e) {e_preventDefault(e); e_stopPropagation(e);}; + + function e_target (e) {return e.target || e.srcElement;} + function e_button (e) { + var b = e.which; + if (b == null) { + if (e.button & 1) b = 1; + else if (e.button & 2) b = 3; + else if (e.button & 4) b = 2; + } + if (mac && e.ctrlKey && b == 1) b = 3; + return b; + } + + // EVENT HANDLING + + // Lightweight event framework. on/off also work on DOM nodes, + // registering native DOM handlers. + + var on = CodeMirror.on = function (emitter, type, f) { + if (emitter.addEventListener) {emitter.addEventListener(type, f, false);} else if (emitter.attachEvent) {emitter.attachEvent("on" + type, f);} else { + var map = emitter._handlers || (emitter._handlers = {}); + var arr = map[type] || (map[type] = []); + arr.push(f); + } + }; + + var off = CodeMirror.off = function (emitter, type, f) { + if (emitter.removeEventListener) {emitter.removeEventListener(type, f, false);} else if (emitter.detachEvent) {emitter.detachEvent("on" + type, f);} else { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + for (var i = 0; i < arr.length; ++i) {if (arr[i] == f) { arr.splice(i, 1); break; }} + } + }; + + var signal = CodeMirror.signal = function (emitter, type /* , values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); + }; + + var orphanDelayedCallbacks = null; + + // Often, we want to signal events at a point where we are in the + // middle of some work, but don't want the handler to start calling + // other methods on the editor, which might be in an inconsistent + // state or simply not expect any other events to happen. + // signalLater looks whether there are any handlers, and schedules + // them to be executed when the last operation ends, or, if no + // operation is active, when a timeout fires. + function signalLater (emitter, type /* , values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + function bnd (f) {return function () {f.apply(null, args);};} + for (var i = 0; i < arr.length; ++i) {list.push(bnd(arr[i]));} + } + + function fireOrphanDelayed () { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) delayed[i](); + } + + // The DOM events that CodeMirror handles can be overridden by + // registering a (non-DOM) handler on the editor for the event name, + // and preventDefault-ing the event in that handler. + function signalDOMEvent (cm, e, override) { + if (typeof e === "string") {e = {type: e, preventDefault: function () { this.defaultPrevented = true; }};} + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + + function signalCursorActivity (cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) return; + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i = 0; i < arr.length; ++i) { + if (indexOf(set, arr[i]) == -1) {set.push(arr[i]);} + } + } + + function hasHandler (emitter, type) { + var arr = emitter._handlers && emitter._handlers[type]; + return arr && arr.length > 0; + } + + // Add on and off methods to a constructor's prototype, to make + // registering events on such objects more convenient. + function eventMixin (ctor) { + ctor.prototype.on = function (type, f) {on(this, type, f);}; + ctor.prototype.off = function (type, f) {off(this, type, f);}; + } + + // MISC UTILITIES + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerGap = 30; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = CodeMirror.Pass = {toString: function () {return "CodeMirror.Pass";}}; + + // Reused option objects for setSelection & friends + var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; + + function Delayed () {this.id = null;} + Delayed.prototype.set = function (ms, f) { + clearTimeout(this.id); + this.id = setTimeout(f, ms); + }; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + var countColumn = CodeMirror.countColumn = function (string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = startIndex || 0, n = startValue || 0; ;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) {return n + (end - i);} + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } + }; + + // The inverse of countColumn -- find the offset that corresponds to + // a particular column. + function findColumn (string, goal, tabSize) { + for (var pos = 0, col = 0; ;) { + var nextTab = string.indexOf("\t", pos); + if (nextTab == -1) nextTab = string.length; + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) {return pos + Math.min(skipped, goal - col);} + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) return pos; + } + } + + var spaceStrs = [""]; + function spaceStr (n) { + while (spaceStrs.length <= n) {spaceStrs.push(lst(spaceStrs) + " ");} + return spaceStrs[n]; + } + + function lst (arr) { return arr[arr.length - 1]; } + + var selectInput = function (node) { node.select(); }; + if (ios) // Mobile Safari apparently has a bug where select() is broken. + {selectInput = function (node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };} else if (ie) // Suppress mysterious IE10 errors + {selectInput = function (node) { try { node.select(); } catch(_e) {} };} + + function indexOf (array, elt) { + for (var i = 0; i < array.length; ++i) {if (array[i] == elt) return i;} + return -1; + } + function map (array, f) { + var out = []; + for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); + return out; + } + + function nothing () {} + + function createObj (base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) copyObj(props, inst); + return inst; + } + + function copyObj (obj, target, overwrite) { + if (!target) target = {}; + for (var prop in obj) { + if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) {target[prop] = obj[prop];} + } + return target; + } + + function bind (f) { + var args = Array.prototype.slice.call(arguments, 1); + return function () {return f.apply(null, args);}; + } + + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + var isWordCharBasic = CodeMirror.isWordChar = function (ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + }; + function isWordChar (ch, helper) { + if (!helper) return isWordCharBasic(ch); + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; + return helper.test(ch); + } + + function isEmpty (obj) { + for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; + return true; + } + + // Extending unicode characters. A series of a non-extending char + + // any number of extending chars is treated as a single unit as far + // as editing and measuring is concerned. This is not fully correct, + // since some scripts/font/browsers also treat other configurations + // of code points as a group. + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar (ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } + + // DOM UTILITIES + + function elt (tag, content, className, style) { + var e = document.createElement(tag); + if (className) e.className = className; + if (style) e.style.cssText = style; + if (typeof content === "string") e.appendChild(document.createTextNode(content)); + else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + + var range; + if (document.createRange) { + range = function (node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + } else { + range = function (node, start, end) { + var r = document.body.createTextRange(); + try { r.moveToElementText(node.parentNode); } catch(e) { return r; } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + } + + function removeChildren (e) { + for (var count = e.childNodes.length; count > 0; --count) {e.removeChild(e.firstChild);} + return e; + } + + function removeChildrenAndAdd (parent, e) { + return removeChildren(parent).appendChild(e); + } + + var contains = CodeMirror.contains = function (parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + {child = child.parentNode;} + if (parent.contains) {return parent.contains(child);} + do { + if (child.nodeType == 11) child = child.host; + if (child == parent) return true; + } while (child = child.parentNode); + }; + + function activeElt () { return document.activeElement; } + // Older versions of IE throws unspecified error when touching + // document.activeElement in some cases (during loading, in iframe) + if (ie && ie_version < 11) { + activeElt = function () { + try { return document.activeElement; } catch(e) { return document.body; } + }; + } + + function classTest (cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } + var rmClass = CodeMirror.rmClass = function (node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + var addClass = CodeMirror.addClass = function (node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; + }; + function joinClasses (a, b) { + var as = a.split(" "); + for (var i = 0; i < as.length; i++) {if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];} + return b; + } + + // WINDOW-WIDE EVENTS + + // These must be handled carefully, because naively registering a + // handler for each editor will cause the editors to never be + // garbage collected. + + function forEachCodeMirror (f) { + if (!document.body.getElementsByClassName) return; + var byClass = document.body.getElementsByClassName("CodeMirror"); + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) f(cm); + } + } + + var globalsRegistered = false; + function ensureGlobalHandlers () { + if (globalsRegistered) return; + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers () { + // When the window resizes, we need to refresh active editors. + var resizeTimer; + on(window, "resize", function () { + if (resizeTimer == null) { + resizeTimer = setTimeout(function () { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + } + }); + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { + forEachCodeMirror(onBlur); + }); + } + + // FEATURE DETECTION + + // Detect drag-and-drop + var dragAndDrop = function () { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) return false; + var div = elt("div"); + return "draggable" in div || "dragDrop" in div; + }(); + + var zwspSupported; + function zeroWidthElement (measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) {zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);} + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + + // Feature-detect IE's crummy client rect reporting for bidi text + var badBidiRects; + function hasBadBidiRects (measure) { + if (badBidiRects != null) return badBidiRects; + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) + var r1 = range(txt, 1, 2).getBoundingClientRect(); + return badBidiRects = (r1.right - r0.right < 3); + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) nl = string.length; + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function (string) {return string.split(/\r\n?|\n/);}; + + var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } + } : function (te) { + try {var range = te.ownerDocument.selection.createRange();} catch(e) {} + if (!range || range.parentElement() != te) return false; + return range.compareEndPoints("StartToEnd", range) != 0; + }; + + var hasCopyEvent = (function () { + var e = elt("div"); + if ("oncopy" in e) return true; + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy === "function"; + })(); + + var badZoomedRects = null; + function hasBadZoomedRects (measure) { + if (badZoomedRects != null) return badZoomedRects; + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + + // KEY NAMES + + var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; + CodeMirror.keyNames = keyNames; + (function () { + // Number keys + for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); + // Alphabetic keys + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + // Function keys + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + + // BIDI HELPERS + + function iterateBidiSections (order, from, to, f) { + if (!order) return f(from, to, "ltr"); + var found = false; + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); + found = true; + } + } + if (!found) f(from, to, "ltr"); + } + + function bidiLeft (part) { return part.level % 2 ? part.to : part.from; } + function bidiRight (part) { return part.level % 2 ? part.from : part.to; } + + function lineLeft (line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } + function lineRight (line) { + var order = getOrder(line); + if (!order) return line.text.length; + return bidiRight(lst(order)); + } + + function lineStart (cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) lineN = lineNo(visual); + var order = getOrder(visual); + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); + return Pos(lineN, ch); + } + function lineEnd (cm, lineN) { + var merged, line = getLine(cm.doc, lineN); + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + lineN = null; + } + var order = getOrder(line); + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); + return Pos(lineN == null ? lineNo(line) : lineN, ch); + } + function lineStartSmart (cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS); + } + return start; + } + + function compareBidiLevel (order, a, b) { + var linedir = order[0].level; + if (a == linedir) return true; + if (b == linedir) return false; + return a < b; + } + var bidiOther; + function getBidiPartAt (order, pos) { + bidiOther = null; + for (var i = 0, found; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < pos && cur.to > pos) return i; + if ((cur.from == pos || cur.to == pos)) { + if (found == null) { + found = i; + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + if (cur.from != cur.to) bidiOther = found; + return i; + } else { + if (cur.from != cur.to) bidiOther = i; + return found; + } + } + } + return found; + } + + function moveInLine (line, pos, dir, byUnit) { + if (!byUnit) return pos + dir; + do pos += dir; + while (pos > 0 && isExtendingChar(line.text.charAt(pos))); + return pos; + } + + // This is needed in order to move 'visually' through bi-directional + // text -- i.e., pressing left should make the cursor go left, even + // when in RTL text. The tricky part is the 'jumps', where RTL and + // LTR text touch each other. This often requires the cursor offset + // to move more than one unit, in order to visually move one unit. + function moveVisually (line, start, dir, byUnit) { + var bidi = getOrder(line); + if (!bidi) return moveLogically(line, start, dir, byUnit); + var pos = getBidiPartAt(bidi, start), part = bidi[pos]; + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); + + for (;;) { + if (target > part.from && target < part.to) return target; + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) return target; + part = bidi[pos += dir]; + return (dir > 0) == part.level % 2 ? part.to : part.from; + } + part = bidi[pos += dir]; + if (!part) return null; + if ((dir > 0) == part.level % 2) {target = moveInLine(line, part.to, -1, byUnit);} else {target = moveInLine(line, part.from, 1, byUnit);} + + } + } + + function moveLogically (line, start, dir, byUnit) { + var target = start + dir; + if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; + return target < 0 || target > line.text.length ? null : target; + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function () { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + // Character types for codepoints 0x600 to 0x6ff + var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; + function charType (code) { + if (code <= 0xf7) return lowTypes.charAt(code); + else if (0x590 <= code && code <= 0x5f4) return "R"; + else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); + else if (0x6ee <= code && code <= 0x8ac) return "r"; + else if (0x2000 <= code && code <= 0x200b) return "w"; + else if (code == 0x200c) return "b"; + return "L"; + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L"; + + function BidiSpan (level, from, to) { + this.level = level; + this.from = from; this.to = to; + } + + return function (str) { + if (!bidiRE.test(str)) return false; + var len = str.length, types = []; + for (var i = 0, type; i < len; ++i) {types.push(type = charType(str.charCodeAt(i)));} + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i = 0, prev = outerType; i < len; ++i) { + var type = types[i]; + if (type == "m") types[i] = prev; + else prev = type; + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (type == "1" && cur == "r") types[i] = "n"; + else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i = 1, prev = types[0]; i < len - 1; ++i) { + var type = types[i]; + if (type == "+" && prev == "1" && types[i + 1] == "1") types[i] = "1"; + else if (type == "," && prev == types[i + 1] && + (prev == "1" || prev == "n")) types[i] = prev; + prev = type; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i = 0; i < len; ++i) { + var type = types[i]; + if (type == ",") types[i] = "N"; + else if (type == "%") { + for (var end = i + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i && types[i - 1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (cur == "L" && type == "1") types[i] = "L"; + else if (isStrong.test(type)) cur = type; + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i = 0; i < len; ++i) { + if (isNeutral.test(types[i])) { + for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} + var before = (i ? types[i - 1] : outerType) == "L"; + var after = (end < len ? types[end] : outerType) == "L"; + var replace = before || after ? "L" : "R"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i = 0; i < len;) { + if (countsAsLeft.test(types[i])) { + var start = i; + for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} + order.push(new BidiSpan(0, start, i)); + } else { + var pos = i, at = order.length; + for (++i; i < len && types[i] != "L"; ++i) {} + for (var j = pos; j < i;) { + if (countsAsNum.test(types[j])) { + if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); + var nstart = j; + for (++j; j < i && countsAsNum.test(types[j]); ++j) {} + order.splice(at, 0, new BidiSpan(2, nstart, j)); + pos = j; + } else ++j; + } + if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + if (order[0].level == 2) {order.unshift(new BidiSpan(1, order[0].to, order[0].to));} + if (order[0].level != lst(order).level) {order.push(new BidiSpan(order[0].level, len, len));} + + return order; + }; + })(); + + // THE END + + CodeMirror.version = "5.4.1"; + + return CodeMirror; +});(function (mod) { + mod(CodeMirror); +})(function (CodeMirror) { + var Pos = CodeMirror.Pos; + + function forEach (arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); + } + + function arrayContains (arr, item) { + if (!Array.prototype.indexOf) { + var i = arr.length; + while (i--) { + if (arr[i] === item) { + return true; + } + } + return false; + } + return arr.indexOf(item) != -1; + } + + function scriptHint (editor, keywords, getToken, options) { + // Find the token at the cursor + var cur = editor.getCursor(), token = getToken(editor, cur); + if (/\b(?:string)\b/.test(token.type)) { + return; + } + token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; + + if (!/^[\w$_]*$/.test(token.string)) { + token = { + start: cur.ch, end: cur.ch, string: "", state: token.state, + type: token.string == "." ? "property" : null + }; + } else if (token.end > cur.ch) { + token.end = cur.ch; + token.string = token.string.slice(0, cur.ch - token.start); + } + + var tprop = token; + // If it is a property, find out what it is a property of. + while (tprop.type == "property") { + tprop = getToken(editor, Pos(cur.line, tprop.start)); + if (tprop.string != ".") return; + tprop = getToken(editor, Pos(cur.line, tprop.start)); + if (!context) var context = []; + context.push(tprop); + } + return { + list: getCompletions(token, context, keywords, options), + from: Pos(cur.line, token.start), + to: Pos(cur.line, token.end) + }; + } + + function getFormulaKeywords () { + return BI.FormulaCollections; + } + + function formulaHint (editor, options) { + return scriptHint(editor, getFormulaKeywords(), + function (e, cur) { + return e.getTokenAt(cur); + }, + options); + } + CodeMirror.registerHelper("hint", "formula", formulaHint); + + function getCompletions (token, context, keywords, options) { + var found = [], start = token.string; + if (!start) { + return found; + } + function maybeAdd (str) { + if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) { + found.push(str); + } + } + + if (context && context.length) { + context.pop(); + } else { + forEach(keywords, maybeAdd); + } + return found; + } +});(function (mod) { + mod(CodeMirror); +})(function (CodeMirror) { + "use strict"; + + CodeMirror.defineMode("formula", function () { + function wordObj (words) { + var o = {}; + for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; + return o; + } + + var atoms = wordObj(["false", "true"]); + var keywords = wordObj(BI.FormulaCollections); + + function tokenBase (stream, state) { + if (stream.eatSpace()) { + return null; + } + var ch = stream.next(); + + if (ch === "\"" || ch === "'") { + nextUntilUnescaped(stream, ch); + return "string"; + } + if (ch === "\u200b") { + nextUntilUnescaped(stream, ch); + return "field"; + } + if (/[\[\],\(\)]/.test(ch)) { + return "bracket"; + } + + // richie:暂时不需要解析操作符号 + // if (/[+\-*\/=<>!&|]/.test(ch)) { + // return 'operator'; + // } + // if (/\d|\d./.test(ch)) { + // stream.eatWhile(/\d|\./); + // if (stream.eol() || !/\w/.test(stream.peek())) { + // return 'number'; + // } + // } + + + + stream.eatWhile(/[\w-]/); + var word = stream.current(); + if (atoms.hasOwnProperty(word)) { + return "atom"; + } + if (keywords.hasOwnProperty(word)) { + return "keyword"; + } + return null; + } + + function nextUntilUnescaped (stream, end) { + var escaped = false, next; + while ((next = stream.next()) != null) { + if (next === end && !escaped) { + return false; + } + escaped = !escaped && next === "\\"; + } + return escaped; + } + + function tokenize (stream, state) { + return (state.tokens[0] || tokenBase)(stream, state); + } + + return { + startState: function () { + return {tokens: []}; + }, + token: function (stream, state) { + return tokenize(stream, state); + }, + fold: "brace" + }; + }); + CodeMirror.defineMIME("text/fx-formula", "formula"); +});// CodeMirror, copyright (c) by Marijn Haverbeke and others +// Distributed under an MIT license: http://codemirror.net/LICENSE + +(function (mod) { + mod(CodeMirror); +})(function (CodeMirror) { + "use strict"; + + var HINT_ELEMENT_CLASS = "CodeMirror-hint"; + var ACTIVE_HINT_ELEMENT_CLASS = "CodeMirror-hint-active"; + + // This is the old interface, kept around for now to stay + // backwards-compatible. + CodeMirror.showHint = function (cm, getHints, options) { + if (!getHints) return cm.showHint(options); + if (options && options.async) getHints.async = true; + var newOpts = {hint: getHints}; + if (options) for (var prop in options) newOpts[prop] = options[prop]; + return cm.showHint(newOpts); + }; + + CodeMirror.defineExtension("showHint", function (options) { + // We want a single cursor position. + if (this.listSelections().length > 1 || this.somethingSelected()) return; + + if (this.state.completionActive) this.state.completionActive.close(); + var completion = this.state.completionActive = new Completion(this, options); + if (!completion.options.hint) return; + + CodeMirror.signal(this, "startCompletion", this); + completion.update(true); + }); + + function Completion (cm, options) { + this.cm = cm; + this.options = this.buildOptions(options); + this.widget = null; + this.debounce = 0; + this.tick = 0; + this.startPos = this.cm.getCursor(); + this.startLen = this.cm.getLine(this.startPos.line).length; + + var self = this; + cm.on("cursorActivity", this.activityFunc = function () { + self.cursorActivity(); + }); + } + + var requestAnimationFrame = window.requestAnimationFrame || function (fn) { + return setTimeout(fn, 1000 / 60); + }; + var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; + + Completion.prototype = { + close: function () { + if (!this.active()) return; + this.cm.state.completionActive = null; + this.tick = null; + this.cm.off("cursorActivity", this.activityFunc); + + if (this.widget && this.data) CodeMirror.signal(this.data, "close"); + if (this.widget) this.widget.close(); + CodeMirror.signal(this.cm, "endCompletion", this.cm); + }, + + active: function () { + return this.cm.state.completionActive == this; + }, + + pick: function (data, i) { + var completion = data.list[i]; + if (completion.hint) completion.hint(this.cm, data, completion); + else { + this.cm.replaceRange(getText(completion), completion.from || data.from, + completion.to || data.to, "complete"); + if(completion.isKeyword === true) { + }else{ + var to = this.cm.getCursor(); + this.cm.markText(completion.from || data.from, to, {className: "#function", atomic: true}); + this.cm.replaceSelection("() "); + to = this.cm.getCursor(); + to.ch = to.ch - 2; + this.cm.setCursor(to); + this.cm.focus(); + } + } + CodeMirror.signal(data, "pick", completion); + this.close(); + }, + + cursorActivity: function () { + if (this.debounce) { + cancelAnimationFrame(this.debounce); + this.debounce = 0; + } + + var pos = this.cm.getCursor(), line = this.cm.getLine(pos.line); + if (pos.line != this.startPos.line || line.length - pos.ch != this.startLen - this.startPos.ch || + pos.ch < this.startPos.ch || this.cm.somethingSelected() || + (pos.ch && this.options.closeCharacters.test(line.charAt(pos.ch - 1)))) { + this.close(); + } else { + var self = this; + this.debounce = requestAnimationFrame(function () { + self.update(); + }); + if (this.widget) this.widget.disable(); + } + }, + + update: function (first) { + if (this.tick == null) return; + if (this.data) CodeMirror.signal(this.data, "update"); + if (!this.options.hint.async) { + this.finishUpdate(this.options.hint(this.cm, this.options), first); + } else { + var myTick = ++this.tick, self = this; + this.options.hint(this.cm, function (data) { + if (self.tick == myTick) self.finishUpdate(data, first); + }, this.options); + } + }, + + finishUpdate: function (data, first) { + this.data = data; + + var picked = (this.widget && this.widget.picked) || (first && this.options.completeSingle); + if (this.widget) this.widget.close(); + if (data && data.list.length) { + if (picked && data.list.length == 1) { + this.pick(data, 0); + } else { + this.widget = new Widget(this, data); + CodeMirror.signal(data, "shown"); + } + } + }, + + buildOptions: function (options) { + var editor = this.cm.options.hintOptions; + var out = {}; + for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; + if (editor) { + for (var prop in editor) {if (editor[prop] !== undefined) out[prop] = editor[prop];} + } + if (options) { + for (var prop in options) {if (options[prop] !== undefined) out[prop] = options[prop];} + } + return out; + } + }; + + function getText (completion) { + if (typeof completion === "string") return completion; + return completion.text; + } + + function buildKeyMap (completion, handle) { + var baseMap = { + Up: function () { + handle.moveFocus(-1); + }, + Down: function () { + handle.moveFocus(1); + }, + PageUp: function () { + handle.moveFocus(-handle.menuSize() + 1, true); + }, + PageDown: function () { + handle.moveFocus(handle.menuSize() - 1, true); + }, + Home: function () { + handle.setFocus(0); + }, + End: function () { + handle.setFocus(handle.length - 1); + }, + Enter: handle.pick, + Tab: handle.pick, + Esc: handle.close + }; + var custom = completion.options.customKeys; + var ourMap = custom ? {} : baseMap; + + function addBinding (key, val) { + var bound; + if (typeof val !== "string") { + bound = function (cm) { + return val(cm, handle); + }; + } + // This mechanism is deprecated + else if (baseMap.hasOwnProperty(val)) {bound = baseMap[val];} else {bound = val;} + ourMap[key] = bound; + } + + if (custom) { + for (var key in custom) { + if (custom.hasOwnProperty(key)) {addBinding(key, custom[key]);} + } + } + var extra = completion.options.extraKeys; + if (extra) { + for (var key in extra) { + if (extra.hasOwnProperty(key)) {addBinding(key, extra[key]);} + } + } + return ourMap; + } + + function getHintElement (hintsElement, el) { + while (el && el != hintsElement) { + if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; + el = el.parentNode; + } + } + + function Widget (completion, data) { + this.completion = completion; + this.data = data; + this.picked = false; + var widget = this, cm = completion.cm; + + var hints = this.hints = document.createElement("ul"); + hints.className = "CodeMirror-hints"; + this.selectedHint = data.selectedHint || 0; + + var completions = data.list; + for (var i = 0; i < completions.length; ++i) { + var elt = hints.appendChild(document.createElement("li")), cur = completions[i]; + var className = HINT_ELEMENT_CLASS + (i != this.selectedHint ? "" : " " + ACTIVE_HINT_ELEMENT_CLASS); + if (cur.className != null) className = cur.className + " " + className; + elt.className = className; + if (cur.render) cur.render(elt, data, cur); + else elt.appendChild(document.createTextNode(cur.displayText || getText(cur))); + elt.hintId = i; + } + + var pos = cm.cursorCoords(completion.options.alignWithWord ? data.from : null); + var left = pos.left, top = pos.bottom, below = true; + hints.style.left = left + "px"; + hints.style.top = top + "px"; + // If we're at the edge of the screen, then we want the menu to appear on the left of the cursor. + var winW = window.innerWidth || Math.max(document.body.offsetWidth, document.documentElement.offsetWidth); + var winH = window.innerHeight || Math.max(document.body.offsetHeight, document.documentElement.offsetHeight); + (completion.options.container || document.body).appendChild(hints); + var box = hints.getBoundingClientRect(), overlapY = box.bottom - winH; + if (overlapY > 0) { + var height = box.bottom - box.top, curTop = pos.top - (pos.bottom - box.top); + if (curTop - height > 0) { // Fits above cursor + hints.style.top = (top = pos.top - height) + "px"; + below = false; + } else if (height > winH) { + hints.style.height = (winH - 5) + "px"; + hints.style.top = (top = pos.bottom - box.top) + "px"; + var cursor = cm.getCursor(); + if (data.from.ch != cursor.ch) { + pos = cm.cursorCoords(cursor); + hints.style.left = (left = pos.left) + "px"; + box = hints.getBoundingClientRect(); + } + } + } + var overlapX = box.right - winW; + if (overlapX > 0) { + if (box.right - box.left > winW) { + hints.style.width = (winW - 5) + "px"; + overlapX -= (box.right - box.left) - winW; + } + hints.style.left = (left = pos.left - overlapX) + "px"; + } + + cm.addKeyMap(this.keyMap = buildKeyMap(completion, { + moveFocus: function (n, avoidWrap) { + widget.changeActive(widget.selectedHint + n, avoidWrap); + }, + setFocus: function (n) { + widget.changeActive(n); + }, + menuSize: function () { + return widget.screenAmount(); + }, + length: completions.length, + close: function () { + completion.close(); + }, + pick: function () { + widget.pick(); + }, + data: data + })); + + if (completion.options.closeOnUnfocus) { + var closingOnBlur; + cm.on("blur", this.onBlur = function () { + closingOnBlur = setTimeout(function () { + completion.close(); + }, 100); + }); + cm.on("focus", this.onFocus = function () { + clearTimeout(closingOnBlur); + }); + } + + var startScroll = cm.getScrollInfo(); + cm.on("scroll", this.onScroll = function () { + var curScroll = cm.getScrollInfo(), editor = cm.getWrapperElement().getBoundingClientRect(); + var newTop = top + startScroll.top - curScroll.top; + var point = newTop - (window.pageYOffset || (document.documentElement || document.body).scrollTop); + if (!below) point += hints.offsetHeight; + if (point <= editor.top || point >= editor.bottom) return completion.close(); + hints.style.top = newTop + "px"; + hints.style.left = (left + startScroll.left - curScroll.left) + "px"; + }); + + CodeMirror.on(hints, "dblclick", function (e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + widget.pick(); + } + }); + + CodeMirror.on(hints, "click", function (e) { + var t = getHintElement(hints, e.target || e.srcElement); + if (t && t.hintId != null) { + widget.changeActive(t.hintId); + if (completion.options.completeOnSingleClick) widget.pick(); + } + }); + + CodeMirror.on(hints, "mousedown", function () { + setTimeout(function () { + cm.focus(); + }, 20); + }); + + CodeMirror.signal(data, "select", completions[0], hints.firstChild); + return true; + } + + Widget.prototype = { + close: function () { + if (this.completion.widget != this) return; + this.completion.widget = null; + this.hints.parentNode.removeChild(this.hints); + this.completion.cm.removeKeyMap(this.keyMap); + + var cm = this.completion.cm; + if (this.completion.options.closeOnUnfocus) { + cm.off("blur", this.onBlur); + cm.off("focus", this.onFocus); + } + cm.off("scroll", this.onScroll); + }, + + disable: function () { + this.completion.cm.removeKeyMap(this.keyMap); + var widget = this; + this.keyMap = { + Enter: function () { + widget.picked = true; + } + }; + this.completion.cm.addKeyMap(this.keyMap); + }, + + pick: function () { + this.completion.pick(this.data, this.selectedHint); + }, + + changeActive: function (i, avoidWrap) { + if (i >= this.data.list.length) {i = avoidWrap ? this.data.list.length - 1 : 0;} else if (i < 0) {i = avoidWrap ? 0 : this.data.list.length - 1;} + if (this.selectedHint == i) return; + var node = this.hints.childNodes[this.selectedHint]; + node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); + node = this.hints.childNodes[this.selectedHint = i]; + node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; + if (node.offsetTop < this.hints.scrollTop) {this.hints.scrollTop = node.offsetTop - 3;} else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) {this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;} + CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); + }, + + screenAmount: function () { + return Math.floor(this.hints.clientHeight / this.hints.firstChild.offsetHeight) || 1; + } + }; + + CodeMirror.registerHelper("hint", "auto", function (cm, options) { + var helpers = cm.getHelpers(cm.getCursor(), "hint"), words; + if (helpers.length) { + for (var i = 0; i < helpers.length; i++) { + var cur = helpers[i](cm, options); + if (cur && cur.list.length) return cur; + } + } else if (words = cm.getHelper(cm.getCursor(), "hintWords")) { + if (words) return CodeMirror.hint.fromList(cm, {words: words}); + } else if (CodeMirror.hint.anyword) { + return CodeMirror.hint.anyword(cm, options); + } + }); + + CodeMirror.registerHelper("hint", "fromList", function (cm, options) { + var cur = cm.getCursor(), token = cm.getTokenAt(cur); + var found = []; + for (var i = 0; i < options.words.length; i++) { + var word = options.words[i]; + if (word.slice(0, token.string.length) == token.string) {found.push(word);} + } + + if (found.length) { + return { + list: found, + from: CodeMirror.Pos(cur.line, token.start), + to: CodeMirror.Pos(cur.line, token.end) + }; + } + }); + + CodeMirror.commands.autocomplete = CodeMirror.showHint; + + var defaultOptions = { + hint: CodeMirror.hint.auto, + completeSingle: true, + alignWithWord: true, + closeCharacters: /[\s()\[\]{};:>,]/, + closeOnUnfocus: true, + completeOnSingleClick: true, + container: null, + customKeys: null, + extraKeys: null + }; + + CodeMirror.defineOption("hintOptions", null); +});/** + * 公式编辑控件 + * @class BI.FormulaEditor + * @extends BI.Widget + */ +BI.FormulaEditor = BI.inherit(BI.Single, { + _defaultConfig: function () { + return $.extend(BI.FormulaEditor.superclass._defaultConfig.apply(), { + baseCls: "bi-formula-editor bi-card", + watermark: "", + value: "", + fieldTextValueMap: {}, + showHint: true, + lineHeight: 2 + }); + }, + _init: function () { + BI.FormulaEditor.superclass._init.apply(this, arguments); + var o = this.options, self = this; + this.editor = CodeMirror(this.element[0], { + textWrapping: true, + lineWrapping: true, + lineNumbers: false, + mode: "formula", + // 解决插入字段由括号或其他特殊字符包围时分裂的bug + specialChars: /[\u0000-\u001f\u007f\u00ad\u200c-\u200f\u2028\u2029\ufeff]/ + }); + o.lineHeight === 1 ? this.element.addClass("codemirror-low-line-height") : this.element.addClass("codemirror-high-line-height"); + this.editor.on("change", function (cm, change) { + self._checkWaterMark(); + if (o.showHint) { + CodeMirror.showHint(cm, CodeMirror.formulaHint, {completeSingle: false}); + } + BI.nextTick(function () { + self.fireEvent(BI.FormulaEditor.EVENT_CHANGE); + }); + }); + + this.editor.on("focus", function () { + self._checkWaterMark(); + self.fireEvent(BI.FormulaEditor.EVENT_FOCUS); + }); + + this.editor.on("blur", function () { + self.fireEvent(BI.FormulaEditor.EVENT_BLUR); + }); + + + if (BI.isKey(o.value)) { + self.setValue(o.value); + } + + if (BI.isKey(this.options.watermark)) { + var self = this; + this.watermark = BI.createWidget({ + type: "bi.label", + cls: "bi-water-mark", + text: this.options.watermark, + whiteSpace: "nowrap", + textAlign: "left" + }); + BI.createWidget({ + type: "bi.absolute", + element: self, + items: [{ + el: self.watermark, + left: 0, + top: 0 + }] + }); + + this.watermark.element.bind( + "mousedown", function (e) { + self.insertString(""); + self.editor.focus(); + e.stopEvent(); + } + ); + this.watermark.element.bind("click", function (e) { + self.editor.focus(); + e.stopEvent(); + }); + this.watermark.element.css({ + position: "absolute", + left: 3, + right: 3, + top: 6, + bottom: 0 + }); + } + }, + + _checkWaterMark: function () { + var o = this.options; + if (!this.disabledWaterMark && BI.isEmptyString(this.editor.getValue()) && BI.isKey(o.watermark)) { + this.watermark && this.watermark.visible(); + } else { + this.watermark && this.watermark.invisible(); + } + }, + + disableWaterMark: function () { + this.disabledWaterMark = true; + this._checkWaterMark(); + }, + + focus: function () { + this.editor.focus(); + }, + + /** + * 添加字段 + * @param field + */ + insertField: function (field) { + var from = this.editor.getCursor(); + // 解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 + this.editor.replaceSelection("\u200b" + field + "\u200b"); + var to = this.editor.getCursor(); + this.editor.markText(from, to, {className: "fieldName", atomic: true, startStyle: "start", endStyle: "end"}); + this.editor.replaceSelection(" "); + this.editor.focus(); + }, + + insertFunction: function (fn) { + var from = this.editor.getCursor(); + this.editor.replaceSelection(fn); + var to = this.editor.getCursor(); + this.editor.markText(from, to, {className: "#function", atomic: true}); + this.editor.replaceSelection("() "); + to = this.editor.getCursor(); + to.ch = to.ch - 2; + this.editor.setCursor(to); + this.editor.focus(); + }, + insertOperator: function (op) { + var from = this.editor.getCursor(); + this.editor.replaceSelection(op); + var to = this.editor.getCursor(); + this.editor.markText(from, to, {className: "%operator", atomic: true}); + this.editor.replaceSelection(" "); + this.editor.focus(); + }, + + setFunction: function (v) { + var from = this.editor.getCursor(); + this.editor.replaceSelection(v); + var to = this.editor.getCursor(); + this.editor.markText(from, to, {className: "#function", atomic: true}); + }, + + insertString: function (str) { + this.editor.replaceSelection(str); + this.editor.focus(); + }, + + getFormulaString: function () { + return this.editor.getValue(); + }, + + getUsedFields: function () { + var fieldMap = this.options.fieldTextValueMap; + var fields = []; + this.editor.getValue(true, function (line) { + var value = line.text; + _.forEach(line.markedSpans, function (i, ms) { + switch (i.marker.className) { + case "fieldName": + // 因为插入字段的时候首尾加了不可见字符,所以首尾缩进一个字符 + var dId = fieldMap[value.substr(i.from + 1, i.to - i.from - 2)]; + if (!fields.contains(dId)) { + fields.push(dId); + } + + } + }); + }); return fields; }, @@ -14630,28 +14407,28 @@ $.extend(BI, { BI.delay(function () { toast.element.slideUp(500, function () { toast.destroy(); - }) - }, 5000) - }) + }); + }, 5000); + }); }, _show: function (hasCancel, title, message, callback) { - $mask = $('
').css({ - position: 'absolute', - 'zIndex': BI.zIndex_tip - 2, + $mask = $("
").css({ + position: "absolute", + zIndex: BI.zIndex_tip - 2, top: 0, left: 0, right: 0, bottom: 0, opacity: 0.5 - }).appendTo('body'); - $pop = $('
').css({ - position: 'absolute', - 'zIndex': BI.zIndex_tip - 1, + }).appendTo("body"); + $pop = $("
").css({ + position: "absolute", + zIndex: BI.zIndex_tip - 1, top: 0, left: 0, right: 0, bottom: 0 - }).appendTo('body'); + }).appendTo("body"); var close = function () { messageShow.destroy(); $mask.remove(); @@ -14660,10 +14437,10 @@ $.extend(BI, { if (hasCancel === true) { controlItems.push({ el: { - type: 'bi.button', + type: "bi.button", text: BI.i18nText("BI-Basic_Cancel"), height: 30, - level: 'ignore', + level: "ignore", handler: function () { close(); if (BI.isFunction(callback)) { @@ -14675,7 +14452,7 @@ $.extend(BI, { } controlItems.push({ el: { - type: 'bi.button', + type: "bi.button", text: BI.i18nText("BI-Basic_OK"), height: 30, handler: function () { @@ -14688,31 +14465,31 @@ $.extend(BI, { }); var conf = { element: $pop, - type: 'bi.center_adapt', + type: "bi.center_adapt", items: [ { - type: 'bi.border', - cls: 'bi-message-content bi-card', + type: "bi.border", + cls: "bi-message-content bi-card", items: { - 'north': { + north: { el: { - type: 'bi.border', - cls: 'bi-message-title bi-background', + type: "bi.border", + cls: "bi-message-title bi-background", items: { center: { el: { - type: 'bi.label', + type: "bi.label", text: title || BI.i18nText("BI-Basic_Prompt"), - textAlign: 'left', + textAlign: "left", hgap: 20, height: 50 } }, east: { el: { - type: 'bi.icon_button', - cls: 'bi-message-close close-font', -// height: 50, + type: "bi.icon_button", + cls: "bi-message-close close-font", + // height: 50, handler: function () { close(); } @@ -14723,7 +14500,7 @@ $.extend(BI, { }, height: 50 }, - 'center': { + center: { el: { type: "bi.text", cls: "bi-message-text", @@ -14734,12 +14511,12 @@ $.extend(BI, { text: message } }, - 'south': { + south: { el: { type: "bi.absolute", items: [{ el: { - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", hgap: 5, items: controlItems }, @@ -14780,8 +14557,8 @@ BI.GridView = BI.inherit(BI.Widget, { overflowY: true, overscanColumnCount: 0, overscanRowCount: 0, - rowHeightGetter: BI.emptyFn, //number类型或function类型 - columnWidthGetter: BI.emptyFn, //number类型或function类型 + rowHeightGetter: BI.emptyFn, // number类型或function类型 + columnWidthGetter: BI.emptyFn, // number类型或function类型 // estimatedColumnSize: 100, //columnWidthGetter为function时必设 // estimatedRowSize: 30, //rowHeightGetter为function时必设 scrollLeft: 0, @@ -14838,7 +14615,7 @@ BI.GridView = BI.inherit(BI.Widget, { return { overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount) - } + }; }, _calculateChildrenToRender: function () { @@ -14863,7 +14640,7 @@ BI.GridView = BI.inherit(BI.Widget, { this._renderedRowStartIndex = visibleRowIndices.start; this._renderedRowStopIndex = visibleRowIndices.stop; - var overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex) + var overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex); var overscanRowIndices = this._getOverscanIndices(this.rowCount, overscanRowCount, this._renderedRowStartIndex, this._renderedRowStopIndex); @@ -14872,7 +14649,7 @@ BI.GridView = BI.inherit(BI.Widget, { var rowStartIndex = overscanRowIndices.overscanStartIndex; var rowStopIndex = overscanRowIndices.overscanStopIndex; - //算区间size + // 算区间size var minRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStartIndex); var minColumnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnStartIndex); var maxRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStopIndex); @@ -14881,7 +14658,7 @@ BI.GridView = BI.inherit(BI.Widget, { var left = minColumnDatum.offset + horizontalOffsetAdjustment; var bottom = maxRowDatum.offset + verticalOffsetAdjustment + maxRowDatum.size; var right = maxColumnDatum.offset + horizontalOffsetAdjustment + maxColumnDatum.size; - //如果滚动的区间并没有超出渲染的范围 + // 如果滚动的区间并没有超出渲染的范围 if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { return; } @@ -14945,7 +14722,7 @@ BI.GridView = BI.inherit(BI.Widget, { count++; } } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (self.renderedKeys[i]) { @@ -14964,15 +14741,15 @@ BI.GridView = BI.inherit(BI.Widget, { deleteArray.push(key[2]); }); BI.each(deleteArray, function (i, index) { - //性能优化,不调用destroy方法防止触发destroy事件 + // 性能优化,不调用destroy方法防止触发destroy事件 self.renderedCells[index].el._destroy(); }); var addedItems = []; BI.each(addSet, function (index, key) { - addedItems.push(renderedCells[key[2]]) + addedItems.push(renderedCells[key[2]]); }); this.container.addItems(addedItems); - //拦截父子级关系 + // 拦截父子级关系 this.container._children = renderedWidgets; this.container.attr("items", renderedCells); this.renderedCells = renderedCells; @@ -15014,7 +14791,7 @@ BI.GridView = BI.inherit(BI.Widget, { this._rowSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.rowCount, o.rowHeightGetter, o.estimatedRowSize); this._calculateChildrenToRender(); - //元素未挂载时不能设置scrollTop + // 元素未挂载时不能设置scrollTop try { this.element.scrollTop(o.scrollTop); this.element.scrollLeft(o.scrollLeft); @@ -15045,11 +14822,11 @@ BI.GridView = BI.inherit(BI.Widget, { }, setColumnCount: function (columnCount) { - this.options.columnCount = columnCount + this.options.columnCount = columnCount; }, setRowCount: function (rowCount) { - this.options.rowCount = rowCount + this.options.rowCount = rowCount; }, setOverflowX: function (b) { @@ -15057,7 +14834,7 @@ BI.GridView = BI.inherit(BI.Widget, { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; BI.nextTick(function () { - self.element.css({overflowX: !!b ? "auto" : "hidden"}); + self.element.css({overflowX: b ? "auto" : "hidden"}); }); } }, @@ -15067,7 +14844,7 @@ BI.GridView = BI.inherit(BI.Widget, { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; BI.nextTick(function () { - self.element.css({overflowY: !!b ? "auto" : "hidden"}); + self.element.css({overflowY: b ? "auto" : "hidden"}); }); } }, @@ -15096,7 +14873,7 @@ BI.GridView = BI.inherit(BI.Widget, { this.options.estimatedRowSize = height; }, - //重新计算children + // 重新计算children _reRange: function () { this.renderRange = {}; }, @@ -15125,7 +14902,7 @@ BI.GridView = BI.inherit(BI.Widget, { } }); BI.GridView.EVENT_SCROLL = "EVENT_SCROLL"; -BI.shortcut('bi.grid_view', BI.GridView);/** +BI.shortcut("bi.grid_view", BI.GridView);/** * floatBox弹出层, * @class BI.FloatBox * @extends BI.Widget @@ -15136,7 +14913,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { baseCls: "bi-float-box bi-card", width: 600, height: 500 - }) + }); }, _init: function () { BI.FloatBox.superclass._init.apply(this, arguments); @@ -15162,19 +14939,19 @@ BI.FloatBox = BI.inherit(BI.Widget, { if (ui.position.top < 0) { ui.position.top = 0; } - //BI-12134 没有什么特别好的方法 + // BI-12134 没有什么特别好的方法 BI.Resizers._resize(); } }); this._south = BI.createWidget(); BI.createWidget({ - type: 'bi.border', + type: "bi.border", element: this, items: { - 'north': { + north: { el: { - type: 'bi.border', - cls: 'bi-message-title bi-background', + type: "bi.border", + cls: "bi-message-title bi-background", items: { center: { el: { @@ -15190,8 +14967,8 @@ BI.FloatBox = BI.inherit(BI.Widget, { }, east: { el: { - type: 'bi.icon_button', - cls: 'bi-message-close close-font', + type: "bi.icon_button", + cls: "bi-message-close close-font", height: 50, handler: function () { self.currentSectionProvider.close(); @@ -15203,7 +14980,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { }, height: 50 }, - 'center': { + center: { el: { type: "bi.absolute", items: [{ @@ -15215,7 +14992,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { }] } }, - 'south': { + south: { el: { type: "bi.absolute", items: [{ @@ -15229,7 +15006,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { height: 60 } } - }) + }); }, populate: function (sectionProvider) { @@ -15243,7 +15020,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { sectionProvider.rebuildSouth(this._south); sectionProvider.on(BI.PopoverSection.EVENT_CLOSE, function () { self.close(); - }) + }); }, show: function () { @@ -15286,9 +15063,9 @@ BI.PopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.PopupView.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-popup-view", - maxWidth: 'auto', + maxWidth: "auto", minWidth: 100, - //maxHeight: 200, + // maxHeight: 200, minHeight: 25, lgap: 0, rgap: 0, @@ -15296,16 +15073,16 @@ BI.PopupView = BI.inherit(BI.Widget, { bgap: 0, vgap: 0, hgap: 0, - direction: BI.Direction.Top, //工具栏的方向 - stopEvent: false,//是否停止mousedown、mouseup事件 - stopPropagation: false, //是否停止mousedown、mouseup向上冒泡 + direction: BI.Direction.Top, // 工具栏的方向 + stopEvent: false, // 是否停止mousedown、mouseup事件 + stopPropagation: false, // 是否停止mousedown、mouseup向上冒泡 logic: { dynamic: true }, - tool: false, //自定义工具栏 - tabs: [], //导航栏 - buttons: [], //toolbar栏 + tool: false, // 自定义工具栏 + tabs: [], // 导航栏 + buttons: [], // toolbar栏 el: { type: "bi.button_group", @@ -15316,28 +15093,28 @@ BI.PopupView = BI.inherit(BI.Widget, { type: "bi.vertical" }] } - }) + }); }, _init: function () { BI.PopupView.superclass._init.apply(this, arguments); var self = this, o = this.options; var fn = function (e) { - e.stopPropagation(); - }, stop = function (e) { - e.stopEvent(); - return false; - }; + e.stopPropagation(); + }, stop = function (e) { + e.stopEvent(); + return false; + }; this.element.css({ "z-index": BI.zIndex_popup, "min-width": o.minWidth + "px", "max-width": o.maxWidth + "px" - }).bind({"click": fn}); + }).bind({click: fn}); this.element.bind("mousewheel", fn); - o.stopPropagation && this.element.bind({"mousedown": fn, "mouseup": fn, "mouseover": fn}); - o.stopEvent && this.element.bind({"mousedown": stop, "mouseup": stop, "mouseover": stop}); + o.stopPropagation && this.element.bind({mousedown: fn, mouseup: fn, mouseover: fn}); + o.stopEvent && this.element.bind({mousedown: stop, mouseup: stop, mouseover: stop}); this.tool = this._createTool(); this.tab = this._createTab(); this.view = this._createView(); @@ -15382,7 +15159,7 @@ BI.PopupView = BI.inherit(BI.Widget, { if (false === o.tool) { return; } - return BI.createWidget(o.tool) + return BI.createWidget(o.tool); }, _createTab: function () { @@ -15395,7 +15172,7 @@ BI.PopupView = BI.inherit(BI.Widget, { cls: "list-view-tab", height: 25, items: o.tabs - }) + }); }, _createToolBar: function () { @@ -15413,7 +15190,7 @@ BI.PopupView = BI.inherit(BI.Widget, { shadow: true, isShadowShowingOnSelected: true }) - }) + }); }, getView: function () { @@ -15434,7 +15211,7 @@ BI.PopupView = BI.inherit(BI.Widget, { tabHeight = this.tab ? (this.tab.attr("height") || 25) : 0, toolHeight = ((this.tool && this.tool.attr("height")) || 25) * ((this.tool && this.tool.isVisible()) ? 1 : 0); this.view.resetHeight ? this.view.resetHeight(h - tbHeight - tabHeight - toolHeight - 2) : - this.view.element.css({"max-height": (h - tbHeight - tabHeight - toolHeight - 2) + "px"}) + this.view.element.css({"max-height": (h - tbHeight - tabHeight - toolHeight - 2) + "px"}); }, setValue: function (selectedValues) { @@ -15463,7 +15240,7 @@ BI.SearcherView = BI.inherit(BI.Pane, { tipText: BI.i18nText("BI-No_Select"), chooseType: BI.Selection.Single, - matcher: {//完全匹配的构造器 + matcher: {// 完全匹配的构造器 type: "bi.button_group", behaviors: { redmark: function () { @@ -15487,7 +15264,7 @@ BI.SearcherView = BI.inherit(BI.Pane, { type: "bi.vertical" }] } - }) + }); }, _init: function () { @@ -15622,7 +15399,7 @@ BI.ListView = BI.inherit(BI.Widget, { } }, o.el)], element: this - } + }; }, mounted: function () { @@ -15693,7 +15470,7 @@ BI.ListView = BI.inherit(BI.Widget, { this.restore(); } }); -BI.shortcut('bi.list_view', BI.ListView); +BI.shortcut("bi.list_view", BI.ListView); /** * 表示当前对象 @@ -15741,7 +15518,7 @@ BI.VirtualList = BI.inherit(BI.Widget, { } }], element: this - } + }; }, mounted: function () { @@ -15872,7 +15649,7 @@ BI.VirtualList = BI.inherit(BI.Widget, { this.restore(); } }); -BI.shortcut('bi.virtual_list', BI.VirtualList); +BI.shortcut("bi.virtual_list", BI.VirtualList); /** * 分页控件 @@ -15892,35 +15669,35 @@ BI.Pager = BI.inherit(BI.Widget, { vgap: 0 }], - dynamicShow: true, //是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 - //dynamicShow为false时以下两个有用 - dynamicShowFirstLast: false,//是否动态显示首页、尾页 - dynamicShowPrevNext: false,//是否动态显示上一页、下一页 - pages: false, //总页数 + dynamicShow: true, // 是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 + // dynamicShow为false时以下两个有用 + dynamicShowFirstLast: false, // 是否动态显示首页、尾页 + dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 + pages: false, // 总页数 curr: function () { return 1; - }, //初始化当前页 - groups: 0, //连续显示分页数 - jump: BI.emptyFn, //分页的回调函数 + }, // 初始化当前页 + groups: 0, // 连续显示分页数 + jump: BI.emptyFn, // 分页的回调函数 - first: false, //是否显示首页 - last: false, //是否显示尾页 + first: false, // 是否显示首页 + last: false, // 是否显示尾页 prev: "上一页", next: "下一页", firstPage: 1, - lastPage: function () { //在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: function () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, - hasPrev: BI.emptyFn, //pages不可用时有效 - hasNext: BI.emptyFn //pages不可用时有效 - }) + hasPrev: BI.emptyFn, // pages不可用时有效 + hasNext: BI.emptyFn // pages不可用时有效 + }); }, _init: function () { BI.Pager.superclass._init.apply(this, arguments); var self = this; this.currPage = BI.result(this.options, "curr"); - //翻页太灵敏 + // 翻页太灵敏 // this._lock = false; // this._debouce = BI.debounce(function () { // self._lock = false; @@ -15947,17 +15724,17 @@ BI.Pager = BI.inherit(BI.Widget, { groups > pages && (groups = pages); } - //计算当前组 + // 计算当前组 dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); - //当前页非首页,则输出上一页 + // 当前页非首页,则输出上一页 if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) { if (BI.isKey(prev)) { view.push({ text: prev, value: "prev", disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) - }) + }); } else { view.push(BI.extend({ disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) @@ -15965,7 +15742,7 @@ BI.Pager = BI.inherit(BI.Widget, { } } - //当前组非首组,则输出首页 + // 当前组非首组,则输出首页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { view.push({ text: first, @@ -15981,14 +15758,14 @@ BI.Pager = BI.inherit(BI.Widget, { } } - //输出当前页组 + // 输出当前页组 dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; dict.end = dict.index > 1 ? (function () { var max = curr + (groups - dict.poor - 1); return max > pages ? pages : max; }()) : groups; - if (dict.end - dict.start < groups - 1) { //最后一组状态 + if (dict.end - dict.start < groups - 1) { // 最后一组状态 dict.start = dict.end - groups + 1; } var s = dict.start, e = dict.end; @@ -16002,16 +15779,16 @@ BI.Pager = BI.inherit(BI.Widget, { text: s, value: s, selected: true - }) + }); } else { view.push({ text: s, value: s - }) + }); } } - //总页数大于连续分页数,且当前组最大页小于总页,输出尾页 + // 总页数大于连续分页数,且当前组最大页小于总页,输出尾页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0) { view.push({ @@ -16024,27 +15801,27 @@ BI.Pager = BI.inherit(BI.Widget, { text: last, value: "last", disabled: !(pages > groups && dict.end < pages && groups !== 0) - }) + }); } - //当前页不为尾页时,输出下一页 + // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { if (BI.isKey(next)) { if (pages === false) { - return {text: next, value: "next", disabled: o.hasNext(curr) === false} + return {text: next, value: "next", disabled: o.hasNext(curr) === false}; } return (dict.flow && curr === pages) ? - {text: next, value: "next", disabled: true} + {text: next, value: "next", disabled: true} : - {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; - } else { - return BI.extend({ - disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) - }, next); + {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; } + return BI.extend({ + disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) + }, next); + }())); } @@ -16178,7 +15955,7 @@ BI.A = BI.inherit(BI.Text, { target: "_blank", el: null, element: "" - }) + }); }, _init: function () { var o = this.options; @@ -16198,15 +15975,15 @@ BI.shortcut("bi.a", BI.A);/** * @type {*|void|Object} */ BI.LoadingBar = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.LoadingBar.superclass._defaultConfig.apply(this, arguments); return BI.extend( conf, { - baseCls : (conf.baseCls ||"")+' bi-loading-bar bi-tips', + baseCls: (conf.baseCls || "") + " bi-loading-bar bi-tips", height: 30, handler: BI.emptyFn - }) + }); }, - _init : function() { + _init: function () { BI.LoadingBar.superclass._init.apply(this, arguments); var self = this; this.loaded = BI.createWidget({ @@ -16215,25 +15992,25 @@ BI.LoadingBar = BI.inherit(BI.Single, { text: BI.i18nText("BI-Load_More"), width: 120, handler: this.options.handler - }) - this.loaded.on(BI.Controller.EVENT_CHANGE, function(type){ + }); + this.loaded.on(BI.Controller.EVENT_CHANGE, function (type) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); this.loading = BI.createWidget({ type: "bi.layout", width: this.options.height, - height:this.options.height, + height: this.options.height, cls: "loading-background cursor-default" - }) + }); var loaded = BI.createWidget({ type: "bi.center_adapt", items: [this.loaded] - }) + }); var loading = BI.createWidget({ type: "bi.center_adapt", items: [this.loading] - }) + }); this.cardLayout = BI.createWidget({ type: "bi.card", element: this, @@ -16244,28 +16021,28 @@ BI.LoadingBar = BI.inherit(BI.Single, { el: loading, cardName: "loading" }] - }) + }); this.invisible(); }, - _reset: function(){ + _reset: function () { this.visible(); this.loaded.setText(BI.i18nText("BI-Load_More")); this.loaded.enable(); }, - setLoaded: function(){ + setLoaded: function () { this._reset(); this.cardLayout.showCardByName("loaded"); }, - setEnd: function(){ + setEnd: function () { this.setLoaded(); this.loaded.setText(BI.i18nText("BI-No_More_Data")); this.loaded.disable(); }, - setLoading: function(){ + setLoading: function () { this._reset(); this.cardLayout.showCardByName("loading"); } @@ -16283,17 +16060,17 @@ BI.IconButton = BI.inherit(BI.BasicButton, { baseCls: (conf.baseCls || "") + " bi-icon-button horizon-center", iconWidth: null, iconHeight: null - }) + }); }, _init: function () { BI.IconButton.superclass._init.apply(this, arguments); var o = this.options; this.element.css({ - textAlign: 'center' + textAlign: "center" }); this.icon = BI.createWidget({ - type: 'bi.icon', + type: "bi.icon", width: o.iconWidth, height: o.iconHeight }); @@ -16303,11 +16080,11 @@ BI.IconButton = BI.inherit(BI.BasicButton, { type: "bi.default", element: this, items: [this.icon] - }) + }); } else { BI.createWidget({ element: this, - type: 'bi.center_adapt', + type: "bi.center_adapt", items: [this.icon] }); } @@ -16336,7 +16113,7 @@ BI.ImageButton = BI.inherit(BI.BasicButton, { src: "", iconWidth: "100%", iconHeight: "100%" - }) + }); }, _init: function () { @@ -16353,14 +16130,14 @@ BI.ImageButton = BI.inherit(BI.BasicButton, { type: "bi.center_adapt", element: this, items: [this.image] - }) + }); } else { BI.createWidget({ type: "bi.adaptive", element: this, items: [this.image], scrollable: false - }) + }); } }, @@ -16422,15 +16199,15 @@ BI.shortcut("bi.image_button", BI.ImageButton);(function ($) { _defaultConfig: function (props) { var conf = BI.Button.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { - baseCls: (conf.baseCls || "") + ' bi-button', + baseCls: (conf.baseCls || "") + " bi-button", minWidth: (props.block === true || props.clear === true) ? 0 : 90, shadow: props.clear !== true, isShadowShowingOnSelected: true, readonly: true, iconClass: "", - level: 'common', - block: false, //是否块状显示,即不显示边框,没有最小宽度的限制 - clear: false, //是否去掉边框和背景 + level: "common", + block: false, // 是否块状显示,即不显示边框,没有最小宽度的限制 + clear: false, // 是否去掉边框和背景 textAlign: "center", whiteSpace: "nowrap", forceCenter: false, @@ -16442,7 +16219,7 @@ BI.shortcut("bi.image_button", BI.ImageButton);(function ($) { bgap: 0, lgap: 0, rgap: 0 - }) + }); }, _init: function () { @@ -16477,7 +16254,7 @@ BI.shortcut("bi.image_button", BI.ImageButton);(function ($) { type: "bi.horizontal", items: [this.icon, this.text] }] - }) + }); } else { this.text = BI.createWidget({ type: "bi.label", @@ -16548,7 +16325,7 @@ BI.shortcut("bi.image_button", BI.ImageButton);(function ($) { BI.Button.superclass.destroy.apply(this, arguments); } }); - BI.shortcut('bi.button', BI.Button); + BI.shortcut("bi.button", BI.Button); BI.Button.EVENT_CHANGE = "EVENT_CHANGE"; })(jQuery);/** * guy @@ -16572,7 +16349,7 @@ BI.TextButton = BI.inherit(BI.BasicButton, { rgap: 0, text: "", py: "" - }) + }); }, _init: function () { @@ -16667,7 +16444,7 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconIconTextItem.superclass._init.apply(this, arguments); @@ -16676,7 +16453,7 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { type: "bi.layout", width: o.blankWidth, height: o.height - }) + }); this.text = BI.createWidget({ type: "bi.label", cls: "list-item-text", @@ -16789,7 +16566,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconTextIconItem.superclass._init.apply(this, arguments); @@ -16805,7 +16582,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); var icon1 = BI.createWidget({ type: "bi.center_adapt", @@ -16819,7 +16596,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { height: o.iconHeight } }] - }) + }); BI.createWidget({ type: "bi.absolute", element: this, @@ -16841,7 +16618,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { bottom: 0, right: 0 }] - }) + }); BI.createWidget(BI.extend({ element: this @@ -16925,7 +16702,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconTextItem.superclass._init.apply(this, arguments); @@ -16933,7 +16710,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { var blank = BI.createWidget({ type: "bi.layout", width: o.blankWidth - }) + }); this.text = BI.createWidget({ type: "bi.label", cls: "list-item-text", @@ -16946,7 +16723,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); this.icon = BI.createWidget({ type: "bi.center_adapt", width: c.commonWidth, @@ -17037,7 +16814,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextIconItem.superclass._init.apply(this, arguments); @@ -17053,7 +16830,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); var icon1 = BI.createWidget({ type: "bi.center_adapt", @@ -17067,11 +16844,11 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { height: o.iconHeight } }] - }) + }); var blank = BI.createWidget({ type: "bi.layout", width: c.commonWidth - }) + }); BI.createWidget({ type: "bi.absolute", element: this, @@ -17092,7 +16869,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { bottom: 0, right: 0 }] - }) + }); BI.createWidget(BI.extend({ element: this @@ -17169,7 +16946,7 @@ BI.IconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextItem.superclass._init.apply(this, arguments); @@ -17276,7 +17053,7 @@ BI.TextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextIconItem.superclass._init.apply(this, arguments); @@ -17376,7 +17153,7 @@ BI.TextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextItem.superclass._init.apply(this, arguments); @@ -17467,7 +17244,7 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextIconNode.superclass._init.apply(this, arguments); @@ -17483,7 +17260,7 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); var icon1 = BI.createWidget({ type: "bi.center_adapt", @@ -17497,12 +17274,12 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { height: o.iconHeight } }] - }) + }); var blank = BI.createWidget({ type: "bi.layout", width: c.commonWidth, height: o.height - }) + }); BI.createWidget({ type: "bi.absolute", element: this, @@ -17523,7 +17300,7 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { bottom: 0, right: 0 }] - }) + }); BI.createWidget(BI.extend({ element: this @@ -17591,7 +17368,7 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextNode.superclass._init.apply(this, arguments); @@ -17608,7 +17385,7 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); this.icon = BI.createWidget({ type: "bi.center_adapt", width: c.commonWidth, @@ -17620,7 +17397,7 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { height: o.iconHeight } }] - }) + }); BI.createWidget(BI.extend({ element: this @@ -17687,7 +17464,7 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextIconNode.superclass._init.apply(this, arguments); @@ -17704,7 +17481,7 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); this.icon = BI.createWidget({ type: "bi.center_adapt", width: c.commonWidth, @@ -17778,7 +17555,7 @@ BI.TextNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextNode.superclass._init.apply(this, arguments); @@ -17844,12 +17621,12 @@ BI.shortcut("bi.text_node", BI.TextNode);/** BI.CodeEditor = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-code-editor', - value: '', + baseCls: "bi-code-editor", + value: "", watermark: "", lineHeight: 2, readOnly: false, - //参数显示值构造函数 + // 参数显示值构造函数 paramFormatter: function (v) { return v; } @@ -17863,13 +17640,13 @@ BI.CodeEditor = BI.inherit(BI.Single, { lineWrapping: true, lineNumbers: false, readOnly: o.readOnly, - //解决插入字段由括号或其他特殊字符包围时分裂的bug + // 解决插入字段由括号或其他特殊字符包围时分裂的bug specialChars: /[\u0000-\u001f\u007f\u00ad\u200c-\u200f\u2028\u2029\ufeff]/ }); o.lineHeight === 1 ? this.element.addClass("codemirror-low-line-height") : this.element.addClass("codemirror-high-line-height"); this.editor.on("change", function (cm, change) { BI.nextTick(function () { - self.fireEvent(BI.CodeEditor.EVENT_CHANGE) + self.fireEvent(BI.CodeEditor.EVENT_CHANGE); }); }); @@ -17895,7 +17672,7 @@ BI.CodeEditor = BI.inherit(BI.Single, { // self.editor.execCommand("goLineEnd"); // }); - //水印 + // 水印 this.watermark = BI.createWidget({ type: "bi.label", text: o.watermark, @@ -17933,7 +17710,7 @@ BI.CodeEditor = BI.inherit(BI.Single, { _setEnable: function (b) { BI.CodeEditor.superclass._setEnable.apply(this, arguments); - this.editor.setOption("readOnly", b === true ? false : "nocursor") + this.editor.setOption("readOnly", b === true ? false : "nocursor"); }, _checkWaterMark: function () { @@ -17949,12 +17726,12 @@ BI.CodeEditor = BI.inherit(BI.Single, { var value = param; param = this.options.paramFormatter(param); var from = this.editor.getCursor(); - //解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 - this.editor.replaceSelection('\u200b' + param + '\u200b'); + // 解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 + this.editor.replaceSelection("\u200b" + param + "\u200b"); var to = this.editor.getCursor(); - var options = {className: 'param', atomic: true}; + var options = {className: "param", atomic: true}; if (BI.isNotNull(param.match(/^$/))) { - options.className = 'error-param'; + options.className = "error-param"; } options.value = value; this.editor.markText(from, to, options); @@ -17971,16 +17748,16 @@ BI.CodeEditor = BI.inherit(BI.Single, { return this.editor.getValue("\n", function (line) { var rawText = line.text, value = line.text, num = 0; value.text = rawText; - //根据插入位置不同,line.markedSpan可能是乱序的 + // 根据插入位置不同,line.markedSpan可能是乱序的 _.forEach(_.sortBy(line.markedSpans, "from"), function (i, ms) { switch (i.marker.className) { case "param": case "error-param": var fieldNameLength = i.to - i.from; value = value.substr(0, i.from + num) + "$\{" + i.marker.value + "\}" + value.substr(i.to + num, value.length); - //加上${}的偏移 + // 加上${}的偏移 num += 3; - //加上实际值和显示值的长度差的偏移 + // 加上实际值和显示值的长度差的偏移 num += (i.marker.value.length - fieldNameLength); break; } @@ -18054,7 +17831,7 @@ BI.Editor = BI.inherit(BI.Single, { rgap: 0, tgap: 0, bgap: 0, - //title,warningTitle这两个属性没用 + // title,warningTitle这两个属性没用 tipType: "warning", inputType: "text", validationChecker: BI.emptyFn, @@ -18062,7 +17839,7 @@ BI.Editor = BI.inherit(BI.Single, { allowBlank: false, watermark: "", errorText: "" - }) + }); }, _init: function () { @@ -18078,12 +17855,12 @@ BI.Editor = BI.inherit(BI.Single, { allowBlank: o.allowBlank })); this.editor.element.css({ - "width": "100%", - "height": "100%", - "border": "none", - "outline": "none", - "padding": "0", - "margin": "0" + width: "100%", + height: "100%", + border: "none", + outline: "none", + padding: "0", + margin: "0" }); if (BI.isKey(this.options.watermark)) { this.watermark = BI.createWidget({ @@ -18371,10 +18148,10 @@ BI.MultifileEditor = BI.inherit(BI.Single, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-multifile-editor", multiple: false, - maxSize: -1,//1024 * 1024 + maxSize: -1, // 1024 * 1024 accept: "", url: "" - }) + }); }, _init: function () { @@ -18454,8 +18231,8 @@ BI.shortcut("bi.multifile_editor", BI.MultifileEditor);/** BI.TextAreaEditor = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.TextAreaEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-textarea-editor bi-card', - value: '' + baseCls: "bi-textarea-editor bi-card", + value: "" }); }, _init: function () { @@ -18468,7 +18245,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { height: "100%", cls: "bi-textarea textarea-editor-content display-block" }); - this.content.element.css({"resize": "none"}); + this.content.element.css({resize: "none"}); BI.createWidget({ type: "bi.absolute", element: this, @@ -18539,7 +18316,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { self.focus(); }); BI.createWidget({ - type: 'bi.absolute', + type: "bi.absolute", element: this, items: [{ el: this.watermark, @@ -18547,7 +18324,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { top: 0, right: 0 }] - }) + }); } else { this.watermark.setText(o.watermark); this.watermark.setValid(!o.invalid); @@ -18591,7 +18368,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { this.element.css(style); this.content.element.css(BI.extend({}, style, { color: style.color || BI.DOM.getContrastColor(BI.DOM.isRGBColor(style.backgroundColor) ? BI.DOM.rgb2hex(style.backgroundColor) : style.backgroundColor) - })) + })); }, getStyle: function () { @@ -18618,7 +18395,7 @@ BI.Icon = BI.inherit(BI.Single, { return BI.extend(conf, { tagName: "i", baseCls: (conf.baseCls || "") + " x-icon b-font horizon-center display-block" - }) + }); }, _init: function () { BI.Icon.superclass._init.apply(this, arguments); @@ -18641,7 +18418,7 @@ BI.Iframe = BI.inherit(BI.Single, { src: "", width: "100%", height: "100%" - }) + }); }, _init: function () { @@ -18669,11 +18446,11 @@ BI.Iframe = BI.inherit(BI.Single, { }, getWidth: function () { - return this.options.width + return this.options.width; }, getHeight: function () { - return this.options.height + return this.options.height; } }); @@ -18693,7 +18470,7 @@ BI.Img = BI.inherit(BI.Single, { src: "", width: "100%", height: "100%" - }) + }); }, _init: function () { @@ -18719,8 +18496,8 @@ BI.shortcut("bi.img", BI.Img); * @type {*|void|Object} */ BI.Checkbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.Checkbox.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.Checkbox.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-checkbox check-box-icon", selected: false, @@ -18729,16 +18506,16 @@ BI.Checkbox = BI.inherit(BI.IconButton, { height: 16, iconWidth: 16, iconHeight: 16 - }) + }); }, - _init : function() { + _init: function () { BI.Checkbox.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.Checkbox.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.Checkbox.EVENT_CHANGE); } } @@ -19372,9 +19149,9 @@ BI.Input = BI.inherit(BI.Single, { baseCls: (conf.baseCls || "") + " bi-input display-block", element: "", validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn,//按确定键能否退出编辑 + quitChecker: BI.emptyFn, // 按确定键能否退出编辑 allowBlank: false - }) + }); }, _init: function () { @@ -19401,8 +19178,8 @@ BI.Input = BI.inherit(BI.Single, { } }) .on("input propertychange", function (e) { - //这个事件在input的属性发生改变的时候就会触发(class的变化也算) - if(BI.isNotNull(e.keyCode)){ + // 这个事件在input的属性发生改变的时候就会触发(class的变化也算) + if(BI.isNotNull(e.keyCode)) { inputEventValid = true; self._keydown_ = true; _keydown(e.keyCode); @@ -19438,7 +19215,7 @@ BI.Input = BI.inherit(BI.Single, { } else { blur(); } - function blur() { + function blur () { if (!self.isValid() && self.options.quitChecker.apply(self, [BI.trim(self.getValue())]) !== false) { self.element.val(self._lastValidValue ? self._lastValidValue : ""); self._checkValidationOnValueChange(); @@ -19480,7 +19257,7 @@ BI.Input = BI.inherit(BI.Single, { this.fireEvent(BI.Input.EVENT_START); } } - if (ctrlKey === true && keyCode === 86) {//ctrlKey+V + if (ctrlKey === true && keyCode === 86) {// ctrlKey+V this._valueChange(); } else { if (keyCode == BI.KeyCode.ENTER) { @@ -19518,7 +19295,7 @@ BI.Input = BI.inherit(BI.Single, { } }, - //初始状态 + // 初始状态 _defaultState: function () { if (this.getValue() == "") { this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); @@ -19650,8 +19427,8 @@ BI.shortcut("bi.input", BI.Input);/** * @type {*|void|Object} */ BI.Radio = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.Radio.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.Radio.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-radio radio-icon", selected: false, @@ -19660,16 +19437,16 @@ BI.Radio = BI.inherit(BI.IconButton, { height: 16, iconWidth: 16, iconHeight: 16 - }) + }); }, - _init : function() { + _init: function () { BI.Radio.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.Radio.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.Radio.EVENT_CHANGE); } } @@ -19686,8 +19463,8 @@ BI.Label = BI.inherit(BI.Single, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-label", textAlign: "center", - whiteSpace: "nowrap", //normal or nowrap - forceCenter: false, //是否无论如何都要居中, 不考虑超出边界的情况, 在未知宽度和高度时有效 + whiteSpace: "nowrap", // normal or nowrap + forceCenter: false, // 是否无论如何都要居中, 不考虑超出边界的情况, 在未知宽度和高度时有效 textWidth: null, textHeight: null, hgap: 0, @@ -19699,7 +19476,7 @@ BI.Label = BI.inherit(BI.Single, { text: "", py: "", keyword: "" - }) + }); }, _createJson: function () { @@ -19904,7 +19681,7 @@ BI.Label = BI.inherit(BI.Single, { type: "bi.layout", element: this.text, scrollable: o.whiteSpace === "normal" - }) + }); }, _createNotCenterEl: function () { @@ -20022,7 +19799,7 @@ BI.Label = BI.inherit(BI.Single, { return; } if (o.whiteSpace == "normal") { - this.text = BI.createWidget(json) + this.text = BI.createWidget(json); BI.createWidget({ type: "bi.vertical_adapt", scrollable: o.whiteSpace === "normal", @@ -20102,7 +19879,7 @@ BI.Label = BI.inherit(BI.Single, { type: "bi.layout", element: this.text, scrollable: o.whiteSpace === "normal" - }) + }); }, doRedMark: function () { @@ -20131,7 +19908,7 @@ BI.Label = BI.inherit(BI.Single, { }, setStyle: function (css) { - this.text.setStyle(css) + this.text.setStyle(css); }, setValue: function (v) { @@ -20152,19 +19929,19 @@ BI.shortcut("bi.label", BI.Label);/** * @extends BI.Text */ BI.Link = BI.inherit(BI.Label, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Link.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-link", href: "", target: "_blank" - }) + }); }, - _createJson: function(){ + _createJson: function () { var o = this.options; return { - type:"bi.a", + type: "bi.a", textAlign: o.textAlign, whiteSpace: o.whiteSpace, lineHeight: o.textHeight, @@ -20177,7 +19954,7 @@ BI.Link = BI.inherit(BI.Label, { }; }, - _init : function() { + _init: function () { BI.Link.superclass._init.apply(this, arguments); } }); @@ -20190,30 +19967,30 @@ BI.shortcut("bi.link", BI.Link);/** * @type {*|void|Object} */ BI.Bubble = BI.inherit(BI.Tip, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend(BI.Bubble.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-bubble", direction: "top", text: "", height: 35 - }) + }); }, - _init : function() { + _init: function () { BI.Bubble.superclass._init.apply(this, arguments); var fn = function (e) { e.stopPropagation(); e.stopEvent(); return false; }; - this.element.bind({"click": fn, "mousedown": fn, "mouseup": fn, "mouseover": fn, "mouseenter": fn, "mouseleave": fn, "mousemove": fn}); + this.element.bind({click: fn, mousedown: fn, mouseup: fn, mouseover: fn, mouseenter: fn, mouseleave: fn, mousemove: fn}); BI.createWidget({ type: "bi.left", element: this, items: [this["_" + this.options.direction]()] - }) + }); }, - _createBubbleText: function(){ + _createBubbleText: function () { return (this.text = BI.createWidget({ type: "bi.label", cls: "bubble-text", @@ -20223,7 +20000,7 @@ BI.Bubble = BI.inherit(BI.Tip, { })); }, - _top: function(){ + _top: function () { return BI.createWidget({ type: "bi.vertical", items: [{ @@ -20235,10 +20012,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, height: 3 }] - }) + }); }, - _bottom: function(){ + _bottom: function () { return BI.createWidget({ type: "bi.vertical", items: [{ @@ -20250,10 +20027,10 @@ BI.Bubble = BI.inherit(BI.Tip, { el: this._createBubbleText(), height: 30 }] - }) + }); }, - _left: function(){ + _left: function () { return BI.createWidget({ type: "bi.right", items: [{ @@ -20265,10 +20042,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, { el: this._createBubbleText() }] - }) + }); }, - _right: function(){ + _right: function () { return BI.createWidget({ type: "bi.left", items: [{ @@ -20280,10 +20057,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, { el: this._createBubbleText() }] - }) + }); }, - setText: function(text){ + setText: function (text) { this.text.setText(text); } }); @@ -20305,23 +20082,23 @@ BI.Toast = BI.inherit(BI.Tip, { return BI.extend(BI.Toast.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-toast", text: "", - level: "success",//success或warning + level: "success", // success或warning height: 30 - }) + }); }, _init: function () { BI.Toast.superclass._init.apply(this, arguments); var o = this.options; this.element.css({ minWidth: this._const.minWidth + "px" - }) + }); this.element.addClass("toast-" + o.level); var fn = function (e) { e.stopPropagation(); e.stopEvent(); return false; }; - this.element.bind({"click": fn, "mousedown": fn, "mouseup": fn, "mouseover": fn, "mouseenter": fn, "mouseleave": fn, "mousemove": fn}); + this.element.bind({click: fn, mousedown: fn, mouseup: fn, mouseover: fn, mouseenter: fn, mouseleave: fn, mousemove: fn}); this.text = BI.createWidget({ type: "bi.label", @@ -20329,10 +20106,10 @@ BI.Toast = BI.inherit(BI.Tip, { text: o.text, height: 30, hgap: this._const.hgap - }) + }); }, - setWidth: function(width){ + setWidth: function (width) { this.element.width(width); }, @@ -20357,11 +20134,11 @@ BI.Tooltip = BI.inherit(BI.Tip, { return BI.extend(BI.Tooltip.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-tooltip", text: "", - level: "success",//success或warning + level: "success", // success或warning stopEvent: false, stopPropagation: false, height: 20 - }) + }); }, _init: function () { BI.Tooltip.superclass._init.apply(this, arguments); @@ -20372,13 +20149,13 @@ BI.Tooltip = BI.inherit(BI.Tip, { o.stopEvent && e.stopEvent(); }; this.element.bind({ - "click": fn, - "mousedown": fn, - "mouseup": fn, - "mouseover": fn, - "mouseenter": fn, - "mouseleave": fn, - "mousemove": fn + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn }); var texts = (o.text + "").split("\n"); @@ -20394,9 +20171,9 @@ BI.Tooltip = BI.inherit(BI.Tip, { whiteSpace: "normal", text: text, textHeight: 16 - } + }; }) - }) + }); } else { this.text = BI.createWidget({ type: "bi.label", @@ -20431,622 +20208,604 @@ BI.shortcut("bi.tooltip", BI.Tooltip);/** * @abstract */ BI.Trigger = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Trigger.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-trigger cursor-pointer", height: 24 - }) + }); }, - _init : function() { + _init: function () { BI.Trigger.superclass._init.apply(this, arguments); }, - setKey: function(){ + setKey: function () { }, - getKey: function(){ + getKey: function () { } });// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE -(function(mod) { - mod(CodeMirror); -})(function(CodeMirror) { - - var tables; - var defaultTable; - var keywords; - var identifierQuote; - var CONS = { - QUERY_DIV: ";", - ALIAS_KEYWORD: "AS" - }; - var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos; - - function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" } - - function getKeywords(editor) { - var mode = editor.doc.modeOption; - if (mode === "sql") mode = "text/x-sql"; - return CodeMirror.resolveMode(mode).keywords; - } - - function getIdentifierQuote(editor) { - var mode = editor.doc.modeOption; - if (mode === "sql") mode = "text/x-sql"; - return CodeMirror.resolveMode(mode).identifierQuote || "`"; - } - - function getText(item) { - return typeof item == "string" ? item : item.text; - } - - function wrapTable(name, value) { - if (isArray(value)) value = {columns: value} - if (!value.text) value.text = name - return value - } - - function parseTables(input) { - var result = {} - if (isArray(input)) { - for (var i = input.length - 1; i >= 0; i--) { - var item = input[i] - result[getText(item).toUpperCase()] = wrapTable(getText(item), item) - } - } else if (input) { - for (var name in input) - result[name.toUpperCase()] = wrapTable(name, input[name]) - } - return result - } - - function getTable(name) { - return tables[name.toUpperCase()] - } - - function shallowClone(object) { - var result = {}; - for (var key in object) if (object.hasOwnProperty(key)) - result[key] = object[key]; - return result; - } - - function match(string, word) { - if (BI.isNotEmptyString(string) && word.length !== string.length) { - var len = string.length; - var sub = getText(word).substr(0, len); - return string.toUpperCase() === sub.toUpperCase(); - } - } - - function addMatches(result, search, wordlist, formatter) { - if (isArray(wordlist)) { - for (var i = 0; i < wordlist.length; i++) - if (match(search, wordlist[i])) result.push(formatter(wordlist[i], i)); - } else { - for (var word in wordlist) if (wordlist.hasOwnProperty(word)) { - var val = wordlist[word] - if (!val || val === true) - val = word - else - val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text - if (match(search, val)) result.push(formatter(val)) - } - } - } - - function cleanName(name) { +(function (mod) { + mod(CodeMirror); +})(function (CodeMirror) { + + var tables; + var defaultTable; + var keywords; + var identifierQuote; + var CONS = { + QUERY_DIV: ";", + ALIAS_KEYWORD: "AS" + }; + var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos; + + function isArray (val) { return Object.prototype.toString.call(val) == "[object Array]"; } + + function getKeywords (editor) { + var mode = editor.doc.modeOption; + if (mode === "sql") mode = "text/x-sql"; + return CodeMirror.resolveMode(mode).keywords; + } + + function getIdentifierQuote (editor) { + var mode = editor.doc.modeOption; + if (mode === "sql") mode = "text/x-sql"; + return CodeMirror.resolveMode(mode).identifierQuote || "`"; + } + + function getText (item) { + return typeof item === "string" ? item : item.text; + } + + function wrapTable (name, value) { + if (isArray(value)) value = {columns: value}; + if (!value.text) value.text = name; + return value; + } + + function parseTables (input) { + var result = {}; + if (isArray(input)) { + for (var i = input.length - 1; i >= 0; i--) { + var item = input[i]; + result[getText(item).toUpperCase()] = wrapTable(getText(item), item); + } + } else if (input) { + for (var name in input) {result[name.toUpperCase()] = wrapTable(name, input[name]);} + } + return result; + } + + function getTable (name) { + return tables[name.toUpperCase()]; + } + + function shallowClone (object) { + var result = {}; + for (var key in object) { + if (object.hasOwnProperty(key)) {result[key] = object[key];} + } + return result; + } + + function match (string, word) { + if (BI.isNotEmptyString(string) && word.length !== string.length) { + var len = string.length; + var sub = getText(word).substr(0, len); + return string.toUpperCase() === sub.toUpperCase(); + } + } + + function addMatches (result, search, wordlist, formatter) { + if (isArray(wordlist)) { + for (var i = 0; i < wordlist.length; i++) {if (match(search, wordlist[i])) result.push(formatter(wordlist[i], i));} + } else { + for (var word in wordlist) { + if (wordlist.hasOwnProperty(word)) { + var val = wordlist[word]; + if (!val || val === true) {val = word;} else {val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text;} + if (match(search, val)) result.push(formatter(val)); + } + } + } + } + + function cleanName (name) { // Get rid name from identifierQuote and preceding dot(.) - if (name.charAt(0) == ".") { - name = name.substr(1); - } - // replace doublicated identifierQuotes with single identifierQuotes - // and remove single identifierQuotes - var nameParts = name.split(identifierQuote+identifierQuote); - for (var i = 0; i < nameParts.length; i++) - nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote,"g"), ""); - return nameParts.join(identifierQuote); - } - - function insertIdentifierQuotes(name) { - var nameParts = getText(name).split("."); - for (var i = 0; i < nameParts.length; i++) - nameParts[i] = identifierQuote + + if (name.charAt(0) == ".") { + name = name.substr(1); + } + // replace doublicated identifierQuotes with single identifierQuotes + // and remove single identifierQuotes + var nameParts = name.split(identifierQuote + identifierQuote); + for (var i = 0; i < nameParts.length; i++) {nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote, "g"), "");} + return nameParts.join(identifierQuote); + } + + function insertIdentifierQuotes (name) { + var nameParts = getText(name).split("."); + for (var i = 0; i < nameParts.length; i++) { + nameParts[i] = identifierQuote + // doublicate identifierQuotes - nameParts[i].replace(new RegExp(identifierQuote,"g"), identifierQuote+identifierQuote) + + nameParts[i].replace(new RegExp(identifierQuote, "g"), identifierQuote + identifierQuote) + identifierQuote; - var escaped = nameParts.join("."); - if (typeof name == "string") return escaped; - name = shallowClone(name); - name.text = escaped; - return name; - } - - function nameCompletion(cur, token, result, editor) { + } + var escaped = nameParts.join("."); + if (typeof name === "string") return escaped; + name = shallowClone(name); + name.text = escaped; + return name; + } + + function nameCompletion (cur, token, result, editor) { // Try to complete table, column names and return start position of completion - var useIdentifierQuotes = false; - var nameParts = []; - var start = token.start; - var cont = true; - while (cont) { - cont = (token.string.charAt(0) == "."); - useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote); - - start = token.start; - nameParts.unshift(cleanName(token.string)); - - token = editor.getTokenAt(Pos(cur.line, token.start)); - if (token.string == ".") { - cont = true; - token = editor.getTokenAt(Pos(cur.line, token.start)); - } - } - - // Try to complete table names - var string = nameParts.join("."); - addMatches(result, string, tables, function(w) { - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); + var useIdentifierQuotes = false; + var nameParts = []; + var start = token.start; + var cont = true; + while (cont) { + cont = (token.string.charAt(0) == "."); + useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote); - // Try to complete columns from defaultTable - addMatches(result, string, defaultTable, function(w) { - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); + start = token.start; + nameParts.unshift(cleanName(token.string)); - // Try to complete columns - string = nameParts.pop(); - var table = nameParts.join("."); - - var alias = false; - var aliasTable = table; - // Check if table is available. If not, find table by Alias - if (!getTable(table)) { - var oldTable = table; - table = findTableByAlias(table, editor); - if (table !== oldTable) alias = true; - } - - var columns = getTable(table); - if (columns && columns.columns) - columns = columns.columns; - - if (columns) { - addMatches(result, string, columns, function(w) { - var tableInsert = table; - if (alias == true) tableInsert = aliasTable; - if (typeof w == "string") { - w = tableInsert + "." + w; - } else { - w = shallowClone(w); - w.text = tableInsert + "." + w.text; - } - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); - } - - return start; - } - - function eachWord(lineText, f) { - var words = lineText.split(/\s+/) - for (var i = 0; i < words.length; i++) - if (words[i]) f(words[i].replace(/[,;]/g, '')) - } - - function findTableByAlias(alias, editor) { - var doc = editor.doc; - var fullQuery = doc.getValue(); - var aliasUpperCase = alias.toUpperCase(); - var previousWord = ""; - var table = ""; - var separator = []; - var validRange = { - start: Pos(0, 0), - end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length) - }; + token = editor.getTokenAt(Pos(cur.line, token.start)); + if (token.string == ".") { + cont = true; + token = editor.getTokenAt(Pos(cur.line, token.start)); + } + } - //add separator - var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV); - while(indexOfSeparator != -1) { - separator.push(doc.posFromIndex(indexOfSeparator)); - indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1); - } - separator.unshift(Pos(0, 0)); - separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length)); - - //find valid range - var prevItem = null; - var current = editor.getCursor() - for (var i = 0; i < separator.length; i++) { - if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) { - validRange = {start: prevItem, end: separator[i]}; - break; - } - prevItem = separator[i]; - } - - var query = doc.getRange(validRange.start, validRange.end, false); - - for (var i = 0; i < query.length; i++) { - var lineText = query[i]; - eachWord(lineText, function(word) { - var wordUpperCase = word.toUpperCase(); - if (wordUpperCase === aliasUpperCase && getTable(previousWord)) - table = previousWord; - if (wordUpperCase !== CONS.ALIAS_KEYWORD) - previousWord = word; - }); - if (table) break; - } - return table; - } - - CodeMirror.registerHelper("hint", "sql", function(editor, options) { - tables = parseTables(options && options.tables) - var defaultTableName = options && options.defaultTable; - var disableKeywords = options && options.disableKeywords; - defaultTable = defaultTableName && getTable(defaultTableName); - keywords = getKeywords(editor); - var keywordsCount = BI.size(keywords); - var functions = []; - var desc = {}; - var cur = editor.getCursor(); - var token = editor.getTokenAt(cur); - BI.each(BI.FormulaCollections, function(idx, formula){ - if(formula.lastIndexOf(token.string, 0) == 0 && !BI.contains(functions, formula)){ - functions.push(formula); - } - }); - BI.each(BI.FormulaJson, function(idx, formula){ - desc[formula.name.toLowerCase()] = formula.def; - }); - keywords = BI.concat(BI.keys(keywords), functions); - identifierQuote = getIdentifierQuote(editor); + // Try to complete table names + var string = nameParts.join("."); + addMatches(result, string, tables, function (w) { + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); - if (defaultTableName && !defaultTable) - defaultTable = findTableByAlias(defaultTableName, editor); + // Try to complete columns from defaultTable + addMatches(result, string, defaultTable, function (w) { + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + + // Try to complete columns + string = nameParts.pop(); + var table = nameParts.join("."); + + var alias = false; + var aliasTable = table; + // Check if table is available. If not, find table by Alias + if (!getTable(table)) { + var oldTable = table; + table = findTableByAlias(table, editor); + if (table !== oldTable) alias = true; + } - defaultTable = defaultTable || []; + var columns = getTable(table); + if (columns && columns.columns) {columns = columns.columns;} - if (defaultTable.columns) - defaultTable = defaultTable.columns; + if (columns) { + addMatches(result, string, columns, function (w) { + var tableInsert = table; + if (alias == true) tableInsert = aliasTable; + if (typeof w === "string") { + w = tableInsert + "." + w; + } else { + w = shallowClone(w); + w.text = tableInsert + "." + w.text; + } + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + } - var result = []; - var start, end, search; - if (token.end > cur.ch) { - token.end = cur.ch; - token.string = token.string.slice(0, cur.ch - token.start); + return start; } - if (token.string.match(/^[.`"\w@]\w*$/)) { - search = token.string; - start = token.start; - end = token.end; - } else { - start = end = cur.ch; - search = ""; + function eachWord (lineText, f) { + var words = lineText.split(/\s+/); + for (var i = 0; i < words.length; i++) {if (words[i]) f(words[i].replace(/[,;]/g, ""));} } - if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) { - start = nameCompletion(cur, token, result, editor); - } else { - addMatches(result, search, tables, function(w) {return w}); - addMatches(result, search, defaultTable, function(w) {return w}); - if (!disableKeywords) - addMatches(result, search, keywords, function(w, i) { - var isKeyword = i < keywordsCount; - return { - isKeyword: isKeyword, - text: w - // description: desc[w] || "SQL关键字", - // className: isKeyword ? "sql-keyword" : "sql-fr-function", - // render: function (Element, self, data) { - // var label = BI.createWidget({ - // type: "bi.label", - // element: Element, - // text: data.displayText || getText(data) - // }); - // label.setTitle(data.description, { - // container: "body" - - // }); - // } - }; - }); + + function findTableByAlias (alias, editor) { + var doc = editor.doc; + var fullQuery = doc.getValue(); + var aliasUpperCase = alias.toUpperCase(); + var previousWord = ""; + var table = ""; + var separator = []; + var validRange = { + start: Pos(0, 0), + end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length) + }; + + // add separator + var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV); + while(indexOfSeparator != -1) { + separator.push(doc.posFromIndex(indexOfSeparator)); + indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator + 1); + } + separator.unshift(Pos(0, 0)); + separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length)); + + // find valid range + var prevItem = null; + var current = editor.getCursor(); + for (var i = 0; i < separator.length; i++) { + if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) { + validRange = {start: prevItem, end: separator[i]}; + break; + } + prevItem = separator[i]; + } + + var query = doc.getRange(validRange.start, validRange.end, false); + + for (var i = 0; i < query.length; i++) { + var lineText = query[i]; + eachWord(lineText, function (word) { + var wordUpperCase = word.toUpperCase(); + if (wordUpperCase === aliasUpperCase && getTable(previousWord)) {table = previousWord;} + if (wordUpperCase !== CONS.ALIAS_KEYWORD) {previousWord = word;} + }); + if (table) break; + } + return table; } - return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)}; - }); + CodeMirror.registerHelper("hint", "sql", function (editor, options) { + tables = parseTables(options && options.tables); + var defaultTableName = options && options.defaultTable; + var disableKeywords = options && options.disableKeywords; + defaultTable = defaultTableName && getTable(defaultTableName); + keywords = getKeywords(editor); + var keywordsCount = BI.size(keywords); + var functions = []; + var desc = {}; + var cur = editor.getCursor(); + var token = editor.getTokenAt(cur); + BI.each(BI.FormulaCollections, function (idx, formula) { + if(formula.lastIndexOf(token.string, 0) == 0 && !BI.contains(functions, formula)) { + functions.push(formula); + } + }); + BI.each(BI.FormulaJson, function (idx, formula) { + desc[formula.name.toLowerCase()] = formula.def; + }); + keywords = BI.concat(BI.keys(keywords), functions); + identifierQuote = getIdentifierQuote(editor); + + if (defaultTableName && !defaultTable) {defaultTable = findTableByAlias(defaultTableName, editor);} + + defaultTable = defaultTable || []; + + if (defaultTable.columns) {defaultTable = defaultTable.columns;} + + var result = []; + var start, end, search; + if (token.end > cur.ch) { + token.end = cur.ch; + token.string = token.string.slice(0, cur.ch - token.start); + } + + if (token.string.match(/^[.`"\w@]\w*$/)) { + search = token.string; + start = token.start; + end = token.end; + } else { + start = end = cur.ch; + search = ""; + } + if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) { + start = nameCompletion(cur, token, result, editor); + } else { + addMatches(result, search, tables, function (w) {return w;}); + addMatches(result, search, defaultTable, function (w) {return w;}); + if (!disableKeywords) { + addMatches(result, search, keywords, function (w, i) { + var isKeyword = i < keywordsCount; + return { + isKeyword: isKeyword, + text: w + // description: desc[w] || "SQL关键字", + // className: isKeyword ? "sql-keyword" : "sql-fr-function", + // render: function (Element, self, data) { + // var label = BI.createWidget({ + // type: "bi.label", + // element: Element, + // text: data.displayText || getText(data) + // }); + // label.setTitle(data.description, { + // container: "body" + + // }); + // } + }; + }); + } + } + + return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)}; + }); }); // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE -(function(mod) { +(function (mod) { mod(CodeMirror); -})(function(CodeMirror) { +})(function (CodeMirror) { "use strict"; -CodeMirror.defineMode("sql", function(config, parserConfig) { - "use strict"; + CodeMirror.defineMode("sql", function (config, parserConfig) { + "use strict"; - var client = parserConfig.client || {}, - atoms = parserConfig.atoms || {"false": true, "true": true, "null": true}, - builtin = parserConfig.builtin || {}, - keywords = parserConfig.keywords || {}, - operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/, - support = parserConfig.support || {}, - hooks = parserConfig.hooks || {}, - dateSQL = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true}, - functions = parserConfig.functions || {}; + var client = parserConfig.client || {}, + atoms = parserConfig.atoms || {false: true, true: true, null: true}, + builtin = parserConfig.builtin || {}, + keywords = parserConfig.keywords || {}, + operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/, + support = parserConfig.support || {}, + hooks = parserConfig.hooks || {}, + dateSQL = parserConfig.dateSQL || {date: true, time: true, timestamp: true}, + functions = parserConfig.functions || {}; - function tokenBase(stream, state) { - var ch = stream.next(); + function tokenBase (stream, state) { + var ch = stream.next(); - // call hooks from the mime type - if (hooks[ch]) { - var result = hooks[ch](stream, state); - if (result !== false) return result; - } + // call hooks from the mime type + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } - if (support.hexNumber && + if (support.hexNumber && ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) { - // hex - // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html - return "number"; - } else if (support.binaryNumber && + // hex + // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html + return "number"; + } else if (support.binaryNumber && (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) || (ch == "0" && stream.match(/^b[01]+/)))) { - // bitstring - // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html - return "number"; - } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { - // numbers - // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html - stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/); - support.decimallessFloat && stream.match(/^\.(?!\.)/); - return "number"; - } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { - // placeholders - return "variable-3"; - } else if (ch == "'" || (ch == '"' && support.doubleQuote)) { - // strings - // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html - state.tokenize = tokenLiteral(ch); - return state.tokenize(stream, state); - } else if ((((support.nCharCast && (ch == "n" || ch == "N")) + // bitstring + // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html + return "number"; + } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { + // numbers + // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html + stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/); + support.decimallessFloat && stream.match(/^\.(?!\.)/); + return "number"; + } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { + // placeholders + return "variable-3"; + } else if (ch == "'" || (ch == "\"" && support.doubleQuote)) { + // strings + // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html + state.tokenize = tokenLiteral(ch); + return state.tokenize(stream, state); + } else if ((((support.nCharCast && (ch == "n" || ch == "N")) || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) - && (stream.peek() == "'" || stream.peek() == '"'))) { - // charset casting: _utf8'str', N'str', n'str' - // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html - return "keyword"; - } else if (/^[\(\),\;\[\]]/.test(ch)) { - // no highlighting - return null; - } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { - // 1-line comment - stream.skipToEnd(); - return "comment"; - } else if ((support.commentHash && ch == "#") + && (stream.peek() == "'" || stream.peek() == "\""))) { + // charset casting: _utf8'str', N'str', n'str' + // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html + return "keyword"; + } else if (/^[\(\),\;\[\]]/.test(ch)) { + // no highlighting + return null; + } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { + // 1-line comment + stream.skipToEnd(); + return "comment"; + } else if ((support.commentHash && ch == "#") || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) { - // 1-line comments - // ref: https://kb.askmonty.org/en/comment-syntax/ - stream.skipToEnd(); - return "comment"; - } else if (ch == "/" && stream.eat("*")) { - // multi-line comments - // ref: https://kb.askmonty.org/en/comment-syntax/ - state.tokenize = tokenComment(1); - return state.tokenize(stream, state); - } else if (ch == ".") { - // .1 for 0.1 - if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) - return "number"; - if (stream.match(/^\.+/)) - return null - // .table_name (ODBC) - // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html - if (support.ODBCdotTable && stream.match(/^[\w\d_]+/)) - return "variable-2"; - } else if (operatorChars.test(ch)) { - // operators - stream.eatWhile(operatorChars); - return null; - } else if (ch == '{' && + // 1-line comments + // ref: https://kb.askmonty.org/en/comment-syntax/ + stream.skipToEnd(); + return "comment"; + } else if (ch == "/" && stream.eat("*")) { + // multi-line comments + // ref: https://kb.askmonty.org/en/comment-syntax/ + state.tokenize = tokenComment(1); + return state.tokenize(stream, state); + } else if (ch == ".") { + // .1 for 0.1 + if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {return "number";} + if (stream.match(/^\.+/)) {return null;} + // .table_name (ODBC) + // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html + if (support.ODBCdotTable && stream.match(/^[\w\d_]+/)) {return "variable-2";} + } else if (operatorChars.test(ch)) { + // operators + stream.eatWhile(operatorChars); + return null; + } else if (ch == "{" && (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) { - // dates (weird ODBC syntax) - // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html - return "number"; - } else { - stream.eatWhile(/^[_\w\d]/); - var word = stream.current().toLowerCase(); - // dates (standard SQL syntax) - // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html - if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) - return "number"; - if (atoms.hasOwnProperty(word)) return "atom"; - if (builtin.hasOwnProperty(word)) return "builtin"; - if (functions.hasOwnProperty(word) && stream.peek() === '(') return "function"; - if (keywords.hasOwnProperty(word)) return "keyword"; - if (client.hasOwnProperty(word)) return "string-2"; - return null; - } - } - - // 'string', with char specified in quote escaped by '\' - function tokenLiteral(quote) { - return function(stream, state) { - var escaped = false, ch; - while ((ch = stream.next()) != null) { - if (ch == quote && !escaped) { - state.tokenize = tokenBase; - break; - } - escaped = !escaped && ch == "\\"; - } - return "string"; - }; - } - function tokenComment(depth) { - return function(stream, state) { - var m = stream.match(/^.*?(\/\*|\*\/)/) - if (!m) stream.skipToEnd() - else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1) - else if (depth > 1) state.tokenize = tokenComment(depth - 1) - else state.tokenize = tokenBase - return "comment" - } - } - - function pushContext(stream, state, type) { - state.context = { - prev: state.context, - indent: stream.indentation(), - col: stream.column(), - type: type - }; - } + // dates (weird ODBC syntax) + // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html + return "number"; + } else { + stream.eatWhile(/^[_\w\d]/); + var word = stream.current().toLowerCase(); + // dates (standard SQL syntax) + // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html + if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) {return "number";} + if (atoms.hasOwnProperty(word)) return "atom"; + if (builtin.hasOwnProperty(word)) return "builtin"; + if (functions.hasOwnProperty(word) && stream.peek() === "(") return "function"; + if (keywords.hasOwnProperty(word)) return "keyword"; + if (client.hasOwnProperty(word)) return "string-2"; + return null; + } + } + + // 'string', with char specified in quote escaped by '\' + function tokenLiteral (quote) { + return function (stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && ch == "\\"; + } + return "string"; + }; + } + function tokenComment (depth) { + return function (stream, state) { + var m = stream.match(/^.*?(\/\*|\*\/)/); + if (!m) stream.skipToEnd(); + else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1); + else if (depth > 1) state.tokenize = tokenComment(depth - 1); + else state.tokenize = tokenBase; + return "comment"; + }; + } + + function pushContext (stream, state, type) { + state.context = { + prev: state.context, + indent: stream.indentation(), + col: stream.column(), + type: type + }; + } + + function popContext (state) { + state.indent = state.context.indent; + state.context = state.context.prev; + } + + return { + startState: function () { + return {tokenize: tokenBase, context: null}; + }, - function popContext(state) { - state.indent = state.context.indent; - state.context = state.context.prev; - } + token: function (stream, state) { + if (stream.sol()) { + if (state.context && state.context.align == null) {state.context.align = false;} + } + if (state.tokenize == tokenBase && stream.eatSpace()) return null; - return { - startState: function() { - return {tokenize: tokenBase, context: null}; - }, + var style = state.tokenize(stream, state); + if (style == "comment") return style; - token: function(stream, state) { - if (stream.sol()) { - if (state.context && state.context.align == null) - state.context.align = false; - } - if (state.tokenize == tokenBase && stream.eatSpace()) return null; + if (state.context && state.context.align == null) {state.context.align = true;} - var style = state.tokenize(stream, state); - if (style == "comment") return style; + var tok = stream.current(); + if (tok == "(") {pushContext(stream, state, ")");} else if (tok == "[") {pushContext(stream, state, "]");} else if (state.context && state.context.type == tok) {popContext(state);} + return style; + }, - if (state.context && state.context.align == null) - state.context.align = true; + indent: function (state, textAfter) { + var cx = state.context; + if (!cx) return CodeMirror.Pass; + var closing = textAfter.charAt(0) == cx.type; + if (cx.align) return cx.col + (closing ? 0 : 1); + return cx.indent + (closing ? 0 : config.indentUnit); + }, - var tok = stream.current(); - if (tok == "(") - pushContext(stream, state, ")"); - else if (tok == "[") - pushContext(stream, state, "]"); - else if (state.context && state.context.type == tok) - popContext(state); - return style; - }, + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--" + }; + }); - indent: function(state, textAfter) { - var cx = state.context; - if (!cx) return CodeMirror.Pass; - var closing = textAfter.charAt(0) == cx.type; - if (cx.align) return cx.col + (closing ? 0 : 1); - else return cx.indent + (closing ? 0 : config.indentUnit); - }, + (function () { + "use strict"; + + // `identifier` + function hookIdentifier (stream) { + // MySQL/MariaDB identifiers + // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html + var ch; + while ((ch = stream.next()) != null) { + if (ch == "`" && !stream.eat("`")) return "variable-2"; + } + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; + } + + // "identifier" + function hookIdentifierDoublequote (stream) { + // Standard SQL /SQLite identifiers + // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier + // ref: http://sqlite.org/lang_keywords.html + var ch; + while ((ch = stream.next()) != null) { + if (ch == "\"" && !stream.eat("\"")) return "variable-2"; + } + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; + } + + // variable token + function hookVar (stream) { + // variables + // @@prefix.varName @varName + // varName can be quoted with ` or ' or " + // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html + if (stream.eat("@")) { + stream.match(/^session\./); + stream.match(/^local\./); + stream.match(/^global\./); + } + + if (stream.eat("'")) { + stream.match(/^.*'/); + return "variable-2"; + } else if (stream.eat("\"")) { + stream.match(/^.*"/); + return "variable-2"; + } else if (stream.eat("`")) { + stream.match(/^.*`/); + return "variable-2"; + } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { + return "variable-2"; + } + return null; + } - blockCommentStart: "/*", - blockCommentEnd: "*/", - lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--" - }; -}); + // short client keyword token + function hookClient (stream) { + // \N means NULL + // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html + if (stream.eat("N")) { + return "atom"; + } + // \g, etc + // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html + return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; + } + + // these keywords are used by all SQL dialects (however, a mode can still overwrite it) + var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; -(function() { - "use strict"; - - // `identifier` - function hookIdentifier(stream) { - // MySQL/MariaDB identifiers - // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html - var ch; - while ((ch = stream.next()) != null) { - if (ch == "`" && !stream.eat("`")) return "variable-2"; - } - stream.backUp(stream.current().length - 1); - return stream.eatWhile(/\w/) ? "variable-2" : null; - } - - // "identifier" - function hookIdentifierDoublequote(stream) { - // Standard SQL /SQLite identifiers - // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier - // ref: http://sqlite.org/lang_keywords.html - var ch; - while ((ch = stream.next()) != null) { - if (ch == "\"" && !stream.eat("\"")) return "variable-2"; - } - stream.backUp(stream.current().length - 1); - return stream.eatWhile(/\w/) ? "variable-2" : null; - } - - // variable token - function hookVar(stream) { - // variables - // @@prefix.varName @varName - // varName can be quoted with ` or ' or " - // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html - if (stream.eat("@")) { - stream.match(/^session\./); - stream.match(/^local\./); - stream.match(/^global\./); - } - - if (stream.eat("'")) { - stream.match(/^.*'/); - return "variable-2"; - } else if (stream.eat('"')) { - stream.match(/^.*"/); - return "variable-2"; - } else if (stream.eat("`")) { - stream.match(/^.*`/); - return "variable-2"; - } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { - return "variable-2"; - } - return null; - }; - - // short client keyword token - function hookClient(stream) { - // \N means NULL - // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html - if (stream.eat("N")) { - return "atom"; - } - // \g, etc - // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html - return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; - } - - // these keywords are used by all SQL dialects (however, a mode can still overwrite it) - var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; - - // turn a space-separated list into an array - function set(str) { - var obj = {}, words = str.split(" "); - for (var i = 0; i < words.length; ++i) obj[words[i]] = true; - return obj; - } - - // A generic SQL Mode. It's not a standard, it just try to support what is generally supported - CodeMirror.defineMIME("text/x-sql", { - name: "sql", - keywords: set(sqlKeywords + "begin"), - builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"), - atoms: set("false true null unknown"), - operatorChars: /^[*+\-%<>!=]/, - dateSQL: set("date time timestamp"), - support: set("ODBCdotTable doubleQuote binaryNumber hexNumber"), - functions: BI.makeObject(BI.FormulaCollections, true) - }); -}()); + // turn a space-separated list into an array + function set (str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + // A generic SQL Mode. It's not a standard, it just try to support what is generally supported + CodeMirror.defineMIME("text/x-sql", { + name: "sql", + keywords: set(sqlKeywords + "begin"), + builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable doubleQuote binaryNumber hexNumber"), + functions: BI.makeObject(BI.FormulaCollections, true) + }); + }()); }); @@ -21084,8 +20843,8 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { BI.SQLEditor = BI.inherit(BI.Widget, { _defaultConfig: function () { return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-sql-editor', - value: '', + baseCls: "bi-sql-editor", + value: "", lineHeight: 2, showHint: true }); @@ -21109,7 +20868,7 @@ BI.SQLEditor = BI.inherit(BI.Widget, { }); } BI.nextTick(function () { - self.fireEvent(BI.FormulaEditor.EVENT_CHANGE) + self.fireEvent(BI.FormulaEditor.EVENT_CHANGE); }); }); @@ -21122,7 +20881,7 @@ BI.SQLEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.FormulaEditor.EVENT_BLUR); }); - //水印 + // 水印 this.watermark = BI.createWidget({ type: "bi.label", text: BI.i18nText("Please_Enter_SQL"), @@ -21199,7 +20958,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I // └────────────────────────────────────────────────────────────┘ \\ (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("eve", function() { + define("eve", function () { return factory(); }); } else if (typeof exports === "object") { @@ -21207,7 +20966,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } else { glob.eve = factory(); } -}(this, function(){ +}(this, function () { var version = "0.4.2", has = "hasOwnProperty", separator = /[\.\/]/, @@ -21219,7 +20978,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I current_event, stop, events = {n: {}}, - /*\ + /* \ * eve [ method ] @@ -21249,10 +21008,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I errors = []; current_event = name; stop = 0; - for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) { - indexed.push(listeners[i].zIndex); - if (listeners[i].zIndex < 0) { - queue[listeners[i].zIndex] = listeners[i]; + for (var i = 0, ii = listeners.length; i < ii; i++) { + if ("zIndex" in listeners[i]) { + indexed.push(listeners[i].zIndex); + if (listeners[i].zIndex < 0) { + queue[listeners[i].zIndex] = listeners[i]; + } } } indexed.sort(numsort); @@ -21279,7 +21040,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (stop) { break; } - } while (l) + } while (l); } else { queue[l.zIndex] = l; } @@ -21296,7 +21057,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; // Undocumented. Debug only. eve._events = events; - /*\ + /* \ * eve.listeners [ method ] @@ -21340,7 +21101,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return out; }; - /*\ + /* \ * eve.on [ method ] ** @@ -21366,7 +21127,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ eve.on = function (name, f) { name = String(name); - if (typeof f != "function") { + if (typeof f !== "function") { return function () {}; } var names = name.split(separator), @@ -21376,8 +21137,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I e = e.hasOwnProperty(names[i]) && e[names[i]] || (e[names[i]] = {n: {}}); } e.f = e.f || []; - for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) { - return fun; + for (i = 0, ii = e.f.length; i < ii; i++) { + if (e.f[i] == f) { + return fun; + } } e.f.push(f); return function (zIndex) { @@ -21386,7 +21149,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } }; }; - /*\ + /* \ * eve.f [ method ] ** @@ -21408,7 +21171,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve.apply(null, [event, null].concat(attrs).concat([].slice.call(arguments, 0))); }; }; - /*\ + /* \ * eve.stop [ method ] ** @@ -21417,7 +21180,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve.stop = function () { stop = 1; }; - /*\ + /* \ * eve.nt [ method ] ** @@ -21437,7 +21200,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return current_event; }; - /*\ + /* \ * eve.nts [ method ] ** @@ -21449,7 +21212,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve.nts = function () { return current_event.split(separator); }; - /*\ + /* \ * eve.off [ method ] ** @@ -21461,7 +21224,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards - f (function) event handler function \*/ - /*\ + /* \ * eve.unbind [ method ] ** @@ -21487,8 +21250,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I splice.push(e[names[i]]); } } else { - for (key in e) if (e[has](key)) { - splice.push(e[key]); + for (key in e) { + if (e[has](key)) { + splice.push(e[key]); + } } } cur.splice.apply(cur, splice); @@ -21499,31 +21264,39 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I while (e.n) { if (f) { if (e.f) { - for (j = 0, jj = e.f.length; j < jj; j++) if (e.f[j] == f) { - e.f.splice(j, 1); - break; + for (j = 0, jj = e.f.length; j < jj; j++) { + if (e.f[j] == f) { + e.f.splice(j, 1); + break; + } } !e.f.length && delete e.f; } - for (key in e.n) if (e.n[has](key) && e.n[key].f) { - var funcs = e.n[key].f; - for (j = 0, jj = funcs.length; j < jj; j++) if (funcs[j] == f) { - funcs.splice(j, 1); - break; + for (key in e.n) { + if (e.n[has](key) && e.n[key].f) { + var funcs = e.n[key].f; + for (j = 0, jj = funcs.length; j < jj; j++) { + if (funcs[j] == f) { + funcs.splice(j, 1); + break; + } + } + !funcs.length && delete e.n[key].f; } - !funcs.length && delete e.n[key].f; } } else { delete e.f; - for (key in e.n) if (e.n[has](key) && e.n[key].f) { - delete e.n[key].f; + for (key in e.n) { + if (e.n[has](key) && e.n[key].f) { + delete e.n[key].f; + } } } e = e.n; } } }; - /*\ + /* \ * eve.once [ method ] ** @@ -21547,7 +21320,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; return eve.on(name, f2); }; - /*\ + /* \ * eve.version [ property (string) ] ** @@ -21571,7 +21344,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.core", ["eve"], function(eve) { + define("raphael.core", ["eve"], function (eve) { return factory(eve); }); } else if (typeof exports === "object") { @@ -21580,7 +21353,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I glob.Raphael = factory(glob.eve); } }(this, function (eve) { - /*\ + /* \ * Raphael [ method ] ** @@ -21630,22 +21403,22 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I | text: "Dump" | }]); \*/ - function R(first) { + function R (first) { if (R.is(first, "function")) { return loaded ? first() : eve.on("raphael.DOMload", first); } else if (R.is(first, array)) { return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first); - } else { - var args = Array.prototype.slice.call(arguments, 0); - if (R.is(args[args.length - 1], "function")) { - var f = args.pop(); - return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () { - f.call(R._engine.create[apply](R, args)); - }); - } else { - return R._engine.create[apply](R, arguments); - } } + var args = Array.prototype.slice.call(arguments, 0); + if (R.is(args[args.length - 1], "function")) { + var f = args.pop(); + return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () { + f.call(R._engine.create[apply](R, args)); + }); + } + return R._engine.create[apply](R, arguments); + + } R.version = "2.1.4"; R.eve = eve; @@ -21664,13 +21437,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I is: g.win.Raphael }, Paper = function () { - /*\ + /* \ * Paper.ca [ property (object) ] ** * Shortcut for @Paper.customAttributes \*/ - /*\ + /* \ * Paper.customAttributes [ property (object) ] ** @@ -21702,7 +21475,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I appendChild = "appendChild", apply = "apply", concat = "concat", - supportsTouch = ('ontouchstart' in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, //taken from Modernizr touch test + supportsTouch = ("ontouchstart" in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, // taken from Modernizr touch test E = "", S = " ", Str = String, @@ -21730,7 +21503,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I push = "push", ISURL = R._ISURL = /^url\(['"]?(.+?)['"]?\)$/i, colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i, - isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1}, + isnan = {NaN: 1, Infinity: 1, "-Infinity": 1}, bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/, round = math.round, setAttribute = "setAttribute", @@ -21747,8 +21520,8 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I cy: 0, fill: "#fff", "fill-opacity": 1, - font: '10px "Arial"', - "font-family": '"Arial"', + font: "10px \"Arial\"", + "font-family": "\"Arial\"", "font-size": "10", "font-style": "normal", "font-weight": 400, @@ -21854,12 +21627,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); }, - set : function(el) { + set: function (el) { var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); } }, - /*\ + /* \ * Raphael.mapPath [ method ] ** @@ -21888,7 +21661,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; R._g = g; - /*\ + /* \ * Raphael.type [ property (string) ] ** @@ -21898,21 +21671,21 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (R.type == "VML") { var d = g.doc.createElement("div"), b; - d.innerHTML = ''; + d.innerHTML = ""; b = d.firstChild; b.style.behavior = "url(#default#VML)"; - if (!(b && typeof b.adj == "object")) { + if (!(b && typeof b.adj === "object")) { return (R.type = E); } d = null; } - /*\ + /* \ * Raphael.svg [ property (boolean) ] ** * `true` if browser supports SVG. \*/ - /*\ + /* \ * Raphael.vml [ property (boolean) ] ** @@ -21920,7 +21693,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ R.svg = !(R.vml = R.type == "VML"); R._Paper = Paper; - /*\ + /* \ * Raphael.fn [ property (object) ] ** @@ -21949,7 +21722,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.fn = paperproto = Paper.prototype = R.prototype; R._id = 0; R._oid = 0; - /*\ + /* \ * Raphael.is [ method ] ** @@ -21968,24 +21741,26 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return o instanceof Array; } return (type == "null" && o === null) || - (type == typeof o && o !== null) || + (type === typeof o && o !== null) || (type == "object" && o === Object(o)) || (type == "array" && Array.isArray && Array.isArray(o)) || objectToString.call(o).slice(8, -1).toLowerCase() == type; }; - function clone(obj) { - if (typeof obj == "function" || Object(obj) !== obj) { + function clone (obj) { + if (typeof obj === "function" || Object(obj) !== obj) { return obj; } var res = new obj.constructor; - for (var key in obj) if (obj[has](key)) { - res[key] = clone(obj[key]); + for (var key in obj) { + if (obj[has](key)) { + res[key] = clone(obj[key]); + } } return res; } - /*\ + /* \ * Raphael.angle [ method ] ** @@ -22007,11 +21782,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return 0; } return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360; - } else { - return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); } + return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); + }; - /*\ + /* \ * Raphael.rad [ method ] ** @@ -22023,7 +21798,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.rad = function (deg) { return deg % 360 * PI / 180; }; - /*\ + /* \ * Raphael.deg [ method ] ** @@ -22033,9 +21808,9 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (number) angle in degrees. \*/ R.deg = function (rad) { - return Math.round ((rad * 180 / PI% 360)* 1000) / 1000; + return Math.round ((rad * 180 / PI % 360) * 1000) / 1000; }; - /*\ + /* \ * Raphael.snapTo [ method ] ** @@ -22050,8 +21825,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I tolerance = R.is(tolerance, "finite") ? tolerance : 10; if (R.is(values, array)) { var i = values.length; - while (i--) if (abs(values[i] - value) <= tolerance) { - return values[i]; + while (i--) { + if (abs(values[i] - value) <= tolerance) { + return values[i]; + } } } else { values = +values; @@ -22066,7 +21843,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return value; }; - /*\ + /* \ * Raphael.createUUID [ method ] ** @@ -22082,7 +21859,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return v.toString(16); }); - /*\ + /* \ * Raphael.setWindow [ method ] ** @@ -22178,7 +21955,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return rgb; }; - /*\ + /* \ * Raphael.color [ method ] ** @@ -22231,7 +22008,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I clr.toString = rgbtoString; return clr; }; - /*\ + /* \ * Raphael.hsb2rgb [ method ] ** @@ -22268,7 +22045,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; - /*\ + /* \ * Raphael.hsl2rgb [ method ] ** @@ -22309,7 +22086,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; - /*\ + /* \ * Raphael.rgb2hsb [ method ] ** @@ -22335,15 +22112,15 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I V = mmax(r, g, b); C = V - mmin(r, g, b); H = (C == 0 ? null : - V == r ? (g - b) / C : - V == g ? (b - r) / C + 2 : + V == r ? (g - b) / C : + V == g ? (b - r) / C + 2 : (r - g) / C + 4 ); H = ((H + 360) % 6) * 60 / 360; S = C == 0 ? 0 : C / V; return {h: H, s: S, b: V, toString: hsbtoString}; }; - /*\ + /* \ * Raphael.rgb2hsl [ method ] ** @@ -22372,24 +22149,26 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I H = (C == 0 ? null : M == r ? (g - b) / C : M == g ? (b - r) / C + 2 : - (r - g) / C + 4); + (r - g) / C + 4); H = ((H + 360) % 6) * 60 / 360; L = (M + m) / 2; S = (C == 0 ? 0 : L < .5 ? C / (2 * L) : - C / (2 - 2 * L)); + C / (2 - 2 * L)); return {h: H, s: S, l: L, toString: hsltoString}; }; R._path2string = function () { return this.join(",").replace(p2s, "$1"); }; - function repush(array, item) { - for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) { - return array.push(array.splice(i, 1)[0]); + function repush (array, item) { + for (var i = 0, ii = array.length; i < ii; i++) { + if (array[i] === item) { + return array.push(array.splice(i, 1)[0]); + } } } - function cacher(f, scope, postprocessor) { - function newf() { + function cacher (f, scope, postprocessor) { + function newf () { var arg = Array.prototype.slice.call(arguments, 0), args = arg.join("\u2400"), cache = newf.cache = newf.cache || {}, @@ -22421,11 +22200,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I img.src = src; }; - function clrToString() { + function clrToString () { return this.hex; } - /*\ + /* \ * Raphael.getRGB [ method ] ** @@ -22523,7 +22302,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString}; }, R); - /*\ + /* \ * Raphael.hsb [ method ] ** @@ -22537,7 +22316,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.hsb = cacher(function (h, s, b) { return R.hsb2rgb(h, s, b).hex; }); - /*\ + /* \ * Raphael.hsl [ method ] ** @@ -22551,7 +22330,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.hsl = cacher(function (h, s, l) { return R.hsl2rgb(h, s, l).hex; }); - /*\ + /* \ * Raphael.rgb [ method ] ** @@ -22563,10 +22342,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (string) hex representation of the colour. \*/ R.rgb = cacher(function (r, g, b) { - function round(x) { return (x + 0.5) | 0; } + function round (x) { return (x + 0.5) | 0; } return "#" + (16777216 | round(b) | (round(g) << 8) | (round(r) << 16)).toString(16).slice(1); }); - /*\ + /* \ * Raphael.getColor [ method ] ** @@ -22586,7 +22365,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return rgb.hex; }; - /*\ + /* \ * Raphael.getColor.reset [ method ] ** @@ -22597,7 +22376,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; // http://schepers.cc/getting-to-the-point - function catmullRom2bezier(crp, z) { + function catmullRom2bezier (crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [ @@ -22626,7 +22405,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, - (p[1].y + 6*p[2].y - p[3].y) / 6, + (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y ]); @@ -22634,7 +22413,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return d; } - /*\ + /* \ * Raphael.parsePathString [ method ] ** @@ -22673,10 +22452,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (name == "r") { data.push([b][concat](params)); - } else while (params.length >= paramCounts[name]) { - data.push([b][concat](params.splice(0, paramCounts[name]))); - if (!paramCounts[name]) { - break; + } else { + while (params.length >= paramCounts[name]) { + data.push([b][concat](params.splice(0, paramCounts[name]))); + if (!paramCounts[name]) { + break; + } } } }); @@ -22685,7 +22466,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I pth.arr = pathClone(data); return data; }; - /*\ + /* \ * Raphael.parseTransformString [ method ] ** @@ -22729,14 +22510,16 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; } setTimeout(function () { - for (var key in p) if (p[has](key) && key != ps) { - p[key].sleep--; - !p[key].sleep && delete p[key]; + for (var key in p) { + if (p[has](key) && key != ps) { + p[key].sleep--; + !p[key].sleep && delete p[key]; + } } }); return p[ps]; }; - /*\ + /* \ * Raphael.findDotsAtSegment [ method ] ** @@ -22804,7 +22587,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I alpha: alpha }; }; - /*\ + /* \ * Raphael.bezierBBox [ method ] ** @@ -22848,7 +22631,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I height: bbox.max.y - bbox.min.y }; }; - /*\ + /* \ * Raphael.isPointInsideBBox [ method ] ** @@ -22864,7 +22647,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.isPointInsideBBox = function (bbox, x, y) { return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2; }; - /*\ + /* \ * Raphael.isBBoxIntersect [ method ] ** @@ -22889,20 +22672,20 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; - function base3(t, p1, p2, p3, p4) { + function base3 (t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } - function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { + function bezlen (x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z == null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2, n = 12, - Tvalues = [-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816], - Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472], + Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816], + Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472], sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2, @@ -22913,7 +22696,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return z2 * sum; } - function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { + function getTatLen (x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } @@ -22930,7 +22713,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return t2; } - function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { + function intersect (x1, y1, x2, y2, x3, y3, x4, y4) { if ( mmax(x1, x2) < mmin(x3, x4) || mmin(x1, x2) > mmax(x3, x4) || @@ -22964,13 +22747,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return {x: px, y: py}; } - function inter(bez1, bez2) { + function inter (bez1, bez2) { return interHelper(bez1, bez2); } - function interCount(bez1, bez2) { + function interCount (bez1, bez2) { return interHelper(bez1, bez2, 1); } - function interHelper(bez1, bez2, justCount) { + function interHelper (bez1, bez2, justCount) { var bbox1 = R.bezierBBox(bez1), bbox2 = R.bezierBBox(bez2); if (!R.isBBoxIntersect(bbox1, bbox2)) { @@ -23025,7 +22808,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return res; } - /*\ + /* \ * Raphael.pathIntersection [ method ] ** @@ -23055,7 +22838,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.pathIntersectionNumber = function (path1, path2) { return interPathHelper(path1, path2, 1); }; - function interPathHelper(path1, path2, justCount) { + function interPathHelper (path1, path2, justCount) { path1 = R._path2curve(path1); path2 = R._path2curve(path2); var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2, @@ -23108,7 +22891,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return res; } - /*\ + /* \ * Raphael.isPointInsidePath [ method ] ** @@ -23131,7 +22914,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve("raphael.log", null, "Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object", methodname); }; }; - /*\ + /* \ * Raphael.pathBBox [ method ] ** @@ -23476,14 +23259,14 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4][concat](res); - } else { - res = [m2, m3, m4][concat](res).join()[split](","); - var newres = []; - for (var i = 0, ii = res.length; i < ii; i++) { - newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; - } - return newres; } + res = [m2, m3, m4][concat](res).join()[split](","); + var newres = []; + for (var i = 0, ii = res.length; i < ii; i++) { + newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; + } + return newres; + }, findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; @@ -23545,7 +23328,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, processPath = function (path, d, pcom) { - var nx, ny, tq = {T:1, Q:1}; + var nx, ny, tq = {T: 1, Q: 1}; if (!path) { return ["C", d.x, d.y, d.x, d.y, d.x, d.y]; } @@ -23562,8 +23345,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (pcom == "C" || pcom == "S") { // In "S" case we have to take into account, if the previous command is C/S. nx = d.x * 2 - d.bx; // And reflect the previous ny = d.y * 2 - d.by; // command's control point relative to the current point. - } - else { // or some else or nothing + } else { // or some else or nothing nx = d.x; ny = d.y; } @@ -23573,8 +23355,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (pcom == "Q" || pcom == "T") { // In "T" case we have to take into account, if the previous command is Q/T. d.qx = d.x * 2 - d.qx; // And make a reflection similar d.qy = d.y * 2 - d.qy; // to case "S". - } - else { // or something else or nothing + } else { // or something else or nothing d.qx = d.x; d.qy = d.y; } @@ -23605,8 +23386,8 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I pp[i].shift(); var pi = pp[i]; while (pi.length) { - pcoms1[i]="A"; // if created multiple C:s, their original seg is saved - p2 && (pcoms2[i]="A"); // the same as above + pcoms1[i] = "A"; // if created multiple C:s, their original seg is saved + p2 && (pcoms2[i] = "A"); // the same as above pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6))); } pp.splice(i, 1); @@ -23633,7 +23414,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (pfirst != "C") // C is not saved yet, because it may be result of conversion { pcoms1[i] = pfirst; // Save current path command - i && ( pcom = pcoms1[i-1]); // Get previous path command pcom + i && ( pcom = pcoms1[i - 1]); // Get previous path command pcom } p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath @@ -23645,14 +23426,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (p2) { // the same procedures is done to p2 p2[i] && (pfirst = p2[i][0]); - if (pfirst != "C") - { + if (pfirst != "C") { pcoms2[i] = pfirst; - i && (pcom = pcoms2[i-1]); + i && (pcom = pcoms2[i - 1]); } p2[i] = processPath(p2[i], attrs2, pcom); - if (pcoms2[i]!="A" && pfirst=="C") pcoms2[i]="C"; + if (pcoms2[i] != "A" && pfirst == "C") pcoms2[i] = "C"; fixArc(p2, i); } @@ -23756,7 +23536,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I el2.prev = el; el.next = el2; }, - /*\ + /* \ * Raphael.toMatrix [ method ] ** @@ -23781,7 +23561,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I extractTransform(el, transform); return el.matrix; }, - /*\ + /* \ * Raphael.transformPath [ method ] ** @@ -23872,7 +23652,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } } - /*\ + /* \ * Element.matrix [ property (object) ] ** @@ -23900,16 +23680,16 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I case "m": return [l, 1, 0, 0, 1, 0, 0]; case "r": if (item.length == 4) { return [l, 0, item[2], item[3]]; - } else { - return [l, 0]; } + return [l, 0]; + case "s": if (item.length == 5) { return [l, 1, 1, item[3], item[4]]; } else if (item.length == 3) { - return [l, 1, 1]; - } else { + return [l, 1, 1]; + } return [l, 1]; - } + } }, equaliseTransform = R._equaliseTransform = function (t1, t2) { @@ -23955,13 +23735,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I width: container.style.pixelWidth || container.offsetWidth, height: container.style.pixelHeight || container.offsetHeight }; - } else { - return { - container: container, - width: y, - height: w - }; } + return { + container: container, + width: y, + height: w + }; + } return { container: 1, @@ -23971,7 +23751,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I height: h }; }; - /*\ + /* \ * Raphael.pathToRelative [ method ] ** @@ -23984,7 +23764,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ R.pathToRelative = pathToRelative; R._engine = {}; - /*\ + /* \ * Raphael.path2curve [ method ] ** @@ -23996,7 +23776,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (array) array of segments. \*/ R.path2curve = path2curve; - /*\ + /* \ * Raphael.matrix [ method ] ** @@ -24015,7 +23795,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.matrix = function (a, b, c, d, e, f) { return new Matrix(a, b, c, d, e, f); }; - function Matrix(a, b, c, d, e, f) { + function Matrix (a, b, c, d, e, f) { if (a != null) { this.a = +a; this.b = +b; @@ -24033,7 +23813,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } } (function (matrixproto) { - /*\ + /* \ * Matrix.add [ method ] ** @@ -24074,7 +23854,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.e = out[0][2]; this.f = out[1][2]; }; - /*\ + /* \ * Matrix.invert [ method ] ** @@ -24086,7 +23866,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I x = me.a * me.d - me.b * me.c; return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x); }; - /*\ + /* \ * Matrix.clone [ method ] ** @@ -24096,7 +23876,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I matrixproto.clone = function () { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; - /*\ + /* \ * Matrix.translate [ method ] ** @@ -24108,7 +23888,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I matrixproto.translate = function (x, y) { this.add(1, 0, 0, 1, x, y); }; - /*\ + /* \ * Matrix.scale [ method ] ** @@ -24125,7 +23905,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.add(x, 0, 0, y, 0, 0); (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy); }; - /*\ + /* \ * Matrix.rotate [ method ] ** @@ -24144,7 +23924,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.add(cos, sin, -sin, cos, x, y); this.add(1, 0, 0, 1, -x, -y); }; - /*\ + /* \ * Matrix.x [ method ] ** @@ -24157,7 +23937,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I matrixproto.x = function (x, y) { return x * this.a + y * this.c + this.e; }; - /*\ + /* \ * Matrix.y [ method ] ** @@ -24175,7 +23955,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; matrixproto.toString = function () { return R.svg ? - "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : + "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join(); }; matrixproto.toFilter = function () { @@ -24186,15 +23966,15 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I matrixproto.offset = function () { return [this.e.toFixed(4), this.f.toFixed(4)]; }; - function norm(a) { + function norm (a) { return a[0] * a[0] + a[1] * a[1]; } - function normalize(a) { + function normalize (a) { var mag = math.sqrt(norm(a)); a[0] && (a[0] /= mag); a[1] && (a[1] /= mag); } - /*\ + /* \ * Matrix.split [ method ] ** @@ -24243,7 +24023,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I out.noRotation = !+out.shear.toFixed(9) && !out.rotate; return out; }; - /*\ + /* \ * Matrix.toTransformString [ method ] ** @@ -24259,9 +24039,9 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) + (s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) + (s.rotate ? "r" + [s.rotate, 0, 0] : E); - } else { - return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; } + return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; + }; })(Matrix.prototype); @@ -24318,8 +24098,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return function () { obj.removeEventListener(type, f, false); - if (supportsTouch && touchMap[type]) - obj.removeEventListener(touchMap[type], _f, false); + if (supportsTouch && touchMap[type]) {obj.removeEventListener(touchMap[type], _f, false);} return true; }; @@ -24397,7 +24176,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } drag = []; }, - /*\ + /* \ * Raphael.el [ property (object) ] ** @@ -24412,7 +24191,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I | paper.circle(100, 100, 20).red(); \*/ elproto = R.el = {}; - /*\ + /* \ * Element.click [ method ] ** @@ -24421,7 +24200,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unclick [ method ] ** @@ -24431,7 +24210,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.dblclick [ method ] ** @@ -24440,7 +24219,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.undblclick [ method ] ** @@ -24450,7 +24229,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mousedown [ method ] ** @@ -24459,7 +24238,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmousedown [ method ] ** @@ -24469,7 +24248,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mousemove [ method ] ** @@ -24478,7 +24257,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmousemove [ method ] ** @@ -24488,7 +24267,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mouseout [ method ] ** @@ -24497,7 +24276,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseout [ method ] ** @@ -24507,7 +24286,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mouseover [ method ] ** @@ -24516,7 +24295,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseover [ method ] ** @@ -24526,7 +24305,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mouseup [ method ] ** @@ -24535,7 +24314,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseup [ method ] ** @@ -24545,7 +24324,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.touchstart [ method ] ** @@ -24554,7 +24333,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchstart [ method ] ** @@ -24564,7 +24343,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.touchmove [ method ] ** @@ -24573,7 +24352,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchmove [ method ] ** @@ -24583,7 +24362,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.touchend [ method ] ** @@ -24592,7 +24371,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchend [ method ] ** @@ -24602,7 +24381,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.touchcancel [ method ] ** @@ -24611,7 +24390,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchcancel [ method ] ** @@ -24632,7 +24411,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R["un" + eventName] = elproto["un" + eventName] = function (fn) { var events = this.events || [], l = events.length; - while (l--){ + while (l--) { if (events[l].name == eventName && (R.is(fn, "undefined") || events[l].f == fn)) { events[l].unbind(); events.splice(l, 1); @@ -24644,7 +24423,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I })(events[i]); } - /*\ + /* \ * Element.data [ method ] ** @@ -24676,8 +24455,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (arguments.length == 1) { if (R.is(key, "object")) { - for (var i in key) if (key[has](i)) { - this.data(i, key[i]); + for (var i in key) { + if (key[has](i)) { + this.data(i, key[i]); + } } return this; } @@ -24689,11 +24470,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return this; }; - elproto.datum = function(){ + elproto.datum = function () { return arguments.length == 0 ? this._bindData : ((this._bindData = arguments[0]), this); }; - /*\ + /* \ * Element.removeData [ method ] ** @@ -24711,7 +24492,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Element.getData [ method ] ** @@ -24721,7 +24502,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I elproto.getData = function () { return clone(eldata[this.id] || {}); }; - /*\ + /* \ * Element.hover [ method ] ** @@ -24736,7 +24517,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I elproto.hover = function (f_in, f_out, scope_in, scope_out) { return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in); }; - /*\ + /* \ * Element.unhover [ method ] ** @@ -24750,7 +24531,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return this.unmouseover(f_in).unmouseout(f_out); }; var draggable = []; - /*\ + /* \ * Element.drag [ method ] ** @@ -24781,7 +24562,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) { - function start(e) { + function start (e) { (e.originalEvent || e).preventDefault(); var x = e.clientX, y = e.clientY, @@ -24814,7 +24595,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.mousedown(start); return this; }; - /*\ + /* \ * Element.onDragOver [ method ] ** @@ -24825,7 +24606,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I elproto.onDragOver = function (f) { f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id); }; - /*\ + /* \ * Element.undrag [ method ] ** @@ -24833,15 +24614,17 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ elproto.undrag = function () { var i = draggable.length; - while (i--) if (draggable[i].el == this) { - this.unmousedown(draggable[i].start); - draggable.splice(i, 1); - eve.unbind("raphael.drag.*." + this.id); + while (i--) { + if (draggable[i].el == this) { + this.unmousedown(draggable[i].start); + draggable.splice(i, 1); + eve.unbind("raphael.drag.*." + this.id); + } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); drag = []; }; - /*\ + /* \ * Paper.circle [ method ] ** @@ -24862,7 +24645,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.rect [ method ] * @@ -24888,7 +24671,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.ellipse [ method ] ** @@ -24910,7 +24693,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.path [ method ] ** @@ -24948,7 +24731,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.image [ method ] ** @@ -24971,7 +24754,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.text [ method ] ** @@ -24992,7 +24775,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.set [ method ] ** @@ -25017,7 +24800,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I out["type"] = "set"; return out; }; - /*\ + /* \ * Paper.setStart [ method ] ** @@ -25034,7 +24817,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I paperproto.setStart = function (set) { this.__set__ = set || this.set(); }; - /*\ + /* \ * Paper.setFinish [ method ] ** @@ -25047,7 +24830,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I delete this.__set__; return out; }; - /*\ + /* \ * Paper.getSize [ method ] ** @@ -25062,7 +24845,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I height: container.offsetHeight }; }; - /*\ + /* \ * Paper.setSize [ method ] ** @@ -25076,7 +24859,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I paperproto.setSize = function (width, height) { return R._engine.setSize.call(this, width, height); }; - /*\ + /* \ * Paper.setViewBox [ method ] ** @@ -25094,20 +24877,20 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I paperproto.setViewBox = function (x, y, w, h, fit) { return R._engine.setViewBox.call(this, x, y, w, h, fit); }; - /*\ + /* \ * Paper.top [ property ] ** * Points to the topmost element on the paper \*/ - /*\ + /* \ * Paper.bottom [ property ] ** * Points to the bottom element on the paper \*/ paperproto.top = paperproto.bottom = null; - /*\ + /* \ * Paper.raphael [ property ] ** @@ -25127,7 +24910,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I x: left }; }; - /*\ + /* \ * Paper.getElementByPoint [ method ] ** @@ -25167,7 +24950,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return target; }; - /*\ + /* \ * Paper.getElementsByBBox [ method ] ** @@ -25188,7 +24971,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return set; }; - /*\ + /* \ * Paper.getById [ method ] ** @@ -25209,7 +24992,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return null; }; - /*\ + /* \ * Paper.forEach [ method ] ** @@ -25237,7 +25020,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Paper.getElementsByPoint [ method ] ** @@ -25258,13 +25041,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); return set; }; - function x_y() { + function x_y () { return this.x + S + this.y; } - function x_y_w_h() { + function x_y_w_h () { return this.x + S + this.y + S + this.width + " \xd7 " + this.height; } - /*\ + /* \ * Element.isPointInside [ method ] ** @@ -25278,12 +25061,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ elproto.isPointInside = function (x, y) { var rp = this.realPath = getPath[this.type](this); - if (this.attr('transform') && this.attr('transform').length) { - rp = R.transformPath(rp, this.attr('transform')); + if (this.attr("transform") && this.attr("transform").length) { + rp = R.transformPath(rp, this.attr("transform")); } return R.isPointInsidePath(rp, x, y); }; - /*\ + /* \ * Element.getBBox [ method ] ** @@ -25327,7 +25110,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return _.bbox; }; - /*\ + /* \ * Element.clone [ method ] ** @@ -25342,7 +25125,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Element.glow [ method ] ** @@ -25397,9 +25180,9 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) { if (length == null) { return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y); - } else { - return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); } + return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); + }, getLengthFactory = function (istotal, subpath) { return function (path, length, onlystart) { @@ -25445,7 +25228,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var getTotalLength = getLengthFactory(1), getPointAtLength = getLengthFactory(), getSubpathsAtLength = getLengthFactory(0, 1); - /*\ + /* \ * Raphael.getTotalLength [ method ] ** @@ -25458,7 +25241,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (number) length. \*/ R.getTotalLength = getTotalLength; - /*\ + /* \ * Raphael.getPointAtLength [ method ] ** @@ -25477,7 +25260,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I o } \*/ R.getPointAtLength = getPointAtLength; - /*\ + /* \ * Raphael.getSubpath [ method ] ** @@ -25498,7 +25281,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var a = getSubpathsAtLength(path, to, 1); return from ? getSubpathsAtLength(a, from).end : a; }; - /*\ + /* \ * Element.getTotalLength [ method ] ** @@ -25517,7 +25300,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return getTotalLength(path); }; - /*\ + /* \ * Element.getPointAtLength [ method ] ** @@ -25542,7 +25325,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return getPointAtLength(path, length); }; - /*\ + /* \ * Element.getPath [ method ] ** @@ -25564,7 +25347,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return path; }; - /*\ + /* \ * Element.getSubpath [ method ] ** @@ -25585,7 +25368,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return R.getSubpath(path, from, to); }; - /*\ + /* \ * Raphael.easing_formulas [ property ] ** @@ -25708,65 +25491,67 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (time < ms) { var pos = easing(time / ms); - for (var attr in from) if (from[has](attr)) { - switch (availableAnimAttrs[attr]) { - case nu: - now = +from[attr] + pos * ms * diff[attr]; - break; - case "colour": - now = "rgb(" + [ + for (var attr in from) { + if (from[has](attr)) { + switch (availableAnimAttrs[attr]) { + case nu: + now = +from[attr] + pos * ms * diff[attr]; + break; + case "colour": + now = "rgb(" + [ upto255(round(from[attr].r + pos * ms * diff[attr].r)), upto255(round(from[attr].g + pos * ms * diff[attr].g)), upto255(round(from[attr].b + pos * ms * diff[attr].b)) ].join(",") + ")"; - break; - case "path": - now = []; - for (var i = 0, ii = from[attr].length; i < ii; i++) { - now[i] = [from[attr][i][0]]; - for (var j = 1, jj = from[attr][i].length; j < jj; j++) { - now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j]; - } - now[i] = now[i].join(S); - } - now = now.join(S); - break; - case "transform": - if (diff[attr].real) { + break; + case "path": now = []; - for (i = 0, ii = from[attr].length; i < ii; i++) { + for (var i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; - for (j = 1, jj = from[attr][i].length; j < jj; j++) { - now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; + for (var j = 1, jj = from[attr][i].length; j < jj; j++) { + now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j]; } + now[i] = now[i].join(S); } - } else { - var get = function (i) { - return +from[attr][i] + pos * ms * diff[attr][i]; - }; - // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; - now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; - } - break; - case "csv": - if (attr == "clip-rect") { + now = now.join(S); + break; + case "transform": + if (diff[attr].real) { + now = []; + for (i = 0, ii = from[attr].length; i < ii; i++) { + now[i] = [from[attr][i][0]]; + for (j = 1, jj = from[attr][i].length; j < jj; j++) { + now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; + } + } + } else { + var get = function (i) { + return +from[attr][i] + pos * ms * diff[attr][i]; + }; + // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; + now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; + } + break; + case "csv": + if (attr == "clip-rect") { + now = []; + i = 4; + while (i--) { + now[i] = +from[attr][i] + pos * ms * diff[attr][i]; + } + } + break; + default: + var from2 = [][concat](from[attr]); now = []; - i = 4; + i = that.paper.customAttributes[attr].length; while (i--) { - now[i] = +from[attr][i] + pos * ms * diff[attr][i]; + now[i] = +from2[i] + pos * ms * diff[attr][i]; } - } - break; - default: - var from2 = [][concat](from[attr]); - now = []; - i = that.paper.customAttributes[attr].length; - while (i--) { - now[i] = +from2[i] + pos * ms * diff[attr][i]; - } - break; + break; + } + set[attr] = now; } - set[attr] = now; } that.attr(set); (function (id, that, anim) { @@ -25775,8 +25560,8 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); })(that.id, that, e.anim); } else { - (function(f, el, a) { - setTimeout(function() { + (function (f, el, a) { + setTimeout(function () { eve("raphael.anim.frame." + el.id, el, a); eve("raphael.anim.finish." + el.id, el, a); R.is(f, "function") && f.call(el); @@ -25785,8 +25570,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I that.attr(to); animationElements.splice(l--, 1); if (e.repeat > 1 && !e.next) { - for (key in to) if (to[has](key)) { - init[key] = e.totalOrigin[key]; + for (key in to) { + if (to[has](key)) { + init[key] = e.totalOrigin[key]; + } } e.el.attr(init); runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1); @@ -25801,7 +25588,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I upto255 = function (color) { return color > 255 ? 255 : color < 0 ? 0 : color; }; - /*\ + /* \ * Element.animateWith [ method ] ** @@ -25844,21 +25631,21 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I // status = element.status(anim); // return this.animate(a).status(a, status * anim.ms / a.ms); }; - function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) { + function CubicBezierAtTime (t, p1x, p1y, p2x, p2y, duration) { var cx = 3 * p1x, bx = 3 * (p2x - p1x) - cx, ax = 1 - cx - bx, cy = 3 * p1y, by = 3 * (p2y - p1y) - cy, ay = 1 - cy - by; - function sampleCurveX(t) { + function sampleCurveX (t) { return ((ax * t + bx) * t + cx) * t; } - function solve(x, epsilon) { + function solve (x, epsilon) { var t = solveCurveX(x, epsilon); return ((ay * t + by) * t + cy) * t; } - function solveCurveX(x, epsilon) { + function solveCurveX (x, epsilon) { var t0, t1, t2, x2, d2, i; for(t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; @@ -25900,15 +25687,17 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id); return this; }; - function Animation(anim, ms) { + function Animation (anim, ms) { var percents = [], newAnim = {}; this.ms = ms; this.times = 1; if (anim) { - for (var attr in anim) if (anim[has](attr)) { - newAnim[toFloat(attr)] = anim[attr]; - percents.push(toFloat(attr)); + for (var attr in anim) { + if (anim[has](attr)) { + newAnim[toFloat(attr)] = anim[attr]; + percents.push(toFloat(attr)); + } } percents.sort(sortByNumber); } @@ -25916,7 +25705,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.top = percents[percents.length - 1]; this.percents = percents; } - /*\ + /* \ * Animation.delay [ method ] ** @@ -25937,7 +25726,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I a.del = +delay || 0; return a; }; - /*\ + /* \ * Animation.repeat [ method ] ** @@ -25955,7 +25744,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I a.times = math.floor(mmax(times, 0)) || 1; return a; }; - function runAnimation(anim, element, percent, status, totalOrigin, times) { + function runAnimation (anim, element, percent, status, totalOrigin, times) { percent = toFloat(percent); var params, isInAnim, @@ -26001,76 +25790,77 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return; } if (!isInAnim) { - for (var attr in params) if (params[has](attr)) { - if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) { - from[attr] = element.attr(attr); - (from[attr] == null) && (from[attr] = availableAttrs[attr]); - to[attr] = params[attr]; - switch (availableAnimAttrs[attr]) { - case nu: - diff[attr] = (to[attr] - from[attr]) / ms; - break; - case "colour": - from[attr] = R.getRGB(from[attr]); - var toColour = R.getRGB(to[attr]); - diff[attr] = { - r: (toColour.r - from[attr].r) / ms, - g: (toColour.g - from[attr].g) / ms, - b: (toColour.b - from[attr].b) / ms - }; - break; - case "path": - var pathes = path2curve(from[attr], to[attr]), - toPath = pathes[1]; - from[attr] = pathes[0]; - diff[attr] = []; - for (i = 0, ii = from[attr].length; i < ii; i++) { - diff[attr][i] = [0]; - for (var j = 1, jj = from[attr][i].length; j < jj; j++) { - diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; - } - } - break; - case "transform": - var _ = element._, - eq = equaliseTransform(_[attr], to[attr]); - if (eq) { - from[attr] = eq.from; - to[attr] = eq.to; + for (var attr in params) { + if (params[has](attr)) { + if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) { + from[attr] = element.attr(attr); + (from[attr] == null) && (from[attr] = availableAttrs[attr]); + to[attr] = params[attr]; + switch (availableAnimAttrs[attr]) { + case nu: + diff[attr] = (to[attr] - from[attr]) / ms; + break; + case "colour": + from[attr] = R.getRGB(from[attr]); + var toColour = R.getRGB(to[attr]); + diff[attr] = { + r: (toColour.r - from[attr].r) / ms, + g: (toColour.g - from[attr].g) / ms, + b: (toColour.b - from[attr].b) / ms + }; + break; + case "path": + var pathes = path2curve(from[attr], to[attr]), + toPath = pathes[1]; + from[attr] = pathes[0]; diff[attr] = []; - diff[attr].real = true; for (i = 0, ii = from[attr].length; i < ii; i++) { - diff[attr][i] = [from[attr][i][0]]; - for (j = 1, jj = from[attr][i].length; j < jj; j++) { - diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; + diff[attr][i] = [0]; + for (var j = 1, jj = from[attr][i].length; j < jj; j++) { + diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; } } - } else { - var m = (element.matrix || new Matrix), - to2 = { - _: {transform: _.transform}, - getBBox: function () { - return element.getBBox(1); + break; + case "transform": + var _ = element._, + eq = equaliseTransform(_[attr], to[attr]); + if (eq) { + from[attr] = eq.from; + to[attr] = eq.to; + diff[attr] = []; + diff[attr].real = true; + for (i = 0, ii = from[attr].length; i < ii; i++) { + diff[attr][i] = [from[attr][i][0]]; + for (j = 1, jj = from[attr][i].length; j < jj; j++) { + diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; } - }; - from[attr] = [ - m.a, - m.b, - m.c, - m.d, - m.e, - m.f - ]; - extractTransform(to2, to[attr]); - to[attr] = to2._.transform; - diff[attr] = [ - (to2.matrix.a - m.a) / ms, - (to2.matrix.b - m.b) / ms, - (to2.matrix.c - m.c) / ms, - (to2.matrix.d - m.d) / ms, - (to2.matrix.e - m.e) / ms, - (to2.matrix.f - m.f) / ms - ]; + } + } else { + var m = (element.matrix || new Matrix), + to2 = { + _: {transform: _.transform}, + getBBox: function () { + return element.getBBox(1); + } + }; + from[attr] = [ + m.a, + m.b, + m.c, + m.d, + m.e, + m.f + ]; + extractTransform(to2, to[attr]); + to[attr] = to2._.transform; + diff[attr] = [ + (to2.matrix.a - m.a) / ms, + (to2.matrix.b - m.b) / ms, + (to2.matrix.c - m.c) / ms, + (to2.matrix.d - m.d) / ms, + (to2.matrix.e - m.e) / ms, + (to2.matrix.f - m.f) / ms + ]; // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy]; // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }}; // extractTransform(to2, to[attr]); @@ -26081,30 +25871,31 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I // (to2._.dx - _.dx) / ms, // (to2._.dy - _.dy) / ms // ]; - } - break; - case "csv": - var values = Str(params[attr])[split](separator), - from2 = Str(from[attr])[split](separator); - if (attr == "clip-rect") { - from[attr] = from2; + } + break; + case "csv": + var values = Str(params[attr])[split](separator), + from2 = Str(from[attr])[split](separator); + if (attr == "clip-rect") { + from[attr] = from2; + diff[attr] = []; + i = from2.length; + while (i--) { + diff[attr][i] = (values[i] - from[attr][i]) / ms; + } + } + to[attr] = values; + break; + default: + values = [][concat](params[attr]); + from2 = [][concat](from[attr]); diff[attr] = []; - i = from2.length; + i = element.paper.customAttributes[attr].length; while (i--) { - diff[attr][i] = (values[i] - from[attr][i]) / ms; + diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms; } - } - to[attr] = values; - break; - default: - values = [][concat](params[attr]); - from2 = [][concat](from[attr]); - diff[attr] = []; - i = element.paper.customAttributes[attr].length; - while (i--) { - diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms; - } - break; + break; + } } } } @@ -26161,7 +25952,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } eve("raphael.anim.start." + element.id, element, anim); } - /*\ + /* \ * Raphael.animation [ method ] ** @@ -26190,33 +25981,35 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var p = {}, json, attr; - for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { - json = true; - p[attr] = params[attr]; + for (attr in params) { + if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { + json = true; + p[attr] = params[attr]; + } } if (!json) { // if percent-like syntax is used and end-of-all animation callback used - if(callback){ + if(callback) { // find the last one var lastKey = 0; - for(var i in params){ + for(var i in params) { var percent = toInt(i); - if(params[has](i) && percent > lastKey){ + if(params[has](i) && percent > lastKey) { lastKey = percent; } } - lastKey += '%'; + lastKey += "%"; // if already defined callback in the last keyframe, skip !params[lastKey].callback && (params[lastKey].callback = callback); } return new Animation(params, ms); - } else { - easing && (p.easing = easing); - callback && (p.callback = callback); - return new Animation({100: p}, ms); } + easing && (p.easing = easing); + callback && (p.callback = callback); + return new Animation({100: p}, ms); + }; - /*\ + /* \ * Element.animate [ method ] ** @@ -26243,7 +26036,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I runAnimation(anim, element, anim.percents[0], null, element.attr()); return element; }; - /*\ + /* \ * Element.setTime [ method ] ** @@ -26265,7 +26058,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Element.status [ method ] ** @@ -26294,27 +26087,27 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (value != null) { runAnimation(anim, this, -1, mmin(value, 1)); return this; - } else { - len = animationElements.length; - for (; i < len; i++) { - e = animationElements[i]; - if (e.el.id == this.id && (!anim || e.anim == anim)) { - if (anim) { - return e.status; - } - out.push({ - anim: e.anim, - status: e.status - }); + } + len = animationElements.length; + for (; i < len; i++) { + e = animationElements[i]; + if (e.el.id == this.id && (!anim || e.anim == anim)) { + if (anim) { + return e.status; } + out.push({ + anim: e.anim, + status: e.status + }); } - if (anim) { - return 0; - } - return out; } + if (anim) { + return 0; + } + return out; + }; - /*\ + /* \ * Element.pause [ method ] ** @@ -26327,14 +26120,16 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) original element \*/ elproto.pause = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) { - animationElements[i].paused = true; + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) { + animationElements[i].paused = true; + } } } return this; }; - /*\ + /* \ * Element.resume [ method ] ** @@ -26347,16 +26142,18 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) original element \*/ elproto.resume = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - var e = animationElements[i]; - if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { - delete e.paused; - this.status(e.anim, e.status); + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + var e = animationElements[i]; + if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { + delete e.paused; + this.status(e.anim, e.status); + } } } return this; }; - /*\ + /* \ * Element.stop [ method ] ** @@ -26369,16 +26166,20 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) original element \*/ elproto.stop = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) { - animationElements.splice(i--, 1); + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) { + animationElements.splice(i--, 1); + } } } return this; }; - function stopAnimation(paper) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.paper == paper) { - animationElements.splice(i--, 1); + function stopAnimation (paper) { + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.paper == paper) { + animationElements.splice(i--, 1); + } } } eve.on("raphael.remove", stopAnimation); @@ -26402,7 +26203,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } }, setproto = Set.prototype; - /*\ + /* \ * Set.push [ method ] ** @@ -26422,7 +26223,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Set.pop [ method ] ** @@ -26433,7 +26234,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.length && delete this[this.length--]; return this.items.pop(); }; - /*\ + /* \ * Set.forEach [ method ] ** @@ -26455,15 +26256,17 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - for (var method in elproto) if (elproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname][apply](el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname][apply](el, arg); + }); + }; + })(method); + } } setproto.attr = function (name, value) { if (name && R.is(name, array) && R.is(name[0], "object")) { @@ -26477,7 +26280,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Set.clear [ method ] ** @@ -26488,7 +26291,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.pop(); } }; - /*\ + /* \ * Set.splice [ method ] ** @@ -26527,7 +26330,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return new Set(todel); }; - /*\ + /* \ * Set.exclude [ method ] ** @@ -26539,9 +26342,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (boolean) `true` if object was found & removed from the set \*/ setproto.exclude = function (el) { - for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) { - this.splice(i, 1); - return true; + for (var i = 0, ii = this.length; i < ii; i++) { + if (this[i] == el) { + this.splice(i, 1); + return true; + } } }; setproto.animate = function (params, ms, easing, callback) { @@ -26578,12 +26383,14 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I y = [], x2 = [], y2 = []; - for (var i = this.items.length; i--;) if (!this.items[i].removed) { - var box = this.items[i].getBBox(); - x.push(box.x); - y.push(box.y); - x2.push(box.x + box.width); - y2.push(box.y + box.height); + for (var i = this.items.length; i--;) { + if (!this.items[i].removed) { + var box = this.items[i].getBBox(); + x.push(box.x); + y.push(box.y); + x2.push(box.x + box.width); + y2.push(box.y + box.height); + } } x = mmin[apply](0, x); y = mmin[apply](0, y); @@ -26609,12 +26416,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return "Rapha\xebl\u2018s set"; }; - setproto.glow = function(glowConfig) { + setproto.glow = function (glowConfig) { var ret = this.paper.set(); - this.forEach(function(shape, index){ + this.forEach(function (shape, index) { var g = shape.glow(glowConfig); - if(g != null){ - g.forEach(function(shape2, index2){ + if(g != null) { + g.forEach(function (shape2, index2) { ret.push(shape2); }); } @@ -26623,7 +26430,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; - /*\ + /* \ * Set.isPointInside [ method ] ** @@ -26646,7 +26453,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return isPointInside; }; - /*\ + /* \ * Raphael.registerFont [ method ] ** @@ -26672,8 +26479,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I glyphs: {} }, family = font.face["font-family"]; - for (var prop in font.face) if (font.face[has](prop)) { - fontcopy.face[prop] = font.face[prop]; + for (var prop in font.face) { + if (font.face[has](prop)) { + fontcopy.face[prop] = font.face[prop]; + } } if (this.fonts[family]) { this.fonts[family].push(fontcopy); @@ -26682,25 +26491,29 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (!font.svg) { fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10); - for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) { - var path = font.glyphs[glyph]; - fontcopy.glyphs[glyph] = { - w: path.w, - k: {}, - d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) { - return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M"; - }) + "z" - }; - if (path.k) { - for (var k in path.k) if (path[has](k)) { - fontcopy.glyphs[glyph].k[k] = path.k[k]; + for (var glyph in font.glyphs) { + if (font.glyphs[has](glyph)) { + var path = font.glyphs[glyph]; + fontcopy.glyphs[glyph] = { + w: path.w, + k: {}, + d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) { + return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M"; + }) + "z" + }; + if (path.k) { + for (var k in path.k) { + if (path[has](k)) { + fontcopy.glyphs[glyph].k[k] = path.k[k]; + } + } } } } } return font; }; - /*\ + /* \ * Paper.getFont [ method ] ** @@ -26726,10 +26539,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var font = R.fonts[family]; if (!font) { var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i"); - for (var fontName in R.fonts) if (R.fonts[has](fontName)) { - if (name.test(fontName)) { - font = R.fonts[fontName]; - break; + for (var fontName in R.fonts) { + if (R.fonts[has](fontName)) { + if (name.test(fontName)) { + font = R.fonts[fontName]; + break; + } } } } @@ -26744,7 +26559,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return thefont; }; - /*\ + /* \ * Paper.print [ method ] ** @@ -26805,7 +26620,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); }; - /*\ + /* \ * Paper.add [ method ] ** @@ -26847,7 +26662,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return res; }; - /*\ + /* \ * Raphael.format [ method ] ** @@ -26873,7 +26688,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I })); return token || E; }; - /*\ + /* \ * Raphael.fullfill [ method ] ** @@ -26907,7 +26722,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (name in res) { res = res[name]; } - typeof res == "function" && isFunc && (res = res()); + typeof res === "function" && isFunc && (res = res()); } }); res = (res == null || res == obj ? all : res) + ""; @@ -26919,7 +26734,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); }; })(); - /*\ + /* \ * Raphael.ninja [ method ] ** @@ -26937,7 +26752,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael; return R; }; - /*\ + /* \ * Raphael.st [ property (object) ] ** @@ -26965,14 +26780,14 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html (function (doc, loaded, f) { - if (doc.readyState == null && doc.addEventListener){ + if (doc.readyState == null && doc.addEventListener) { doc.addEventListener(loaded, f = function () { doc.removeEventListener(loaded, f, false); doc.readyState = "complete"; }, false); doc.readyState = "loading"; } - function isLoaded() { + function isLoaded () { (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload"); } isLoaded(); @@ -26993,7 +26808,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.svg", ["raphael.core"], function(raphael) { + define("raphael.svg", ["raphael.core"], function (raphael) { return factory(raphael); }); } else if (typeof exports === "object") { @@ -27001,7 +26816,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } else { factory(glob.Raphael); } -}(this, function(R) { +}(this, function (R) { if (R && !R.svg) { return; } @@ -27032,14 +26847,16 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; var $ = function (el, attr) { if (attr) { - if (typeof el == "string") { + if (typeof el === "string") { el = $(el); } - for (var key in attr) if (attr[has](key)) { - if (key.substring(0, 6) == "xlink:") { - el.setAttributeNS(xlink, key.substring(6), Str(attr[key])); - } else { - el.setAttribute(key, Str(attr[key])); + for (var key in attr) { + if (attr[has](key)) { + if (key.substring(0, 6) == "xlink:") { + el.setAttributeNS(xlink, key.substring(6), Str(attr[key])); + } else { + el.setAttribute(key, Str(attr[key])); + } } } } else { @@ -27271,9 +27088,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I delete o._.arrows[se + "Type"]; delete o._.arrows[se + "String"]; } - for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) { - var item = R._g.doc.getElementById(attr); - item && item.parentNode.removeChild(item); + for (attr in markerCounter) { + if (markerCounter[has](attr) && !markerCounter[attr]) { + var item = R._g.doc.getElementById(attr); + item && item.parentNode.removeChild(item); + } } } }, @@ -27300,8 +27119,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt; } $(o.node, {"stroke-dasharray": dashes.join(",")}); - } - else { + } else { $(o.node, {"stroke-dasharray": "none"}); } }, @@ -27587,10 +27405,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } } else { tspans = node.getElementsByTagName("tspan"); - for (i = 0, ii = tspans.length; i < ii; i++) if (i) { - $(tspans[i], {dy: fontSize * leading, x: a.x}); - } else { - $(tspans[0], {dy: 0}); + for (i = 0, ii = tspans.length; i < ii; i++) { + if (i) { + $(tspans[i], {dy: fontSize * leading, x: a.x}); + } else { + $(tspans[0], {dy: 0}); + } } } $(node, {x: a.x, y: a.y}); @@ -27602,14 +27422,14 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I getRealNode = function (node) { if (node.parentNode && node.parentNode.tagName.toLowerCase() === "a") { return node.parentNode; - } else { - return node; } + return node; + }, Element = function (node, svg) { var X = 0, Y = 0; - /*\ + /* \ * Element.node [ property (object) ] ** @@ -27624,7 +27444,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I | }; \*/ this[0] = this.node = node; - /*\ + /* \ * Element.raphael [ property (object) ] ** @@ -27637,7 +27457,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I | } \*/ node.raphael = true; - /*\ + /* \ * Element.id [ property (number) ] ** @@ -27648,7 +27468,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I node.raphaelid = this.id; this.matrix = R.matrix(); this.realPath = null; - /*\ + /* \ * Element.paper [ property (object) ] ** @@ -27672,7 +27492,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I dirty: 1 }; !svg.bottom && (svg.bottom = this); - /*\ + /* \ * Element.prev [ property (object) ] ** @@ -27681,7 +27501,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.prev = svg.top; svg.top && (svg.top.next = this); svg.top = this; - /*\ + /* \ * Element.next [ property (object) ] ** @@ -27706,7 +27526,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); return p; }; - /*\ + /* \ * Element.rotate [ method ] ** @@ -27739,7 +27559,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.transform(this._.transform.concat([["r", deg, cx, cy]])); return this; }; - /*\ + /* \ * Element.scale [ method ] ** @@ -27775,7 +27595,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.transform(this._.transform.concat([["s", sx, sy, cx, cy]])); return this; }; - /*\ + /* \ * Element.translate [ method ] ** @@ -27799,7 +27619,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.transform(this._.transform.concat([["t", dx, dy]])); return this; }; - /*\ + /* \ * Element.transform [ method ] ** @@ -27854,7 +27674,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return this; }; - /*\ + /* \ * Element.hide [ method ] ** @@ -27865,7 +27685,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if(!this.removed) this.node.style.display = "none"; return this; }; - /*\ + /* \ * Element.show [ method ] ** @@ -27876,7 +27696,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if(!this.removed) this.node.style.display = ""; return this; }; - /*\ + /* \ * Element.remove [ method ] ** @@ -27901,7 +27721,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.removeData(); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } this.removed = true; }; @@ -27914,7 +27734,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I containerStyle; if (this.paper.canvas.parentElement) { containerStyle = this.paper.canvas.parentElement.style; - } //IE10+ can't find parentElement + } // IE10+ can't find parentElement else if (this.paper.canvas.parentNode) { containerStyle = this.paper.canvas.parentNode.style; } @@ -27933,17 +27753,17 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I y: this.node.clientTop, width: this.node.clientWidth, height: this.node.clientHeight - } + }; } finally { bbox = bbox || {}; - if(canvasHidden){ + if(canvasHidden) { containerStyle.display = "none"; } } hide && this.hide(); return bbox; }; - /*\ + /* \ * Element.attr [ method ] ** @@ -28030,8 +27850,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (name == null) { var res = {}; - for (var a in this.attrs) if (this.attrs[has](a)) { - res[a] = this.attrs[a]; + for (var a in this.attrs) { + if (this.attrs[has](a)) { + res[a] = this.attrs[a]; + } } res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient; res.transform = this._.transform; @@ -28074,17 +27896,21 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I for (var key in params) { eve("raphael.attr." + key + "." + this.id, this, params[key]); } - for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { - var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); - this.attrs[key] = params[key]; - for (var subkey in par) if (par[has](subkey)) { - params[subkey] = par[subkey]; + for (key in this.paper.customAttributes) { + if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { + var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); + this.attrs[key] = params[key]; + for (var subkey in par) { + if (par[has](subkey)) { + params[subkey] = par[subkey]; + } + } } } setFillAndStroke(this, params); return this; }; - /*\ + /* \ * Element.toFront [ method ] ** @@ -28101,7 +27927,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I svg.top != this && R._tofront(this, svg); return this; }; - /*\ + /* \ * Element.toBack [ method ] ** @@ -28119,7 +27945,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var svg = this.paper; return this; }; - /*\ + /* \ * Element.insertAfter [ method ] ** @@ -28141,7 +27967,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R._insertafter(this, element, this.paper); return this; }; - /*\ + /* \ * Element.insertBefore [ method ] ** @@ -28325,7 +28151,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this._viewBox = [x, y, w, h, !!fit]; return this; }; - /*\ + /* \ * Paper.renderfix [ method ] ** @@ -28357,7 +28183,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } } }; - /*\ + /* \ * Paper.clear [ method ] ** @@ -28374,7 +28200,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I c.appendChild(this.desc); c.appendChild(this.defs = $("defs")); }; - /*\ + /* \ * Paper.remove [ method ] ** @@ -28384,19 +28210,21 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve("raphael.remove", this); this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } }; var setproto = R.st; - for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname].apply(el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method) && !setproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname].apply(el, arg); + }); + }; + })(method); + } } })); @@ -28412,7 +28240,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.vml", ["raphael.core"], function(raphael) { + define("raphael.vml", ["raphael.core"], function (raphael) { return factory(raphael); }); } else if (typeof exports === "object") { @@ -28420,7 +28248,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } else { factory(glob.Raphael); } -}(this, function(R) { +}(this, function (R) { if (R && !R.vml) { return; } @@ -28573,8 +28401,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I res = o; - for (var par in params) if (params[has](par)) { - a[par] = params[par]; + for (var par in params) { + if (params[has](par)) { + a[par] = params[par]; + } } if (newpath) { a.path = R._getPath[o.type](o); @@ -28629,7 +28459,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (o.textpath) { var textpathStyle = o.textpath.style; params.font && (textpathStyle.font = params.font); - params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"'); + params["font-family"] && (textpathStyle.fontFamily = "\"" + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + "\""); params["font-size"] && (textpathStyle.fontSize = params["font-size"]); params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]); params["font-style"] && (textpathStyle.fontStyle = params["font-style"]); @@ -28762,9 +28592,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I ("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1)); var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"]; - for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) { - res._.dirty = 1; - break; + for (var d = 0, dd = dirtyattrs.length; d < dd; d++) { + if (dirtyattrs[d] in params) { + res._.dirty = 1; + break; + } } // text-anchor emulation @@ -28994,12 +28826,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; // Needed to fix the vml setViewBox issues elproto.auxGetBBox = R.el.getBBox; - elproto.getBBox = function(){ + elproto.getBBox = function () { var b = this.auxGetBBox(); - if (this.paper && this.paper._viewBoxShift) - { + if (this.paper && this.paper._viewBoxShift) { var c = {}; - var z = 1/this.paper._viewBoxShift.scale; + var z = 1 / this.paper._viewBoxShift.scale; c.x = b.x - this.paper._viewBoxShift.dx; c.x *= z; c.y = b.y - this.paper._viewBoxShift.dy; @@ -29033,7 +28864,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.node.parentNode.removeChild(this.node); this.shape && this.shape.parentNode.removeChild(this.shape); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } this.removed = true; }; @@ -29043,8 +28874,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (name == null) { var res = {}; - for (var a in this.attrs) if (this.attrs[has](a)) { - res[a] = this.attrs[a]; + for (var a in this.attrs) { + if (this.attrs[has](a)) { + res[a] = this.attrs[a]; + } } res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient; res.transform = this._.transform; @@ -29085,11 +28918,15 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve("raphael.attr." + key + "." + this.id, this, params[key]); } if (params) { - for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { - var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); - this.attrs[key] = params[key]; - for (var subkey in par) if (par[has](subkey)) { - params[subkey] = par[subkey]; + for (key in this.paper.customAttributes) { + if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { + var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); + this.attrs[key] = params[key]; + for (var subkey in par) { + if (par[has](subkey)) { + params[subkey] = par[subkey]; + } + } } } // this.paper.canvas.style.display = "none"; @@ -29339,11 +29176,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I try { !doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml"); createNode = function (tagName) { - return doc.createElement(''); + return doc.createElement(""); }; } catch (e) { createNode = function (tagName) { - return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">'); + return doc.createElement("<" + tagName + " xmlns=\"urn:schemas-microsoft.com:vml\" class=\"rvml\">"); }; } }; @@ -29403,21 +29240,23 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.eve("raphael.remove", this); this.canvas.parentNode.removeChild(this.canvas); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } return true; }; var setproto = R.st; - for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname].apply(el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method) && !setproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname].apply(el, arg); + }); + }; + })(method); + } } })); @@ -29432,7 +29271,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael", ["raphael.core", "raphael.svg", "raphael.vml"], function(Raphael) { + define("raphael", ["raphael.core", "raphael.svg", "raphael.vml"], function (Raphael) { return factory(Raphael); }); } else if (typeof exports === "object") { @@ -29443,7 +29282,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I module.exports = factory(raphael); } else { - //glob.Raphael = factory(glob.Raphael); + // glob.Raphael = factory(glob.Raphael); } }(this, function (Raphael) { return Raphael.ninja(); @@ -29459,7 +29298,7 @@ BI.Svg = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Svg.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-svg" - }) + }); }, _init: function () { @@ -29467,7 +29306,7 @@ BI.Svg = BI.inherit(BI.Widget, { this.paper = Raphael(this.element[0]); this.element.css("overflow", "hidden"); - $(this.paper.canvas).width("100%").height("100%").css({"left": "0", "top": "0"}).appendTo(this.element); + $(this.paper.canvas).width("100%").height("100%").css({left: "0", top: "0"}).appendTo(this.element); this.top = this.paper.top; this.bottom = this.paper.bottom; @@ -29571,12 +29410,12 @@ BI.NativeTableScrollbar = BI.inherit(BI.Widget, { defaultPosition: 0, position: 0, size: 0 - }) + }); }, render: function () { var self = this, o = this.options; - //把滚动台size改掉 + // 把滚动台size改掉 this.element.width(36); var throttle = BI.throttle(function () { @@ -29595,7 +29434,7 @@ BI.NativeTableScrollbar = BI.inherit(BI.Widget, { self.inner = _ref; } }] - } + }; }, mounted: function () { @@ -29647,12 +29486,12 @@ BI.NativeTableHorizontalScrollbar = BI.inherit(BI.Widget, { contentSize: 0, position: 0, size: 0 - }) + }); }, render: function () { var self = this, o = this.options; - //把滚动台size改掉 + // 把滚动台size改掉 this.element.height(36); var throttle = BI.throttle(function () { @@ -29671,7 +29510,7 @@ BI.NativeTableHorizontalScrollbar = BI.inherit(BI.Widget, { self.inner = _ref; } }] - } + }; }, setContentSize: function (contentSize) { @@ -29721,7 +29560,7 @@ BI.TableCell = BI.inherit(BI.Widget, { baseCls: "bi-table-cell", textAlign: "left", text: "" - }) + }); }, _init: function () { @@ -29735,7 +29574,7 @@ BI.TableCell = BI.inherit(BI.Widget, { text: this.options.text, value: this.options.value, lgap: 5 - }) + }); } }); @@ -29756,7 +29595,7 @@ BI.CollectionTableCell = BI.inherit(BI.Widget, { _left: 0, _top: 0, cell: {} - }) + }); }, _init: function () { @@ -30069,7 +29908,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { overflow: "scroll", overflowX: "scroll", overflowY: "scroll" - }) + }); }; this.topLeft.setWidth(otlw); @@ -30127,7 +29966,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { _digest: function () { var o = this.options; var freezeColLength = this._getFreezeColLength(); - //如果表头位置不够,取消表头冻结 + // 如果表头位置不够,取消表头冻结 if (this._getFreezeHeaderHeight() <= 0) { this.topLeftItems = []; this.topRightItems = []; @@ -30217,7 +30056,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { var isNeedMergeCol = o.mergeRule(cache[i][j], cache[i][j - 1]); if (isNeedMergeCol && isNeedMergeRow) { continue; - //mergeRow(i, j);//优先合并列 + // mergeRow(i, j);//优先合并列 } if (isNeedMergeCol) { mergeCol(i, j); @@ -30242,7 +30081,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { col: item.item._col, width: item.item._width, height: item.item._height - } + }; }); }, @@ -30352,7 +30191,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { this._restore(); } }); -BI.shortcut('bi.collection_table', BI.CollectionTable);/** +BI.shortcut("bi.collection_table", BI.CollectionTable);/** * QuickCollectionTable * * Created by GUY on 2016/1/12. @@ -30419,25 +30258,25 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { _shouldHandleLeftX: function (delta) { if (delta > 0) { return this.bottomLeftCollection.getScrollLeft() < this.bottomLeftCollection.getMaxScrollLeft(); - } else { - return this.bottomLeftCollection.getScrollLeft() > 0; } + return this.bottomLeftCollection.getScrollLeft() > 0; + }, _shouldHandleRightX: function (delta) { if (delta > 0) { return this.bottomRightCollection.getScrollLeft() < this.bottomRightCollection.getMaxScrollLeft(); - } else { - return this.bottomRightCollection.getScrollLeft() > 0; } + return this.bottomRightCollection.getScrollLeft() > 0; + }, _shouldHandleY: function (delta) { if (delta > 0) { return this.bottomRightCollection.getScrollTop() < this.bottomRightCollection.getMaxScrollTop(); - } else { - return this.bottomRightCollection.getScrollTop() > 0; } + return this.bottomRightCollection.getScrollTop() > 0; + }, _onWheelLeft: function (deltaX, deltaY) { @@ -30471,7 +30310,7 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { _populateTable: function () { var self = this, o = this.options; var regionSize = this.getRegionSize(), totalLeftColumnSize = 0, totalRightColumnSize = 0, totalColumnSize = 0, - summaryColumnSizeArray = [] + summaryColumnSizeArray = []; BI.each(o.columnSize, function (i, size) { if (o.isNeedFreeze === true && o.freezeCols.contains(i)) { totalLeftColumnSize += size; @@ -30542,7 +30381,7 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { this.bottomRightCollection.populate(rightItems); } }); -BI.shortcut('bi.quick_collection_table', BI.QuickCollectionTable);/** +BI.shortcut("bi.quick_collection_table", BI.QuickCollectionTable);/** * * 表格单元格 * @@ -30561,7 +30400,7 @@ BI.GridTableCell = BI.inherit(BI.Widget, { _left: 0, _top: 0, cell: {} - }) + }); }, _init: function () { @@ -30922,7 +30761,7 @@ BI.GridTable = BI.inherit(BI.Widget, { overflow: "scroll", overflowX: "scroll", overflowY: "scroll" - }) + }); }; this.topLeft.setWidth(otlw); @@ -31078,7 +30917,7 @@ BI.GridTable = BI.inherit(BI.Widget, { this._restore(); } }); -BI.shortcut('bi.grid_table', BI.GridTable);/** +BI.shortcut("bi.grid_table", BI.GridTable);/** * QuickGridTable * * Created by GUY on 2016/1/12. @@ -31145,25 +30984,25 @@ BI.QuickGridTable = BI.inherit(BI.GridTable, { _shouldHandleLeftX: function (delta) { if (delta > 0) { return this.bottomLeftGrid.getScrollLeft() < this.bottomLeftGrid.getMaxScrollLeft(); - } else { - return this.bottomLeftGrid.getScrollLeft() > 0; } + return this.bottomLeftGrid.getScrollLeft() > 0; + }, _shouldHandleRightX: function (delta) { if (delta > 0) { return this.bottomRightGrid.getScrollLeft() < this.bottomRightGrid.getMaxScrollLeft(); - } else { - return this.bottomRightGrid.getScrollLeft() > 0; } + return this.bottomRightGrid.getScrollLeft() > 0; + }, _shouldHandleY: function (delta) { if (delta > 0) { return this.bottomRightGrid.getScrollTop() < this.bottomRightGrid.getMaxScrollTop(); - } else { - return this.bottomRightGrid.getScrollTop() > 0; } + return this.bottomRightGrid.getScrollTop() > 0; + }, _onWheelLeft: function (deltaX, deltaY) { @@ -31300,7 +31139,7 @@ BI.QuickGridTable = BI.inherit(BI.GridTable, { this.bottomRightGrid.populate(rightItems); } }); -BI.shortcut('bi.quick_grid_table', BI.QuickGridTable);/** +BI.shortcut("bi.quick_grid_table", BI.QuickGridTable);/** * * 表格滚动条 * @@ -31327,7 +31166,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { orientation: "vertical", position: 0, size: 0 - }) + }); }, render: function () { @@ -31352,7 +31191,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { mounted: function () { var self = this, o = this.options; - var onWheel = o.orientation === 'horizontal' ? this._onWheelX : this._onWheelY; + var onWheel = o.orientation === "horizontal" ? this._onWheelX : this._onWheelY; this._wheelHandler = new BI.WheelHandler( BI.bind(onWheel, this), BI.bind(this._shouldHandleX, this), @@ -31385,7 +31224,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { }, _isHorizontal: function () { - return this.options.orientation === 'horizontal' + return this.options.orientation === "horizontal"; }, _getScale: function () { @@ -31411,13 +31250,13 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { }, _shouldHandleX: function (delta) { - return this.options.orientation === 'horizontal' ? + return this.options.orientation === "horizontal" ? this._shouldHandleChange(delta) : false; }, _shouldHandleY: function (delta) { - return this.options.orientation !== 'horizontal' ? + return this.options.orientation !== "horizontal" ? this._shouldHandleChange(delta) : false; }, @@ -31651,7 +31490,7 @@ BI.GridTableHorizontalScrollbar = BI.inherit(BI.Widget, { contentSize: 0, position: 0, size: 0 - }) + }); }, _init: function () { @@ -31732,7 +31571,7 @@ BI.TableHeaderCell = BI.inherit(BI.Widget, { return BI.extend(BI.TableHeaderCell.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-table-header-cell", text: "" - }) + }); }, _init: function () { @@ -31744,7 +31583,7 @@ BI.TableHeaderCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); @@ -31763,16 +31602,16 @@ BI.Table = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Table.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-table", - logic: { //冻结的页面布局逻辑 + logic: { // 冻结的页面布局逻辑 dynamic: false }, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 - mergeRule: function (row1, row2) { //合并规则, 默认相等时合并 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 + mergeRule: function (row1, row2) { // 合并规则, 默认相等时合并 return BI.isEqual(row1, row2); }, @@ -31785,8 +31624,8 @@ BI.Table = BI.inherit(BI.Widget, { header: [], footer: false, - items: [] //二维数组 - }) + items: [] // 二维数组 + }); }, _calculateWidth: function (width) { @@ -32076,17 +31915,17 @@ BI.Table = BI.inherit(BI.Widget, { var regionColumnSize = o.regionColumnSize; if (o.freezeCols.length === 0) { - regionColumnSize = isRight ? ['fill', 0] : [0, 'fill']; + regionColumnSize = isRight ? ["fill", 0] : [0, "fill"]; } else if (o.freezeCols.length >= o.columnSize.length) { - regionColumnSize = isRight ? [0, 'fill'] : ['fill', 0]; + regionColumnSize = isRight ? [0, "fill"] : ["fill", 0]; } this.partitions = BI.createWidget(BI.extend({ element: this }, BI.LogicFactory.createLogic("table", BI.extend({}, o.logic, { rows: 2, columns: 2, - columnSize: regionColumnSize || (isRight ? ['fill', leftWidth] : [leftWidth, 'fill']), - rowSize: [headerHeight, 'fill'], + columnSize: regionColumnSize || (isRight ? ["fill", leftWidth] : [leftWidth, "fill"]), + rowSize: [headerHeight, "fill"], items: [[{ el: this.topLeft }, { @@ -32115,7 +31954,7 @@ BI.Table = BI.inherit(BI.Widget, { scroll(this.scrollBottomRight.element, this.scrollTopRight.element, this.scrollBottomLeft.element); // scroll(this.scrollBottomLeft.element, this.scrollTopLeft.element, this.scrollBottomRight.element); - function scroll(scrollElement, scrollTopElement, otherElement) { + function scroll (scrollElement, scrollTopElement, otherElement) { scrollElement.scroll(function (e) { otherElement.scrollTop(scrollElement.scrollTop()); scrollTopElement.scrollLeft(scrollElement.scrollLeft()); @@ -32192,10 +32031,10 @@ BI.Table = BI.inherit(BI.Widget, { createOneEl(i, j); } }); - function mergeRow(i, j) { + function mergeRow (i, j) { var height = (preCol[j].attr("height") | 0) + rowSize + 1; preCol[j].attr("height", height).css("height", height); - //preCW[j].element.css("height", height); + // preCW[j].element.css("height", height); var rowspan = ((preCol[j].attr("rowspan") || 1) | 0) + 1; preCol[j].attr("rowspan", rowspan); preCol[j].__mergeRows.pushDistinct(i); @@ -32203,7 +32042,7 @@ BI.Table = BI.inherit(BI.Widget, { Ws[i][j] = preCW[j]; } - function mergeCol(i, j) { + function mergeCol (i, j) { if (columnSize[j]) { var width = preRow[i].attr("width") | 0; if (width > 1.05 && columnSize[j]) { @@ -32212,7 +32051,7 @@ BI.Table = BI.inherit(BI.Widget, { width--; } } else { - width = width + columnSize[j] + width = width + columnSize[j]; } width = self._calculateWidth(width); preRow[i].attr("width", width).css("width", width); @@ -32225,14 +32064,14 @@ BI.Table = BI.inherit(BI.Widget, { Ws[i][j] = preRW[i]; } - function createOneEl(r, c) { + function createOneEl (r, c) { var width = self._calculateWidth(columnSize[c]); if (width > 1.05 && c === columnSize.length - 1) { width--; } var height = self._calculateHeight(rowSize); var td = $("").attr("height", height) - .attr("width", width).css({"width": width, "height": height, "position": "relative"}) + .attr("width", width).css({width: width, height: height, position: "relative"}) .addClass((c & 1) === 0 ? "odd-col" : "even-col") .addClass(r === 0 ? "first-row" : "") .addClass(c === 0 ? "first-col" : "") @@ -32403,12 +32242,12 @@ BI.Table = BI.inherit(BI.Widget, { } else { (isRight ? left : right)[i].push(cell); } - }) + }); }); return { left: left, right: right - } + }; }, _table: function () { @@ -32416,7 +32255,7 @@ BI.Table = BI.inherit(BI.Widget, { type: "bi.layout", tagName: "table", cls: "table", - attribute: {"cellspacing": 0, "cellpadding": 0} + attribute: {cellspacing: 0, cellpadding: 0} }); }, @@ -32570,7 +32409,7 @@ BI.Table = BI.inherit(BI.Widget, { } }); } - }) + }); }; run(topleft); run(topright); @@ -32830,21 +32669,21 @@ BI.Table = BI.inherit(BI.Widget, { if (o.isNeedFreeze === true) { if (BI.size(this.bottomLeftBodyTds) > 0 || BI.size(this.bottomRightBodyTds) > 0) { if (!BI.any(this.bottomLeftBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.bottomLeftBodyTds[0], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.bottomLeftBodyTds[0]) - 1) { @@ -32854,21 +32693,21 @@ BI.Table = BI.inherit(BI.Widget, { }); } if (!BI.any(this.bottomRightBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.bottomRightBodyTds[0], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.bottomRightBodyTds[0]) - 1) { @@ -32880,21 +32719,21 @@ BI.Table = BI.inherit(BI.Widget, { return columnSize; } if (!BI.any(this.topLeftBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.topLeftBodyTds[BI.size(this.topLeftBodyTds) - 1], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.topLeftBodyTds[BI.size(self.topLeftBodyTds) - 1]) - 1) { @@ -32904,21 +32743,21 @@ BI.Table = BI.inherit(BI.Widget, { }); } if (!BI.any(this.topRightBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.topRightBodyTds[BI.size(this.topRightBodyTds) - 1], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.topRightBodyTds[BI.size(self.topRightBodyTds) - 1]) - 1) { @@ -33041,7 +32880,7 @@ BI.Table = BI.inherit(BI.Widget, { } }); } - }) + }); }; run(topleft); run(topright); @@ -33154,7 +32993,7 @@ BI.Table = BI.inherit(BI.Widget, { o.regionColumnSize = columnSize; if (o.freezeCols.length === 0) { if (o.isNeedFreeze) { - this.partitions.attr("columnSize", this._isRightFreeze() ? ['fill', 0] : [0, 'fill']); + this.partitions.attr("columnSize", this._isRightFreeze() ? ["fill", 0] : [0, "fill"]); this.partitions.resize(); } else { this.tableContainer.element.width(columnSize[0]); @@ -33168,7 +33007,7 @@ BI.Table = BI.inherit(BI.Widget, { } } else { if (o.isNeedFreeze) { - this.partitions.attr("columnSize", this._isRightFreeze() ? [0, 'fill'] : ['fill', 0]); + this.partitions.attr("columnSize", this._isRightFreeze() ? [0, "fill"] : ["fill", 0]); this.partitions.resize(); } else { this.tableContainer.element.width(columnSize[0]); @@ -33225,9 +33064,9 @@ BI.Table = BI.inherit(BI.Widget, { if (o.isNeedFreeze) { if (o.freezeCols.length < o.columnSize.length) { return [this.scrollTopRight.element[0].scrollHeight, this.scrollBottomRight.element[0].scrollHeight]; - } else { - return [this.scrollTopLeft.element[0].scrollHeight, this.scrollBottomLeft.element[0].scrollHeight]; } + return [this.scrollTopLeft.element[0].scrollHeight, this.scrollBottomLeft.element[0].scrollHeight]; + } return [this.scrollBottomRight.element[0].scrollHeight]; }, @@ -33320,14 +33159,14 @@ BI.Table = BI.inherit(BI.Widget, { topRight: this.topRightBodyItems, bottomLeft: this.bottomLeftBodyItems, bottomRight: this.bottomRightBodyItems - } - } else { - return { - header: this.headerItems, - body: this.bodyItems, - footer: this.footerItems - } + }; } + return { + header: this.headerItems, + body: this.bodyItems, + footer: this.footerItems + }; + }, populate: function (items, header) { @@ -33374,7 +33213,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { start: BI.emptyFn, resize: BI.emptyFn, stop: BI.emptyFn - }) + }); }, _init: function () { @@ -33385,7 +33224,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { var startDrag = false; var size = 0, offset = 0, defaultSize = o.width; - function optimizeSize(s) { + function optimizeSize (s) { var optSize = BI.clamp(s, o.minSize, o.maxSize || Number.MAX_VALUE); // if (o.suitableSize) { // if (Math.abs(o.suitableSize - optSize) < 5) { @@ -33454,7 +33293,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { top: 0, bottom: 0 }] - }) + }); }, setWidth: function (width) { @@ -33489,7 +33328,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { isResizeAdapt: false, headerRowSize: 25, rowSize: 25, - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, columnSize: [], @@ -33499,7 +33338,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { header: [], items: [], regionColumnSize: [] - }) + }); }, _init: function () { @@ -33688,7 +33527,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { self.resizer.setVisible(true); var height = o.headerRowSize + self._getRegionRowSize()[1]; self.resizer.setHeight(height); - //TODO 不知道为什么加入这段代码会使得列宽调整出问题 + // TODO 不知道为什么加入这段代码会使得列宽调整出问题 // if (o.minColumnSize[j]) { // if (size === o.minColumnSize[j]) { // self.resizer.element.addClass("suitable"); @@ -33759,7 +33598,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { setWidth: function (width) { BI.ResizableTable.superclass.setWidth.apply(this, arguments); - this.table.setWidth(width) + this.table.setWidth(width); }, setHeight: function (height) { @@ -33797,1901 +33636,1898 @@ BI.ResizableTable = BI.inherit(BI.Widget, { return this.table.getRegionColumnSize(); }, - getVerticalScroll: function () { - return this.table.getVerticalScroll(); + getVerticalScroll: function () { + return this.table.getVerticalScroll(); + }, + + getLeftHorizontalScroll: function () { + return this.table.getLeftHorizontalScroll(); + }, + + getRightHorizontalScroll: function () { + return this.table.getRightHorizontalScroll(); + }, + + attr: function () { + BI.ResizableTable.superclass.attr.apply(this, arguments); + this.table.attr.apply(this.table, arguments); + }, + + restore: function () { + this.table.restore(); + }, + + populate: function (items, header) { + if (items) { + this.options.items = items; + } + if (header) { + this.options.header = header; + if (this.options.isNeedResize) { + header = this._formatHeader(header); + } + } + this.table.populate(items, header); + this._populate(); + } +}); + +BI.shortcut("bi.resizable_table", BI.ResizableTable);/** + * + * 自定义树 + * + * Created by GUY on 2015/9/7. + * @class BI.CustomTree + * @extends BI.Single + */ +BI.CustomTree = BI.inherit(BI.Widget, { + _defaultConfig: function () { + return BI.extend(BI.CustomTree.superclass._defaultConfig.apply(this, arguments), { + baseCls: "bi-custom-tree", + expander: { + el: {}, + popup: { + type: "bi.custom_tree" + } + }, + + items: [], + itemsCreator: BI.emptyFn, + + el: { + type: "bi.button_tree", + chooseType: 0, + layouts: [{ + type: "bi.vertical" + }] + } + }); + }, + + _init: function () { + BI.CustomTree.superclass._init.apply(this, arguments); + this.initTree(this.options.items); + }, + + _formatItems: function (nodes) { + var self = this, o = this.options; + nodes = BI.Tree.transformToTreeFormat(nodes); + + var items = []; + BI.each(nodes, function (i, node) { + if (BI.isNotEmptyArray(node.children) || node.isParent === true) { + var item = BI.extend({ + type: "bi.expander", + el: {}, + popup: {type: "bi.custom_tree"} + }, BI.deepClone(o.expander), { + id: node.id, + pId: node.pId, + value: node.value + }); + var el = BI.stripEL(node); + if (!BI.isWidget(el)) { + el = BI.clone(el); + delete el.children; + BI.extend(item.el, el); + } else { + item.el = el; + } + item.popup.expander = BI.deepClone(o.expander); + item.items = item.popup.items = node.children; + item.itemsCreator = item.popup.itemsCreator = function (op) { + if (BI.isNotNull(op.node)) {// 从子节点传过来的itemsCreator直接向上传递 + return o.itemsCreator.apply(self, arguments); + } + var args = Array.prototype.slice.call(arguments, 0); + args[0].node = node; + return o.itemsCreator.apply(self, args); + }; + BI.isNull(item.popup.el) && (item.popup.el = BI.deepClone(o.el)); + items.push(item); + } else { + items.push(node); + } + }); + return items; + }, + + // 构造树结构, + initTree: function (nodes) { + var self = this, o = this.options; + this.tree = BI.createWidget(o.el, { + element: this, + items: this._formatItems(nodes), + itemsCreator: function (op, callback) { + o.itemsCreator.apply(this, [op, function (items) { + var args = Array.prototype.slice.call(arguments, 0); + args[0] = self._formatItems(items); + callback.apply(null, args); + }]); + } + }); + this.tree.on(BI.Controller.EVENT_CHANGE, function (type, val, obj) { + self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + if (type === BI.Events.CLICK) { + self.fireEvent(BI.CustomTree.EVENT_CHANGE, val, obj); + } + }); + }, + + // 生成树方法 + stroke: function (nodes) { + this.populate.apply(this, arguments); + }, + + populate: function (nodes) { + var args = Array.prototype.slice.call(arguments, 0); + if (arguments.length > 0) { + args[0] = this._formatItems(nodes); + } + this.tree.populate.apply(this.tree, args); + }, + + setValue: function (v) { + this.tree && this.tree.setValue(v); + }, + + getValue: function () { + return this.tree ? this.tree.getValue() : []; }, - getLeftHorizontalScroll: function () { - return this.table.getLeftHorizontalScroll(); + getAllButtons: function () { + return this.tree ? this.tree.getAllButtons() : []; }, - getRightHorizontalScroll: function () { - return this.table.getRightHorizontalScroll(); + getAllLeaves: function () { + return this.tree ? this.tree.getAllLeaves() : []; }, - attr: function () { - BI.ResizableTable.superclass.attr.apply(this, arguments); - this.table.attr.apply(this.table, arguments); + getNodeById: function (id) { + return this.tree && this.tree.getNodeById(id); }, - restore: function () { - this.table.restore(); + getNodeByValue: function (id) { + return this.tree && this.tree.getNodeByValue(id); }, - populate: function (items, header) { - if (items) { - this.options.items = items; - } - if (header) { - this.options.header = header; - if (this.options.isNeedResize) { - header = this._formatHeader(header); - } - } - this.table.populate(items, header); - this._populate(); + empty: function () { + this.tree.empty(); } }); +BI.CustomTree.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.resizable_table", BI.ResizableTable);/** +BI.shortcut("bi.custom_tree", BI.CustomTree);/* + * JQuery zTree core v3.5.18 + * http://zTree.me/ * - * 自定义树 + * Copyright (c) 2010 Hunter.z * - * Created by GUY on 2015/9/7. - * @class BI.CustomTree - * @extends BI.Single + * Licensed same as jquery - MIT License + * http://www.opensource.org/licenses/mit-license.php + * + * email: hunter.z@263.net + * Date: 2015-06-18 */ -BI.CustomTree = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.CustomTree.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-custom-tree", - expander: { - el: {}, - popup: { - type: "bi.custom_tree" +(function ($) { + var settings = {}, roots = {}, caches = {}, + // default consts of core + _consts = { + className: { + BUTTON: "button", + LEVEL: "level", + ICO_LOADING: "ico_loading", + SWITCH: "switch" + }, + event: { + NODECREATED: "ztree_nodeCreated", + CLICK: "ztree_click", + EXPAND: "ztree_expand", + COLLAPSE: "ztree_collapse", + ASYNC_SUCCESS: "ztree_async_success", + ASYNC_ERROR: "ztree_async_error", + REMOVE: "ztree_remove", + SELECTED: "ztree_selected", + UNSELECTED: "ztree_unselected" + }, + id: { + A: "_a", + ICON: "_ico", + SPAN: "_span", + SWITCH: "_switch", + UL: "_ul" + }, + line: { + ROOT: "root", + ROOTS: "roots", + CENTER: "center", + BOTTOM: "bottom", + NOLINE: "noline", + LINE: "line" + }, + folder: { + OPEN: "open", + CLOSE: "close", + DOCU: "docu" + }, + node: { + CURSELECTED: "curSelectedNode" + } + }, + // default setting of core + _setting = { + treeId: "", + treeObj: null, + view: { + addDiyDom: null, + autoCancelSelected: true, + dblClickExpand: true, + expandSpeed: "fast", + fontCss: {}, + nameIsHTML: false, + selectedMulti: true, + showIcon: true, + showLine: true, + showTitle: true, + txtSelectedEnable: false + }, + data: { + key: { + children: "children", + name: "name", + title: "", + url: "url" + }, + simpleData: { + enable: false, + idKey: "id", + pIdKey: "pId", + rootPId: null + }, + keep: { + parent: false, + leaf: false + } + }, + async: { + enable: false, + contentType: "application/x-www-form-urlencoded", + type: "post", + dataType: "text", + url: "", + autoParam: [], + otherParam: [], + dataFilter: null + }, + callback: { + beforeAsync: null, + beforeClick: null, + beforeDblClick: null, + beforeRightClick: null, + beforeMouseDown: null, + beforeMouseUp: null, + beforeExpand: null, + beforeCollapse: null, + beforeRemove: null, + + onAsyncError: null, + onAsyncSuccess: null, + onNodeCreated: null, + onClick: null, + onDblClick: null, + onRightClick: null, + onMouseDown: null, + onMouseUp: null, + onExpand: null, + onCollapse: null, + onRemove: null + } + }, + // default root of core + // zTree use root to save full data + _initRoot = function (setting) { + var r = data.getRoot(setting); + if (!r) { + r = {}; + data.setRoot(setting, r); + } + r[setting.data.key.children] = []; + r.expandTriggerFlag = false; + r.curSelectedList = []; + r.noSelection = true; + r.createdNodes = []; + r.zId = 0; + r._ver = (new Date()).getTime(); + }, + // default cache of core + _initCache = function (setting) { + var c = data.getCache(setting); + if (!c) { + c = {}; + data.setCache(setting, c); + } + c.nodes = []; + c.doms = []; + }, + // default bindEvent of core + _bindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.bind(c.NODECREATED, function (event, treeId, node) { + tools.apply(setting.callback.onNodeCreated, [event, treeId, node]); + }); + + o.bind(c.CLICK, function (event, srcEvent, treeId, node, clickFlag) { + tools.apply(setting.callback.onClick, [srcEvent, treeId, node, clickFlag]); + }); + + o.bind(c.EXPAND, function (event, treeId, node) { + tools.apply(setting.callback.onExpand, [event, treeId, node]); + }); + + o.bind(c.COLLAPSE, function (event, treeId, node) { + tools.apply(setting.callback.onCollapse, [event, treeId, node]); + }); + + o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) { + tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]); + }); + + o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { + tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); + }); + + o.bind(c.REMOVE, function (event, treeId, treeNode) { + tools.apply(setting.callback.onRemove, [event, treeId, treeNode]); + }); + + o.bind(c.SELECTED, function (event, srcEvent, treeId, node) { + tools.apply(setting.callback.onSelected, [srcEvent, treeId, node]); + }); + o.bind(c.UNSELECTED, function (event, srcEvent, treeId, node) { + tools.apply(setting.callback.onUnSelected, [srcEvent, treeId, node]); + }); + }, + _unbindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.unbind(c.NODECREATED) + .unbind(c.CLICK) + .unbind(c.EXPAND) + .unbind(c.COLLAPSE) + .unbind(c.ASYNC_SUCCESS) + .unbind(c.ASYNC_ERROR) + .unbind(c.REMOVE) + .unbind(c.SELECTED) + .unbind(c.UNSELECTED); + }, + // default event proxy of core + _eventProxy = function (event) { + var target = event.target, + setting = data.getSetting(event.data.treeId), + tId = "", node = null, + nodeEventType = "", treeEventType = "", + nodeEventCallback = null, treeEventCallback = null, + tmp = null; + + if (tools.eqs(event.type, "mousedown")) { + treeEventType = "mousedown"; + } else if (tools.eqs(event.type, "mouseup")) { + treeEventType = "mouseup"; + } else if (tools.eqs(event.type, "contextmenu")) { + treeEventType = "contextmenu"; + } else if (tools.eqs(event.type, "click")) { + if (tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.SWITCH) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "switchNode"; + } else { + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) { + tId = tools.getNodeMainDom(tmp).id; + nodeEventType = "clickNode"; + } + } + } else if (tools.eqs(event.type, "dblclick")) { + treeEventType = "dblclick"; + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) { + tId = tools.getNodeMainDom(tmp).id; + nodeEventType = "switchNode"; + } + } + if (treeEventType.length > 0 && tId.length == 0) { + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) {tId = tools.getNodeMainDom(tmp).id;} + } + // event to node + if (tId.length > 0) { + node = data.getNodeCache(setting, tId); + switch (nodeEventType) { + case "switchNode" : + if (!node.isParent) { + nodeEventType = ""; + } else if (tools.eqs(event.type, "click") + || (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) { + nodeEventCallback = handler.onSwitchNode; + } else { + nodeEventType = ""; + } + break; + case "clickNode" : + nodeEventCallback = handler.onClickNode; + break; + } + } + // event to zTree + switch (treeEventType) { + case "mousedown" : + treeEventCallback = handler.onZTreeMousedown; + break; + case "mouseup" : + treeEventCallback = handler.onZTreeMouseup; + break; + case "dblclick" : + treeEventCallback = handler.onZTreeDblclick; + break; + case "contextmenu" : + treeEventCallback = handler.onZTreeContextmenu; + break; + } + var proxyResult = { + stop: false, + node: node, + nodeEventType: nodeEventType, + nodeEventCallback: nodeEventCallback, + treeEventType: treeEventType, + treeEventCallback: treeEventCallback + }; + return proxyResult; + }, + // default init node of core + _initNode = function (setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { + if (!n) return; + var r = data.getRoot(setting), + childKey = setting.data.key.children; + n.level = level; + n.tId = setting.treeId + "_" + (++r.zId); + n.parentTId = parentNode ? parentNode.tId : null; + n.open = (typeof n.open === "string") ? tools.eqs(n.open, "true") : !!n.open; + if (n[childKey] && n[childKey].length > 0) { + n.isParent = true; + n.zAsync = true; + } else { + n.isParent = (typeof n.isParent === "string") ? tools.eqs(n.isParent, "true") : !!n.isParent; + n.open = (n.isParent && !setting.async.enable) ? n.open : false; + n.zAsync = !n.isParent; + } + n.isFirstNode = isFirstNode; + n.isLastNode = isLastNode; + n.getParentNode = function () {return data.getNodeCache(setting, n.parentTId);}; + n.getPreNode = function () {return data.getPreNode(setting, n);}; + n.getNextNode = function () {return data.getNextNode(setting, n);}; + n.isAjaxing = false; + data.fixPIdKeyValue(setting, n); + }, + _init = { + bind: [_bindEvent], + unbind: [_unbindEvent], + caches: [_initCache], + nodes: [_initNode], + proxys: [_eventProxy], + roots: [_initRoot], + beforeA: [], + afterA: [], + innerBeforeA: [], + innerAfterA: [], + zTreeTools: [] + }, + // method of operate data + data = { + addNodeCache: function (setting, node) { + data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = node; + }, + getNodeCacheId: function (tId) { + return tId.substring(tId.lastIndexOf("_") + 1); + }, + addAfterA: function (afterA) { + _init.afterA.push(afterA); + }, + addBeforeA: function (beforeA) { + _init.beforeA.push(beforeA); + }, + addInnerAfterA: function (innerAfterA) { + _init.innerAfterA.push(innerAfterA); + }, + addInnerBeforeA: function (innerBeforeA) { + _init.innerBeforeA.push(innerBeforeA); + }, + addInitBind: function (bindEvent) { + _init.bind.push(bindEvent); + }, + addInitUnBind: function (unbindEvent) { + _init.unbind.push(unbindEvent); + }, + addInitCache: function (initCache) { + _init.caches.push(initCache); + }, + addInitNode: function (initNode) { + _init.nodes.push(initNode); + }, + addInitProxy: function (initProxy, isFirst) { + if (isFirst) { + _init.proxys.splice(0, 0, initProxy); + } else { + _init.proxys.push(initProxy); + } + }, + addInitRoot: function (initRoot) { + _init.roots.push(initRoot); + }, + addNodesData: function (setting, parentNode, nodes) { + var childKey = setting.data.key.children; + if (!parentNode[childKey]) parentNode[childKey] = []; + if (parentNode[childKey].length > 0) { + parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false; + view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]); + } + parentNode.isParent = true; + parentNode[childKey] = parentNode[childKey].concat(nodes); + }, + addSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + if (!data.isSelectedNode(setting, node)) { + root.curSelectedList.push(node); + } + }, + addCreatedNode: function (setting, node) { + if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { + var root = data.getRoot(setting); + root.createdNodes.push(node); + } + }, + addZTreeTools: function (zTreeTools) { + _init.zTreeTools.push(zTreeTools); + }, + exSetting: function (s) { + $.extend(true, _setting, s); + }, + fixPIdKeyValue: function (setting, node) { + if (setting.data.simpleData.enable) { + node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; + } + }, + getAfterA: function (setting, node, array) { + for (var i = 0, j = _init.afterA.length; i < j; i++) { + _init.afterA[i].apply(this, arguments); + } + }, + getBeforeA: function (setting, node, array) { + for (var i = 0, j = _init.beforeA.length; i < j; i++) { + _init.beforeA[i].apply(this, arguments); + } + }, + getInnerAfterA: function (setting, node, array) { + for (var i = 0, j = _init.innerAfterA.length; i < j; i++) { + _init.innerAfterA[i].apply(this, arguments); + } + }, + getInnerBeforeA: function (setting, node, array) { + for (var i = 0, j = _init.innerBeforeA.length; i < j; i++) { + _init.innerBeforeA[i].apply(this, arguments); + } + }, + getCache: function (setting) { + return caches[setting.treeId]; + }, + getNextNode: function (setting, node) { + if (!node) return null; + var childKey = setting.data.key.children, + p = node.parentTId ? node.getParentNode() : data.getRoot(setting); + for (var i = 0, l = p[childKey].length - 1; i <= l; i++) { + if (p[childKey][i] === node) { + return (i == l ? null : p[childKey][i + 1]); + } + } + return null; + }, + getNodeByParam: function (setting, nodes, key, value) { + if (!nodes || !key) return null; + var childKey = setting.data.key.children; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i][key] == value) { + return nodes[i]; + } + var tmp = data.getNodeByParam(setting, nodes[i][childKey], key, value); + if (tmp) return tmp; + } + return null; + }, + getNodeCache: function (setting, tId) { + if (!tId) return null; + var n = caches[setting.treeId].nodes[data.getNodeCacheId(tId)]; + return n ? n : null; + }, + getNodeName: function (setting, node) { + var nameKey = setting.data.key.name; + return "" + node[nameKey]; + }, + getNodeTitle: function (setting, node) { + var t = setting.data.key.title === "" ? setting.data.key.name : setting.data.key.title; + return "" + node[t]; + }, + getNodes: function (setting) { + return data.getRoot(setting)[setting.data.key.children]; + }, + getNodesByParam: function (setting, nodes, key, value) { + if (!nodes || !key) return []; + var childKey = setting.data.key.children, + result = []; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i][key] == value) { + result.push(nodes[i]); + } + result = result.concat(data.getNodesByParam(setting, nodes[i][childKey], key, value)); + } + return result; + }, + getNodesByParamFuzzy: function (setting, nodes, key, value) { + if (!nodes || !key) return []; + var childKey = setting.data.key.children, + result = []; + value = value.toLowerCase(); + for (var i = 0, l = nodes.length; i < l; i++) { + if (typeof nodes[i][key] === "string" && nodes[i][key].toLowerCase().indexOf(value) > -1) { + result.push(nodes[i]); + } + result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value)); + } + return result; + }, + getNodesByFilter: function (setting, nodes, filter, isSingle, invokeParam) { + if (!nodes) return (isSingle ? null : []); + var childKey = setting.data.key.children, + result = isSingle ? null : []; + for (var i = 0, l = nodes.length; i < l; i++) { + if (tools.apply(filter, [nodes[i], invokeParam], false)) { + if (isSingle) {return nodes[i];} + result.push(nodes[i]); + } + var tmpResult = data.getNodesByFilter(setting, nodes[i][childKey], filter, isSingle, invokeParam); + if (isSingle && !!tmpResult) {return tmpResult;} + result = isSingle ? tmpResult : result.concat(tmpResult); + } + return result; + }, + getPreNode: function (setting, node) { + if (!node) return null; + var childKey = setting.data.key.children, + p = node.parentTId ? node.getParentNode() : data.getRoot(setting); + for (var i = 0, l = p[childKey].length; i < l; i++) { + if (p[childKey][i] === node) { + return (i == 0 ? null : p[childKey][i - 1]); + } + } + return null; + }, + getRoot: function (setting) { + return setting ? roots[setting.treeId] : null; + }, + getRoots: function () { + return roots; + }, + getSetting: function (treeId) { + return settings[treeId]; + }, + getSettings: function () { + return settings; + }, + getZTreeTools: function (treeId) { + var r = this.getRoot(this.getSetting(treeId)); + return r ? r.treeTools : null; + }, + initCache: function (setting) { + for (var i = 0, j = _init.caches.length; i < j; i++) { + _init.caches[i].apply(this, arguments); + } + }, + initNode: function (setting, level, node, parentNode, preNode, nextNode) { + for (var i = 0, j = _init.nodes.length; i < j; i++) { + _init.nodes[i].apply(this, arguments); + } + }, + initRoot: function (setting) { + for (var i = 0, j = _init.roots.length; i < j; i++) { + _init.roots[i].apply(this, arguments); + } + }, + isSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + for (var i = 0, j = root.curSelectedList.length; i < j; i++) { + if(node === root.curSelectedList[i]) return true; + } + return false; + }, + removeNodeCache: function (setting, node) { + var childKey = setting.data.key.children; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + arguments.callee(setting, node[childKey][i]); + } + } + data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = null; + }, + removeSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + for (var i = 0, j = root.curSelectedList.length; i < j; i++) { + if(node === root.curSelectedList[i] || !data.getNodeCache(setting, root.curSelectedList[i].tId)) { + root.curSelectedList.splice(i, 1); + i--; j--; + } + } + }, + setCache: function (setting, cache) { + caches[setting.treeId] = cache; + }, + setRoot: function (setting, root) { + roots[setting.treeId] = root; + }, + setZTreeTools: function (setting, zTreeTools) { + for (var i = 0, j = _init.zTreeTools.length; i < j; i++) { + _init.zTreeTools[i].apply(this, arguments); + } + }, + transformToArrayFormat: function (setting, nodes) { + if (!nodes) return []; + var childKey = setting.data.key.children, + r = []; + if (tools.isArray(nodes)) { + for (var i = 0, l = nodes.length; i < l; i++) { + r.push(nodes[i]); + if (nodes[i][childKey]) {r = r.concat(data.transformToArrayFormat(setting, nodes[i][childKey]));} + } + } else { + r.push(nodes); + if (nodes[childKey]) {r = r.concat(data.transformToArrayFormat(setting, nodes[childKey]));} + } + return r; + }, + transformTozTreeFormat: function (setting, sNodes) { + var i, l, + key = setting.data.simpleData.idKey, + parentKey = setting.data.simpleData.pIdKey, + childKey = setting.data.key.children; + if (!key || key == "" || !sNodes) return []; + + if (tools.isArray(sNodes)) { + var r = []; + var tmpMap = []; + for (i = 0, l = sNodes.length; i < l; i++) { + tmpMap[sNodes[i][key]] = sNodes[i]; + } + for (i = 0, l = sNodes.length; i < l; i++) { + if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) { + if (!tmpMap[sNodes[i][parentKey]][childKey]) {tmpMap[sNodes[i][parentKey]][childKey] = [];} + tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]); + } else { + r.push(sNodes[i]); + } + } + return r; + } + return [sNodes]; + + } + }, + // method of event proxy + event = { + bindEvent: function (setting) { + for (var i = 0, j = _init.bind.length; i < j; i++) { + _init.bind[i].apply(this, arguments); + } + }, + unbindEvent: function (setting) { + for (var i = 0, j = _init.unbind.length; i < j; i++) { + _init.unbind[i].apply(this, arguments); + } + }, + bindTree: function (setting) { + var eventParam = { + treeId: setting.treeId + }, + o = setting.treeObj; + if (!setting.view.txtSelectedEnable) { + // for can't select text + o.bind("selectstart", function (e) { + var node; + var n = e.originalEvent.srcElement.nodeName.toLowerCase(); + return (n === "input" || n === "textarea" ); + }).css({ + "-moz-user-select": "-moz-none" + }); + } + o.bind("click", eventParam, event.proxy); + o.bind("dblclick", eventParam, event.proxy); + o.bind("mouseover", eventParam, event.proxy); + o.bind("mouseout", eventParam, event.proxy); + o.bind("mousedown", eventParam, event.proxy); + o.bind("mouseup", eventParam, event.proxy); + o.bind("contextmenu", eventParam, event.proxy); + }, + unbindTree: function (setting) { + var o = setting.treeObj; + o.unbind("click", event.proxy) + .unbind("dblclick", event.proxy) + .unbind("mouseover", event.proxy) + .unbind("mouseout", event.proxy) + .unbind("mousedown", event.proxy) + .unbind("mouseup", event.proxy) + .unbind("contextmenu", event.proxy); + }, + doProxy: function (e) { + var results = []; + for (var i = 0, j = _init.proxys.length; i < j; i++) { + var proxyResult = _init.proxys[i].apply(this, arguments); + results.push(proxyResult); + if (proxyResult.stop) { + break; + } + } + return results; + }, + proxy: function (e) { + var setting = data.getSetting(e.data.treeId); + if (!tools.uCanDo(setting, e)) return true; + var results = event.doProxy(e), + r = true, x = false; + for (var i = 0, l = results.length; i < l; i++) { + var proxyResult = results[i]; + if (proxyResult.nodeEventCallback) { + x = true; + r = proxyResult.nodeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; + } + if (proxyResult.treeEventCallback) { + x = true; + r = proxyResult.treeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; + } + } + return r; + } + }, + // method of event handler + handler = { + onSwitchNode: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (node.open) { + if (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false) return true; + data.getRoot(setting).expandTriggerFlag = true; + view.switchNode(setting, node); + } else { + if (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false) return true; + data.getRoot(setting).expandTriggerFlag = true; + view.switchNode(setting, node); + } + return true; + }, + onClickNode: function (event, node) { + var setting = data.getSetting(event.data.treeId), + clickFlag = ( (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey)) && data.isSelectedNode(setting, node)) ? 0 : (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey) && setting.view.selectedMulti) ? 2 : 1; + if (tools.apply(setting.callback.beforeClick, [setting.treeId, node, clickFlag], true) == false) return true; + if (clickFlag === 0) { + view.cancelPreSelectedNode(setting, node); + } else { + view.selectNode(setting, node, clickFlag === 2); + } + setting.treeObj.trigger(consts.event.CLICK, [event, setting.treeId, node, clickFlag]); + return true; + }, + onZTreeMousedown: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeMouseDown, [setting.treeId, node], true)) { + tools.apply(setting.callback.onMouseDown, [event, setting.treeId, node]); + } + return true; + }, + onZTreeMouseup: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeMouseUp, [setting.treeId, node], true)) { + tools.apply(setting.callback.onMouseUp, [event, setting.treeId, node]); + } + return true; + }, + onZTreeDblclick: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeDblClick, [setting.treeId, node], true)) { + tools.apply(setting.callback.onDblClick, [event, setting.treeId, node]); + } + return true; + }, + onZTreeContextmenu: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeRightClick, [setting.treeId, node], true)) { + tools.apply(setting.callback.onRightClick, [event, setting.treeId, node]); + } + return (typeof setting.callback.onRightClick) !== "function"; + } + }, + // method of tools for zTree + tools = { + apply: function (fun, param, defaultValue) { + if ((typeof fun) === "function") { + return fun.apply(zt, param ? param : []); + } + return defaultValue; + }, + canAsync: function (setting, node) { + var childKey = setting.data.key.children; + return (setting.async.enable && node && node.isParent && !(node.zAsync || (node[childKey] && node[childKey].length > 0))); + }, + clone: function (obj) { + if (obj === null) return null; + var o = tools.isArray(obj) ? [] : {}; + for(var i in obj) { + o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]); + } + return o; + }, + eqs: function (str1, str2) { + return str1.toLowerCase() === str2.toLowerCase(); + }, + isArray: function (arr) { + return Object.prototype.toString.apply(arr) === "[object Array]"; + }, + $: function (node, exp, setting) { + if (!!exp && typeof exp !== "string") { + setting = exp; + exp = ""; + } + if (typeof node === "string") { + return $(node, setting ? setting.treeObj.get(0).ownerDocument : null); + } + return $("#" + node.tId + exp, setting ? setting.treeObj : null); + + }, + getMDom: function (setting, curDom, targetExpr) { + if (!curDom) return null; + while (curDom && curDom.id !== setting.treeId) { + for (var i = 0, l = targetExpr.length; curDom.tagName && i < l; i++) { + if (tools.eqs(curDom.tagName, targetExpr[i].tagName) && curDom.getAttribute(targetExpr[i].attrName) !== null) { + return curDom; + } + } + curDom = curDom.parentNode; } + return null; + }, + getNodeMainDom: function (target) { + return ($(target).parent("li").get(0) || $(target).parentsUntil("li").parent().get(0)); }, + isChildOrSelf: function (dom, parentId) { + return ( $(dom).closest("#" + parentId).length > 0 ); + }, + uCanDo: function (setting, e) { + return true; + } + }, + // method of operate ztree dom + view = { + addNodes: function (setting, parentNode, newNodes, isSilent) { + if (setting.data.keep.leaf && parentNode && !parentNode.isParent) { + return; + } + if (!tools.isArray(newNodes)) { + newNodes = [newNodes]; + } + if (setting.data.simpleData.enable) { + newNodes = data.transformTozTreeFormat(setting, newNodes); + } + if (parentNode) { + var target_switchObj = $$(parentNode, consts.id.SWITCH, setting), + target_icoObj = $$(parentNode, consts.id.ICON, setting), + target_ulObj = $$(parentNode, consts.id.UL, setting); - items: [], - itemsCreator: BI.emptyFn, + if (!parentNode.open) { + view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE); + view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); + parentNode.open = false; + target_ulObj.css({ + display: "none" + }); + } - el: { - type: "bi.button_tree", - chooseType: 0, - layouts: [{ - type: "bi.vertical" - }] - } - }) - }, + data.addNodesData(setting, parentNode, newNodes); + view.createNodes(setting, parentNode.level + 1, newNodes, parentNode); + if (!isSilent) { + view.expandCollapseParentNode(setting, parentNode, true); + } + } else { + data.addNodesData(setting, data.getRoot(setting), newNodes); + view.createNodes(setting, 0, newNodes, null); + } + }, + appendNodes: function (setting, level, nodes, parentNode, initFlag, openFlag) { + if (!nodes) return []; + var html = [], + childKey = setting.data.key.children; + for (var i = 0, l = nodes.length; i < l; i++) { + var node = nodes[i]; + if (initFlag) { + var tmpPNode = (parentNode) ? parentNode : data.getRoot(setting), + tmpPChild = tmpPNode[childKey], + isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)), + isLastNode = (i == (nodes.length - 1)); + data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); + data.addNodeCache(setting, node); + } - _init: function () { - BI.CustomTree.superclass._init.apply(this, arguments); - this.initTree(this.options.items); - }, + var childHtml = []; + if (node[childKey] && node[childKey].length > 0) { + // make child html first, because checkType + childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open); + } + if (openFlag) { + + view.makeDOMNodeMainBefore(html, setting, node); + view.makeDOMNodeLine(html, setting, node); + data.getBeforeA(setting, node, html); + view.makeDOMNodeNameBefore(html, setting, node); + data.getInnerBeforeA(setting, node, html); + view.makeDOMNodeIcon(html, setting, node); + data.getInnerAfterA(setting, node, html); + view.makeDOMNodeNameAfter(html, setting, node); + data.getAfterA(setting, node, html); + if (node.isParent && node.open) { + view.makeUlHtml(setting, node, html, childHtml.join("")); + } + view.makeDOMNodeMainAfter(html, setting, node); + data.addCreatedNode(setting, node); + } + } + return html; + }, + appendParentULDom: function (setting, node) { + var html = [], + nObj = $$(node, setting); + if (!nObj.get(0) && !!node.parentTId) { + view.appendParentULDom(setting, node.getParentNode()); + nObj = $$(node, setting); + } + var ulObj = $$(node, consts.id.UL, setting); + if (ulObj.get(0)) { + ulObj.remove(); + } + var childKey = setting.data.key.children, + childHtml = view.appendNodes(setting, node.level + 1, node[childKey], node, false, true); + view.makeUlHtml(setting, node, html, childHtml.join("")); + nObj.append(html.join("")); + }, + asyncNode: function (setting, node, isSilent, callback) { + var i, l; + if (node && !node.isParent) { + tools.apply(callback); + return false; + } else if (node && node.isAjaxing) { + return false; + } else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) { + tools.apply(callback); + return false; + } + if (node) { + node.isAjaxing = true; + var icoObj = $$(node, consts.id.ICON, setting); + icoObj.attr({style: "", class: consts.className.BUTTON + " " + consts.className.ICO_LOADING}); + } - _formatItems: function (nodes) { - var self = this, o = this.options; - nodes = BI.Tree.transformToTreeFormat(nodes); + var tmpParam = {}; + for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) { + var pKey = setting.async.autoParam[i].split("="), spKey = pKey; + if (pKey.length > 1) { + spKey = pKey[1]; + pKey = pKey[0]; + } + tmpParam[spKey] = node[pKey]; + } + if (tools.isArray(setting.async.otherParam)) { + for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) { + tmpParam[setting.async.otherParam[i]] = setting.async.otherParam[i + 1]; + } + } else { + for (var p in setting.async.otherParam) { + tmpParam[p] = setting.async.otherParam[p]; + } + } - var items = []; - BI.each(nodes, function (i, node) { - if (BI.isNotEmptyArray(node.children) || node.isParent === true) { - var item = BI.extend({ - type: "bi.expander", - el: {}, - popup: {type: "bi.custom_tree"} - }, BI.deepClone(o.expander), { - id: node.id, - pId: node.pId, - value: node.value + var _tmpV = data.getRoot(setting)._ver; + $.ajax({ + contentType: setting.async.contentType, + cache: false, + type: setting.async.type, + url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), + data: tmpParam, + dataType: setting.async.dataType, + success: function (msg) { + if (_tmpV != data.getRoot(setting)._ver) { + return; + } + var newNodes = []; + try { + if (!msg || msg.length == 0) { + newNodes = []; + } else if (typeof msg === "string") { + newNodes = eval("(" + msg + ")"); + } else { + newNodes = msg; + } + } catch(err) { + newNodes = msg; + } + + if (node) { + node.isAjaxing = null; + node.zAsync = true; + } + view.setNodeLineIcos(setting, node); + if (newNodes && newNodes !== "") { + newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); + view.addNodes(setting, node, newNodes ? tools.clone(newNodes) : [], !!isSilent); + } else { + view.addNodes(setting, node, [], !!isSilent); + } + setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]); + tools.apply(callback); + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + if (_tmpV != data.getRoot(setting)._ver) { + return; + } + if (node) node.isAjaxing = null; + view.setNodeLineIcos(setting, node); + setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); + } }); - var el = BI.stripEL(node); - if (!BI.isWidget(el)) { - el = BI.clone(el); - delete el.children; - BI.extend(item.el, el); - } else { - item.el = el; + return true; + }, + cancelPreSelectedNode: function (setting, node, excludeNode) { + var list = data.getRoot(setting).curSelectedList, + i, n; + for (i = list.length - 1; i >= 0; i--) { + n = list[i]; + if (node === n || (!node && (!excludeNode || excludeNode !== n))) { + $$(n, consts.id.A, setting).removeClass(consts.node.CURSELECTED); + if (node) { + data.removeSelectedNode(setting, node); + setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); + break; + } else { + list.splice(i, 1); + setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); + } + } } - item.popup.expander = BI.deepClone(o.expander); - item.items = item.popup.items = node.children; - item.itemsCreator = item.popup.itemsCreator = function (op) { - if (BI.isNotNull(op.node)) {//从子节点传过来的itemsCreator直接向上传递 - return o.itemsCreator.apply(self, arguments); + }, + createNodeCallback: function (setting) { + if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { + var root = data.getRoot(setting); + while (root.createdNodes.length > 0) { + var node = root.createdNodes.shift(); + tools.apply(setting.view.addDiyDom, [setting.treeId, node]); + if (setting.callback.onNodeCreated) { + setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]); + } } - var args = Array.prototype.slice.call(arguments, 0); - args[0].node = node; - return o.itemsCreator.apply(self, args); - }; - BI.isNull(item.popup.el) && (item.popup.el = BI.deepClone(o.el)); - items.push(item); - } else { - items.push(node); - } - }); - return items; - }, + } + }, + createNodes: function (setting, level, nodes, parentNode) { + if (!nodes || nodes.length == 0) return; + var root = data.getRoot(setting), + childKey = setting.data.key.children, + openFlag = !parentNode || parentNode.open || !!$$(parentNode[childKey][0], setting).get(0); + root.createdNodes = []; + var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag); + if (!parentNode) { + setting.treeObj.append(zTreeHtml.join("")); + } else { + var ulObj = $$(parentNode, consts.id.UL, setting); + if (ulObj.get(0)) { + ulObj.append(zTreeHtml.join("")); + } + } + view.createNodeCallback(setting); + }, + destroy: function (setting) { + if (!setting) return; + data.initCache(setting); + data.initRoot(setting); + event.unbindTree(setting); + event.unbindEvent(setting); + setting.treeObj.empty(); + delete settings[setting.treeId]; + }, + expandCollapseNode: function (setting, node, expandFlag, animateFlag, callback) { + var root = data.getRoot(setting), + childKey = setting.data.key.children; + if (!node) { + tools.apply(callback, []); + return; + } + if (root.expandTriggerFlag) { + var _callback = callback; + callback = function () { + if (_callback) _callback(); + if (node.open) { + setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]); + } else { + setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]); + } + }; + root.expandTriggerFlag = false; + } + if (!node.open && node.isParent && ((!$$(node, consts.id.UL, setting).get(0)) || (node[childKey] && node[childKey].length > 0 && !$$(node[childKey][0], setting).get(0)))) { + view.appendParentULDom(setting, node); + view.createNodeCallback(setting); + } + if (node.open == expandFlag) { + tools.apply(callback, []); + return; + } + var ulObj = $$(node, consts.id.UL, setting), + switchObj = $$(node, consts.id.SWITCH, setting), + icoObj = $$(node, consts.id.ICON, setting); - //构造树结构, - initTree: function (nodes) { - var self = this, o = this.options; - this.tree = BI.createWidget(o.el, { - element: this, - items: this._formatItems(nodes), - itemsCreator: function (op, callback) { - o.itemsCreator.apply(this, [op, function (items) { - var args = Array.prototype.slice.call(arguments, 0); - args[0] = self._formatItems(items); - callback.apply(null, args); - }]); - } - }); - this.tree.on(BI.Controller.EVENT_CHANGE, function (type, val, obj) { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - if (type === BI.Events.CLICK) { - self.fireEvent(BI.CustomTree.EVENT_CHANGE, val, obj); - } - }) - }, + if (node.isParent) { + node.open = !node.open; + if (node.iconOpen && node.iconClose) { + icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); + } - //生成树方法 - stroke: function (nodes) { - this.populate.apply(this, arguments); - }, + if (node.open) { + view.replaceSwitchClass(node, switchObj, consts.folder.OPEN); + view.replaceIcoClass(node, icoObj, consts.folder.OPEN); + if (animateFlag == false || setting.view.expandSpeed == "") { + ulObj.show(); + tools.apply(callback, []); + } else { + if (node[childKey] && node[childKey].length > 0) { + ulObj.slideDown(setting.view.expandSpeed, callback); + } else { + ulObj.show(); + tools.apply(callback, []); + } + } + } else { + view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); + view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); + if (animateFlag == false || setting.view.expandSpeed == "" || !(node[childKey] && node[childKey].length > 0)) { + ulObj.hide(); + tools.apply(callback, []); + } else { + ulObj.slideUp(setting.view.expandSpeed, callback); + } + } + } else { + tools.apply(callback, []); + } + }, + expandCollapseParentNode: function (setting, node, expandFlag, animateFlag, callback) { + if (!node) return; + if (!node.parentTId) { + view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback); + return; + } + view.expandCollapseNode(setting, node, expandFlag, animateFlag); + + if (node.parentTId) { + view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback); + } + }, + expandCollapseSonNode: function (setting, node, expandFlag, animateFlag, callback) { + var root = data.getRoot(setting), + childKey = setting.data.key.children, + treeNodes = (node) ? node[childKey] : root[childKey], + selfAnimateSign = (node) ? false : animateFlag, + expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; + data.getRoot(setting).expandTriggerFlag = false; + if (treeNodes) { + for (var i = 0, l = treeNodes.length; i < l; i++) { + if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); + } + } + data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; + view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback ); + }, + isSelectedNode: function (setting, node) { + if (!node) { + return false; + } + var list = data.getRoot(setting).curSelectedList, + i; + for (i = list.length - 1; i >= 0; i--) { + if (node === list[i]) { + return true; + } + } + return false; + }, + makeDOMNodeIcon: function (html, setting, node) { + var nameStr = data.getNodeName(setting, node), + name = setting.view.nameIsHTML ? nameStr : nameStr.replace(/&/g, "&").replace(//g, ">"); + html.push("", name, ""); + }, + makeDOMNodeLine: function (html, setting, node) { + html.push(""); + }, + makeDOMNodeMainAfter: function (html, setting, node) { + html.push(""); + }, + makeDOMNodeMainBefore: function (html, setting, node) { + html.push("
  • "); + }, + makeDOMNodeNameAfter: function (html, setting, node) { + html.push(""); + }, + makeDOMNodeNameBefore: function (html, setting, node) { + var title = data.getNodeTitle(setting, node), + url = view.makeNodeUrl(setting, node), + fontcss = view.makeNodeFontCss(setting, node), + fontStyle = []; + for (var f in fontcss) { + fontStyle.push(f, ":", fontcss[f], ";"); + } + html.push(" 0) ? "href='" + url + "'" : ""), " target='", view.makeNodeTarget(node), "' style='", fontStyle.join(""), + "'"); + if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && title) {html.push("title='", title.replace(/'/g, "'").replace(//g, ">"), "'");} + html.push(">"); + }, + makeNodeFontCss: function (setting, node) { + var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); + return (fontCss && ((typeof fontCss) !== "function")) ? fontCss : {}; + }, + makeNodeIcoClass: function (setting, node) { + var icoCss = ["ico"]; + if (!node.isAjaxing) { + icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0]; + if (node.isParent) { + icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); + } else { + icoCss.push(consts.folder.DOCU); + } + } + return consts.className.BUTTON + " " + icoCss.join("_"); + }, + makeNodeIcoStyle: function (setting, node) { + var icoStyle = []; + if (!node.isAjaxing) { + var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon; + if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); + if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { + icoStyle.push("width:0px;height:0px;"); + } + } + return icoStyle.join(""); + }, + makeNodeLineClass: function (setting, node) { + var lineClass = []; + if (setting.view.showLine) { + if (node.level == 0 && node.isFirstNode && node.isLastNode) { + lineClass.push(consts.line.ROOT); + } else if (node.level == 0 && node.isFirstNode) { + lineClass.push(consts.line.ROOTS); + } else if (node.isLastNode) { + lineClass.push(consts.line.BOTTOM); + } else { + lineClass.push(consts.line.CENTER); + } + } else { + lineClass.push(consts.line.NOLINE); + } + if (node.isParent) { + lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); + } else { + lineClass.push(consts.folder.DOCU); + } + return view.makeNodeLineClassEx(node) + lineClass.join("_"); + }, + makeNodeLineClassEx: function (node) { + return consts.className.BUTTON + " " + consts.className.LEVEL + node.level + " " + consts.className.SWITCH + " "; + }, + makeNodeTarget: function (node) { + return (node.target || "_blank"); + }, + makeNodeUrl: function (setting, node) { + var urlKey = setting.data.key.url; + return node[urlKey] ? node[urlKey] : null; + }, + makeUlHtml: function (setting, node, html, content) { + html.push("
      "); + html.push(content); + html.push("
    "); + }, + makeUlLineClass: function (setting, node) { + return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : ""); + }, + removeChildNodes: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children, + nodes = node[childKey]; + if (!nodes) return; + + for (var i = 0, l = nodes.length; i < l; i++) { + data.removeNodeCache(setting, nodes[i]); + } + data.removeSelectedNode(setting); + delete node[childKey]; + + if (!setting.data.keep.parent) { + node.isParent = false; + node.open = false; + var tmp_switchObj = $$(node, consts.id.SWITCH, setting), + tmp_icoObj = $$(node, consts.id.ICON, setting); + view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU); + view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU); + $$(node, consts.id.UL, setting).remove(); + } else { + $$(node, consts.id.UL, setting).empty(); + } + }, + setFirstNode: function (setting, parentNode) { + var childKey = setting.data.key.children, childLength = parentNode[childKey].length; + if ( childLength > 0) { + parentNode[childKey][0].isFirstNode = true; + } + }, + setLastNode: function (setting, parentNode) { + var childKey = setting.data.key.children, childLength = parentNode[childKey].length; + if ( childLength > 0) { + parentNode[childKey][childLength - 1].isLastNode = true; + } + }, + removeNode: function (setting, node) { + var root = data.getRoot(setting), + childKey = setting.data.key.children, + parentNode = (node.parentTId) ? node.getParentNode() : root; - populate: function (nodes) { - var args = Array.prototype.slice.call(arguments, 0); - if (arguments.length > 0) { - args[0] = this._formatItems(nodes); - } - this.tree.populate.apply(this.tree, args); - }, + node.isFirstNode = false; + node.isLastNode = false; + node.getPreNode = function () {return null;}; + node.getNextNode = function () {return null;}; - setValue: function (v) { - this.tree && this.tree.setValue(v); - }, + if (!data.getNodeCache(setting, node.tId)) { + return; + } - getValue: function () { - return this.tree ? this.tree.getValue() : []; - }, + $$(node, setting).remove(); + data.removeNodeCache(setting, node); + data.removeSelectedNode(setting, node); - getAllButtons: function () { - return this.tree ? this.tree.getAllButtons() : []; - }, + for (var i = 0, l = parentNode[childKey].length; i < l; i++) { + if (parentNode[childKey][i].tId == node.tId) { + parentNode[childKey].splice(i, 1); + break; + } + } + view.setFirstNode(setting, parentNode); + view.setLastNode(setting, parentNode); + + var tmp_ulObj, tmp_switchObj, tmp_icoObj, + childLength = parentNode[childKey].length; + + // repair nodes old parent + if (!setting.data.keep.parent && childLength == 0) { + // old parentNode has no child nodes + parentNode.isParent = false; + parentNode.open = false; + tmp_ulObj = $$(parentNode, consts.id.UL, setting); + tmp_switchObj = $$(parentNode, consts.id.SWITCH, setting); + tmp_icoObj = $$(parentNode, consts.id.ICON, setting); + view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU); + view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU); + tmp_ulObj.css("display", "none"); + + } else if (setting.view.showLine && childLength > 0) { + // old parentNode has child nodes + var newLast = parentNode[childKey][childLength - 1]; + tmp_ulObj = $$(newLast, consts.id.UL, setting); + tmp_switchObj = $$(newLast, consts.id.SWITCH, setting); + tmp_icoObj = $$(newLast, consts.id.ICON, setting); + if (parentNode == root) { + if (parentNode[childKey].length == 1) { + // node was root, and ztree has only one root after move node + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT); + } else { + var tmp_first_switchObj = $$(parentNode[childKey][0], consts.id.SWITCH, setting); + view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS); + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); + } + } else { + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); + } + tmp_ulObj.removeClass(consts.line.LINE); + } + }, + replaceIcoClass: function (node, obj, newName) { + if (!obj || node.isAjaxing) return; + var tmpName = obj.attr("class"); + if (tmpName == undefined) return; + var tmpList = tmpName.split("_"); + switch (newName) { + case consts.folder.OPEN: + case consts.folder.CLOSE: + case consts.folder.DOCU: + tmpList[tmpList.length - 1] = newName; + break; + } + obj.attr("class", tmpList.join("_")); + }, + replaceSwitchClass: function (node, obj, newName) { + if (!obj) return; + var tmpName = obj.attr("class"); + if (tmpName == undefined) return; + var tmpList = tmpName.split("_"); + switch (newName) { + case consts.line.ROOT: + case consts.line.ROOTS: + case consts.line.CENTER: + case consts.line.BOTTOM: + case consts.line.NOLINE: + tmpList[0] = view.makeNodeLineClassEx(node) + newName; + break; + case consts.folder.OPEN: + case consts.folder.CLOSE: + case consts.folder.DOCU: + tmpList[1] = newName; + break; + } + obj.attr("class", tmpList.join("_")); + if (newName !== consts.folder.DOCU) { + obj.removeAttr("disabled"); + } else { + obj.attr("disabled", "disabled"); + } + }, + selectNode: function (setting, node, addFlag) { + if (!addFlag) { + view.cancelPreSelectedNode(setting, null, node); + } + $$(node, consts.id.A, setting).addClass(consts.node.CURSELECTED); + data.addSelectedNode(setting, node); + setting.treeObj.trigger(consts.event.SELECTED, [event, setting.treeId, node]); + }, + setNodeFontCss: function (setting, treeNode) { + var aObj = $$(treeNode, consts.id.A, setting), + fontCss = view.makeNodeFontCss(setting, treeNode); + if (fontCss) { + aObj.css(fontCss); + } + }, + setNodeLineIcos: function (setting, node) { + if (!node) return; + var switchObj = $$(node, consts.id.SWITCH, setting), + ulObj = $$(node, consts.id.UL, setting), + icoObj = $$(node, consts.id.ICON, setting), + ulLine = view.makeUlLineClass(setting, node); + if (ulLine.length == 0) { + ulObj.removeClass(consts.line.LINE); + } else { + ulObj.addClass(ulLine); + } + switchObj.attr("class", view.makeNodeLineClass(setting, node)); + if (node.isParent) { + switchObj.removeAttr("disabled"); + } else { + switchObj.attr("disabled", "disabled"); + } + icoObj.removeAttr("style"); + icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); + icoObj.attr("class", view.makeNodeIcoClass(setting, node)); + }, + setNodeName: function (setting, node) { + var title = data.getNodeTitle(setting, node), + nObj = $$(node, consts.id.SPAN, setting); + nObj.empty(); + if (setting.view.nameIsHTML) { + nObj.html(data.getNodeName(setting, node)); + } else { + nObj.text(data.getNodeName(setting, node)); + } + if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle)) { + var aObj = $$(node, consts.id.A, setting); + aObj.attr("title", !title ? "" : title); + } + }, + setNodeTarget: function (setting, node) { + var aObj = $$(node, consts.id.A, setting); + aObj.attr("target", view.makeNodeTarget(node)); + }, + setNodeUrl: function (setting, node) { + var aObj = $$(node, consts.id.A, setting), + url = view.makeNodeUrl(setting, node); + if (url == null || url.length == 0) { + aObj.removeAttr("href"); + } else { + aObj.attr("href", url); + } + }, + switchNode: function (setting, node) { + if (node.open || !tools.canAsync(setting, node)) { + view.expandCollapseNode(setting, node, !node.open); + } else if (setting.async.enable) { + if (!view.asyncNode(setting, node)) { + view.expandCollapseNode(setting, node, !node.open); + return; + } + } else if (node) { + view.expandCollapseNode(setting, node, !node.open); + } + } + }; + // zTree defind + $.fn.zTree = { + consts: _consts, + _z: { + tools: tools, + view: view, + event: event, + data: data + }, + getZTreeObj: function (treeId) { + var o = data.getZTreeTools(treeId); + return o ? o : null; + }, + destroy: function (treeId) { + if (!!treeId && treeId.length > 0) { + view.destroy(data.getSetting(treeId)); + } else { + for(var s in settings) { + view.destroy(settings[s]); + } + } + }, + init: function (obj, zSetting, zNodes) { + var setting = tools.clone(_setting); + $.extend(true, setting, zSetting); + setting.treeId = obj.attr("id"); + setting.treeObj = obj; + setting.treeObj.empty(); + settings[setting.treeId] = setting; + // For some older browser,(e.g., ie6) + if(typeof document.body.style.maxHeight === "undefined") { + setting.view.expandSpeed = ""; + } + data.initRoot(setting); + var root = data.getRoot(setting), + childKey = setting.data.key.children; + zNodes = zNodes ? tools.clone(tools.isArray(zNodes) ? zNodes : [zNodes]) : []; + if (setting.data.simpleData.enable) { + root[childKey] = data.transformTozTreeFormat(setting, zNodes); + } else { + root[childKey] = zNodes; + } + + data.initCache(setting); + event.unbindTree(setting); + event.bindTree(setting); + event.unbindEvent(setting); + event.bindEvent(setting); + + var zTreeTools = { + setting: setting, + addNodes: function (parentNode, newNodes, isSilent) { + if (!newNodes) return null; + if (!parentNode) parentNode = null; + if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null; + var xNewNodes = tools.clone(tools.isArray(newNodes) ? newNodes : [newNodes]); + function addCallback () { + view.addNodes(setting, parentNode, xNewNodes, (isSilent == true)); + } - getAllLeaves: function () { - return this.tree ? this.tree.getAllLeaves() : []; - }, + if (tools.canAsync(setting, parentNode)) { + view.asyncNode(setting, parentNode, isSilent, addCallback); + } else { + addCallback(); + } + return xNewNodes; + }, + cancelSelectedNode: function (node) { + view.cancelPreSelectedNode(setting, node); + }, + destroy: function () { + view.destroy(setting); + }, + expandAll: function (expandFlag) { + expandFlag = !!expandFlag; + view.expandCollapseSonNode(setting, null, expandFlag, true); + return expandFlag; + }, + expandNode: function (node, expandFlag, sonSign, focus, callbackFlag) { + if (!node || !node.isParent) return null; + if (expandFlag !== true && expandFlag !== false) { + expandFlag = !node.open; + } + callbackFlag = !!callbackFlag; - getNodeById: function (id) { - return this.tree && this.tree.getNodeById(id); - }, + if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) { + return null; + } else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) { + return null; + } + if (expandFlag && node.parentTId) { + view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, false); + } + if (expandFlag === node.open && !sonSign) { + return null; + } - getNodeByValue: function (id) { - return this.tree && this.tree.getNodeByValue(id); - }, + data.getRoot(setting).expandTriggerFlag = callbackFlag; + if (!tools.canAsync(setting, node) && sonSign) { + view.expandCollapseSonNode(setting, node, expandFlag, true, function () { + if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e) {}} + }); + } else { + node.open = !expandFlag; + view.switchNode(this.setting, node); + if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e) {}} + } + return expandFlag; + }, + getNodes: function () { + return data.getNodes(setting); + }, + getNodeByParam: function (key, value, parentNode) { + if (!key) return null; + return data.getNodeByParam(setting, parentNode ? parentNode[setting.data.key.children] : data.getNodes(setting), key, value); + }, + getNodeByTId: function (tId) { + return data.getNodeCache(setting, tId); + }, + getNodesByParam: function (key, value, parentNode) { + if (!key) return null; + return data.getNodesByParam(setting, parentNode ? parentNode[setting.data.key.children] : data.getNodes(setting), key, value); + }, + getNodesByParamFuzzy: function (key, value, parentNode) { + if (!key) return null; + return data.getNodesByParamFuzzy(setting, parentNode ? parentNode[setting.data.key.children] : data.getNodes(setting), key, value); + }, + getNodesByFilter: function (filter, isSingle, parentNode, invokeParam) { + isSingle = !!isSingle; + if (!filter || (typeof filter !== "function")) return (isSingle ? null : []); + return data.getNodesByFilter(setting, parentNode ? parentNode[setting.data.key.children] : data.getNodes(setting), filter, isSingle, invokeParam); + }, + getNodeIndex: function (node) { + if (!node) return null; + var childKey = setting.data.key.children, + parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); + for (var i = 0, l = parentNode[childKey].length; i < l; i++) { + if (parentNode[childKey][i] == node) return i; + } + return -1; + }, + getSelectedNodes: function () { + var r = [], list = data.getRoot(setting).curSelectedList; + for (var i = 0, l = list.length; i < l; i++) { + r.push(list[i]); + } + return r; + }, + isSelectedNode: function (node) { + return data.isSelectedNode(setting, node); + }, + reAsyncChildNodes: function (parentNode, reloadType, isSilent) { + if (!this.setting.async.enable) return; + var isRoot = !parentNode; + if (isRoot) { + parentNode = data.getRoot(setting); + } + if (reloadType == "refresh") { + var childKey = this.setting.data.key.children; + for (var i = 0, l = parentNode[childKey] ? parentNode[childKey].length : 0; i < l; i++) { + data.removeNodeCache(setting, parentNode[childKey][i]); + } + data.removeSelectedNode(setting); + parentNode[childKey] = []; + if (isRoot) { + this.setting.treeObj.empty(); + } else { + var ulObj = $$(parentNode, consts.id.UL, setting); + ulObj.empty(); + } + } + view.asyncNode(this.setting, isRoot ? null : parentNode, !!isSilent); + }, + refresh: function () { + this.setting.treeObj.empty(); + var root = data.getRoot(setting), + nodes = root[setting.data.key.children]; + data.initRoot(setting); + root[setting.data.key.children] = nodes; + data.initCache(setting); + view.createNodes(setting, 0, root[setting.data.key.children]); + }, + removeChildNodes: function (node) { + if (!node) return null; + var childKey = setting.data.key.children, + nodes = node[childKey]; + view.removeChildNodes(setting, node); + return nodes ? nodes : null; + }, + removeNode: function (node, callbackFlag) { + if (!node) return; + callbackFlag = !!callbackFlag; + if (callbackFlag && tools.apply(setting.callback.beforeRemove, [setting.treeId, node], true) == false) return; + view.removeNode(setting, node); + if (callbackFlag) { + this.setting.treeObj.trigger(consts.event.REMOVE, [setting.treeId, node]); + } + }, + selectNode: function (node, addFlag) { + if (!node) return; + if (tools.uCanDo(setting)) { + addFlag = setting.view.selectedMulti && addFlag; + if (node.parentTId) { + view.expandCollapseParentNode(setting, node.getParentNode(), true, false, function () { + try{$$(node, setting).focus().blur();}catch(e) {} + }); + } else { + try{$$(node, setting).focus().blur();}catch(e) {} + } + view.selectNode(setting, node, addFlag); + } + }, + transformTozTreeNodes: function (simpleNodes) { + return data.transformTozTreeFormat(setting, simpleNodes); + }, + transformToArray: function (nodes) { + return data.transformToArrayFormat(setting, nodes); + }, + updateNode: function (node, checkTypeFlag) { + if (!node) return; + var nObj = $$(node, setting); + if (nObj.get(0) && tools.uCanDo(setting)) { + view.setNodeName(setting, node); + view.setNodeTarget(setting, node); + view.setNodeUrl(setting, node); + view.setNodeLineIcos(setting, node); + view.setNodeFontCss(setting, node); + } + } + }; + root.treeTools = zTreeTools; + data.setZTreeTools(setting, zTreeTools); - empty: function () { - this.tree.empty(); - } -}); -BI.CustomTree.EVENT_CHANGE = "EVENT_CHANGE"; + if (root[childKey] && root[childKey].length > 0) { + view.createNodes(setting, 0, root[childKey]); + } else if (setting.async.enable && setting.async.url && setting.async.url !== "") { + view.asyncNode(setting); + } + return zTreeTools; + } + }; -BI.shortcut("bi.custom_tree", BI.CustomTree);/* - * JQuery zTree core v3.5.18 - * http://zTree.me/ - * - * Copyright (c) 2010 Hunter.z - * - * Licensed same as jquery - MIT License - * http://www.opensource.org/licenses/mit-license.php - * - * email: hunter.z@263.net - * Date: 2015-06-18 - */ -(function($){ - var settings = {}, roots = {}, caches = {}, - //default consts of core - _consts = { - className: { - BUTTON: "button", - LEVEL: "level", - ICO_LOADING: "ico_loading", - SWITCH: "switch" - }, - event: { - NODECREATED: "ztree_nodeCreated", - CLICK: "ztree_click", - EXPAND: "ztree_expand", - COLLAPSE: "ztree_collapse", - ASYNC_SUCCESS: "ztree_async_success", - ASYNC_ERROR: "ztree_async_error", - REMOVE: "ztree_remove", - SELECTED: "ztree_selected", - UNSELECTED: "ztree_unselected" - }, - id: { - A: "_a", - ICON: "_ico", - SPAN: "_span", - SWITCH: "_switch", - UL: "_ul" - }, - line: { - ROOT: "root", - ROOTS: "roots", - CENTER: "center", - BOTTOM: "bottom", - NOLINE: "noline", - LINE: "line" - }, - folder: { - OPEN: "open", - CLOSE: "close", - DOCU: "docu" - }, - node: { - CURSELECTED: "curSelectedNode" - } - }, - //default setting of core - _setting = { - treeId: "", - treeObj: null, - view: { - addDiyDom: null, - autoCancelSelected: true, - dblClickExpand: true, - expandSpeed: "fast", - fontCss: {}, - nameIsHTML: false, - selectedMulti: true, - showIcon: true, - showLine: true, - showTitle: true, - txtSelectedEnable: false - }, - data: { - key: { - children: "children", - name: "name", - title: "", - url: "url" - }, - simpleData: { - enable: false, - idKey: "id", - pIdKey: "pId", - rootPId: null - }, - keep: { - parent: false, - leaf: false - } - }, - async: { - enable: false, - contentType: "application/x-www-form-urlencoded", - type: "post", - dataType: "text", - url: "", - autoParam: [], - otherParam: [], - dataFilter: null - }, - callback: { - beforeAsync:null, - beforeClick:null, - beforeDblClick:null, - beforeRightClick:null, - beforeMouseDown:null, - beforeMouseUp:null, - beforeExpand:null, - beforeCollapse:null, - beforeRemove:null, - - onAsyncError:null, - onAsyncSuccess:null, - onNodeCreated:null, - onClick:null, - onDblClick:null, - onRightClick:null, - onMouseDown:null, - onMouseUp:null, - onExpand:null, - onCollapse:null, - onRemove:null - } - }, - //default root of core - //zTree use root to save full data - _initRoot = function (setting) { - var r = data.getRoot(setting); - if (!r) { - r = {}; - data.setRoot(setting, r); - } - r[setting.data.key.children] = []; - r.expandTriggerFlag = false; - r.curSelectedList = []; - r.noSelection = true; - r.createdNodes = []; - r.zId = 0; - r._ver = (new Date()).getTime(); - }, - //default cache of core - _initCache = function(setting) { - var c = data.getCache(setting); - if (!c) { - c = {}; - data.setCache(setting, c); - } - c.nodes = []; - c.doms = []; - }, - //default bindEvent of core - _bindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.bind(c.NODECREATED, function (event, treeId, node) { - tools.apply(setting.callback.onNodeCreated, [event, treeId, node]); - }); - - o.bind(c.CLICK, function (event, srcEvent, treeId, node, clickFlag) { - tools.apply(setting.callback.onClick, [srcEvent, treeId, node, clickFlag]); - }); - - o.bind(c.EXPAND, function (event, treeId, node) { - tools.apply(setting.callback.onExpand, [event, treeId, node]); - }); - - o.bind(c.COLLAPSE, function (event, treeId, node) { - tools.apply(setting.callback.onCollapse, [event, treeId, node]); - }); - - o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) { - tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]); - }); - - o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { - tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); - }); - - o.bind(c.REMOVE, function (event, treeId, treeNode) { - tools.apply(setting.callback.onRemove, [event, treeId, treeNode]); - }); - - o.bind(c.SELECTED, function (event, srcEvent, treeId, node) { - tools.apply(setting.callback.onSelected, [srcEvent, treeId, node]); - }); - o.bind(c.UNSELECTED, function (event, srcEvent, treeId, node) { - tools.apply(setting.callback.onUnSelected, [srcEvent, treeId, node]); - }); - }, - _unbindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.unbind(c.NODECREATED) - .unbind(c.CLICK) - .unbind(c.EXPAND) - .unbind(c.COLLAPSE) - .unbind(c.ASYNC_SUCCESS) - .unbind(c.ASYNC_ERROR) - .unbind(c.REMOVE) - .unbind(c.SELECTED) - .unbind(c.UNSELECTED); - }, - //default event proxy of core - _eventProxy = function(event) { - var target = event.target, - setting = data.getSetting(event.data.treeId), - tId = "", node = null, - nodeEventType = "", treeEventType = "", - nodeEventCallback = null, treeEventCallback = null, - tmp = null; - - if (tools.eqs(event.type, "mousedown")) { - treeEventType = "mousedown"; - } else if (tools.eqs(event.type, "mouseup")) { - treeEventType = "mouseup"; - } else if (tools.eqs(event.type, "contextmenu")) { - treeEventType = "contextmenu"; - } else if (tools.eqs(event.type, "click")) { - if (tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.SWITCH) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "switchNode"; - } else { - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) { - tId = tools.getNodeMainDom(tmp).id; - nodeEventType = "clickNode"; - } - } - } else if (tools.eqs(event.type, "dblclick")) { - treeEventType = "dblclick"; - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) { - tId = tools.getNodeMainDom(tmp).id; - nodeEventType = "switchNode"; - } - } - if (treeEventType.length > 0 && tId.length == 0) { - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) {tId = tools.getNodeMainDom(tmp).id;} - } - // event to node - if (tId.length>0) { - node = data.getNodeCache(setting, tId); - switch (nodeEventType) { - case "switchNode" : - if (!node.isParent) { - nodeEventType = ""; - } else if (tools.eqs(event.type, "click") - || (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) { - nodeEventCallback = handler.onSwitchNode; - } else { - nodeEventType = ""; - } - break; - case "clickNode" : - nodeEventCallback = handler.onClickNode; - break; - } - } - // event to zTree - switch (treeEventType) { - case "mousedown" : - treeEventCallback = handler.onZTreeMousedown; - break; - case "mouseup" : - treeEventCallback = handler.onZTreeMouseup; - break; - case "dblclick" : - treeEventCallback = handler.onZTreeDblclick; - break; - case "contextmenu" : - treeEventCallback = handler.onZTreeContextmenu; - break; - } - var proxyResult = { - stop: false, - node: node, - nodeEventType: nodeEventType, - nodeEventCallback: nodeEventCallback, - treeEventType: treeEventType, - treeEventCallback: treeEventCallback - }; - return proxyResult - }, - //default init node of core - _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { - if (!n) return; - var r = data.getRoot(setting), - childKey = setting.data.key.children; - n.level = level; - n.tId = setting.treeId + "_" + (++r.zId); - n.parentTId = parentNode ? parentNode.tId : null; - n.open = (typeof n.open == "string") ? tools.eqs(n.open, "true") : !!n.open; - if (n[childKey] && n[childKey].length > 0) { - n.isParent = true; - n.zAsync = true; - } else { - n.isParent = (typeof n.isParent == "string") ? tools.eqs(n.isParent, "true") : !!n.isParent; - n.open = (n.isParent && !setting.async.enable) ? n.open : false; - n.zAsync = !n.isParent; - } - n.isFirstNode = isFirstNode; - n.isLastNode = isLastNode; - n.getParentNode = function() {return data.getNodeCache(setting, n.parentTId);}; - n.getPreNode = function() {return data.getPreNode(setting, n);}; - n.getNextNode = function() {return data.getNextNode(setting, n);}; - n.isAjaxing = false; - data.fixPIdKeyValue(setting, n); - }, - _init = { - bind: [_bindEvent], - unbind: [_unbindEvent], - caches: [_initCache], - nodes: [_initNode], - proxys: [_eventProxy], - roots: [_initRoot], - beforeA: [], - afterA: [], - innerBeforeA: [], - innerAfterA: [], - zTreeTools: [] - }, - //method of operate data - data = { - addNodeCache: function(setting, node) { - data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = node; - }, - getNodeCacheId: function(tId) { - return tId.substring(tId.lastIndexOf("_")+1); - }, - addAfterA: function(afterA) { - _init.afterA.push(afterA); - }, - addBeforeA: function(beforeA) { - _init.beforeA.push(beforeA); - }, - addInnerAfterA: function(innerAfterA) { - _init.innerAfterA.push(innerAfterA); - }, - addInnerBeforeA: function(innerBeforeA) { - _init.innerBeforeA.push(innerBeforeA); - }, - addInitBind: function(bindEvent) { - _init.bind.push(bindEvent); - }, - addInitUnBind: function(unbindEvent) { - _init.unbind.push(unbindEvent); - }, - addInitCache: function(initCache) { - _init.caches.push(initCache); - }, - addInitNode: function(initNode) { - _init.nodes.push(initNode); - }, - addInitProxy: function(initProxy, isFirst) { - if (!!isFirst) { - _init.proxys.splice(0,0,initProxy); - } else { - _init.proxys.push(initProxy); - } - }, - addInitRoot: function(initRoot) { - _init.roots.push(initRoot); - }, - addNodesData: function(setting, parentNode, nodes) { - var childKey = setting.data.key.children; - if (!parentNode[childKey]) parentNode[childKey] = []; - if (parentNode[childKey].length > 0) { - parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false; - view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]); - } - parentNode.isParent = true; - parentNode[childKey] = parentNode[childKey].concat(nodes); - }, - addSelectedNode: function(setting, node) { - var root = data.getRoot(setting); - if (!data.isSelectedNode(setting, node)) { - root.curSelectedList.push(node); - } - }, - addCreatedNode: function(setting, node) { - if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { - var root = data.getRoot(setting); - root.createdNodes.push(node); - } - }, - addZTreeTools: function(zTreeTools) { - _init.zTreeTools.push(zTreeTools); - }, - exSetting: function(s) { - $.extend(true, _setting, s); - }, - fixPIdKeyValue: function(setting, node) { - if (setting.data.simpleData.enable) { - node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; - } - }, - getAfterA: function(setting, node, array) { - for (var i=0, j=_init.afterA.length; i-1) { - result.push(nodes[i]); - } - result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value)); - } - return result; - }, - getNodesByFilter: function(setting, nodes, filter, isSingle, invokeParam) { - if (!nodes) return (isSingle ? null : []); - var childKey = setting.data.key.children, - result = isSingle ? null : []; - for (var i = 0, l = nodes.length; i < l; i++) { - if (tools.apply(filter, [nodes[i], invokeParam], false)) { - if (isSingle) {return nodes[i];} - result.push(nodes[i]); - } - var tmpResult = data.getNodesByFilter(setting, nodes[i][childKey], filter, isSingle, invokeParam); - if (isSingle && !!tmpResult) {return tmpResult;} - result = isSingle ? tmpResult : result.concat(tmpResult); - } - return result; - }, - getPreNode: function(setting, node) { - if (!node) return null; - var childKey = setting.data.key.children, - p = node.parentTId ? node.getParentNode() : data.getRoot(setting); - for (var i=0, l=p[childKey].length; i 0))); - }, - clone: function (obj){ - if (obj === null) return null; - var o = tools.isArray(obj) ? [] : {}; - for(var i in obj){ - o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]); - } - return o; - }, - eqs: function(str1, str2) { - return str1.toLowerCase() === str2.toLowerCase(); - }, - isArray: function(arr) { - return Object.prototype.toString.apply(arr) === "[object Array]"; - }, - $: function(node, exp, setting) { - if (!!exp && typeof exp != "string") { - setting = exp; - exp = ""; - } - if (typeof node == "string") { - return $(node, setting ? setting.treeObj.get(0).ownerDocument : null); - } else { - return $("#" + node.tId + exp, setting ? setting.treeObj : null); - } - }, - getMDom: function (setting, curDom, targetExpr) { - if (!curDom) return null; - while (curDom && curDom.id !== setting.treeId) { - for (var i=0, l=targetExpr.length; curDom.tagName && i 0 ); - }, - uCanDo: function(setting, e) { - return true; - } - }, - //method of operate ztree dom - view = { - addNodes: function(setting, parentNode, newNodes, isSilent) { - if (setting.data.keep.leaf && parentNode && !parentNode.isParent) { - return; - } - if (!tools.isArray(newNodes)) { - newNodes = [newNodes]; - } - if (setting.data.simpleData.enable) { - newNodes = data.transformTozTreeFormat(setting, newNodes); - } - if (parentNode) { - var target_switchObj = $$(parentNode, consts.id.SWITCH, setting), - target_icoObj = $$(parentNode, consts.id.ICON, setting), - target_ulObj = $$(parentNode, consts.id.UL, setting); - - if (!parentNode.open) { - view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE); - view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); - parentNode.open = false; - target_ulObj.css({ - "display": "none" - }); - } - - data.addNodesData(setting, parentNode, newNodes); - view.createNodes(setting, parentNode.level + 1, newNodes, parentNode); - if (!isSilent) { - view.expandCollapseParentNode(setting, parentNode, true); - } - } else { - data.addNodesData(setting, data.getRoot(setting), newNodes); - view.createNodes(setting, 0, newNodes, null); - } - }, - appendNodes: function(setting, level, nodes, parentNode, initFlag, openFlag) { - if (!nodes) return []; - var html = [], - childKey = setting.data.key.children; - for (var i = 0, l = nodes.length; i < l; i++) { - var node = nodes[i]; - if (initFlag) { - var tmpPNode = (parentNode) ? parentNode: data.getRoot(setting), - tmpPChild = tmpPNode[childKey], - isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)), - isLastNode = (i == (nodes.length - 1)); - data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); - data.addNodeCache(setting, node); - } - - var childHtml = []; - if (node[childKey] && node[childKey].length > 0) { - //make child html first, because checkType - childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open); - } - if (openFlag) { - - view.makeDOMNodeMainBefore(html, setting, node); - view.makeDOMNodeLine(html, setting, node); - data.getBeforeA(setting, node, html); - view.makeDOMNodeNameBefore(html, setting, node); - data.getInnerBeforeA(setting, node, html); - view.makeDOMNodeIcon(html, setting, node); - data.getInnerAfterA(setting, node, html); - view.makeDOMNodeNameAfter(html, setting, node); - data.getAfterA(setting, node, html); - if (node.isParent && node.open) { - view.makeUlHtml(setting, node, html, childHtml.join('')); - } - view.makeDOMNodeMainAfter(html, setting, node); - data.addCreatedNode(setting, node); - } - } - return html; - }, - appendParentULDom: function(setting, node) { - var html = [], - nObj = $$(node, setting); - if (!nObj.get(0) && !!node.parentTId) { - view.appendParentULDom(setting, node.getParentNode()); - nObj = $$(node, setting); - } - var ulObj = $$(node, consts.id.UL, setting); - if (ulObj.get(0)) { - ulObj.remove(); - } - var childKey = setting.data.key.children, - childHtml = view.appendNodes(setting, node.level+1, node[childKey], node, false, true); - view.makeUlHtml(setting, node, html, childHtml.join('')); - nObj.append(html.join('')); - }, - asyncNode: function(setting, node, isSilent, callback) { - var i, l; - if (node && !node.isParent) { - tools.apply(callback); - return false; - } else if (node && node.isAjaxing) { - return false; - } else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) { - tools.apply(callback); - return false; - } - if (node) { - node.isAjaxing = true; - var icoObj = $$(node, consts.id.ICON, setting); - icoObj.attr({"style":"", "class":consts.className.BUTTON + " " + consts.className.ICO_LOADING}); - } - - var tmpParam = {}; - for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) { - var pKey = setting.async.autoParam[i].split("="), spKey = pKey; - if (pKey.length>1) { - spKey = pKey[1]; - pKey = pKey[0]; - } - tmpParam[spKey] = node[pKey]; - } - if (tools.isArray(setting.async.otherParam)) { - for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) { - tmpParam[setting.async.otherParam[i]] = setting.async.otherParam[i + 1]; - } - } else { - for (var p in setting.async.otherParam) { - tmpParam[p] = setting.async.otherParam[p]; - } - } - - var _tmpV = data.getRoot(setting)._ver; - $.ajax({ - contentType: setting.async.contentType, - cache: false, - type: setting.async.type, - url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), - data: tmpParam, - dataType: setting.async.dataType, - success: function(msg) { - if (_tmpV != data.getRoot(setting)._ver) { - return; - } - var newNodes = []; - try { - if (!msg || msg.length == 0) { - newNodes = []; - } else if (typeof msg == "string") { - newNodes = eval("(" + msg + ")"); - } else { - newNodes = msg; - } - } catch(err) { - newNodes = msg; - } - - if (node) { - node.isAjaxing = null; - node.zAsync = true; - } - view.setNodeLineIcos(setting, node); - if (newNodes && newNodes !== "") { - newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); - view.addNodes(setting, node, !!newNodes ? tools.clone(newNodes) : [], !!isSilent); - } else { - view.addNodes(setting, node, [], !!isSilent); - } - setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]); - tools.apply(callback); - }, - error: function(XMLHttpRequest, textStatus, errorThrown) { - if (_tmpV != data.getRoot(setting)._ver) { - return; - } - if (node) node.isAjaxing = null; - view.setNodeLineIcos(setting, node); - setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); - } - }); - return true; - }, - cancelPreSelectedNode: function (setting, node, excludeNode) { - var list = data.getRoot(setting).curSelectedList, - i, n; - for (i=list.length-1; i>=0; i--) { - n = list[i]; - if (node === n || (!node && (!excludeNode || excludeNode !== n))) { - $$(n, consts.id.A, setting).removeClass(consts.node.CURSELECTED); - if (node) { - data.removeSelectedNode(setting, node); - setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); - break; - } else { - list.splice(i, 1); - setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); - } - } - } - }, - createNodeCallback: function(setting) { - if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { - var root = data.getRoot(setting); - while (root.createdNodes.length>0) { - var node = root.createdNodes.shift(); - tools.apply(setting.view.addDiyDom, [setting.treeId, node]); - if (!!setting.callback.onNodeCreated) { - setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]); - } - } - } - }, - createNodes: function(setting, level, nodes, parentNode) { - if (!nodes || nodes.length == 0) return; - var root = data.getRoot(setting), - childKey = setting.data.key.children, - openFlag = !parentNode || parentNode.open || !!$$(parentNode[childKey][0], setting).get(0); - root.createdNodes = []; - var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag); - if (!parentNode) { - setting.treeObj.append(zTreeHtml.join('')); - } else { - var ulObj = $$(parentNode, consts.id.UL, setting); - if (ulObj.get(0)) { - ulObj.append(zTreeHtml.join('')); - } - } - view.createNodeCallback(setting); - }, - destroy: function(setting) { - if (!setting) return; - data.initCache(setting); - data.initRoot(setting); - event.unbindTree(setting); - event.unbindEvent(setting); - setting.treeObj.empty(); - delete settings[setting.treeId]; - }, - expandCollapseNode: function(setting, node, expandFlag, animateFlag, callback) { - var root = data.getRoot(setting), - childKey = setting.data.key.children; - if (!node) { - tools.apply(callback, []); - return; - } - if (root.expandTriggerFlag) { - var _callback = callback; - callback = function(){ - if (_callback) _callback(); - if (node.open) { - setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]); - } else { - setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]); - } - }; - root.expandTriggerFlag = false; - } - if (!node.open && node.isParent && ((!$$(node, consts.id.UL, setting).get(0)) || (node[childKey] && node[childKey].length>0 && !$$(node[childKey][0], setting).get(0)))) { - view.appendParentULDom(setting, node); - view.createNodeCallback(setting); - } - if (node.open == expandFlag) { - tools.apply(callback, []); - return; - } - var ulObj = $$(node, consts.id.UL, setting), - switchObj = $$(node, consts.id.SWITCH, setting), - icoObj = $$(node, consts.id.ICON, setting); - - if (node.isParent) { - node.open = !node.open; - if (node.iconOpen && node.iconClose) { - icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); - } - - if (node.open) { - view.replaceSwitchClass(node, switchObj, consts.folder.OPEN); - view.replaceIcoClass(node, icoObj, consts.folder.OPEN); - if (animateFlag == false || setting.view.expandSpeed == "") { - ulObj.show(); - tools.apply(callback, []); - } else { - if (node[childKey] && node[childKey].length > 0) { - ulObj.slideDown(setting.view.expandSpeed, callback); - } else { - ulObj.show(); - tools.apply(callback, []); - } - } - } else { - view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); - view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); - if (animateFlag == false || setting.view.expandSpeed == "" || !(node[childKey] && node[childKey].length > 0)) { - ulObj.hide(); - tools.apply(callback, []); - } else { - ulObj.slideUp(setting.view.expandSpeed, callback); - } - } - } else { - tools.apply(callback, []); - } - }, - expandCollapseParentNode: function(setting, node, expandFlag, animateFlag, callback) { - if (!node) return; - if (!node.parentTId) { - view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback); - return; - } else { - view.expandCollapseNode(setting, node, expandFlag, animateFlag); - } - if (node.parentTId) { - view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback); - } - }, - expandCollapseSonNode: function(setting, node, expandFlag, animateFlag, callback) { - var root = data.getRoot(setting), - childKey = setting.data.key.children, - treeNodes = (node) ? node[childKey]: root[childKey], - selfAnimateSign = (node) ? false : animateFlag, - expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; - data.getRoot(setting).expandTriggerFlag = false; - if (treeNodes) { - for (var i = 0, l = treeNodes.length; i < l; i++) { - if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); - } - } - data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; - view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback ); - }, - isSelectedNode: function (setting, node) { - if (!node) { - return false; - } - var list = data.getRoot(setting).curSelectedList, - i; - for (i=list.length-1; i>=0; i--) { - if (node === list[i]) { - return true; - } - } - return false; - }, - makeDOMNodeIcon: function(html, setting, node) { - var nameStr = data.getNodeName(setting, node), - name = setting.view.nameIsHTML ? nameStr : nameStr.replace(/&/g,'&').replace(//g,'>'); - html.push("",name,""); - }, - makeDOMNodeLine: function(html, setting, node) { - html.push(""); - }, - makeDOMNodeMainAfter: function(html, setting, node) { - html.push("
  • "); - }, - makeDOMNodeMainBefore: function(html, setting, node) { - html.push("
  • "); - }, - makeDOMNodeNameAfter: function(html, setting, node) { - html.push(""); - }, - makeDOMNodeNameBefore: function(html, setting, node) { - var title = data.getNodeTitle(setting, node), - url = view.makeNodeUrl(setting, node), - fontcss = view.makeNodeFontCss(setting, node), - fontStyle = []; - for (var f in fontcss) { - fontStyle.push(f, ":", fontcss[f], ";"); - } - html.push(" 0) ? "href='" + url + "'" : ""), " target='",view.makeNodeTarget(node),"' style='", fontStyle.join(''), - "'"); - if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && title) {html.push("title='", title.replace(/'/g,"'").replace(//g,'>'),"'");} - html.push(">"); - }, - makeNodeFontCss: function(setting, node) { - var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); - return (fontCss && ((typeof fontCss) != "function")) ? fontCss : {}; - }, - makeNodeIcoClass: function(setting, node) { - var icoCss = ["ico"]; - if (!node.isAjaxing) { - icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0]; - if (node.isParent) { - icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); - } else { - icoCss.push(consts.folder.DOCU); - } - } - return consts.className.BUTTON + " " + icoCss.join('_'); - }, - makeNodeIcoStyle: function(setting, node) { - var icoStyle = []; - if (!node.isAjaxing) { - var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon; - if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); - if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { - icoStyle.push("width:0px;height:0px;"); - } - } - return icoStyle.join(''); - }, - makeNodeLineClass: function(setting, node) { - var lineClass = []; - if (setting.view.showLine) { - if (node.level == 0 && node.isFirstNode && node.isLastNode) { - lineClass.push(consts.line.ROOT); - } else if (node.level == 0 && node.isFirstNode) { - lineClass.push(consts.line.ROOTS); - } else if (node.isLastNode) { - lineClass.push(consts.line.BOTTOM); - } else { - lineClass.push(consts.line.CENTER); - } - } else { - lineClass.push(consts.line.NOLINE); - } - if (node.isParent) { - lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); - } else { - lineClass.push(consts.folder.DOCU); - } - return view.makeNodeLineClassEx(node) + lineClass.join('_'); - }, - makeNodeLineClassEx: function(node) { - return consts.className.BUTTON + " " + consts.className.LEVEL + node.level + " " + consts.className.SWITCH + " "; - }, - makeNodeTarget: function(node) { - return (node.target || "_blank"); - }, - makeNodeUrl: function(setting, node) { - var urlKey = setting.data.key.url; - return node[urlKey] ? node[urlKey] : null; - }, - makeUlHtml: function(setting, node, html, content) { - html.push("
      "); - html.push(content); - html.push("
    "); - }, - makeUlLineClass: function(setting, node) { - return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : ""); - }, - removeChildNodes: function(setting, node) { - if (!node) return; - var childKey = setting.data.key.children, - nodes = node[childKey]; - if (!nodes) return; - - for (var i = 0, l = nodes.length; i < l; i++) { - data.removeNodeCache(setting, nodes[i]); - } - data.removeSelectedNode(setting); - delete node[childKey]; - - if (!setting.data.keep.parent) { - node.isParent = false; - node.open = false; - var tmp_switchObj = $$(node, consts.id.SWITCH, setting), - tmp_icoObj = $$(node, consts.id.ICON, setting); - view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU); - view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU); - $$(node, consts.id.UL, setting).remove(); - } else { - $$(node, consts.id.UL, setting).empty(); - } - }, - setFirstNode: function(setting, parentNode) { - var childKey = setting.data.key.children, childLength = parentNode[childKey].length; - if ( childLength > 0) { - parentNode[childKey][0].isFirstNode = true; - } - }, - setLastNode: function(setting, parentNode) { - var childKey = setting.data.key.children, childLength = parentNode[childKey].length; - if ( childLength > 0) { - parentNode[childKey][childLength - 1].isLastNode = true; - } - }, - removeNode: function(setting, node) { - var root = data.getRoot(setting), - childKey = setting.data.key.children, - parentNode = (node.parentTId) ? node.getParentNode() : root; - - node.isFirstNode = false; - node.isLastNode = false; - node.getPreNode = function() {return null;}; - node.getNextNode = function() {return null;}; - - if (!data.getNodeCache(setting, node.tId)) { - return; - } - - $$(node, setting).remove(); - data.removeNodeCache(setting, node); - data.removeSelectedNode(setting, node); - - for (var i = 0, l = parentNode[childKey].length; i < l; i++) { - if (parentNode[childKey][i].tId == node.tId) { - parentNode[childKey].splice(i, 1); - break; - } - } - view.setFirstNode(setting, parentNode); - view.setLastNode(setting, parentNode); - - var tmp_ulObj,tmp_switchObj,tmp_icoObj, - childLength = parentNode[childKey].length; - - //repair nodes old parent - if (!setting.data.keep.parent && childLength == 0) { - //old parentNode has no child nodes - parentNode.isParent = false; - parentNode.open = false; - tmp_ulObj = $$(parentNode, consts.id.UL, setting); - tmp_switchObj = $$(parentNode, consts.id.SWITCH, setting); - tmp_icoObj = $$(parentNode, consts.id.ICON, setting); - view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU); - view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU); - tmp_ulObj.css("display", "none"); - - } else if (setting.view.showLine && childLength > 0) { - //old parentNode has child nodes - var newLast = parentNode[childKey][childLength - 1]; - tmp_ulObj = $$(newLast, consts.id.UL, setting); - tmp_switchObj = $$(newLast, consts.id.SWITCH, setting); - tmp_icoObj = $$(newLast, consts.id.ICON, setting); - if (parentNode == root) { - if (parentNode[childKey].length == 1) { - //node was root, and ztree has only one root after move node - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT); - } else { - var tmp_first_switchObj = $$(parentNode[childKey][0], consts.id.SWITCH, setting); - view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS); - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); - } - } else { - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); - } - tmp_ulObj.removeClass(consts.line.LINE); - } - }, - replaceIcoClass: function(node, obj, newName) { - if (!obj || node.isAjaxing) return; - var tmpName = obj.attr("class"); - if (tmpName == undefined) return; - var tmpList = tmpName.split("_"); - switch (newName) { - case consts.folder.OPEN: - case consts.folder.CLOSE: - case consts.folder.DOCU: - tmpList[tmpList.length-1] = newName; - break; - } - obj.attr("class", tmpList.join("_")); - }, - replaceSwitchClass: function(node, obj, newName) { - if (!obj) return; - var tmpName = obj.attr("class"); - if (tmpName == undefined) return; - var tmpList = tmpName.split("_"); - switch (newName) { - case consts.line.ROOT: - case consts.line.ROOTS: - case consts.line.CENTER: - case consts.line.BOTTOM: - case consts.line.NOLINE: - tmpList[0] = view.makeNodeLineClassEx(node) + newName; - break; - case consts.folder.OPEN: - case consts.folder.CLOSE: - case consts.folder.DOCU: - tmpList[1] = newName; - break; - } - obj.attr("class", tmpList.join("_")); - if (newName !== consts.folder.DOCU) { - obj.removeAttr("disabled"); - } else { - obj.attr("disabled", "disabled"); - } - }, - selectNode: function(setting, node, addFlag) { - if (!addFlag) { - view.cancelPreSelectedNode(setting, null, node); - } - $$(node, consts.id.A, setting).addClass(consts.node.CURSELECTED); - data.addSelectedNode(setting, node); - setting.treeObj.trigger(consts.event.SELECTED, [event, setting.treeId, node]); - }, - setNodeFontCss: function(setting, treeNode) { - var aObj = $$(treeNode, consts.id.A, setting), - fontCss = view.makeNodeFontCss(setting, treeNode); - if (fontCss) { - aObj.css(fontCss); - } - }, - setNodeLineIcos: function(setting, node) { - if (!node) return; - var switchObj = $$(node, consts.id.SWITCH, setting), - ulObj = $$(node, consts.id.UL, setting), - icoObj = $$(node, consts.id.ICON, setting), - ulLine = view.makeUlLineClass(setting, node); - if (ulLine.length==0) { - ulObj.removeClass(consts.line.LINE); - } else { - ulObj.addClass(ulLine); - } - switchObj.attr("class", view.makeNodeLineClass(setting, node)); - if (node.isParent) { - switchObj.removeAttr("disabled"); - } else { - switchObj.attr("disabled", "disabled"); - } - icoObj.removeAttr("style"); - icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); - icoObj.attr("class", view.makeNodeIcoClass(setting, node)); - }, - setNodeName: function(setting, node) { - var title = data.getNodeTitle(setting, node), - nObj = $$(node, consts.id.SPAN, setting); - nObj.empty(); - if (setting.view.nameIsHTML) { - nObj.html(data.getNodeName(setting, node)); - } else { - nObj.text(data.getNodeName(setting, node)); - } - if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle)) { - var aObj = $$(node, consts.id.A, setting); - aObj.attr("title", !title ? "" : title); - } - }, - setNodeTarget: function(setting, node) { - var aObj = $$(node, consts.id.A, setting); - aObj.attr("target", view.makeNodeTarget(node)); - }, - setNodeUrl: function(setting, node) { - var aObj = $$(node, consts.id.A, setting), - url = view.makeNodeUrl(setting, node); - if (url == null || url.length == 0) { - aObj.removeAttr("href"); - } else { - aObj.attr("href", url); - } - }, - switchNode: function(setting, node) { - if (node.open || !tools.canAsync(setting, node)) { - view.expandCollapseNode(setting, node, !node.open); - } else if (setting.async.enable) { - if (!view.asyncNode(setting, node)) { - view.expandCollapseNode(setting, node, !node.open); - return; - } - } else if (node) { - view.expandCollapseNode(setting, node, !node.open); - } - } - }; - // zTree defind - $.fn.zTree = { - consts : _consts, - _z : { - tools: tools, - view: view, - event: event, - data: data - }, - getZTreeObj: function(treeId) { - var o = data.getZTreeTools(treeId); - return o ? o : null; - }, - destroy: function(treeId) { - if (!!treeId && treeId.length > 0) { - view.destroy(data.getSetting(treeId)); - } else { - for(var s in settings) { - view.destroy(settings[s]); - } - } - }, - init: function(obj, zSetting, zNodes) { - var setting = tools.clone(_setting); - $.extend(true, setting, zSetting); - setting.treeId = obj.attr("id"); - setting.treeObj = obj; - setting.treeObj.empty(); - settings[setting.treeId] = setting; - //For some older browser,(e.g., ie6) - if(typeof document.body.style.maxHeight === "undefined") { - setting.view.expandSpeed = ""; - } - data.initRoot(setting); - var root = data.getRoot(setting), - childKey = setting.data.key.children; - zNodes = zNodes ? tools.clone(tools.isArray(zNodes)? zNodes : [zNodes]) : []; - if (setting.data.simpleData.enable) { - root[childKey] = data.transformTozTreeFormat(setting, zNodes); - } else { - root[childKey] = zNodes; - } - - data.initCache(setting); - event.unbindTree(setting); - event.bindTree(setting); - event.unbindEvent(setting); - event.bindEvent(setting); - - var zTreeTools = { - setting : setting, - addNodes : function(parentNode, newNodes, isSilent) { - if (!newNodes) return null; - if (!parentNode) parentNode = null; - if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null; - var xNewNodes = tools.clone(tools.isArray(newNodes)? newNodes: [newNodes]); - function addCallback() { - view.addNodes(setting, parentNode, xNewNodes, (isSilent==true)); - } - - if (tools.canAsync(setting, parentNode)) { - view.asyncNode(setting, parentNode, isSilent, addCallback); - } else { - addCallback(); - } - return xNewNodes; - }, - cancelSelectedNode : function(node) { - view.cancelPreSelectedNode(setting, node); - }, - destroy : function() { - view.destroy(setting); - }, - expandAll : function(expandFlag) { - expandFlag = !!expandFlag; - view.expandCollapseSonNode(setting, null, expandFlag, true); - return expandFlag; - }, - expandNode : function(node, expandFlag, sonSign, focus, callbackFlag) { - if (!node || !node.isParent) return null; - if (expandFlag !== true && expandFlag !== false) { - expandFlag = !node.open; - } - callbackFlag = !!callbackFlag; - - if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) { - return null; - } else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) { - return null; - } - if (expandFlag && node.parentTId) { - view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, false); - } - if (expandFlag === node.open && !sonSign) { - return null; - } - - data.getRoot(setting).expandTriggerFlag = callbackFlag; - if (!tools.canAsync(setting, node) && sonSign) { - view.expandCollapseSonNode(setting, node, expandFlag, true, function() { - if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e){}} - }); - } else { - node.open = !expandFlag; - view.switchNode(this.setting, node); - if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e){}} - } - return expandFlag; - }, - getNodes : function() { - return data.getNodes(setting); - }, - getNodeByParam : function(key, value, parentNode) { - if (!key) return null; - return data.getNodeByParam(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodeByTId : function(tId) { - return data.getNodeCache(setting, tId); - }, - getNodesByParam : function(key, value, parentNode) { - if (!key) return null; - return data.getNodesByParam(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodesByParamFuzzy : function(key, value, parentNode) { - if (!key) return null; - return data.getNodesByParamFuzzy(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodesByFilter: function(filter, isSingle, parentNode, invokeParam) { - isSingle = !!isSingle; - if (!filter || (typeof filter != "function")) return (isSingle ? null : []); - return data.getNodesByFilter(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), filter, isSingle, invokeParam); - }, - getNodeIndex : function(node) { - if (!node) return null; - var childKey = setting.data.key.children, - parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); - for (var i=0, l = parentNode[childKey].length; i < l; i++) { - if (parentNode[childKey][i] == node) return i; - } - return -1; - }, - getSelectedNodes : function() { - var r = [], list = data.getRoot(setting).curSelectedList; - for (var i=0, l=list.length; i 0) { - view.createNodes(setting, 0, root[childKey]); - } else if (setting.async.enable && setting.async.url && setting.async.url !== '') { - view.asyncNode(setting); - } - return zTreeTools; - } - }; - - var zt = $.fn.zTree, - $$ = tools.$, - consts = zt.consts; + var zt = $.fn.zTree, + $$ = tools.$, + consts = zt.consts; })(jQuery);/* * JQuery zTree excheck v3.5.18 * http://zTree.me/ @@ -35704,619 +35540,619 @@ BI.shortcut("bi.custom_tree", BI.CustomTree);/* * email: hunter.z@263.net * Date: 2015-06-18 */ -(function($){ - //default consts of excheck - var _consts = { - event: { - CHECK: "ztree_check" - }, - id: { - CHECK: "_check" - }, - checkbox: { - STYLE: "checkbox", - DEFAULT: "chk", - DISABLED: "disable", - FALSE: "false", - TRUE: "true", - FULL: "full", - PART: "part", - FOCUS: "focus" - }, - radio: { - STYLE: "radio", - TYPE_ALL: "all", - TYPE_LEVEL: "level" - } - }, - //default setting of excheck - _setting = { - check: { - enable: false, - autoCheckTrigger: false, - chkStyle: _consts.checkbox.STYLE, - nocheckInherit: false, - chkDisabledInherit: false, - radioType: _consts.radio.TYPE_LEVEL, - chkboxType: { - "Y": "ps", - "N": "ps" - } - }, - data: { - key: { - checked: "checked" - } - }, - callback: { - beforeCheck:null, - onCheck:null - } - }, - //default root of excheck - _initRoot = function (setting) { - var r = data.getRoot(setting); - r.radioCheckedList = []; - }, - //default cache of excheck - _initCache = function(treeId) {}, - //default bind event of excheck - _bindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.bind(c.CHECK, function (event, srcEvent, treeId, node) { - event.srcEvent = srcEvent; - tools.apply(setting.callback.onCheck, [event, treeId, node]); - }); - }, - _unbindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.unbind(c.CHECK); - }, - //default event proxy of excheck - _eventProxy = function(e) { - var target = e.target, - setting = data.getSetting(e.data.treeId), - tId = "", node = null, - nodeEventType = "", treeEventType = "", - nodeEventCallback = null, treeEventCallback = null; - - if (tools.eqs(e.type, "mouseover")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "mouseoverCheck"; - } - } else if (tools.eqs(e.type, "mouseout")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "mouseoutCheck"; - } - } else if (tools.eqs(e.type, "click")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "checkNode"; - } - } - if (tId.length>0) { - node = data.getNodeCache(setting, tId); - switch (nodeEventType) { - case "checkNode" : - nodeEventCallback = _handler.onCheckNode; - break; - case "mouseoverCheck" : - nodeEventCallback = _handler.onMouseoverCheck; - break; - case "mouseoutCheck" : - nodeEventCallback = _handler.onMouseoutCheck; - break; - } - } - var proxyResult = { - stop: nodeEventType === "checkNode", - node: node, - nodeEventType: nodeEventType, - nodeEventCallback: nodeEventCallback, - treeEventType: treeEventType, - treeEventCallback: treeEventCallback - }; - return proxyResult - }, - //default init node of excheck - _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { - if (!n) return; - var checkedKey = setting.data.key.checked; - if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); - n[checkedKey] = !!n[checkedKey]; - n.checkedOld = n[checkedKey]; - if (typeof n.nocheck == "string") n.nocheck = tools.eqs(n.nocheck, "true"); - n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); - if (typeof n.chkDisabled == "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); - n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); - if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); - n.halfCheck = !!n.halfCheck; - n.check_Child_State = -1; - n.check_Focus = false; - n.getCheckStatus = function() {return data.getCheckStatus(setting, n);}; - - if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey] ) { - var r = data.getRoot(setting); - r.radioCheckedList.push(n); - } - }, - //add dom for check - _beforeA = function(setting, node, html) { - var checkedKey = setting.data.key.checked; - if (setting.check.enable) { - data.makeChkFlag(setting, node); - html.push(""); - } - }, - //update zTreeObj, add method of check - _zTreeTools = function(setting, zTreeTools) { - zTreeTools.checkNode = function(node, checked, checkTypeFlag, callbackFlag) { - var checkedKey = this.setting.data.key.checked; - if (node.chkDisabled === true) return; - if (checked !== true && checked !== false) { - checked = !node[checkedKey]; - } - callbackFlag = !!callbackFlag; - - if (node[checkedKey] === checked && !checkTypeFlag) { - return; - } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { - return; - } - if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { - node[checkedKey] = checked; - var checkObj = $$(node, consts.id.CHECK, this.setting); - if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); - view.setChkClass(this.setting, checkObj, node); - view.repairParentChkClassWithSelf(this.setting, node); - if (callbackFlag) { - this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); - } - } - } - - zTreeTools.checkAllNodes = function(checked) { - view.repairAllChk(this.setting, !!checked); - } - - zTreeTools.getCheckedNodes = function(checked) { - var childKey = this.setting.data.key.children; - checked = (checked !== false); - return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); - } - - zTreeTools.getChangeCheckedNodes = function() { - var childKey = this.setting.data.key.children; - return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); - } - - zTreeTools.setChkDisabled = function(node, disabled, inheritParent, inheritChildren) { - disabled = !!disabled; - inheritParent = !!inheritParent; - inheritChildren = !!inheritChildren; - view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); - view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); - } - - var _updateNode = zTreeTools.updateNode; - zTreeTools.updateNode = function(node, checkTypeFlag) { - if (_updateNode) _updateNode.apply(zTreeTools, arguments); - if (!node || !this.setting.check.enable) return; - var nObj = $$(node, this.setting); - if (nObj.get(0) && tools.uCanDo(this.setting)) { - var checkObj = $$(node, consts.id.CHECK, this.setting); - if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); - view.setChkClass(this.setting, checkObj, node); - view.repairParentChkClassWithSelf(this.setting, node); - } - } - }, - //method of operate data - _data = { - getRadioCheckedList: function(setting) { - var checkedList = data.getRoot(setting).radioCheckedList; - for (var i=0, j=checkedList.length; i -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) - }; - return r; - }, - getTreeCheckedNodes: function(setting, nodes, checked, results) { - if (!nodes) return []; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); - results = !results ? [] : results; - for (var i = 0, l = nodes.length; i < l; i++) { - if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { - results.push(nodes[i]); - if(onlyOne) { - break; - } - } - data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); - if(onlyOne && results.length > 0) { - break; - } - } - return results; - }, - getTreeChangeCheckedNodes: function(setting, nodes, results) { - if (!nodes) return []; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked; - results = !results ? [] : results; - for (var i = 0, l = nodes.length; i < l; i++) { - if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { - results.push(nodes[i]); - } - data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); - } - return results; - }, - makeChkFlag: function(setting, node) { - if (!node) return; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - chkFlag = -1; - if (node[childKey]) { - for (var i = 0, l = node[childKey].length; i < l; i++) { - var cNode = node[childKey][i]; - var tmp = -1; - if (setting.check.chkStyle == consts.radio.STYLE) { - if (cNode.nocheck === true || cNode.chkDisabled === true) { - tmp = cNode.check_Child_State; - } else if (cNode.halfCheck === true) { - tmp = 2; - } else if (cNode[checkedKey]) { - tmp = 2; - } else { - tmp = cNode.check_Child_State > 0 ? 2:0; - } - if (tmp == 2) { - chkFlag = 2; break; - } else if (tmp == 0){ - chkFlag = 0; - } - } else if (setting.check.chkStyle == consts.checkbox.STYLE) { - if (cNode.nocheck === true || cNode.chkDisabled === true) { - tmp = cNode.check_Child_State; - } else if (cNode.halfCheck === true) { - tmp = 1; - } else if (cNode[checkedKey] ) { - tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; - } else { - tmp = (cNode.check_Child_State > 0) ? 1 : 0; - } - if (tmp === 1) { - chkFlag = 1; break; - } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { - chkFlag = 1; break; - } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { - chkFlag = 1; break; - } else if (tmp > -1) { - chkFlag = tmp; - } - } - } - } - node.check_Child_State = chkFlag; - } - }, - //method of event proxy - _event = { - - }, - //method of event handler - _handler = { - onCheckNode: function (event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkedKey = setting.data.key.checked; - if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; - node[checkedKey] = !node[checkedKey]; - view.checkNodeRelation(setting, node); - var checkObj = $$(node, consts.id.CHECK, setting); - view.setChkClass(setting, checkObj, node); - view.repairParentChkClassWithSelf(setting, node); - setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); - return true; - }, - onMouseoverCheck: function(event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkObj = $$(node, consts.id.CHECK, setting); - node.check_Focus = true; - view.setChkClass(setting, checkObj, node); - return true; - }, - onMouseoutCheck: function(event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkObj = $$(node, consts.id.CHECK, setting); - node.check_Focus = false; - view.setChkClass(setting, checkObj, node); - return true; - } - }, - //method of tools for zTree - _tools = { - - }, - //method of operate ztree dom - _view = { - checkNodeRelation: function(setting, node) { - var pNode, i, l, - childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - r = consts.radio; - if (setting.check.chkStyle == r.STYLE) { - var checkedList = data.getRadioCheckedList(setting); - if (node[checkedKey]) { - if (setting.check.radioType == r.TYPE_ALL) { - for (i = checkedList.length-1; i >= 0; i--) { - pNode = checkedList[i]; - if (pNode[checkedKey] && pNode != node) { - pNode[checkedKey] = false; - checkedList.splice(i, 1); - - view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); - if (pNode.parentTId != node.parentTId) { - view.repairParentChkClassWithSelf(setting, pNode); - } - } - } - checkedList.push(node); - } else { - var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); - for (i = 0, l = parentNode[childKey].length; i < l; i++) { - pNode = parentNode[childKey][i]; - if (pNode[checkedKey] && pNode != node) { - pNode[checkedKey] = false; - view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); - } - } - } - } else if (setting.check.radioType == r.TYPE_ALL) { - for (i = 0, l = checkedList.length; i < l; i++) { - if (node == checkedList[i]) { - checkedList.splice(i, 1); - break; - } - } - } - - } else { - if (node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { - view.setSonNodeCheckBox(setting, node, true); - } - if (!node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.N.indexOf("s") > -1)) { - view.setSonNodeCheckBox(setting, node, false); - } - if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { - view.setParentNodeCheckBox(setting, node, true); - } - if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { - view.setParentNodeCheckBox(setting, node, false); - } - } - }, - makeChkClass: function(setting, node) { - var checkedKey = setting.data.key.checked, - c = consts.checkbox, r = consts.radio, - fullStyle = ""; - if (node.chkDisabled === true) { - fullStyle = c.DISABLED; - } else if (node.halfCheck) { - fullStyle = c.PART; - } else if (setting.check.chkStyle == r.STYLE) { - fullStyle = (node.check_Child_State < 1)? c.FULL:c.PART; - } else { - fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL:c.PART) : ((node.check_Child_State < 1)? c.FULL:c.PART); - } - var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; - chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; - return consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; - }, - repairAllChk: function(setting, checked) { - if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { - var checkedKey = setting.data.key.checked, - childKey = setting.data.key.children, - root = data.getRoot(setting); - for (var i = 0, l = root[childKey].length; i 0) { - view.repairParentChkClass(setting, node[childKey][0]); - } else { - view.repairParentChkClass(setting, node); - } - }, - repairSonChkDisabled: function(setting, node, chkDisabled, inherit) { - if (!node) return; - var childKey = setting.data.key.children; - if (node.chkDisabled != chkDisabled) { - node.chkDisabled = chkDisabled; - } - view.repairChkClass(setting, node); - if (node[childKey] && inherit) { - for (var i = 0, l = node[childKey].length; i < l; i++) { - var sNode = node[childKey][i]; - view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); - } - } - }, - repairParentChkDisabled: function(setting, node, chkDisabled, inherit) { - if (!node) return; - if (node.chkDisabled != chkDisabled && inherit) { - node.chkDisabled = chkDisabled; - } - view.repairChkClass(setting, node); - view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); - }, - setChkClass: function(setting, obj, node) { - if (!obj) return; - if (node.nocheck === true) { - obj.hide(); - } else { - obj.show(); - } - obj.attr('class', view.makeChkClass(setting, node)); - }, - setParentNodeCheckBox: function(setting, node, value, srcNode) { - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - checkObj = $$(node, consts.id.CHECK, setting); - if (!srcNode) srcNode = node; - data.makeChkFlag(setting, node); - if (node.nocheck !== true && node.chkDisabled !== true) { - node[checkedKey] = value; - view.setChkClass(setting, checkObj, node); - if (setting.check.autoCheckTrigger && node != srcNode) { - setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); - } - } - if (node.parentTId) { - var pSign = true; - if (!value) { - var pNodes = node.getParentNode()[childKey]; - for (var i = 0, l = pNodes.length; i < l; i++) { - if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) +(function ($) { + // default consts of excheck + var _consts = { + event: { + CHECK: "ztree_check" + }, + id: { + CHECK: "_check" + }, + checkbox: { + STYLE: "checkbox", + DEFAULT: "chk", + DISABLED: "disable", + FALSE: "false", + TRUE: "true", + FULL: "full", + PART: "part", + FOCUS: "focus" + }, + radio: { + STYLE: "radio", + TYPE_ALL: "all", + TYPE_LEVEL: "level" + } + }, + // default setting of excheck + _setting = { + check: { + enable: false, + autoCheckTrigger: false, + chkStyle: _consts.checkbox.STYLE, + nocheckInherit: false, + chkDisabledInherit: false, + radioType: _consts.radio.TYPE_LEVEL, + chkboxType: { + Y: "ps", + N: "ps" + } + }, + data: { + key: { + checked: "checked" + } + }, + callback: { + beforeCheck: null, + onCheck: null + } + }, + // default root of excheck + _initRoot = function (setting) { + var r = data.getRoot(setting); + r.radioCheckedList = []; + }, + // default cache of excheck + _initCache = function (treeId) {}, + // default bind event of excheck + _bindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.bind(c.CHECK, function (event, srcEvent, treeId, node) { + event.srcEvent = srcEvent; + tools.apply(setting.callback.onCheck, [event, treeId, node]); + }); + }, + _unbindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.unbind(c.CHECK); + }, + // default event proxy of excheck + _eventProxy = function (e) { + var target = e.target, + setting = data.getSetting(e.data.treeId), + tId = "", node = null, + nodeEventType = "", treeEventType = "", + nodeEventCallback = null, treeEventCallback = null; + + if (tools.eqs(e.type, "mouseover")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "mouseoverCheck"; + } + } else if (tools.eqs(e.type, "mouseout")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "mouseoutCheck"; + } + } else if (tools.eqs(e.type, "click")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "checkNode"; + } + } + if (tId.length > 0) { + node = data.getNodeCache(setting, tId); + switch (nodeEventType) { + case "checkNode" : + nodeEventCallback = _handler.onCheckNode; + break; + case "mouseoverCheck" : + nodeEventCallback = _handler.onMouseoverCheck; + break; + case "mouseoutCheck" : + nodeEventCallback = _handler.onMouseoutCheck; + break; + } + } + var proxyResult = { + stop: nodeEventType === "checkNode", + node: node, + nodeEventType: nodeEventType, + nodeEventCallback: nodeEventCallback, + treeEventType: treeEventType, + treeEventCallback: treeEventCallback + }; + return proxyResult; + }, + // default init node of excheck + _initNode = function (setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { + if (!n) return; + var checkedKey = setting.data.key.checked; + if (typeof n[checkedKey] === "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); + n[checkedKey] = !!n[checkedKey]; + n.checkedOld = n[checkedKey]; + if (typeof n.nocheck === "string") n.nocheck = tools.eqs(n.nocheck, "true"); + n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); + if (typeof n.chkDisabled === "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); + n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); + if (typeof n.halfCheck === "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); + n.halfCheck = !!n.halfCheck; + n.check_Child_State = -1; + n.check_Focus = false; + n.getCheckStatus = function () {return data.getCheckStatus(setting, n);}; + + if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey] ) { + var r = data.getRoot(setting); + r.radioCheckedList.push(n); + } + }, + // add dom for check + _beforeA = function (setting, node, html) { + var checkedKey = setting.data.key.checked; + if (setting.check.enable) { + data.makeChkFlag(setting, node); + html.push(""); + } + }, + // update zTreeObj, add method of check + _zTreeTools = function (setting, zTreeTools) { + zTreeTools.checkNode = function (node, checked, checkTypeFlag, callbackFlag) { + var checkedKey = this.setting.data.key.checked; + if (node.chkDisabled === true) return; + if (checked !== true && checked !== false) { + checked = !node[checkedKey]; + } + callbackFlag = !!callbackFlag; + + if (node[checkedKey] === checked && !checkTypeFlag) { + return; + } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { + return; + } + if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { + node[checkedKey] = checked; + var checkObj = $$(node, consts.id.CHECK, this.setting); + if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); + view.setChkClass(this.setting, checkObj, node); + view.repairParentChkClassWithSelf(this.setting, node); + if (callbackFlag) { + this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); + } + } + }; + + zTreeTools.checkAllNodes = function (checked) { + view.repairAllChk(this.setting, !!checked); + }; + + zTreeTools.getCheckedNodes = function (checked) { + var childKey = this.setting.data.key.children; + checked = (checked !== false); + return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); + }; + + zTreeTools.getChangeCheckedNodes = function () { + var childKey = this.setting.data.key.children; + return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); + }; + + zTreeTools.setChkDisabled = function (node, disabled, inheritParent, inheritChildren) { + disabled = !!disabled; + inheritParent = !!inheritParent; + inheritChildren = !!inheritChildren; + view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); + view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); + }; + + var _updateNode = zTreeTools.updateNode; + zTreeTools.updateNode = function (node, checkTypeFlag) { + if (_updateNode) _updateNode.apply(zTreeTools, arguments); + if (!node || !this.setting.check.enable) return; + var nObj = $$(node, this.setting); + if (nObj.get(0) && tools.uCanDo(this.setting)) { + var checkObj = $$(node, consts.id.CHECK, this.setting); + if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); + view.setChkClass(this.setting, checkObj, node); + view.repairParentChkClassWithSelf(this.setting, node); + } + }; + }, + // method of operate data + _data = { + getRadioCheckedList: function (setting) { + var checkedList = data.getRoot(setting).radioCheckedList; + for (var i = 0, j = checkedList.length; i < j; i++) { + if(!data.getNodeCache(setting, checkedList[i].tId)) { + checkedList.splice(i, 1); + i--; j--; + } + } + return checkedList; + }, + getCheckStatus: function (setting, node) { + if (!setting.check.enable || node.nocheck || node.chkDisabled) return null; + var checkedKey = setting.data.key.checked, + r = { + checked: node[checkedKey], + half: node.halfCheck ? node.halfCheck : (setting.check.chkStyle == consts.radio.STYLE ? (node.check_Child_State === 2) : (node[checkedKey] ? (node.check_Child_State > -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) + }; + return r; + }, + getTreeCheckedNodes: function (setting, nodes, checked, results) { + if (!nodes) return []; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); + results = !results ? [] : results; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { + results.push(nodes[i]); + if(onlyOne) { + break; + } + } + data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); + if(onlyOne && results.length > 0) { + break; + } + } + return results; + }, + getTreeChangeCheckedNodes: function (setting, nodes, results) { + if (!nodes) return []; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked; + results = !results ? [] : results; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { + results.push(nodes[i]); + } + data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); + } + return results; + }, + makeChkFlag: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + chkFlag = -1; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + var cNode = node[childKey][i]; + var tmp = -1; + if (setting.check.chkStyle == consts.radio.STYLE) { + if (cNode.nocheck === true || cNode.chkDisabled === true) { + tmp = cNode.check_Child_State; + } else if (cNode.halfCheck === true) { + tmp = 2; + } else if (cNode[checkedKey]) { + tmp = 2; + } else { + tmp = cNode.check_Child_State > 0 ? 2 : 0; + } + if (tmp == 2) { + chkFlag = 2; break; + } else if (tmp == 0) { + chkFlag = 0; + } + } else if (setting.check.chkStyle == consts.checkbox.STYLE) { + if (cNode.nocheck === true || cNode.chkDisabled === true) { + tmp = cNode.check_Child_State; + } else if (cNode.halfCheck === true) { + tmp = 1; + } else if (cNode[checkedKey] ) { + tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; + } else { + tmp = (cNode.check_Child_State > 0) ? 1 : 0; + } + if (tmp === 1) { + chkFlag = 1; break; + } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { + chkFlag = 1; break; + } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { + chkFlag = 1; break; + } else if (tmp > -1) { + chkFlag = tmp; + } + } + } + } + node.check_Child_State = chkFlag; + } + }, + // method of event proxy + _event = { + + }, + // method of event handler + _handler = { + onCheckNode: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkedKey = setting.data.key.checked; + if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; + node[checkedKey] = !node[checkedKey]; + view.checkNodeRelation(setting, node); + var checkObj = $$(node, consts.id.CHECK, setting); + view.setChkClass(setting, checkObj, node); + view.repairParentChkClassWithSelf(setting, node); + setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); + return true; + }, + onMouseoverCheck: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkObj = $$(node, consts.id.CHECK, setting); + node.check_Focus = true; + view.setChkClass(setting, checkObj, node); + return true; + }, + onMouseoutCheck: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkObj = $$(node, consts.id.CHECK, setting); + node.check_Focus = false; + view.setChkClass(setting, checkObj, node); + return true; + } + }, + // method of tools for zTree + _tools = { + + }, + // method of operate ztree dom + _view = { + checkNodeRelation: function (setting, node) { + var pNode, i, l, + childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + r = consts.radio; + if (setting.check.chkStyle == r.STYLE) { + var checkedList = data.getRadioCheckedList(setting); + if (node[checkedKey]) { + if (setting.check.radioType == r.TYPE_ALL) { + for (i = checkedList.length - 1; i >= 0; i--) { + pNode = checkedList[i]; + if (pNode[checkedKey] && pNode != node) { + pNode[checkedKey] = false; + checkedList.splice(i, 1); + + view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); + if (pNode.parentTId != node.parentTId) { + view.repairParentChkClassWithSelf(setting, pNode); + } + } + } + checkedList.push(node); + } else { + var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); + for (i = 0, l = parentNode[childKey].length; i < l; i++) { + pNode = parentNode[childKey][i]; + if (pNode[checkedKey] && pNode != node) { + pNode[checkedKey] = false; + view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); + } + } + } + } else if (setting.check.radioType == r.TYPE_ALL) { + for (i = 0, l = checkedList.length; i < l; i++) { + if (node == checkedList[i]) { + checkedList.splice(i, 1); + break; + } + } + } + + } else { + if (node[checkedKey] && (!node[childKey] || node[childKey].length == 0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { + view.setSonNodeCheckBox(setting, node, true); + } + if (!node[checkedKey] && (!node[childKey] || node[childKey].length == 0 || setting.check.chkboxType.N.indexOf("s") > -1)) { + view.setSonNodeCheckBox(setting, node, false); + } + if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { + view.setParentNodeCheckBox(setting, node, true); + } + if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { + view.setParentNodeCheckBox(setting, node, false); + } + } + }, + makeChkClass: function (setting, node) { + var checkedKey = setting.data.key.checked, + c = consts.checkbox, r = consts.radio, + fullStyle = ""; + if (node.chkDisabled === true) { + fullStyle = c.DISABLED; + } else if (node.halfCheck) { + fullStyle = c.PART; + } else if (setting.check.chkStyle == r.STYLE) { + fullStyle = (node.check_Child_State < 1) ? c.FULL : c.PART; + } else { + fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL : c.PART) : ((node.check_Child_State < 1) ? c.FULL : c.PART); + } + var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; + chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; + return consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; + }, + repairAllChk: function (setting, checked) { + if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { + var checkedKey = setting.data.key.checked, + childKey = setting.data.key.children, + root = data.getRoot(setting); + for (var i = 0, l = root[childKey].length; i < l; i++) { + var node = root[childKey][i]; + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = checked; + } + view.setSonNodeCheckBox(setting, node, checked); + } + } + }, + repairChkClass: function (setting, node) { + if (!node) return; + data.makeChkFlag(setting, node); + if (node.nocheck !== true) { + var checkObj = $$(node, consts.id.CHECK, setting); + view.setChkClass(setting, checkObj, node); + } + }, + repairParentChkClass: function (setting, node) { + if (!node || !node.parentTId) return; + var pNode = node.getParentNode(); + view.repairChkClass(setting, pNode); + view.repairParentChkClass(setting, pNode); + }, + repairParentChkClassWithSelf: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children; + if (node[childKey] && node[childKey].length > 0) { + view.repairParentChkClass(setting, node[childKey][0]); + } else { + view.repairParentChkClass(setting, node); + } + }, + repairSonChkDisabled: function (setting, node, chkDisabled, inherit) { + if (!node) return; + var childKey = setting.data.key.children; + if (node.chkDisabled != chkDisabled) { + node.chkDisabled = chkDisabled; + } + view.repairChkClass(setting, node); + if (node[childKey] && inherit) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + var sNode = node[childKey][i]; + view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); + } + } + }, + repairParentChkDisabled: function (setting, node, chkDisabled, inherit) { + if (!node) return; + if (node.chkDisabled != chkDisabled && inherit) { + node.chkDisabled = chkDisabled; + } + view.repairChkClass(setting, node); + view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); + }, + setChkClass: function (setting, obj, node) { + if (!obj) return; + if (node.nocheck === true) { + obj.hide(); + } else { + obj.show(); + } + obj.attr("class", view.makeChkClass(setting, node)); + }, + setParentNodeCheckBox: function (setting, node, value, srcNode) { + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + checkObj = $$(node, consts.id.CHECK, setting); + if (!srcNode) srcNode = node; + data.makeChkFlag(setting, node); + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = value; + view.setChkClass(setting, checkObj, node); + if (setting.check.autoCheckTrigger && node != srcNode) { + setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + } + } + if (node.parentTId) { + var pSign = true; + if (!value) { + var pNodes = node.getParentNode()[childKey]; + for (var i = 0, l = pNodes.length; i < l; i++) { + if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) || ((pNodes[i].nocheck === true || pNodes[i].chkDisabled === true) && pNodes[i].check_Child_State > 0)) { - pSign = false; - break; - } - } - } - if (pSign) { - view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); - } - } - }, - setSonNodeCheckBox: function(setting, node, value, srcNode) { - if (!node) return; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - checkObj = $$(node, consts.id.CHECK, setting); - if (!srcNode) srcNode = node; - - var hasDisable = false; - if (node[childKey]) { - for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { - var sNode = node[childKey][i]; - view.setSonNodeCheckBox(setting, sNode, value, srcNode); - if (sNode.chkDisabled === true) hasDisable = true; - } - } - - if (node != data.getRoot(setting) && node.chkDisabled !== true) { - if (hasDisable && node.nocheck !== true) { - data.makeChkFlag(setting, node); - } - if (node.nocheck !== true && node.chkDisabled !== true) { - node[checkedKey] = value; - if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; - } else { - node.check_Child_State = -1; - } - view.setChkClass(setting, checkObj, node); - if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { - setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); - } - } - - } - }, - - _z = { - tools: _tools, - view: _view, - event: _event, - data: _data - }; - $.extend(true, $.fn.zTree.consts, _consts); - $.extend(true, $.fn.zTree._z, _z); - - var zt = $.fn.zTree, - tools = zt._z.tools, - consts = zt.consts, - view = zt._z.view, - data = zt._z.data, - event = zt._z.event, - $$ = tools.$; - - data.exSetting(_setting); - data.addInitBind(_bindEvent); - data.addInitUnBind(_unbindEvent); - data.addInitCache(_initCache); - data.addInitNode(_initNode); - data.addInitProxy(_eventProxy, true); - data.addInitRoot(_initRoot); - data.addBeforeA(_beforeA); - data.addZTreeTools(_zTreeTools); - - var _createNodes = view.createNodes; - view.createNodes = function(setting, level, nodes, parentNode) { - if (_createNodes) _createNodes.apply(view, arguments); - if (!nodes) return; - view.repairParentChkClassWithSelf(setting, parentNode); - } - var _removeNode = view.removeNode; - view.removeNode = function(setting, node) { - var parentNode = node.getParentNode(); - if (_removeNode) _removeNode.apply(view, arguments); - if (!node || !parentNode) return; - view.repairChkClass(setting, parentNode); - view.repairParentChkClass(setting, parentNode); - } - - var _appendNodes = view.appendNodes; - view.appendNodes = function(setting, level, nodes, parentNode, initFlag, openFlag) { - var html = ""; - if (_appendNodes) { - html = _appendNodes.apply(view, arguments); - } - if (parentNode) { - data.makeChkFlag(setting, parentNode); - } - return html; - } + pSign = false; + break; + } + } + } + if (pSign) { + view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); + } + } + }, + setSonNodeCheckBox: function (setting, node, value, srcNode) { + if (!node) return; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + checkObj = $$(node, consts.id.CHECK, setting); + if (!srcNode) srcNode = node; + + var hasDisable = false; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { + var sNode = node[childKey][i]; + view.setSonNodeCheckBox(setting, sNode, value, srcNode); + if (sNode.chkDisabled === true) hasDisable = true; + } + } + + if (node != data.getRoot(setting) && node.chkDisabled !== true) { + if (hasDisable && node.nocheck !== true) { + data.makeChkFlag(setting, node); + } + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = value; + if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; + } else { + node.check_Child_State = -1; + } + view.setChkClass(setting, checkObj, node); + if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { + setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + } + } + + } + }, + + _z = { + tools: _tools, + view: _view, + event: _event, + data: _data + }; + $.extend(true, $.fn.zTree.consts, _consts); + $.extend(true, $.fn.zTree._z, _z); + + var zt = $.fn.zTree, + tools = zt._z.tools, + consts = zt.consts, + view = zt._z.view, + data = zt._z.data, + event = zt._z.event, + $$ = tools.$; + + data.exSetting(_setting); + data.addInitBind(_bindEvent); + data.addInitUnBind(_unbindEvent); + data.addInitCache(_initCache); + data.addInitNode(_initNode); + data.addInitProxy(_eventProxy, true); + data.addInitRoot(_initRoot); + data.addBeforeA(_beforeA); + data.addZTreeTools(_zTreeTools); + + var _createNodes = view.createNodes; + view.createNodes = function (setting, level, nodes, parentNode) { + if (_createNodes) _createNodes.apply(view, arguments); + if (!nodes) return; + view.repairParentChkClassWithSelf(setting, parentNode); + }; + var _removeNode = view.removeNode; + view.removeNode = function (setting, node) { + var parentNode = node.getParentNode(); + if (_removeNode) _removeNode.apply(view, arguments); + if (!node || !parentNode) return; + view.repairChkClass(setting, parentNode); + view.repairParentChkClass(setting, parentNode); + }; + + var _appendNodes = view.appendNodes; + view.appendNodes = function (setting, level, nodes, parentNode, initFlag, openFlag) { + var html = ""; + if (_appendNodes) { + html = _appendNodes.apply(view, arguments); + } + if (parentNode) { + data.makeChkFlag(setting, parentNode); + } + return html; + }; })(jQuery); \ No newline at end of file diff --git a/dist/bundle.js b/dist/bundle.js index cb0a37a5c..6c4b87abb 100644 --- a/dist/bundle.js +++ b/dist/bundle.js @@ -25715,10 +25715,10 @@ Data.Constant = BICst = {}; * 缓冲池 * @type {{Buffer: {}}} */ -; + (function () { var Buffer = {}; - var MODE = false;//设置缓存模式为关闭 + var MODE = false;// 设置缓存模式为关闭 Data.BufferPool = { put: function (name, cache) { @@ -25736,7 +25736,7 @@ Data.Constant = BICst = {}; * 共享池 * @type {{Shared: {}}} */ -; + (function () { var _Shared = {}; Data.SharingPool = { @@ -25767,7 +25767,7 @@ Data.Constant = BICst = {}; }; Data.Source = BISource = { -};/*! +};/* ! * jQuery Mousewheel 3.1.13 * * Copyright jQuery Foundation and other contributors @@ -25776,10 +25776,10 @@ Data.Source = BISource = { */ (function (factory) { - if ( typeof define === 'function' && define.amd ) { + if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. - define(['../core/jquery'], factory); - } else if (typeof exports === 'object') { + define(["../core/jquery"], factory); + } else if (typeof exports === "object") { // Node/CommonJS style for Browserify module.exports = factory; } else { @@ -25788,9 +25788,9 @@ Data.Source = BISource = { } }(function ($) { - var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], - toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? - ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], + var toFix = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], + toBind = ( "onwheel" in document || document.documentMode >= 9 ) ? + ["wheel"] : ["mousewheel", "DomMouseScroll", "MozMousePixelScroll"], slice = Array.prototype.slice, nullLowestDeltaTimeout, lowestDelta; @@ -25801,9 +25801,9 @@ Data.Source = BISource = { } var special = $.event.special.mousewheel = { - version: '3.1.12', + version: "3.1.12", - setup: function() { + setup: function () { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); @@ -25813,7 +25813,7 @@ Data.Source = BISource = { } }, - teardown: function() { + teardown: function () { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); @@ -25830,17 +25830,17 @@ Data.Source = BISource = { }; $.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); + mousewheel: function (fn) { + return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, - unmousewheel: function(fn) { - return this.unbind('mousewheel', fn); + unmousewheel: function (fn) { + return this.unbind("mousewheel", fn); } }); - function handler(event) { + function handler (event) { var orgEvent = event || window.event, args = slice.call(arguments, 1), delta = 0, @@ -25850,16 +25850,16 @@ Data.Source = BISource = { offsetX = 0, offsetY = 0; event = $.event.fix(orgEvent); - event.type = 'mousewheel'; + event.type = "mousewheel"; // Old school scrollwheel delta - if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } - if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } - if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } - if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } + if ( "detail" in orgEvent ) { deltaY = orgEvent.detail * -1; } + if ( "wheelDelta" in orgEvent ) { deltaY = orgEvent.wheelDelta; } + if ( "wheelDeltaY" in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } + if ( "wheelDeltaX" in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event - if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { + if ( "axis" in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaX = deltaY * -1; deltaY = 0; } @@ -25868,11 +25868,11 @@ Data.Source = BISource = { delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) - if ( 'deltaY' in orgEvent ) { + if ( "deltaY" in orgEvent ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } - if ( 'deltaX' in orgEvent ) { + if ( "deltaX" in orgEvent ) { deltaX = orgEvent.deltaX; if ( deltaY === 0 ) { delta = deltaX * -1; } } @@ -25918,9 +25918,9 @@ Data.Source = BISource = { } // Get a whole, normalized value for the deltas - delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); - deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); - deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); + delta = Math[ delta >= 1 ? "floor" : "ceil" ](delta / lowestDelta); + deltaX = Math[ deltaX >= 1 ? "floor" : "ceil" ](deltaX / lowestDelta); + deltaY = Math[ deltaY >= 1 ? "floor" : "ceil" ](deltaY / lowestDelta); // Normalise offsetX and offsetY properties if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { @@ -25953,11 +25953,11 @@ Data.Source = BISource = { return ($.event.dispatch || $.event.handle).apply(this, args); } - function nullLowestDelta() { + function nullLowestDelta () { lowestDelta = null; } - function shouldAdjustOldDeltas(orgEvent, absDelta) { + function shouldAdjustOldDeltas (orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas @@ -25965,15 +25965,15 @@ Data.Source = BISource = { // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. - return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; + return special.settings.adjustOldDeltas && orgEvent.type === "mousewheel" && absDelta % 120 === 0; } }));/** * Created by User on 2017/3/21. */ -BI.FormulaCollections = ["abs","ABS","acos","ACOS","acosh","ACOSH","add2array","ADD2ARRAY","and","AND","array","ARRAY","asin","ASIN","asinh","ASINH","atan","ATAN","atan2","ATAN2","atanh","ATANH","average","AVERAGE","bitnot","BITNOT","bitoperation","BITOPERATION","ceiling","CEILING","char","CHAR","circular","CIRCULAR","class","CLASS","cnmoney","CNMONEY","code","CODE","col","COL","colcount","COLCOUNT","colname","COLNAME","combin","COMBIN","concatenate","CONCATENATE","correl","CORREL","cos","COS","cosh","COSH","count","COUNT","crosslayertotal","CROSSLAYERTOTAL","date","DATE","datedelta","DATEDELTA","datedif","DATEDIF","dateinmonth","DATEINMONTH","dateinquarter","DATEINQUARTER","dateinweek","DATEINWEEK","dateinyear","DATEINYEAR","datesubdate","DATESUBDATE","datetime","DATETIME","datetonumber","DATETONUMBER","day","DAY","days360","DAYS360","daysofmonth","DAYSOFMONTH","daysofquarter","DAYSOFQUARTER","daysofyear","DAYSOFYEAR","dayvalue","DAYVALUE","decimal","DECIMAL","decode","DECODE","degrees","DEGREES","encode","ENCODE","endwith","ENDWITH","enmoney","ENMONEY","ennumber","ENNUMBER","eval","EVAL","even","EVEN","exact","EXACT","exp","EXP","fact","FACT","fields","FIELDS","filename","FILENAME","filesize","FILESIZE","filetype","FILETYPE","find","FIND","floor","FLOOR","format","FORMAT","getuserdepartments","GETUSERDEPARTMENTS","getuserjobtitles","GETUSERJOBTITLES","greparray","GREPARRAY","hierarchy","HIERARCHY","hour","HOUR","i18n","I18N","if","IF","inarray","INARRAY","index","INDEX","indexof","INDEXOF","indexofarray","INDEXOFARRAY","int","INT","isnull","ISNULL","joinarray","JOINARRAY","jvm","JVM","layertotal","LAYERTOTAL","left","LEFT","len","LEN","let","LET","ln","LN","log","LOG","log10","LOG10","lower","LOWER","lunar","LUNAR","map","MAP","maparray","MAPARRAY","max","MAX","median","MEDIAN","mid","MID","min","MIN","minute","MINUTE","mod","MOD","mom","MOM","month","MONTH","monthdelta","MONTHDELTA","now","NOW","numto","NUMTO","nvl","NVL","odd","ODD","or","OR","pi","PI","power","POWER","product","PRODUCT","promotion","PROMOTION","proper","PROPER","proportion","PROPORTION","radians","RADIANS","rand","RAND","randbetween","RANDBETWEEN","range","RANGE","rank","RANK","records","RECORDS","regexp","REGEXP","removearray","REMOVEARRAY","repeat","REPEAT","replace","REPLACE","reverse","REVERSE","reversearray","REVERSEARRAY","right","RIGHT","round","ROUND","round5","ROUND5","rounddown","ROUNDDOWN","roundup","ROUNDUP","row","ROW","rowcount","ROWCOUNT","second","SECOND","seq","SEQ","sign","SIGN","sin","SIN","sinh","SINH","slicearray","SLICEARRAY","sort","SORT","sortarray","SORTARRAY","split","SPLIT","sql","SQL","sqrt","SQRT","startwith","STARTWITH","stdev","STDEV","substitute","SUBSTITUTE","sum","SUM","sumsq","SUMSQ","switch","SWITCH","tabledatafields","TABLEDATAFIELDS","tabledatas","TABLEDATAS","tables","TABLES","tan","TAN","tanh","TANH","time","TIME","tobigdecimal","TOBIGDECIMAL","tobinary","TOBINARY","todate","TODATE","today","TODAY","todouble","TODOUBLE","tohex","TOHEX","toimage","TOIMAGE","tointeger","TOINTEGER","tooctal","TOOCTAL","totext","TOTEXT","treelayer","TREELAYER","trim","TRIM","trunc","TRUNC","uniquearray","UNIQUEARRAY","upper","UPPER","uuid","UUID","value","VALUE","webimage","WEBIMAGE","week","WEEK","weekdate","WEEKDATE","weekday","WEEKDAY","weightedaverage","WEIGHTEDAVERAGE","year","YEAR","yeardelta","YEARDELTA"]; +BI.FormulaCollections = ["abs", "ABS", "acos", "ACOS", "acosh", "ACOSH", "add2array", "ADD2ARRAY", "and", "AND", "array", "ARRAY", "asin", "ASIN", "asinh", "ASINH", "atan", "ATAN", "atan2", "ATAN2", "atanh", "ATANH", "average", "AVERAGE", "bitnot", "BITNOT", "bitoperation", "BITOPERATION", "ceiling", "CEILING", "char", "CHAR", "circular", "CIRCULAR", "class", "CLASS", "cnmoney", "CNMONEY", "code", "CODE", "col", "COL", "colcount", "COLCOUNT", "colname", "COLNAME", "combin", "COMBIN", "concatenate", "CONCATENATE", "correl", "CORREL", "cos", "COS", "cosh", "COSH", "count", "COUNT", "crosslayertotal", "CROSSLAYERTOTAL", "date", "DATE", "datedelta", "DATEDELTA", "datedif", "DATEDIF", "dateinmonth", "DATEINMONTH", "dateinquarter", "DATEINQUARTER", "dateinweek", "DATEINWEEK", "dateinyear", "DATEINYEAR", "datesubdate", "DATESUBDATE", "datetime", "DATETIME", "datetonumber", "DATETONUMBER", "day", "DAY", "days360", "DAYS360", "daysofmonth", "DAYSOFMONTH", "daysofquarter", "DAYSOFQUARTER", "daysofyear", "DAYSOFYEAR", "dayvalue", "DAYVALUE", "decimal", "DECIMAL", "decode", "DECODE", "degrees", "DEGREES", "encode", "ENCODE", "endwith", "ENDWITH", "enmoney", "ENMONEY", "ennumber", "ENNUMBER", "eval", "EVAL", "even", "EVEN", "exact", "EXACT", "exp", "EXP", "fact", "FACT", "fields", "FIELDS", "filename", "FILENAME", "filesize", "FILESIZE", "filetype", "FILETYPE", "find", "FIND", "floor", "FLOOR", "format", "FORMAT", "getuserdepartments", "GETUSERDEPARTMENTS", "getuserjobtitles", "GETUSERJOBTITLES", "greparray", "GREPARRAY", "hierarchy", "HIERARCHY", "hour", "HOUR", "i18n", "I18N", "if", "IF", "inarray", "INARRAY", "index", "INDEX", "indexof", "INDEXOF", "indexofarray", "INDEXOFARRAY", "int", "INT", "isnull", "ISNULL", "joinarray", "JOINARRAY", "jvm", "JVM", "layertotal", "LAYERTOTAL", "left", "LEFT", "len", "LEN", "let", "LET", "ln", "LN", "log", "LOG", "log10", "LOG10", "lower", "LOWER", "lunar", "LUNAR", "map", "MAP", "maparray", "MAPARRAY", "max", "MAX", "median", "MEDIAN", "mid", "MID", "min", "MIN", "minute", "MINUTE", "mod", "MOD", "mom", "MOM", "month", "MONTH", "monthdelta", "MONTHDELTA", "now", "NOW", "numto", "NUMTO", "nvl", "NVL", "odd", "ODD", "or", "OR", "pi", "PI", "power", "POWER", "product", "PRODUCT", "promotion", "PROMOTION", "proper", "PROPER", "proportion", "PROPORTION", "radians", "RADIANS", "rand", "RAND", "randbetween", "RANDBETWEEN", "range", "RANGE", "rank", "RANK", "records", "RECORDS", "regexp", "REGEXP", "removearray", "REMOVEARRAY", "repeat", "REPEAT", "replace", "REPLACE", "reverse", "REVERSE", "reversearray", "REVERSEARRAY", "right", "RIGHT", "round", "ROUND", "round5", "ROUND5", "rounddown", "ROUNDDOWN", "roundup", "ROUNDUP", "row", "ROW", "rowcount", "ROWCOUNT", "second", "SECOND", "seq", "SEQ", "sign", "SIGN", "sin", "SIN", "sinh", "SINH", "slicearray", "SLICEARRAY", "sort", "SORT", "sortarray", "SORTARRAY", "split", "SPLIT", "sql", "SQL", "sqrt", "SQRT", "startwith", "STARTWITH", "stdev", "STDEV", "substitute", "SUBSTITUTE", "sum", "SUM", "sumsq", "SUMSQ", "switch", "SWITCH", "tabledatafields", "TABLEDATAFIELDS", "tabledatas", "TABLEDATAS", "tables", "TABLES", "tan", "TAN", "tanh", "TANH", "time", "TIME", "tobigdecimal", "TOBIGDECIMAL", "tobinary", "TOBINARY", "todate", "TODATE", "today", "TODAY", "todouble", "TODOUBLE", "tohex", "TOHEX", "toimage", "TOIMAGE", "tointeger", "TOINTEGER", "tooctal", "TOOCTAL", "totext", "TOTEXT", "treelayer", "TREELAYER", "trim", "TRIM", "trunc", "TRUNC", "uniquearray", "UNIQUEARRAY", "upper", "UPPER", "uuid", "UUID", "value", "VALUE", "webimage", "WEBIMAGE", "week", "WEEK", "weekdate", "WEEKDATE", "weekday", "WEEKDAY", "weightedaverage", "WEIGHTEDAVERAGE", "year", "YEAR", "yeardelta", "YEARDELTA"]; -BI.FormulaJson = [{"def":"MONTH:(serial_number)返回日期中的月。月是介于1和12之间的一个数。\nSerial_number:含有所求的月的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nMONTH(\"2000/1/1\")等于1。\nMONTH(\"2006/05/05\")等于5。\nMONTH(\"1997/04/20\")等于4。\nMONTH(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nMONTH(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nMONTH(\"1997-04-20\", \"yyyy-MM-dd\")等于4。\nMONTH(35796)等于1。","name":"MONTH","type":"DATETIME"},{"def":"ROWCOUNT(tableData)返回tableData的行数。\ntableData:TableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是tableData的行数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nROWCOUNT(\"ds1\")等于20。","name":"ROWCOUNT","type":"REPORT"},{"def":"RAND(): 返回均匀分布的随机数。每计算一次工作表,函数都会返回一个新的随机数值。\n备注:\n 要生成一个位于a和b之间的随机数,可以使用以下的公式: C=RAND()*(b-a)+a。\n 如果要使一个随机产生的数值不随单元格的重计算而改变,可以在编辑框中输入=RAND()并保持编辑状态,然后按F9,将公式永久性地改为随机数。\n示例:\n假如需要生成一个大于等于0,小于60的随机数,使用公式: =RAND()*60。\n假如需要生成一个大于等于0,小于19的随机数,使用公式: =RAND()*19。\n假如需要生成一个大于等于0,小于50的随机数,使用公式: =RAND()*50。","name":"RAND","type":"MATH"},{"def":"GETUSERDEPARTMENTS():返回角色部门\n示例:\nGETUSERDEPARTMENTS():返回角色所有部门,若多个部门则数组\nGETUSERDEPARTMENTS(3,2):返回角色该部门的第三层和第二层名字,\n若多个部门则返回数组,若没有第三层则只显示第二层","name":"GETUSERDEPARTMENTS","type":"OTHER"},{"def":"FORMAT(object,format) : 返回object的format格式。\nobject 需要被格式化对象,可以是String,数字,Object(常用的有Date, Time)。\nformat 格式化的样式。\n示例\nFORMAT(1234.5, \"#,##0.00\") => 1234.50\nFORMAT(1234.5, \"#,##0\") => 1234\nFORMAT(1234.5, \"¥#,##0.00\") => ¥1234.50\nFORMAT(1.5, \"0%\") => 150%\nFORMAT(1.5, \"0.000%\") => 150.000%\nFORMAT(6789, \"##0.0E0\") => 6.789E3\nFORMAT(6789, \"0.00E00\") => 6.79E03\nFORMAT(date(2007,1,1), \"EEEEE, MMMMM dd, yyyy\") => 星期一,一月 01,2007\nFORMAT(date(2007,1,13), \"MM/dd/yyyy\") => 01/13/2007\nFORMAT(date(2007,1,13), \"M-d-yy\") => 1-13-07\nFORMAT(time(16,23,56), \"h:mm:ss a\") => 4:23:56 下午","name":"FORMAT","type":"TEXT"},{"def":"TRIM(text): 清除文本中所有空格,单词间的单个空格除外,也可用于带有不规则空格的文本。\nText:需要清除空格的文本。\n示例:\nTRIM(\" Monthly Report\")等于Monthly Report。","name":"TRIM","type":"TEXT"},{"def":"SQRT(number): 返回一个正数的平方根。\nNumber:要求其平方根的任一正数。\n备注:\nNumber必须是一个正数,否则函数返回错误信息*NUM!。\n示例:\nSQRT(64)等于8。\nSQRT(-64)返回*NUM!。","name":"SQRT","type":"MATH"},{"def":"DAYSOFYEAR(year):返回某年包含的天数。\n示例:\nDAYSOFYEAR(2008)等于365,等价于DAYSOFYEAR(\"2008-01-01\")。","name":"DAYSOFYEAR","type":"DATETIME"},{"def":"RANK(number,ref,order): 返回一个数在一个数组中的秩。(如果把这个数组排序,该数的秩即为它在数组中的序号。)\nNumber 所求秩的数。(可以是Boolean型,true=1,false=0)\nRef 可以是数组,引用,或一系列数,非实数的值被忽略处理(接受Boolean型,true=1,false=0)。\nOrder 指定求秩的参数,非零为升序,零为降序\n\n备注\n1. RANK对重复的数返回相同的秩,但重复的数影响后面的数的秩,比如,在一组升序排列的整数中,如果5出现了2次,并且秩为3,那么6的秩为5 (没有数的秩是4).\n\n示例\nA1:A5 = 6, 4.5, 4.5, 2, 4\nRANK(A1,A1:A5,1) 即 6 的秩为 5.\n\nRANK(3,1,2,\"go\",3,4,1) = 3, \"go\"被忽略。","name":"RANK","type":"OTHER"},{"def":"ODD(number):返回对指定数值进行舍入后的奇数。\nnumber:是要舍入求奇的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是奇数,则不须进行任何舍入处理。\n示例:\nODD(1.5) 等于 3\nODD(3) 等于 3\nODD(2) 等于 3\nODD(-1) 等于 -1","name":"ODD","type":"MATH"},{"def":"COLCOUNT(tableData):返回tableData中列的个数。\ntableData:tableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是第一个查找到的tableData中列数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nCOLCOUNT(\"ds1\")等于6。\n","name":"COLCOUNT","type":"REPORT"},{"def":"ENDWITH(str1,str2):判断字符串str1是否以str2结束。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nENDWITH(\"FineReport\",\"Report\")等于true。\nENDWITH(\"FineReport\",\"Fine\")等于false。\nENDWITH(\"FineReport\",\"report\")等于false。","name":"ENDWITH","type":"TEXT"},{"def":"LOG10(number):返回以 10 为底的对数。\nnumber: 用于常用对数计算的正实数。\n示例:\nLOG10(86) 等于 1.934498451\nLOG10(10) 等于 1\nLOG10(1E5) 等于 5\n","name":"LOG10","type":"MATH"},{"def":"MAPARRAY(array, fn):把一个数组中的项目转换到另一个数组中。\narray (Array): 要转换的数组 \nfn (Function): 处理数组项目的函数 \n示例:\nMAPARRAY([3,4,2,3,6,8,7], item != 3)等于[false,true,true,false,true,true,true].","name":"MAPARRAY","type":"ARRAY"},{"def":"FLOOR(number): 将参数number沿绝对值减小的方向去尾舍入。\nNumber:待舍入的数值。\n示例:\nFLOOR(-2.5)等于-2。\nFLOOR(2.5)等于2。\n","name":"FLOOR","type":"MATH"},{"def":"NUMTO(number,bool)或NUMTO(number):返回number的中文表示。其中bool用于选择中文表示的方式,当没有bool时采用默认方式显示。\n示例:NUMTO(2345,true)等于二三四五。\n示例:NUMTO(2345,false)等于二千三百四十五。\n示例:NUMTO(2345)等于二千三百四十五。","name":"NUMTO","type":"TEXT"},{"def":"ATANH(number): 返回数字的反双曲正切值,该函数的参数值即为反双曲正切值的双曲正切值。\nNumber:指介于-1~1之间的任意实数。\n备注:\n 指定的number必须介于-1~1之间(不包括-1,1)。\n ATANH(TANH(number))=number,例如,ATANH(TANH(8))=8。\n示例:\nATANH(-0.5)等于-0.549306144。\nATANH(0)等于0。\nATANH(0.7)等于0.867300528。","name":"ATANH","type":"MATH"},{"def":"YEAR:(serial_number)返回日期中的年。Year是介于1900和9999之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nYEAR(\"2000/1/1\")等于2000。\nYEAR(\"2006/05/05\")等于2006。\nYEAR(\"1997/04/20\")等于1997。\nYEAR(\"2000-1-1\", \"yyyy-MM-dd\")等于2000。\nYEAR(\"2006-05-05\", \"yyyy-MM-dd\")等于2006。\nYEAR(\"1997-04-20\", \"yyyy-MM-dd\")等于1997。\nYEAR(35796)等于1998。","name":"YEAR","type":"DATETIME"},{"def":"SLICEARRAY(array, start, end):返回数组从第start个到第end个元素(包括第end个元素)。\n示例:\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3, 6)返回[4, 5, 1, 5].\n当不使用end参数时,返回从start开始到数组结束之间的元素。\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3)返回[4, 5, 1, 5, 7].","name":"SLICEARRAY","type":"ARRAY"},{"def":"","name":"DECODE","type":"OTHER"},{"def":"ENMONEY(value):将给定的BigDemical类型的数字转换成英文金额字符串。\n示例:\nENMONEY(23.49)等于TWENTY THREE AND CENTS FORTY NINE","name":"ENMONEY","type":"TEXT"},{"def":"IF(boolean,number1/string1,number2/string2):判断函数,boolean为true时返回第二个参数,为false时返回第三个。\nboolean: 用于判断的布尔值,true或者false。\nnumber1/string1: 第一个参数,如果boolean为ture,返回这个值。\nnumber2/string2: 第二个参数,如果boolean为false,返回这个值。\n示例:\nIF(true,2,8)等于2\nIF(false,\"first\",\"second\")等于second\nIF(true,\"first\",7)等于first","name":"IF","type":"LOGIC"},{"def":"DATEINWEEK(date, number):函数返回在某一个星期当中第几天的日期。\n示例:\ndateInWeek(\"2008-08-28\", 2)等于2008-08-26。\ndateInWeek(\"2008-08-28\", -1)等于2008-08-31。\n如果最后一个参数为-1,返回该日期所在星期的最后一天\n","name":"DATEINWEEK","type":"DATETIME"},{"def":"MONTHDELTA(date,delta):返回指定日期date后delta个月的日期。\n示例:\nMONTHDELTA(\"2008-08-08\", 4)等于2008-12-08。","name":"MONTHDELTA","type":"DATETIME"},{"def":"FIELDS(connectionName,tableName):返回tableName这个表中的所有字段名。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么FIELDS(\"BASE\",\"task\")等于[name,start,end].","name":"FIELDS","type":"REPORT"},{"def":"DATEDIF(start_date,end_date,unit):返回两个指定日期间的天数、月数或年数。\nStart_date:代表所指定时间段的初始日期。\nEnd_date:代表所指定时间段的终止日期。\nUnit:函数返回信息的类型。\n若unit=“Y”,则DATEDIF返回指定时间段的年差数。\n若unit=“M”,则DATEDIF返回指定时间段的月差数。\n若unit=“D”,则DATEDIF返回指定时间段的日差数。\n若unit=“MD”,则DATEDIF忽略年和月,返回指定时间段的日差数。\n若unit=“YM”,则DATEDIF忽略年和日,返回指定时间段的月差数。\n若unit=“YD”,则DATEDIF忽略年,返回指定时间段的日差数。\n示例:\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"Y\")等于3,即在2001年2月28日与2004年3月20日之间有3个整年。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"M\")等于37,即在2001年2月28日与2004年3月20日之间有36个整月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"D\")等于1116,即在2001年2月28日与2004年3月20日之间有1116个整天。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"MD\")等于8,即忽略月和年后,2001年2月28日与2004年3月20日的差为8天。\nDATEDIF(\"2001/1/28\",\"2004/3/20\",\"YM\")等于2,即忽略日和年后,2001年1月28日与2004年3月20日的差为2个月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"YD\")等于21,即忽略年后,2001年2月28日与2004年3月20日的差为21天。","name":"DATEDIF","type":"DATETIME"},{"def":"TOIMAGE(path):显示指定路径下的图片。此处默认开启了图片缓存功能以加速报表的生成.\n如不需要缓存,请在参数后面追加值FALSE,例如:TOIMAGE(\"D:/fr.png\",false).\n如需要指定图片大小,拉伸显示, 则需要添加参数,TOIMAGE(patch, true, width, height).\n示例:=toimage(\"d:/1.jpg\", true, \"50%\", 300), 第三个参数为指定宽度, 第四个参数为指定高度.\n如果参数为整数, 则直接写数字, 如果为百分比, 则需要加上引号, 如\"300%\"","name":"TOIMAGE","type":"OTHER"},{"def":"LEFT(text,num_chars): 根据指定的字符数返回文本串中的第一个或前几个字符。\nText:包含需要选取字符的文本串或单元格引用。\nNum_chars:指定返回的字符串长度。\n备注:\n Num_chars的值必须等于或大于0。\n 如果num_chars大于整个文本的长度,LEFT函数将返回所有的文本。\n 如果省略num_chars,则默认值为1。\n示例:\nLEFT(\"Fine software\",8)等于“Fine sof”。\nLEFT(\"Fine software\")等于“F”。\n如果单元格A3中含有“China”,则LEFT(A3,2)等于“Ch”。","name":"LEFT","type":"TEXT"},{"def":"SUBSTITUTE(text,old_text,new_text,instance_num): 用new_text替换文本串中的old_text。\nText:需要被替换字符的文本,或含有文本的单元格引用。\nOld_text:需要被替换的部分文本。\nNew_text:用于替换old_text的文本。\nInstance_num:指定用new_text来替换第几次出现的old_text。如果指定了instance_num,则只有指定位置上的old_text被替换,否则文字串中出现的所有old_text都被new_text替换。\n备注:\n 如果需要替换文本串中的指定文本,则使用SUBSTITUTE函数;如果需要替换文本串中指定位置上的任意文本,则使用REPLACE函数。\n示例:\nSUBSTITUTE(\"data base\",\"base\",\"model\")等于“data model”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",1)等于“July 18, 2000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\")等于“July 18, 1000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",2)等于“July 28, 1000”。 ","name":"SUBSTITUTE","type":"TEXT"},{"def":"LOG(number,base): 按指定的任意底数,返回数值的对数。\nNumber:需要求对数的正实数。\nBase:对数的底数。如果省略底数,默认值为10。\n示例:\nLOG(16,2)等于4。\nLOG(10)等于1。\nLOG(24,3)等于2.892789261。","name":"LOG","type":"MATH"},{"def":"SORTARRAY(array):返回数组array排过序的数组。\n示例:\nSORTARRAY([3, 4, 4, 5, 1, 5, 7])返回[1, 3, 4, 4, 5, 5, 7].\n注意:数组array的元素类型必须一样,并且要可比较。","name":"SORTARRAY","type":"ARRAY"},{"def":"DATEDELTA(date, deltadays):返回一个日期??date后deltadays的日期。\ndeltaDays可以为正值,负值,零。\n示例:\nDATEDELTA(\"2008-08-08\", -10)等于2008-07-29。\nDATEDELTA(\"2008-08-08\", 10)等于2008-08-18。","name":"DATEDELTA","type":"DATETIME"},{"def":"MID(text,start_num,num_chars): 返回文本串中从指定位置开始的一定数目的字符,该数目由用户指定。\nText:包含要提取字符的文本串。\nStart_num:文本中需要提取字符的起始位置。文本中第一个字符的start_num为1,依此类推。\nNum_chars:返回字符的长度。\n备注:\n 如果start_num大于文本长度,MID函数返回“”(空文本)。\n 如果start_num小于文本长度,并且start_num加上num_chars大于文本长度,MID函数将从start_num指定的起始字符直至文本末的所有字符。\n 如果start_num小于1,MID函数返回错误信息*VALUE!。\n 如果num_chars是负数,MID函数返回错误信息*VALUE!。\n示例:\nMID(\"Finemore software\",10,8)返回“software”。\nMID(\"Finemore software\",30,5)返回“”(空文本)。\nMID(\"Finemore software\",0,8)返回*VALUE!。\nMID(\"Finemore software\",5,-1)返回*VALUE!。","name":"MID","type":"TEXT"},{"def":"ATAN2(x_num,y_num): 返回x、y坐标的反正切值。返回角度为x轴与过(x_num,y_num)与坐标原点(0,0)的一条直线形成的角度。该角度以弧度显示。\nX_num:指定点的x坐标。\nY_num:指定点的y坐标。\n备注:\n 正值表示从x轴开始以逆时针方式所得的角度;负值表示从x轴开始以顺时针方式所得的角度。\na > 0,b > 0 or a > 0, b < 0时,公式直接成立;\na < 0,b > 0, ATAN2(a,b)=PI()-ABS(ATAN(b/a))\na < 0,b < 0, ATAN2(a,b)=ABS(ATAN(b/a))-PI()\n 当x_num与y_num都为0时,ATAN2返回错误信息*DIV/0!。\n 用角度制显示返回数值时,把返回数值乘以180/PI()。\n 返回值以弧度表示(返回值大于-pi且小于等于pi)。\n示例:\nATAN2(-2,2)等于2.356194490192345(弧度制的3*pi/4)。\nATAN2(2,2)等于0.785398163(弧度制的pi/4)。\nATAN2(-2,2)*180/PI()等于135(角度制)。","name":"ATAN2","type":"MATH"},{"def":"SUM(number1,number2,…): 求一个指定单元格区域中所有数字之和。\nNumber1,number2,…:1到30个参数或指定单元格区域中所有数字。\n备注:\n 函数将直接键入参数中的数值、逻辑值及文本表达式计算在内。\n 若参数是数组或引用,则只有数组或单元格引用中的数值进行计算。\n示例:\nSUM(70,80)等于150。\nSUM(\"70\",80,TRUE)等于151,逻辑值“TRUE”作为1来计算;“FALSE”作为0计算;文本“70”作为70来计算。","name":"SUM","type":"MATH"},{"def":"EXACT(text1,text2): 检测两组文本是否相同。如果完全相同,EXACT函数返回TRUE;否则,返回FALSE。EXACT函数可以区分大小写,但忽略格式的不同。同时也可以利用EXACT函数来检测输入文档的文字。\nText1:需要比较的第一组文本。\nText2:需要比较的第二组文本。\n示例:\nEXACT(\"Spreadsheet\",\"Spreadsheet\")等于TRUE。\nEXACT(\"Spreadsheet\",\"S preadsheet\")等于FALSE。\nEXACT(\"Spreadsheet\",\"spreadsheet\")等于FALSE。","name":"EXACT","type":"TEXT"},{"def":"TOINTEGER(text): 将文本转换成Integer对象。\nText:需要转换的文本。\n示例:\nTOINTEGER(\"123\")等于 new Integer(123)。","name":"TOINTEGER","type":"TEXT"},{"def":"ACOSH(number): 返回给定数值的反双曲余弦。\nNumber:返回值的双曲余弦。\n备注:\n 参数number的值必须大于或等于1。\n ACOSH(COSH(number))=number。\n示例:\nACOSH(1)等于0。\nACOSH(8)等于2.768659383。\nACOSH(5.5)等于2.389526435。","name":"ACOSH","type":"MATH"},{"def":"weekdate(year,month,weekOfMonth,dayOfWeek): 返回指定年月的指定周的周几的具体日期。\n示例:\nweekdate(2009,10,2,1)\n返回的是2009年的10月的第二个周的第一天即星期天的日期,返回的是2009-10-04\n最后一个参数dayOfWeek为-1时,表示这个周的最后一天\n示例:\nweekdate(2009,12,1,-1)\n返回的是2009年的12月的第一个周的最后一天即星期六的日期,返回的是2009-12-05\n","name":"WEEKDATE","type":"DATETIME"},{"def":"MIN(number1,number2,…): 返回参数列表中的最小值。\nNumber1,number2,…:1到30个需要找出最小值的参数。\n备注:\n 若参数中没有数字,函数MIN将返回0。\n 参数应为数字、空白单元格、逻辑值或是表示数值的文本串。如果参数是错误值时,MIN将返回错误信息。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n示例:\n如果B1:B4包含3,6,9,12,则:\nMIN(B1:B4)等于3。\nMIN(B1:B4,0)等于0。","name":"MIN","type":"MATH"},{"def":"STARTWITH(str1,str2):判断字符串str1是否以str2开始。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nSTARTWITH(\"FineReport\",\"Fine\")等于true。\nSTARTWITH(\"FineReport\",\"Report\")等于false。\nSTARTWITH(\"FineReport\",\"fine\")等于false。","name":"STARTWITH","type":"TEXT"},{"def":"COMBIN(number,number_chosen): 返回若干个指定对象的组合数。该函数与数学表达式为Cnk功能相同。\nNumber或数学表达式中的“n”指对象总数。\nNumber_chosen或数学表达式中的“k”指在对象总数中某一组合的数量。\n备注:\n Number必须是正整数,number_chosen必须是非负整数。\n 如果number和number_chosen小于0或number小于number_chosen,函数返回错误信息*NUM!。\n 对象组合是对象的子集。与排列不同的是,组合不涉及对象内部的先后顺序,而顺序对排列是非常重要的。\n 假设number=n,number_chosen=k,则: COMBIN(n,k)=Cnk=n!/(k!(n-k)!)。\n示例:\nCOMBIN(5,6)等于*NUM!。\nCOMBIN(5,2)等于10。","name":"COMBIN","type":"MATH"},{"def":"EVEN(number):返回沿绝对值增大方向取整后最接近的偶数。使用该函数可以处理那些成对出现的对象。\nnumber:所要取整的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是偶数,则不须进行任何舍入处理。\n示例:\nEVEN(1.5) 等于 2\nEVEN(3) 等于 4\nEVEN(2) 等于 2\nEVEN(-1) 等于 -2","name":"EVEN","type":"MATH"},{"def":"COUNT(value1,value2,…): 计算数组或数据区域中所含项的个数。\nValue1,value2,…:可包含任何类型数据的参数。","name":"COUNT","type":"MATH"},{"def":"INDEXOFARRAY(array, index):返回数组array的第index个元素。\n示例:\nINDEXOFARRAY([\"第一个\", \"第二个\", \"第三个\"], 2)返回\"第二个\"。","name":"INDEXOFARRAY","type":"ARRAY"},{"def":"MAP(object, string, int, int):四个参数分别是索引值,数据集的名字,索引值所在列序号,返回值所在列序号。\n提醒:后两个参数也可以写列名代替。\n根据数据集的名字,找到对应的数据集,找到其中索引列的值为key所对应的返回值。\n数据集的查找方式是依次从报表数据集找到服务器数据集。\n索引列序号与返回值序列号的初始值为1示例:\nMAP(1001, \"employee\", 1, 2)返回employee数据集,第1列中值为1001那条记录中第2列的值。\nMAP(1001, \"employee\", \"name\", \"address\")返回employee数据集,name列中值为1001那条记录中address列的值。","name":"MAP","type":"REPORT"},{"def":"SEQ(): 返回数值,在整个报表执行过程中,返回该函数被第几次执行了。\n示例:\nSEQ()在第一次执行时,结果为1。\nSEQ()在第二次执行时,结果为2。","name":"SEQ","type":"OTHER"},{"def":"i18n为本软件内置的国际化公式,可以对一些常用的词语进行国际化.\n示例:i18n('File'), 则会在中文语言环境下显示为: 文件, 而在英文语言环境下显示为: File","name":"I18N","type":"REPORT"},{"def":"层次坐标简写, 等同于=A1[A1:-1], 若需=B1[A1:-1]则HIERARCHY(A1, B1).\n若为横向, 偏移量为-2, 则写成HIERARCHY(A1, B1, -2, false), 等同于=B1[;A1:-1].\n公式中最后一个参数表示横纵向, 默认不传递, 表示纵向扩展, 若横向扩展, 则需要加上最后一个参数FALSE来区分. ","name":"HIERARCHY","type":"HA"},{"def":"","name":"ENCODE","type":"OTHER"},{"def":"DATEINMONTH(date, number):函数返回在某一个月当中第几天的日期。\n示例:\nDATEINMONTH(\"2008-08-08\", 20) 等于2008-08-20。\nDATEINMONTH(\"2008-08-08\", -1) 等于2008-08-31。","name":"DATEINMONTH","type":"DATETIME"},{"def":"TOOCTAL(int): 将一个十进制整型数转换成八进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOOCTAL(10)等于 \"12\"。\nTOOCTAL(20)等于 \"24\"。","name":"TOOCTAL","type":"MATH"},{"def":"REPEAT(text,number_times): 根据指定的次数重复显示文本。REPEAT函数可用来显示同一字符串,并对单元格进行填充。\nText:需要重复显示的文本或包含文本的单元格引用。\nNumber_times:指定文本重复的次数,且为正数。如果number_times为0,REPEAT函数将返回“”(空文本)。如果number_times不是整数,将被取整。REPEAT函数的最终结果通常不大于32767个字符。\n备注:\n 该函数可被用于在工作表中创建简单的直方图。\n示例:\nREPEAT(\"$\",4)等于“$$$$”。\n如果单元格B10的内容为“你好”,REPEAT(B10,3)等于“你好你好你好”。","name":"REPEAT","type":"TEXT"},{"def":"GREPARRAY(array,fn):函数(返回true或者false)是条件,过滤此数组,最后形成一个新数组。\n示例:\nGREPARRAY([3,4,2,3,6,8,7], item != 3)等于[4,2,6,8,7].\n","name":"GREPARRAY","type":"ARRAY"},{"def":"MAX(number1,number2,…): 返回参数列表中的最大值。\nNumber1,number2,…:1到30个需要找出最大值的参数。\n备注:\n 参数可以是数字、空白单元格、逻辑值或数字的文本表达式。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n 如果参数中没有任何数字,MAX将返回0。\n示例:\nMAX(0.1,0,1.2)等于1.2。","name":"MAX","type":"MATH"},{"def":"CHAR(number): 根据指定数字返回对应的字符。CHAR函数可将计算机其他类型的数字代码转换为字符。\nNumber:用于指定字符的数字,介于1~65535之间(包括1和65535)。\n示例:\nCHAR(88)等于“X”。\nCHAR(45)等于“-”。","name":"CHAR","type":"TEXT"},{"def":"TRUNC(number,num_digits):将数字的小数部分截去,返回整数。\nnumber:需要截尾取整的数字。\nnum_digits:用于指定取整精度的数字。\n示例:\nTRUNC(8.9) 等于 8\nTRUNC(-8.9) 等于 -8\nTRUNC(PI()) 等于 3\n","name":"TRUNC","type":"MATH"},{"def":"FACT(number):返回数的阶乘,一个数的阶乘等于 1*2*3*...*该数。\nnumber:要计算其阶乘的非负数。如果输入的 number 不是整数,则截尾取整。\n示例:\nFACT(1) 等于 1\nFACT(1.9) 等于 FACT(1) 等于 1\nFACT(0) 等于 1\nFACT(5) 等于 1*2*3*4*5 等于 120\n","name":"FACT","type":"MATH"},{"def":"STDEV(array1): 计算数据系列的标准偏差(与Excel的同名函数作用相同)。\n\n示例:\nSTDEV([1,2,3])=1。\n","name":"STDEV","type":"OTHER"},{"def":"SPLIT(String1,String2):返回由String2分割String1组成的字符串数组。\nString1:以双引号表示的字符串。\nString2:以双引号表示的分隔符。例如逗号\",\"\n示例:\nSPLIT(\"hello,world,yes\",\",\") = [\"hello\",\"world\",\"yes\"]。\nSPLIT(\"this is very good\",\" \") = [\"this\",\"is\",\"very\",\"good\"]。\n备注:\n如果只有一个参数,则返回一个错误。\n如果有多个参数,则只有前两个起作用。","name":"SPLIT","type":"TEXT"},{"def":"INARRAY(co, array):返回co在数组array中的位置,如果co不在array中,则返回0.\n示例:\nString[] arr = {\"a\",\"b\",\"c\",\"d\"}\n那么INARRAY(\"b\", arr)等于2.","name":"INARRAY","type":"ARRAY"},{"def":"REVERSEARRAY(array):返回数组array的倒序数组。\n示例:\nREVERSEARRAY([\"第一个\", \"第二个\", \"第三个\"])返回[\"第三个\", \"第二个\", \"第一个\"].","name":"REVERSEARRAY","type":"ARRAY"},{"def":"RANDBETWEEN(value1,value2):返回value1和value2之间的一个随机整数。\n示例:\nRANDBETWEEN(12.333, 13.233)只会返回13。\nRANDBETWEEN(11.2, 13.3)有可能返回12或者13。","name":"RANDBETWEEN","type":"MATH"},{"def":"UPPER(text): 将文本中所有的字符转化为大写。\nText:需要转化为大写字符的文本,或是包含文本的单元格引用。\n示例:\nUPPER(\"notes\")等于“NOTES”。\n如果单元格E5的值为“Examples”,则UPPER(E5)等于“EXAMPLES”。","name":"UPPER","type":"TEXT"},{"def":"ABS(number): 返回指定数字的绝对值。绝对值是指没有正负符号的数值。\nNumber:需要求出绝对值的任意实数。\n示例:\nABS(-1.5)等于1.5。\nABS(0)等于0。\nABS(2.5)等于2.5。","name":"ABS","type":"MATH"},{"def":"RIGHT(text,num_chars): 根据指定的字符数从右开始返回文本串中的最后一个或几个字符。\nText:包含需要提取字符的文本串或单元格引用。\nNum_chars:指定RIGHT函数从文本串中提取的字符数。Num_chars不能小于0。如果num_chars大于文本串长度,RIGHT函数将返回整个文本。如果不指定num_chars,则默认值为1。\n示例:\nRIGHT(\"It is interesting\",6)等于“esting”。\nRIGHT(\"Share Holder\")等于“r”。\nRIGHT(\"Huge sale\",4)等于“sale”。","name":"RIGHT","type":"TEXT"},{"def":"MEDIAN(array1): 返回数据系列的中值(与Excel的同名函数作用相同)。\n\n示例:\nMEDIAN([1,2,3])=2。\n","name":"MEDIAN","type":"OTHER"},{"def":"TABLEDATAFIELDS(tableData):返回tableData中所有的字段名。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的列名组成的数组。\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nTABLEDATAFIELDS(\"ds1\")等于\nCUSTOMERID,CUSTOMERAME,CITY,COUNTRY,TEL,DISTRICT。","name":"TABLEDATAFIELDS","type":"REPORT"},{"def":"占比公式, =PROPORTION(A1)等同于=A1/sum(A1[!0])","name":"PROPORTION","type":"HA"},{"def":"COL()返回当前单元格的列号,必须使用于条件属性中\n示例:\n如果当前单元格是A5,在A5中写入\"=col()\"则返回1。\n如果当前单元格是C6,在C6中写入\"=col()\"则返回3。","name":"COL","type":"REPORT"},{"def":"TOHEX(int): 将一个十进制整型数转换成十六进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOHEX(15)等于 \"f\"。\nTOHEX(20)等于 \"14\"。","name":"TOHEX","type":"MATH"},{"def":"COS(number): 返回一个角度的余弦值。\nNumber:以弧度表示的需要求余弦值的角度。\n备注:\n 要把一个角度转换成弧度值,将角度乘于PI()/180。\n COS(n*2*PI()+number)=COS(number)(其中n为整数,number从-pi到pi)。\n示例:\nCOS(0.5)等于0.877582562。\nCOS(30*PI()/180)等于0.866025404。","name":"COS","type":"MATH"},{"def":"跨层累计, =CROSSLAYERTOTAL(A1, B1, C1, D1)等同于=IF(&B1 >1, D1[B1:-1] + C1, D1[A1:-1,B1:!-1] + C1), 如需横向, 则传递第五个参数false","name":"CROSSLAYERTOTAL","type":"HA"},{"def":"POWER(number,power): 返回指定数字的乘幂。\nNumber:底数,可以为任意实数。\nPower:指数。参数number按照该指数次幂乘方。\n备注:\n 可以使用符号“^”代替POWER,如: POWER(5,2)等于5^2。\n示例:\nPOWER(6,2)等于36。\nPOWER(14,5)等于537824。\nPOWER(4,2/3)等于2.519842100。\nPOWER(3,-2.3)等于0.079913677。","name":"POWER","type":"MATH"},{"def":"DAYS360(start_date,end_date,method):按照一年 360 天的算法(每个月以 30 天计,一年共计 12 个月),\n返回两日期间相差的天数,这在会计计算中将会用到。如果财务系统是基于一年 12 个月,每月 30 天,\n可用此函数帮助计算支付款项。\nStart_date 和 end_date :是用于计算期间天数的起止日期。\nMethod : 它指定了在计算中是采用欧洲方法还是美国方法。\nMethod 定义 :\nFALSE或忽略 美国方法 (NASD)。如果起始日期是一个月的 31 号,则等于同月的 30 号。如果终止日期是一个月的\n31号,并且起始日期早于 30 号,则终止日期等于下一个月的 1 号,否则,终止日期等于本月的 30 号。\nTRUE 欧洲方法。无论是起始日期还是终止日期为一个月的 31 号,都将等于本月的 30 号。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAYS360(\"1998/1/30\", \"1998/2/1\") 等于 1","name":"DAYS360","type":"DATETIME"},{"def":"filetype(file)获取文件的类型。\n当file为单文件时,返回文件类型字符串,当file为多文件时,返回文件类型的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.txt },则filetype(B2)返回值为[“doc”, “xls”, “txt”]。","name":"FILETYPE","type":"OTHER"},{"def":"ADDARRAY(array, insertArray, start):在数组第start个位置插入insertArray中的所有元素,再返回该数组。\n示例:\nADDARRAY([3, 4, 1, 5, 7], [23, 43, 22], 3)返回[3, 4, 23, 43, 22, 1, 5, 7].\nADDARRAY([3, 4, 1, 5, 7], \"测试\", 3)返回[3, 4, \"测试\", 1, 5, 7].\n注意:如果start为小于1的数或者不写start参数,则默认从数组的第一位开始插入数组元素。","name":"ADD2ARRAY","type":"ARRAY"},{"def":"BITNOT(int):将一个十进制整数进行二进制取反运算。\nint:需要进行转换的十进制数。\n示例:\nBITNOT(3)等于-4。\nBITNOT(12)等于-13。","name":"BITNOT","type":"LOGIC"},{"def":"TABLEAS(connectionName):返回名为connectionName的数据库中的所有表名。\n示例:\n假设在FRDemo这个数据库中,有3个表:a,b,c;\n那么TABLES(\"FRDemo\")等于[a,b,c].","name":"TABLES","type":"REPORT"},{"def":"SUMSQ(number1,number2, ...):返回所有参数的平方和。\nnumber1, number2, ...:为 1 到 30 个需要求平方和的参数,也可以使用数组或对数组的引用来代替以逗号分隔的参数。\n示例:\nSUMSQ(3, 4) 等于 25\n","name":"SUMSQ","type":"MATH"},{"def":"RECORDS(connection, table,field):返回数据库表table中字段名field下的所有元素。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么RECORDS(\"BASE\",\"task\",\"end\")等于[2009,2012].\n\nRECORDS(connection, table,field,row)返回table中field字段下的第row行的记录,field可以为列名也可以为列号。\n RECORDS(\"BASE\",\"task\",\"end\",2)等于2012.\n RECORDS(\"BASE\",\"task\",2,2)等于2009.","name":"RECORDS","type":"REPORT"},{"def":"","name":"TOBIGDECIMAL","type":"DELETE"},{"def":"TODOUBLE(text): 将文本转换成Double对象。\nText:需要转换的文本。\n示例:\nTODOUBLE(\"123.21\")等于 new Double(123.21)。","name":"TODOUBLE","type":"TEXT"},{"def":"TODATE()函数可以将各种日期形式的参数转换为日期类型。\n它有三种参数的形式:\n1 参数是一个日期型的参数,那么直接将这个参数返回。\n示例:\nTODATE(DATE(2007,12,12))返回2007年12月12日组成的日期。\n2 参数是以从1970年1月1日0时0分0秒开始的毫秒数,返回对应的时间。\n示例:\nTODATE(1023542354746)返回2002年6月8日。\n3 参数是日期格式的文本,那么返回这个文本对应的日期。\n示例:\nTODATE(\"2007/10/15\")返回2007年10月5日组成的日期。\nTODATE(\"2007-6-8\")返回2007年6月8日组成的日期。\n4 有两个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式。\n示例:\nTODATE(\"1/15/07\",\"mm/dd/yy\")返回07年1月15日组成的日期。\n特别的,\"yyyyMMdd\"是用来解析形如“20081230”之类的日期格式的。比如TODATE(\"20110830\",\"yyyyMMdd\")返回11年08月30日组成的日期\n5 有三个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式,第三个参数为解析日期的语言,如:zh(中文),en(英文)。\n示例:\nTODATE(\"星期三 1/15/07\",\"EEE mm/dd/yy\", \"zh\")返回07年1月15日组成的日期,使用“zh(中文)”才能够正常解析“星期三”这个字符串。","name":"TODATE","type":"DATETIME"},{"def":"PROPER(text): 将文本中的第一个字母和所有非字母字符后的第一个字母转化成大写,其他字母变为小写。\nText:需要转化为文本的公式、由双引号引用的文本串或是单元格引用。\n示例:\nPROPER(\"Finemore Integrated Office\")等于“Finemore Integrated Office”。\nPROPER(\"100 percent\")等于“100 Percent”。\nPROPER(\"SpreaDSheEt\")等于“Spreadsheet”。","name":"PROPER","type":"TEXT"},{"def":"DAY:(serial_number)返回日期中的日。DAY是介于1和31之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAY(\"2000/1/1\")等于1。\nDAY(\"2006/05/05\")等于5。\nDAY(\"1997/04/20\")等于20。\nDAY(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nDAY(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nDAY(\"1997-04-20\", \"yyyy-MM-dd\")等于20。\nDAY(35796)等于1。","name":"DAY","type":"DATETIME"},{"def":"LUNAR(year,day,month): 返回当前日期对应的农历时间。\nyear,month,day:分别对应年月日。\n示例:\n如果需要查询2011年7月21日对应的农历时间,则只需输入LUNAR(2011,7,21)结果将显示为:辛卯年六月廿一\n同样,如输入LUNAR(2001,7,21),则显示:辛巳年六月初一 。本公式支持的时间段为1900-2100年。","name":"LUNAR","type":"DATETIME"},{"def":"TABLEDATAS():返回报表数据集和服务器数据集名字。\n示例:\n服务器数据集有:ds1,ds2,ds3;报表数据集有dsr1,dsr2.\nTABLEDATAS()等于[dsr1,dsr2,ds1,ds2,ds3].\n而TABLEDATAS(0)返回服务器数据集名字;TABLEDATAS(1)返回报表数据集名字;\nTABLEDATAS(0)等于[ds1,ds2,ds3];TABLEDATAS(1)等于[dsr1,dsr2].","name":"TABLEDATAS","type":"REPORT"},{"def":"TAN(number): 返回指定角度的正切值。\nNumber:待求正切值的角度,以弧度表示。如果参数是以度为单位的,乘以Pi()/180后转换为弧度。\n示例:\nTAN(0.8)等于1.029638557。\nTAN(45*Pi()/180)等于1。","name":"TAN","type":"MATH"},{"def":"","name":"JVM","type":"DELETE"},{"def":"LN(number):返回一个数的自然对数。自然对数以常数项 e(2.71828182845904)为底。\nnumber:是用于计算其自然对数的正实数。\n示例:\nLN(86) 等于 4.45437\nLN(2.7182818) 等于 1\nLN(EXP(3)) 等于 3\nEXP(LN(4)) 等于 4\n","name":"LN","type":"MATH"},{"def":"ARRAY(arg1,arg2...):返回一个由arg1,arg2,...组成的数组.\narg1,arg2,...:字符串或者数字.\n示例:\nARRAY(\"hello\") = [\"hello\"].\nARRAY(\"hello\",\"world\") = [\"hello\",\"world\"].\nARRAY(\"hello\",98) = [\"hello\",98].\nARRAY(67,98) = [67,98].","name":"ARRAY","type":"ARRAY"},{"def":"TOBINARY(int): 将一个十进制整型数转换成二进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOBINARY(10)等于 \"1010\"。\nTOBINARY(20)等于 \"10100\"。","name":"TOBINARY","type":"MATH"},{"def":"NVL(value1,value2,value3,...):在所有参数中返回第一个不是null的值value1:可以为任意数,也可以为null。\nvalue2:可以为任意数,也可以为null。\n当字符串长度为0时, 返回也为null\n示例:\nNVL(12,20)等于12。\nNVL(null,12)等于12。\nNVL(null,null)等于null。\nNVL(20,null)等于20。\nNVL(null,null,10)等于10。","name":"NVL","type":"OTHER"},{"def":"CORREL(array1,array2): 求两个相同长度数据系列的相关系数(与Excel的同名函数作用相同)。\n如果数组或引用参数包含文本、逻辑值或空白单元格,则这些值将被忽略;但包含零值的单元格将计算在内。\n函数计算结果出现负数表示负相关。相关系数的取值范围是[-1,1]之间的数。相关系数的绝对值越大,表示误差越小。 Array1 和 Array2 的数据点的个数必须相同,例如:\nCORREL([1,2,3],[2,4,6])=1。\n","name":"CORREL","type":"OTHER"},{"def":"COLNAME(tableData,colIndex)返回的是tableData中列序号colIndex的列名。\ntableData:表示TableData的名字,字符串形式。\ncolIndex:表示列序号。\n备注:\n TableData先从私有数据源中查找,再从公有数据源中查找。\n示例:\nCOLNAME(\"Check\",3)等于AcceName。\nCOLNAME(\"country\",4)等于Area。","name":"COLNAME","type":"REPORT"},{"def":"DECIMAL(number): 返回number的大数类型,常用于精确计算。","name":"DECIMAL","type":"MATH"},{"def":"CLASS(object):返回object对象的所属的类。","name":"CLASS","type":"OTHER"},{"def":"VALUE(tableData,col,row)返回tableData中列号为col的值, 行号为row。\ntableData:tableData的名字,字符串形式的。\nrow:行号。\ncol:列号。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的行数。\n示例:\nVALUE(\"country\",5,3)等于South America。\nVALUE(\"Simple\",8,3)等于jonnason。\n示例:VALUE(\"country\",5,\"大陆\")等于South America。\n\nVALUE(tableData,col)返回tableData中列号为col的一列值。\nVALUE(tableData,targetCol, orgCol, element)返回tableData中第targetCol列中的元素,这些元素对应的第orgCol列的值为element。\n示例:\ntableData : co\n国家 省份\n\n中国 江苏\n中国 浙江\n中国 北京\n美国 纽约\n美国 新泽西\nVALUE(\"co\",2, 1, \"中国\")等于[\"江苏\", \"浙江\", \"北京\"]。\n特别说明:列号也可以写为列名。\nVALUE(tableData,targetCol, orgCol, element, idx)返回VALUE(tableData,targetCol, orgCol, element)数组的第idx个值。\n特别说明:idx的值小于0时,会取数组的第一个值,idx的值大于数组长度时,会取数组的最后一个值。\n","name":"VALUE","type":"REPORT"},{"def":"JOINARRAY(array,sepa):返回一个由sepa作为分隔符的字符串.\narray:[arg1,arg2...]格式的数组;\nsepa:分隔符。\n示例:\nJOINARRAY([1,2],\";\") = [1;2].\nJOINARRAY([hello,world],\"-\") = [hello-world].","name":"JOINARRAY","type":"ARRAY"},{"def":"DATETONUMBER(date):返回自 1970 年 1 月 1 日 00:00:00 GMT 经过的毫秒数。\n示例:\nDATETONUMBER(\"2008-08-08\")等于1218124800000。","name":"DATETONUMBER","type":"DATETIME"},{"def":"INDEXOF(str1,index):返回字符串str1在index位置上的字符。\n备注:\n index是从0开始计数的。\n示例:\nINDEXOF(\"FineReport\",0)等于'F'。\nINDEXOF(\"FineReport\",2)等于'n'。\nINDEXOF(\"FineReport\",9)等于't'。\n\nINDEXOF(array, index):返回数组在index位置上的元素。\n备注:\n index是从1开始计数的。\n示例:\nString[] array = {\"a\", \"b\", \"c\"}\nINDEXOF(array, 1)等于\"a\".\n","name":"INDEXOF","type":"TEXT"},{"def":"PRODUCT(number1,number2, ...):将所有以参数形式给出的数字相乘,并返回乘积值。\nnumber1, number2, ...:为 1 到 30 个需要相乘的数字参数。\n示例:\nPRODUCT(3,4) 等于 12\nPRODUCT(3,4,5) 等于 60\n\n","name":"PRODUCT","type":"MATH"},{"def":"ACOS(number): 返回指定数值的反余弦值。反余弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的余弦值。\n备注:\n 函数的参数必须在-1和1之间,包括-1和1。\n 返回的角度值在0和Pi之间。\n 如果要把返回的角度用度数来表示,用180/PI()乘返回值即可。\n示例:\nACOS(1)等于0(弧度)。\nACOS(0.5)等于1.047197551(Pi/3弧度)。\nACOS(0.5)*180/PI()等于60(度)。","name":"ACOS","type":"MATH"},{"def":"FIND(find_text,within_text,start_num):从指定的索引(start_num)处开始,返回第一次出现的指定子字符串(find_text)在此字符串(within_text)中的索引。\nFind_text:需要查找的文本或包含文本的单元格引用。\nWithin_text:包含需要查找文本的文本或单元格引用。\nStart_num:指定进行查找字符的索引位置。within_text里的索引从1开始。如果省略start_num,则假设值为1。\n备注:\n 如果find_text不在within_text中,FIND函数返回值为0。\n 如果start_num不大于0,FIND函数返回错误信息*VALUE!。\n 如果start_num大于within_text的长度,FIND函数返回值为0。\n 如果find_text是空白文本,FIND函数将在搜索串中匹配第一个字符(即编号为start_num或1的字符)。\n示例:\nFIND(\"I\",\"Information\")等于1。\nFIND(\"i\",\"Information\")等于9。\nFIND(\"o\",\"Information\",2)等于4。\nFIND(\"o\",\"Information\",12)等于0。\nFIND(\"o\",\"Information\",-1)等于*VALUE!。","name":"FIND","type":"TEXT"},{"def":"MINUTE(serial_number):返回某一指定时间的分钟数,其值是介于0与59之间的一个整数。\nserial_number:包含所求分钟数的时间。\n示例:\nMINUTE(\"15:36:25\")等于36。\nMINUTE(\"15:36:25\", \"HH:mm:ss\")等于36。","name":"MINUTE","type":"DATETIME"},{"def":"SIGN(number):返回数字的符号。当数字为正数时返回 1,为零时返回 0,为负数时返回 -1。\nNumber:为任意实数。\n示例:\nSIGN(10) 等于 1\nSIGN(4-4) 等于 0\nSIGN(-0.00001) 等于 -1\n","name":"SIGN","type":"MATH"},{"def":"INDEX(key,val1,val2,...):返回key在val1,val2,...所组成的序列中的位置,不存在于序列中则返回参数的个数.\n备注:\n key和valn可以是任意类型\n示例:\nINDEX(2,2)等于1。\nINDEX(2,1,2)等于2。\nINDEX(2,4,5,6)等于4。\nINDEX(\"b\",\"b\",\"o\",\"y\")等于1。","name":"INDEX","type":"OTHER"},{"def":"REVERSE(value):返回与value相反的逻辑值。\n示例:\nREVERSE(true)等于false。","name":"REVERSE","type":"LOGIC"},{"def":"REPLACE(text, texttoreplace, replacetext):根据指定字符串,用其他文本来代替原始文本中的内容。\ntext:需要被替换部分字符的文本或单元格引用。\ntexttoreplace:指定的字符串或正则表达式。\nreplacetext:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"abcd\", \"a\", \"re\")等于\"rebcd\"。\nREPLACE(\"a**d\", \"**d\", \"rose\")等于\"arose\"。\nREPLACE(old_text,start_num,num_chars,new_text): 根据指定的字符数,用其他文本串来替换某个文本串中的部分内容。\nOld_text:需要被替换部分字符的文本或单元格引用。\nStart_num:需要用new_text来替换old_text中字符的起始位置。\nNum_chars:需要用new_text来替换old_text中字符的个数。\nNew_text:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"0123456789\",5,4,\"*\")等于“0123*89”。\nREPLACE(\"1980\",3,2,\"99\")等于“1999”。","name":"REPLACE","type":"TEXT"},{"def":"UUID():返回随机的UUID。\n示例:UUID()返回36位随机机器数。\n UUID(32)返回32位随机机器数。","name":"UUID","type":"OTHER"},{"def":"DATESUBDATE(date1, date2, op):返回两个日期之间的时间差。\nop表示返回的时间单位:\n\"s\",以秒为单位。\n\"m\",以分钟为单位。\n\"h\",以小时为单位。\n\"d\",以天为单位。\n\"w\",以周为单位。\n示例:\nDATESUBDATE(\"2008-08-08\", \"2008-06-06\",\"h\")等于1512。","name":"DATESUBDATE","type":"DATETIME"},{"def":"CONCATENATE(text1,text2,...): 将数个字符串合并成一个字符串。\nText1,text2,...:需要合并成单个文本的文本项,可以是字符,数字或是单元格引用。\n示例:\nCONCATENATE(\"Average \",\"Price\")等于“Average Price”。\nCONCATENATE(\"1\",\"2\")等于12。","name":"CONCATENATE","type":"TEXT"},{"def":"filesize(file)获取文件的大小,单位为Kb。\n当file为单文件时,返回文件大小,当file为多文件时,返回文件大小的数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了两个大小分别为100字节和10240字节的文件,则filename(B2)返回值为[0.098, 10.0]。","name":"FILESIZE","type":"OTHER"},{"def":"DAYSOFMONTH(date):返回从1900年1月后某年某月包含的天数。\n示例:\nDAYSOFMONTH(\"1900-02-01\")等于28。\nDAYSOFMONTH(\"2008/04/04\")等于30。","name":"DAYSOFMONTH","type":"DATETIME"},{"def":"DATEINQUARTER(date, number): 函数返回在某一个季度当中第几天的日期。\n示例:\nDATEINQUARTER(\"2009-05-05\", 20)等于 2009-04-20。","name":"DATEINQUARTER","type":"DATETIME"},{"def":"逐层累计, =LAYERTOTAL(B1, C1, D1)等同于=D1[B1:-1] + C1, 如需横向, 则传递第四个参数false.如LAYERTOTAL(B1, C1, D1, false)","name":"LAYERTOTAL","type":"HA"},{"def":"CNMONEY(number,unit)返回人民币大写。\nnumber:需要转换的数值型的数。\nunit:单位,\"s\",\"b\",\"q\",\"w\",\"sw\",\"bw\",\"qw\",\"y\",\"sy\",\"by\",\"qy\",\"wy\"分别代表“拾”,“佰”,“仟”,“万”,“拾万”,“佰万”,“仟万”,“亿”,“拾亿”,“佰亿”,“仟亿”,“万亿”。\n备注:\n 单位可以为空,如果为空,则直接将number转换为人民币大写,否则先将number与单位的进制相乘,然后再将相乘的结果转换为人民币大写。\n示例:\nCNMONEY(1200)等于壹仟贰佰圆整。\nCNMONEY(12.5,\"w\")等于壹拾贰万伍仟圆整。\nCNMONEY(56.3478,\"bw\")等于伍仟陆佰叁拾肆万柒仟捌佰圆整。\nCNMONEY(3.4567,\"y\")等于叁亿肆仟伍佰陆拾柒万圆整。","name":"CNMONEY","type":"TEXT"},{"def":"DAYVALUE(date):返回1900年至 date日期所经历的天数。\n示例:\nDAYVALUE(\"2008/08/08\")等于39668。","name":"DAYVALUE","type":"DATETIME"},{"def":"SQL(connectionName,sql,columnIndex,rowIndex)返回通过sql语句从connectionName中获得数据表的第columnIndex列第rowIndex行所对应的元素。\nconnectionName:数据库库的名字,字符串形式;\nsql:SQL语句,字符串形式;\ncolumnIndex:列序号,整形;\nrowIndex:行序号,整形。\n备注:行序号可以不写,这样返回值为数据列。\n示例:\n以我们提供的数据源HSQL为例\nSQL(\"HSQL\",\"SELECT * FROM CUSTOMER\",2,2)等于王先生。","name":"SQL","type":"REPORT"},{"def":"DATE(year,month,day): 返回一个表示某一特定日期的系列数。\nYear:代表年,可为一到四位数。\nMonth:代表月份。\n若1 month 12,则函数把参数值作为月。\n若month>12,则函数从年的一月份开始往上累加。例如: DATE(2000,25,2)等于2002年1月2日的系列数。\nDay:代表日。\n若日期小于等于某指定月的天数,则函数将此参数值作为日。\n若日期大于某指定月的天数,则函数从指定月份的第一天开始往上累加。若日期大于两个或多个月的总天数,则函数把减去两个月或多个月的余数加到第三或第四个月上,依此类推。例如:DATE(2000,3,35)等于2000年4月4日的系列数。\n备注:\n 若需要处理公式中日期的一部分,如年或月等,则可用此公式。\n 若年,月和日是函数而不是函数中的常量,则此公式最能体现其作用。\n示例:\nDATE(1978, 9, 19) 等于1978-09-19.\nDATE(1211, 12, 1) 等于1211-12-01. ","name":"DATE","type":"DATETIME"},{"def":"BITOPERATIOIN(int,int,op) 位运算,返回两个整数根据op进行位运算后的结果。\nint:十进制整数。\nop:位运算操作符,支持\"&\"(与),\"|\"(或),\"^\"(异或),\"<<\"(左移),\">>\"(右移)。\n示例:\nBITOPERATION(4,2,\"&\")表示4与2进行\"与\"运算,结果等于0。\nBITOPERATION(4,2,\"|\")表示4与2进行\"或\"运算,结果等于6。\nBITOPERATION(4,2,\"^\")表示4与2进行\"异或\"运算,结果等于6。\nBITOPERATION(4,2,\"<<\")表示4按位左移2位,结果等于16。\nBITOPERATION(4,2,\">>\")表示4按位右移2位,结果等于1。\nBITOPERATION(4,2,\"^~\")表示4与2进行\"同或\"运算,结果为-7。","name":"BITOPERATION","type":"LOGIC"},{"def":"LOWER(text): 将所有的大写字母转化为小写字母。\nText:需要转化为小写字母的文本串。LOWER函数不转化文本串中非字母的字符。\n示例:\nLOWER(\"A.M.10:30\")等于“a.m.10:30”。\nLOWER(\"China\")等于“china”。","name":"LOWER","type":"TEXT"},{"def":"CEILING(number): 将参数number沿绝对值增大的方向,舍入为最接近的整数\nNumber:指待舍入的数值。\nCEILING(-2.5)等于-3。\nCEILING(0.5)等于1。","name":"CEILING","type":"MATH"},{"def":"SINH(number):返回某一数字的双曲正弦值。\nnumber:为任意实数。\n示例:\nSINH(1) 等于 1.175201194\nSINH(-1) 等于 -1.175201194","name":"SINH","type":"MATH"},{"def":"AND(logical1,logical2,…): 当所有参数的值为真时,返回TRUE;当任意参数的值为假时,返回FALSE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nAND(1+7=8,5+7=12)等于TRUE。\nAND(1+7=8,5+7=11)等于FALSE。\n如果单元格A1到A4的值分别为TRUE、TRUE、FALSE和TRUE,则:\nAND(A1:A4)等于FALSE。\n如果单元格A5的值在0~50之间,则: AND(0 $A1}) + 1, 默认升序排列, 如需要降序, 则传递参数false,\n =SORT(A1, false)等同于=COUNT(A1[!0]{A1 < $A1}) + 1.","name":"SORT","type":"HA"},{"def":"SIN(number): 计算给定角度的正弦值。\nNumber:待求正弦值的以弧度表示的角度。\n备注:\n 如果参数的单位是度,将其乘以PI()/180即可转换成弧度。\n示例:\nSIN(10)等于-0.5440211108893698。\nSIN(45*PI()/180)等于0.707106781。","name":"SIN","type":"MATH"},{"def":"switch(表达式, 值1, 结果1, 值2, 结果2, ...)\n如果表达式的结果是值1,整个函数返回结果1\n如果表达式的结果是值2,整个函数返回结果2\n如果表达式的结果是值3,整个函数返回结果3\n等等\n","name":"SWITCH","type":"LOGIC"},{"def":"ROW()返回当前单元格的行号,必须使用于条件属性中\n示例:\n如果当前单元格为A5,在A5中写入\"=ROW()\"则返回5。\n如果当前单元格为B8,在B8中写入\"=ROW()\"则返回8。","name":"ROW","type":"REPORT"},{"def":"EVAL(exp)返回表达式exp计算后的结果。\nexp:一个表达式形式字符串。\n备注:\n 只要EVAL中的参数exp最终可以转化成一表达式形式的字符串,比如\"sum(2,4)\",\"2+7\"等等,那么它就可以被计算。\nEVAL(\"2+5\")等于7。\nEVAL(\"count(2,3)\")等于2。\nEVAL(\"sum\"+\"(2,3,5)\")等于10。\nEVAL(IF(true, \"sum\", \"count\") + \"(1,2,3,4)\")等于10。\nEVAL(IF(false, \"sum\", \"count\") + \"(1,2,3,4)\")等于4。","name":"EVAL","type":"OTHER"},{"def":"ATAN(number): 计算指定数值的反正切值。指定数值是返回角度的正切值,返回角度以弧度形式表示。\nNumber:返回角度的正切。\n备注:\n 返回角度在-pi/2到pi/2之间。\n 如果返回角度等于-pi/2或pi/2,ATAN将返回错误信息*NUM!。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nATAN(-1)等于-0.785398163(-pi/4弧度)。\nATAN(0)等于0(弧度)。\nATAN(2)*180/PI()等于63.43494882(度)。","name":"ATAN","type":"MATH"},{"def":"RANGE(from,to,step)函数表示从整数from开始,以step为每一步的大小,直到整数to的一个数字序列。\n例如:\nRANGE(1,5,1)表示从1开始,直到5(包括5),每一步大小为1,那么它返回一个数字序列为[1,2,3,4,5]。\nRANGE(-1,6,2)表示从-1开始,直到6(包括6),每一步大小为2,那么它返回一个数字序列为[-1,1,3,5]。\n备注:RANGE函数有三种参数形式:\n1 RANGE(to),默认的from为1,step为1,例如:\n RANGE(4)返回[1,2,3,4]。\n RANGE(-5)返回[]。\n2 RANGE(from,to),默认的step为1,例如:\n RANGE(-1,3)返回[-1,0,1,2,3]。\n RANGE(0,5)返回[0,1,2,3,4,5]。\n3 RANGE(from,to,step),三个参数的情况参照上面的注释,例如:\n RANGE(6,-1,-2)返回[6,4,2,0]。\n RANGE(4,1,1)返回[]。","name":"RANGE","type":"ARRAY"},{"def":"TANH(number):返回某一数字的双曲正切值。\nnumber:为任意实数。\n双曲正切的计算公式如下:\n示例:\nTANH(-2) 等于 -0.96403\nTANH(0) 等于 0\nTANH(0.5) 等于 0.462117\n","name":"TANH","type":"MATH"},{"def":"ROUNDDOWN(number,num_digits):靠近零值,向下(绝对值减小的方向)舍入数字。\nnumber:为需要向下舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDDOWN 和函数 ROUND 功能相似,不同之处在于函数 ROUNDDOWN 总是向下舍入数字。\n示例:\nROUNDDOWN(3.2, 0) 等于 3\nROUNDDOWN(76.9,0) 等于 76\nROUNDDOWN(3.14159, 3) 等于 3.141\nROUNDDOWN(-3.14159, 1) 等于 -3.1\nROUNDDOWN(31415.92654, -2) 等于 31,400\n","name":"ROUNDDOWN","type":"MATH"},{"def":"循环引用, =CIRCULAR(A1, B1, C1, D1)等同于=IF(&A1 = 1, 0, B1[A1:-1] + C1[A1:-1] – D1[A1:-1]),如需横向, 则传递第五个参数false","name":"CIRCULAR","type":"HA"},{"def":"HOUR(serial_number):返回某一指定时间的小时数。函数指定HOUR为0(0:00)到23(23:00)之间的一个整数。\nSerial_number:包含所求小时的时间。\n示例:\nHOUR(\"11:32:40\")等于11。\nHOUR(\"11:32:40\", \"HH:mm:ss\")等于11。","name":"HOUR","type":"DATETIME"},{"def":"ROUND(number,num_digits):返回某个数字按指定位数舍入后的数字。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND(2.15, 1) 等于 2.2\nROUND(2.149, 1) 等于 2.1\nROUND(-1.475, 2) 等于 -1.48\nROUND(21.5, -1) 等于 20\n因浮点数存在精度计算丢失问题, 导致计算结果里可能带上9999, 0000这些, \n因此加入第三个参数来控制是否需要去除9999. true表示需要过滤9999, 0000这些数据.","name":"ROUND","type":"MATH"},{"def":"YEARDELTA(date, delta):返回指定日期后delta年的日期。\n示例:\nYEARDELTA(\"2008-10-10\",10)等于2018-10-10。","name":"YEARDELTA","type":"DATETIME"},{"def":"DATEINYEAR(date, number):函数返回在一年当中第几天的日期。\n示例:\nDATEINYEAR(2008,100)等于2008-04-09,等价于DATEINYEAR(\"2008-08-08\",100),也返回2008-04-09.\nDATEINYEAR(2008,-1)等于2008-12-31,等价于DATEINYEAR(\"2008-08-08\",-1),也返回2008-12-31.","name":"DATEINYEAR","type":"DATETIME"},{"def":"WEIGHTEDAVERAGE(A1:A4,B1:B4): 返回指定数据的加权平均值。\n加权平均数是不同比重数据的平均数,加权平均数就是把原始数据按照合理的比例来计算。\nA1:A4,B1:B4:用于计算平均值的参数,A1~A4为数据,B1~B4为权值。\n示例:\n如果A1:A4为10,9,8,7,B1:B4为0.2,0.1,0.3,0.4则:\nWEIGHTEDAVERAGE(A1:A4,B1:B4)等于8.1。","name":"WEIGHTEDAVERAGE","type":"MATH"},{"def":"ASIN(number): 返回指定数值的反正弦值。反正弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的正弦值。\n备注:\n 指定数值必须在-1到1之间(含1与-1)。\n 返回角度在-pi/2到pi/2之间(含-pi/2与pi/2)。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nASIN(0.5)等于0.523598776(pi/6弧度)。\nASIN(1)等于1.570796327(pi/2弧度)。\nASIN(0.5)*180/PI()等于30(度)。","name":"ASIN","type":"MATH"},{"def":"INT(number): 返回数字下舍入(数值减小的方向)后最接近的整数值。\nNumber:需要下舍入为整数的实数。\n示例:\nINT(4.8)等于4。\nINT(-4.8)等于-5。\nINT(4.3)等于4。\nINT(-4.3)等于-5。\n公式INT(A1)将返回A1单元格中的一个正实数的整数数部分。","name":"INT","type":"MATH"},{"def":"GETUSERJOBTITLES():返回角色职务\n示例:\nGETUSERDEPARTMENTS():返回角色所有职务,若多个部门职务则返回职务数组","name":"GETUSERJOBTITLES","type":"OTHER"},{"def":"REGEXP(str, pattern):字符串str是否与正则表达式pattern相匹配。\n示例:\nREGEXP(\"aaaaac\",\"a*c\")等于true。\nREGEXP(\"abc\",\"a*c\")等于false。\n\nREGEXP(str, pattern, intNumber):字符串str是否与具有给定模式 intNumber的正则表达式pattern相匹配。\n示例:\nCASE_INSENSITIVE = 0 启用不区分大小写的匹配。 默认情况下,不区分大小写的匹配假定仅匹配 US-ASCII 字符集中的字符。可以通过指 定 UNICODE_CASE 标志连同此标志来启用 Unicode 感知的、不区分大小写的匹配。 \nMULTILINE = 1 启用多行模式。\nDOTALL = 2 启用 dotall 模式。在 dotall 模式中,表达式 . 可以匹配任何字符,包括行结束符。默认情况下,此表达式不匹配行 结束符。\nUNICODE_CASE = 3 启用 Unicode 感知的大小写折叠。指定此标志后,由 CASE_INSENSITIVE 标志启用时,不区分大小写的匹配将以 符合 Unicode Standard 的方式完成。\nCANON_EQ = 4 启用规范等价。 指定此标志后,当且仅当其完整规范分解匹配时,两个字符才可视为匹配。\nUNIX_LINES = 5 启用 Unix 行模式。 在此模式中,.、^ 和 $ 的行为中仅识别 '\\n' 行结束符。\nLITERAL = 6 启用模式的字面值解析。 指定此标志后,指定模式的输入字符串就会作为字面值字符序列来对待。输入序列中的 元字符或转义序列不具有任何特殊意义。 标志 CASE_INSENSITIVE 和 UNICODE_CASE 在与此标志一起使用时将 对匹配产生影响。其他标志都变得多余了。\nCOMMENTS = 7 模式中允许空白和注释。 此模式将忽略空白和在结束行之前以 # 开头的嵌入式注释。\n \nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 3)等于true。\nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 1)等于false。\n\n","name":"REGEXP","type":"TEXT"},{"def":"DAYSOFQUARTER(date): 返回从1900年1月后某年某季度的天数。\n示例:\nDAYSOFQUARTER(\"2009-02-01\")等于90。\nDAYSOFQUARTER(\"2009/05/05\")等于91。","name":"DAYSOFQUARTER","type":"DATETIME"},{"def":"AVERAGE(number1,number2,…,countstring): 返回指定数据的平均值。\nNumber1,number2…:用于计算平均值的参数; countString:文字、逻辑值是否参与计数。\n备注:\n 参数必须是数字,或是含有数字的名称,数组或引用。\n 如果数组或引用参数中含有文字,逻辑值,默认参与计数,countString为false则不参与计数;\n 空单元格始终不参与计数,但是,单元格中的零值参与。\n示例:\n如果A1:A6被命名为“ages”,分别等于10,23,文字,29,33及25,则:\nAVERAGE(A1:A6)等于20。\nAVERAGE(A1:A6, false)等于24。\nAVERAGE(ages)等于20。\n如果还有一个年龄为27的,求所有年龄的平均值为: AVERAGE(A1:A6,27)等于21。","name":"AVERAGE","type":"MATH"},{"def":"RADIANS(angle): 将角度转换成弧度。\nAngle:需要转换为弧度的角度。\n示例:\nRADIANS(90)等于1.570796327(π/2弧度)。","name":"RADIANS","type":"MATH"},{"def":"REMOVEARRAY(array, start, deleteCount):从数组array中删除从第start个元素开始的deleteCount个数组元素,并返回删除后的数组。\n示例:\nREMOVEARRAY([3, 4, 4, 2, 6, 7, 87], 4, 2)返回[3, 4, 4, 7, 87].\n","name":"REMOVEARRAY","type":"ARRAY"},{"def":"WEBIMAGE(path):在web页面上显示指定路径下的图片。","name":"WEBIMAGE","type":"OTHER"},{"def":"WEEK(serial_num):返回一个代表一年中的第几周的数字。\nSerial_num:表示输入的日期。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nWEEK(\"2010/1/1\")等于52。\nWEEK(\"2010/1/6\")等于1。\nWEEK(35796)等于1。","name":"WEEK","type":"DATETIME"},{"def":"filename(file)获取文件的文件名。\n当file为单文件时,返回文件名字符串,当file为多文件时,返回文件名的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.cpt },则filename(B2)返回值为[“A.doc”, “C.xls”, “B.cpt”]。","name":"FILENAME","type":"OTHER"},{"def":"COSH(number): 返回一个数值的双曲线余弦值。\nNumber:需要求其双曲线余弦值的一个实数。\n备注:\n 双曲线余弦值计算公式为: ,其中e是自然对数的底,e=2.71828182845904。\n示例:\nCOSH(3)等于10.06766200。\nCOSH(5)等于74.20994852。\nCOSH(6)等于201.7156361。","name":"COSH","type":"MATH"},{"def":"WEEKDAY(Serial_number):获取日期并返回星期数。返回值为介于0到6之间的某一整数,分别代表星期中的某一天(从星期日到星期六)。\nSerial_number:输入的日期\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n举例:\nWEEKDAY(\"2005/9/10\")等于6(星期六)。\nWEEKDAY(\"2005/9/11\")等于0(星期日)。\nWEEKDAY(35796)等于4(星期四)。\n","name":"WEEKDAY","type":"DATETIME"},{"def":"OR(logical1,logical2,…): 当所有参数的值为假时,返回FALSE;当任意参数的值为真时,返回TRUE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nOR(1+7=9,5+7=11)等于FALSE。\nOR(1+7=8,5+7=11)等于TRUE。","name":"OR","type":"LOGIC"},{"def":"MOD(number,divisor):返回两数相除的余数。结果的正负号与除数相同。\nnumber:为被除数。\ndivisor:为除数。\n示例:\nMOD(3, 2) 等于 1\nMOD(-3, 2) 等于 1\nMOD(3, -2) 等于 -1\nMOD(-3, -2) 等于 -1\n","name":"MOD","type":"MATH"},{"def":"TODAY():获取当前日期。\n示例:\n如果系统日期是2005年9月10日\n则TODAY()等于2005-9-10。","name":"TODAY","type":"DATETIME"},{"def":"ROUNDUP(number,num_digits):远离零值,向上(绝对值增大的方向)舍入数字。\nnumber:为需要向上舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDUP 和函数 ROUND 功能相似,不同之处在于函数 ROUNDUP 总是向上舍入数字。\n示例:\nROUNDUP(3.2,0) 等于 4\nROUNDUP(76.9,0) 等于 77\nROUNDUP(3.14159, 3) 等于 3.142\nROUNDUP(-3.14159, 1) 等于 -3.2\nROUNDUP(31415.92654, -2) 等于 31,500\n\n","name":"ROUNDUP","type":"MATH"},{"def":"ROUND5(number,num_digits):这个是四舍五入,奇进偶不进。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND5(2.125, 2) 等于 2.12\nROUND5(2.135, 2) 等于 2.14\n","name":"ROUND5","type":"MATH"},{"def":"TIME(hour,minute,second): 返回代表指定时间的小数。介于0:00:00(12:00:00 A.M.)与23:59:59(11:59:59 P.M.)之间的时间可返回0到0.99999999之间的对应数值。\nHour:介于0到23之间的数。\nMinute:介于0到59之间的数。\nSecond:介于0到59之间的数。\n示例:\nTIME(14,40,0)等于2:40 PM。\nTIME(19,43,24)等于7:43 PM。","name":"TIME","type":"DATETIME"},{"def":"环比公式, =MOM(A1, B1)等同于=IF(&A1 > 1, B1 / B1[A1:-1],0), 其中如果需要指定偏移量x, 则传递第三个参数x, 第四个参数表示横纵向.\n如=MOM(A1, B1, -2, false)等同于=IF(&A1 > 1, B1 / B1[;A1:-2], 0)","name":"MOM","type":"HA"},{"def":"ASINH(number): 返回指定数值的反双曲正弦值。反双曲正弦值的双曲正弦等于指定数值。即: ASINH(SINH(number))=number。\nNumber:任意实数。\n示例:\nASINH(-5)等于-2.312438341。\nASINH(8)等于2.776472281。\nASINH(16)等于3.466711038。","name":"ASINH","type":"MATH"},{"def":"EENNUMBER(value):将给定的BigDecimal类型的数字(100以内)取整后转化成英文金额的字符串。\n示例:\nENNUMBER(23.49)等于TWENTY THREE。\n注:若出现结果为空,需要将数字强制转换为BigDecimal类型,例如:ENNUMBER(TOBIGDECIMAL(80))","name":"ENNUMBER","type":"TEXT"},{"def":"CODE(text): 计算文本串中第一个字符的数字代码。返回的代码对应于计算机使用的字符集。\nText:需要计算第一个字符代码的文本或单元格引用。\n示例:\nCODE(\"S\")等于83。\nCODE(\"Spreadsheet\")等于83。","name":"CODE","type":"TEXT"},{"def":"DEGREES(angle): 将弧度转化为度。\nangle:待转换的弧度角。\n示例:\nDEGREES(PI()/2)等于90。\nDEGREES(3.1415926)等于179.9999969。","name":"DEGREES","type":"MATH"},{"def":"LEN(args): 返回文本串中的字符数或者数组的长度。\n需要注意的是:参数args为文本串时,空格也计为字符。\n参数args为数组时,直接返回数组长度。\n示例:\nLEN(\"Evermore software\")等于17。\nLEN(\" \")等于1。\nLEN(['a','b'])等于2。\n","name":"LEN","type":"TEXT"},{"def":"DATETIME():获取当前日期和时间。\n示例:\n如果系统时间是2005年9月10日 15点18分38秒\n则DATETIME()等于2005-9-10 15:18:36。","name":"DATETIME","type":"DELETE"},{"def":"UNIQUEARRAY(array):去掉数组array中的重复元素。\n示例:\nUNIQUEARRAY([14, 2, 3, 4, 3, 2, 5, 6, 2, 7, 9, 12, 3])返回[14, 2, 3, 4, 5, 6, 7, 9, 12].","name":"UNIQUEARRAY","type":"ARRAY"},{"def":"PROMOTION(value1,value2):返回value2在value1上提升的比例。\n示例:\nPROMOTION(12, 14)等于0.166666666,即提升了16.6666666%.\nPROMOTION(-12, 14)等于2.166666666,即提升了216.6666666%.","name":"PROMOTION","type":"MATH"},{"def":"PI(number): 是一个数学常量函数,当number为空时,函数返回精确到15位的数值3.141592653589793;当参数不为空时,number表示PI的倍数。\n示例:\nSIN(PI()/2)等于1。\n计算圆的面积的公式: S=PI()*(r^2),其中S为圆的面积,R为圆的半径。\nPI(3)等于9.42477796076938。","name":"PI","type":"MATH"},{"def":"ISNULL(object):判断对象中所有的值是否全部都是NULL或者为空字符串。","name":"ISNULL","type":"OTHER"},{"def":"LET(变量名,变量值,变量名,变量值,..., 表达式):局部变量赋值函数,参数的个数N必须为奇数, 最后一个是表达式,前面是N-1(偶数)为局部变量赋值对。\n变量名: 必须是合法的变量名,以字母开头,可以包括字母,数字和下划线\n表达式: 根据前面的N-1个参数赋值后计算出来的结果,这些变量赋值只在这个表达式内部有效\n示例:\nLET(a, 5,b, 6, a+b)等于11\n","name":"LET","type":"OTHER"},{"def":"SECOND(serial_number):返回某一指定时间的秒数,其值是介于0与59之间的一个整数。\nSerial_number:包含所求秒数的时间。\n示例:\nSECOND(\"15:36:25\")等于25。\nSECOND(\"15:36:25\", \"HH:mm:ss\")等于25。","name":"SECOND","type":"DATETIME"},{"def":"EXP(number): 返回e的n次幂。常数e为自然对数的底数,等于2.71828182845904。\nNumber:为任意实数,作为常数e的指数。\n备注:\n 如果要返回其他常数作为底数的幂,可以使用指数运算符(^)。例如: 在4^2中,4是底数,而2是指数。\n EXP函数与LN函数互为反函数。\n示例:\nEXP(0)等于1。\nEXP(3)等于20.08553692。\nEXP(LN(2))等于2。","name":"EXP","type":"MATH"},{"def":"treelayer(TreeObject, Int, Boolean, String):\n返回tree对象第n层的值,并且可以设置返回值类型及分隔符。\nTreeObject:tree对象,如$tree。\nInt:想要获得层级的数值,最上层为1,第二层为2,依此类推,若无则返回最底层\n。Boolean:返回值类型为字符串还是数组,默认false,返回数组;为true时返回字符串。\nString:当Boolean为true返回字符串时的分隔符,以双引号表示,默认为逗号\",\",如\";\"。\n示例:\n假设$tree勾选的值为中国-江苏-南京,中国-浙江-杭州,则treelayer($tree, true, ”\\’,\\’”):返回”’,’”分割的所选中节点字符串”南京’,’杭州”treelayer($tree, 2):以数组形式返回第二层[“江苏”,”浙江”]。treelayer($tree, 2, true, ”\\’,\\’”):返回”’,’”分割的字符串江苏’,’浙江。","name":"TREELAYER","type":"OTHER"},{"def":"读取配置文件","name":"TOTEXT","type":"DELETE"}]; +BI.FormulaJson = [{def: "MONTH:(serial_number)返回日期中的月。月是介于1和12之间的一个数。\nSerial_number:含有所求的月的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nMONTH(\"2000/1/1\")等于1。\nMONTH(\"2006/05/05\")等于5。\nMONTH(\"1997/04/20\")等于4。\nMONTH(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nMONTH(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nMONTH(\"1997-04-20\", \"yyyy-MM-dd\")等于4。\nMONTH(35796)等于1。", name: "MONTH", type: "DATETIME"}, {def: "ROWCOUNT(tableData)返回tableData的行数。\ntableData:TableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是tableData的行数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nROWCOUNT(\"ds1\")等于20。", name: "ROWCOUNT", type: "REPORT"}, {def: "RAND(): 返回均匀分布的随机数。每计算一次工作表,函数都会返回一个新的随机数值。\n备注:\n 要生成一个位于a和b之间的随机数,可以使用以下的公式: C=RAND()*(b-a)+a。\n 如果要使一个随机产生的数值不随单元格的重计算而改变,可以在编辑框中输入=RAND()并保持编辑状态,然后按F9,将公式永久性地改为随机数。\n示例:\n假如需要生成一个大于等于0,小于60的随机数,使用公式: =RAND()*60。\n假如需要生成一个大于等于0,小于19的随机数,使用公式: =RAND()*19。\n假如需要生成一个大于等于0,小于50的随机数,使用公式: =RAND()*50。", name: "RAND", type: "MATH"}, {def: "GETUSERDEPARTMENTS():返回角色部门\n示例:\nGETUSERDEPARTMENTS():返回角色所有部门,若多个部门则数组\nGETUSERDEPARTMENTS(3,2):返回角色该部门的第三层和第二层名字,\n若多个部门则返回数组,若没有第三层则只显示第二层", name: "GETUSERDEPARTMENTS", type: "OTHER"}, {def: "FORMAT(object,format) : 返回object的format格式。\nobject 需要被格式化对象,可以是String,数字,Object(常用的有Date, Time)。\nformat 格式化的样式。\n示例\nFORMAT(1234.5, \"#,##0.00\") => 1234.50\nFORMAT(1234.5, \"#,##0\") => 1234\nFORMAT(1234.5, \"¥#,##0.00\") => ¥1234.50\nFORMAT(1.5, \"0%\") => 150%\nFORMAT(1.5, \"0.000%\") => 150.000%\nFORMAT(6789, \"##0.0E0\") => 6.789E3\nFORMAT(6789, \"0.00E00\") => 6.79E03\nFORMAT(date(2007,1,1), \"EEEEE, MMMMM dd, yyyy\") => 星期一,一月 01,2007\nFORMAT(date(2007,1,13), \"MM/dd/yyyy\") => 01/13/2007\nFORMAT(date(2007,1,13), \"M-d-yy\") => 1-13-07\nFORMAT(time(16,23,56), \"h:mm:ss a\") => 4:23:56 下午", name: "FORMAT", type: "TEXT"}, {def: "TRIM(text): 清除文本中所有空格,单词间的单个空格除外,也可用于带有不规则空格的文本。\nText:需要清除空格的文本。\n示例:\nTRIM(\" Monthly Report\")等于Monthly Report。", name: "TRIM", type: "TEXT"}, {def: "SQRT(number): 返回一个正数的平方根。\nNumber:要求其平方根的任一正数。\n备注:\nNumber必须是一个正数,否则函数返回错误信息*NUM!。\n示例:\nSQRT(64)等于8。\nSQRT(-64)返回*NUM!。", name: "SQRT", type: "MATH"}, {def: "DAYSOFYEAR(year):返回某年包含的天数。\n示例:\nDAYSOFYEAR(2008)等于365,等价于DAYSOFYEAR(\"2008-01-01\")。", name: "DAYSOFYEAR", type: "DATETIME"}, {def: "RANK(number,ref,order): 返回一个数在一个数组中的秩。(如果把这个数组排序,该数的秩即为它在数组中的序号。)\nNumber 所求秩的数。(可以是Boolean型,true=1,false=0)\nRef 可以是数组,引用,或一系列数,非实数的值被忽略处理(接受Boolean型,true=1,false=0)。\nOrder 指定求秩的参数,非零为升序,零为降序\n\n备注\n1. RANK对重复的数返回相同的秩,但重复的数影响后面的数的秩,比如,在一组升序排列的整数中,如果5出现了2次,并且秩为3,那么6的秩为5 (没有数的秩是4).\n\n示例\nA1:A5 = 6, 4.5, 4.5, 2, 4\nRANK(A1,A1:A5,1) 即 6 的秩为 5.\n\nRANK(3,1,2,\"go\",3,4,1) = 3, \"go\"被忽略。", name: "RANK", type: "OTHER"}, {def: "ODD(number):返回对指定数值进行舍入后的奇数。\nnumber:是要舍入求奇的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是奇数,则不须进行任何舍入处理。\n示例:\nODD(1.5) 等于 3\nODD(3) 等于 3\nODD(2) 等于 3\nODD(-1) 等于 -1", name: "ODD", type: "MATH"}, {def: "COLCOUNT(tableData):返回tableData中列的个数。\ntableData:tableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是第一个查找到的tableData中列数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nCOLCOUNT(\"ds1\")等于6。\n", name: "COLCOUNT", type: "REPORT"}, {def: "ENDWITH(str1,str2):判断字符串str1是否以str2结束。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nENDWITH(\"FineReport\",\"Report\")等于true。\nENDWITH(\"FineReport\",\"Fine\")等于false。\nENDWITH(\"FineReport\",\"report\")等于false。", name: "ENDWITH", type: "TEXT"}, {def: "LOG10(number):返回以 10 为底的对数。\nnumber: 用于常用对数计算的正实数。\n示例:\nLOG10(86) 等于 1.934498451\nLOG10(10) 等于 1\nLOG10(1E5) 等于 5\n", name: "LOG10", type: "MATH"}, {def: "MAPARRAY(array, fn):把一个数组中的项目转换到另一个数组中。\narray (Array): 要转换的数组 \nfn (Function): 处理数组项目的函数 \n示例:\nMAPARRAY([3,4,2,3,6,8,7], item != 3)等于[false,true,true,false,true,true,true].", name: "MAPARRAY", type: "ARRAY"}, {def: "FLOOR(number): 将参数number沿绝对值减小的方向去尾舍入。\nNumber:待舍入的数值。\n示例:\nFLOOR(-2.5)等于-2。\nFLOOR(2.5)等于2。\n", name: "FLOOR", type: "MATH"}, {def: "NUMTO(number,bool)或NUMTO(number):返回number的中文表示。其中bool用于选择中文表示的方式,当没有bool时采用默认方式显示。\n示例:NUMTO(2345,true)等于二三四五。\n示例:NUMTO(2345,false)等于二千三百四十五。\n示例:NUMTO(2345)等于二千三百四十五。", name: "NUMTO", type: "TEXT"}, {def: "ATANH(number): 返回数字的反双曲正切值,该函数的参数值即为反双曲正切值的双曲正切值。\nNumber:指介于-1~1之间的任意实数。\n备注:\n 指定的number必须介于-1~1之间(不包括-1,1)。\n ATANH(TANH(number))=number,例如,ATANH(TANH(8))=8。\n示例:\nATANH(-0.5)等于-0.549306144。\nATANH(0)等于0。\nATANH(0.7)等于0.867300528。", name: "ATANH", type: "MATH"}, {def: "YEAR:(serial_number)返回日期中的年。Year是介于1900和9999之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nYEAR(\"2000/1/1\")等于2000。\nYEAR(\"2006/05/05\")等于2006。\nYEAR(\"1997/04/20\")等于1997。\nYEAR(\"2000-1-1\", \"yyyy-MM-dd\")等于2000。\nYEAR(\"2006-05-05\", \"yyyy-MM-dd\")等于2006。\nYEAR(\"1997-04-20\", \"yyyy-MM-dd\")等于1997。\nYEAR(35796)等于1998。", name: "YEAR", type: "DATETIME"}, {def: "SLICEARRAY(array, start, end):返回数组从第start个到第end个元素(包括第end个元素)。\n示例:\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3, 6)返回[4, 5, 1, 5].\n当不使用end参数时,返回从start开始到数组结束之间的元素。\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3)返回[4, 5, 1, 5, 7].", name: "SLICEARRAY", type: "ARRAY"}, {def: "", name: "DECODE", type: "OTHER"}, {def: "ENMONEY(value):将给定的BigDemical类型的数字转换成英文金额字符串。\n示例:\nENMONEY(23.49)等于TWENTY THREE AND CENTS FORTY NINE", name: "ENMONEY", type: "TEXT"}, {def: "IF(boolean,number1/string1,number2/string2):判断函数,boolean为true时返回第二个参数,为false时返回第三个。\nboolean: 用于判断的布尔值,true或者false。\nnumber1/string1: 第一个参数,如果boolean为ture,返回这个值。\nnumber2/string2: 第二个参数,如果boolean为false,返回这个值。\n示例:\nIF(true,2,8)等于2\nIF(false,\"first\",\"second\")等于second\nIF(true,\"first\",7)等于first", name: "IF", type: "LOGIC"}, {def: "DATEINWEEK(date, number):函数返回在某一个星期当中第几天的日期。\n示例:\ndateInWeek(\"2008-08-28\", 2)等于2008-08-26。\ndateInWeek(\"2008-08-28\", -1)等于2008-08-31。\n如果最后一个参数为-1,返回该日期所在星期的最后一天\n", name: "DATEINWEEK", type: "DATETIME"}, {def: "MONTHDELTA(date,delta):返回指定日期date后delta个月的日期。\n示例:\nMONTHDELTA(\"2008-08-08\", 4)等于2008-12-08。", name: "MONTHDELTA", type: "DATETIME"}, {def: "FIELDS(connectionName,tableName):返回tableName这个表中的所有字段名。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么FIELDS(\"BASE\",\"task\")等于[name,start,end].", name: "FIELDS", type: "REPORT"}, {def: "DATEDIF(start_date,end_date,unit):返回两个指定日期间的天数、月数或年数。\nStart_date:代表所指定时间段的初始日期。\nEnd_date:代表所指定时间段的终止日期。\nUnit:函数返回信息的类型。\n若unit=“Y”,则DATEDIF返回指定时间段的年差数。\n若unit=“M”,则DATEDIF返回指定时间段的月差数。\n若unit=“D”,则DATEDIF返回指定时间段的日差数。\n若unit=“MD”,则DATEDIF忽略年和月,返回指定时间段的日差数。\n若unit=“YM”,则DATEDIF忽略年和日,返回指定时间段的月差数。\n若unit=“YD”,则DATEDIF忽略年,返回指定时间段的日差数。\n示例:\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"Y\")等于3,即在2001年2月28日与2004年3月20日之间有3个整年。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"M\")等于37,即在2001年2月28日与2004年3月20日之间有36个整月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"D\")等于1116,即在2001年2月28日与2004年3月20日之间有1116个整天。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"MD\")等于8,即忽略月和年后,2001年2月28日与2004年3月20日的差为8天。\nDATEDIF(\"2001/1/28\",\"2004/3/20\",\"YM\")等于2,即忽略日和年后,2001年1月28日与2004年3月20日的差为2个月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"YD\")等于21,即忽略年后,2001年2月28日与2004年3月20日的差为21天。", name: "DATEDIF", type: "DATETIME"}, {def: "TOIMAGE(path):显示指定路径下的图片。此处默认开启了图片缓存功能以加速报表的生成.\n如不需要缓存,请在参数后面追加值FALSE,例如:TOIMAGE(\"D:/fr.png\",false).\n如需要指定图片大小,拉伸显示, 则需要添加参数,TOIMAGE(patch, true, width, height).\n示例:=toimage(\"d:/1.jpg\", true, \"50%\", 300), 第三个参数为指定宽度, 第四个参数为指定高度.\n如果参数为整数, 则直接写数字, 如果为百分比, 则需要加上引号, 如\"300%\"", name: "TOIMAGE", type: "OTHER"}, {def: "LEFT(text,num_chars): 根据指定的字符数返回文本串中的第一个或前几个字符。\nText:包含需要选取字符的文本串或单元格引用。\nNum_chars:指定返回的字符串长度。\n备注:\n Num_chars的值必须等于或大于0。\n 如果num_chars大于整个文本的长度,LEFT函数将返回所有的文本。\n 如果省略num_chars,则默认值为1。\n示例:\nLEFT(\"Fine software\",8)等于“Fine sof”。\nLEFT(\"Fine software\")等于“F”。\n如果单元格A3中含有“China”,则LEFT(A3,2)等于“Ch”。", name: "LEFT", type: "TEXT"}, {def: "SUBSTITUTE(text,old_text,new_text,instance_num): 用new_text替换文本串中的old_text。\nText:需要被替换字符的文本,或含有文本的单元格引用。\nOld_text:需要被替换的部分文本。\nNew_text:用于替换old_text的文本。\nInstance_num:指定用new_text来替换第几次出现的old_text。如果指定了instance_num,则只有指定位置上的old_text被替换,否则文字串中出现的所有old_text都被new_text替换。\n备注:\n 如果需要替换文本串中的指定文本,则使用SUBSTITUTE函数;如果需要替换文本串中指定位置上的任意文本,则使用REPLACE函数。\n示例:\nSUBSTITUTE(\"data base\",\"base\",\"model\")等于“data model”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",1)等于“July 18, 2000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\")等于“July 18, 1000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",2)等于“July 28, 1000”。 ", name: "SUBSTITUTE", type: "TEXT"}, {def: "LOG(number,base): 按指定的任意底数,返回数值的对数。\nNumber:需要求对数的正实数。\nBase:对数的底数。如果省略底数,默认值为10。\n示例:\nLOG(16,2)等于4。\nLOG(10)等于1。\nLOG(24,3)等于2.892789261。", name: "LOG", type: "MATH"}, {def: "SORTARRAY(array):返回数组array排过序的数组。\n示例:\nSORTARRAY([3, 4, 4, 5, 1, 5, 7])返回[1, 3, 4, 4, 5, 5, 7].\n注意:数组array的元素类型必须一样,并且要可比较。", name: "SORTARRAY", type: "ARRAY"}, {def: "DATEDELTA(date, deltadays):返回一个日期??date后deltadays的日期。\ndeltaDays可以为正值,负值,零。\n示例:\nDATEDELTA(\"2008-08-08\", -10)等于2008-07-29。\nDATEDELTA(\"2008-08-08\", 10)等于2008-08-18。", name: "DATEDELTA", type: "DATETIME"}, {def: "MID(text,start_num,num_chars): 返回文本串中从指定位置开始的一定数目的字符,该数目由用户指定。\nText:包含要提取字符的文本串。\nStart_num:文本中需要提取字符的起始位置。文本中第一个字符的start_num为1,依此类推。\nNum_chars:返回字符的长度。\n备注:\n 如果start_num大于文本长度,MID函数返回“”(空文本)。\n 如果start_num小于文本长度,并且start_num加上num_chars大于文本长度,MID函数将从start_num指定的起始字符直至文本末的所有字符。\n 如果start_num小于1,MID函数返回错误信息*VALUE!。\n 如果num_chars是负数,MID函数返回错误信息*VALUE!。\n示例:\nMID(\"Finemore software\",10,8)返回“software”。\nMID(\"Finemore software\",30,5)返回“”(空文本)。\nMID(\"Finemore software\",0,8)返回*VALUE!。\nMID(\"Finemore software\",5,-1)返回*VALUE!。", name: "MID", type: "TEXT"}, {def: "ATAN2(x_num,y_num): 返回x、y坐标的反正切值。返回角度为x轴与过(x_num,y_num)与坐标原点(0,0)的一条直线形成的角度。该角度以弧度显示。\nX_num:指定点的x坐标。\nY_num:指定点的y坐标。\n备注:\n 正值表示从x轴开始以逆时针方式所得的角度;负值表示从x轴开始以顺时针方式所得的角度。\na > 0,b > 0 or a > 0, b < 0时,公式直接成立;\na < 0,b > 0, ATAN2(a,b)=PI()-ABS(ATAN(b/a))\na < 0,b < 0, ATAN2(a,b)=ABS(ATAN(b/a))-PI()\n 当x_num与y_num都为0时,ATAN2返回错误信息*DIV/0!。\n 用角度制显示返回数值时,把返回数值乘以180/PI()。\n 返回值以弧度表示(返回值大于-pi且小于等于pi)。\n示例:\nATAN2(-2,2)等于2.356194490192345(弧度制的3*pi/4)。\nATAN2(2,2)等于0.785398163(弧度制的pi/4)。\nATAN2(-2,2)*180/PI()等于135(角度制)。", name: "ATAN2", type: "MATH"}, {def: "SUM(number1,number2,…): 求一个指定单元格区域中所有数字之和。\nNumber1,number2,…:1到30个参数或指定单元格区域中所有数字。\n备注:\n 函数将直接键入参数中的数值、逻辑值及文本表达式计算在内。\n 若参数是数组或引用,则只有数组或单元格引用中的数值进行计算。\n示例:\nSUM(70,80)等于150。\nSUM(\"70\",80,TRUE)等于151,逻辑值“TRUE”作为1来计算;“FALSE”作为0计算;文本“70”作为70来计算。", name: "SUM", type: "MATH"}, {def: "EXACT(text1,text2): 检测两组文本是否相同。如果完全相同,EXACT函数返回TRUE;否则,返回FALSE。EXACT函数可以区分大小写,但忽略格式的不同。同时也可以利用EXACT函数来检测输入文档的文字。\nText1:需要比较的第一组文本。\nText2:需要比较的第二组文本。\n示例:\nEXACT(\"Spreadsheet\",\"Spreadsheet\")等于TRUE。\nEXACT(\"Spreadsheet\",\"S preadsheet\")等于FALSE。\nEXACT(\"Spreadsheet\",\"spreadsheet\")等于FALSE。", name: "EXACT", type: "TEXT"}, {def: "TOINTEGER(text): 将文本转换成Integer对象。\nText:需要转换的文本。\n示例:\nTOINTEGER(\"123\")等于 new Integer(123)。", name: "TOINTEGER", type: "TEXT"}, {def: "ACOSH(number): 返回给定数值的反双曲余弦。\nNumber:返回值的双曲余弦。\n备注:\n 参数number的值必须大于或等于1。\n ACOSH(COSH(number))=number。\n示例:\nACOSH(1)等于0。\nACOSH(8)等于2.768659383。\nACOSH(5.5)等于2.389526435。", name: "ACOSH", type: "MATH"}, {def: "weekdate(year,month,weekOfMonth,dayOfWeek): 返回指定年月的指定周的周几的具体日期。\n示例:\nweekdate(2009,10,2,1)\n返回的是2009年的10月的第二个周的第一天即星期天的日期,返回的是2009-10-04\n最后一个参数dayOfWeek为-1时,表示这个周的最后一天\n示例:\nweekdate(2009,12,1,-1)\n返回的是2009年的12月的第一个周的最后一天即星期六的日期,返回的是2009-12-05\n", name: "WEEKDATE", type: "DATETIME"}, {def: "MIN(number1,number2,…): 返回参数列表中的最小值。\nNumber1,number2,…:1到30个需要找出最小值的参数。\n备注:\n 若参数中没有数字,函数MIN将返回0。\n 参数应为数字、空白单元格、逻辑值或是表示数值的文本串。如果参数是错误值时,MIN将返回错误信息。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n示例:\n如果B1:B4包含3,6,9,12,则:\nMIN(B1:B4)等于3。\nMIN(B1:B4,0)等于0。", name: "MIN", type: "MATH"}, {def: "STARTWITH(str1,str2):判断字符串str1是否以str2开始。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nSTARTWITH(\"FineReport\",\"Fine\")等于true。\nSTARTWITH(\"FineReport\",\"Report\")等于false。\nSTARTWITH(\"FineReport\",\"fine\")等于false。", name: "STARTWITH", type: "TEXT"}, {def: "COMBIN(number,number_chosen): 返回若干个指定对象的组合数。该函数与数学表达式为Cnk功能相同。\nNumber或数学表达式中的“n”指对象总数。\nNumber_chosen或数学表达式中的“k”指在对象总数中某一组合的数量。\n备注:\n Number必须是正整数,number_chosen必须是非负整数。\n 如果number和number_chosen小于0或number小于number_chosen,函数返回错误信息*NUM!。\n 对象组合是对象的子集。与排列不同的是,组合不涉及对象内部的先后顺序,而顺序对排列是非常重要的。\n 假设number=n,number_chosen=k,则: COMBIN(n,k)=Cnk=n!/(k!(n-k)!)。\n示例:\nCOMBIN(5,6)等于*NUM!。\nCOMBIN(5,2)等于10。", name: "COMBIN", type: "MATH"}, {def: "EVEN(number):返回沿绝对值增大方向取整后最接近的偶数。使用该函数可以处理那些成对出现的对象。\nnumber:所要取整的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是偶数,则不须进行任何舍入处理。\n示例:\nEVEN(1.5) 等于 2\nEVEN(3) 等于 4\nEVEN(2) 等于 2\nEVEN(-1) 等于 -2", name: "EVEN", type: "MATH"}, {def: "COUNT(value1,value2,…): 计算数组或数据区域中所含项的个数。\nValue1,value2,…:可包含任何类型数据的参数。", name: "COUNT", type: "MATH"}, {def: "INDEXOFARRAY(array, index):返回数组array的第index个元素。\n示例:\nINDEXOFARRAY([\"第一个\", \"第二个\", \"第三个\"], 2)返回\"第二个\"。", name: "INDEXOFARRAY", type: "ARRAY"}, {def: "MAP(object, string, int, int):四个参数分别是索引值,数据集的名字,索引值所在列序号,返回值所在列序号。\n提醒:后两个参数也可以写列名代替。\n根据数据集的名字,找到对应的数据集,找到其中索引列的值为key所对应的返回值。\n数据集的查找方式是依次从报表数据集找到服务器数据集。\n索引列序号与返回值序列号的初始值为1示例:\nMAP(1001, \"employee\", 1, 2)返回employee数据集,第1列中值为1001那条记录中第2列的值。\nMAP(1001, \"employee\", \"name\", \"address\")返回employee数据集,name列中值为1001那条记录中address列的值。", name: "MAP", type: "REPORT"}, {def: "SEQ(): 返回数值,在整个报表执行过程中,返回该函数被第几次执行了。\n示例:\nSEQ()在第一次执行时,结果为1。\nSEQ()在第二次执行时,结果为2。", name: "SEQ", type: "OTHER"}, {def: "i18n为本软件内置的国际化公式,可以对一些常用的词语进行国际化.\n示例:i18n('File'), 则会在中文语言环境下显示为: 文件, 而在英文语言环境下显示为: File", name: "I18N", type: "REPORT"}, {def: "层次坐标简写, 等同于=A1[A1:-1], 若需=B1[A1:-1]则HIERARCHY(A1, B1).\n若为横向, 偏移量为-2, 则写成HIERARCHY(A1, B1, -2, false), 等同于=B1[;A1:-1].\n公式中最后一个参数表示横纵向, 默认不传递, 表示纵向扩展, 若横向扩展, 则需要加上最后一个参数FALSE来区分. ", name: "HIERARCHY", type: "HA"}, {def: "", name: "ENCODE", type: "OTHER"}, {def: "DATEINMONTH(date, number):函数返回在某一个月当中第几天的日期。\n示例:\nDATEINMONTH(\"2008-08-08\", 20) 等于2008-08-20。\nDATEINMONTH(\"2008-08-08\", -1) 等于2008-08-31。", name: "DATEINMONTH", type: "DATETIME"}, {def: "TOOCTAL(int): 将一个十进制整型数转换成八进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOOCTAL(10)等于 \"12\"。\nTOOCTAL(20)等于 \"24\"。", name: "TOOCTAL", type: "MATH"}, {def: "REPEAT(text,number_times): 根据指定的次数重复显示文本。REPEAT函数可用来显示同一字符串,并对单元格进行填充。\nText:需要重复显示的文本或包含文本的单元格引用。\nNumber_times:指定文本重复的次数,且为正数。如果number_times为0,REPEAT函数将返回“”(空文本)。如果number_times不是整数,将被取整。REPEAT函数的最终结果通常不大于32767个字符。\n备注:\n 该函数可被用于在工作表中创建简单的直方图。\n示例:\nREPEAT(\"$\",4)等于“$$$$”。\n如果单元格B10的内容为“你好”,REPEAT(B10,3)等于“你好你好你好”。", name: "REPEAT", type: "TEXT"}, {def: "GREPARRAY(array,fn):函数(返回true或者false)是条件,过滤此数组,最后形成一个新数组。\n示例:\nGREPARRAY([3,4,2,3,6,8,7], item != 3)等于[4,2,6,8,7].\n", name: "GREPARRAY", type: "ARRAY"}, {def: "MAX(number1,number2,…): 返回参数列表中的最大值。\nNumber1,number2,…:1到30个需要找出最大值的参数。\n备注:\n 参数可以是数字、空白单元格、逻辑值或数字的文本表达式。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n 如果参数中没有任何数字,MAX将返回0。\n示例:\nMAX(0.1,0,1.2)等于1.2。", name: "MAX", type: "MATH"}, {def: "CHAR(number): 根据指定数字返回对应的字符。CHAR函数可将计算机其他类型的数字代码转换为字符。\nNumber:用于指定字符的数字,介于1~65535之间(包括1和65535)。\n示例:\nCHAR(88)等于“X”。\nCHAR(45)等于“-”。", name: "CHAR", type: "TEXT"}, {def: "TRUNC(number,num_digits):将数字的小数部分截去,返回整数。\nnumber:需要截尾取整的数字。\nnum_digits:用于指定取整精度的数字。\n示例:\nTRUNC(8.9) 等于 8\nTRUNC(-8.9) 等于 -8\nTRUNC(PI()) 等于 3\n", name: "TRUNC", type: "MATH"}, {def: "FACT(number):返回数的阶乘,一个数的阶乘等于 1*2*3*...*该数。\nnumber:要计算其阶乘的非负数。如果输入的 number 不是整数,则截尾取整。\n示例:\nFACT(1) 等于 1\nFACT(1.9) 等于 FACT(1) 等于 1\nFACT(0) 等于 1\nFACT(5) 等于 1*2*3*4*5 等于 120\n", name: "FACT", type: "MATH"}, {def: "STDEV(array1): 计算数据系列的标准偏差(与Excel的同名函数作用相同)。\n\n示例:\nSTDEV([1,2,3])=1。\n", name: "STDEV", type: "OTHER"}, {def: "SPLIT(String1,String2):返回由String2分割String1组成的字符串数组。\nString1:以双引号表示的字符串。\nString2:以双引号表示的分隔符。例如逗号\",\"\n示例:\nSPLIT(\"hello,world,yes\",\",\") = [\"hello\",\"world\",\"yes\"]。\nSPLIT(\"this is very good\",\" \") = [\"this\",\"is\",\"very\",\"good\"]。\n备注:\n如果只有一个参数,则返回一个错误。\n如果有多个参数,则只有前两个起作用。", name: "SPLIT", type: "TEXT"}, {def: "INARRAY(co, array):返回co在数组array中的位置,如果co不在array中,则返回0.\n示例:\nString[] arr = {\"a\",\"b\",\"c\",\"d\"}\n那么INARRAY(\"b\", arr)等于2.", name: "INARRAY", type: "ARRAY"}, {def: "REVERSEARRAY(array):返回数组array的倒序数组。\n示例:\nREVERSEARRAY([\"第一个\", \"第二个\", \"第三个\"])返回[\"第三个\", \"第二个\", \"第一个\"].", name: "REVERSEARRAY", type: "ARRAY"}, {def: "RANDBETWEEN(value1,value2):返回value1和value2之间的一个随机整数。\n示例:\nRANDBETWEEN(12.333, 13.233)只会返回13。\nRANDBETWEEN(11.2, 13.3)有可能返回12或者13。", name: "RANDBETWEEN", type: "MATH"}, {def: "UPPER(text): 将文本中所有的字符转化为大写。\nText:需要转化为大写字符的文本,或是包含文本的单元格引用。\n示例:\nUPPER(\"notes\")等于“NOTES”。\n如果单元格E5的值为“Examples”,则UPPER(E5)等于“EXAMPLES”。", name: "UPPER", type: "TEXT"}, {def: "ABS(number): 返回指定数字的绝对值。绝对值是指没有正负符号的数值。\nNumber:需要求出绝对值的任意实数。\n示例:\nABS(-1.5)等于1.5。\nABS(0)等于0。\nABS(2.5)等于2.5。", name: "ABS", type: "MATH"}, {def: "RIGHT(text,num_chars): 根据指定的字符数从右开始返回文本串中的最后一个或几个字符。\nText:包含需要提取字符的文本串或单元格引用。\nNum_chars:指定RIGHT函数从文本串中提取的字符数。Num_chars不能小于0。如果num_chars大于文本串长度,RIGHT函数将返回整个文本。如果不指定num_chars,则默认值为1。\n示例:\nRIGHT(\"It is interesting\",6)等于“esting”。\nRIGHT(\"Share Holder\")等于“r”。\nRIGHT(\"Huge sale\",4)等于“sale”。", name: "RIGHT", type: "TEXT"}, {def: "MEDIAN(array1): 返回数据系列的中值(与Excel的同名函数作用相同)。\n\n示例:\nMEDIAN([1,2,3])=2。\n", name: "MEDIAN", type: "OTHER"}, {def: "TABLEDATAFIELDS(tableData):返回tableData中所有的字段名。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的列名组成的数组。\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nTABLEDATAFIELDS(\"ds1\")等于\nCUSTOMERID,CUSTOMERAME,CITY,COUNTRY,TEL,DISTRICT。", name: "TABLEDATAFIELDS", type: "REPORT"}, {def: "占比公式, =PROPORTION(A1)等同于=A1/sum(A1[!0])", name: "PROPORTION", type: "HA"}, {def: "COL()返回当前单元格的列号,必须使用于条件属性中\n示例:\n如果当前单元格是A5,在A5中写入\"=col()\"则返回1。\n如果当前单元格是C6,在C6中写入\"=col()\"则返回3。", name: "COL", type: "REPORT"}, {def: "TOHEX(int): 将一个十进制整型数转换成十六进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOHEX(15)等于 \"f\"。\nTOHEX(20)等于 \"14\"。", name: "TOHEX", type: "MATH"}, {def: "COS(number): 返回一个角度的余弦值。\nNumber:以弧度表示的需要求余弦值的角度。\n备注:\n 要把一个角度转换成弧度值,将角度乘于PI()/180。\n COS(n*2*PI()+number)=COS(number)(其中n为整数,number从-pi到pi)。\n示例:\nCOS(0.5)等于0.877582562。\nCOS(30*PI()/180)等于0.866025404。", name: "COS", type: "MATH"}, {def: "跨层累计, =CROSSLAYERTOTAL(A1, B1, C1, D1)等同于=IF(&B1 >1, D1[B1:-1] + C1, D1[A1:-1,B1:!-1] + C1), 如需横向, 则传递第五个参数false", name: "CROSSLAYERTOTAL", type: "HA"}, {def: "POWER(number,power): 返回指定数字的乘幂。\nNumber:底数,可以为任意实数。\nPower:指数。参数number按照该指数次幂乘方。\n备注:\n 可以使用符号“^”代替POWER,如: POWER(5,2)等于5^2。\n示例:\nPOWER(6,2)等于36。\nPOWER(14,5)等于537824。\nPOWER(4,2/3)等于2.519842100。\nPOWER(3,-2.3)等于0.079913677。", name: "POWER", type: "MATH"}, {def: "DAYS360(start_date,end_date,method):按照一年 360 天的算法(每个月以 30 天计,一年共计 12 个月),\n返回两日期间相差的天数,这在会计计算中将会用到。如果财务系统是基于一年 12 个月,每月 30 天,\n可用此函数帮助计算支付款项。\nStart_date 和 end_date :是用于计算期间天数的起止日期。\nMethod : 它指定了在计算中是采用欧洲方法还是美国方法。\nMethod 定义 :\nFALSE或忽略 美国方法 (NASD)。如果起始日期是一个月的 31 号,则等于同月的 30 号。如果终止日期是一个月的\n31号,并且起始日期早于 30 号,则终止日期等于下一个月的 1 号,否则,终止日期等于本月的 30 号。\nTRUE 欧洲方法。无论是起始日期还是终止日期为一个月的 31 号,都将等于本月的 30 号。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAYS360(\"1998/1/30\", \"1998/2/1\") 等于 1", name: "DAYS360", type: "DATETIME"}, {def: "filetype(file)获取文件的类型。\n当file为单文件时,返回文件类型字符串,当file为多文件时,返回文件类型的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.txt },则filetype(B2)返回值为[“doc”, “xls”, “txt”]。", name: "FILETYPE", type: "OTHER"}, {def: "ADDARRAY(array, insertArray, start):在数组第start个位置插入insertArray中的所有元素,再返回该数组。\n示例:\nADDARRAY([3, 4, 1, 5, 7], [23, 43, 22], 3)返回[3, 4, 23, 43, 22, 1, 5, 7].\nADDARRAY([3, 4, 1, 5, 7], \"测试\", 3)返回[3, 4, \"测试\", 1, 5, 7].\n注意:如果start为小于1的数或者不写start参数,则默认从数组的第一位开始插入数组元素。", name: "ADD2ARRAY", type: "ARRAY"}, {def: "BITNOT(int):将一个十进制整数进行二进制取反运算。\nint:需要进行转换的十进制数。\n示例:\nBITNOT(3)等于-4。\nBITNOT(12)等于-13。", name: "BITNOT", type: "LOGIC"}, {def: "TABLEAS(connectionName):返回名为connectionName的数据库中的所有表名。\n示例:\n假设在FRDemo这个数据库中,有3个表:a,b,c;\n那么TABLES(\"FRDemo\")等于[a,b,c].", name: "TABLES", type: "REPORT"}, {def: "SUMSQ(number1,number2, ...):返回所有参数的平方和。\nnumber1, number2, ...:为 1 到 30 个需要求平方和的参数,也可以使用数组或对数组的引用来代替以逗号分隔的参数。\n示例:\nSUMSQ(3, 4) 等于 25\n", name: "SUMSQ", type: "MATH"}, {def: "RECORDS(connection, table,field):返回数据库表table中字段名field下的所有元素。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么RECORDS(\"BASE\",\"task\",\"end\")等于[2009,2012].\n\nRECORDS(connection, table,field,row)返回table中field字段下的第row行的记录,field可以为列名也可以为列号。\n RECORDS(\"BASE\",\"task\",\"end\",2)等于2012.\n RECORDS(\"BASE\",\"task\",2,2)等于2009.", name: "RECORDS", type: "REPORT"}, {def: "", name: "TOBIGDECIMAL", type: "DELETE"}, {def: "TODOUBLE(text): 将文本转换成Double对象。\nText:需要转换的文本。\n示例:\nTODOUBLE(\"123.21\")等于 new Double(123.21)。", name: "TODOUBLE", type: "TEXT"}, {def: "TODATE()函数可以将各种日期形式的参数转换为日期类型。\n它有三种参数的形式:\n1 参数是一个日期型的参数,那么直接将这个参数返回。\n示例:\nTODATE(DATE(2007,12,12))返回2007年12月12日组成的日期。\n2 参数是以从1970年1月1日0时0分0秒开始的毫秒数,返回对应的时间。\n示例:\nTODATE(1023542354746)返回2002年6月8日。\n3 参数是日期格式的文本,那么返回这个文本对应的日期。\n示例:\nTODATE(\"2007/10/15\")返回2007年10月5日组成的日期。\nTODATE(\"2007-6-8\")返回2007年6月8日组成的日期。\n4 有两个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式。\n示例:\nTODATE(\"1/15/07\",\"mm/dd/yy\")返回07年1月15日组成的日期。\n特别的,\"yyyyMMdd\"是用来解析形如“20081230”之类的日期格式的。比如TODATE(\"20110830\",\"yyyyMMdd\")返回11年08月30日组成的日期\n5 有三个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式,第三个参数为解析日期的语言,如:zh(中文),en(英文)。\n示例:\nTODATE(\"星期三 1/15/07\",\"EEE mm/dd/yy\", \"zh\")返回07年1月15日组成的日期,使用“zh(中文)”才能够正常解析“星期三”这个字符串。", name: "TODATE", type: "DATETIME"}, {def: "PROPER(text): 将文本中的第一个字母和所有非字母字符后的第一个字母转化成大写,其他字母变为小写。\nText:需要转化为文本的公式、由双引号引用的文本串或是单元格引用。\n示例:\nPROPER(\"Finemore Integrated Office\")等于“Finemore Integrated Office”。\nPROPER(\"100 percent\")等于“100 Percent”。\nPROPER(\"SpreaDSheEt\")等于“Spreadsheet”。", name: "PROPER", type: "TEXT"}, {def: "DAY:(serial_number)返回日期中的日。DAY是介于1和31之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAY(\"2000/1/1\")等于1。\nDAY(\"2006/05/05\")等于5。\nDAY(\"1997/04/20\")等于20。\nDAY(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nDAY(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nDAY(\"1997-04-20\", \"yyyy-MM-dd\")等于20。\nDAY(35796)等于1。", name: "DAY", type: "DATETIME"}, {def: "LUNAR(year,day,month): 返回当前日期对应的农历时间。\nyear,month,day:分别对应年月日。\n示例:\n如果需要查询2011年7月21日对应的农历时间,则只需输入LUNAR(2011,7,21)结果将显示为:辛卯年六月廿一\n同样,如输入LUNAR(2001,7,21),则显示:辛巳年六月初一 。本公式支持的时间段为1900-2100年。", name: "LUNAR", type: "DATETIME"}, {def: "TABLEDATAS():返回报表数据集和服务器数据集名字。\n示例:\n服务器数据集有:ds1,ds2,ds3;报表数据集有dsr1,dsr2.\nTABLEDATAS()等于[dsr1,dsr2,ds1,ds2,ds3].\n而TABLEDATAS(0)返回服务器数据集名字;TABLEDATAS(1)返回报表数据集名字;\nTABLEDATAS(0)等于[ds1,ds2,ds3];TABLEDATAS(1)等于[dsr1,dsr2].", name: "TABLEDATAS", type: "REPORT"}, {def: "TAN(number): 返回指定角度的正切值。\nNumber:待求正切值的角度,以弧度表示。如果参数是以度为单位的,乘以Pi()/180后转换为弧度。\n示例:\nTAN(0.8)等于1.029638557。\nTAN(45*Pi()/180)等于1。", name: "TAN", type: "MATH"}, {def: "", name: "JVM", type: "DELETE"}, {def: "LN(number):返回一个数的自然对数。自然对数以常数项 e(2.71828182845904)为底。\nnumber:是用于计算其自然对数的正实数。\n示例:\nLN(86) 等于 4.45437\nLN(2.7182818) 等于 1\nLN(EXP(3)) 等于 3\nEXP(LN(4)) 等于 4\n", name: "LN", type: "MATH"}, {def: "ARRAY(arg1,arg2...):返回一个由arg1,arg2,...组成的数组.\narg1,arg2,...:字符串或者数字.\n示例:\nARRAY(\"hello\") = [\"hello\"].\nARRAY(\"hello\",\"world\") = [\"hello\",\"world\"].\nARRAY(\"hello\",98) = [\"hello\",98].\nARRAY(67,98) = [67,98].", name: "ARRAY", type: "ARRAY"}, {def: "TOBINARY(int): 将一个十进制整型数转换成二进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOBINARY(10)等于 \"1010\"。\nTOBINARY(20)等于 \"10100\"。", name: "TOBINARY", type: "MATH"}, {def: "NVL(value1,value2,value3,...):在所有参数中返回第一个不是null的值value1:可以为任意数,也可以为null。\nvalue2:可以为任意数,也可以为null。\n当字符串长度为0时, 返回也为null\n示例:\nNVL(12,20)等于12。\nNVL(null,12)等于12。\nNVL(null,null)等于null。\nNVL(20,null)等于20。\nNVL(null,null,10)等于10。", name: "NVL", type: "OTHER"}, {def: "CORREL(array1,array2): 求两个相同长度数据系列的相关系数(与Excel的同名函数作用相同)。\n如果数组或引用参数包含文本、逻辑值或空白单元格,则这些值将被忽略;但包含零值的单元格将计算在内。\n函数计算结果出现负数表示负相关。相关系数的取值范围是[-1,1]之间的数。相关系数的绝对值越大,表示误差越小。 Array1 和 Array2 的数据点的个数必须相同,例如:\nCORREL([1,2,3],[2,4,6])=1。\n", name: "CORREL", type: "OTHER"}, {def: "COLNAME(tableData,colIndex)返回的是tableData中列序号colIndex的列名。\ntableData:表示TableData的名字,字符串形式。\ncolIndex:表示列序号。\n备注:\n TableData先从私有数据源中查找,再从公有数据源中查找。\n示例:\nCOLNAME(\"Check\",3)等于AcceName。\nCOLNAME(\"country\",4)等于Area。", name: "COLNAME", type: "REPORT"}, {def: "DECIMAL(number): 返回number的大数类型,常用于精确计算。", name: "DECIMAL", type: "MATH"}, {def: "CLASS(object):返回object对象的所属的类。", name: "CLASS", type: "OTHER"}, {def: "VALUE(tableData,col,row)返回tableData中列号为col的值, 行号为row。\ntableData:tableData的名字,字符串形式的。\nrow:行号。\ncol:列号。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的行数。\n示例:\nVALUE(\"country\",5,3)等于South America。\nVALUE(\"Simple\",8,3)等于jonnason。\n示例:VALUE(\"country\",5,\"大陆\")等于South America。\n\nVALUE(tableData,col)返回tableData中列号为col的一列值。\nVALUE(tableData,targetCol, orgCol, element)返回tableData中第targetCol列中的元素,这些元素对应的第orgCol列的值为element。\n示例:\ntableData : co\n国家 省份\n\n中国 江苏\n中国 浙江\n中国 北京\n美国 纽约\n美国 新泽西\nVALUE(\"co\",2, 1, \"中国\")等于[\"江苏\", \"浙江\", \"北京\"]。\n特别说明:列号也可以写为列名。\nVALUE(tableData,targetCol, orgCol, element, idx)返回VALUE(tableData,targetCol, orgCol, element)数组的第idx个值。\n特别说明:idx的值小于0时,会取数组的第一个值,idx的值大于数组长度时,会取数组的最后一个值。\n", name: "VALUE", type: "REPORT"}, {def: "JOINARRAY(array,sepa):返回一个由sepa作为分隔符的字符串.\narray:[arg1,arg2...]格式的数组;\nsepa:分隔符。\n示例:\nJOINARRAY([1,2],\";\") = [1;2].\nJOINARRAY([hello,world],\"-\") = [hello-world].", name: "JOINARRAY", type: "ARRAY"}, {def: "DATETONUMBER(date):返回自 1970 年 1 月 1 日 00:00:00 GMT 经过的毫秒数。\n示例:\nDATETONUMBER(\"2008-08-08\")等于1218124800000。", name: "DATETONUMBER", type: "DATETIME"}, {def: "INDEXOF(str1,index):返回字符串str1在index位置上的字符。\n备注:\n index是从0开始计数的。\n示例:\nINDEXOF(\"FineReport\",0)等于'F'。\nINDEXOF(\"FineReport\",2)等于'n'。\nINDEXOF(\"FineReport\",9)等于't'。\n\nINDEXOF(array, index):返回数组在index位置上的元素。\n备注:\n index是从1开始计数的。\n示例:\nString[] array = {\"a\", \"b\", \"c\"}\nINDEXOF(array, 1)等于\"a\".\n", name: "INDEXOF", type: "TEXT"}, {def: "PRODUCT(number1,number2, ...):将所有以参数形式给出的数字相乘,并返回乘积值。\nnumber1, number2, ...:为 1 到 30 个需要相乘的数字参数。\n示例:\nPRODUCT(3,4) 等于 12\nPRODUCT(3,4,5) 等于 60\n\n", name: "PRODUCT", type: "MATH"}, {def: "ACOS(number): 返回指定数值的反余弦值。反余弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的余弦值。\n备注:\n 函数的参数必须在-1和1之间,包括-1和1。\n 返回的角度值在0和Pi之间。\n 如果要把返回的角度用度数来表示,用180/PI()乘返回值即可。\n示例:\nACOS(1)等于0(弧度)。\nACOS(0.5)等于1.047197551(Pi/3弧度)。\nACOS(0.5)*180/PI()等于60(度)。", name: "ACOS", type: "MATH"}, {def: "FIND(find_text,within_text,start_num):从指定的索引(start_num)处开始,返回第一次出现的指定子字符串(find_text)在此字符串(within_text)中的索引。\nFind_text:需要查找的文本或包含文本的单元格引用。\nWithin_text:包含需要查找文本的文本或单元格引用。\nStart_num:指定进行查找字符的索引位置。within_text里的索引从1开始。如果省略start_num,则假设值为1。\n备注:\n 如果find_text不在within_text中,FIND函数返回值为0。\n 如果start_num不大于0,FIND函数返回错误信息*VALUE!。\n 如果start_num大于within_text的长度,FIND函数返回值为0。\n 如果find_text是空白文本,FIND函数将在搜索串中匹配第一个字符(即编号为start_num或1的字符)。\n示例:\nFIND(\"I\",\"Information\")等于1。\nFIND(\"i\",\"Information\")等于9。\nFIND(\"o\",\"Information\",2)等于4。\nFIND(\"o\",\"Information\",12)等于0。\nFIND(\"o\",\"Information\",-1)等于*VALUE!。", name: "FIND", type: "TEXT"}, {def: "MINUTE(serial_number):返回某一指定时间的分钟数,其值是介于0与59之间的一个整数。\nserial_number:包含所求分钟数的时间。\n示例:\nMINUTE(\"15:36:25\")等于36。\nMINUTE(\"15:36:25\", \"HH:mm:ss\")等于36。", name: "MINUTE", type: "DATETIME"}, {def: "SIGN(number):返回数字的符号。当数字为正数时返回 1,为零时返回 0,为负数时返回 -1。\nNumber:为任意实数。\n示例:\nSIGN(10) 等于 1\nSIGN(4-4) 等于 0\nSIGN(-0.00001) 等于 -1\n", name: "SIGN", type: "MATH"}, {def: "INDEX(key,val1,val2,...):返回key在val1,val2,...所组成的序列中的位置,不存在于序列中则返回参数的个数.\n备注:\n key和valn可以是任意类型\n示例:\nINDEX(2,2)等于1。\nINDEX(2,1,2)等于2。\nINDEX(2,4,5,6)等于4。\nINDEX(\"b\",\"b\",\"o\",\"y\")等于1。", name: "INDEX", type: "OTHER"}, {def: "REVERSE(value):返回与value相反的逻辑值。\n示例:\nREVERSE(true)等于false。", name: "REVERSE", type: "LOGIC"}, {def: "REPLACE(text, texttoreplace, replacetext):根据指定字符串,用其他文本来代替原始文本中的内容。\ntext:需要被替换部分字符的文本或单元格引用。\ntexttoreplace:指定的字符串或正则表达式。\nreplacetext:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"abcd\", \"a\", \"re\")等于\"rebcd\"。\nREPLACE(\"a**d\", \"**d\", \"rose\")等于\"arose\"。\nREPLACE(old_text,start_num,num_chars,new_text): 根据指定的字符数,用其他文本串来替换某个文本串中的部分内容。\nOld_text:需要被替换部分字符的文本或单元格引用。\nStart_num:需要用new_text来替换old_text中字符的起始位置。\nNum_chars:需要用new_text来替换old_text中字符的个数。\nNew_text:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"0123456789\",5,4,\"*\")等于“0123*89”。\nREPLACE(\"1980\",3,2,\"99\")等于“1999”。", name: "REPLACE", type: "TEXT"}, {def: "UUID():返回随机的UUID。\n示例:UUID()返回36位随机机器数。\n UUID(32)返回32位随机机器数。", name: "UUID", type: "OTHER"}, {def: "DATESUBDATE(date1, date2, op):返回两个日期之间的时间差。\nop表示返回的时间单位:\n\"s\",以秒为单位。\n\"m\",以分钟为单位。\n\"h\",以小时为单位。\n\"d\",以天为单位。\n\"w\",以周为单位。\n示例:\nDATESUBDATE(\"2008-08-08\", \"2008-06-06\",\"h\")等于1512。", name: "DATESUBDATE", type: "DATETIME"}, {def: "CONCATENATE(text1,text2,...): 将数个字符串合并成一个字符串。\nText1,text2,...:需要合并成单个文本的文本项,可以是字符,数字或是单元格引用。\n示例:\nCONCATENATE(\"Average \",\"Price\")等于“Average Price”。\nCONCATENATE(\"1\",\"2\")等于12。", name: "CONCATENATE", type: "TEXT"}, {def: "filesize(file)获取文件的大小,单位为Kb。\n当file为单文件时,返回文件大小,当file为多文件时,返回文件大小的数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了两个大小分别为100字节和10240字节的文件,则filename(B2)返回值为[0.098, 10.0]。", name: "FILESIZE", type: "OTHER"}, {def: "DAYSOFMONTH(date):返回从1900年1月后某年某月包含的天数。\n示例:\nDAYSOFMONTH(\"1900-02-01\")等于28。\nDAYSOFMONTH(\"2008/04/04\")等于30。", name: "DAYSOFMONTH", type: "DATETIME"}, {def: "DATEINQUARTER(date, number): 函数返回在某一个季度当中第几天的日期。\n示例:\nDATEINQUARTER(\"2009-05-05\", 20)等于 2009-04-20。", name: "DATEINQUARTER", type: "DATETIME"}, {def: "逐层累计, =LAYERTOTAL(B1, C1, D1)等同于=D1[B1:-1] + C1, 如需横向, 则传递第四个参数false.如LAYERTOTAL(B1, C1, D1, false)", name: "LAYERTOTAL", type: "HA"}, {def: "CNMONEY(number,unit)返回人民币大写。\nnumber:需要转换的数值型的数。\nunit:单位,\"s\",\"b\",\"q\",\"w\",\"sw\",\"bw\",\"qw\",\"y\",\"sy\",\"by\",\"qy\",\"wy\"分别代表“拾”,“佰”,“仟”,“万”,“拾万”,“佰万”,“仟万”,“亿”,“拾亿”,“佰亿”,“仟亿”,“万亿”。\n备注:\n 单位可以为空,如果为空,则直接将number转换为人民币大写,否则先将number与单位的进制相乘,然后再将相乘的结果转换为人民币大写。\n示例:\nCNMONEY(1200)等于壹仟贰佰圆整。\nCNMONEY(12.5,\"w\")等于壹拾贰万伍仟圆整。\nCNMONEY(56.3478,\"bw\")等于伍仟陆佰叁拾肆万柒仟捌佰圆整。\nCNMONEY(3.4567,\"y\")等于叁亿肆仟伍佰陆拾柒万圆整。", name: "CNMONEY", type: "TEXT"}, {def: "DAYVALUE(date):返回1900年至 date日期所经历的天数。\n示例:\nDAYVALUE(\"2008/08/08\")等于39668。", name: "DAYVALUE", type: "DATETIME"}, {def: "SQL(connectionName,sql,columnIndex,rowIndex)返回通过sql语句从connectionName中获得数据表的第columnIndex列第rowIndex行所对应的元素。\nconnectionName:数据库库的名字,字符串形式;\nsql:SQL语句,字符串形式;\ncolumnIndex:列序号,整形;\nrowIndex:行序号,整形。\n备注:行序号可以不写,这样返回值为数据列。\n示例:\n以我们提供的数据源HSQL为例\nSQL(\"HSQL\",\"SELECT * FROM CUSTOMER\",2,2)等于王先生。", name: "SQL", type: "REPORT"}, {def: "DATE(year,month,day): 返回一个表示某一特定日期的系列数。\nYear:代表年,可为一到四位数。\nMonth:代表月份。\n若1 month 12,则函数把参数值作为月。\n若month>12,则函数从年的一月份开始往上累加。例如: DATE(2000,25,2)等于2002年1月2日的系列数。\nDay:代表日。\n若日期小于等于某指定月的天数,则函数将此参数值作为日。\n若日期大于某指定月的天数,则函数从指定月份的第一天开始往上累加。若日期大于两个或多个月的总天数,则函数把减去两个月或多个月的余数加到第三或第四个月上,依此类推。例如:DATE(2000,3,35)等于2000年4月4日的系列数。\n备注:\n 若需要处理公式中日期的一部分,如年或月等,则可用此公式。\n 若年,月和日是函数而不是函数中的常量,则此公式最能体现其作用。\n示例:\nDATE(1978, 9, 19) 等于1978-09-19.\nDATE(1211, 12, 1) 等于1211-12-01. ", name: "DATE", type: "DATETIME"}, {def: "BITOPERATIOIN(int,int,op) 位运算,返回两个整数根据op进行位运算后的结果。\nint:十进制整数。\nop:位运算操作符,支持\"&\"(与),\"|\"(或),\"^\"(异或),\"<<\"(左移),\">>\"(右移)。\n示例:\nBITOPERATION(4,2,\"&\")表示4与2进行\"与\"运算,结果等于0。\nBITOPERATION(4,2,\"|\")表示4与2进行\"或\"运算,结果等于6。\nBITOPERATION(4,2,\"^\")表示4与2进行\"异或\"运算,结果等于6。\nBITOPERATION(4,2,\"<<\")表示4按位左移2位,结果等于16。\nBITOPERATION(4,2,\">>\")表示4按位右移2位,结果等于1。\nBITOPERATION(4,2,\"^~\")表示4与2进行\"同或\"运算,结果为-7。", name: "BITOPERATION", type: "LOGIC"}, {def: "LOWER(text): 将所有的大写字母转化为小写字母。\nText:需要转化为小写字母的文本串。LOWER函数不转化文本串中非字母的字符。\n示例:\nLOWER(\"A.M.10:30\")等于“a.m.10:30”。\nLOWER(\"China\")等于“china”。", name: "LOWER", type: "TEXT"}, {def: "CEILING(number): 将参数number沿绝对值增大的方向,舍入为最接近的整数\nNumber:指待舍入的数值。\nCEILING(-2.5)等于-3。\nCEILING(0.5)等于1。", name: "CEILING", type: "MATH"}, {def: "SINH(number):返回某一数字的双曲正弦值。\nnumber:为任意实数。\n示例:\nSINH(1) 等于 1.175201194\nSINH(-1) 等于 -1.175201194", name: "SINH", type: "MATH"}, {def: "AND(logical1,logical2,…): 当所有参数的值为真时,返回TRUE;当任意参数的值为假时,返回FALSE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nAND(1+7=8,5+7=12)等于TRUE。\nAND(1+7=8,5+7=11)等于FALSE。\n如果单元格A1到A4的值分别为TRUE、TRUE、FALSE和TRUE,则:\nAND(A1:A4)等于FALSE。\n如果单元格A5的值在0~50之间,则: AND(0 $A1}) + 1, 默认升序排列, 如需要降序, 则传递参数false,\n =SORT(A1, false)等同于=COUNT(A1[!0]{A1 < $A1}) + 1.", name: "SORT", type: "HA"}, {def: "SIN(number): 计算给定角度的正弦值。\nNumber:待求正弦值的以弧度表示的角度。\n备注:\n 如果参数的单位是度,将其乘以PI()/180即可转换成弧度。\n示例:\nSIN(10)等于-0.5440211108893698。\nSIN(45*PI()/180)等于0.707106781。", name: "SIN", type: "MATH"}, {def: "switch(表达式, 值1, 结果1, 值2, 结果2, ...)\n如果表达式的结果是值1,整个函数返回结果1\n如果表达式的结果是值2,整个函数返回结果2\n如果表达式的结果是值3,整个函数返回结果3\n等等\n", name: "SWITCH", type: "LOGIC"}, {def: "ROW()返回当前单元格的行号,必须使用于条件属性中\n示例:\n如果当前单元格为A5,在A5中写入\"=ROW()\"则返回5。\n如果当前单元格为B8,在B8中写入\"=ROW()\"则返回8。", name: "ROW", type: "REPORT"}, {def: "EVAL(exp)返回表达式exp计算后的结果。\nexp:一个表达式形式字符串。\n备注:\n 只要EVAL中的参数exp最终可以转化成一表达式形式的字符串,比如\"sum(2,4)\",\"2+7\"等等,那么它就可以被计算。\nEVAL(\"2+5\")等于7。\nEVAL(\"count(2,3)\")等于2。\nEVAL(\"sum\"+\"(2,3,5)\")等于10。\nEVAL(IF(true, \"sum\", \"count\") + \"(1,2,3,4)\")等于10。\nEVAL(IF(false, \"sum\", \"count\") + \"(1,2,3,4)\")等于4。", name: "EVAL", type: "OTHER"}, {def: "ATAN(number): 计算指定数值的反正切值。指定数值是返回角度的正切值,返回角度以弧度形式表示。\nNumber:返回角度的正切。\n备注:\n 返回角度在-pi/2到pi/2之间。\n 如果返回角度等于-pi/2或pi/2,ATAN将返回错误信息*NUM!。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nATAN(-1)等于-0.785398163(-pi/4弧度)。\nATAN(0)等于0(弧度)。\nATAN(2)*180/PI()等于63.43494882(度)。", name: "ATAN", type: "MATH"}, {def: "RANGE(from,to,step)函数表示从整数from开始,以step为每一步的大小,直到整数to的一个数字序列。\n例如:\nRANGE(1,5,1)表示从1开始,直到5(包括5),每一步大小为1,那么它返回一个数字序列为[1,2,3,4,5]。\nRANGE(-1,6,2)表示从-1开始,直到6(包括6),每一步大小为2,那么它返回一个数字序列为[-1,1,3,5]。\n备注:RANGE函数有三种参数形式:\n1 RANGE(to),默认的from为1,step为1,例如:\n RANGE(4)返回[1,2,3,4]。\n RANGE(-5)返回[]。\n2 RANGE(from,to),默认的step为1,例如:\n RANGE(-1,3)返回[-1,0,1,2,3]。\n RANGE(0,5)返回[0,1,2,3,4,5]。\n3 RANGE(from,to,step),三个参数的情况参照上面的注释,例如:\n RANGE(6,-1,-2)返回[6,4,2,0]。\n RANGE(4,1,1)返回[]。", name: "RANGE", type: "ARRAY"}, {def: "TANH(number):返回某一数字的双曲正切值。\nnumber:为任意实数。\n双曲正切的计算公式如下:\n示例:\nTANH(-2) 等于 -0.96403\nTANH(0) 等于 0\nTANH(0.5) 等于 0.462117\n", name: "TANH", type: "MATH"}, {def: "ROUNDDOWN(number,num_digits):靠近零值,向下(绝对值减小的方向)舍入数字。\nnumber:为需要向下舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDDOWN 和函数 ROUND 功能相似,不同之处在于函数 ROUNDDOWN 总是向下舍入数字。\n示例:\nROUNDDOWN(3.2, 0) 等于 3\nROUNDDOWN(76.9,0) 等于 76\nROUNDDOWN(3.14159, 3) 等于 3.141\nROUNDDOWN(-3.14159, 1) 等于 -3.1\nROUNDDOWN(31415.92654, -2) 等于 31,400\n", name: "ROUNDDOWN", type: "MATH"}, {def: "循环引用, =CIRCULAR(A1, B1, C1, D1)等同于=IF(&A1 = 1, 0, B1[A1:-1] + C1[A1:-1] – D1[A1:-1]),如需横向, 则传递第五个参数false", name: "CIRCULAR", type: "HA"}, {def: "HOUR(serial_number):返回某一指定时间的小时数。函数指定HOUR为0(0:00)到23(23:00)之间的一个整数。\nSerial_number:包含所求小时的时间。\n示例:\nHOUR(\"11:32:40\")等于11。\nHOUR(\"11:32:40\", \"HH:mm:ss\")等于11。", name: "HOUR", type: "DATETIME"}, {def: "ROUND(number,num_digits):返回某个数字按指定位数舍入后的数字。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND(2.15, 1) 等于 2.2\nROUND(2.149, 1) 等于 2.1\nROUND(-1.475, 2) 等于 -1.48\nROUND(21.5, -1) 等于 20\n因浮点数存在精度计算丢失问题, 导致计算结果里可能带上9999, 0000这些, \n因此加入第三个参数来控制是否需要去除9999. true表示需要过滤9999, 0000这些数据.", name: "ROUND", type: "MATH"}, {def: "YEARDELTA(date, delta):返回指定日期后delta年的日期。\n示例:\nYEARDELTA(\"2008-10-10\",10)等于2018-10-10。", name: "YEARDELTA", type: "DATETIME"}, {def: "DATEINYEAR(date, number):函数返回在一年当中第几天的日期。\n示例:\nDATEINYEAR(2008,100)等于2008-04-09,等价于DATEINYEAR(\"2008-08-08\",100),也返回2008-04-09.\nDATEINYEAR(2008,-1)等于2008-12-31,等价于DATEINYEAR(\"2008-08-08\",-1),也返回2008-12-31.", name: "DATEINYEAR", type: "DATETIME"}, {def: "WEIGHTEDAVERAGE(A1:A4,B1:B4): 返回指定数据的加权平均值。\n加权平均数是不同比重数据的平均数,加权平均数就是把原始数据按照合理的比例来计算。\nA1:A4,B1:B4:用于计算平均值的参数,A1~A4为数据,B1~B4为权值。\n示例:\n如果A1:A4为10,9,8,7,B1:B4为0.2,0.1,0.3,0.4则:\nWEIGHTEDAVERAGE(A1:A4,B1:B4)等于8.1。", name: "WEIGHTEDAVERAGE", type: "MATH"}, {def: "ASIN(number): 返回指定数值的反正弦值。反正弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的正弦值。\n备注:\n 指定数值必须在-1到1之间(含1与-1)。\n 返回角度在-pi/2到pi/2之间(含-pi/2与pi/2)。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nASIN(0.5)等于0.523598776(pi/6弧度)。\nASIN(1)等于1.570796327(pi/2弧度)。\nASIN(0.5)*180/PI()等于30(度)。", name: "ASIN", type: "MATH"}, {def: "INT(number): 返回数字下舍入(数值减小的方向)后最接近的整数值。\nNumber:需要下舍入为整数的实数。\n示例:\nINT(4.8)等于4。\nINT(-4.8)等于-5。\nINT(4.3)等于4。\nINT(-4.3)等于-5。\n公式INT(A1)将返回A1单元格中的一个正实数的整数数部分。", name: "INT", type: "MATH"}, {def: "GETUSERJOBTITLES():返回角色职务\n示例:\nGETUSERDEPARTMENTS():返回角色所有职务,若多个部门职务则返回职务数组", name: "GETUSERJOBTITLES", type: "OTHER"}, {def: "REGEXP(str, pattern):字符串str是否与正则表达式pattern相匹配。\n示例:\nREGEXP(\"aaaaac\",\"a*c\")等于true。\nREGEXP(\"abc\",\"a*c\")等于false。\n\nREGEXP(str, pattern, intNumber):字符串str是否与具有给定模式 intNumber的正则表达式pattern相匹配。\n示例:\nCASE_INSENSITIVE = 0 启用不区分大小写的匹配。 默认情况下,不区分大小写的匹配假定仅匹配 US-ASCII 字符集中的字符。可以通过指 定 UNICODE_CASE 标志连同此标志来启用 Unicode 感知的、不区分大小写的匹配。 \nMULTILINE = 1 启用多行模式。\nDOTALL = 2 启用 dotall 模式。在 dotall 模式中,表达式 . 可以匹配任何字符,包括行结束符。默认情况下,此表达式不匹配行 结束符。\nUNICODE_CASE = 3 启用 Unicode 感知的大小写折叠。指定此标志后,由 CASE_INSENSITIVE 标志启用时,不区分大小写的匹配将以 符合 Unicode Standard 的方式完成。\nCANON_EQ = 4 启用规范等价。 指定此标志后,当且仅当其完整规范分解匹配时,两个字符才可视为匹配。\nUNIX_LINES = 5 启用 Unix 行模式。 在此模式中,.、^ 和 $ 的行为中仅识别 '\\n' 行结束符。\nLITERAL = 6 启用模式的字面值解析。 指定此标志后,指定模式的输入字符串就会作为字面值字符序列来对待。输入序列中的 元字符或转义序列不具有任何特殊意义。 标志 CASE_INSENSITIVE 和 UNICODE_CASE 在与此标志一起使用时将 对匹配产生影响。其他标志都变得多余了。\nCOMMENTS = 7 模式中允许空白和注释。 此模式将忽略空白和在结束行之前以 # 开头的嵌入式注释。\n \nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 3)等于true。\nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 1)等于false。\n\n", name: "REGEXP", type: "TEXT"}, {def: "DAYSOFQUARTER(date): 返回从1900年1月后某年某季度的天数。\n示例:\nDAYSOFQUARTER(\"2009-02-01\")等于90。\nDAYSOFQUARTER(\"2009/05/05\")等于91。", name: "DAYSOFQUARTER", type: "DATETIME"}, {def: "AVERAGE(number1,number2,…,countstring): 返回指定数据的平均值。\nNumber1,number2…:用于计算平均值的参数; countString:文字、逻辑值是否参与计数。\n备注:\n 参数必须是数字,或是含有数字的名称,数组或引用。\n 如果数组或引用参数中含有文字,逻辑值,默认参与计数,countString为false则不参与计数;\n 空单元格始终不参与计数,但是,单元格中的零值参与。\n示例:\n如果A1:A6被命名为“ages”,分别等于10,23,文字,29,33及25,则:\nAVERAGE(A1:A6)等于20。\nAVERAGE(A1:A6, false)等于24。\nAVERAGE(ages)等于20。\n如果还有一个年龄为27的,求所有年龄的平均值为: AVERAGE(A1:A6,27)等于21。", name: "AVERAGE", type: "MATH"}, {def: "RADIANS(angle): 将角度转换成弧度。\nAngle:需要转换为弧度的角度。\n示例:\nRADIANS(90)等于1.570796327(π/2弧度)。", name: "RADIANS", type: "MATH"}, {def: "REMOVEARRAY(array, start, deleteCount):从数组array中删除从第start个元素开始的deleteCount个数组元素,并返回删除后的数组。\n示例:\nREMOVEARRAY([3, 4, 4, 2, 6, 7, 87], 4, 2)返回[3, 4, 4, 7, 87].\n", name: "REMOVEARRAY", type: "ARRAY"}, {def: "WEBIMAGE(path):在web页面上显示指定路径下的图片。", name: "WEBIMAGE", type: "OTHER"}, {def: "WEEK(serial_num):返回一个代表一年中的第几周的数字。\nSerial_num:表示输入的日期。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nWEEK(\"2010/1/1\")等于52。\nWEEK(\"2010/1/6\")等于1。\nWEEK(35796)等于1。", name: "WEEK", type: "DATETIME"}, {def: "filename(file)获取文件的文件名。\n当file为单文件时,返回文件名字符串,当file为多文件时,返回文件名的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.cpt },则filename(B2)返回值为[“A.doc”, “C.xls”, “B.cpt”]。", name: "FILENAME", type: "OTHER"}, {def: "COSH(number): 返回一个数值的双曲线余弦值。\nNumber:需要求其双曲线余弦值的一个实数。\n备注:\n 双曲线余弦值计算公式为: ,其中e是自然对数的底,e=2.71828182845904。\n示例:\nCOSH(3)等于10.06766200。\nCOSH(5)等于74.20994852。\nCOSH(6)等于201.7156361。", name: "COSH", type: "MATH"}, {def: "WEEKDAY(Serial_number):获取日期并返回星期数。返回值为介于0到6之间的某一整数,分别代表星期中的某一天(从星期日到星期六)。\nSerial_number:输入的日期\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n举例:\nWEEKDAY(\"2005/9/10\")等于6(星期六)。\nWEEKDAY(\"2005/9/11\")等于0(星期日)。\nWEEKDAY(35796)等于4(星期四)。\n", name: "WEEKDAY", type: "DATETIME"}, {def: "OR(logical1,logical2,…): 当所有参数的值为假时,返回FALSE;当任意参数的值为真时,返回TRUE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nOR(1+7=9,5+7=11)等于FALSE。\nOR(1+7=8,5+7=11)等于TRUE。", name: "OR", type: "LOGIC"}, {def: "MOD(number,divisor):返回两数相除的余数。结果的正负号与除数相同。\nnumber:为被除数。\ndivisor:为除数。\n示例:\nMOD(3, 2) 等于 1\nMOD(-3, 2) 等于 1\nMOD(3, -2) 等于 -1\nMOD(-3, -2) 等于 -1\n", name: "MOD", type: "MATH"}, {def: "TODAY():获取当前日期。\n示例:\n如果系统日期是2005年9月10日\n则TODAY()等于2005-9-10。", name: "TODAY", type: "DATETIME"}, {def: "ROUNDUP(number,num_digits):远离零值,向上(绝对值增大的方向)舍入数字。\nnumber:为需要向上舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDUP 和函数 ROUND 功能相似,不同之处在于函数 ROUNDUP 总是向上舍入数字。\n示例:\nROUNDUP(3.2,0) 等于 4\nROUNDUP(76.9,0) 等于 77\nROUNDUP(3.14159, 3) 等于 3.142\nROUNDUP(-3.14159, 1) 等于 -3.2\nROUNDUP(31415.92654, -2) 等于 31,500\n\n", name: "ROUNDUP", type: "MATH"}, {def: "ROUND5(number,num_digits):这个是四舍五入,奇进偶不进。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND5(2.125, 2) 等于 2.12\nROUND5(2.135, 2) 等于 2.14\n", name: "ROUND5", type: "MATH"}, {def: "TIME(hour,minute,second): 返回代表指定时间的小数。介于0:00:00(12:00:00 A.M.)与23:59:59(11:59:59 P.M.)之间的时间可返回0到0.99999999之间的对应数值。\nHour:介于0到23之间的数。\nMinute:介于0到59之间的数。\nSecond:介于0到59之间的数。\n示例:\nTIME(14,40,0)等于2:40 PM。\nTIME(19,43,24)等于7:43 PM。", name: "TIME", type: "DATETIME"}, {def: "环比公式, =MOM(A1, B1)等同于=IF(&A1 > 1, B1 / B1[A1:-1],0), 其中如果需要指定偏移量x, 则传递第三个参数x, 第四个参数表示横纵向.\n如=MOM(A1, B1, -2, false)等同于=IF(&A1 > 1, B1 / B1[;A1:-2], 0)", name: "MOM", type: "HA"}, {def: "ASINH(number): 返回指定数值的反双曲正弦值。反双曲正弦值的双曲正弦等于指定数值。即: ASINH(SINH(number))=number。\nNumber:任意实数。\n示例:\nASINH(-5)等于-2.312438341。\nASINH(8)等于2.776472281。\nASINH(16)等于3.466711038。", name: "ASINH", type: "MATH"}, {def: "EENNUMBER(value):将给定的BigDecimal类型的数字(100以内)取整后转化成英文金额的字符串。\n示例:\nENNUMBER(23.49)等于TWENTY THREE。\n注:若出现结果为空,需要将数字强制转换为BigDecimal类型,例如:ENNUMBER(TOBIGDECIMAL(80))", name: "ENNUMBER", type: "TEXT"}, {def: "CODE(text): 计算文本串中第一个字符的数字代码。返回的代码对应于计算机使用的字符集。\nText:需要计算第一个字符代码的文本或单元格引用。\n示例:\nCODE(\"S\")等于83。\nCODE(\"Spreadsheet\")等于83。", name: "CODE", type: "TEXT"}, {def: "DEGREES(angle): 将弧度转化为度。\nangle:待转换的弧度角。\n示例:\nDEGREES(PI()/2)等于90。\nDEGREES(3.1415926)等于179.9999969。", name: "DEGREES", type: "MATH"}, {def: "LEN(args): 返回文本串中的字符数或者数组的长度。\n需要注意的是:参数args为文本串时,空格也计为字符。\n参数args为数组时,直接返回数组长度。\n示例:\nLEN(\"Evermore software\")等于17。\nLEN(\" \")等于1。\nLEN(['a','b'])等于2。\n", name: "LEN", type: "TEXT"}, {def: "DATETIME():获取当前日期和时间。\n示例:\n如果系统时间是2005年9月10日 15点18分38秒\n则DATETIME()等于2005-9-10 15:18:36。", name: "DATETIME", type: "DELETE"}, {def: "UNIQUEARRAY(array):去掉数组array中的重复元素。\n示例:\nUNIQUEARRAY([14, 2, 3, 4, 3, 2, 5, 6, 2, 7, 9, 12, 3])返回[14, 2, 3, 4, 5, 6, 7, 9, 12].", name: "UNIQUEARRAY", type: "ARRAY"}, {def: "PROMOTION(value1,value2):返回value2在value1上提升的比例。\n示例:\nPROMOTION(12, 14)等于0.166666666,即提升了16.6666666%.\nPROMOTION(-12, 14)等于2.166666666,即提升了216.6666666%.", name: "PROMOTION", type: "MATH"}, {def: "PI(number): 是一个数学常量函数,当number为空时,函数返回精确到15位的数值3.141592653589793;当参数不为空时,number表示PI的倍数。\n示例:\nSIN(PI()/2)等于1。\n计算圆的面积的公式: S=PI()*(r^2),其中S为圆的面积,R为圆的半径。\nPI(3)等于9.42477796076938。", name: "PI", type: "MATH"}, {def: "ISNULL(object):判断对象中所有的值是否全部都是NULL或者为空字符串。", name: "ISNULL", type: "OTHER"}, {def: "LET(变量名,变量值,变量名,变量值,..., 表达式):局部变量赋值函数,参数的个数N必须为奇数, 最后一个是表达式,前面是N-1(偶数)为局部变量赋值对。\n变量名: 必须是合法的变量名,以字母开头,可以包括字母,数字和下划线\n表达式: 根据前面的N-1个参数赋值后计算出来的结果,这些变量赋值只在这个表达式内部有效\n示例:\nLET(a, 5,b, 6, a+b)等于11\n", name: "LET", type: "OTHER"}, {def: "SECOND(serial_number):返回某一指定时间的秒数,其值是介于0与59之间的一个整数。\nSerial_number:包含所求秒数的时间。\n示例:\nSECOND(\"15:36:25\")等于25。\nSECOND(\"15:36:25\", \"HH:mm:ss\")等于25。", name: "SECOND", type: "DATETIME"}, {def: "EXP(number): 返回e的n次幂。常数e为自然对数的底数,等于2.71828182845904。\nNumber:为任意实数,作为常数e的指数。\n备注:\n 如果要返回其他常数作为底数的幂,可以使用指数运算符(^)。例如: 在4^2中,4是底数,而2是指数。\n EXP函数与LN函数互为反函数。\n示例:\nEXP(0)等于1。\nEXP(3)等于20.08553692。\nEXP(LN(2))等于2。", name: "EXP", type: "MATH"}, {def: "treelayer(TreeObject, Int, Boolean, String):\n返回tree对象第n层的值,并且可以设置返回值类型及分隔符。\nTreeObject:tree对象,如$tree。\nInt:想要获得层级的数值,最上层为1,第二层为2,依此类推,若无则返回最底层\n。Boolean:返回值类型为字符串还是数组,默认false,返回数组;为true时返回字符串。\nString:当Boolean为true返回字符串时的分隔符,以双引号表示,默认为逗号\",\",如\";\"。\n示例:\n假设$tree勾选的值为中国-江苏-南京,中国-浙江-杭州,则treelayer($tree, true, ”\\’,\\’”):返回”’,’”分割的所选中节点字符串”南京’,’杭州”treelayer($tree, 2):以数组形式返回第二层[“江苏”,”浙江”]。treelayer($tree, 2, true, ”\\’,\\’”):返回”’,’”分割的字符串江苏’,’浙江。", name: "TREELAYER", type: "OTHER"}, {def: "读取配置文件", name: "TOTEXT", type: "DELETE"}]; /** * 当没有元素时有提示信息的view * @@ -25990,7 +25990,7 @@ BI.Pane = BI.inherit(BI.Widget, { tipText: BI.i18nText("BI-No_Selected_Item"), overlap: true, onLoaded: BI.emptyFn - }) + }); }, _init: function () { @@ -26020,7 +26020,7 @@ BI.Pane = BI.inherit(BI.Widget, { if (o.overlap === true) { if (!BI.Layers.has(this.getName())) { BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", items: [{ el: { type: "bi.layout", @@ -26048,7 +26048,7 @@ BI.Pane = BI.inherit(BI.Widget, { right: 0, top: 0 }] - }) + }); } }, @@ -26104,7 +26104,7 @@ BI.Single = BI.inherit(BI.Widget, { warningTitle: null, tipType: null, // success或warning value: null - }) + }); }, _showToolTip: function (e, opt) { @@ -26173,7 +26173,7 @@ BI.Single = BI.inherit(BI.Widget, { }, disabledHover: function () { - //取消hover事件 + // 取消hover事件 if (BI.isNotNull(this.timeout)) { clearTimeout(this.timeout); } @@ -26188,7 +26188,7 @@ BI.Single = BI.inherit(BI.Widget, { this.items = items || []; }, - //opt: {container: '', belowMouse: false} + // opt: {container: '', belowMouse: false} setTitle: function (title, opt) { this.options.title = title; if (BI.isKey(title)) { @@ -26253,7 +26253,7 @@ BI.Text = BI.inherit(BI.Single, { textAlign: "left", whiteSpace: "normal", lineHeight: null, - handler: null,//如果传入handler,表示处理文字的点击事件,不是区域的 + handler: null, // 如果传入handler,表示处理文字的点击事件,不是区域的 hgap: 0, vgap: 0, lgap: 0, @@ -26262,7 +26262,7 @@ BI.Text = BI.inherit(BI.Single, { bgap: 0, text: "", py: "" - }) + }); }, _init: function () { @@ -26271,37 +26271,37 @@ BI.Text = BI.inherit(BI.Single, { if (o.hgap + o.lgap > 0) { this.element.css({ "padding-left": o.hgap + o.lgap + "px" - }) + }); } if (o.hgap + o.rgap > 0) { this.element.css({ "padding-right": o.hgap + o.rgap + "px" - }) + }); } if (o.vgap + o.tgap > 0) { this.element.css({ "padding-top": o.vgap + o.tgap + "px" - }) + }); } if (o.vgap + o.bgap > 0) { this.element.css({ "padding-bottom": o.vgap + o.bgap + "px" - }) + }); } if (BI.isNumber(o.height)) { - this.element.css({"lineHeight": o.height + "px"}); + this.element.css({lineHeight: o.height + "px"}); } if (BI.isNumber(o.lineHeight)) { - this.element.css({"lineHeight": o.lineHeight + "px"}); + this.element.css({lineHeight: o.lineHeight + "px"}); } this.element.css({ - "textAlign": o.textAlign, - "whiteSpace": o.whiteSpace + textAlign: o.textAlign, + whiteSpace: o.whiteSpace }); if (o.handler) { this.text = BI.createWidget({ type: "bi.layout", - tagName: 'span' + tagName: "span" }); this.text.element.click(function () { o.handler(self.getValue()); @@ -26350,7 +26350,7 @@ BI.Text = BI.inherit(BI.Single, { }, setStyle: function (css) { - this.text.element.css(css) + this.text.element.css(css); }, setText: function (text) { @@ -26377,16 +26377,16 @@ BI.BasicButton = BI.inherit(BI.Single, { stopEvent: false, stopPropagation: false, selected: false, - once: false, //点击一次选中有效,再点无效 - forceSelected: false, //点击即选中, 选中了就不会被取消,与once的区别是forceSelected不影响事件的触发 - forceNotSelected: false, //无论怎么点击都不会被选中 - disableSelected: false, //使能选中 + once: false, // 点击一次选中有效,再点无效 + forceSelected: false, // 点击即选中, 选中了就不会被取消,与once的区别是forceSelected不影响事件的触发 + forceNotSelected: false, // 无论怎么点击都不会被选中 + disableSelected: false, // 使能选中 shadow: false, - isShadowShowingOnSelected: false, //选中状态下是否显示阴影 + isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 trigger: null, handler: BI.emptyFn - }) + }); }, _init: function () { BI.BasicButton.superclass._init.apply(this, arguments); @@ -26557,10 +26557,10 @@ BI.BasicButton = BI.inherit(BI.Single, { } }); - //之后的300ms点击无效 + // 之后的300ms点击无效 var onClick = BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, true); - function ev(e) { + function ev (e) { if (o.stopEvent) { e.stopEvent(); } @@ -26569,7 +26569,7 @@ BI.BasicButton = BI.inherit(BI.Single, { } } - function clk(e) { + function clk (e) { ev(e); if (!self.isEnabled() || (self.isOnce() && self.isSelected())) { return; @@ -26710,47 +26710,47 @@ BI.BasicButton.EVENT_CHANGE = "BasicButton.EVENT_CHANGE";/** * @abstract */ BI.NodeButton = BI.inherit(BI.BasicButton, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.NodeButton.superclass._defaultConfig.apply(this, arguments); return BI.extend( conf, { baseCls: (conf.baseCls || "") + " bi-node", open: false - }) + }); }, - _init:function() { + _init: function () { BI.NodeButton.superclass._init.apply(this, arguments); var self = this; - BI.nextTick(function(){ + BI.nextTick(function () { self.setOpened(self.isOpened()); - }) + }); }, - doClick: function(){ + doClick: function () { BI.NodeButton.superclass.doClick.apply(this, arguments); this.setOpened(!this.isOpened()); }, - isOnce: function(){ + isOnce: function () { return false; }, - isOpened: function(){ + isOpened: function () { return !!this.options.open; }, - setOpened: function(b){ + setOpened: function (b) { this.options.open = !!b; }, - triggerCollapse: function(){ + triggerCollapse: function () { if(this.isOpened()) { this.setOpened(false); this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, this.getValue(), this); } }, - triggerExpand: function(){ + triggerExpand: function () { if(!this.isOpened()) { this.setOpened(true); this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, this.getValue(), this); @@ -26765,17 +26765,17 @@ BI.NodeButton = BI.inherit(BI.BasicButton, { * @abstract */ BI.Tip = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Link.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-tip", zIndex: BI.zIndex_tip - }) + }); }, - _init : function() { + _init: function () { BI.Tip.superclass._init.apply(this, arguments); - this.element.css({"zIndex": this.options.zIndex}); + this.element.css({zIndex: this.options.zIndex}); } });/** * Created by GUY on 2015/6/26. @@ -26795,7 +26795,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { hgap: 0, vgap: 0 }] - }) + }); }, _init: function () { @@ -26804,7 +26804,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { BI.each(this.options.behaviors, function (key, rule) { behaviors[key] = BI.BehaviorFactory.createBehavior(key, { rule: rule - }) + }); }); this.behaviors = behaviors; this.populate(this.options.items); @@ -26844,7 +26844,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { }); btn.on(BI.Events.DESTROY, function () { BI.remove(self.buttons, btn); - }) + }); }); return buttons; @@ -26860,8 +26860,8 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { el: it }) ] - }) - }) + }); + }); } return btns; }, @@ -26874,8 +26874,8 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { } return BI.extend({}, item, { el: btns[i] - }) - }) + }); + }); }, _packageItems: function (items, packBtns) { @@ -26893,10 +26893,10 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { return layout; }, - //如果是一个简单的layout + // 如果是一个简单的layout _isSimpleLayout: function () { var o = this.options; - return o.layouts.length === 1 && !BI.isArray(o.items[0]) + return o.layouts.length === 1 && !BI.isArray(o.items[0]); }, doBehavior: function () { @@ -26904,7 +26904,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { args.unshift(this.buttons); BI.each(this.behaviors, function (i, behavior) { behavior.doBehavior.apply(behavior, args); - }) + }); }, prependItems: function (items) { @@ -26926,7 +26926,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { var btns = this._btnsCreator.apply(this, arguments); this.buttons = BI.concat(this.buttons, btns); - //如果是一个简单的layout + // 如果是一个简单的layout if (this._isSimpleLayout() && this.layouts && this.layouts.addItems) { this.layouts.addItems(btns); return; @@ -27111,7 +27111,7 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { _defaultConfig: function () { return BI.extend(BI.ButtonTree.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-button-tree" - }) + }); }, _init: function () { @@ -27219,7 +27219,7 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { return btns; }, - //获取所有的叶子节点 + // 获取所有的叶子节点 getAllLeaves: function () { var leaves = []; BI.each(this.buttons, function (i, item) { @@ -27294,7 +27294,7 @@ BI.TreeView = BI.inherit(BI.Pane, { baseCls: "bi-tree", paras: {}, itemsCreator: BI.emptyFn - }) + }); }, _init: function () { BI.TreeView.superclass._init.apply(this, arguments); @@ -27335,13 +27335,13 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //选择节点触发方法 + // 选择节点触发方法 _selectTreeNode: function (treeId, treeNode) { this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, treeNode, this); this.fireEvent(BI.TreeView.EVENT_CHANGE, treeNode, this); }, - //配置属性 + // 配置属性 _configSetting: function () { var paras = this.options.paras; var self = this; @@ -27383,11 +27383,11 @@ BI.TreeView = BI.inherit(BI.Pane, { }; var className = "dark", perTime = 100; - function onClick(event, treeId, treeNode) { + function onClick (event, treeId, treeNode) { self.nodes.checkNode(treeNode, !treeNode.checked, true, true); } - function getUrl(treeId, treeNode) { + function getUrl (treeId, treeNode) { var parentNode = self._getParentValues(treeNode); treeNode.times = treeNode.times || 1; var param = "id=" + treeNode.id @@ -27395,23 +27395,23 @@ BI.TreeView = BI.inherit(BI.Pane, { + "&parentValues= " + window.encodeURIComponent(BI.jsonEncode(parentNode)) + "&checkState=" + window.encodeURIComponent(BI.jsonEncode(treeNode.getCheckStatus())); - return BI.servletURL + '?op=' + self.options.op + '&cmd=' + self.options.cmd + "&" + param; + return BI.servletURL + "?op=" + self.options.op + "&cmd=" + self.options.cmd + "&" + param; } - function beforeExpand(treeId, treeNode) { + function beforeExpand (treeId, treeNode) { if (!treeNode.isAjaxing) { if (!treeNode.children) { treeNode.times = 1; ajaxGetNodes(treeNode, "refresh"); } return true; - } else { - BI.Msg.toast("Please Wait。", "warning"); - return false; } + BI.Msg.toast("Please Wait。", "warning"); + return false; + } - function onAsyncSuccess(event, treeId, treeNode, msg) { + function onAsyncSuccess (event, treeId, treeNode, msg) { treeNode.halfCheck = false; if (!msg || msg.length === 0 || /^[\s,\S]*<\/html>$/gi.test(msg) || self._stop) { return; @@ -27419,7 +27419,7 @@ BI.TreeView = BI.inherit(BI.Pane, { var zTree = self.nodes; var totalCount = treeNode.count || 0; - //尝试去获取下一组节点,若获取值为空数组,表示获取完成 + // 尝试去获取下一组节点,若获取值为空数组,表示获取完成 // TODO by GUY if (treeNode.children.length > totalCount) { treeNode.count = treeNode.children.length; @@ -27427,41 +27427,41 @@ BI.TreeView = BI.inherit(BI.Pane, { ajaxGetNodes(treeNode); }, perTime); } else { - //treeNode.icon = ""; + // treeNode.icon = ""; zTree.updateNode(treeNode); zTree.selectNode(treeNode.children[0]); - //className = (className === "dark" ? "":"dark"); + // className = (className === "dark" ? "":"dark"); } } - function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { + function onAsyncError (event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { var zTree = self.nodes; BI.Msg.toast("Error!", "warning"); - //treeNode.icon = ""; - //zTree.updateNode(treeNode); + // treeNode.icon = ""; + // zTree.updateNode(treeNode); } - function ajaxGetNodes(treeNode, reloadType) { + function ajaxGetNodes (treeNode, reloadType) { var zTree = self.nodes; if (reloadType == "refresh") { - //treeNode.icon = BI.servletURL +"?op=resource&resource=/com/fr/bi/web/css/base/third/ztree/img/loading.gif"; + // treeNode.icon = BI.servletURL +"?op=resource&resource=/com/fr/bi/web/css/base/third/ztree/img/loading.gif"; zTree.updateNode(treeNode); } zTree.reAsyncChildNodes(treeNode, reloadType, true); } - function beforeCheck(treeId, treeNode) { + function beforeCheck (treeId, treeNode) { treeNode.halfCheck = false; if (treeNode.checked === true) { - //将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy - //所有的半选状态都需要取消halfCheck=true的情况 - function track(children) { + // 将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy + // 所有的半选状态都需要取消halfCheck=true的情况 + function track (children) { BI.each(children, function (i, ch) { if (ch.halfCheck === true) { ch.halfCheck = false; track(ch.children); } - }) + }); } track(treeNode.children); @@ -27469,19 +27469,19 @@ BI.TreeView = BI.inherit(BI.Pane, { var nodes = treeObj.getSelectedNodes(); $.each(nodes, function (index, node) { node.halfCheck = false; - }) + }); } } - function onCheck(event, treeId, treeNode) { + function onCheck (event, treeId, treeNode) { self._selectTreeNode(treeId, treeNode); } - function onExpand(event, treeId, treeNode) { + function onExpand (event, treeId, treeNode) { treeNode.halfCheck = false; } - function onCollapse(event, treeId, treeNode) { + function onCollapse (event, treeId, treeNode) { } return setting; @@ -27498,19 +27498,19 @@ BI.TreeView = BI.inherit(BI.Pane, { }, _getNodeValue: function (node) { - //去除标红 + // 去除标红 return node.value == null ? node.text.replace(/<[^>]+>/g, "").replaceAll(" ", " ") : node.value; }, - //获取半选框值 + // 获取半选框值 _getHalfSelectedValues: function (map, node) { var self = this; var checkState = node.getCheckStatus(); - //将未选的去掉 + // 将未选的去掉 if (checkState.checked === false && checkState.half === false) { return; } - //如果节点已展开,并且是半选 + // 如果节点已展开,并且是半选 if (BI.isNotEmptyArray(node.children) && checkState.half === true) { var children = node.children; BI.each(children, function (i, ch) { @@ -27551,7 +27551,7 @@ BI.TreeView = BI.inherit(BI.Pane, { cur[key] = value; }, - //构造树节点 + // 构造树节点 _buildTree: function (map, values) { var cur = map; BI.each(values, function (i, value) { @@ -27559,16 +27559,16 @@ BI.TreeView = BI.inherit(BI.Pane, { cur[value] = {}; } cur = cur[value]; - }) + }); }, - //获取选中的值 + // 获取选中的值 _getSelectedValues: function () { var self = this; var hashMap = {}; var rootNoots = this.nodes.getNodes(); track(rootNoots); - function track(nodes) { + function track (nodes) { BI.each(nodes, function (i, node) { var checkState = node.getCheckStatus(); if (checkState.checked === true || checkState.half === true) { @@ -27580,19 +27580,19 @@ BI.TreeView = BI.inherit(BI.Pane, { self._buildTree(hashMap, values); } } - }) + }); } return hashMap; }, - //处理节点 + // 处理节点 _dealWidthNodes: function (nodes) { var self = this, o = this.options; var ns = BI.Tree.arrayFormat(nodes); BI.each(ns, function (i, n) { n.title = n.title || n.text || n.value; - //处理标红 + // 处理标红 if (BI.isKey(o.paras.keyword)) { n.text = $("
    ").__textKeywordMarked__(n.text, o.paras.keyword, n.py).html(); } else { @@ -27625,7 +27625,7 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //生成树内部方法 + // 生成树内部方法 _initTree: function (setting) { var self = this, o = this.options; self.fireEvent(BI.Events.INIT); @@ -27663,31 +27663,31 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes, setting) { var setting = setting || { - async: { - enable: false - }, - check: { - enable: false - }, - data: { - key: { - title: "title", - name: "text" - }, - simpleData: { - enable: true - } - }, - view: { - showIcon: false, - expandSpeed: "", - nameIsHTML: true + async: { + enable: false + }, + check: { + enable: false + }, + data: { + key: { + title: "title", + name: "text" }, - callback: {} - }; + simpleData: { + enable: true + } + }, + view: { + showIcon: false, + expandSpeed: "", + nameIsHTML: true + }, + callback: {} + }; this.nodes = $.fn.zTree.init(this.tree.element, setting, nodes); }, @@ -27699,7 +27699,7 @@ BI.TreeView = BI.inherit(BI.Pane, { this._stop = true; }, - //生成树方法 + // 生成树方法 stroke: function (config) { delete this.options.keyword; BI.extend(this.options.paras, config); @@ -27719,7 +27719,7 @@ BI.TreeView = BI.inherit(BI.Pane, { }, checkAll: function (checked) { - function setNode(children) { + function setNode (children) { BI.each(children, function (i, child) { child.halfCheck = false; setNode(child.children); @@ -27737,7 +27737,7 @@ BI.TreeView = BI.inherit(BI.Pane, { this.nodes && this.nodes.expandAll(flag); }, - //设置树节点的状态 + // 设置树节点的状态 setValue: function (value, param) { this.checkAll(false); this.updateValue(value, param); @@ -27759,7 +27759,7 @@ BI.TreeView = BI.inherit(BI.Pane, { BI.each(nodes, function (j, node) { BI.extend(node, {checked: true}, op); treeObj.updateNode(node); - }) + }); }); }, @@ -28006,7 +28006,7 @@ BI.shortcut("bi.async_tree", BI.AsyncTree);/** */ BI.PartTree = BI.inherit(BI.AsyncTree, { _defaultConfig: function () { - return BI.extend(BI.PartTree.superclass._defaultConfig.apply(this, arguments), {}) + return BI.extend(BI.PartTree.superclass._defaultConfig.apply(this, arguments), {}); }, _init: function () { @@ -28044,7 +28044,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { if (treeNode.checked === true) { BI.AsyncTree.superclass._selectTreeNode.apply(self, arguments); } else { - //如果选中的值中不存在该值不处理 + // 如果选中的值中不存在该值不处理 var t = this.options.paras.selectedValues; var p = parentValues.concat(name); for (var i = 0, len = p.length; i < len; i++) { @@ -28072,19 +28072,19 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { var hashMap = {}; var rootNoots = this.nodes.getNodes(); track(rootNoots); - function track(nodes) { + function track (nodes) { BI.each(nodes, function (i, node) { var checkState = node.getCheckStatus(); if (checkState.checked === false) { return true; } var parentValues = node.parentValues || self._getParentValues(node); - //把文字中的html去掉,其实就是把文字颜色去掉 + // 把文字中的html去掉,其实就是把文字颜色去掉 var values = parentValues.concat([self._getNodeValue(node)]); self._buildTree(hashMap, values); -// if(checkState.checked === true && checkState.half === false && nodes[i].flag === true){ -// continue; -// } + // if(checkState.checked === true && checkState.half === false && nodes[i].flag === true){ + // continue; + // } if (BI.isNotEmptyArray(node.children)) { track(node.children); return true; @@ -28092,7 +28092,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { if (checkState.half === true) { self._getHalfSelectedValues(hashMap, node); } - }) + }); } return hashMap; @@ -28128,7 +28128,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { self.fireEvent(BI.Events.AFTERINIT); }; - function callback(nodes) { + function callback (nodes) { if (self._stop === true) { return; } @@ -28152,7 +28152,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { return result; }, - //生成树方法 + // 生成树方法 stroke: function (config) { var o = this.options; delete o.paras.keyword; @@ -28182,14 +28182,14 @@ BI.Canvas = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Canvas.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-canvas" - }) + }); }, _init: function () { BI.Canvas.superclass._init.apply(this, arguments); var self = this, o = this.options; var canvas = document.createElement("canvas"); - if (!document.createElement('canvas').getContext) { + if (!document.createElement("canvas").getContext) { canvas = window.G_vmlCanvasManager.initElement(canvas); } this.element.append(canvas); @@ -28207,7 +28207,7 @@ BI.Canvas = BI.inherit(BI.Widget, { _getContext: function () { if (!this.ctx) { - this.ctx = this.canvas.getContext('2d'); + this.ctx = this.canvas.getContext("2d"); } return this.ctx; }, @@ -28291,7 +28291,7 @@ BI.Canvas = BI.inherit(BI.Widget, { stroke: function () { var ctx = this._getContext(); - if(!ctx){ + if(!ctx) { return false; } BI.each(this._queue, function (i, q) { @@ -28406,7 +28406,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { _cellRenderers: function (height, width, x, y) { this._lastRenderedCellIndices = this._sectionManager.getCellIndices(height, width, x, y); - return this._cellGroupRenderer() + return this._cellGroupRenderer(); }, _cellGroupRenderer: function () { @@ -28428,13 +28428,13 @@ BI.CollectionView = BI.inherit(BI.Widget, { var right = Math.min(this._width, scrollLeft + o.width + o.horizontalOverscanSize); var bottom = Math.min(this._height, scrollTop + o.height + o.verticalOverscanSize); if (right > 0 && bottom > 0) { - //如果滚动的区间并没有超出渲染的范围 + // 如果滚动的区间并没有超出渲染的范围 if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { return; } var childrenToDisplay = this._cellRenderers(bottom - top, right - left, left, top); var renderedCells = [], renderedKeys = {}, renderedWidgets = {}; - //存储所有的left和top + // 存储所有的left和top var lefts = {}, tops = {}; for (var i = 0, len = childrenToDisplay.length; i < len; i++) { var datum = childrenToDisplay[i]; @@ -28447,7 +28447,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { tops = BI.toArray(tops); var leftMap = BI.invert(lefts); var topMap = BI.invert(tops); - //存储上下左右四个边界 + // 存储上下左右四个边界 var leftBorder = {}, rightBorder = {}, topBorder = {}, bottomBorder = {}; var assertMinBorder = function (border, offset) { if (border[offset] == null) { @@ -28521,7 +28521,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { renderedKeys[datum.index] = [datum.index, i]; renderedWidgets[i] = child; } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (self.renderedKeys[i]) { @@ -28540,21 +28540,21 @@ BI.CollectionView = BI.inherit(BI.Widget, { deleteArray.push(key[1]); }); BI.each(deleteArray, function (i, index) { - //性能优化,不调用destroy方法防止触发destroy事件 + // 性能优化,不调用destroy方法防止触发destroy事件 self.renderedCells[index].el._destroy(); }); var addedItems = []; BI.each(addSet, function (index, key) { - addedItems.push(renderedCells[key[1]]) + addedItems.push(renderedCells[key[1]]); }); this.container.addItems(addedItems); - //拦截父子级关系 + // 拦截父子级关系 this.container._children = renderedWidgets; this.container.attr("items", renderedCells); this.renderedCells = renderedCells; this.renderedKeys = renderedKeys; - //Todo 左右比较特殊 + // Todo 左右比较特殊 var minX = BI.min(leftBorder); var maxX = BI.max(rightBorder); @@ -28585,7 +28585,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { this.container.setHeight(this._height); this._calculateChildrenToRender(); - //元素未挂载时不能设置scrollTop + // 元素未挂载时不能设置scrollTop try { this.element.scrollTop(o.scrollTop); this.element.scrollLeft(o.scrollLeft); @@ -28621,7 +28621,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; BI.nextTick(function () { - self.element.css({overflowX: !!b ? "auto" : "hidden"}); + self.element.css({overflowX: b ? "auto" : "hidden"}); }); } }, @@ -28631,7 +28631,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; BI.nextTick(function () { - self.element.css({overflowY: !!b ? "auto" : "hidden"}); + self.element.css({overflowY: b ? "auto" : "hidden"}); }); } }, @@ -28652,7 +28652,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { return this._getMaxScrollTop(); }, - //重新计算children + // 重新计算children _reRange: function () { this.renderRange = {}; }, @@ -28681,7 +28681,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { } }); BI.CollectionView.EVENT_SCROLL = "EVENT_SCROLL"; -BI.shortcut('bi.collection_view', BI.CollectionView);/** +BI.shortcut("bi.collection_view", BI.CollectionView);/** * @class BI.Combo * @extends BI.Widget */ @@ -28692,24 +28692,24 @@ BI.Combo = BI.inherit(BI.Widget, { baseCls: (conf.baseCls || "") + " bi-combo", trigger: "click", toggle: true, - direction: "bottom", //top||bottom||left||right||top,left||top,right||bottom,left||bottom,right - container: null,//popupview放置的容器,默认为this.element + direction: "bottom", // top||bottom||left||right||top,left||top,right||bottom,left||bottom,right + container: null, // popupview放置的容器,默认为this.element isDefaultInit: false, destroyWhenHide: false, - isNeedAdjustHeight: true,//是否需要高度调整 + isNeedAdjustHeight: true, // 是否需要高度调整 isNeedAdjustWidth: true, stopEvent: false, stopPropagation: false, - adjustLength: 0,//调整的距离 + adjustLength: 0, // 调整的距离 adjustXOffset: 0, adjustYOffset: 0, hideChecker: BI.emptyFn, - offsetStyle: "left", //left,right,center + offsetStyle: "left", // left,right,center el: {}, popup: {}, comboClass: "bi-combo-popup", hoverClass: "bi-combo-hover" - }) + }); }, _init: function () { @@ -28791,7 +28791,7 @@ BI.Combo = BI.inherit(BI.Widget, { var enterPopup = false; - function hide() { + function hide () { if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid() && o.toggle === true) { self._hideView(); self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.combo); @@ -28934,8 +28934,8 @@ BI.Combo = BI.inherit(BI.Widget, { // if (this.element.__isMouseInBounds__(e) || (this.popupView && this.popupView.element.__isMouseInBounds__(e))) { // return; // } - //BI-10290 公式combo双击公式内容会收起 - if (this.element.find(e.target).length > 0 || e.target.className === "CodeMirror-cursor" || $(e.target).closest(".CodeMirror-hints").length > 0) {//BI-9887 CodeMirror的公式弹框需要特殊处理下 + // BI-10290 公式combo双击公式内容会收起 + if (this.element.find(e.target).length > 0 || e.target.className === "CodeMirror-cursor" || $(e.target).closest(".CodeMirror-hints").length > 0) {// BI-9887 CodeMirror的公式弹框需要特殊处理下 return; } var isHide = this.options.hideChecker.apply(this, [e]); @@ -29002,31 +29002,31 @@ BI.Combo = BI.inherit(BI.Widget, { switch (o.direction) { case "bottom": case "bottom,right": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['bottom', 'top', 'right', 'left'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["bottom", "top", "right", "left"], o.offsetStyle); break; case "top": case "top,right": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['top', 'bottom', 'right', 'left'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["top", "bottom", "right", "left"], o.offsetStyle); break; case "left": case "left,bottom": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['left', 'right', 'bottom', 'top'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["left", "right", "bottom", "top"], o.offsetStyle); break; case "right": case "right,bottom": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['right', 'left', 'bottom', 'top'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "bottom", "top"], o.offsetStyle); break; case "top,left": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['top', 'bottom', 'left', 'right'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["top", "bottom", "left", "right"], o.offsetStyle); break; case "bottom,left": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['bottom', 'top', 'left', 'right'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["bottom", "top", "left", "right"], o.offsetStyle); break; case "left,top": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['left', 'right', 'top', 'bottom'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["left", "right", "top", "bottom"], o.offsetStyle); break; case "right,top": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['right', 'left', 'top', 'bottom'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "top", "bottom"], o.offsetStyle); break; case "top,custom": case "custom,top": @@ -29051,7 +29051,7 @@ BI.Combo = BI.inherit(BI.Widget, { } if ("adaptHeight" in p) { - this.resetListHeight(p['adaptHeight']); + this.resetListHeight(p["adaptHeight"]); } if ("left" in p) { this.popupView.element.css({ @@ -29162,13 +29162,13 @@ BI.Expander = BI.inherit(BI.Widget, { baseCls: "bi-expander", trigger: "click", toggle: true, - //direction: "bottom", //top,bottom四个方向 - isDefaultInit: false, //是否默认初始化子节点 + // direction: "bottom", //top,bottom四个方向 + isDefaultInit: false, // 是否默认初始化子节点 el: {}, popup: {}, expanderClass: "bi-expander-popup", hoverClass: "bi-expander-hover" - }) + }); }, _init: function () { @@ -29242,13 +29242,13 @@ BI.Expander = BI.inherit(BI.Widget, { self.element[e](function (e) { if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { self._popupView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); self.fireEvent(BI.Expander.EVENT_EXPAND); } }, function () { if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid() && o.toggle) { self._hideView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); self.fireEvent(BI.Expander.EVENT_COLLAPSE); } }); @@ -29263,7 +29263,7 @@ BI.Expander = BI.inherit(BI.Widget, { self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); self.fireEvent(BI.Expander.EVENT_EXPAND); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); self.fireEvent(BI.Expander.EVENT_COLLAPSE); } } @@ -29272,7 +29272,7 @@ BI.Expander = BI.inherit(BI.Widget, { } break; } - }) + }); }, _initExpander: function () { @@ -29294,7 +29294,7 @@ BI.Expander = BI.inherit(BI.Widget, { this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); if (type === BI.Events.CLICK) { - //self.setValue(self.getValue()); + // self.setValue(self.getValue()); self.fireEvent(BI.Expander.EVENT_CHANGE, value, obj); } }); @@ -29341,7 +29341,7 @@ BI.Expander = BI.inherit(BI.Widget, { }, populate: function (items) { - //this._assertPopupView(); + // this._assertPopupView(); this.popupView && this.popupView.populate.apply(this.popupView, arguments); this.expander.populate.apply(this.expander, arguments); }, @@ -29353,13 +29353,13 @@ BI.Expander = BI.inherit(BI.Widget, { }, setValue: function (v) { - //this._assertPopupView(); + // this._assertPopupView(); this.expander.setValue(v); this.popupView && this.popupView.setValue(v); }, getValue: function () { - //this._assertPopupView(); + // this._assertPopupView(); return this.popupView ? this.popupView.getValue() : []; }, @@ -29428,7 +29428,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { return BI.extend(BI.ComboGroup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-combo-group bi-list-item", - //以下这些属性对每一个combo都是公用的 + // 以下这些属性对每一个combo都是公用的 trigger: "click,hover", direction: "right", adjustLength: 0, @@ -29448,7 +29448,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { }] } } - }) + }); }, _init: function () { @@ -29478,7 +29478,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { ch.adjustLength = o.adjustLength; ch.popup = o.popup; } - }) + }); this.combo = BI.createWidget({ type: "bi.combo", element: this, @@ -29495,13 +29495,13 @@ BI.ComboGroup = BI.inherit(BI.Widget, { items: children }, o.popup.el) }) - }) + }); this.combo.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); if (type === BI.Events.CLICK) { self.fireEvent(BI.ComboGroup.EVENT_CHANGE, obj); } - }) + }); }, getValue: function () { @@ -29524,7 +29524,7 @@ BI.shortcut("bi.combo_group", BI.ComboGroup);BI.VirtualGroup = BI.inherit(BI.Wid hgap: 0, vgap: 0 }] - }) + }); }, render: function () { @@ -29542,8 +29542,8 @@ BI.shortcut("bi.combo_group", BI.ComboGroup);BI.VirtualGroup = BI.inherit(BI.Wid el: BI.stripEL(it) }) ] - }) - }) + }); + }); } return items; }, @@ -29606,13 +29606,13 @@ BI.Loader = BI.inherit(BI.Widget, { baseCls: "bi-loader", direction: "top", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 logic: { dynamic: true, scrolly: true }, - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -29621,13 +29621,13 @@ BI.Loader = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, prev: false, next: {}, hasPrev: BI.emptyFn, hasNext: BI.emptyFn - }) + }); }, _prevLoad: function () { @@ -29690,7 +29690,7 @@ BI.Loader = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self._nextLoad(); } - }) + }); } BI.createWidget(BI.extend({ @@ -29717,7 +29717,7 @@ BI.Loader = BI.inherit(BI.Widget, { return !!o.hasPrev.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, hasNext: function () { @@ -29728,7 +29728,7 @@ BI.Loader = BI.inherit(BI.Widget, { return !!o.hasNext.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, prependItems: function (items) { @@ -29853,7 +29853,7 @@ BI.shortcut("bi.loader", BI.Loader);/** BI.Navigation = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Navigation.superclass._defaultConfig.apply(this, arguments), { - direction: "bottom",//top, bottom, left, right, custom + direction: "bottom", // top, bottom, left, right, custom logic: { dynamic: false }, @@ -29866,7 +29866,7 @@ BI.Navigation = BI.inherit(BI.Widget, { afterCardCreated: BI.emptyFn, afterCardShow: BI.emptyFn - }) + }); }, render: function () { @@ -30023,13 +30023,13 @@ BI.Searcher = BI.inherit(BI.Widget, { hgap: 0, isDefaultInit: false, - isAutoSearch: true, //是否自动搜索 - isAutoSync: true, //是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一 + isAutoSearch: true, // 是否自动搜索 + isAutoSync: true, // 是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一 chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, - //isAutoSearch为false时启用 + // isAutoSearch为false时启用 onSearch: function (op, callback) { - callback([]) + callback([]); }, el: { @@ -30041,10 +30041,10 @@ BI.Searcher = BI.inherit(BI.Widget, { }, adapter: null, - masker: { //masker层 + masker: { // masker层 offset: {} } - }) + }); }, _init: function () { @@ -30084,7 +30084,7 @@ BI.Searcher = BI.inherit(BI.Widget, { self._pauseSearch(); break; } - }) + }); }, _assertPopupView: function () { @@ -30134,7 +30134,7 @@ BI.Searcher = BI.inherit(BI.Widget, { this._isSearching = true; this.fireEvent(BI.Searcher.EVENT_START); this.popupView.startSearch && this.popupView.startSearch(); - //搜索前先清空dom + // 搜索前先清空dom // BI.Maskers.get(this.getName()).empty(); BI.nextTick(function (name) { BI.Maskers.show(name); @@ -30211,8 +30211,8 @@ BI.Searcher = BI.inherit(BI.Widget, { }, stopSearch: function () { - this._stopSearch();//先停止搜索,然后再去设置editor为空 - //important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) + this._stopSearch();// 先停止搜索,然后再去设置editor为空 + // important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) try { this.editor.blur(); } catch (e) { @@ -30273,9 +30273,9 @@ BI.Searcher = BI.inherit(BI.Widget, { return this.popupView.getValue(); } else if (o.adapter && o.adapter.getValue) { return o.adapter.getValue(); - } else { - return this.popupView.getValue(); } + return this.popupView.getValue(); + }, populate: function (result, searchResult, keyword) { @@ -30324,7 +30324,7 @@ BI.Switcher = BI.inherit(BI.Widget, { masker: {}, switcherClass: "bi-switcher-popup", hoverClass: "bi-switcher-hover" - }) + }); }, _init: function () { @@ -30394,13 +30394,13 @@ BI.Switcher = BI.inherit(BI.Widget, { self.element[e](function (e) { if (self.isEnabled() && self.switcher.isEnabled()) { self._popupView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_EXPAND); } }, function () { if (self.isEnabled() && self.switcher.isEnabled() && o.toggle) { self._hideView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_COLLAPSE); } }); @@ -30412,10 +30412,10 @@ BI.Switcher = BI.inherit(BI.Widget, { if (self.isEnabled() && self.switcher.isEnabled()) { o.toggle ? self._toggle() : self._popupView(); if (self.isExpanded()) { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_EXPAND); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_COLLAPSE); } } @@ -30424,7 +30424,7 @@ BI.Switcher = BI.inherit(BI.Widget, { } break; } - }) + }); }, _initSwitcher: function () { @@ -30590,8 +30590,8 @@ BI.Tab = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Tab.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-tab", - direction: "top",//top, bottom, left, right, custom - single: false, //是不是单页面 + direction: "top", // top, bottom, left, right, custom + single: false, // 是不是单页面 logic: { dynamic: false }, @@ -30600,7 +30600,7 @@ BI.Tab = BI.inherit(BI.Widget, { cardCreator: function (v) { return BI.createWidget(); } - }) + }); }, render: function () { @@ -30609,7 +30609,7 @@ BI.Tab = BI.inherit(BI.Widget, { this.tab = BI.createWidget(this.options.tab, {type: "bi.button_group"}); this.tab.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); } this.cardMap = {}; this.layout = BI.createWidget({ @@ -30760,7 +30760,7 @@ BI.EL = BI.inherit(BI.Widget, { }); this.ele.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); }, setValue: function (v) { @@ -30775,7 +30775,7 @@ BI.EL = BI.inherit(BI.Widget, { this.ele.populate.apply(this, arguments); } }); -BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and others +BI.shortcut("bi.el", BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE // This is CodeMirror (http://codemirror.net), a code editor @@ -30784,8766 +30784,8544 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . -(function(mod) { +(function (mod) { this.CodeMirror = mod(); -})(function() { - "use strict"; - - // BROWSER SNIFFING - - // Kludges for bugs and behavior differences that can't be feature - // detected are enabled based on userAgent etc sniffing. - - var gecko = /gecko\/\d/i.test(navigator.userAgent); - var ie_upto10 = /MSIE \d/.test(navigator.userAgent); - var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); - var ie = ie_upto10 || ie_11up; - var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); - var webkit = /WebKit\//.test(navigator.userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); - var chrome = /Chrome\//.test(navigator.userAgent); - var presto = /Opera\//.test(navigator.userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); - var phantom = /PhantomJS/.test(navigator.userAgent); - - var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); - // This is woefully incomplete. Suggestions for alternative methods welcome. - var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); - var mac = ios || /Mac/.test(navigator.platform); - var windows = /win/i.test(navigator.platform); - - var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); - if (presto_version) presto_version = Number(presto_version[1]); - if (presto_version && presto_version >= 15) { presto = false; webkit = true; } - // Some browsers use the wrong event properties to signal cmd/ctrl on OS X - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || (ie && ie_version >= 9); - - // Optimize some code when these features are not used. - var sawReadOnlySpans = false, sawCollapsedSpans = false; - - // EDITOR CONSTRUCTOR - - // A CodeMirror instance represents an editor. This is the object - // that user code is usually dealing with. - - function CodeMirror(place, options) { - if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); - - this.options = options = options ? copyObj(options) : {}; - // Determine effective options based on given values and defaults. - copyObj(defaults, options, false); - setGuttersForLineNumbers(options); - - var doc = options.value; - if (typeof doc == "string") doc = new Doc(doc, options.mode); - this.doc = doc; - - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input); - display.wrapper.CodeMirror = this; - updateGutters(this); - themeChanged(this); - if (options.lineWrapping) - this.display.wrapper.className += " CodeMirror-wrap"; - if (options.autofocus && !mobile) display.input.focus(); - initScrollbars(this); - - this.state = { - keyMaps: [], // stores maps added by addKeyMap - overlays: [], // highlighting overlays, as added by addOverlay - modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, // used to disable editing during key handlers when in readOnly mode - pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll - draggingText: false, - highlight: new Delayed(), // stores highlight worker timeout - keySeq: null, // Unfinished key sequence - specialChars: null - }; - - var cm = this; - - // Override magic textarea content restore that IE sometimes does - // on our hidden textarea on reload - if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20); - - registerEventHandlers(this); - ensureGlobalHandlers(); - - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - - if ((options.autofocus && !mobile) || cm.hasFocus()) - setTimeout(bind(onFocus, this), 20); - else - onBlur(this); - - for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) - optionHandlers[opt](this, options[opt], Init); - maybeUpdateLineNumberWidth(this); - if (options.finishInit) options.finishInit(this); - for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); - endOperation(this); - // Suppress optimizelegibility in Webkit, since it breaks text - // measuring on line wrapping boundaries. - if (webkit && options.lineWrapping && - getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") - display.lineDiv.style.textRendering = "auto"; - } - - // DISPLAY CONSTRUCTOR - - // The display handles the DOM integration, both for input reading - // and content drawing. It holds references to DOM nodes and - // display-related state. - - function Display(place, doc, input) { - var d = this; - this.input = input; - - // Covers bottom-right square when both scrollbars are present. - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - // Covers bottom of gutter when coverGutterNextToScrollbar is on - // and h scrollbar is present. - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - // Will contain the actual code, positioned to cover the viewport. - d.lineDiv = elt("div", null, "CodeMirror-code"); - // Elements are added to these to represent selection and cursors. - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - // A visibility: hidden element used to find the size of things. - d.measure = elt("div", null, "CodeMirror-measure"); - // When lines outside of the viewport are measured, they are drawn in this. - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - // Wraps everything that needs to exist inside the vertically-padded coordinate system - d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], - null, "position: relative; outline: none"); - // Moved around its parent to cover visible view. - d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); - // Set to the height of the document, allowing scrolling. - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - // Behavior of elts with overflow: auto and padding is - // inconsistent across browsers. This is used to ensure the - // scrollable area is big enough. - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - // Will contain the gutters, if any. - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - // Actual scrollable element. - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - - // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) - if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } - if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; - - if (place) { - if (place.appendChild) place.appendChild(d.wrapper); - else place(d.wrapper); - } - - // Current rendered range (may be bigger than the view window). - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - // Information about the rendered lines. - d.view = []; - d.renderedView = null; - // Holds info about a single rendered line when it was rendered - // for measurement, while not in view. - d.externalMeasured = null; - // Empty space (in pixels) above the view - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - - // Used to only resize the line number gutter when necessary (when - // the amount of lines crosses a boundary that makes its width change) - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - // Set to true when a non-horizontal-scrolling line widget is - // added. As an optimization, line widget aligning is skipped when - // this is false. - d.alignWidgets = false; - - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - // True when shift is held down. - d.shift = false; - - // Used to track whether anything happened since the context menu - // was opened. - d.selForContextMenu = null; - - d.activeTouch = null; - - input.init(d); - } - - // STATE UPDATES - - // Used to get the editor into a consistent state again when options change. - - function loadMode(cm) { - cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - - function resetModeState(cm) { - cm.doc.iter(function(line) { - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - }); - cm.doc.frontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) regChange(cm); - } - - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; - } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function(){updateScrollbars(cm);}, 100); - } - - // Returns a function that estimates the height of a line, to use as - // first approximation until the line becomes visible (and is thus - // properly measurable). - function estimateHeight(cm) { - var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function(line) { - if (lineIsHidden(cm.doc, line)) return 0; - - var widgetsHeight = 0; - if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { - if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; - } - - if (wrapping) - return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; - else - return widgetsHeight + th; - }; - } - - function estimateLineHeights(cm) { - var doc = cm.doc, est = estimateHeight(cm); - doc.iter(function(line) { - var estHeight = est(line); - if (estHeight != line.height) updateLineHeight(line, estHeight); - }); - } +})(function () { + "use strict"; - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + - cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); - } - - function guttersChanged(cm) { - updateGutters(cm); - regChange(cm); - setTimeout(function(){alignHorizontally(cm);}, 20); - } - - // Rebuild the gutter elements, ensure the margin to the left of the - // code matches their width. - function updateGutters(cm) { - var gutters = cm.display.gutters, specs = cm.options.gutters; - removeChildren(gutters); - for (var i = 0; i < specs.length; ++i) { - var gutterClass = specs[i]; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); - if (gutterClass == "CodeMirror-linenumbers") { - cm.display.lineGutter = gElt; - gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = i ? "" : "none"; - updateGutterSpace(cm); - } - - function updateGutterSpace(cm) { - var width = cm.display.gutters.offsetWidth; - cm.display.sizer.style.marginLeft = width + "px"; - } - - // Compute the character length of a line, taking into account - // collapsed ranges (see markText) that might hide parts, and join - // other lines onto it. - function lineLength(line) { - if (line.height == 0) return 0; - var len = line.text.length, merged, cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found = merged.find(0, true); - len -= cur.text.length - found.from.ch; - cur = found.to.line; - len += cur.text.length - found.to.ch; - } - return len; - } - - // Find the longest line in the document. - function findMaxLine(cm) { - var d = cm.display, doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function(line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - - // Make sure the gutters options contains the element - // "CodeMirror-linenumbers" when the lineNumbers option is true. - function setGuttersForLineNumbers(options) { - var found = indexOf(options.gutters, "CodeMirror-linenumbers"); - if (found == -1 && options.lineNumbers) { - options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); - } else if (found > -1 && !options.lineNumbers) { - options.gutters = options.gutters.slice(0); - options.gutters.splice(found, 1); - } - } - - // SCROLLBARS - - // Prepare DOM reads needed to update the scrollbars. Done in one - // shot to minimize update/measure roundtrips. - function measureForScrollbars(cm) { - var d = cm.display, gutterW = d.gutters.offsetWidth; - var docH = Math.round(cm.doc.height + paddingVert(cm.display)); - return { - clientHeight: d.scroller.clientHeight, - viewHeight: d.wrapper.clientHeight, - scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, - viewWidth: d.wrapper.clientWidth, - barLeft: cm.options.fixedGutter ? gutterW : 0, - docHeight: docH, - scrollHeight: docH + scrollGap(cm) + d.barHeight, - nativeBarWidth: d.nativeBarWidth, - gutterWidth: gutterW - }; - } + // BROWSER SNIFFING + + // Kludges for bugs and behavior differences that can't be feature + // detected are enabled based on userAgent etc sniffing. + + var gecko = /gecko\/\d/i.test(navigator.userAgent); + var ie_upto10 = /MSIE \d/.test(navigator.userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + var ie = ie_upto10 || ie_11up; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); + var webkit = /WebKit\//.test(navigator.userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); + var chrome = /Chrome\//.test(navigator.userAgent); + var presto = /Opera\//.test(navigator.userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); + var phantom = /PhantomJS/.test(navigator.userAgent); + + var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); + var mac = ios || /Mac/.test(navigator.platform); + var windows = /win/i.test(navigator.platform); + + var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) presto_version = Number(presto_version[1]); + if (presto_version && presto_version >= 15) { presto = false; webkit = true; } + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || (ie && ie_version >= 9); + + // Optimize some code when these features are not used. + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + // EDITOR CONSTRUCTOR + + // A CodeMirror instance represents an editor. This is the object + // that user code is usually dealing with. + + function CodeMirror (place, options) { + if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + setGuttersForLineNumbers(options); + + var doc = options.value; + if (typeof doc === "string") doc = new Doc(doc, options.mode); + this.doc = doc; + + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input); + display.wrapper.CodeMirror = this; + updateGutters(this); + themeChanged(this); + if (options.lineWrapping) {this.display.wrapper.className += " CodeMirror-wrap";} + if (options.autofocus && !mobile) display.input.focus(); + initScrollbars(this); + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + }; - function NativeScrollbars(place, scroll, cm) { - this.cm = cm; - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - place(vert); place(horiz); + var cm = this; + + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) setTimeout(function () { cm.display.input.reset(true); }, 20); + + registerEventHandlers(this); + ensureGlobalHandlers(); + + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); + + if ((options.autofocus && !mobile) || cm.hasFocus()) {setTimeout(bind(onFocus, this), 20);} else {onBlur(this);} + + for (var opt in optionHandlers) { + if (optionHandlers.hasOwnProperty(opt)) {optionHandlers[opt](this, options[opt], Init);} + } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) options.finishInit(this); + for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); + endOperation(this); + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") {display.lineDiv.style.textRendering = "auto";} + } + + // DISPLAY CONSTRUCTOR + + // The display handles the DOM integration, both for input reading + // and content drawing. It holds references to DOM nodes and + // display-related state. + + function Display (place, doc, input) { + var d = this; + this.input = input; + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = elt("div", null, "CodeMirror-code"); + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure"); + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none"); + // Moved around its parent to cover visible view. + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; + + if (place) { + if (place.appendChild) place.appendChild(d.wrapper); + else place(d.wrapper); + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + // Information about the rendered lines. + d.view = []; + d.renderedView = null; + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null; + // Empty space (in pixels) above the view + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false; + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + // True when shift is held down. + d.shift = false; + + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null; + + d.activeTouch = null; + + input.init(d); + } + + // STATE UPDATES + + // Used to get the editor into a consistent state again when options change. + + function loadMode (cm) { + cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); + } + + function resetModeState (cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + }); + cm.doc.frontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) regChange(cm); + } + + function wrappingChanged (cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; + } else { + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); + } + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function () {updateScrollbars(cm);}, 100); + } - on(vert, "scroll", function() { - if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); - }); - on(horiz, "scroll", function() { - if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); - }); + // Returns a function that estimates the height of a line, to use as + // first approximation until the line becomes visible (and is thus + // properly measurable). + function estimateHeight (cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function (line) { + if (lineIsHidden(cm.doc, line)) return 0; - this.checkedOverlay = false; - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; - } - - NativeScrollbars.prototype = copyObj({ - update: function(measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - // A bug in IE8 can cause this value to be negative, so guard it. - this.vert.firstChild.style.height = - Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; - } else { - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; - } - - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = - (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; - } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; - } - - if (!this.checkedOverlay && measure.clientHeight > 0) { - if (sWidth == 0) this.overlayHack(); - this.checkedOverlay = true; - } - - return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; - }, - setScrollLeft: function(pos) { - if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; - }, - setScrollTop: function(pos) { - if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; - }, - overlayHack: function() { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.minHeight = this.vert.style.minWidth = w; - var self = this; - var barMouseDown = function(e) { - if (e_target(e) != self.vert && e_target(e) != self.horiz) - operation(self.cm, onMouseDown)(e); - }; - on(this.vert, "mousedown", barMouseDown); - on(this.horiz, "mousedown", barMouseDown); - }, - clear: function() { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - } - }, NativeScrollbars.prototype); - - function NullScrollbars() {} - - NullScrollbars.prototype = copyObj({ - update: function() { return {bottom: 0, right: 0}; }, - setScrollLeft: function() {}, - setScrollTop: function() {}, - clear: function() {} - }, NullScrollbars.prototype); - - CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; - - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) - rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - - cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - // Prevent clicks in the scrollbars from killing focus - on(node, "mousedown", function() { - if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0); - }); - node.setAttribute("cm-not-content", "true"); - }, function(pos, axis) { - if (axis == "horizontal") setScrollLeft(cm, pos); - else setScrollTop(cm, pos); - }, cm); - if (cm.display.scrollbars.addClass) - addClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - - function updateScrollbars(cm, measure) { - if (!measure) measure = measureForScrollbars(cm); - var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; - updateScrollbarsInner(cm, measure); - for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) - updateHeightsInViewport(cm); - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; - } - } - - // Re-synchronize the fake scrollbars with the actual size of the - // content. - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var sizes = d.scrollbars.update(measure); - - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; - - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else d.scrollbarFiller.style.display = ""; - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = sizes.bottom + "px"; - d.gutterFiller.style.width = measure.gutterWidth + "px"; - } else d.gutterFiller.style.display = ""; - } - - // Compute the lines that are visible in a given viewport (defaults - // the the current scroll position). viewport may contain top, - // height, and ensure (see op.scrollToPos) properties. - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - - var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); - // Ensure is a {from: {line, ch}, to: {line, ch}} object, and - // forces those lines into the viewport (if possible). - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; - } - } - return {from: from, to: Math.max(to, from + 1)}; - } - - // LINE NUMBERS - - // Re-align line numbers and gutter marks to compensate for - // horizontal scrolling. - function alignHorizontally(cm) { - var display = cm.display, view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, left = comp + "px"; - for (var i = 0; i < view.length; i++) if (!view[i].hidden) { - if (cm.options.fixedGutter && view[i].gutter) - view[i].gutter.style.left = left; - var align = view[i].alignable; - if (align) for (var j = 0; j < align.length; j++) - align[j].style.left = left; - } - if (cm.options.fixedGutter) - display.gutters.style.left = (comp + gutterW) + "px"; - } - - // Used to ensure that the line number gutter is still the right - // size for the current document size. Returns true when an update - // is needed. - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) return false; - var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], - "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm); - return true; - } - return false; - } - - function lineNumberFor(options, i) { - return String(options.lineNumberFormatter(i + options.firstLineNumber)); - } - - // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, - // but using getBoundingClientRect to get a sub-pixel-accurate - // result. - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; - } - - // DISPLAY DRAWING - - function DisplayUpdate(cm, viewport, force) { - var display = cm.display; - - this.viewport = viewport; - // Store some values that we'll need later (but don't want to force a relayout for) - this.visible = visibleLines(display, cm.doc, viewport); - this.editorIsHidden = !display.wrapper.offsetWidth; - this.wrapperHeight = display.wrapper.clientHeight; - this.wrapperWidth = display.wrapper.clientWidth; - this.oldDisplayWidth = displayWidth(cm); - this.force = force; - this.dims = getDimensions(cm); - this.events = []; - } - - DisplayUpdate.prototype.signal = function(emitter, type) { - if (hasHandler(emitter, type)) - this.events.push(arguments); - }; - DisplayUpdate.prototype.finish = function() { - for (var i = 0; i < this.events.length; i++) - signal.apply(null, this.events[i]); - }; - - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!display.scrollbarsClipped && display.scroller.offsetWidth) { - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; - display.heightForcer.style.height = scrollGap(cm) + "px"; - display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; - display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; - display.scrollbarsClipped = true; - } - } - - // Does the actual updating of the line display. Bails out - // (returning false) when there is nothing to be done and forced is - // false. - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, doc = cm.doc; - - if (update.editorIsHidden) { - resetView(cm); - return false; - } - - // Bail out if the visible area is already rendered and nothing changed. - if (!update.force && - update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && - display.renderedView == display.view && countDirtyView(cm) == 0) - return false; + var widgetsHeight = 0; + if (line.widgets) { + for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; + } + } - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); + if (wrapping) {return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;} + return widgetsHeight + th; + }; } - // Compute a suitable new viewport (from & to) - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); - if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); + function estimateLineHeights (cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function (line) { + var estHeight = est(line); + if (estHeight != line.height) updateLineHeight(line, estHeight); + }); } - var different = from != display.viewFrom || to != display.viewTo || - display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - // Position the mover div to align with the current scroll position - cm.display.mover.style.top = display.viewOffset + "px"; - - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) - return false; - - // For big changes, we hide the enclosing element during the - // update, since that speeds up the operations on most browsers. - var focused = activeElt(); - if (toUpdate > 4) display.lineDiv.style.display = "none"; - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) display.lineDiv.style.display = ""; - display.renderedView = display.view; - // There might have been a widget with a focused element that got - // hidden or updated, if so re-focus it. - if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); - - // Prevent selection and cursors from interfering with the scroll - // width and height. - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = 0; - - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - - display.updateLineNumbers = null; - - return true; - } - - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - // Clip forced viewport to actual scrollable area. - if (viewport && viewport.top != null) - viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; - // Updated line heights might result in the drawn area not - // actually covering the viewport. Keep looping until it does. - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) - break; - } - if (!updateDisplayIfNeeded(cm, update)) break; - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - setDocumentHeight(cm, barMeasure); - updateScrollbars(cm, barMeasure); - } - - update.signal(cm, "update", cm); - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); - cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; - } - } - - function updateDisplaySimple(cm, viewport) { - var update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - setDocumentHeight(cm, barMeasure); - updateScrollbars(cm, barMeasure); - update.finish(); - } - } - - function setDocumentHeight(cm, measure) { - cm.display.sizer.style.minHeight = measure.docHeight + "px"; - var total = measure.docHeight + cm.display.barHeight; - cm.display.heightForcer.style.top = total + "px"; - cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px"; - } - - // Read the actual heights of the rendered lines, and update their - // stored heights to match. - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - for (var i = 0; i < display.view.length; i++) { - var cur = display.view[i], height; - if (cur.hidden) continue; - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; - } - var diff = cur.line.height - height; - if (height < 2) height = textHeight(display); - if (diff > .001 || diff < -.001) { - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) for (var j = 0; j < cur.rest.length; j++) - updateWidgetHeight(cur.rest[j]); - } - } - } - - // Read and store the height of line widgets associated with the - // given line. - function updateWidgetHeight(line) { - if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) - line.widgets[i].height = line.widgets[i].node.offsetHeight; - } - - // Do a bulk-read of the DOM positions and sizes needed to draw the - // view, so that we don't interleave reading and writing to the DOM. - function getDimensions(cm) { - var d = cm.display, left = {}, width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { - left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; - width[cm.options.gutters[i]] = n.clientWidth; - } - return {fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth}; - } - - // Sync the actual display DOM structure with display.view, removing - // nodes for lines that are no longer in view, and creating the ones - // that are not there yet, and updating the ones that are out of - // date. - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, cur = container.firstChild; - - function rm(node) { - var next = node.nextSibling; - // Works around a throw-scroll bug in OS X Webkit - if (webkit && mac && cm.display.currentWheelTarget == node) - node.style.display = "none"; - else - node.parentNode.removeChild(node); - return next; - } - - var view = display.view, lineN = display.viewFrom; - // Loop over the elements in the view, syncing cur (the DOM nodes - // in display.lineDiv) with the view as we go. - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (lineView.hidden) { - } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { // Already drawn - while (cur != lineView.node) cur = rm(cur); - var updateNumber = lineNumbers && updateNumbersFrom != null && - updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; - updateLineForChanges(cm, lineView, lineN, dims); - } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); - } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) cur = rm(cur); - } - - // When an aspect of a line changes, a string is added to - // lineView.changes. This updates the relevant part of the line's - // DOM structure. - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") updateLineText(cm, lineView); - else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); - else if (type == "class") updateLineClasses(lineView); - else if (type == "widget") updateLineWidgets(cm, lineView, dims); - } - lineView.changes = null; - } - - // Lines with gutter elements, widgets or a background class need to - // be wrapped, and have the extra elements added to the wrapper div - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) - lineView.text.parentNode.replaceChild(lineView.node, lineView.text); - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) lineView.node.style.zIndex = 2; - } - return lineView.node; - } - - function updateLineBackground(lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) cls += " CodeMirror-linebackground"; - if (lineView.background) { - if (cls) lineView.background.className = cls; - else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - } - } - - // Wrapper around buildLineContent which will reuse the structure - // in display.externalMeasured when possible. - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built; - } - return buildLineContent(cm, lineView); - } - - // Redraw the line's text. Interacts with the background and text - // classes because the mode may output tokens that influence these - // classes. - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) lineView.node = built.pre; - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - - function updateLineClasses(lineView) { - updateLineBackground(lineView); - if (lineView.line.wrapClass) - ensureLineWrapped(lineView).className = lineView.line.wrapClass; - else if (lineView.node != lineView.text) - lineView.node.className = ""; - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + - (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + - "px; width: " + dims.gutterTotalWidth + "px"); - cm.display.input.setUneditable(gutterWrap); - wrap.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) - gutterWrap.className += " " + lineView.line.gutterClass; - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) - lineView.lineNumber = gutterWrap.appendChild( - elt("div", lineNumberFor(cm.options, lineN), - "CodeMirror-linenumber CodeMirror-gutter-elt", - "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " - + cm.display.lineNumInnerWidth + "px")); - if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { - var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; - if (found) - gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + - dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); - } - } - } - - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) lineView.alignable = null; - for (var node = lineView.node.firstChild, next; node; node = next) { - var next = node.nextSibling; - if (node.className == "CodeMirror-linewidget") - lineView.node.removeChild(node); - } - insertLineWidgets(cm, lineView, dims); - } - - // Build a line's DOM representation from scratch - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) lineView.bgClass = built.bgClass; - if (built.textClass) lineView.textClass = built.textClass; - - updateLineClasses(lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node; - } - - // A lineView may contain multiple logical lines (when merged by - // collapsed spans). The widgets for all of them need to be drawn. - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) - insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); - } - - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) return; - var wrap = ensureLineWrapped(lineView); - for (var i = 0, ws = line.widgets; i < ws.length; ++i) { - var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); - if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) - wrap.insertBefore(node, lineView.gutter || lineView.text); - else - wrap.appendChild(node); - signalLater(widget, "redraw"); - } - } - - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; - } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; - } - } - - // POSITION OBJECT - - // A Pos instance represents a position within the text. - var Pos = CodeMirror.Pos = function(line, ch) { - if (!(this instanceof Pos)) return new Pos(line, ch); - this.line = line; this.ch = ch; - }; - - // Compare two positions, return 0 if they are the same, a negative - // number when a is less, and a positive number otherwise. - var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; - - function copyPos(x) {return Pos(x.line, x.ch);} - function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } - function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } - - // INPUT HANDLING - - function ensureFocus(cm) { - if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } - } - - function isReadOnly(cm) { - return cm.options.readOnly || cm.doc.cantEdit; - } - - // This will be set to an array of strings when copying, so that, - // when pasting, we know what kind of selections the copied text - // was made out of. - var lastCopied = null; - - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) sel = doc.sel; - - var paste = cm.state.pasteIncoming || origin == "paste"; - var textLines = splitLines(inserted), multiPaste = null; - // When pasing N lines into N selections, insert one line per selection - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.join("\n") == inserted) - multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines); - else if (textLines.length == sel.ranges.length) - multiPaste = map(textLines, function(l) { return [l]; }); - } - - // Normal behavior is to insert the new text into every selection - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - var from = range.from(), to = range.to(); - if (range.empty()) { - if (deleted && deleted > 0) // Handle deletion - from = Pos(from.line, from.ch - deleted); - else if (cm.state.overwrite && !paste) // Handle overwrite - to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); - } - var updateInput = cm.curOp.updateInput; - var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); - } - if (inserted && !paste) - triggerElectric(cm, inserted); - - ensureCursorVisible(cm); - cm.curOp.updateInput = updateInput; - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = false; - } - - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); - if (pasted) { - e.preventDefault(); - runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); - return true; - } - } - - function triggerElectric(cm, inserted) { - // When an 'electric' character is inserted, immediately trigger a reindent - if (!cm.options.electricChars || !cm.options.smartIndent) return; - var sel = cm.doc.sel; - - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; - var mode = cm.getModeAt(range.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) - if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range.head.line, "smart"); - break; - } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) - indented = indentLine(cm, range.head.line, "smart"); - } - if (indented) signalLater(cm, "electricInput", cm, range.head.line); - } - } - - function copyableRanges(cm) { - var text = [], ranges = []; - for (var i = 0; i < cm.doc.sel.ranges.length; i++) { - var line = cm.doc.sel.ranges[i].head.line; - var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return {text: text, ranges: ranges}; - } - - function disableBrowserMagic(field) { - field.setAttribute("autocorrect", "off"); - field.setAttribute("autocapitalize", "off"); - field.setAttribute("spellcheck", "false"); - } - - // TEXTAREA INPUT STYLE - - function TextareaInput(cm) { - this.cm = cm; - // See input.poll and input.reset - this.prevInput = ""; - - // Flag that indicates whether we expect input to appear real soon - // now (after some event like 'keypress' or 'input') and are - // polling intensively. - this.pollingFast = false; - // Self-resetting timeout for the poller - this.polling = new Delayed(); - // Tracks when input.reset has punted to just putting a short - // string into the textarea instead of the full selection. - this.inaccurateSelection = false; - // Used to work around IE issue with selection being forgotten when focus moves away from textarea - this.hasSelection = false; - this.composing = null; - }; - - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The textarea is kept positioned near the cursor to prevent the - // fact that it'll be scrolled into view on input from scrolling - // our fake cursor out of view. On webkit, when wrap=off, paste is - // very slow. So make the area wide instead. - if (webkit) te.style.width = "1000px"; - else te.setAttribute("wrap", "off"); - // If border: 0; -- iOS fails to open keyboard (issue #1287) - if (ios) te.style.border = "1px solid black"; - disableBrowserMagic(te); - return div; - } - - TextareaInput.prototype = copyObj({ - init: function(display) { - var input = this, cm = this.cm; - - // Wraps and hides input textarea - var div = this.wrapper = hiddenTextarea(); - // The semihidden textarea that is focused when the editor is - // focused, and receives input. - var te = this.textarea = div.firstChild; - display.wrapper.insertBefore(div, display.wrapper.firstChild); - - // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) - if (ios) te.style.width = "0px"; - - on(te, "input", function() { - if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; - input.poll(); - }); - - on(te, "paste", function(e) { - if (handlePaste(e, cm)) return true; - - cm.state.pasteIncoming = true; - input.fastPoll(); - }); - - function prepareCopyCut(e) { - if (cm.somethingSelected()) { - lastCopied = cm.getSelections(); - if (input.inaccurateSelection) { - input.prevInput = ""; - input.inaccurateSelection = false; - te.value = lastCopied.join("\n"); - selectInput(te); - } - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - lastCopied = ranges.text; - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } - } - if (e.type == "cut") cm.state.cutIncoming = true; - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - - on(display.scroller, "paste", function(e) { - if (eventInWidget(display, e)) return; - cm.state.pasteIncoming = true; - input.focus(); - }); - - // Prevent normal selection in the editor (we handle our own) - on(display.lineSpace, "selectstart", function(e) { - if (!eventInWidget(display, e)) e_preventDefault(e); - }); - - on(te, "compositionstart", function() { - var start = cm.getCursor("from"); - input.composing = { - start: start, - range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) - }; - }); - on(te, "compositionend", function() { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }, - - prepareSelection: function() { - // Redraw the selection and/or cursor - var cm = this.cm, display = cm.display, doc = cm.doc; - var result = prepareSelection(cm); - - // Move the hidden textarea near the cursor to prevent scrolling artifacts - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, - headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, - headPos.left + lineOff.left - wrapOff.left)); - } - - return result; - }, - - showSelection: function(drawn) { - var cm = this.cm, display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } - }, - - // Reset the input to correspond to the selection (or to be empty, - // when not typing and nothing is selected) - reset: function(typing) { - if (this.contextMenuPending) return; - var minimal, selected, cm = this.cm, doc = cm.doc; - if (cm.somethingSelected()) { - this.prevInput = ""; - var range = doc.sel.primary(); - minimal = hasCopyEvent && - (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); - var content = minimal ? "-" : selected || cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) selectInput(this.textarea); - if (ie && ie_version >= 9) this.hasSelection = content; - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) this.hasSelection = null; - } - this.inaccurateSelection = minimal; - }, - - getField: function() { return this.textarea; }, - - supportsTouch: function() { return false; }, - - focus: function() { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { this.textarea.focus(); } - catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM - } - }, - - blur: function() { this.textarea.blur(); }, - - resetPosition: function() { - this.wrapper.style.top = this.wrapper.style.left = 0; - }, - - receivedFocus: function() { this.slowPoll(); }, - - // Poll for input changes, using the normal rate of polling. This - // runs as long as the editor is focused. - slowPoll: function() { - var input = this; - if (input.pollingFast) return; - input.polling.set(this.cm.options.pollInterval, function() { - input.poll(); - if (input.cm.state.focused) input.slowPoll(); - }); - }, - - // When an event has just come in that is likely to add or change - // something in the input textarea, we poll faster, to ensure that - // the change appears on the screen quickly. - fastPoll: function() { - var missed = false, input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) {missed = true; input.polling.set(60, p);} - else {input.pollingFast = false; input.slowPoll();} - } - input.polling.set(20, p); - }, - - // Read input from the textarea, and update the document to match. - // When something is selected, it is present in the textarea, and - // selected (unless it is huge, in which case a placeholder is - // used). When nothing is selected, the cursor sits after previously - // seen text (can be empty), which is stored in prevInput (we must - // not reset the textarea when typing, because that breaks IME). - poll: function() { - var cm = this.cm, input = this.textarea, prevInput = this.prevInput; - // Since this is called a *lot*, try to bail out as cheaply as - // possible when it is clear that nothing happened. hasSelection - // will be the case when there is a lot of text in the textarea, - // in which case reading its value would be expensive. - if (this.contextMenuPending || !cm.state.focused || - (hasSelection(input) && !prevInput) || - isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq) - return false; - - var text = input.value; - // If nothing changed, bail. - if (text == prevInput && !cm.somethingSelected()) return false; - // Work around nonsensical selection resetting in IE9/10, and - // inexplicable appearance of private area unicode characters on - // some key combos in Mac (#2689). - if (ie && ie_version >= 9 && this.hasSelection === text || - mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false; - } + function themeChanged (cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 0x200b && !prevInput) prevInput = "\u200b"; - if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } - } - // Find the part of the input that is actually new - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; + function guttersChanged (cm) { + updateGutters(cm); + regChange(cm); + setTimeout(function () {alignHorizontally(cm);}, 20); + } - var self = this; - runInOp(cm, function() { - applyTextInput(cm, text.slice(same), prevInput.length - same, - null, self.composing ? "*compose" : null); + // Rebuild the gutter elements, ensure the margin to the left of the + // code matches their width. + function updateGutters (cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters; + removeChildren(gutters); + for (var i = 0; i < specs.length; ++i) { + var gutterClass = specs[i]; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt; + gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = i ? "" : "none"; + updateGutterSpace(cm); + } - // Don't leave long text in the textarea, since it makes further polling slow - if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; - else self.prevInput = text; + function updateGutterSpace (cm) { + var width = cm.display.gutters.offsetWidth; + cm.display.sizer.style.marginLeft = width + "px"; + } - if (self.composing) { - self.composing.range.clear(); - self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), - {className: "CodeMirror-composing"}); + // Compute the character length of a line, taking into account + // collapsed ranges (see markText) that might hide parts, and join + // other lines onto it. + function lineLength (line) { + if (line.height == 0) return 0; + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; } - }); - return true; - }, - - ensurePolled: function() { - if (this.pollingFast && this.poll()) this.pollingFast = false; - }, + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found = merged.find(0, true); + len -= cur.text.length - found.from.ch; + cur = found.to.line; + len += cur.text.length - found.to.ch; + } + return len; + } - onKeyPress: function() { - if (ie && ie_version >= 9) this.hasSelection = null; - this.fastPoll(); - }, + // Find the longest line in the document. + function findMaxLine (cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function (line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } - onContextMenu: function(e) { - var input = this, cm = input.cm, display = cm.display, te = input.textarea; - var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; - if (!pos || presto) return; // Opera is difficult. + // Make sure the gutters options contains the element + // "CodeMirror-linenumbers" when the lineNumbers option is true. + function setGuttersForLineNumbers (options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers"); + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0); + options.gutters.splice(found, 1); + } + } - // Reset the current text selection only if the click is done outside of the selection - // and 'resetSelectionOnContextMenu' option is true. - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) - operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); + // SCROLLBARS - var oldCSS = te.style.cssText; - input.wrapper.style.position = "absolute"; - te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + - "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + - (ie ? "rgba(255, 255, 255, .05)" : "transparent") + - "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) - display.input.focus(); - if (webkit) window.scrollTo(null, oldScrollY); - display.input.reset(); - // Adds "Select all" to context menu in FF - if (!cm.somethingSelected()) te.value = input.prevInput = " "; - input.contextMenuPending = true; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - - // Select-all will be greyed out if there's nothing to select, so - // this adds a zero-width space so that we can later check whether - // it got selected. - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "\u200b" + (selected ? te.value : ""); - te.value = "\u21da"; // Used to catch context-menu undo - te.value = extval; - input.prevInput = selected ? "" : "\u200b"; - te.selectionStart = 1; te.selectionEnd = extval.length; - // Re-set this, in case some other handler touched the - // selection in the meantime. - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - input.contextMenuPending = false; - input.wrapper.style.position = "relative"; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); - - // Try to detect the user choosing select-all - if (te.selectionStart != null) { - if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); - var i = 0, poll = function() { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && - te.selectionEnd > 0 && input.prevInput == "\u200b") - operation(cm, commands.selectAll)(cm); - else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); - else display.input.reset(); - }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } - - if (ie && ie_version >= 9) prepareSelectAllHack(); - if (captureRightClick) { - e_stop(e); - var mouseup = function() { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); + // Prepare DOM reads needed to update the scrollbars. Done in one + // shot to minimize update/measure roundtrips. + function measureForScrollbars (cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW }; - on(window, "mouseup", mouseup); - } else { - setTimeout(rehide, 50); - } - }, - - setUneditable: nothing, - - needsContentAttribute: false - }, TextareaInput.prototype); - - // CONTENTEDITABLE INPUT STYLE - - function ContentEditableInput(cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.gracePeriod = false; - } - - ContentEditableInput.prototype = copyObj({ - init: function(display) { - var input = this, cm = input.cm; - var div = input.div = display.lineDiv; - div.contentEditable = "true"; - disableBrowserMagic(div); - - on(div, "paste", function(e) { handlePaste(e, cm); }) - - on(div, "compositionstart", function(e) { - var data = e.data; - input.composing = {sel: cm.doc.sel, data: data, startData: data}; - if (!data) return; - var prim = cm.doc.sel.primary(); - var line = cm.getLine(prim.head.line); - var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); - if (found > -1 && found <= prim.head.ch) - input.composing.sel = simpleSelection(Pos(prim.head.line, found), - Pos(prim.head.line, found + data.length)); - }); - on(div, "compositionupdate", function(e) { - input.composing.data = e.data; - }); - on(div, "compositionend", function(e) { - var ours = input.composing; - if (!ours) return; - if (e.data != ours.startData && !/\u200b/.test(e.data)) - ours.data = e.data; - // Need a small delay to prevent other code (input event, - // selection polling) from doing damage when fired right after - // compositionend. - setTimeout(function() { - if (!ours.handled) - input.applyComposition(ours); - if (input.composing == ours) - input.composing = null; - }, 50); - }); - - on(div, "touchstart", function() { - input.forceCompositionEnd(); - }); - - on(div, "input", function() { - if (input.composing) return; - if (!input.pollContent()) - runInOp(input.cm, function() {regChange(cm);}); - }); - - function onCopyCut(e) { - if (cm.somethingSelected()) { - lastCopied = cm.getSelections(); - if (e.type == "cut") cm.replaceSelection("", null, "cut"); - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - lastCopied = ranges.text; - if (e.type == "cut") { - cm.operation(function() { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); - }); - } - } - // iOS exposes the clipboard API, but seems to discard content inserted into it - if (e.clipboardData && !ios) { - e.preventDefault(); - e.clipboardData.clearData(); - e.clipboardData.setData("text/plain", lastCopied.join("\n")); - } else { - // Old-fashioned briefly-focus-a-textarea hack - var kludge = hiddenTextarea(), te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.join("\n"); - var hadFocus = document.activeElement; - selectInput(te); - setTimeout(function() { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - }, 50); - } - } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }, - - prepareSelection: function() { - var result = prepareSelection(this.cm, false); - result.focus = this.cm.state.focused; - return result; - }, - - showSelection: function(info) { - if (!info || !this.cm.display.view.length) return; - if (info.focus) this.showPrimarySelection(); - this.showMultipleSelections(info); - }, - - showPrimarySelection: function() { - var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); - var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && - cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && - cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) - return; - - var start = posToDOM(this.cm, prim.from()); - var end = posToDOM(this.cm, prim.to()); - if (!start && !end) return; - - var view = this.cm.display.view; - var old = sel.rangeCount && sel.getRangeAt(0); - if (!start) { - start = {node: view[0].measure.map[2], offset: 0}; - } else if (!end) { // FIXME dangerously hacky - var measure = view[view.length - 1].measure; - var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; - } - - try { var rng = range(start.node, start.offset, end.offset, end.node); } - catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible - if (rng) { - sel.removeAllRanges(); - sel.addRange(rng); - if (old && sel.anchorNode == null) sel.addRange(old); - else if (gecko) this.startGracePeriod(); - } - this.rememberSelection(); - }, + } - startGracePeriod: function() { - var input = this; - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function() { - input.gracePeriod = false; - if (input.selectionChanged()) - input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); - }, 20); - }, + function NativeScrollbars (place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + place(vert); place(horiz); - showMultipleSelections: function(info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); - }, + on(vert, "scroll", function () { + if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); + }); + on(horiz, "scroll", function () { + if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); + }); - rememberSelection: function() { - var sel = window.getSelection(); - this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; - }, + this.checkedOverlay = false; + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; + } - selectionInEditor: function() { - var sel = window.getSelection(); - if (!sel.rangeCount) return false; - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node); - }, + NativeScrollbars.prototype = copyObj({ + update: function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; - focus: function() { - if (this.cm.options.readOnly != "nocursor") this.div.focus(); - }, - blur: function() { this.div.blur(); }, - getField: function() { return this.div; }, + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } - supportsTouch: function() { return true; }, + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } - receivedFocus: function() { - var input = this; - if (this.selectionInEditor()) - this.pollSelection(); - else - runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); + if (!this.checkedOverlay && measure.clientHeight > 0) { + if (sWidth == 0) this.overlayHack(); + this.checkedOverlay = true; + } - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; + }, + setScrollLeft: function (pos) { + if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; + }, + setScrollTop: function (pos) { + if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; + }, + overlayHack: function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.minHeight = this.vert.style.minWidth = w; + var self = this; + var barMouseDown = function (e) { + if (e_target(e) != self.vert && e_target(e) != self.horiz) {operation(self.cm, onMouseDown)(e);} + }; + on(this.vert, "mousedown", barMouseDown); + on(this.horiz, "mousedown", barMouseDown); + }, + clear: function () { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); } - } - this.polling.set(this.cm.options.pollInterval, poll); - }, - - selectionChanged: function() { - var sel = window.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || - sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; - }, - - pollSelection: function() { - if (!this.composing && !this.gracePeriod && this.selectionChanged()) { - var sel = window.getSelection(), cm = this.cm; - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) runInOp(cm, function() { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; - }); - } - }, - - pollContent: function() { - var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); - var from = sel.from(), to = sel.to(); - if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; - - var fromIndex; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - var fromLine = lineNo(display.view[0].line); - var fromNode = display.view[0].node; - } else { - var fromLine = lineNo(display.view[fromIndex].line); - var fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - if (toIndex == display.view.length - 1) { - var toLine = display.viewTo - 1; - var toNode = display.lineDiv.lastChild; - } else { - var toLine = lineNo(display.view[toIndex + 1].line) - 1; - var toNode = display.view[toIndex + 1].node.previousSibling; - } - - var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } - else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } - else break; - } - - var cutFront = 0, cutEnd = 0; - var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) - ++cutFront; - var newBot = lst(newText), oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), - oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) - ++cutEnd; - - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); - newText[0] = newText[0].slice(cutFront); - - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true; - } - }, - - ensurePolled: function() { - this.forceCompositionEnd(); - }, - reset: function() { - this.forceCompositionEnd(); - }, - forceCompositionEnd: function() { - if (!this.composing || this.composing.handled) return; - this.applyComposition(this.composing); - this.composing.handled = true; - this.div.blur(); - this.div.focus(); - }, - applyComposition: function(composing) { - if (composing.data && composing.data != composing.startData) - operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); - }, - - setUneditable: function(node) { - node.setAttribute("contenteditable", "false"); - }, + }, NativeScrollbars.prototype); - onKeyPress: function(e) { - e.preventDefault(); - operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); - }, + function NullScrollbars () {} - onContextMenu: nothing, - resetPosition: nothing, + NullScrollbars.prototype = copyObj({ + update: function () { return {bottom: 0, right: 0}; }, + setScrollLeft: function () {}, + setScrollTop: function () {}, + clear: function () {} + }, NullScrollbars.prototype); - needsContentAttribute: true - }, ContentEditableInput.prototype); + CodeMirror.scrollbarModel = {native: NativeScrollbars, null: NullScrollbars}; - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) return null; - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); + function initScrollbars (cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) {rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);} + } - var order = getOrder(line), side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; + cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) setTimeout(function () { cm.display.input.focus(); }, 0); + }); + node.setAttribute("cm-not-content", "true"); + }, function (pos, axis) { + if (axis == "horizontal") setScrollLeft(cm, pos); + else setScrollTop(cm, pos); + }, cm); + if (cm.display.scrollbars.addClass) {addClass(cm.display.wrapper, cm.display.scrollbars.addClass);} + } + + function updateScrollbars (cm, measure) { + if (!measure) measure = measureForScrollbars(cm); + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) {updateHeightsInViewport(cm);} + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; + } + } + + // Re-synchronize the fake scrollbars with the actual size of the + // content. + function updateScrollbarsInner (cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else d.scrollbarFiller.style.display = ""; + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else d.gutterFiller.style.display = ""; + } + + // Compute the lines that are visible in a given viewport (defaults + // the the current scroll position). viewport may contain top, + // height, and ensure (see op.scrollToPos) properties. + function visibleLines (display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return {from: from, to: Math.max(to, from + 1)}; + } + + // LINE NUMBERS + + // Re-align line numbers and gutter marks to compensate for + // horizontal scrolling. + function alignHorizontally (cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; + for (var i = 0; i < view.length; i++) { + if (!view[i].hidden) { + if (cm.options.fixedGutter && view[i].gutter) {view[i].gutter.style.left = left;} + var align = view[i].alignable; + if (align) { + for (var j = 0; j < align.length; j++) {align[j].style.left = left;} + } + } + } + if (cm.options.fixedGutter) {display.gutters.style.left = (comp + gutterW) + "px";} + } + + // Used to ensure that the line number gutter is still the right + // size for the current document size. Returns true when an update + // is needed. + function maybeUpdateLineNumberWidth (cm) { + if (!cm.options.lineNumbers) return false; + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm); + return true; + } + return false; } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result; - } - function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } + function lineNumberFor (options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)); + } - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); - node = null; offset = 0; - } else { - for (lineNode = node;; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) return null; - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; - } - } - for (var i = 0; i < cm.display.view.length; i++) { - var lineView = cm.display.view[i]; - if (lineView.node == lineNode) - return locateNodeInLineView(lineView, node, offset); - } - } - - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, bad = false; - if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad); - } - } - - var textNode = node.nodeType == 3 ? node : null, topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) offset = textNode.nodeValue.length; - } - while (topNode.parentNode != wrapper) topNode = topNode.parentNode; - var measure = lineView.measure, maps = measure.maps; - - function find(textNode, topNode, offset) { - for (var i = -1; i < (maps ? maps.length : 0); i++) { - var map = i < 0 ? measure.map : maps[i]; - for (var j = 0; j < map.length; j += 3) { - var curNode = map[j + 2]; - if (curNode == textNode || curNode == topNode) { - var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); - var ch = map[j] + offset; - if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; - return Pos(line, ch); - } - } - } - } - var found = find(textNode, topNode, offset); - if (found) return badPos(found, bad); - - // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) - return badPos(Pos(found.line, found.ch - dist), bad); - else - dist += after.textContent.length; - } - for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) - return badPos(Pos(found.line, found.ch + dist), bad); - else - dist += after.textContent.length; - } - } - - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", closing = false; - function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText != null) { - if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); - text += cmText; - return; - } - var markerID = node.getAttribute("cm-marker"), range; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range = found[0].find())) - text += getBetween(cm.doc, range.from, range.to).join("\n"); - return; - } - if (node.getAttribute("contenteditable") == "false") return; - for (var i = 0; i < node.childNodes.length; i++) - walk(node.childNodes[i]); - if (/^(pre|div|p)$/i.test(node.nodeName)) - closing = true; - } else if (node.nodeType == 3) { - var val = node.nodeValue; - if (!val) return; - if (closing) { - text += "\n"; - closing = false; - } - text += val; - } - } - for (;;) { - walk(from); - if (from == to) break; - from = from.nextSibling; - } - return text; - } - - CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; - - // SELECTION / CURSOR - - // Selection objects are immutable. A new one is created every time - // the selection changes. A selection is one or more non-overlapping - // (and non-touching) ranges, sorted, and an integer that indicates - // which one is the primary selection (the one that's scrolled into - // view, that getCursor returns, etc). - function Selection(ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; - } - - Selection.prototype = { - primary: function() { return this.ranges[this.primIndex]; }, - equals: function(other) { - if (other == this) return true; - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; - for (var i = 0; i < this.ranges.length; i++) { - var here = this.ranges[i], there = other.ranges[i]; - if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; - } - return true; - }, - deepCopy: function() { - for (var out = [], i = 0; i < this.ranges.length; i++) - out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); - return new Selection(out, this.primIndex); - }, - somethingSelected: function() { - for (var i = 0; i < this.ranges.length; i++) - if (!this.ranges[i].empty()) return true; - return false; - }, - contains: function(pos, end) { - if (!end) end = pos; - for (var i = 0; i < this.ranges.length; i++) { - var range = this.ranges[i]; - if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) - return i; - } - return -1; - } - }; - - function Range(anchor, head) { - this.anchor = anchor; this.head = head; - } - - Range.prototype = { - from: function() { return minPos(this.anchor, this.head); }, - to: function() { return maxPos(this.anchor, this.head); }, - empty: function() { - return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; - } - }; - - // Take an unsorted, potentially overlapping set of ranges, and - // build a selection out of it. 'Consumes' ranges array (modifying - // it). - function normalizeSelection(ranges, primIndex) { - var prim = ranges[primIndex]; - ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); - primIndex = indexOf(ranges, prim); - for (var i = 1; i < ranges.length; i++) { - var cur = ranges[i], prev = ranges[i - 1]; - if (cmp(prev.to(), cur.from()) >= 0) { - var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i <= primIndex) --primIndex; - ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); - } - } - return new Selection(ranges, primIndex); - } - - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0); - } - - // Most of the external API clips given positions to make sure they - // actually exist within the document. - function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} - function clipPos(doc, pos) { - if (pos.line < doc.first) return Pos(doc.first, 0); - var last = doc.first + doc.size - 1; - if (pos.line > last) return Pos(last, getLine(doc, last).text.length); - return clipToLen(pos, getLine(doc, pos.line).text.length); - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) return Pos(pos.line, linelen); - else if (ch < 0) return Pos(pos.line, 0); - else return pos; - } - function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} - function clipPosArray(doc, array) { - for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); - return out; - } - - // SELECTION UPDATES - - // The 'scroll' parameter given to many of these indicated whether - // the new cursor position should be scrolled into view after - // modifying the selection. - - // If shift is held or the extend flag is set, extends a range to - // include a given position (and optionally a second position). - // Otherwise, simply returns the range between the given positions. - // Used for cursor motion and such. - function extendRange(doc, range, head, other) { - if (doc.cm && doc.cm.display.shift || doc.extend) { - var anchor = range.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != (cmp(other, anchor) < 0)) { - anchor = head; - head = other; - } else if (posBefore != (cmp(head, other) < 0)) { - head = other; - } - } - return new Range(anchor, head); - } else { - return new Range(other || head, head); - } - } - - // Extend the primary selection range, discard the rest. - function extendSelection(doc, head, other, options) { - setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); - } - - // Extend all selections (pos is an array of selections with length - // equal the number of selections) - function extendSelections(doc, heads, options) { - for (var out = [], i = 0; i < doc.sel.ranges.length; i++) - out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); - var newSel = normalizeSelection(out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - - // Updates a single range in the selection. - function replaceOneSelection(doc, i, range, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i] = range; - setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); - } - - // Reset the selection to a single range. - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - - // Give beforeSelectionChange handlers a change to influence a - // selection update. - function filterSelectionChange(doc, sel) { - var obj = { - ranges: sel.ranges, - update: function(ranges) { - this.ranges = []; - for (var i = 0; i < ranges.length; i++) - this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), - clipPos(doc, ranges[i].head)); - } - }; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); - if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); - else return sel; - } - - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); - } else { - setSelection(doc, sel, options); + // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, + // but using getBoundingClientRect to get a sub-pixel-accurate + // result. + function compensateForHScroll (display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; } - } - // Set a new selection. - function setSelection(doc, sel, options) { - setSelectionNoUndo(doc, sel, options); - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); - } + // DISPLAY DRAWING - function setSelectionNoUndo(doc, sel, options) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) - sel = filterSelectionChange(doc, sel); + function DisplayUpdate (cm, viewport, force) { + var display = cm.display; - var bias = options && options.bias || - (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); - - if (!(options && options.scroll === false) && doc.cm) - ensureCursorVisible(doc.cm); - } - - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) return; - - doc.sel = sel; - - if (doc.cm) { - doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - - // Verify that the selection does not partially select any atomic - // marked ranges. - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); - } - - // Return a selection that does not partially select any atomic - // ranges. - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range.head, bias, mayClear); - if (out || newAnchor != range.anchor || newHead != range.head) { - if (!out) out = sel.ranges.slice(0, i); - out[i] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(out, sel.primIndex) : sel; - } - - // Ensure a given position is not inside an atomic range. - function skipAtomic(doc, pos, bias, mayClear) { - var flipped = false, curPos = pos; - var dir = bias || 1; - doc.cantEdit = false; - search: for (;;) { - var line = getLine(doc, curPos.line); - if (line.markedSpans) { - for (var i = 0; i < line.markedSpans.length; ++i) { - var sp = line.markedSpans[i], m = sp.marker; - if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && - (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) break; - else {--i; continue;} - } - } - if (!m.atomic) continue; - var newPos = m.find(dir < 0 ? -1 : 1); - if (cmp(newPos, curPos) == 0) { - newPos.ch += dir; - if (newPos.ch < 0) { - if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); - else newPos = null; - } else if (newPos.ch > line.text.length) { - if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); - else newPos = null; - } - if (!newPos) { - if (flipped) { - // Driven in a corner -- no valid cursor position found at all - // -- try again *with* clearing, if we didn't already - if (!mayClear) return skipAtomic(doc, pos, bias, true); - // Otherwise, turn off editing until further notice, and return the start of the doc - doc.cantEdit = true; - return Pos(doc.first, 0); - } - flipped = true; newPos = pos; dir = -dir; - } - } - curPos = newPos; - continue search; - } - } - } - return curPos; - } - } - - // SELECTION DRAWING - - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - - function prepareSelection(cm, primary) { - var doc = cm.doc, result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - - for (var i = 0; i < doc.sel.ranges.length; i++) { - if (primary === false && i == doc.sel.primIndex) continue; - var range = doc.sel.ranges[i]; - var collapsed = range.empty(); - if (collapsed || cm.options.showCursorWhenSelecting) - drawSelectionCursor(cm, range, curFragment); - if (!collapsed) - drawSelectionRange(cm, range, selFragment); - } - return result; - } - - // Draws a cursor for the given range - function drawSelectionCursor(cm, range, output) { - var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine); - - var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - - if (pos.other) { - // Secondary cursor, shown when on a 'jump' in bi-directional text - var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; - } - } - - // Draws the given range as a highlighted selection - function drawSelectionRange(cm, range, output) { - var display = cm.display, doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - - function add(left, top, width, bottom) { - if (top < 0) top = 0; - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + - "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + - "px; height: " + (bottom - top) + "px")); + this.viewport = viewport; + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; } - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias); - } - - iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { - var leftPos = coords(from, "left"), rightPos, left, right; - if (from == to) { - rightPos = leftPos; - left = right = leftPos.left; - } else { - rightPos = coords(to - 1, "right"); - if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } - left = leftPos.left; - right = rightPos.right; - } - if (fromArg == null && from == 0) left = leftSide; - if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part - add(left, leftPos.top, null, leftPos.bottom); - left = leftSide; - if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); - } - if (toArg == null && to == lineLen) right = rightSide; - if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) - start = leftPos; - if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) - end = rightPos; - if (left < leftSide + 1) left = leftSide; - add(left, rightPos.top, right - left, rightPos.bottom); - }); - return {start: start, end: end}; - } - - var sFrom = range.from(), sTo = range.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); - } - } - if (leftEnd.bottom < rightStart.top) - add(leftSide, leftEnd.bottom, null, rightStart.top); - } - - output.appendChild(fragment); - } - - // Cursor-blinking - function restartBlink(cm) { - if (!cm.state.focused) return; - var display = cm.display; - clearInterval(display.blinker); - var on = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) - display.blinker = setInterval(function() { - display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; - }, cm.options.cursorBlinkRate); - else if (cm.options.cursorBlinkRate < 0) - display.cursorDiv.style.visibility = "hidden"; - } - - // HIGHLIGHT WORKER - - function startWorker(cm, time) { - if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) - cm.state.highlight.set(time, bind(highlightWorker, cm)); - } - - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.frontier < doc.first) doc.frontier = doc.first; - if (doc.frontier >= cm.display.viewTo) return; - var end = +new Date + cm.options.workTime; - var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); - var changedLines = []; - - doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { - if (doc.frontier >= cm.display.viewFrom) { // Visible - var oldStyles = line.styles; - var highlighted = highlightLine(cm, line, state, true); - line.styles = highlighted.styles; - var oldCls = line.styleClasses, newCls = highlighted.classes; - if (newCls) line.styleClasses = newCls; - else if (oldCls) line.styleClasses = null; - var ischange = !oldStyles || oldStyles.length != line.styles.length || - oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; - if (ischange) changedLines.push(doc.frontier); - line.stateAfter = copyState(doc.mode, state); - } else { - processLine(cm, line.text, state); - line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; - } - ++doc.frontier; - if (+new Date > end) { - startWorker(cm, cm.options.workDelay); - return true; - } - }); - if (changedLines.length) runInOp(cm, function() { - for (var i = 0; i < changedLines.length; i++) - regLineChange(cm, changedLines[i], "text"); - }); - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(cm, n, precise) { - var minindent, minline, doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) return doc.first; - var line = getLine(doc, search - 1); - if (line.stateAfter && (!precise || search <= doc.frontier)) return search; - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline; - } - - function getStateBefore(cm, n, precise) { - var doc = cm.doc, display = cm.display; - if (!doc.mode.startState) return true; - var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; - if (!state) state = startState(doc.mode); - else state = copyState(doc.mode, state); - doc.iter(pos, n, function(line) { - processLine(cm, line.text, state); - var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; - line.stateAfter = save ? copyState(doc.mode, state) : null; - ++pos; - }); - if (precise) doc.frontier = pos; - return state; - } - - // POSITION MEASUREMENT - - function paddingTop(display) {return display.lineSpace.offsetTop;} - function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} - function paddingH(display) { - if (display.cachedPaddingH) return display.cachedPaddingH; - var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; - if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; - return data; - } - - function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; } - function displayWidth(cm) { - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; - } - function displayHeight(cm) { - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; - } - - // Ensure the lineView.wrapping.heights array is populated. This is - // an array of bottom offsets for the lines that make up a drawn - // line. When lineWrapping is on, there might be more than one - // height. - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i = 0; i < rects.length - 1; i++) { - var cur = rects[i], next = rects[i + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) - heights.push((cur.bottom + next.top) / 2 - rect.top); - } - } - heights.push(rect.bottom - rect.top); - } - } - - // Find a line map (mapping character offsets to text nodes) and a - // measurement cache for the given line number. (A line view might - // contain multiple lines when collapsed ranges are present.) - function mapFromLineView(lineView, line, lineN) { - if (lineView.line == line) - return {map: lineView.measure.map, cache: lineView.measure.cache}; - for (var i = 0; i < lineView.rest.length; i++) - if (lineView.rest[i] == line) - return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; - for (var i = 0; i < lineView.rest.length; i++) - if (lineNo(lineView.rest[i]) > lineN) - return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; - } - - // Render a line into the hidden node display.externalMeasured. Used - // when measurement is needed for a line that's not in the viewport. - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view; - } - - // Get a {top, bottom, left, right} box (in line-local coordinates) - // for a given character. - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); - } - - // Find a line view that corresponds to the given line number. - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) - return cm.display.view[findViewIndex(cm, lineN)]; - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) - return ext; - } - - // Measurement can be split in two steps, the set-up work that - // applies to the whole line, and the measurement of the actual - // character. Functions like coordsChar, that need to do a lot of - // measurements in a row, can thus ensure that the set-up work is - // only done once. - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) - view = null; - else if (view && view.changes) - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - if (!view) - view = updateExternalMeasurement(cm, line); - - var info = mapFromLineView(view, line, lineN); - return { - line: line, view: view, rect: null, - map: info.map, cache: info.cache, before: info.before, - hasHeights: false + DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) {this.events.push(arguments);} }; - } - - // Given a prepared measurement object, measures the position of an - // actual character (or fetches it from the cache). - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) ch = -1; - var key = ch + (bias || ""), found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) - prepared.rect = prepared.view.text.getBoundingClientRect(); - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) prepared.cache[key] = found; - } - return {left: found.left, right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom}; - } - - var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; - - function nodeAndOffsetInLineMap(map, ch, bias) { - var node, start, end, collapse; - // First, search the line map for the text node corresponding to, - // or closest to, the target character. - for (var i = 0; i < map.length; i += 3) { - var mStart = map[i], mEnd = map[i + 1]; - if (ch < mStart) { - start = 0; end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) collapse = "right"; - } - if (start != null) { - node = map[i + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) - collapse = bias; - if (bias == "left" && start == 0) - while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { - node = map[(i -= 3) + 2]; - collapse = "left"; - } - if (bias == "right" && start == mEnd - mStart) - while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { - node = map[(i += 3) + 2]; - collapse = "right"; - } - break; - } - } - return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; - } - - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, start = place.start, end = place.end, collapse = place.collapse; - - var rect; - if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. - for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { - rect = node.parentNode.getBoundingClientRect(); - } else if (ie && cm.options.lineWrapping) { - var rects = range(node, start, end).getClientRects(); - if (rects.length) - rect = rects[bias == "right" ? rects.length - 1 : 0]; - else - rect = nullRect; - } else { - rect = range(node, start, end).getBoundingClientRect() || nullRect; - } - if (rect.left || rect.right || start == 0) break; - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); - } else { // If it is a widget, simply get the box for the whole widget. - if (start > 0) collapse = bias = "right"; - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) - rect = rects[bias == "right" ? rects.length - 1 : 0]; - else - rect = node.getBoundingClientRect(); - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) - rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; - else - rect = nullRect; - } - - var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - for (var i = 0; i < heights.length - 1; i++) - if (mid < heights[i]) break; - var top = i ? heights[i - 1] : 0, bot = heights[i]; - var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top: top, bottom: bot}; - if (!rect.left && !rect.right) result.bogus = true; - if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } - - return result; - } - - // Work around problem with bounding client rects on ranges being - // returned incorrectly when zoomed on IE10 and below. - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || - screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) - return rect; - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return {left: rect.left * scaleX, right: rect.right * scaleX, - top: rect.top * scaleY, bottom: rect.bottom * scaleY}; - } - - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) - lineView.measure.caches[i] = {}; - } - } - - function clearLineMeasurementCache(cm) { - cm.display.externalMeasure = null; - removeChildren(cm.display.lineMeasure); - for (var i = 0; i < cm.display.view.length; i++) - clearLineMeasurementCacheFor(cm.display.view[i]); - } - - function clearCaches(cm) { - clearLineMeasurementCache(cm); - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; - if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; - cm.display.lineNumChars = null; - } - - function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } - function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } - - // Converts a {top, bottom, left, right} box from line-local - // coordinates into another coordinate system. Context may be one of - // "line", "div" (display.lineDiv), "local"/null (editor), "window", - // or "page". - function intoCoordSystem(cm, lineObj, rect, context) { - if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { - var size = widgetHeight(lineObj.widgets[i]); - rect.top += size; rect.bottom += size; - } - if (context == "line") return rect; - if (!context) context = "local"; - var yOff = heightAtLine(lineObj); - if (context == "local") yOff += paddingTop(cm.display); - else yOff -= cm.display.viewOffset; - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; rect.right += xOff; - } - rect.top += yOff; rect.bottom += yOff; - return rect; - } - - // Coverts a box from "div" coords to another coordinate system. - // Context may be "window", "page", "div", or "local"/null. - function fromCoordSystem(cm, coords, context) { - if (context == "div") return coords; - var left = coords.left, top = coords.top; - // First move into "page" coordinate system - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; - } - - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) lineObj = getLine(cm.doc, pos.line); - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); - } - - // Returns a box for a given cursor position, which may have an - // 'other' property containing the position of the secondary cursor - // on a bidi boundary. - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); - function get(ch, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); - if (right) m.left = m.right; else m.right = m.left; - return intoCoordSystem(cm, lineObj, m, context); - } - function getBidi(ch, partPos) { - var part = order[partPos], right = part.level % 2; - if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { - part = order[--partPos]; - ch = bidiRight(part) - (part.level % 2 ? 0 : 1); - right = true; - } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { - part = order[++partPos]; - ch = bidiLeft(part) - part.level % 2; - right = false; - } - if (right && ch == part.to && ch > part.from) return get(ch - 1); - return get(ch, right); - } - var order = getOrder(lineObj), ch = pos.ch; - if (!order) return get(ch); - var partPos = getBidiPartAt(order, ch); - var val = getBidi(ch, partPos); - if (bidiOther != null) val.other = getBidi(ch, bidiOther); - return val; - } - - // Used to cheaply estimate the coordinates for a position. Used for - // intermediate scroll updates. - function estimateCoords(cm, pos) { - var left = 0, pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return {left: left, right: left, top: top, bottom: top + lineObj.height}; - } - - // Positions returned by coordsChar contain some extra information. - // xRel is the relative x position of the input coordinates compared - // to the found position (so xRel > 0 means the coordinates are to - // the right of the character position, for example). When outside - // is true, that means the coordinates lie outside the line's - // vertical range. - function PosWithInfo(line, ch, outside, xRel) { - var pos = Pos(line, ch); - pos.xRel = xRel; - if (outside) pos.outside = true; - return pos; - } - - // Compute the character position closest to the given coordinates. - // Input must be lineSpace-local ("div" coordinate system). - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) return PosWithInfo(doc.first, 0, true, -1); - var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; - if (lineN > last) - return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); - if (x < 0) x = 0; - - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var merged = collapsedSpanAtEnd(lineObj); - var mergedPos = merged && merged.find(0, true); - if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) - lineN = lineNo(lineObj = mergedPos.to.line); - else - return found; - } - } - - function coordsCharInner(cm, lineObj, lineNo, x, y) { - var innerOff = y - heightAtLine(lineObj); - var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - - function getX(ch) { - var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); - wrongLine = true; - if (innerOff > sp.bottom) return sp.left - adjust; - else if (innerOff < sp.top) return sp.left + adjust; - else wrongLine = false; - return sp.left; - } - - var bidi = getOrder(lineObj), dist = lineObj.text.length; - var from = lineLeft(lineObj), to = lineRight(lineObj); - var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; - - if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); - // Do a binary search between these bounds. - for (;;) { - if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { - var ch = x < fromX || x - fromX <= toX - x ? from : to; - var xDiff = x - (ch == from ? fromX : toX); - while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; - var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, - xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); - return pos; - } - var step = Math.ceil(dist / 2), middle = from + step; - if (bidi) { - middle = from; - for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); - } - var middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} - else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} - } - } - - var measureText; - // Compute the default text height. - function textHeight(display) { - if (display.cachedTextHeight != null) return display.cachedTextHeight; - if (measureText == null) { - measureText = elt("pre"); - // Measure a bunch of lines, for browsers that compute - // fractional heights. - for (var i = 0; i < 49; ++i) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) display.cachedTextHeight = height; - removeChildren(display.measure); - return height || 1; - } - - // Compute the default character width. - function charWidth(display) { - if (display.cachedCharWidth != null) return display.cachedCharWidth; - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor]); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; - if (width > 2) display.cachedCharWidth = width; - return width || 10; - } - - // OPERATIONS - - // Operations are used to wrap a series of changes to the editor - // state in such a way that each change won't have to update the - // cursor and display (which would be awkward, slow, and - // error-prone). Instead, display updates are batched and then all - // combined and executed at once. - - var operationGroup = null; - - var nextOpId = 0; - // Start a new operation. - function startOperation(cm) { - cm.curOp = { - cm: cm, - viewChanged: false, // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, // Used to detect need to update scrollbar - forceUpdate: false, // Used to force a redraw - updateInput: null, // Whether to reset the input textarea - typing: false, // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, // Accumulated changes, for firing change events - cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already - selectionChanged: false, // Whether the selection needs to be redrawn - updateMaxLine: false, // Set when the widest line needs to be determined anew - scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, // Used to scroll to a specific position - focus: false, - id: ++nextOpId // Unique ID + DisplayUpdate.prototype.finish = function () { + for (var i = 0; i < this.events.length; i++) {signal.apply(null, this.events[i]);} }; - if (operationGroup) { - operationGroup.ops.push(cm.curOp); - } else { - cm.curOp.ownsGroup = operationGroup = { - ops: [cm.curOp], - delayedCallbacks: [] - }; + + function maybeClipScrollbars (cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } } - } - function fireCallbacksForOps(group) { - // Calls delayed callbacks and cursorActivity handlers until no - // new ones appear - var callbacks = group.delayedCallbacks, i = 0; - do { - for (; i < callbacks.length; i++) - callbacks[i](); - for (var j = 0; j < group.ops.length; j++) { - var op = group.ops[j]; - if (op.cursorActivityHandlers) - while (op.cursorActivityCalled < op.cursorActivityHandlers.length) - op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm); - } - } while (i < callbacks.length); - } - - // Finish an operation, updating the display and signalling delayed events - function endOperation(cm) { - var op = cm.curOp, group = op.ownsGroup; - if (!group) return; - - try { fireCallbacksForOps(group); } - finally { - operationGroup = null; - for (var i = 0; i < group.ops.length; i++) - group.ops[i].cm.curOp = null; - endOperations(group); - } - } - - // The DOM updates done when an operation finishes are batched so - // that the minimum number of relayouts are required. - function endOperations(group) { - var ops = group.ops; - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_R1(ops[i]); - for (var i = 0; i < ops.length; i++) // Write DOM (maybe) - endOperation_W1(ops[i]); - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_R2(ops[i]); - for (var i = 0; i < ops.length; i++) // Write DOM (maybe) - endOperation_W2(ops[i]); - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_finish(ops[i]); - } - - function endOperation_R1(op) { - var cm = op.cm, display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) findMaxLine(cm); - - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || - op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || - op.scrollToPos.to.line >= display.viewTo) || - display.maxLineChanged && cm.options.lineWrapping; - op.update = op.mustUpdate && - new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); - } + // Does the actual updating of the line display. Bails out + // (returning false) when there is nothing to be done and forced is + // false. + function updateDisplayIfNeeded (cm, update) { + var display = cm.display, doc = cm.doc; + + if (update.editorIsHidden) { + resetView(cm); + return false; + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) {return false;} - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } - function endOperation_R2(op) { - var cm = op.cm, display = cm.display; - if (op.updatedDisplay) updateHeightsInViewport(cm); + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); + if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } - op.barMeasure = measureForScrollbars(cm); + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); - // If the max line changed since it was last measured, measure it, - // and ensure the document's width matches it. - // updateDisplay_W2 will use these properties to do the actual resizing - if (display.maxLineChanged && !cm.options.lineWrapping) { - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; - cm.display.sizerWidth = op.adjustWidthTo; - op.barMeasure.scrollWidth = - Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); - } - - if (op.updatedDisplay || op.selectionChanged) - op.preparedSelection = display.input.prepareSelection(); - } - - function endOperation_W2(op) { - var cm = op.cm; - - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) - setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); - cm.display.maxLineChanged = false; - } - - if (op.preparedSelection) - cm.display.input.showSelection(op.preparedSelection); - if (op.updatedDisplay) - setDocumentHeight(cm, op.barMeasure); - if (op.updatedDisplay || op.startHeight != cm.doc.height) - updateScrollbars(cm, op.barMeasure); - - if (op.selectionChanged) restartBlink(cm); - - if (cm.state.focused && op.updateInput) - cm.display.input.reset(op.typing); - if (op.focus && op.focus == activeElt()) ensureFocus(op.cm); - } - - function endOperation_finish(op) { - var cm = op.cm, display = cm.display, doc = cm.doc; - - if (op.updatedDisplay) postUpdateDisplay(cm, op.update); - - // Abort mouse wheel delta measurement, when scrolling explicitly - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) - display.wheelStartX = display.wheelStartY = null; - - // Propagate the scroll position to the actual DOM scroller - if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { - doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); - display.scrollbars.setScrollTop(doc.scrollTop); - display.scroller.scrollTop = doc.scrollTop; - } - if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { - doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft)); - display.scrollbars.setScrollLeft(doc.scrollLeft); - display.scroller.scrollLeft = doc.scrollLeft; - alignHorizontally(cm); - } - // If we need to scroll a specific position into view, do so. - if (op.scrollToPos) { - var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), - clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); - } - - // Fire events for markers that are hidden/unidden by editing or - // undoing - var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; - if (hidden) for (var i = 0; i < hidden.length; ++i) - if (!hidden[i].lines.length) signal(hidden[i], "hide"); - if (unhidden) for (var i = 0; i < unhidden.length; ++i) - if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); - - if (display.wrapper.offsetHeight) - doc.scrollTop = cm.display.scroller.scrollTop; - - // Fire change events, and delayed event handlers - if (op.changeObjs) - signal(cm, "changes", cm, op.changeObjs); - if (op.update) - op.update.finish(); - } - - // Run the given function in an operation - function runInOp(cm, f) { - if (cm.curOp) return f(); - startOperation(cm); - try { return f(); } - finally { endOperation(cm); } - } - // Wraps a function in an operation. Returns the wrapped function. - function operation(cm, f) { - return function() { - if (cm.curOp) return f.apply(cm, arguments); - startOperation(cm); - try { return f.apply(cm, arguments); } - finally { endOperation(cm); } - }; - } - // Used to add methods to editor and doc instances, wrapping them in - // operations. - function methodOp(f) { - return function() { - if (this.curOp) return f.apply(this, arguments); - startOperation(this); - try { return f.apply(this, arguments); } - finally { endOperation(this); } - }; - } - function docMethodOp(f) { - return function() { - var cm = this.cm; - if (!cm || cm.curOp) return f.apply(this, arguments); - startOperation(cm); - try { return f.apply(this, arguments); } - finally { endOperation(cm); } - }; - } + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px"; - // VIEW TRACKING + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) {return false;} - // These objects are used to represent the visible (currently drawn) - // part of the document. A LineView may correspond to multiple - // logical lines, if those are connected by collapsed ranges. - function LineView(doc, line, lineN) { - // The starting line - this.line = line; - // Continuing lines, if any - this.rest = visualLineContinued(line); - // Number of logical lines in this visual line - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - - // Create a range of LineView objects for the given lines. - function buildViewArray(cm, from, to) { - var array = [], nextPos; - for (var pos = from; pos < to; pos = nextPos) { - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); - nextPos = pos + view.size; - array.push(view); - } - return array; - } - - // Updates the display.view data structure for a given change to the - // document. From and to are in pre-change coordinates. Lendiff is - // the amount of lines added or subtracted by the change. This is - // used for changes that span multiple lines, or change the way - // lines are divided into visual lines. regLineChange (below) - // registers single-line changes. - function regChange(cm, from, to, lendiff) { - if (from == null) from = cm.doc.first; - if (to == null) to = cm.doc.first + cm.doc.size; - if (!lendiff) lendiff = 0; - - var display = cm.display; - if (lendiff && to < display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers > from)) - display.updateLineNumbers = from; - - cm.curOp.viewChanged = true; - - if (from >= display.viewTo) { // Change after - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) - resetView(cm); - } else if (to <= display.viewFrom) { // Change before - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap - resetView(cm); - } else if (from <= display.viewFrom) { // Top overlap - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { // Bottom overlap - var cut = viewCuttingPoint(cm, from, from, -1); - if (cut) { - display.view = display.view.slice(0, cut.index); - display.viewTo = cut.lineN; - } else { - resetView(cm); - } - } else { // Gap in the middle - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index) - .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) - .concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); - } - } - - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) - ext.lineN += lendiff; - else if (from < ext.lineN + ext.size) - display.externalMeasured = null; - } - } - - // Register a change to a single line. Type must be one of "text", - // "gutter", "class", "widget" - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) - display.externalMeasured = null; - - if (line < display.viewFrom || line >= display.viewTo) return; - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) return; - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) arr.push(type); - } - - // Clear the view. - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - - // Find the view element corresponding to a given line. Return null - // when the line isn't visible. - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) return null; - n -= cm.display.viewFrom; - if (n < 0) return null; - var view = cm.display.view; - for (var i = 0; i < view.length; i++) { - n -= view[i].size; - if (n < 0) return i; - } - } - - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), diff, view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) - return {index: index, lineN: newN}; - for (var i = 0, n = cm.display.viewFrom; i < index; i++) - n += view[i].size; - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) return null; - diff = (n + view[index].size) - oldN; - index++; - } else { - diff = n - oldN; - } - oldN += diff; newN += diff; - } - while (visualLineNo(cm.doc, newN) != newN) { - if (index == (dir < 0 ? 0 : view.length - 1)) return null; - newN += dir * view[index - (dir < 0 ? 1 : 0)].size; - index += dir; - } - return {index: index, lineN: newN}; - } - - // Force the view to cover a given range, adding empty view element - // or clipping off existing ones as needed. - function adjustView(cm, from, to) { - var display = cm.display, view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) - display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); - else if (display.viewFrom < from) - display.view = display.view.slice(findViewIndex(cm, from)); - display.viewFrom = from; - if (display.viewTo < to) - display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); - else if (display.viewTo > to) - display.view = display.view.slice(0, findViewIndex(cm, to)); - } - display.viewTo = to; - } - - // Count the number of lines in the view whose DOM representation is - // out of date (or nonexistent). - function countDirtyView(cm) { - var view = cm.display.view, dirty = 0; - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; - } - return dirty; - } - - // EVENT HANDLERS - - // Attach the necessary event handlers when initializing the editor - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - // Older IE's will not fire a second mousedown for a double click - if (ie && ie_version < 11) - on(d.scroller, "dblclick", operation(cm, function(e) { - if (signalDOMEvent(cm, e)) return; - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); - else - on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); - // Some browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for these browsers. - if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); - - // Used to suppress mouse event handling when a touch happens - var touchFinished, prevTouch = {end: 0}; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); - prevTouch = d.activeTouch; - prevTouch.end = +new Date; - } - }; - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) return false; - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1; - } - function farAway(touch, other) { - if (other.left == null) return true; - var dx = other.left - touch.left, dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20; - } - on(d.scroller, "touchstart", function(e) { - if (!isMouseLikeTouchEvent(e)) { - clearTimeout(touchFinished); - var now = +new Date; - d.activeTouch = {start: now, moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null}; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; - } - } - }); - on(d.scroller, "touchmove", function() { - if (d.activeTouch) d.activeTouch.moved = true; - }); - on(d.scroller, "touchend", function(e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && - !touch.moved && new Date - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), range; - if (!touch.prev || farAway(touch, touch.prev)) // Single tap - range = new Range(pos, pos); - else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap - range = cm.findWordAt(pos); - else // Triple tap - range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); - cm.setSelection(range.anchor, range.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - - // Sync scrolling between fake scrollbars and real scrollable - // area, ensure viewport is updated when scrolling. - on(d.scroller, "scroll", function() { - if (d.scroller.clientHeight) { - setScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt(); + if (toUpdate > 4) display.lineDiv.style.display = "none"; + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) display.lineDiv.style.display = ""; + display.renderedView = display.view; + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); - // Listen to wheel events in order to try and update the viewport on time. - on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); - on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = 0; - // Prevent wrapper from ever scrolling - on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } - d.dragFunctions = { - simple: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, - start: function(e){onDragStart(cm, e);}, - drop: operation(cm, onDrop) - }; + display.updateLineNumbers = null; - var inp = d.input.getField(); - on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", bind(onFocus, cm)); - on(inp, "blur", bind(onBlur, cm)); - } - - function dragDropChanged(cm, value, old) { - var wasOn = old && old != CodeMirror.Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.simple); - toggle(cm.display.scroller, "dragover", funcs.simple); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - - // Called when the window resizes - function onResize(cm) { - var d = cm.display; - if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) - return; - // Might be a text scaling operation, clear size caches. - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - - // MOUSE EVENTS - - // Return true when the given mouse event happened in a widget - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || - (n.parentNode == display.sizer && n != display.mover)) return true; } - } - - // Given a mouse event, find the corresponding position. If liberal - // is false, it checks whether a gutter or scrollbar was clicked, - // and returns null if it was. forRect is used by rectangular - // selections, and tries to estimate a character position even for - // coordinates beyond the right of the text. - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; - - var x, y, space = display.lineSpace.getBoundingClientRect(); - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX - space.left; y = e.clientY - space.top; } - catch (e) { return null; } - var coords = coordsChar(cm, x, y), line; - if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords; - } - - // A mouse down can be a single click, double click, triple click, - // start of selection drag, start of text drag, new cursor - // (ctrl-click), rectangle drag (alt-drag), or xwin - // middle-click-paste. Or it might be a click on something we should - // not interfere with, such as a scrollbar or widget. - function onMouseDown(e) { - var cm = this, display = cm.display; - if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return; - display.shift = e.shiftKey; - - if (eventInWidget(display, e)) { - if (!webkit) { - // Briefly turn off draggability, to allow widgets to do - // normal dragging things. - display.scroller.draggable = false; - setTimeout(function(){display.scroller.draggable = true;}, 100); - } - return; - } - if (clickInGutter(cm, e)) return; - var start = posFromMouse(cm, e); - window.focus(); - - switch (e_button(e)) { - case 1: - if (start) - leftButtonDown(cm, e, start); - else if (e_target(e) == display.scroller) - e_preventDefault(e); - break; - case 2: - if (webkit) cm.state.lastMiddleDown = +new Date; - if (start) extendSelection(cm.doc, start); - setTimeout(function() {display.input.focus();}, 20); - e_preventDefault(e); - break; - case 3: - if (captureRightClick) onContextMenu(cm, e); - else delayBlurEvent(cm); - break; - } - } - - var lastClick, lastDoubleClick; - function leftButtonDown(cm, e, start) { - if (ie) setTimeout(bind(ensureFocus, cm), 0); - else cm.curOp.focus = activeElt(); - - var now = +new Date, type; - if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { - type = "triple"; - } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { - type = "double"; - lastDoubleClick = {time: now, pos: start}; - } else { - type = "single"; - lastClick = {time: now, pos: start}; + + function postUpdateDisplay (cm, update) { + var viewport = update.viewport; + for (var first = true; ; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) {viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};} + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) {break;} + } + if (!updateDisplayIfNeeded(cm, update)) break; + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + } + + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; + } + } + + function updateDisplaySimple (cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + update.finish(); + } + } + + function setDocumentHeight (cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + var total = measure.docHeight + cm.display.barHeight; + cm.display.heightForcer.style.top = total + "px"; + cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px"; + } + + // Read the actual heights of the rendered lines, and update their + // stored heights to match. + function updateHeightsInViewport (cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height; + if (cur.hidden) continue; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + } + var diff = cur.line.height - height; + if (height < 2) height = textHeight(display); + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { + for (var j = 0; j < cur.rest.length; j++) {updateWidgetHeight(cur.rest[j]);} + } + } + } } - var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; - if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && - type == "single" && (contained = sel.contains(start)) > -1 && - (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && - (cmp(contained.to(), start) > 0 || start.xRel < 0)) - leftButtonStartDrag(cm, e, start, modifier); - else - leftButtonSelect(cm, e, start, type, modifier); - } - - // Start a text drag. When it ends, see if any dragging actually - // happen, and treat as a click if it didn't. - function leftButtonStartDrag(cm, e, start, modifier) { - var display = cm.display, startTime = +new Date; - var dragEnd = operation(cm, function(e2) { - if (webkit) display.scroller.draggable = false; - cm.state.draggingText = false; - off(document, "mouseup", dragEnd); - off(display.scroller, "drop", dragEnd); - if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { - e_preventDefault(e2); - if (!modifier && +new Date - 200 < startTime) - extendSelection(cm.doc, start); - // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) - if (webkit || ie && ie_version == 9) - setTimeout(function() {document.body.focus(); display.input.focus();}, 20); - else - display.input.focus(); - } - }); - // Let the drag handler handle this. - if (webkit) display.scroller.draggable = true; - cm.state.draggingText = dragEnd; - // IE's approach to draggable - if (display.scroller.dragDrop) display.scroller.dragDrop(); - on(document, "mouseup", dragEnd); - on(display.scroller, "drop", dragEnd); - } - - // Normal selection, as opposed to text dragging. - function leftButtonSelect(cm, e, start, type, addNew) { - var display = cm.display, doc = cm.doc; - e_preventDefault(e); - - var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; - if (addNew && !e.shiftKey) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) - ourRange = ranges[ourIndex]; - else - ourRange = new Range(start, start); - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - - if (e.altKey) { - type = "rect"; - if (!addNew) ourRange = new Range(start, start); - start = posFromMouse(cm, e, true, true); - ourIndex = -1; - } else if (type == "double") { - var word = cm.findWordAt(start); - if (cm.display.shift || doc.extend) - ourRange = extendRange(doc, ourRange, word.anchor, word.head); - else - ourRange = word; - } else if (type == "triple") { - var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); - if (cm.display.shift || doc.extend) - ourRange = extendRange(doc, ourRange, line.anchor, line.head); - else - ourRange = line; - } else { - ourRange = extendRange(doc, ourRange, start); - } - - if (!addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), - {scroll: false, origin: "*mouse"}); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { - setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0)); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) return; - lastPos = pos; - - if (type == "rect") { - var ranges = [], tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); - line <= end; line++) { - var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); - if (left == right) - ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); - else if (text.length > leftPos) - ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); - } - if (!ranges.length) ranges.push(new Range(start, start)); - setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), - {origin: "*mouse", scroll: false}); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var anchor = oldRange.anchor, head = pos; - if (type != "single") { - if (type == "double") - var range = cm.findWordAt(pos); - else - var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); - if (cmp(range.anchor, anchor) > 0) { - head = range.head; - anchor = minPos(oldRange.from(), range.anchor); - } else { - head = range.anchor; - anchor = maxPos(oldRange.to(), range.head); - } - } - var ranges = startSel.ranges.slice(0); - ranges[ourIndex] = new Range(clipPos(doc, anchor), head); - setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); - } - } - - var editorSize = display.wrapper.getBoundingClientRect(); - // Used to ensure timeout re-tries don't fire when another extend - // happened in the meantime (clearTimeout isn't reliable -- at - // least on Chrome, the timeouts still happen even when cleared, - // if the clear happens after their scheduled firing time). - var counter = 0; - - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, type == "rect"); - if (!cur) return; - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) - setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) setTimeout(operation(cm, function() { - if (counter != curCount) return; - display.scroller.scrollTop += outside; - extend(e); - }), 50); - } - } - - function done(e) { - counter = Infinity; - e_preventDefault(e); - display.input.focus(); - off(document, "mousemove", move); - off(document, "mouseup", up); - doc.history.lastSelOrigin = null; - } - - var move = operation(cm, function(e) { - if (!e_button(e)) done(e); - else extend(e); - }); - var up = operation(cm, done); - on(document, "mousemove", move); - on(document, "mouseup", up); - } - - // Determines whether an event happened in the gutter, and fires the - // handlers for the corresponding event. - function gutterEvent(cm, e, type, prevent, signalfn) { - try { var mX = e.clientX, mY = e.clientY; } - catch(e) { return false; } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; - if (prevent) e_preventDefault(e); - - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - - if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); - mY -= lineBox.top - display.viewOffset; - - for (var i = 0; i < cm.options.gutters.length; ++i) { - var g = display.gutters.childNodes[i]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.options.gutters[i]; - signalfn(cm, type, cm, line, gutter, e); - return e_defaultPrevented(e); - } - } - } - - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true, signalLater); - } - - // Kludge to work around strange IE behavior where it'll sometimes - // re-fire a series of drag-related events right after the drop (#1551) - var lastDrop = 0; - - function onDrop(e) { - var cm = this; - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) - return; - e_preventDefault(e); - if (ie) lastDrop = +new Date; - var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; - if (!pos || isReadOnly(cm)) return; - // Might be a file drop, in which case we simply extract the text - // and insert it. - if (files && files.length && window.FileReader && window.File) { - var n = files.length, text = Array(n), read = 0; - var loadFile = function(file, i) { - var reader = new FileReader; - reader.onload = operation(cm, function() { - text[i] = reader.result; - if (++read == n) { - pos = clipPos(cm.doc, pos); - var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); - } - }); - reader.readAsText(file); - }; - for (var i = 0; i < n; ++i) loadFile(files[i], i); - } else { // Normal drop - // Don't do a replace if the drop happened inside of the selected text. - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - // Ensure the editor is re-focused - setTimeout(function() {cm.display.input.focus();}, 20); - return; - } - try { - var text = e.dataTransfer.getData("Text"); - if (text) { - if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) - var selected = cm.listSelections(); - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) for (var i = 0; i < selected.length; ++i) - replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); - cm.replaceSelection(text, "around", "paste"); - cm.display.input.focus(); - } - } - catch(e){} - } - } - - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; - - e.dataTransfer.setData("Text", cm.getSelection()); - - // Use dummy image instead of default browsers image. - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - // Force a relayout, or Opera won't use our image for some obscure reason - img._top = img.offsetTop; - } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) img.parentNode.removeChild(img); - } - } - - // SCROLL EVENTS - - // Sync the scrollable area and scrollbars, ensure the viewport - // covers the visible area. - function setScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) return; - cm.doc.scrollTop = val; - if (!gecko) updateDisplaySimple(cm, {top: val}); - if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (gecko) updateDisplaySimple(cm); - startWorker(cm, 100); - } - // Sync scroller and scrollbar, ensure the gutter elements are - // aligned. - function setScrollLeft(cm, val, isScroller) { - if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; - val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; - cm.display.scrollbars.setScrollLeft(val); - } - - // Since the delta values reported on mouse wheel events are - // unstandardized between browsers and even browser versions, and - // generally horribly unpredictable, this code starts by measuring - // the scroll effect that the first few mouse wheel events have, - // and, from that, detects the way it can convert deltas to pixel - // offsets afterwards. - // - // The reason we want to know the amount a wheel event will scroll - // is that it gives us a chance to update the display before the - // actual scrolling happens, reducing flickering. - - var wheelSamples = 0, wheelPixelsPerUnit = null; - // Fill in a browser-detected starting value on browsers where we - // know one. These don't have to be accurate -- the result of them - // being wrong would just be a slight flicker on the first wheel - // scroll (if it is large enough). - if (ie) wheelPixelsPerUnit = -.53; - else if (gecko) wheelPixelsPerUnit = 15; - else if (chrome) wheelPixelsPerUnit = -.7; - else if (safari) wheelPixelsPerUnit = -1/3; - - var wheelEventDelta = function(e) { - var dx = e.wheelDeltaX, dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; - else if (dy == null) dy = e.wheelDelta; - return {x: dx, y: dy}; - }; - CodeMirror.wheelEventPixels = function(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta; - }; - - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; - - var display = cm.display, scroll = display.scroller; - // Quit if there's nothing to scroll here - if (!(dx && scroll.scrollWidth > scroll.clientWidth || - dy && scroll.scrollHeight > scroll.clientHeight)) return; + // Read and store the height of line widgets associated with the + // given line. + function updateWidgetHeight (line) { + if (line.widgets) { + for (var i = 0; i < line.widgets.length; ++i) {line.widgets[i].height = line.widgets[i].node.offsetHeight;} + } + } + + // Do a bulk-read of the DOM positions and sizes needed to draw the + // view, so that we don't interleave reading and writing to the DOM. + function getDimensions (cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; + width[cm.options.gutters[i]] = n.clientWidth; + } + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth}; + } + + // Sync the actual display DOM structure with display.view, removing + // nodes for lines that are no longer in view, and creating the ones + // that are not there yet, and updating the ones that are out of + // date. + function patchDisplay (cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; + + function rm (node) { + var next = node.nextSibling; + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) {node.style.display = "none";} else {node.parentNode.removeChild(node);} + return next; + } - // Webkit browsers on OS X abort momentum scrolls when the target - // of the scroll event is removed from the scrollable element. - // This hack (see related code in patchDisplay) makes sure the - // element is kept around. - if (dy && mac && webkit) { - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + var view = display.view, lineN = display.viewFrom; + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. for (var i = 0; i < view.length; i++) { - if (view[i].node == cur) { - cm.display.currentWheelTarget = cur; - break outer; - } - } - } - } - - // On some browsers, horizontal scrolling will cause redraws to - // happen before the gutter has been realigned, causing it to - // wriggle around in a most unseemly way. When we have an - // estimated pixels/delta value, we just handle horizontal - // scrolling entirely here. It'll be slightly off from native, but - // better than glitching out. - if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { - if (dy) - setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); - setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); - e_preventDefault(e); - display.wheelStartX = null; // Abort measurement, if in progress - return; - } - - // 'Project' the visible viewport to cover the area that is being - // scrolled into view (if we know enough to estimate it). - if (dy && wheelPixelsPerUnit != null) { - var pixels = dy * wheelPixelsPerUnit; - var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; - if (pixels < 0) top = Math.max(0, top + pixels - 50); - else bot = Math.min(cm.doc.height, bot + pixels + 50); - updateDisplaySimple(cm, {top: top, bottom: bot}); - } - - if (wheelSamples < 20) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; display.wheelDY = dy; - setTimeout(function() { - if (display.wheelStartX == null) return; - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || - (movedX && display.wheelDX && movedX / display.wheelDX); - display.wheelStartX = display.wheelStartY = null; - if (!sample) return; - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; display.wheelDY += dy; - } - } - } - - // KEY EVENTS - - // Run a handler that was bound to a key. - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) return false; - } - // Ensure previous input has been read, so that the handler sees a - // consistent view of the document - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, done = false; - try { - if (isReadOnly(cm)) cm.state.suppressEdits = true; - if (dropShift) cm.display.shift = false; - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; - } - return done; - } - - function lookupKeyForEditor(cm, name, handle) { - for (var i = 0; i < cm.state.keyMaps.length; i++) { - var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); - if (result) return result; - } - return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) - || lookupKey(name, cm.options.keyMap, handle, cm); - } - - var stopSeq = new Delayed; - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) return "handled"; - stopSeq.set(50, function() { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); - name = seq + " " + name; - } - var result = lookupKeyForEditor(cm, name, handle); - - if (result == "multi") - cm.state.keySeq = name; - if (result == "handled") - signalLater(cm, "keyHandled", cm, name, e); - - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - - if (seq && !result && /\'$/.test(name)) { - e_preventDefault(e); - return true; - } - return !!result; - } - - // Handle a key from the keydown event. - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) return false; - - if (e.shiftKey && !cm.state.keySeq) { - // First try to resolve full name (including 'Shift-'). Failing - // that, see if there is a cursor-motion command (starting with - // 'go') bound to the keyname without 'Shift-'. - return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) - || dispatchKey(cm, name, e, function(b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) - return doHandleBinding(cm, b); - }); - } else { - return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); - } - } - - // Handle a key from the keypress event - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, - function(b) { return doHandleBinding(cm, b, true); }); - } - - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) return; - // IE does strange things with escape. - if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) - cm.replaceSelection("", null, "cut"); - } - - // Turn mouse into crosshair when Alt is held on Mac. - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) - showCrossHair(cm); - } - - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); - } - - function onKeyUp(e) { - if (e.keyCode == 16) this.doc.sel.shift = false; - signalDOMEvent(this, e); - } - - function onKeyPress(e) { - var cm = this; - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; - var keyCode = e.keyCode, charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} - if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (handleCharBinding(cm, e, ch)) return; - cm.display.input.onKeyPress(e); - } - - // FOCUS/BLUR EVENTS - - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function() { - if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - onBlur(cm); - } - }, 100); - } - - function onFocus(cm) { - if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; - - if (cm.options.readOnly == "nocursor") return; - if (!cm.state.focused) { - signal(cm, "focus", cm); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - // This test prevents this from firing when a context - // menu is closed (since the input reset would kill the - // select-all detection hack) - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 - } - cm.display.input.receivedFocus(); - } - restartBlink(cm); - } - function onBlur(cm) { - if (cm.state.delayingBlurEvent) return; - - if (cm.state.focused) { - signal(cm, "blur", cm); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); - } - clearInterval(cm.display.blinker); - setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); - } - - // CONTEXT MENU HANDLING - - // To make the context menu work, we need to briefly unhide the - // textarea (making it as unobtrusive as possible) to let the - // right-click take effect on it. - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; - cm.display.input.onContextMenu(e); - } - - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) return false; - return gutterEvent(cm, e, "gutterContextMenu", false, signal); - } - - // UPDATING - - // Compute the position of the end of a change (its 'to' property - // refers to the pre-change end). - var changeEnd = CodeMirror.changeEnd = function(change) { - if (!change.text) return change.to; - return Pos(change.from.line + change.text.length - 1, - lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); - }; - - // Adjust a position to refer to the post-change position of the - // same text, or the end of the change if the change covers it. - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) return pos; - if (cmp(pos, change.to) <= 0) return changeEnd(change); - - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; - if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; - return Pos(line, ch); - } - - function computeSelAfterChange(doc, change) { - var out = []; - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - out.push(new Range(adjustForChange(range.anchor, change), - adjustForChange(range.head, change))); - } - return normalizeSelection(out, doc.sel.primIndex); - } - - function offsetPos(pos, old, nw) { - if (pos.line == old.line) - return Pos(nw.line, pos.ch - old.ch + nw.ch); - else - return Pos(nw.line + (pos.line - old.line), pos.ch); - } - - // Used by replaceSelections to allow moving the selection to the - // start or around the replaced test. Hint may be "start" or "around". - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; - out[i] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i] = new Range(from, from); - } - } - return new Selection(out, doc.sel.primIndex); - } - - // Allow "beforeChange" event handlers to influence a change - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function() { this.canceled = true; } - }; - if (update) obj.update = function(from, to, text, origin) { - if (from) this.from = clipPos(doc, from); - if (to) this.to = clipPos(doc, to); - if (text) this.text = text; - if (origin !== undefined) this.origin = origin; - }; - signal(doc, "beforeChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); + var lineView = view[i]; + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { // Already drawn + while (cur != lineView.node) cur = rm(cur); + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) cur = rm(cur); + } - if (obj.canceled) return null; - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; - } + // When an aspect of a line changes, a string is added to + // lineView.changes. This updates the relevant part of the line's + // DOM structure. + function updateLineForChanges (cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") updateLineText(cm, lineView); + else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); + else if (type == "class") updateLineClasses(lineView); + else if (type == "widget") updateLineWidgets(cm, lineView, dims); + } + lineView.changes = null; + } - // Apply a change to a document, and add it to the document's - // history, and propagating it to all linked documents. - function makeChange(doc, change, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); - if (doc.cm.state.suppressEdits) return; + // Lines with gutter elements, widgets or a background class need to + // be wrapped, and have the extra elements added to the wrapper div + function ensureLineWrapped (lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) {lineView.text.parentNode.replaceChild(lineView.node, lineView.text);} + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) lineView.node.style.zIndex = 2; + } + return lineView.node; } - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) return; + function updateLineBackground (lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) cls += " CodeMirror-linebackground"; + if (lineView.background) { + if (cls) lineView.background.className = cls; + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + } } - // Possibly split or suppress the update based on the presence - // of read-only spans in its range. - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i = split.length - 1; i >= 0; --i) - makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); - } else { - makeChangeInner(doc, change); + // Wrapper around buildLineContent which will reuse the structure + // in display.externalMeasured when possible. + function getLineContent (cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); } - } - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + // Redraw the line's text. Interacts with the background and text + // classes because the mode may output tokens that influence these + // classes. + function updateLineText (cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) lineView.node = built.pre; + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(lineView); + } else if (cls) { + lineView.text.className = cls; + } + } - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; + function updateLineClasses (lineView) { + updateLineBackground(lineView); + if (lineView.line.wrapClass) {ensureLineWrapped(lineView).className = lineView.line.wrapClass;} else if (lineView.node != lineView.text) {lineView.node.className = "";} + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); - }); - } - - // Revert a change stored in a document's history. - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - if (doc.cm && doc.cm.state.suppressEdits) return; - - var hist = doc.history, event, selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; - - // Verify that there is a useable event (so that ctrl-z won't - // needlessly clear selection events) - for (var i = 0; i < source.length; i++) { - event = source[i]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) - break; - } - if (i == source.length) return; - hist.lastOrigin = hist.lastSelOrigin = null; - - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, {clearRedo: false}); - return; - } - selAfter = event; - } - else break; - } - - // Build up a reverse change object to add to the opposite history - // stack (redo when undoing, and vice versa). - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({changes: antiChanges, generation: hist.generation}); - hist.generation = event.generation || ++hist.maxGeneration; - - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - - for (var i = event.changes.length - 1; i >= 0; --i) { - var change = event.changes[i]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return; - } - - antiChanges.push(historyChangeFromChange(doc, change)); - - var after = i ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); - var rebased = []; - - // Propagate to the linked documents - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); - }); - } - } - - // Sub-views need their line numbers shifted when text is added - // above or below them in the parent document. - function shiftDoc(doc, distance) { - if (distance == 0) return; - doc.first += distance; - doc.sel = new Selection(map(doc.sel.ranges, function(range) { - return new Range(Pos(range.anchor.line + distance, range.anchor.ch), - Pos(range.head.line + distance, range.head.ch)); - }), doc.sel.primIndex); - if (doc.cm) { - regChange(doc.cm, doc.first, doc.first - distance, distance); - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) - regLineChange(doc.cm, l, "gutter"); - } - } - - // More lower-level change function, handling only a single document - // (not linked ones). - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) - return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); - - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return; - } - if (change.from.line > doc.lastLine()) return; - - // Clip the change to the size of this doc - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], origin: change.origin}; + function updateLineGutter (cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + + "px; width: " + dims.gutterTotalWidth + "px"); + cm.display.input.setUneditable(gutterWrap); + wrap.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) {gutterWrap.className += " " + lineView.line.gutterClass;} + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { + lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + + cm.display.lineNumInnerWidth + "px")); + } + if (markers) { + for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; + if (found) { + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + } + } + } + } } - var last = doc.lastLine(); - if (change.to.line > last) { - change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], origin: change.origin}; + + function updateLineWidgets (cm, lineView, dims) { + if (lineView.alignable) lineView.alignable = null; + for (var node = lineView.node.firstChild, next; node; node = next) { + var next = node.nextSibling; + if (node.className == "CodeMirror-linewidget") {lineView.node.removeChild(node);} + } + insertLineWidgets(cm, lineView, dims); } - change.removed = getBetween(doc, change.from, change.to); - - if (!selAfter) selAfter = computeSelAfterChange(doc, change); - if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); - else updateDoc(doc, change, spans); - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - } - - // Handle the interaction of a change to a document with the editor - // that this document is part of. - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, display = cm.display, from = change.from, to = change.to; - - var recomputeMaxLength = false, checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function(line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true; - } - }); - } - - if (doc.sel.contains(change.from, change.to) > -1) - signalCursorActivity(cm); - - updateDoc(doc, change, spans, estimateHeight(cm)); - - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function(line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) cm.curOp.updateMaxLine = true; - } - - // Adjust frontier, schedule worker - doc.frontier = Math.min(doc.frontier, from.line); - startWorker(cm, 400); - - var lendiff = change.text.length - (to.line - from.line) - 1; - // Remember that these lines changed, for updating the display - if (change.full) - regChange(cm); - else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) - regLineChange(cm, from.line, "text"); - else - regChange(cm, from.line, to.line + 1, lendiff); - - var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from: from, to: to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) signalLater(cm, "change", cm, obj); - if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); - } - cm.display.selForContextMenu = null; - } - - function replaceRange(doc, code, from, to, origin) { - if (!to) to = from; - if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } - if (typeof code == "string") code = splitLines(code); - makeChange(doc, {from: from, to: to, text: code, origin: origin}); - } - - // SCROLLING THINGS INTO VIEW - - // If an editor sits on the top or bottom of the window, partially - // scrolled out of view, this ensures that the cursor is visible. - function maybeScrollWindow(cm, coords) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) return; - - var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; - if (coords.top + box.top < 0) doScroll = true; - else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + - (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + - (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + - coords.left + "px; width: 2px;"); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); - } - } - - // Scroll a given position into view (immediately), verifying that - // it actually became visible (as line heights are accurately - // measured, the position of something may 'drift' during drawing). - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) margin = 0; - for (var limit = 0; limit < 5; limit++) { - var changed = false, coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), - Math.min(coords.top, endCoords.top) - margin, - Math.max(coords.left, endCoords.left), - Math.max(coords.bottom, endCoords.bottom) + margin); - var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - setScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; - } - if (!changed) break; - } - return coords; - } - - // Scroll a given set of coordinates into view (immediately). - function scrollIntoView(cm, x1, y1, x2, y2) { - var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); - if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); - if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); - } - - // Calculate a new scroll position needed to scroll the given - // rectangle into view. Returns an object with scrollTop and - // scrollLeft properties. When these are undefined, the - // vertical/horizontal position does not need to be adjusted. - function calculateScrollPos(cm, x1, y1, x2, y2) { - var display = cm.display, snapMargin = textHeight(cm.display); - if (y1 < 0) y1 = 0; - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen = displayHeight(cm), result = {}; - if (y2 - y1 > screen) y2 = y1 + screen; - var docBottom = cm.doc.height + paddingVert(display); - var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; - if (y1 < screentop) { - result.scrollTop = atTop ? 0 : y1; - } else if (y2 > screentop + screen) { - var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); - if (newTop != screentop) result.scrollTop = newTop; - } - - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; - var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); - var tooWide = x2 - x1 > screenw; - if (tooWide) x2 = x1 + screenw; - if (x1 < 10) - result.scrollLeft = 0; - else if (x1 < screenleft) - result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); - else if (x2 > screenw + screenleft - 3) - result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; - return result; - } - - // Store a relative adjustment to the scroll position in the current - // operation (to be applied when the operation finishes). - function addToScrollPos(cm, left, top) { - if (left != null || top != null) resolveScrollToPos(cm); - if (left != null) - cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; - if (top != null) - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - - // Make sure that at the end of the operation the current cursor is - // shown. - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(), from = cur, to = cur; - if (!cm.options.lineWrapping) { - from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; - to = Pos(cur.line, cur.ch + 1); - } - cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; - } - - // When an operation has its scrollToPos property set, and another - // scroll action is applied before the end of the operation, this - // 'simulates' scrolling that position into view in a cheap way, so - // that the effect of intermediate scroll commands is not ignored. - function resolveScrollToPos(cm) { - var range = cm.curOp.scrollToPos; - if (range) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); - var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), - Math.min(from.top, to.top) - range.margin, - Math.max(from.right, to.right), - Math.max(from.bottom, to.bottom) + range.margin); - cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); - } - } - - // API UTILITIES - - // Indent the given line. The how parameter can be "smart", - // "add"/null, "subtract", or "prev". When aggressive is false - // (typically set to true for forced single-line indents), empty - // lines are not indented, and places where the mode returns Pass - // are left alone. - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, state; - if (how == null) how = "add"; - if (how == "smart") { - // Fall back to "prev" when the mode doesn't have an indentation - // method. - if (!doc.mode.indent) how = "prev"; - else state = getStateBefore(cm, n); - } - - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) line.stateAfter = null; - var curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) return; - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); - else indentation = 0; - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - - var indentString = "", pos = 0; - if (cm.options.indentWithTabs) - for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} - if (pos < indentation) indentString += spaceStr(indentation - pos); - - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true; - } else { - // Ensure that, if the cursor was in the whitespace at the start - // of the line, it is moved to the end of that space. - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - if (range.head.line == n && range.head.ch < curSpaceString.length) { - var pos = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i, new Range(pos, pos)); - break; - } - } - } - } - - // Utility for applying a change to a line by handle or number, - // returning the number and optionally registering the line as - // changed. - function changeLine(doc, handle, changeType, op) { - var no = handle, line = handle; - if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); - else no = lineNo(handle); - if (no == null) return null; - if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); - return line; - } - - // Helper for deleting text near the selection(s), used to implement - // backspace, delete, and similar functionality. - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, kill = []; - // Build up a set of ranges to kill first, merging overlapping - // ranges. - for (var i = 0; i < ranges.length; i++) { - var toKill = compute(ranges[i]); - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { - var replaced = kill.pop(); - if (cmp(replaced.from, toKill.from) < 0) { - toKill.from = replaced.from; - break; - } - } - kill.push(toKill); - } - // Next, remove those actual ranges. - runInOp(cm, function() { - for (var i = kill.length - 1; i >= 0; i--) - replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); - ensureCursorVisible(cm); - }); - } - - // Used for horizontal relative motion. Dir is -1 or 1 (left or - // right), unit can be "char", "column" (like char, but doesn't - // cross line boundaries), "word" (across next word), or "group" (to - // the start of next group of word or non-word-non-whitespace - // chars). The visually param controls whether, in right-to-left - // text, direction 1 means to move towards the next index in the - // string, or towards the character to the right of the current - // position. The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosH(doc, pos, dir, unit, visually) { - var line = pos.line, ch = pos.ch, origDir = dir; - var lineObj = getLine(doc, line); - var possible = true; - function findNextLine() { - var l = line + dir; - if (l < doc.first || l >= doc.first + doc.size) return (possible = false); - line = l; - return lineObj = getLine(doc, l); - } - function moveOnce(boundToLine) { - var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); - if (next == null) { - if (!boundToLine && findNextLine()) { - if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); - else ch = dir < 0 ? lineObj.text.length : 0; - } else return (possible = false); - } else ch = next; - return true; - } - - if (unit == "char") moveOnce(); - else if (unit == "column") moveOnce(true); - else if (unit == "word" || unit == "group") { - var sawType = null, group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) break; - var cur = lineObj.text.charAt(ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" - : group && cur == "\n" ? "n" - : !group || /\s/.test(cur) ? null - : "p"; - if (group && !first && !type) type = "s"; - if (sawType && sawType != type) { - if (dir < 0) {dir = 1; moveOnce();} - break; - } - - if (type) sawType = type; - if (dir > 0 && !moveOnce(!first)) break; - } - } - var result = skipAtomic(doc, Pos(line, ch), origDir, true); - if (!possible) result.hitSide = true; - return result; - } - - // For relative vertical movement. Dir may be -1 or 1. Unit can be - // "page" or "line". The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, x = pos.left, y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - for (;;) { - var target = coordsChar(cm, x, y); - if (!target.outside) break; - if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } - y += dir * 5; - } - return target; - } - - // EDITOR METHODS - - // The publicly visible API. Note that methodOp(f) means - // 'wrap f in an operation, performed on its `this` parameter'. - - // This is not the complete set of editor methods. Most of the - // methods defined on the Doc type are also injected into - // CodeMirror.prototype, for backwards compatibility and - // convenience. - - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function(){window.focus(); this.display.input.focus();}, - - setOption: function(option, value) { - var options = this.options, old = options[option]; - if (options[option] == value && option != "mode") return; - options[option] = value; - if (optionHandlers.hasOwnProperty(option)) - operation(this, optionHandlers[option])(this, value, old); - }, - - getOption: function(option) {return this.options[option];}, - getDoc: function() {return this.doc;}, - - addKeyMap: function(map, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); - }, - removeKeyMap: function(map) { - var maps = this.state.keyMaps; - for (var i = 0; i < maps.length; ++i) - if (maps[i] == map || maps[i].name == map) { - maps.splice(i, 1); - return true; - } - }, - - addOverlay: methodOp(function(spec, options) { - var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); - if (mode.startState) throw new Error("Overlays may not be stateful."); - this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function(spec) { - var overlays = this.state.overlays; - for (var i = 0; i < overlays.length; ++i) { - var cur = overlays[i].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i, 1); - this.state.modeGen++; - regChange(this); - return; - } - } - }), - - indentLine: methodOp(function(n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; - else dir = dir ? "add" : "subtract"; - } - if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); - }), - indentSelection: methodOp(function(how) { - var ranges = this.doc.sel.ranges, end = -1; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (!range.empty()) { - var from = range.from(), to = range.to(); - var start = Math.max(end, from.line); - end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) - indentLine(this, j, how); - var newRanges = this.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) - replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); - } else if (range.head.line > end) { - indentLine(this, range.head.line, how, true); - end = range.head.line; - if (i == this.doc.sel.primIndex) ensureCursorVisible(this); - } - } - }), - - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(pos, precise) { - return takeToken(this, pos, precise); - }, - - getLineTokens: function(line, precise) { - return takeToken(this, Pos(line), precise, true); - }, - - getTokenTypeAt: function(pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; - var type; - if (ch == 0) type = styles[2]; - else for (;;) { - var mid = (before + after) >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; - else if (styles[mid * 2 + 1] < ch) before = mid + 1; - else { type = styles[mid * 2 + 2]; break; } - } - var cut = type ? type.indexOf("cm-overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); - }, - - getModeAt: function(pos) { - var mode = this.doc.mode; - if (!mode.innerMode) return mode; - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; - }, - - getHelper: function(pos, type) { - return this.getHelpers(pos, type)[0]; - }, - - getHelpers: function(pos, type) { - var found = []; - if (!helpers.hasOwnProperty(type)) return found; - var help = helpers[type], mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) found.push(help[mode[type]]); - } else if (mode[type]) { - for (var i = 0; i < mode[type].length; i++) { - var val = help[mode[type][i]]; - if (val) found.push(val); - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i = 0; i < help._global.length; i++) { - var cur = help._global[i]; - if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) - found.push(cur.val); - } - return found; - }, - - getStateAfter: function(line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); - return getStateBefore(this, line + 1, precise); - }, - - cursorCoords: function(start, mode) { - var pos, range = this.doc.sel.primary(); - if (start == null) pos = range.head; - else if (typeof start == "object") pos = clipPos(this.doc, start); - else pos = start ? range.from() : range.to(); - return cursorCoords(this, pos, mode || "page"); - }, - - charCoords: function(pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page"); - }, - - coordsChar: function(coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); - }, - - lineAtHeight: function(height, mode) { - height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset); - }, - heightAtLine: function(line, mode) { - var end = false, lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) line = this.doc.first; - else if (line > last) { line = last; end = true; } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + - (end ? this.doc.height - heightAtLine(lineObj) : 0); - }, + // Build a line's DOM representation from scratch + function buildLineElement (cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) lineView.bgClass = built.bgClass; + if (built.textClass) lineView.textClass = built.textClass; - defaultTextHeight: function() { return textHeight(this.display); }, - defaultCharWidth: function() { return charWidth(this.display); }, + updateLineClasses(lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } - setGutterMarker: methodOp(function(line, gutterID, value) { - return changeLine(this.doc, line, "gutter", function(line) { - var markers = line.gutterMarkers || (line.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) line.gutterMarkers = null; - return true; - }); - }), - - clearGutter: methodOp(function(gutterID) { - var cm = this, doc = cm.doc, i = doc.first; - doc.iter(function(line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - line.gutterMarkers[gutterID] = null; - regLineChange(cm, i, "gutter"); - if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; - } - ++i; - }); - }), - - lineInfo: function(line) { - if (typeof line == "number") { - if (!isLine(this.doc, line)) return null; - var n = line; - line = getLine(this.doc, line); - if (!line) return null; - } else { - var n = lineNo(line); - if (n == null) return null; - } - return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, - textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, - widgets: line.widgets}; - }, - - getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, - - addWidget: function(pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - // Default to positioning above (if specified and possible); otherwise default to positioning below - if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) - top = pos.top - node.offsetHeight; - else if (pos.bottom + node.offsetHeight <= vspace) - top = pos.bottom; - if (left + node.offsetWidth > hspace) - left = hspace - node.offsetWidth; - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") left = 0; - else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; - node.style.left = left + "px"; - } - if (scroll) - scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); - }, - - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - - execCommand: function(cmd) { - if (commands.hasOwnProperty(cmd)) - return commands[cmd](this); - }, - - triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), - - findPosH: function(from, amount, unit, visually) { - var dir = 1; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) break; - } - return cur; - }, - - moveH: methodOp(function(dir, unit) { - var cm = this; - cm.extendSelectionsBy(function(range) { - if (cm.display.shift || cm.doc.extend || range.empty()) - return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); - else - return dir < 0 ? range.from() : range.to(); - }, sel_move); - }), - - deleteH: methodOp(function(dir, unit) { - var sel = this.doc.sel, doc = this.doc; - if (sel.somethingSelected()) - doc.replaceSelection("", null, "+delete"); - else - deleteNearSelection(this, function(range) { - var other = findPosH(doc, range.head, dir, unit, false); - return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; - }); - }), - - findPosV: function(from, amount, unit, goalColumn) { - var dir = 1, x = goalColumn; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) x = coords.left; - else coords.left = x; - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) break; - } - return cur; - }, - - moveV: methodOp(function(dir, unit) { - var cm = this, doc = this.doc, goals = []; - var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function(range) { - if (collapse) - return dir < 0 ? range.from() : range.to(); - var headPos = cursorCoords(cm, range.head, "div"); - if (range.goalColumn != null) headPos.left = range.goalColumn; - goals.push(headPos.left); - var pos = findPosV(cm, headPos, dir, unit); - if (unit == "page" && range == doc.sel.primary()) - addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); - return pos; - }, sel_move); - if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) - doc.sel.ranges[i].goalColumn = goals[i]; - }), - - // Find the word at the given position (as returned by coordsChar). - findWordAt: function(pos) { - var doc = this.doc, line = getLine(doc, pos.line).text; - var start = pos.ch, end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) - ? function(ch) { return isWordChar(ch, helper); } - : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} - : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; - while (start > 0 && check(line.charAt(start - 1))) --start; - while (end < line.length && check(line.charAt(end))) ++end; - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)); - }, - - toggleOverwrite: function(value) { - if (value != null && value == this.state.overwrite) return; - if (this.state.overwrite = !this.state.overwrite) - addClass(this.display.cursorDiv, "CodeMirror-overwrite"); - else - rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); - - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function() { return this.display.input.getField() == activeElt(); }, - - scrollTo: methodOp(function(x, y) { - if (x != null || y != null) resolveScrollToPos(this); - if (x != null) this.curOp.scrollLeft = x; - if (y != null) this.curOp.scrollTop = y; - }), - getScrollInfo: function() { - var scroller = this.display.scroller; - return {left: scroller.scrollLeft, top: scroller.scrollTop, - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, - clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; - }, - - scrollIntoView: methodOp(function(range, margin) { - if (range == null) { - range = {from: this.doc.sel.primary().head, to: null}; - if (margin == null) margin = this.options.cursorScrollMargin; - } else if (typeof range == "number") { - range = {from: Pos(range, 0), to: null}; - } else if (range.from == null) { - range = {from: range, to: null}; - } - if (!range.to) range.to = range.from; - range.margin = margin || 0; - - if (range.from.line != null) { - resolveScrollToPos(this); - this.curOp.scrollToPos = range; - } else { - var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), - Math.min(range.from.top, range.to.top) - range.margin, - Math.max(range.from.right, range.to.right), - Math.max(range.from.bottom, range.to.bottom) + range.margin); - this.scrollTo(sPos.scrollLeft, sPos.scrollTop); - } - }), - - setSize: methodOp(function(width, height) { - var cm = this; - function interpret(val) { - return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; - } - if (width != null) cm.display.wrapper.style.width = interpret(width); - if (height != null) cm.display.wrapper.style.height = interpret(height); - if (cm.options.lineWrapping) clearLineMeasurementCache(this); - var lineNo = cm.display.viewFrom; - cm.doc.iter(lineNo, cm.display.viewTo, function(line) { - if (line.widgets) for (var i = 0; i < line.widgets.length; i++) - if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } - ++lineNo; - }); - cm.curOp.forceUpdate = true; - signal(cm, "refresh", this); - }), - - operation: function(f){return runInOp(this, f);}, - - refresh: methodOp(function() { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) - estimateLineHeights(this); - signal(this, "refresh", this); - }), - - swapDoc: methodOp(function(doc) { - var old = this.doc; - old.cm = null; - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - this.scrollTo(doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old; - }), - - getInputField: function(){return this.display.input.getField();}, - getWrapperElement: function(){return this.display.wrapper;}, - getScrollerElement: function(){return this.display.scroller;}, - getGutterElement: function(){return this.display.gutters;} - }; - eventMixin(CodeMirror); - - // OPTION DEFAULTS - - // The default configuration options. - var defaults = CodeMirror.defaults = {}; - // Functions to run when options are changed. - var optionHandlers = CodeMirror.optionHandlers = {}; - - function option(name, deflt, handle, notOnInit) { - CodeMirror.defaults[name] = deflt; - if (handle) optionHandlers[name] = - notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; - } - - // Passed to option handlers when there is no old value. - var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; - - // These two are, on init, called from the constructor because they - // have to be initialized before the editor can start at all. - option("value", "", function(cm, val) { - cm.setValue(val); - }, true); - option("mode", null, function(cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function(cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); - if (old != CodeMirror.Init) cm.refresh(); - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function() { - throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME - }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - - option("theme", "default", function(cm) { - themeChanged(cm); - guttersChanged(cm); - }, true); - option("keyMap", "default", function(cm, val, old) { - var next = getKeyMap(val); - var prev = old != CodeMirror.Init && getKeyMap(old); - if (prev && prev.detach) prev.detach(cm, next); - if (next.attach) next.attach(cm, prev || null); - }); - option("extraKeys", null); - - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("fixedGutter", true, function(cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); - option("scrollbarStyle", "native", function(cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("firstLineNumber", 1, guttersChanged, true); - option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); - option("showCursorWhenSelecting", false, updateSelection, true); - - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - - option("readOnly", false, function(cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - cm.display.disabled = true; - } else { - cm.display.disabled = false; - if (!val) cm.display.input.reset(); - } - }); - option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); - option("dragDrop", true, dragDropChanged); - - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function(cm){cm.refresh();}, true); - option("maxHighlightLength", 10000, resetModeState, true); - option("moveInputWithCursor", true, function(cm, val) { - if (!val) cm.display.input.resetPosition(); - }); - - option("tabindex", null, function(cm, val) { - cm.display.input.getField().tabIndex = val || ""; - }); - option("autofocus", null); - - // MODE DEFINITION AND QUERYING - - // Known modes, by name and by MIME - var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - CodeMirror.defineMode = function(name, mode) { - if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; - if (arguments.length > 2) - mode.dependencies = Array.prototype.slice.call(arguments, 2); - modes[name] = mode; - }; - - CodeMirror.defineMIME = function(mime, spec) { - mimeModes[mime] = spec; - }; - - // Given a MIME type, a {name, ...options} config object, or a name - // string, return a mode config object. - CodeMirror.resolveMode = function(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") found = {name: found}; - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return CodeMirror.resolveMode("application/xml"); - } - if (typeof spec == "string") return {name: spec}; - else return spec || {name: "null"}; - }; - - // Given a mode spec (anything that resolveMode accepts), find and - // initialize an actual mode object. - CodeMirror.getMode = function(options, spec) { - var spec = CodeMirror.resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) return CodeMirror.getMode(options, "text/plain"); - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop in exts) { - if (!exts.hasOwnProperty(prop)) continue; - if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; - modeObj[prop] = exts[prop]; - } - } - modeObj.name = spec.name; - if (spec.helperType) modeObj.helperType = spec.helperType; - if (spec.modeProps) for (var prop in spec.modeProps) - modeObj[prop] = spec.modeProps[prop]; - - return modeObj; - }; - - // Minimal default mode. - CodeMirror.defineMode("null", function() { - return {token: function(stream) {stream.skipToEnd();}}; - }); - CodeMirror.defineMIME("text/plain", "null"); - - // This can be used to attach properties to mode objects from - // outside the actual mode definition. - var modeExtensions = CodeMirror.modeExtensions = {}; - CodeMirror.extendMode = function(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); - copyObj(properties, exts); - }; - - // EXTENSIONS - - CodeMirror.defineExtension = function(name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function(name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.defineOption = option; - - var initHooks = []; - CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; - - var helpers = CodeMirror.helpers = {}; - CodeMirror.registerHelper = function(type, name, value) { - if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; - helpers[type][name] = value; - }; - CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { - CodeMirror.registerHelper(type, name, value); - helpers[type]._global.push({pred: predicate, val: value}); - }; - - // MODE STATE HANDLING - - // Utility functions for working with state. Exported because nested - // modes need to do this for their inner modes. - - var copyState = CodeMirror.copyState = function(mode, state) { - if (state === true) return state; - if (mode.copyState) return mode.copyState(state); - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) val = val.concat([]); - nstate[n] = val; - } - return nstate; - }; - - var startState = CodeMirror.startState = function(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - }; - - // Given a mode and a state (for that mode), find the inner mode and - // state at the position that the state refers to. - CodeMirror.innerMode = function(mode, state) { - while (mode.innerMode) { - var info = mode.innerMode(state); - if (!info || info.mode == mode) break; - state = info.state; - mode = info.mode; - } - return info || {mode: mode, state: state}; - }; - - // STANDARD COMMANDS - - // Commands are parameter-less actions that can be performed on an - // editor, mostly used for keybindings. - var commands = CodeMirror.commands = { - selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, - singleSelection: function(cm) { - cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); - }, - killLine: function(cm) { - deleteNearSelection(cm, function(range) { - if (range.empty()) { - var len = getLine(cm.doc, range.head.line).text.length; - if (range.head.ch == len && range.head.line < cm.lastLine()) - return {from: range.head, to: Pos(range.head.line + 1, 0)}; - else - return {from: range.head, to: Pos(range.head.line, len)}; - } else { - return {from: range.from(), to: range.to()}; - } - }); - }, - deleteLine: function(cm) { - deleteNearSelection(cm, function(range) { - return {from: Pos(range.from().line, 0), - to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; - }); - }, - delLineLeft: function(cm) { - deleteNearSelection(cm, function(range) { - return {from: Pos(range.from().line, 0), to: range.from()}; - }); - }, - delWrappedLineLeft: function(cm) { - deleteNearSelection(cm, function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var leftPos = cm.coordsChar({left: 0, top: top}, "div"); - return {from: leftPos, to: range.from()}; - }); - }, - delWrappedLineRight: function(cm) { - deleteNearSelection(cm, function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - return {from: range.from(), to: rightPos }; - }); - }, - undo: function(cm) {cm.undo();}, - redo: function(cm) {cm.redo();}, - undoSelection: function(cm) {cm.undoSelection();}, - redoSelection: function(cm) {cm.redoSelection();}, - goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, - goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, - goLineStart: function(cm) { - cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, - {origin: "+move", bias: 1}); - }, - goLineStartSmart: function(cm) { - cm.extendSelectionsBy(function(range) { - return lineStartSmart(cm, range.head); - }, {origin: "+move", bias: 1}); - }, - goLineEnd: function(cm) { - cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, - {origin: "+move", bias: -1}); - }, - goLineRight: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - }, sel_move); - }, - goLineLeft: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - return cm.coordsChar({left: 0, top: top}, "div"); - }, sel_move); - }, - goLineLeftSmart: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var pos = cm.coordsChar({left: 0, top: top}, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); - return pos; - }, sel_move); - }, - goLineUp: function(cm) {cm.moveV(-1, "line");}, - goLineDown: function(cm) {cm.moveV(1, "line");}, - goPageUp: function(cm) {cm.moveV(-1, "page");}, - goPageDown: function(cm) {cm.moveV(1, "page");}, - goCharLeft: function(cm) {cm.moveH(-1, "char");}, - goCharRight: function(cm) {cm.moveH(1, "char");}, - goColumnLeft: function(cm) {cm.moveH(-1, "column");}, - goColumnRight: function(cm) {cm.moveH(1, "column");}, - goWordLeft: function(cm) {cm.moveH(-1, "word");}, - goGroupRight: function(cm) {cm.moveH(1, "group");}, - goGroupLeft: function(cm) {cm.moveH(-1, "group");}, - goWordRight: function(cm) {cm.moveH(1, "word");}, - delCharBefore: function(cm) {cm.deleteH(-1, "char");}, - delCharAfter: function(cm) {cm.deleteH(1, "char");}, - delWordBefore: function(cm) {cm.deleteH(-1, "word");}, - delWordAfter: function(cm) {cm.deleteH(1, "word");}, - delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, - delGroupAfter: function(cm) {cm.deleteH(1, "group");}, - indentAuto: function(cm) {cm.indentSelection("smart");}, - indentMore: function(cm) {cm.indentSelection("add");}, - indentLess: function(cm) {cm.indentSelection("subtract");}, - insertTab: function(cm) {cm.replaceSelection("\t");}, - insertSoftTab: function(cm) { - var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; - for (var i = 0; i < ranges.length; i++) { - var pos = ranges[i].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); - } - cm.replaceSelections(spaces); - }, - defaultTab: function(cm) { - if (cm.somethingSelected()) cm.indentSelection("add"); - else cm.execCommand("insertTab"); - }, - transposeChars: function(cm) { - runInOp(cm, function() { - var ranges = cm.listSelections(), newSel = []; - for (var i = 0; i < ranges.length; i++) { - var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); - if (cur.ch > 0) { - cur = new Pos(cur.line, cur.ch + 1); - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), - Pos(cur.line, cur.ch - 2), cur, "+transpose"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) - cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1), - Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); - } - } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); - }, - newlineAndIndent: function(cm) { - runInOp(cm, function() { - var len = cm.listSelections().length; - for (var i = 0; i < len; i++) { - var range = cm.listSelections()[i]; - cm.replaceRange("\n", range.anchor, range.head, "+input"); - cm.indentLine(range.from().line + 1, null, true); - ensureCursorVisible(cm); - } - }); - }, - toggleOverwrite: function(cm) {cm.toggleOverwrite();} - }; - - - // STANDARD KEYMAPS - - var keyMap = CodeMirror.keyMap = {}; - - keyMap.basic = { - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", - "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", - "Esc": "singleSelection" - }; - // Note that the save and find-related commands aren't defined by - // default. User code or addons can define them. Unknown commands - // are simply ignored. - keyMap.pcDefault = { - "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", - "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", - "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", - "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", - fallthrough: "basic" - }; - // Very basic readline/emacs-style bindings, which are standard on Mac. - keyMap.emacsy = { - "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", - "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", - "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", - "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", - "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", - "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", - fallthrough: ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - - // KEYMAP DISPATCH - - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i = 0; i < parts.length - 1; i++) { - var mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; - else if (/^a(lt)?$/i.test(mod)) alt = true; - else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; - else if (/^s(hift)$/i.test(mod)) shift = true; - else throw new Error("Unrecognized modifier name: " + mod); - } - if (alt) name = "Alt-" + name; - if (ctrl) name = "Ctrl-" + name; - if (cmd) name = "Cmd-" + name; - if (shift) name = "Shift-" + name; - return name; - } - - // This is a kludge to keep keymaps mostly working as raw objects - // (backwards compatibility) while at the same time support features - // like normalization and multi-stroke key bindings. It compiles a - // new normalized keymap, and then updates the old object to reflect - // this. - CodeMirror.normalizeKeyMap = function(keymap) { - var copy = {}; - for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; - if (value == "...") { delete keymap[keyname]; continue; } - - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i = 0; i < keys.length; i++) { - var val, name; - if (i == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) copy[name] = val; - else if (prev != val) throw new Error("Inconsistent bindings for " + name); - } - delete keymap[keyname]; - } - for (var prop in copy) keymap[prop] = copy[prop]; - return keymap; - }; - - var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { - map = getKeyMap(map); - var found = map.call ? map.call(key, context) : map[key]; - if (found === false) return "nothing"; - if (found === "...") return "multi"; - if (found != null && handle(found)) return "handled"; - - if (map.fallthrough) { - if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") - return lookupKey(key, map.fallthrough, handle, context); - for (var i = 0; i < map.fallthrough.length; i++) { - var result = lookupKey(key, map.fallthrough[i], handle, context); - if (result) return result; - } - } - }; - - // Modifier key presses don't count as 'real' key presses for the - // purpose of keymap fallthrough. - var isModifierKey = CodeMirror.isModifierKey = function(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - }; - - // Look up the name of a key as indicated by an event object. - var keyName = CodeMirror.keyName = function(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) return false; - var base = keyNames[event.keyCode], name = base; - if (name == null || event.altGraphKey) return false; - if (event.altKey && base != "Alt") name = "Alt-" + name; - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; - if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; - return name; - }; - - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val; - } - - // FROMTEXTAREA - - CodeMirror.fromTextArea = function(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) - options.tabindex = textarea.tabIndex; - if (!options.placeholder && textarea.placeholder) - options.placeholder = textarea.placeholder; - // Set autofocus to true if this textarea is focused, or if it has - // autofocus and no other element is focused. - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || - textarea.getAttribute("autofocus") != null && hasFocus == document.body; + // A lineView may contain multiple logical lines (when merged by + // collapsed spans). The widgets for all of them need to be drawn. + function insertLineWidgets (cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { + for (var i = 0; i < lineView.rest.length; i++) {insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);} + } } - function save() {textarea.value = cm.getValue();} - if (textarea.form) { - on(textarea.form, "submit", save); - // Deplorable hack to make the submit method do the right thing. - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form, realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function() { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch(e) {} - } - } - - options.finishInit = function(cm) { - cm.save = save; - cm.getTextArea = function() { return textarea; }; - cm.toTextArea = function() { - cm.toTextArea = isNaN; // Prevent this from being ran twice - save(); - textarea.parentNode.removeChild(cm.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (typeof textarea.form.submit == "function") - textarea.form.submit = realSubmit; + function insertLineWidgetsFor (cm, line, lineView, dims, allowAbove) { + if (!line.widgets) return; + var wrap = ensureLineWrapped(lineView); + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); + if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) {wrap.insertBefore(node, lineView.gutter || lineView.text);} else {wrap.appendChild(node);} + signalLater(widget, "redraw"); + } + } + + function positionLineWidget (widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; } - }; + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } + + // POSITION OBJECT + + // A Pos instance represents a position within the text. + var Pos = CodeMirror.Pos = function (line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; }; - textarea.style.display = "none"; - var cm = CodeMirror(function(node) { - textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - return cm; - }; - - // STRING STREAM - - // Fed to the mode parsers, provides helper functions to make - // parsers more succinct. - - var StringStream = CodeMirror.StringStream = function(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - }; - - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == this.lineStart;}, - peek: function() {return this.string.charAt(this.pos) || undefined;}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }, - indentation: function() { - return countColumn(this.string, null, this.tabSize) - - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) this.pos += pattern.length; - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) return null; - if (match && consume !== false) this.pos += match[0].length; - return match; - } - }, - current: function(){return this.string.slice(this.start, this.pos);}, - hideFirstChars: function(n, inner) { - this.lineStart += n; - try { return inner(); } - finally { this.lineStart -= n; } - } - }; - - // TEXTMARKERS - - // Created with markText and setBookmark methods. A TextMarker is a - // handle that can be used to clear or find a marked position in the - // document. Line objects hold arrays (markedSpans) containing - // {from, to, marker} object pointing to such marker objects, and - // indicating that such a marker is present on that line. Multiple - // lines may point to the same marker when it spans across lines. - // The spans will have null for their from/to properties when the - // marker continues beyond the start/end of the line. Markers have - // links back to the lines they currently touch. - - var nextMarkerId = 0; - - var TextMarker = CodeMirror.TextMarker = function(doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - eventMixin(TextMarker); - - // Clear the marker. - TextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - var cm = this.doc.cm, withOp = cm && !cm.curOp; - if (withOp) startOperation(cm); - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) signalLater(this, "clear", found.from, found.to); - } - var min = null, max = null; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); - else if (cm) { - if (span.to != null) max = lineNo(line); - if (span.from != null) min = lineNo(line); - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) - updateLineHeight(line, textHeight(cm.display)); - } - if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { - var visual = visualLine(this.lines[i]), len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } - - if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) reCheckSelection(cm.doc); - } - if (cm) signalLater(cm, "markerCleared", cm, this); - if (withOp) endOperation(cm); - if (this.parent) this.parent.clear(); - }; - - // Find the position of the marker in the document. Returns a {from, - // to} object by default. Side can be passed to get a specific side - // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the - // Pos objects returned contain a line object, rather than a line - // number (used to prevent looking up the same line twice). - TextMarker.prototype.find = function(side, lineObj) { - if (side == null && this.type == "bookmark") side = 1; - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) return from; - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) return to; - } - } - return from && {from: from, to: to}; - }; - - // Signals that the marker's widget changed, and surrounding layout - // should be recomputed. - TextMarker.prototype.changed = function() { - var pos = this.find(-1, true), widget = this, cm = this.doc.cm; - if (!pos || !cm) return; - runInOp(cm, function() { - var line = pos.line, lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) - updateLineHeight(line, line.height + dHeight); - } - }); - }; - - TextMarker.prototype.attachLine = function(line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) - (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); - } - this.lines.push(line); - }; - TextMarker.prototype.detachLine = function(line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - - // Collapsed markers have unique ids, in order to be able to order - // them, which is needed for uniquely determining an outer marker - // when they overlap (they may nest, but not partially overlap). - var nextMarkerId = 0; - - // Create a marker, wire it up to the right lines, and - function markText(doc, from, to, options, type) { - // Shared markers (across linked documents) are handled separately - // (markTextShared will call out to this again, once per - // document). - if (options && options.shared) return markTextShared(doc, from, to, options, type); - // Ensure we are in an operation. - if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); - - var marker = new TextMarker(doc, type), diff = cmp(from, to); - if (options) copyObj(options, marker, false); - // Don't connect empty markers unless clearWhenEmpty is false - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) - return marker; - if (marker.replacedWith) { - // Showing up as a widget implies collapsed (widget replaces text) - marker.collapsed = true; - marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); - if (options.insertLeft) marker.widgetNode.insertLeft = true; - } - if (marker.collapsed) { - if (conflictingCollapsedRange(doc, from.line, from, to, marker) || - from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) - throw new Error("Inserting collapsed marker partially overlapping an existing one"); - sawCollapsedSpans = true; - } - - if (marker.addToHistory) - addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); - - var curLine = from.line, cm = doc.cm, updateMaxLine; - doc.iter(curLine, to.line + 1, function(line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) - updateMaxLine = true; - if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); - addMarkedSpan(line, new MarkedSpan(marker, - curLine == from.line ? from.ch : null, - curLine == to.line ? to.ch : null)); - ++curLine; - }); - // lineIsHidden depends on the presence of the spans, so needs a second pass - if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { - if (lineIsHidden(doc, line)) updateLineHeight(line, 0); - }); + // Compare two positions, return 0 if they are the same, a negative + // number when a is less, and a positive number otherwise. + var cmp = CodeMirror.cmpPos = function (a, b) { return a.line - b.line || a.ch - b.ch; }; - if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); - - if (marker.readOnly) { - sawReadOnlySpans = true; - if (doc.history.done.length || doc.history.undone.length) - doc.clearHistory(); - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - // Sync editor state - if (updateMaxLine) cm.curOp.updateMaxLine = true; - if (marker.collapsed) - regChange(cm, from.line, to.line + 1); - else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) - for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); - if (marker.atomic) reCheckSelection(cm.doc); - signalLater(cm, "markerAdded", cm, marker); - } - return marker; - } - - // SHARED TEXTMARKERS - - // A shared marker spans multiple linked documents. It is - // implemented as a meta-marker-object controlling multiple normal - // markers. - var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { - this.markers = markers; - this.primary = primary; - for (var i = 0; i < markers.length; ++i) - markers[i].parent = this; - }; - eventMixin(SharedTextMarker); - - SharedTextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - this.explicitlyCleared = true; - for (var i = 0; i < this.markers.length; ++i) - this.markers[i].clear(); - signalLater(this, "clear"); - }; - SharedTextMarker.prototype.find = function(side, lineObj) { - return this.primary.find(side, lineObj); - }; - - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function(doc) { - if (widget) options.widgetNode = widget.cloneNode(true); - markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); - for (var i = 0; i < doc.linked.length; ++i) - if (doc.linked[i].isParent) return; - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary); - } - - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), - function(m) { return m.parent; }); - } - - function copySharedMarkers(doc, markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], pos = marker.find(); - var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; - } - } - } - - function detachSharedMarkers(markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], linked = [marker.primary.doc];; - linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } - } - } - } - - // TEXTMARKER SPANS - - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; this.to = to; - } - - // Search an array of spans for a span matching the given marker. - function getMarkedSpanFor(spans, marker) { - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.marker == marker) return span; - } - } - // Remove a span from an array, returning undefined if no spans are - // left (we don't store arrays for lines without spans). - function removeMarkedSpan(spans, span) { - for (var r, i = 0; i < spans.length; ++i) - if (spans[i] != span) (r || (r = [])).push(spans[i]); - return r; - } - // Add a span to a line. - function addMarkedSpan(line, span) { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - span.marker.attachLine(line); - } - - // Used for the algorithm that adjusts markers for a change in the - // document. These functions cut an array of spans at a given - // character position, returning an array of remaining chunks (or - // undefined if nothing remains). - function markedSpansBefore(old, startCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); - } - } - return nw; - } - function markedSpansAfter(old, endCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, - span.to == null ? null : span.to - endCh)); - } - } - return nw; - } - - // Given a change object, compute the new set of marker spans that - // cover the line in which the change took place. Removes spans - // entirely within the change, reconnects spans belonging to the - // same marker that appear on both sides of the change, and cuts off - // spans partially within the change. Returns an array of span - // arrays with one element for each line in (after) the change. - function stretchSpansOverChange(doc, change) { - if (change.full) return null; - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) return null; - - var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - - // Next, merge those two ends - var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - // Fix up .to properties of first - for (var i = 0; i < first.length; ++i) { - var span = first[i]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) span.to = startCh; - else if (sameLine) span.to = found.to == null ? null : found.to + offset; - } - } - } - if (last) { - // Fix up .from in last (or move them into first in case of sameLine) - for (var i = 0; i < last.length; ++i) { - var span = last[i]; - if (span.to != null) span.to += offset; - if (span.from == null) { - var found = getMarkedSpanFor(first, span.marker); - if (!found) { - span.from = offset; - if (sameLine) (first || (first = [])).push(span); - } - } else { - span.from += offset; - if (sameLine) (first || (first = [])).push(span); - } - } - } - // Make sure we didn't create any zero-length spans - if (first) first = clearEmptySpans(first); - if (last && last != first) last = clearEmptySpans(last); - - var newMarkers = [first]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = change.text.length - 2, gapMarkers; - if (gap > 0 && first) - for (var i = 0; i < first.length; ++i) - if (first[i].to == null) - (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); - for (var i = 0; i < gap; ++i) - newMarkers.push(gapMarkers); - newMarkers.push(last); - } - return newMarkers; - } - - // Remove spans that are empty and don't have a clearWhenEmpty - // option of false. - function clearEmptySpans(spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) - spans.splice(i--, 1); - } - if (!spans.length) return null; - return spans; - } - - // Used for un/re-doing changes from the history. Combines the - // result of computing the existing spans with the set of spans that - // existed in the history (so that deleting around a span and then - // undoing brings back the span). - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) return stretched; - if (!stretched) return old; - - for (var i = 0; i < old.length; ++i) { - var oldCur = old[i], stretchCur = stretched[i]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) - if (oldCur[k].marker == span.marker) continue spans; - oldCur.push(span); - } - } else if (stretchCur) { - old[i] = stretchCur; - } - } - return old; - } - - // Used to 'clip' out readOnly ranges when making a change. - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function(line) { - if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { - var mark = line.markedSpans[i].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) - (markers || (markers = [])).push(mark); - } - }); - if (!markers) return null; - var parts = [{from: from, to: to}]; - for (var i = 0; i < markers.length; ++i) { - var mk = markers[i], m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; - var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) - newParts.push({from: p.from, to: m.from}); - if (dto > 0 || !mk.inclusiveRight && !dto) - newParts.push({from: m.to, to: p.to}); - parts.splice.apply(parts, newParts); - j += newParts.length - 1; - } - } - return parts; - } - - // Connect or disconnect spans from a line. - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.detachLine(line); - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.attachLine(line); - line.markedSpans = spans; - } - - // Helpers used when computing which overlapping collapsed span - // counts as the larger one. - function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } - function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } - - // Returns a number indicating which of two overlapping collapsed - // spans is larger (and thus includes the other). Falls back to - // comparing ids when the spans cover exactly the same range. - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) return lenDiff; - var aPos = a.find(), bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) return -fromCmp; - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) return toCmp; - return b.id - a.id; - } - - // Find out whether a line ends or starts in a collapsed span. If - // so, return the marker for that span. - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) - found = sp.marker; - } - return found; - } - function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } - function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } - - // Test whether there exists a collapsed span that partially - // overlaps (covers the start or end, but not both) of a new span. - // Such overlap is not allowed. - function conflictingCollapsedRange(doc, lineNo, from, to, marker) { - var line = getLine(doc, lineNo); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (!sp.marker.collapsed) continue; - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; - if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || - fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) - return true; - } - } - - // A visual line is a line as drawn on the screen. Folding, for - // example, can cause multiple logical lines to appear on the same - // visual line. This finds the start of the visual line that the - // given line is part of (usually that is the line itself). - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) - line = merged.find(-1, true).line; - return line; - } - - // Returns an array of logical lines that continue the visual line - // started by the argument, or undefined if there are no such lines. - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - (lines || (lines = [])).push(line); - } - return lines; - } - - // Get the line number of the start of the visual line that the - // given line number is part of. - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), vis = visualLine(line); - if (line == vis) return lineN; - return lineNo(vis); - } - // Get the line number of the start of the next visual line after - // the given line. - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) return lineN; - var line = getLine(doc, lineN), merged; - if (!lineIsHidden(doc, line)) return lineN; - while (merged = collapsedSpanAtEnd(line)) - line = merged.find(1, true).line; - return lineNo(line) + 1; - } - - // Compute whether a line is hidden. Lines count as hidden when they - // are part of a visual line that starts with another line, or when - // they are entirely covered by collapsed, non-widget span. - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) continue; - if (sp.from == null) return true; - if (sp.marker.widgetNode) continue; - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) - return true; + function copyPos (x) {return Pos(x.line, x.ch);} + function maxPos (a, b) { return cmp(a, b) < 0 ? b : a; } + function minPos (a, b) { return cmp(a, b) < 0 ? a : b; } + + // INPUT HANDLING + + function ensureFocus (cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); - } - if (span.marker.inclusiveRight && span.to == line.text.length) - return true; - for (var sp, i = 0; i < line.markedSpans.length; ++i) { - sp = line.markedSpans[i]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && - (sp.to == null || sp.to != span.from) && - (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && - lineIsHiddenInner(doc, line, sp)) return true; + + function isReadOnly (cm) { + return cm.options.readOnly || cm.doc.cantEdit; } - } - - // LINE WIDGETS - - // Line widgets are block elements displayed above or below a line. - - var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { - if (options) for (var opt in options) if (options.hasOwnProperty(opt)) - this[opt] = options[opt]; - this.doc = doc; - this.node = node; - }; - eventMixin(LineWidget); - - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) - addToScrollPos(cm, null, diff); - } - - LineWidget.prototype.clear = function() { - var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); - if (no == null || !ws) return; - for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); - if (!ws.length) line.widgets = null; - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) runInOp(cm, function() { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - }; - LineWidget.prototype.changed = function() { - var oldH = this.height, cm = this.doc.cm, line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) return; - updateLineHeight(line, line.height + diff); - if (cm) runInOp(cm, function() { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - }); - }; - - function widgetHeight(widget) { - if (widget.height != null) return widget.height; - var cm = widget.doc.cm; - if (!cm) return 0; - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) - parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; - if (widget.noHScroll) - parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); - } - return widget.height = widget.node.offsetHeight; - } - - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) cm.display.alignWidgets = true; - changeLine(doc, handle, "widget", function(line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) widgets.push(widget); - else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) addToScrollPos(cm, null, widget.height); - cm.curOp.forceUpdate = true; - } - return true; - }); - return widget; - } - - // LINE DATA STRUCTURE - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight ? estimateHeight(this) : 1; - }; - eventMixin(Line); - Line.prototype.lineNo = function() { return lineNo(this); }; - - // Change the content (text, markers) of a line. Automatically - // invalidates cached information and tries to re-estimate the - // line's height. - function updateLine(line, text, markedSpans, estimateHeight) { - line.text = text; - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - if (line.order != null) line.order = null; - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight ? estimateHeight(line) : 1; - if (estHeight != line.height) updateLineHeight(line, estHeight); - } - - // Detach a line from the document tree and its markers. - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - - function extractLineClasses(type, output) { - if (type) for (;;) { - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); - if (!lineClass) break; - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); - var prop = lineClass[1] ? "bgClass" : "textClass"; - if (output[prop] == null) - output[prop] = lineClass[2]; - else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) - output[prop] += " " + lineClass[2]; - } - return type; - } - - function callBlankLine(mode, state) { - if (mode.blankLine) return mode.blankLine(state); - if (!mode.innerMode) return; - var inner = CodeMirror.innerMode(mode, state); - if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); - } - - function readToken(mode, stream, state, inner) { - for (var i = 0; i < 10; i++) { - if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; - var style = mode.token(stream, state); - if (stream.pos > stream.start) return style; - } - throw new Error("Mode " + mode.name + " failed to advance stream."); - } - - // Utility for getTokenAt and getLineTokens - function takeToken(cm, pos, precise, asArray) { - function getObj(copy) { - return {start: stream.start, end: stream.pos, - string: stream.current(), - type: style || null, - state: copy ? copyState(doc.mode, state) : state}; - } - - var doc = cm.doc, mode = doc.mode, style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize), tokens; - if (asArray) tokens = []; - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, state); - if (asArray) tokens.push(getObj(true)); - } - return asArray ? tokens : getObj(); - } - - // Run the given mode's parser over a line, calling f for each token. - function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; - var curStart = 0, curStyle = null; - var stream = new StringStream(text, cm.options.tabSize), style; - var inner = cm.options.addModeClass && [null]; - if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) processLine(cm, text, state, stream.pos); - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); - } - if (inner) { - var mName = inner[0].name; - if (mName) style = "m-" + (style ? mName + " " + style : mName); - } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 50000); - f(curStart, curStyle); - } - curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - // Webkit seems to refuse to render text nodes longer than 57444 characters - var pos = Math.min(stream.pos, curStart + 50000); - f(pos, curStyle); - curStart = pos; - } - } - - // Compute a style array (an array starting with a mode generation - // -- for invalidation -- followed by pairs of end positions and - // style strings), which is used to highlight the tokens on the - // line. - function highlightLine(cm, line, state, forceToEnd) { - // A styles array always starts with a number identifying the - // mode/overlays that it is based on (for easy invalidation). - var st = [cm.state.modeGen], lineClasses = {}; - // Compute the base array of styles - runMode(cm, line.text, cm.doc.mode, state, function(end, style) { - st.push(end, style); - }, lineClasses, forceToEnd); - - // Run overlays, adjust style array. - for (var o = 0; o < cm.state.overlays.length; ++o) { - var overlay = cm.state.overlays[o], i = 1, at = 0; - runMode(cm, line.text, overlay.mode, true, function(end, style) { - var start = i; - // Ensure there's a token end at the current position, and that i points at it - while (at < end) { - var i_end = st[i]; - if (i_end > end) - st.splice(i, 1, end, st[i+1], i_end); - i += 2; - at = Math.min(end, i_end); - } - if (!style) return; - if (overlay.opaque) { - st.splice(start, i - start, end, "cm-overlay " + style); - i = start + 2; - } else { - for (; start < i; start += 2) { - var cur = st[start+1]; - st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; - } - } - }, lineClasses); - } - - return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; - } - - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); - line.styles = result.styles; - if (result.classes) line.styleClasses = result.classes; - else if (line.styleClasses) line.styleClasses = null; - if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; - } - return line.styles; - } - - // Lightweight form of highlight -- proceed over this line and - // update state, but don't save a style array. Used for lines that - // aren't currently visible. - function processLine(cm, text, state, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize); - stream.start = stream.pos = startAt || 0; - if (text == "") callBlankLine(mode, state); - while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { - readToken(mode, stream, state); - stream.start = stream.pos; - } - } - - // Convert a style as returned by a mode (either null, or a string - // containing one or more styles) to a CSS style. This is cached, - // and also looks for line-wide styles. - var styleToClassCache = {}, styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) return null; - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || - (cache[style] = style.replace(/\S+/g, "cm-$&")); - } - - // Render the DOM representation of the text of a line. Also builds - // up a 'line map', which points at the DOM nodes that represent - // specific stretches of text, and is used by the measuring code. - // The returned object contains the DOM node, this map, and - // information about line-wide styles that were set by the mode. - function buildLineContent(cm, lineView) { - // The padding-right forces the element to have a 'border', which - // is needed on Webkit to be able to get line-level bounding - // rectangles for it (in measureChar). - var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, - col: 0, pos: 0, cm: cm, - splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; - lineView.measure = {}; - - // Iterate over the logical lines that make up this visual line. - for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { - var line = i ? lineView.rest[i - 1] : lineView.line, order; - builder.pos = 0; - builder.addToken = buildToken; - // Optionally wire in some hacks into the token-rendering - // algorithm, to deal with browser quirks. - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) - builder.addToken = buildTokenBadBidi(builder.addToken, order); - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) - builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); - if (line.styleClasses.textClass) - builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); - } - - // Ensure at least a single node is present, for measuring. - if (builder.map.length == 0) - builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); - - // Store the map and a cache object for the current logical line - if (i == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); - (lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - - // See issue #2901 - if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className)) - builder.content.className = "cm-tab-wrap-hack"; - - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) - builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); - - return builder; - } - - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token; - } - - // Build up the DOM representation for a single token, and add it to - // the line map. Takes care to render special characters separately. - function buildToken(builder, text, style, startStyle, endStyle, title, css) { - if (!text) return; - var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; - var special = builder.cm.state.specialChars, mustWrap = false; - if (!special.test(text)) { - builder.col += text.length; - var content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) mustWrap = true; - builder.pos += text.length; - } else { - var content = document.createDocumentFragment(), pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); - else content.appendChild(txt); - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) break; - pos += skipped + 1; - if (m[0] == "\t") { - var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; - var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt.setAttribute("role", "presentation"); - txt.setAttribute("cm-text", "\t"); - builder.col += tabWidth; - } else { - var txt = builder.cm.options.specialCharPlaceholder(m[0]); - txt.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); - else content.appendChild(txt); - builder.col += 1; - } - builder.map.push(builder.pos, builder.pos + 1, txt); - builder.pos++; - } - } - if (style || startStyle || endStyle || mustWrap || css) { - var fullStyle = style || ""; - if (startStyle) fullStyle += startStyle; - if (endStyle) fullStyle += endStyle; - var token = elt("span", [content], fullStyle, css); - if (title) token.title = title; - return builder.content.appendChild(token); - } - builder.content.appendChild(content); - } - - function splitSpaces(old) { - var out = " "; - for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; - out += " "; - return out; - } - - // Work around nonsense dimensions being reported for stretches of - // right-to-left text. - function buildTokenBadBidi(inner, order) { - return function(builder, text, style, startStyle, endStyle, title, css) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, end = start + text.length; - for (;;) { - // Find the part that overlaps with the start of this text - for (var i = 0; i < order.length; i++) { - var part = order[i]; - if (part.to > start && part.from <= start) break; - } - if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); - inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - }; - } - - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) builder.map.push(builder.pos, builder.pos + size, widget); - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) - widget = builder.content.appendChild(document.createElement("span")); - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - } - - // Outputs a number of spans to make up a line, taking highlighting - // and marked text into account. - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, allText = line.text, at = 0; - if (!spans) { - for (var i = 1; i < styles.length; i+=2) - builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); - return; - } - - var len = allText.length, pos = 0, i = 1, text = "", style, css; - var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; - for (;;) { - if (nextChange == pos) { // Update current marker set - spanStyle = spanEndStyle = spanStartStyle = title = css = ""; - collapsed = null; nextChange = Infinity; - var foundBookmarks = []; - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) spanStyle += " " + m.className; - if (m.css) css = m.css; - if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; - if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; - if (m.title && !title) title = m.title; - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) - collapsed = sp; - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, - collapsed.marker, collapsed.from == null); - if (collapsed.to == null) return; - if (collapsed.to == pos) collapsed = false; - } - if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) - buildCollapsedSpan(builder, 0, foundBookmarks[j]); - } - if (pos >= len) break; - - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, - spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); - } - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i++]); - style = interpretTokenStyle(styles[i++], builder.cm.options); - } - } - } - - // DOCUMENT DATA STRUCTURE - - // By default, updates that start and end at the beginning of a line - // are treated specially, in order to make the association of line - // widgets and marker elements with the text behave more intuitive. - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && - (!doc.cm || doc.cm.options.wholeLineUpdateBefore); - } - - // Perform a change on the document data structure. - function updateDoc(doc, change, markedSpans, estimateHeight) { - function spansFor(n) {return markedSpans ? markedSpans[n] : null;} - function update(line, text, spans) { - updateLine(line, text, spans, estimateHeight); - signalLater(line, "change", line, change); - } - function linesFor(start, end) { - for (var i = start, result = []; i < end; ++i) - result.push(new Line(text[i], spansFor(i), estimateHeight)); - return result; - } - - var from = change.from, to = change.to, text = change.text; - var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); - var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; - - // Adjust the line structure - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) doc.remove(from.line, nlines); - if (added.length) doc.insert(from.line, added); - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added = linesFor(1, text.length - 1); - added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added = linesFor(1, text.length - 1); - if (nlines > 1) doc.remove(from.line + 1, nlines - 1); - doc.insert(from.line + 1, added); - } - - signalLater(doc, "change", doc, change); - } - - // The document is represented as a BTree consisting of leaves, with - // chunk of lines in them, and branches, with up to ten leaves or - // other branch nodes below them. The top node is always a branch - // node, and is the document object itself (meaning it has - // additional methods and properties). - // - // All nodes have parent links. The tree is used both to go from - // line numbers to line objects, and to go from objects to numbers. - // It also indexes by height, and is used to convert between height - // and line object, and to find the total height of the document. - // - // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html - - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - for (var i = 0, height = 0; i < lines.length; ++i) { - lines[i].parent = this; - height += lines[i].height; - } - this.height = height; - } - - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length; }, - // Remove the n lines at offset 'at'. - removeInner: function(at, n) { - for (var i = at, e = at + n; i < e; ++i) { - var line = this.lines[i]; - this.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - // Helper used to collapse a small branch into a single leaf. - collapse: function(lines) { - lines.push.apply(lines, this.lines); - }, - // Insert the given array of lines at offset 'at', count them as - // having the given height. - insertInner: function(at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0; i < lines.length; ++i) lines[i].parent = this; - }, - // Used to iterate over a part of the tree. - iterN: function(at, n, op) { - for (var e = at + n; at < e; ++at) - if (op(this.lines[at])) return true; - } - }; - - function BranchChunk(children) { - this.children = children; - var size = 0, height = 0; - for (var i = 0; i < children.length; ++i) { - var ch = children[i]; - size += ch.chunkSize(); height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - - BranchChunk.prototype = { - chunkSize: function() { return this.size; }, - removeInner: function(at, n) { - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), oldHeight = child.height; - child.removeInner(at, rm); - this.height -= oldHeight - child.height; - if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) break; - at = 0; - } else at -= sz; - } - // If the result is smaller than 25 lines, ensure that it is a - // single leaf node. - if (this.size - n < 25 && - (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function(lines) { - for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); - }, - insertInner: function(at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - while (child.lines.length > 50) { - var spilled = child.lines.splice(child.lines.length - 25, 25); - var newleaf = new LeafChunk(spilled); - child.height -= newleaf.height; - this.children.splice(i + 1, 0, newleaf); - newleaf.parent = this; - } - this.maybeSpill(); - } - break; - } - at -= sz; - } - }, - // When a node has grown, check whether it should be split. - maybeSpill: function() { - if (this.children.length <= 10) return; - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - me.parent.maybeSpill(); - }, - iterN: function(at, n, op) { - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) return true; - if ((n -= used) == 0) break; - at = 0; - } else at -= sz; - } - } - }; - - var nextDocId = 0; - var Doc = CodeMirror.Doc = function(text, mode, firstLine) { - if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); - if (firstLine == null) firstLine = 0; - - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.frontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - - if (typeof text == "string") text = splitLines(text); - updateDoc(this, {from: start, to: start, text: text}); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function(from, to, op) { - if (op) this.iterN(from - this.first, to - from, op); - else this.iterN(this.first, this.first + this.size, from); - }, - - // Non-public interface for adding and removing lines. - insert: function(at, lines) { - var height = 0; - for (var i = 0; i < lines.length; ++i) height += lines[i].height; - this.insertInner(at - this.first, lines, height); - }, - remove: function(at, n) { this.removeInner(at - this.first, n); }, - - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - - getValue: function(lineSep, lineFilter) { - var lines = getLines(this, this.first, this.first + this.size, lineFilter); - if (lineSep === false) return lines; - return lines.join(lineSep || "\n"); - }, - setValue: docMethodOp(function(code) { - var top = Pos(this.first, 0), last = this.first + this.size - 1; - makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), - text: splitLines(code), origin: "setValue", full: true}, true); - setSelection(this, simpleSelection(top)); - }), - replaceRange: function(code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function(from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) return lines; - return lines.join(lineSep || "\n"); - }, - - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, - - getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, - getLineNumber: function(line) {return lineNo(line);}, - - getLineHandleVisualStart: function(line) { - if (typeof line == "number") line = getLine(this, line); - return visualLine(line); - }, - - lineCount: function() {return this.size;}, - firstLine: function() {return this.first;}, - lastLine: function() {return this.first + this.size - 1;}, - - clipPos: function(pos) {return clipPos(this, pos);}, - - getCursor: function(start) { - var range = this.sel.primary(), pos; - if (start == null || start == "head") pos = range.head; - else if (start == "anchor") pos = range.anchor; - else if (start == "end" || start == "to" || start === false) pos = range.to(); - else pos = range.from(); - return pos; - }, - listSelections: function() { return this.sel.ranges; }, - somethingSelected: function() {return this.sel.somethingSelected();}, - - setCursor: docMethodOp(function(line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); - }), - setSelection: docMethodOp(function(anchor, head, options) { - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); - }), - extendSelection: docMethodOp(function(head, other, options) { - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); - }), - extendSelections: docMethodOp(function(heads, options) { - extendSelections(this, clipPosArray(this, heads, options)); - }), - extendSelectionsBy: docMethodOp(function(f, options) { - extendSelections(this, map(this.sel.ranges, f), options); - }), - setSelections: docMethodOp(function(ranges, primary, options) { - if (!ranges.length) return; - for (var i = 0, out = []; i < ranges.length; i++) - out[i] = new Range(clipPos(this, ranges[i].anchor), - clipPos(this, ranges[i].head)); - if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); - setSelection(this, normalizeSelection(out, primary), options); - }), - addSelection: docMethodOp(function(anchor, head, options) { - var ranges = this.sel.ranges.slice(0); - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); - setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); - }), - - getSelection: function(lineSep) { - var ranges = this.sel.ranges, lines; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) return lines; - else return lines.join(lineSep || "\n"); - }, - getSelections: function(lineSep) { - var parts = [], ranges = this.sel.ranges; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - if (lineSep !== false) sel = sel.join(lineSep || "\n"); - parts[i] = sel; - } - return parts; - }, - replaceSelection: function(code, collapse, origin) { - var dup = []; - for (var i = 0; i < this.sel.ranges.length; i++) - dup[i] = code; - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function(code, collapse, origin) { - var changes = [], sel = this.sel; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin}; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i = changes.length - 1; i >= 0; i--) - makeChange(this, changes[i]); - if (newSel) setSelectionReplaceHistory(this, newSel); - else if (this.cm) ensureCursorVisible(this.cm); - }), - undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), - redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), - undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), - redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), - - setExtending: function(val) {this.extend = val;}, - getExtending: function() {return this.extend;}, - - historySize: function() { - var hist = this.history, done = 0, undone = 0; - for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; - for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; - return {undo: done, redo: undone}; - }, - clearHistory: function() {this.history = new History(this.history.maxGeneration);}, - - markClean: function() { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function(forceSplit) { - if (forceSplit) - this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; - return this.history.generation; - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration); - }, - - getHistory: function() { - return {done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone)}; - }, - setHistory: function(histData) { - var hist = this.history = new History(this.history.maxGeneration); - hist.done = copyHistoryArray(histData.done.slice(0), null, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - - addLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop]) line[prop] = cls; - else if (classTest(cls).test(line[prop])) return false; - else line[prop] += " " + cls; - return true; - }); - }), - removeLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop]; - if (!cur) return false; - else if (cls == null) line[prop] = null; - else { - var found = cur.match(classTest(cls)); - if (!found) return false; - var end = found.index + found[0].length; - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; - } - return true; - }); - }), - - addLineWidget: docMethodOp(function(handle, node, options) { - return addLineWidget(this, handle, node, options); - }), - removeLineWidget: function(widget) { widget.clear(); }, - - markText: function(from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); - }, - setBookmark: function(pos, options) { - var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents}; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark"); - }, - findMarksAt: function(pos) { - pos = clipPos(this, pos); - var markers = [], spans = getLine(this, pos.line).markedSpans; - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if ((span.from == null || span.from <= pos.ch) && - (span.to == null || span.to >= pos.ch)) - markers.push(span.marker.parent || span.marker); - } - return markers; - }, - findMarks: function(from, to, filter) { - from = clipPos(this, from); to = clipPos(this, to); - var found = [], lineNo = from.line; - this.iter(from.line, to.line + 1, function(line) { - var spans = line.markedSpans; - if (spans) for (var i = 0; i < spans.length; i++) { - var span = spans[i]; - if (!(lineNo == from.line && from.ch > span.to || - span.from == null && lineNo != from.line|| - lineNo == to.line && span.from > to.ch) && - (!filter || filter(span.marker))) - found.push(span.marker.parent || span.marker); - } - ++lineNo; - }); - return found; - }, - getAllMarks: function() { - var markers = []; - this.iter(function(line) { - var sps = line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) - if (sps[i].from != null) markers.push(sps[i].marker); - }); - return markers; - }, - - posFromIndex: function(off) { - var ch, lineNo = this.first; - this.iter(function(line) { - var sz = line.text.length + 1; - if (sz > off) { ch = off; return true; } - off -= sz; - ++lineNo; - }); - return clipPos(this, Pos(lineNo, ch)); - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) return 0; - this.iter(this.first, coords.line, function (line) { - index += line.text.length + 1; - }); - return index; - }, - - copy: function(copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); - doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc; - }, - - linkedDoc: function(options) { - if (!options) options = {}; - var from = this.first, to = this.first + this.size; - if (options.from != null && options.from > from) from = options.from; - if (options.to != null && options.to < to) to = options.to; - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); - if (options.sharedHist) copy.history = this.history; - (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); - copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy; - }, - unlinkDoc: function(other) { - if (other instanceof CodeMirror) other = other.doc; - if (this.linked) for (var i = 0; i < this.linked.length; ++i) { - var link = this.linked[i]; - if (link.doc != other) continue; - this.linked.splice(i, 1); - other.unlinkDoc(this); - detachSharedMarkers(findSharedMarkers(this)); - break; - } - // If the histories were shared, split them again - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); - other.history = new History(null); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function(f) {linkedDocs(this, f);}, - - getMode: function() {return this.mode;}, - getEditor: function() {return this.cm;} - }); - - // Public alias. - Doc.prototype.eachLine = Doc.prototype.iter; - - // Set up methods on CodeMirror's prototype to redirect to the editor's document. - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) - CodeMirror.prototype[prop] = (function(method) { - return function() {return method.apply(this.doc, arguments);}; - })(Doc.prototype[prop]); - - eventMixin(Doc); - - // Call f for all linked documents. - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc, skip, sharedHist) { - if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { - var rel = doc.linked[i]; - if (rel.doc == skip) continue; - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) continue; - f(rel.doc, shared); - propagate(rel.doc, doc, shared); - } - } - propagate(doc, null, true); - } - - // Attach a document to an editor. - function attachDoc(cm, doc) { - if (doc.cm) throw new Error("This document is already in use."); - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - if (!cm.options.lineWrapping) findMaxLine(cm); - cm.options.mode = doc.modeOption; - regChange(cm); - } - - // LINE UTILITIES - - // Find the line object corresponding to the given line number. - function getLine(doc, n) { - n -= doc.first; - if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); - for (var chunk = doc; !chunk.lines;) { - for (var i = 0;; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; break; } - n -= sz; - } - } - return chunk.lines[n]; - } - - // Get the part of a document between two positions, as an array of - // strings. - function getBetween(doc, start, end) { - var out = [], n = start.line; - doc.iter(start.line, end.line + 1, function(line) { - var text = line.text; - if (n == end.line) text = text.slice(0, end.ch); - if (n == start.line) text = text.slice(start.ch); - out.push(text); - ++n; - }); - return out; - } - // Get the lines between from and to, as array of strings. - function getLines(doc, from, to, lineFilter) { - var out = []; - doc.iter(from, to, function(line) { - var text = line.text; - if(lineFilter){ - text = lineFilter(line); - } - out.push(text); - }); - return out; - } - - // Update the height of a line, propagating the height change - // upwards to parent nodes. - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) for (var n = line; n; n = n.parent) n.height += diff; - } - - // Given a line object, find its line number by walking up through - // its parent links. - function lineNo(line) { - if (line.parent == null) return null; - var cur = line.parent, no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0;; ++i) { - if (chunk.children[i] == cur) break; - no += chunk.children[i].chunkSize(); - } - } - return no + cur.first; - } - - // Find the line at the given vertical position, using the height - // information in the document tree. - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i = 0; i < chunk.children.length; ++i) { - var child = chunk.children[i], ch = child.height; - if (h < ch) { chunk = child; continue outer; } - h -= ch; - n += child.chunkSize(); - } - return n; - } while (!chunk.lines); - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i], lh = line.height; - if (h < lh) break; - h -= lh; - } - return n + i; - } - - - // Find the height above the given line. - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - - var h = 0, chunk = lineObj.parent; - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i]; - if (line == lineObj) break; - else h += line.height; - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i = 0; i < p.children.length; ++i) { - var cur = p.children[i]; - if (cur == chunk) break; - else h += cur.height; - } - } - return h; - } - - // Get the bidi ordering for the given line (and cache it). Returns - // false for lines that are fully left-to-right, and an array of - // BidiSpan objects otherwise. - function getOrder(line) { - var order = line.order; - if (order == null) order = line.order = bidiOrdering(line.text); - return order; - } - - // HISTORY - - function History(startGen) { - // Arrays of change events and selections. Doing something adds an - // event to done and clears undo. Undoing moves events from done - // to undone, redoing moves them in the other direction. - this.done = []; this.undone = []; - this.undoDepth = Infinity; - // Used to track when changes can be merged into a single undo - // event - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - // Used by the isClean() method - this.generation = this.maxGeneration = startGen || 1; - } - - // Create a history change event from an updateDoc-style change - // object. - function historyChangeFromChange(doc, change) { - var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); - return histChange; - } - - // Pop all selection events off the end of a history array. Stop at - // a change event. - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) array.pop(); - else break; - } - } - - // Find the top change event in the history. Pop off selection - // events that are in the way. - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done); - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done); - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done); - } - } - - // Register a change in the history. Merges changes that are within - // a single operation, ore are close together with an origin that - // allows merging (starting with "+") into a single event. - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = +new Date, cur; - - if ((hist.lastOp == opId || - hist.lastOrigin == change.origin && change.origin && - ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || - change.origin.charAt(0) == "*")) && - (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - // Merge this change into the last event - var last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - // Optimized case for simple insertion -- don't want to add - // new changesets for every character typed - last.to = changeEnd(change); - } else { - // Add new sub-event - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - // Can not be merged, start a new event. - var before = lst(hist.done); - if (!before || !before.ranges) - pushSelectionToHistory(doc.sel, hist.done); - cur = {changes: [historyChangeFromChange(doc, change)], - generation: hist.generation}; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!hist.done[0].ranges) hist.done.shift(); - } - } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - - if (!last) signal(doc, "historyAdded"); - } - - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || - ch == "+" && - prev.ranges.length == sel.ranges.length && - prev.somethingSelected() == sel.somethingSelected() && - new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); - } - - // Called whenever the selection changes, sets the new selection as - // the pending selection in the history, and pushes the old pending - // selection into the 'done' array when it was significantly - // different (in number of selected ranges, emptiness, or time). - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, origin = options && options.origin; - - // A new event is started when the previous origin does not match - // the current, or the origins don't allow matching. Origins - // starting with * are always merged, those starting with + are - // merged when similar and close together in time. - if (opId == hist.lastSelOp || - (origin && hist.lastSelOrigin == origin && - (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || - selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) - hist.done[hist.done.length - 1] = sel; - else - pushSelectionToHistory(sel, hist.done); - - hist.lastSelTime = +new Date; - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) - clearSelectionEvents(hist.undone); - } - - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) - dest.push(sel); - } - - // Used to store marked span information in the history. - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { - if (line.markedSpans) - (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; - ++n; - }); - } - - // When un/re-doing restores text containing marked spans, those - // that have been explicitly cleared should not be restored. - function removeClearedSpans(spans) { - if (!spans) return null; - for (var i = 0, out; i < spans.length; ++i) { - if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } - else if (out) out.push(spans[i]); - } - return !out ? spans : out.length ? out : null; - } - - // Retrieve and filter the old marked spans stored in a change event. - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) return null; - for (var i = 0, nw = []; i < change.text.length; ++i) - nw.push(removeClearedSpans(found[i])); - return nw; - } - - // Used both to provide a JSON-safe object in .getHistory, and, when - // detaching a document, to split the history in two - function copyHistoryArray(events, newGroup, instantiateSel) { - for (var i = 0, copy = []; i < events.length; ++i) { - var event = events[i]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue; - } - var changes = event.changes, newChanges = []; - copy.push({changes: newChanges}); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], m; - newChanges.push({from: change.from, to: change.to, text: change.text}); - if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop] = change[prop]; - delete change[prop]; - } - } - } - } - return copy; - } - - // Rebasing/resetting history to deal with externally-sourced changes - - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - - // Tries to rebase an array of history events given a change in the - // document. If the change touches the same lines as the event, the - // event, and everything 'behind' it, is discarded. If the change is - // before the event, the event's positions are updated. Uses a - // copy-on-write scheme for the positions, to avoid having to - // reallocate them all on every rebase, but also avoid problems with - // shared position objects being unsafely updated. - function rebaseHistArray(array, from, to, diff) { - for (var i = 0; i < array.length; ++i) { - var sub = array[i], ok = true; - if (sub.ranges) { - if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } - for (var j = 0; j < sub.ranges.length; j++) { - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); - } - continue; - } - for (var j = 0; j < sub.changes.length; ++j) { - var cur = sub.changes[j]; - if (to < cur.from.line) { - cur.from = Pos(cur.from.line + diff, cur.from.ch); - cur.to = Pos(cur.to.line + diff, cur.to.ch); - } else if (from <= cur.to.line) { - ok = false; - break; - } - } - if (!ok) { - array.splice(0, i + 1); - i = 0; - } - } - } - - function rebaseHist(hist, change) { - var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - - // EVENT UTILITIES - - // Due to the fact that we still support jurassic IE versions, some - // compatibility wrappers are needed. - - var e_preventDefault = CodeMirror.e_preventDefault = function(e) { - if (e.preventDefault) e.preventDefault(); - else e.returnValue = false; - }; - var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { - if (e.stopPropagation) e.stopPropagation(); - else e.cancelBubble = true; - }; - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; - } - var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; - - function e_target(e) {return e.target || e.srcElement;} - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) b = 1; - else if (e.button & 2) b = 3; - else if (e.button & 4) b = 2; - } - if (mac && e.ctrlKey && b == 1) b = 3; - return b; - } - - // EVENT HANDLING - - // Lightweight event framework. on/off also work on DOM nodes, - // registering native DOM handlers. - - var on = CodeMirror.on = function(emitter, type, f) { - if (emitter.addEventListener) - emitter.addEventListener(type, f, false); - else if (emitter.attachEvent) - emitter.attachEvent("on" + type, f); - else { - var map = emitter._handlers || (emitter._handlers = {}); - var arr = map[type] || (map[type] = []); - arr.push(f); - } - }; - - var off = CodeMirror.off = function(emitter, type, f) { - if (emitter.removeEventListener) - emitter.removeEventListener(type, f, false); - else if (emitter.detachEvent) - emitter.detachEvent("on" + type, f); - else { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - for (var i = 0; i < arr.length; ++i) - if (arr[i] == f) { arr.splice(i, 1); break; } - } - }; - - var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - var args = Array.prototype.slice.call(arguments, 2); - for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); - }; - - var orphanDelayedCallbacks = null; - - // Often, we want to signal events at a point where we are in the - // middle of some work, but don't want the handler to start calling - // other methods on the editor, which might be in an inconsistent - // state or simply not expect any other events to happen. - // signalLater looks whether there are any handlers, and schedules - // them to be executed when the last operation ends, or, if no - // operation is active, when a timeout fires. - function signalLater(emitter, type /*, values...*/) { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - var args = Array.prototype.slice.call(arguments, 2), list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - function bnd(f) {return function(){f.apply(null, args);};}; - for (var i = 0; i < arr.length; ++i) - list.push(bnd(arr[i])); - } - - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) delayed[i](); - } - - // The DOM events that CodeMirror handles can be overridden by - // registering a (non-DOM) handler on the editor for the event name, - // and preventDefault-ing the event in that handler. - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") - e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore; - } - - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) return; - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) - set.push(arr[i]); - } - - function hasHandler(emitter, type) { - var arr = emitter._handlers && emitter._handlers[type]; - return arr && arr.length > 0; - } - - // Add on and off methods to a constructor's prototype, to make - // registering events on such objects more convenient. - function eventMixin(ctor) { - ctor.prototype.on = function(type, f) {on(this, type, f);}; - ctor.prototype.off = function(type, f) {off(this, type, f);}; - } - - // MISC UTILITIES - - // Number of pixels added to scroller and sizer to hide scrollbar - var scrollerGap = 30; - - // Returned or thrown by various protocols to signal 'I'm not - // handling this'. - var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; - - // Reused option objects for setSelection & friends - var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; - - function Delayed() {this.id = null;} - Delayed.prototype.set = function(ms, f) { - clearTimeout(this.id); - this.id = setTimeout(f, ms); - }; - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) end = string.length; - } - for (var i = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf("\t", i); - if (nextTab < 0 || nextTab >= end) - return n + (end - i); - n += nextTab - i; - n += tabSize - (n % tabSize); - i = nextTab + 1; - } - }; - - // The inverse of countColumn -- find the offset that corresponds to - // a particular column. - function findColumn(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf("\t", pos); - if (nextTab == -1) nextTab = string.length; - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) - return pos + Math.min(skipped, goal - col); - col += nextTab - pos; - col += tabSize - (col % tabSize); - pos = nextTab + 1; - if (col >= goal) return pos; - } - } - - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) - spaceStrs.push(lst(spaceStrs) + " "); - return spaceStrs[n]; - } - - function lst(arr) { return arr[arr.length-1]; } - - var selectInput = function(node) { node.select(); }; - if (ios) // Mobile Safari apparently has a bug where select() is broken. - selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; - else if (ie) // Suppress mysterious IE10 errors - selectInput = function(node) { try { node.select(); } catch(_e) {} }; - - function indexOf(array, elt) { - for (var i = 0; i < array.length; ++i) - if (array[i] == elt) return i; - return -1; - } - function map(array, f) { - var out = []; - for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); - return out; - } - - function nothing() {} - - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) copyObj(props, inst); - return inst; - }; - - function copyObj(obj, target, overwrite) { - if (!target) target = {}; - for (var prop in obj) - if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) - target[prop] = obj[prop]; - return target; - } - - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function(){return f.apply(null, args);}; - } - - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - var isWordCharBasic = CodeMirror.isWordChar = function(ch) { - return /\w/.test(ch) || ch > "\x80" && - (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); - }; - function isWordChar(ch, helper) { - if (!helper) return isWordCharBasic(ch); - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; - return helper.test(ch); - } - - function isEmpty(obj) { - for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; - return true; - } - - // Extending unicode characters. A series of a non-extending char + - // any number of extending chars is treated as a single unit as far - // as editing and measuring is concerned. This is not fully correct, - // since some scripts/font/browsers also treat other configurations - // of code points as a group. - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; - function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } - - // DOM UTILITIES - - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) e.className = className; - if (style) e.style.cssText = style; - if (typeof content == "string") e.appendChild(document.createTextNode(content)); - else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); - return e; - } - - var range; - if (document.createRange) range = function(node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r; - }; - else range = function(node, start, end) { - var r = document.body.createTextRange(); - try { r.moveToElementText(node.parentNode); } - catch(e) { return r; } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r; - }; - - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) - e.removeChild(e.firstChild); - return e; - } - - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e); - } - - var contains = CodeMirror.contains = function(parent, child) { - if (child.nodeType == 3) // Android browser always returns false when child is a textnode - child = child.parentNode; - if (parent.contains) - return parent.contains(child); - do { - if (child.nodeType == 11) child = child.host; - if (child == parent) return true; - } while (child = child.parentNode); - }; - - function activeElt() { return document.activeElement; } - // Older versions of IE throws unspecified error when touching - // document.activeElement in some cases (during loading, in iframe) - if (ie && ie_version < 11) activeElt = function() { - try { return document.activeElement; } - catch(e) { return document.body; } - }; - - function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } - var rmClass = CodeMirror.rmClass = function(node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - var addClass = CodeMirror.addClass = function(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; - }; - function joinClasses(a, b) { - var as = a.split(" "); - for (var i = 0; i < as.length; i++) - if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; - return b; - } - - // WINDOW-WIDE EVENTS - - // These must be handled carefully, because naively registering a - // handler for each editor will cause the editors to never be - // garbage collected. - - function forEachCodeMirror(f) { - if (!document.body.getElementsByClassName) return; - var byClass = document.body.getElementsByClassName("CodeMirror"); - for (var i = 0; i < byClass.length; i++) { - var cm = byClass[i].CodeMirror; - if (cm) f(cm); - } - } - - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) return; - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { - // When the window resizes, we need to refresh active editors. - var resizeTimer; - on(window, "resize", function() { - if (resizeTimer == null) resizeTimer = setTimeout(function() { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); - }); - // When the window loses focus, we want to show the editor as blurred - on(window, "blur", function() { - forEachCodeMirror(onBlur); - }); - } - // FEATURE DETECTION + // This will be set to an array of strings when copying, so that, + // when pasting, we know what kind of selections the copied text + // was made out of. + var lastCopied = null; - // Detect drag-and-drop - var dragAndDrop = function() { - // There is *some* kind of drag-and-drop support in IE6-8, but I - // couldn't get it to work yet. - if (ie && ie_version < 9) return false; - var div = elt('div'); - return "draggable" in div || "dragDrop" in div; - }(); - - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "\u200b"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) - zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); - } - var node = zwspSupported ? elt("span", "\u200b") : - elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node; - } - - // Feature-detect IE's crummy client rect reporting for bidi text - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) return badBidiRects; - var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) - var r1 = range(txt, 1, 2).getBoundingClientRect(); - return badBidiRects = (r1.right - r0.right < 3); - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { - var pos = 0, result = [], l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) nl = string.length; - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result; - } : function(string){return string.split(/\r\n?|\n/);}; - - var hasSelection = window.getSelection ? function(te) { - try { return te.selectionStart != te.selectionEnd; } - catch(e) { return false; } - } : function(te) { - try {var range = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range || range.parentElement() != te) return false; - return range.compareEndPoints("StartToEnd", range) != 0; - }; - - var hasCopyEvent = (function() { - var e = elt("div"); - if ("oncopy" in e) return true; - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function"; - })(); - - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) return badZoomedRects; - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; - } - - // KEY NAMES - - var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", - 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", - 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", - 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", - 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", - 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", - 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; - CodeMirror.keyNames = keyNames; - (function() { - // Number keys - for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); - // Alphabetic keys - for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); - // Function keys - for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; - })(); - - // BIDI HELPERS - - function iterateBidiSections(order, from, to, f) { - if (!order) return f(from, to, "ltr"); - var found = false; - for (var i = 0; i < order.length; ++i) { - var part = order[i]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); - found = true; - } - } - if (!found) f(from, to, "ltr"); - } - - function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } - function bidiRight(part) { return part.level % 2 ? part.from : part.to; } - - function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } - function lineRight(line) { - var order = getOrder(line); - if (!order) return line.text.length; - return bidiRight(lst(order)); - } - - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) lineN = lineNo(visual); - var order = getOrder(visual); - var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); - return Pos(lineN, ch); - } - function lineEnd(cm, lineN) { - var merged, line = getLine(cm.doc, lineN); - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - lineN = null; - } - var order = getOrder(line); - var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); - return Pos(lineN == null ? lineNo(line) : lineN, ch); - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(0, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS); - } - return start; - } - - function compareBidiLevel(order, a, b) { - var linedir = order[0].level; - if (a == linedir) return true; - if (b == linedir) return false; - return a < b; - } - var bidiOther; - function getBidiPartAt(order, pos) { - bidiOther = null; - for (var i = 0, found; i < order.length; ++i) { - var cur = order[i]; - if (cur.from < pos && cur.to > pos) return i; - if ((cur.from == pos || cur.to == pos)) { - if (found == null) { - found = i; - } else if (compareBidiLevel(order, cur.level, order[found].level)) { - if (cur.from != cur.to) bidiOther = found; - return i; - } else { - if (cur.from != cur.to) bidiOther = i; - return found; - } - } - } - return found; - } - - function moveInLine(line, pos, dir, byUnit) { - if (!byUnit) return pos + dir; - do pos += dir; - while (pos > 0 && isExtendingChar(line.text.charAt(pos))); - return pos; - } - - // This is needed in order to move 'visually' through bi-directional - // text -- i.e., pressing left should make the cursor go left, even - // when in RTL text. The tricky part is the 'jumps', where RTL and - // LTR text touch each other. This often requires the cursor offset - // to move more than one unit, in order to visually move one unit. - function moveVisually(line, start, dir, byUnit) { - var bidi = getOrder(line); - if (!bidi) return moveLogically(line, start, dir, byUnit); - var pos = getBidiPartAt(bidi, start), part = bidi[pos]; - var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); - - for (;;) { - if (target > part.from && target < part.to) return target; - if (target == part.from || target == part.to) { - if (getBidiPartAt(bidi, target) == pos) return target; - part = bidi[pos += dir]; - return (dir > 0) == part.level % 2 ? part.to : part.from; - } else { - part = bidi[pos += dir]; - if (!part) return null; - if ((dir > 0) == part.level % 2) - target = moveInLine(line, part.to, -1, byUnit); - else - target = moveInLine(line, part.from, 1, byUnit); - } - } - } - - function moveLogically(line, start, dir, byUnit) { - var target = start + dir; - if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; - return target < 0 || target > line.text.length ? null : target; - } - - // Bidirectional ordering algorithm - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm - // that this (partially) implements. - - // One-char codes used for character types: - // L (L): Left-to-Right - // R (R): Right-to-Left - // r (AL): Right-to-Left Arabic - // 1 (EN): European Number - // + (ES): European Number Separator - // % (ET): European Number Terminator - // n (AN): Arabic Number - // , (CS): Common Number Separator - // m (NSM): Non-Spacing Mark - // b (BN): Boundary Neutral - // s (B): Paragraph Separator - // t (S): Segment Separator - // w (WS): Whitespace - // N (ON): Other Neutrals - - // Returns null if characters are ordered as they appear - // (left-to-right), or an array of sections ({from, to, level} - // objects) in the order in which they occur visually. - var bidiOrdering = (function() { - // Character types for codepoints 0 to 0xff - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - // Character types for codepoints 0x600 to 0x6ff - var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; - function charType(code) { - if (code <= 0xf7) return lowTypes.charAt(code); - else if (0x590 <= code && code <= 0x5f4) return "R"; - else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); - else if (0x6ee <= code && code <= 0x8ac) return "r"; - else if (0x2000 <= code && code <= 0x200b) return "w"; - else if (code == 0x200c) return "b"; - else return "L"; - } - - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; - // Browsers seem to always treat the boundaries of block elements as being L. - var outerType = "L"; - - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; this.to = to; - } - - return function(str) { - if (!bidiRE.test(str)) return false; - var len = str.length, types = []; - for (var i = 0, type; i < len; ++i) - types.push(type = charType(str.charCodeAt(i))); - - // W1. Examine each non-spacing mark (NSM) in the level run, and - // change the type of the NSM to the type of the previous - // character. If the NSM is at the start of the level run, it will - // get the type of sor. - for (var i = 0, prev = outerType; i < len; ++i) { - var type = types[i]; - if (type == "m") types[i] = prev; - else prev = type; - } - - // W2. Search backwards from each instance of a European number - // until the first strong type (R, L, AL, or sor) is found. If an - // AL is found, change the type of the European number to Arabic - // number. - // W3. Change all ALs to R. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (type == "1" && cur == "r") types[i] = "n"; - else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } - } - - // W4. A single European separator between two European numbers - // changes to a European number. A single common separator between - // two numbers of the same type changes to that type. - for (var i = 1, prev = types[0]; i < len - 1; ++i) { - var type = types[i]; - if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; - else if (type == "," && prev == types[i+1] && - (prev == "1" || prev == "n")) types[i] = prev; - prev = type; - } - - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - for (var i = 0; i < len; ++i) { - var type = types[i]; - if (type == ",") types[i] = "N"; - else if (type == "%") { - for (var end = i + 1; end < len && types[end] == "%"; ++end) {} - var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // W7. Search backwards from each instance of a European number - // until the first strong type (R, L, or sor) is found. If an L is - // found, then change the type of the European number to L. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (cur == "L" && type == "1") types[i] = "L"; - else if (isStrong.test(type)) cur = type; - } - - // N1. A sequence of neutrals takes the direction of the - // surrounding strong text if the text on both sides has the same - // direction. European and Arabic numbers act as if they were R in - // terms of their influence on neutrals. Start-of-level-run (sor) - // and end-of-level-run (eor) are used at level run boundaries. - // N2. Any remaining neutrals take the embedding direction. - for (var i = 0; i < len; ++i) { - if (isNeutral.test(types[i])) { - for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} - var before = (i ? types[i-1] : outerType) == "L"; - var after = (end < len ? types[end] : outerType) == "L"; - var replace = before || after ? "L" : "R"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - var order = [], m; - for (var i = 0; i < len;) { - if (countsAsLeft.test(types[i])) { - var start = i; - for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} - order.push(new BidiSpan(0, start, i)); - } else { - var pos = i, at = order.length; - for (++i; i < len && types[i] != "L"; ++i) {} - for (var j = pos; j < i;) { - if (countsAsNum.test(types[j])) { - if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); - var nstart = j; - for (++j; j < i && countsAsNum.test(types[j]); ++j) {} - order.splice(at, 0, new BidiSpan(2, nstart, j)); - pos = j; - } else ++j; - } - if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); - } - } - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); - } - if (order[0].level == 2) - order.unshift(new BidiSpan(1, order[0].to, order[0].to)); - if (order[0].level != lst(order).level) - order.push(new BidiSpan(order[0].level, len, len)); - - return order; - }; - })(); + function applyTextInput (cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) sel = doc.sel; - // THE END + var paste = cm.state.pasteIncoming || origin == "paste"; + var textLines = splitLines(inserted), multiPaste = null; + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.join("\n") == inserted) {multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);} else if (textLines.length == sel.ranges.length) {multiPaste = map(textLines, function (l) { return [l]; });} + } - CodeMirror.version = "5.4.1"; + // Normal behavior is to insert the new text into every selection + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + var from = range.from(), to = range.to(); + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + {from = Pos(from.line, from.ch - deleted);} else if (cm.state.overwrite && !paste) // Handle overwrite + {to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));} + } + var updateInput = cm.curOp.updateInput; + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) {triggerElectric(cm, inserted);} - return CodeMirror; -});(function (mod) { - mod(CodeMirror); -})(function (CodeMirror) { - var Pos = CodeMirror.Pos; + ensureCursorVisible(cm); + cm.curOp.updateInput = updateInput; + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = false; + } - function forEach(arr, f) { - for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); + function handlePaste (e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); + if (pasted) { + e.preventDefault(); + runInOp(cm, function () { applyTextInput(cm, pasted, 0, null, "paste"); }); + return true; + } } - function arrayContains(arr, item) { - if (!Array.prototype.indexOf) { - var i = arr.length; - while (i--) { - if (arr[i] === item) { - return true; + function triggerElectric (cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) return; + var sel = cm.doc.sel; + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; + var mode = cm.getModeAt(range.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) { + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart"); + break; + } } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) {indented = indentLine(cm, range.head.line, "smart");} } - return false; + if (indented) signalLater(cm, "electricInput", cm, range.head.line); } - return arr.indexOf(item) != -1; } - function scriptHint(editor, keywords, getToken, options) { - // Find the token at the cursor - var cur = editor.getCursor(), token = getToken(editor, cur); - if (/\b(?:string)\b/.test(token.type)) { - return; + function copyableRanges (cm) { + var text = [], ranges = []; + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line; + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); } - token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; + return {text: text, ranges: ranges}; + } - if (!/^[\w$_]*$/.test(token.string)) { - token = { - start: cur.ch, end: cur.ch, string: "", state: token.state, - type: token.string == "." ? "property" : null + function disableBrowserMagic (field) { + field.setAttribute("autocorrect", "off"); + field.setAttribute("autocapitalize", "off"); + field.setAttribute("spellcheck", "false"); + } + + // TEXTAREA INPUT STYLE + + function TextareaInput (cm) { + this.cm = cm; + // See input.poll and input.reset + this.prevInput = ""; + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false; + // Self-resetting timeout for the poller + this.polling = new Delayed(); + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false; + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false; + this.composing = null; + } + + function hiddenTextarea () { + var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) te.style.width = "1000px"; + else te.setAttribute("wrap", "off"); + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) te.style.border = "1px solid black"; + disableBrowserMagic(te); + return div; + } + + TextareaInput.prototype = copyObj({ + init: function (display) { + var input = this, cm = this.cm; + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild; + display.wrapper.insertBefore(div, display.wrapper.firstChild); + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) te.style.width = "0px"; + + on(te, "input", function () { + if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; + input.poll(); + }); + + on(te, "paste", function (e) { + if (handlePaste(e, cm)) return true; + + cm.state.pasteIncoming = true; + input.fastPoll(); + }); + + function prepareCopyCut (e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (input.inaccurateSelection) { + input.prevInput = ""; + input.inaccurateSelection = false; + te.value = lastCopied.join("\n"); + selectInput(te); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") cm.state.cutIncoming = true; + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e)) return; + cm.state.pasteIncoming = true; + input.focus(); + }); + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) e_preventDefault(e); + }); + + on(te, "compositionstart", function () { + var start = cm.getCursor("from"); + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + }; + }); + on(te, "compositionend", function () { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }, + + prepareSelection: function () { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc; + var result = prepareSelection(cm); + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)); + } + + return result; + }, + + showSelection: function (drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }, + + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + reset: function (typing) { + if (this.contextMenuPending) return; + var minimal, selected, cm = this.cm, doc = cm.doc; + if (cm.somethingSelected()) { + this.prevInput = ""; + var range = doc.sel.primary(); + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); + var content = minimal ? "-" : selected || cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) selectInput(this.textarea); + if (ie && ie_version >= 9) this.hasSelection = content; + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) this.hasSelection = null; + } + this.inaccurateSelection = minimal; + }, + + getField: function () { return this.textarea; }, + + supportsTouch: function () { return false; }, + + focus: function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus(); } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } + }, + + blur: function () { this.textarea.blur(); }, + + resetPosition: function () { + this.wrapper.style.top = this.wrapper.style.left = 0; + }, + + receivedFocus: function () { this.slowPoll(); }, + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + slowPoll: function () { + var input = this; + if (input.pollingFast) return; + input.polling.set(this.cm.options.pollInterval, function () { + input.poll(); + if (input.cm.state.focused) input.slowPoll(); + }); + }, + + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + fastPoll: function () { + var missed = false, input = this; + input.pollingFast = true; + function p () { + var changed = input.poll(); + if (!changed && !missed) {missed = true; input.polling.set(60, p);} else {input.pollingFast = false; input.slowPoll();} + } + input.polling.set(20, p); + }, + + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + poll: function () { + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput) || + isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq) {return false;} + + var text = input.value; + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) return false; + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false; + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 0x200b && !prevInput) prevInput = "\u200b"; + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; + + var self = this; + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, self.composing ? "*compose" : null); + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; + else self.prevInput = text; + + if (self.composing) { + self.composing.range.clear(); + self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}); + } + }); + return true; + }, + + ensurePolled: function () { + if (this.pollingFast && this.poll()) this.pollingFast = false; + }, + + onKeyPress: function () { + if (ie && ie_version >= 9) this.hasSelection = null; + this.fastPoll(); + }, + + onContextMenu: function (e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) return; // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) {operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);} + + var oldCSS = te.style.cssText; + input.wrapper.style.position = "absolute"; + te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + + "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) + display.input.focus(); + if (webkit) window.scrollTo(null, oldScrollY); + display.input.reset(); + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) te.value = input.prevInput = " "; + input.contextMenuPending = true; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack () { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "\u200b" + (selected ? te.value : ""); + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval; + input.prevInput = selected ? "" : "\u200b"; + te.selectionStart = 1; te.selectionEnd = extval.length; + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel; + } + } + function rehide () { + input.contextMenuPending = false; + input.wrapper.style.position = "relative"; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") {operation(cm, commands.selectAll)(cm);} else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); + else display.input.reset(); + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + + if (ie && ie_version >= 9) prepareSelectAllHack(); + if (captureRightClick) { + e_stop(e); + var mouseup = function () { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }, + + setUneditable: nothing, + + needsContentAttribute: false + }, TextareaInput.prototype); + + // CONTENTEDITABLE INPUT STYLE + + function ContentEditableInput (cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.gracePeriod = false; + } + + ContentEditableInput.prototype = copyObj({ + init: function (display) { + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + div.contentEditable = "true"; + disableBrowserMagic(div); + + on(div, "paste", function (e) { handlePaste(e, cm); }); + + on(div, "compositionstart", function (e) { + var data = e.data; + input.composing = {sel: cm.doc.sel, data: data, startData: data}; + if (!data) return; + var prim = cm.doc.sel.primary(); + var line = cm.getLine(prim.head.line); + var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); + if (found > -1 && found <= prim.head.ch) { + input.composing.sel = simpleSelection(Pos(prim.head.line, found), + Pos(prim.head.line, found + data.length)); + } + }); + on(div, "compositionupdate", function (e) { + input.composing.data = e.data; + }); + on(div, "compositionend", function (e) { + var ours = input.composing; + if (!ours) return; + if (e.data != ours.startData && !/\u200b/.test(e.data)) {ours.data = e.data;} + // Need a small delay to prevent other code (input event, + // selection polling) from doing damage when fired right after + // compositionend. + setTimeout(function () { + if (!ours.handled) {input.applyComposition(ours);} + if (input.composing == ours) {input.composing = null;} + }, 50); + }); + + on(div, "touchstart", function () { + input.forceCompositionEnd(); + }); + + on(div, "input", function () { + if (input.composing) return; + if (!input.pollContent()) {runInOp(input.cm, function () {regChange(cm);});} + }); + + function onCopyCut (e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (e.type == "cut") cm.replaceSelection("", null, "cut"); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + // iOS exposes the clipboard API, but seems to discard content inserted into it + if (e.clipboardData && !ios) { + e.preventDefault(); + e.clipboardData.clearData(); + e.clipboardData.setData("text/plain", lastCopied.join("\n")); + } else { + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.join("\n"); + var hadFocus = document.activeElement; + selectInput(te); + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + }, 50); + } + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }, + + prepareSelection: function () { + var result = prepareSelection(this.cm, false); + result.focus = this.cm.state.focused; + return result; + }, + + showSelection: function (info) { + if (!info || !this.cm.display.view.length) return; + if (info.focus) this.showPrimarySelection(); + this.showMultipleSelections(info); + }, + + showPrimarySelection: function () { + var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); + var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && + cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) {return;} + + var start = posToDOM(this.cm, prim.from()); + var end = posToDOM(this.cm, prim.to()); + if (!start && !end) return; + + var view = this.cm.display.view; + var old = sel.rangeCount && sel.getRangeAt(0); + if (!start) { + start = {node: view[0].measure.map[2], offset: 0}; + } else if (!end) { // FIXME dangerously hacky + var measure = view[view.length - 1].measure; + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; + } + + try { var rng = range(start.node, start.offset, end.offset, end.node); } catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + sel.removeAllRanges(); + sel.addRange(rng); + if (old && sel.anchorNode == null) sel.addRange(old); + else if (gecko) this.startGracePeriod(); + } + this.rememberSelection(); + }, + + startGracePeriod: function () { + var input = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function () { + input.gracePeriod = false; + if (input.selectionChanged()) {input.cm.operation(function () { input.cm.curOp.selectionChanged = true; });} + }, 20); + }, + + showMultipleSelections: function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }, + + rememberSelection: function () { + var sel = window.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; + }, + + selectionInEditor: function () { + var sel = window.getSelection(); + if (!sel.rangeCount) return false; + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }, + + focus: function () { + if (this.cm.options.readOnly != "nocursor") this.div.focus(); + }, + blur: function () { this.div.blur(); }, + getField: function () { return this.div; }, + + supportsTouch: function () { return true; }, + + receivedFocus: function () { + var input = this; + if (this.selectionInEditor()) {this.pollSelection();} else {runInOp(this.cm, function () { input.cm.curOp.selectionChanged = true; });} + + function poll () { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }, + + selectionChanged: function () { + var sel = window.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; + }, + + pollSelection: function () { + if (!this.composing && !this.gracePeriod && this.selectionChanged()) { + var sel = window.getSelection(), cm = this.cm; + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { + runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; + }); + } + } + }, + + pollContent: function () { + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; + + var fromIndex; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + var fromLine = lineNo(display.view[0].line); + var fromNode = display.view[0].node; + } else { + var fromLine = lineNo(display.view[fromIndex].line); + var fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + if (toIndex == display.view.length - 1) { + var toLine = display.viewTo - 1; + var toNode = display.lineDiv.lastChild; + } else { + var toLine = lineNo(display.view[toIndex + 1].line) - 1; + var toNode = display.view[toIndex + 1].node.previousSibling; + } + + var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } else break; + } + + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) {++cutFront;} + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {++cutEnd;} + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); + newText[0] = newText[0].slice(cutFront); + + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; + } + }, + + ensurePolled: function () { + this.forceCompositionEnd(); + }, + reset: function () { + this.forceCompositionEnd(); + }, + forceCompositionEnd: function () { + if (!this.composing || this.composing.handled) return; + this.applyComposition(this.composing); + this.composing.handled = true; + this.div.blur(); + this.div.focus(); + }, + applyComposition: function (composing) { + if (composing.data && composing.data != composing.startData) {operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);} + }, + + setUneditable: function (node) { + node.setAttribute("contenteditable", "false"); + }, + + onKeyPress: function (e) { + e.preventDefault(); + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + }, + + onContextMenu: nothing, + resetPosition: nothing, + + needsContentAttribute: true + }, ContentEditableInput.prototype); + + function posToDOM (cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) return null; + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + + var order = getOrder(line), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; + } + + function badPos (pos, bad) { if (bad) pos.bad = true; return pos; } + + function domToPos (cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + node = null; offset = 0; + } else { + for (lineNode = node; ; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) return null; + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i]; + if (lineView.node == lineNode) {return locateNodeInLineView(lineView, node, offset);} + } + } + + function locateNodeInLineView (lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) offset = textNode.nodeValue.length; + } + while (topNode.parentNode != wrapper) topNode = topNode.parentNode; + var measure = lineView.measure, maps = measure.maps; + + function find (textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i]; + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2]; + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); + var ch = map[j] + offset; + if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; + return Pos(line, ch); + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) return badPos(found, bad); + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) {return badPos(Pos(found.line, found.ch - dist), bad);} + dist += after.textContent.length; + } + for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) {return badPos(Pos(found.line, found.ch + dist), bad);} + dist += after.textContent.length; + } + } + + function domTextBetween (cm, from, to, fromLine, toLine) { + var text = "", closing = false; + function recognizeMarker (id) { return function (marker) { return marker.id == id; }; } + function walk (node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText != null) { + if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); + text += cmText; + return; + } + var markerID = node.getAttribute("cm-marker"), range; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range = found[0].find())) {text += getBetween(cm.doc, range.from, range.to).join("\n");} + return; + } + if (node.getAttribute("contenteditable") == "false") return; + for (var i = 0; i < node.childNodes.length; i++) {walk(node.childNodes[i]);} + if (/^(pre|div|p)$/i.test(node.nodeName)) {closing = true;} + } else if (node.nodeType == 3) { + var val = node.nodeValue; + if (!val) return; + if (closing) { + text += "\n"; + closing = false; + } + text += val; + } + } + for (;;) { + walk(from); + if (from == to) break; + from = from.nextSibling; + } + return text; + } + + CodeMirror.inputStyles = {textarea: TextareaInput, contenteditable: ContentEditableInput}; + + // SELECTION / CURSOR + + // Selection objects are immutable. A new one is created every time + // the selection changes. A selection is one or more non-overlapping + // (and non-touching) ranges, sorted, and an integer that indicates + // which one is the primary selection (the one that's scrolled into + // view, that getCursor returns, etc). + function Selection (ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + } + + Selection.prototype = { + primary: function () { return this.ranges[this.primIndex]; }, + equals: function (other) { + if (other == this) return true; + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; + for (var i = 0; i < this.ranges.length; i++) { + var here = this.ranges[i], there = other.ranges[i]; + if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; + } + return true; + }, + deepCopy: function () { + for (var out = [], i = 0; i < this.ranges.length; i++) {out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));} + return new Selection(out, this.primIndex); + }, + somethingSelected: function () { + for (var i = 0; i < this.ranges.length; i++) {if (!this.ranges[i].empty()) return true;} + return false; + }, + contains: function (pos, end) { + if (!end) end = pos; + for (var i = 0; i < this.ranges.length; i++) { + var range = this.ranges[i]; + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) {return i;} + } + return -1; + } + }; + + function Range (anchor, head) { + this.anchor = anchor; this.head = head; + } + + Range.prototype = { + from: function () { return minPos(this.anchor, this.head); }, + to: function () { return maxPos(this.anchor, this.head); }, + empty: function () { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; + } + }; + + // Take an unsorted, potentially overlapping set of ranges, and + // build a selection out of it. 'Consumes' ranges array (modifying + // it). + function normalizeSelection (ranges, primIndex) { + var prim = ranges[primIndex]; + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); + primIndex = indexOf(ranges, prim); + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1]; + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i <= primIndex) --primIndex; + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex); + } + + function simpleSelection (anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + + // Most of the external API clips given positions to make sure they + // actually exist within the document. + function clipLine (doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} + function clipPos (doc, pos) { + if (pos.line < doc.first) return Pos(doc.first, 0); + var last = doc.first + doc.size - 1; + if (pos.line > last) return Pos(last, getLine(doc, last).text.length); + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen (pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) return Pos(pos.line, linelen); + else if (ch < 0) return Pos(pos.line, 0); + return pos; + } + function isLine (doc, l) {return l >= doc.first && l < doc.first + doc.size;} + function clipPosArray (doc, array) { + for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); + return out; + } + + // SELECTION UPDATES + + // The 'scroll' parameter given to many of these indicated whether + // the new cursor position should be scrolled into view after + // modifying the selection. + + // If shift is held or the extend flag is set, extends a range to + // include a given position (and optionally a second position). + // Otherwise, simply returns the range between the given positions. + // Used for cursor motion and such. + function extendRange (doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head; + head = other; + } else if (posBefore != (cmp(head, other) < 0)) { + head = other; + } + } + return new Range(anchor, head); + } + return new Range(other || head, head); + + } + + // Extend the primary selection range, discard the rest. + function extendSelection (doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); + } + + // Extend all selections (pos is an array of selections with length + // equal the number of selections) + function extendSelections (doc, heads, options) { + for (var out = [], i = 0; i < doc.sel.ranges.length; i++) {out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);} + var newSel = normalizeSelection(out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + + // Updates a single range in the selection. + function replaceOneSelection (doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i] = range; + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); + } + + // Reset the selection to a single range. + function setSimpleSelection (doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + + // Give beforeSelectionChange handlers a change to influence a + // selection update. + function filterSelectionChange (doc, sel) { + var obj = { + ranges: sel.ranges, + update: function (ranges) { + this.ranges = []; + for (var i = 0; i < ranges.length; i++) { + this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)); + } + } + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); + return sel; + } + + function setSelectionReplaceHistory (doc, sel, options) { + var done = doc.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } + + // Set a new selection. + function setSelection (doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } + + function setSelectionNoUndo (doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {sel = filterSelectionChange(doc, sel);} + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + + if (!(options && options.scroll === false) && doc.cm) {ensureCursorVisible(doc.cm);} + } + + function setSelectionInner (doc, sel) { + if (sel.equals(doc.sel)) return; + + doc.sel = sel; + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + + // Verify that the selection does not partially select any atomic + // marked ranges. + function reCheckSelection (doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); + } + + // Return a selection that does not partially select any atomic + // ranges. + function skipAtomicInSelection (doc, sel, bias, mayClear) { + var out; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range.head, bias, mayClear); + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) out = sel.ranges.slice(0, i); + out[i] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel; + } + + // Ensure a given position is not inside an atomic range. + function skipAtomic (doc, pos, bias, mayClear) { + var flipped = false, curPos = pos; + var dir = bias || 1; + doc.cantEdit = false; + search: for (;;) { + var line = getLine(doc, curPos.line); + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) break; + else {--i; continue;} + } + } + if (!m.atomic) continue; + var newPos = m.find(dir < 0 ? -1 : 1); + if (cmp(newPos, curPos) == 0) { + newPos.ch += dir; + if (newPos.ch < 0) { + if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); + else newPos = null; + } else if (newPos.ch > line.text.length) { + if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); + else newPos = null; + } + if (!newPos) { + if (flipped) { + // Driven in a corner -- no valid cursor position found at all + // -- try again *with* clearing, if we didn't already + if (!mayClear) return skipAtomic(doc, pos, bias, true); + // Otherwise, turn off editing until further notice, and return the start of the doc + doc.cantEdit = true; + return Pos(doc.first, 0); + } + flipped = true; newPos = pos; dir = -dir; + } + } + curPos = newPos; + continue search; + } + } + } + return curPos; + } + } + + // SELECTION DRAWING + + function updateSelection (cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + + function prepareSelection (cm, primary) { + var doc = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) continue; + var range = doc.sel.ranges[i]; + var collapsed = range.empty(); + if (collapsed || cm.options.showCursorWhenSelecting) {drawSelectionCursor(cm, range, curFragment);} + if (!collapsed) {drawSelectionRange(cm, range, selFragment);} + } + return result; + } + + // Draws a cursor for the given range + function drawSelectionCursor (cm, range, output) { + var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine); + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } + } + + // Draws the given range as a highlighted selection + function drawSelectionRange (cm, range, output) { + var display = cm.display, doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + + function add (left, top, width, bottom) { + if (top < 0) top = 0; + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + + "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + + "px; height: " + (bottom - top) + "px")); + } + + function drawForLine (line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords (ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right; + if (from == to) { + rightPos = leftPos; + left = right = leftPos.left; + } else { + rightPos = coords(to - 1, "right"); + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } + left = leftPos.left; + right = rightPos.right; + } + if (fromArg == null && from == 0) left = leftSide; + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom); + left = leftSide; + if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); + } + if (toArg == null && to == lineLen) right = rightSide; + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) {start = leftPos;} + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) {end = rightPos;} + if (left < leftSide + 1) left = leftSide; + add(left, rightPos.top, right - left, rightPos.bottom); + }); + return {start: start, end: end}; + } + + var sFrom = range.from(), sTo = range.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) {add(leftSide, leftEnd.bottom, null, rightStart.top);} + } + + output.appendChild(fragment); + } + + // Cursor-blinking + function restartBlink (cm) { + if (!cm.state.focused) return; + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) { + display.blinker = setInterval(function () { + display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + } else if (cm.options.cursorBlinkRate < 0) {display.cursorDiv.style.visibility = "hidden";} + } + + // HIGHLIGHT WORKER + + function startWorker (cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) {cm.state.highlight.set(time, bind(highlightWorker, cm));} + } + + function highlightWorker (cm) { + var doc = cm.doc; + if (doc.frontier < doc.first) doc.frontier = doc.first; + if (doc.frontier >= cm.display.viewTo) return; + var end = +new Date + cm.options.workTime; + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); + var changedLines = []; + + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles; + var highlighted = highlightLine(cm, line, state, true); + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) line.styleClasses = newCls; + else if (oldCls) line.styleClasses = null; + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; + if (ischange) changedLines.push(doc.frontier); + line.stateAfter = copyState(doc.mode, state); + } else { + processLine(cm, line.text, state); + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; + } + ++doc.frontier; + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + if (changedLines.length) { + runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) {regLineChange(cm, changedLines[i], "text");} + }); + } + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine (cm, n, precise) { + var minindent, minline, doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) return doc.first; + var line = getLine(doc, search - 1); + if (line.stateAfter && (!precise || search <= doc.frontier)) return search; + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + + function getStateBefore (cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) return true; + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos - 1).stateAfter; + if (!state) state = startState(doc.mode); + else state = copyState(doc.mode, state); + doc.iter(pos, n, function (line) { + processLine(cm, line.text, state); + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; + line.stateAfter = save ? copyState(doc.mode, state) : null; + ++pos; + }); + if (precise) doc.frontier = pos; + return state; + } + + // POSITION MEASUREMENT + + function paddingTop (display) {return display.lineSpace.offsetTop;} + function paddingVert (display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} + function paddingH (display) { + if (display.cachedPaddingH) return display.cachedPaddingH; + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; + if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; + return data; + } + + function scrollGap (cm) { return scrollerGap - cm.display.nativeBarWidth; } + function displayWidth (cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight (cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + + // Ensure the lineView.wrapping.heights array is populated. This is + // an array of bottom offsets for the lines that make up a drawn + // line. When lineWrapping is on, there might be more than one + // height. + function ensureLineHeights (cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) {heights.push((cur.bottom + next.top) / 2 - rect.top);} + } + } + heights.push(rect.bottom - rect.top); + } + } + + // Find a line map (mapping character offsets to text nodes) and a + // measurement cache for the given line number. (A line view might + // contain multiple lines when collapsed ranges are present.) + function mapFromLineView (lineView, line, lineN) { + if (lineView.line == line) {return {map: lineView.measure.map, cache: lineView.measure.cache};} + for (var i = 0; i < lineView.rest.length; i++) { + if (lineView.rest[i] == line) {return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};} + } + for (var i = 0; i < lineView.rest.length; i++) { + if (lineNo(lineView.rest[i]) > lineN) {return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};} + } + } + + // Render a line into the hidden node display.externalMeasured. Used + // when measurement is needed for a line that's not in the viewport. + function updateExternalMeasurement (cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + + // Get a {top, bottom, left, right} box (in line-local coordinates) + // for a given character. + function measureChar (cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + + // Find a line view that corresponds to the given line number. + function findViewForLine (cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) {return cm.display.view[findViewIndex(cm, lineN)];} + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) {return ext;} + } + + // Measurement can be split in two steps, the set-up work that + // applies to the whole line, and the measurement of the actual + // character. Functions like coordsChar, that need to do a lot of + // measurements in a row, can thus ensure that the set-up work is + // only done once. + function prepareMeasureForLine (cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) {view = null;} else if (view && view.changes) {updateLineForChanges(cm, view, lineN, getDimensions(cm));} + if (!view) {view = updateExternalMeasurement(cm, line);} + + var info = mapFromLineView(view, line, lineN); + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + }; + } + + // Given a prepared measurement object, measures the position of an + // actual character (or fetches it from the cache). + function measureCharPrepared (cm, prepared, ch, bias, varHeight) { + if (prepared.before) ch = -1; + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) {prepared.rect = prepared.view.text.getBoundingClientRect();} + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) prepared.cache[key] = found; + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom}; + } + + var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; + + function nodeAndOffsetInLineMap (map, ch, bias) { + var node, start, end, collapse; + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + var mStart = map[i], mEnd = map[i + 1]; + if (ch < mStart) { + start = 0; end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) collapse = "right"; + } + if (start != null) { + node = map[i + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) {collapse = bias;} + if (bias == "left" && start == 0) { + while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2]; + collapse = "left"; + } + } + if (bias == "right" && start == mEnd - mStart) { + while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2]; + collapse = "right"; + } + } + break; + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; + } + + function measureCharInner (cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + + var rect; + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); + } else if (ie && cm.options.lineWrapping) { + var rects = range(node, start, end).getClientRects(); + if (rects.length) {rect = rects[bias == "right" ? rects.length - 1 : 0];} else {rect = nullRect;} + } else { + rect = range(node, start, end).getBoundingClientRect() || nullRect; + } + if (rect.left || rect.right || start == 0) break; + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) collapse = bias = "right"; + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) {rect = rects[bias == "right" ? rects.length - 1 : 0];} else {rect = node.getBoundingClientRect();} + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) {rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};} else {rect = nullRect;} + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + for (var i = 0; i < heights.length - 1; i++) {if (mid < heights[i]) break;} + var top = i ? heights[i - 1] : 0, bot = heights[i]; + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot}; + if (!rect.left && !rect.right) result.bogus = true; + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } + + return result; + } + + // Work around problem with bounding client rects on ranges being + // returned incorrectly when zoomed on IE10 and below. + function maybeUpdateRectForZooming (measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) {return rect;} + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY}; + } + + function clearLineMeasurementCacheFor (lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { + for (var i = 0; i < lineView.rest.length; i++) {lineView.measure.caches[i] = {};} + } + } + } + + function clearLineMeasurementCache (cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i = 0; i < cm.display.view.length; i++) {clearLineMeasurementCacheFor(cm.display.view[i]);} + } + + function clearCaches (cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; + cm.display.lineNumChars = null; + } + + function pageScrollX () { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } + function pageScrollY () { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } + + // Converts a {top, bottom, left, right} box from line-local + // coordinates into another coordinate system. Context may be one of + // "line", "div" (display.lineDiv), "local"/null (editor), "window", + // or "page". + function intoCoordSystem (cm, lineObj, rect, context) { + if (lineObj.widgets) { + for (var i = 0; i < lineObj.widgets.length; ++i) { + if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]); + rect.top += size; rect.bottom += size; + } + } + } + if (context == "line") return rect; + if (!context) context = "local"; + var yOff = heightAtLine(lineObj); + if (context == "local") yOff += paddingTop(cm.display); + else yOff -= cm.display.viewOffset; + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect; + } + + // Coverts a box from "div" coords to another coordinate system. + // Context may be "window", "page", "div", or "local"/null. + function fromCoordSystem (cm, coords, context) { + if (context == "div") return coords; + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; + } + + function charCoords (cm, pos, context, lineObj, bias) { + if (!lineObj) lineObj = getLine(cm.doc, pos.line); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + + // Returns a box for a given cursor position, which may have an + // 'other' property containing the position of the secondary cursor + // on a bidi boundary. + function cursorCoords (cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); + function get (ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); + if (right) m.left = m.right; else m.right = m.left; + return intoCoordSystem(cm, lineObj, m, context); + } + function getBidi (ch, partPos) { + var part = order[partPos], right = part.level % 2; + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos]; + ch = bidiRight(part) - (part.level % 2 ? 0 : 1); + right = true; + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos]; + ch = bidiLeft(part) - part.level % 2; + right = false; + } + if (right && ch == part.to && ch > part.from) return get(ch - 1); + return get(ch, right); + } + var order = getOrder(lineObj), ch = pos.ch; + if (!order) return get(ch); + var partPos = getBidiPartAt(order, ch); + var val = getBidi(ch, partPos); + if (bidiOther != null) val.other = getBidi(ch, bidiOther); + return val; + } + + // Used to cheaply estimate the coordinates for a position. Used for + // intermediate scroll updates. + function estimateCoords (cm, pos) { + var left = 0, pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return {left: left, right: left, top: top, bottom: top + lineObj.height}; + } + + // Positions returned by coordsChar contain some extra information. + // xRel is the relative x position of the input coordinates compared + // to the found position (so xRel > 0 means the coordinates are to + // the right of the character position, for example). When outside + // is true, that means the coordinates lie outside the line's + // vertical range. + function PosWithInfo (line, ch, outside, xRel) { + var pos = Pos(line, ch); + pos.xRel = xRel; + if (outside) pos.outside = true; + return pos; + } + + // Compute the character position closest to the given coordinates. + // Input must be lineSpace-local ("div" coordinate system). + function coordsChar (cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) return PosWithInfo(doc.first, 0, true, -1); + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineN > last) {return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);} + if (x < 0) x = 0; + + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var merged = collapsedSpanAtEnd(lineObj); + var mergedPos = merged && merged.find(0, true); + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) {lineN = lineNo(lineObj = mergedPos.to.line);} else {return found;} + } + } + + function coordsCharInner (cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(lineObj); + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + + function getX (ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); + wrongLine = true; + if (innerOff > sp.bottom) return sp.left - adjust; + else if (innerOff < sp.top) return sp.left + adjust; + wrongLine = false; + return sp.left; + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length; + var from = lineLeft(lineObj), to = lineRight(lineObj); + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; + + if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to; + var xDiff = x - (ch == from ? fromX : toX); + while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; + var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, + xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); + return pos; + } + var step = Math.ceil(dist / 2), middle = from + step; + if (bidi) { + middle = from; + for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); + } + var middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} + } + } + + var measureText; + // Compute the default text height. + function textHeight (display) { + if (display.cachedTextHeight != null) return display.cachedTextHeight; + if (measureText == null) { + measureText = elt("pre"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) display.cachedTextHeight = height; + removeChildren(display.measure); + return height || 1; + } + + // Compute the default character width. + function charWidth (display) { + if (display.cachedCharWidth != null) return display.cachedCharWidth; + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) display.cachedCharWidth = width; + return width || 10; + } + + // OPERATIONS + + // Operations are used to wrap a series of changes to the editor + // state in such a way that each change won't have to update the + // cursor and display (which would be awkward, slow, and + // error-prone). Instead, display updates are batched and then all + // combined and executed at once. + + var operationGroup = null; + + var nextOpId = 0; + // Start a new operation. + function startOperation (cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + }; + if (operationGroup) { + operationGroup.ops.push(cm.curOp); + } else { + cm.curOp.ownsGroup = operationGroup = { + ops: [cm.curOp], + delayedCallbacks: [] + }; + } + } + + function fireCallbacksForOps (group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0; + do { + for (; i < callbacks.length; i++) {callbacks[i]();} + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) { + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) {op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);} + } + } + } while (i < callbacks.length); + } + + // Finish an operation, updating the display and signalling delayed events + function endOperation (cm) { + var op = cm.curOp, group = op.ownsGroup; + if (!group) return; + + try { fireCallbacksForOps(group); } finally { + operationGroup = null; + for (var i = 0; i < group.ops.length; i++) {group.ops[i].cm.curOp = null;} + endOperations(group); + } + } + + // The DOM updates done when an operation finishes are batched so + // that the minimum number of relayouts are required. + function endOperations (group) { + var ops = group.ops; + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_R1(ops[i]);} + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + {endOperation_W1(ops[i]);} + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_R2(ops[i]);} + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + {endOperation_W2(ops[i]);} + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_finish(ops[i]);} + } + + function endOperation_R1 (op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) findMaxLine(cm); + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); + } + + function endOperation_W1 (op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + + function endOperation_R2 (op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) updateHeightsInViewport(cm); + + op.barMeasure = measureForScrollbars(cm); + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + + if (op.updatedDisplay || op.selectionChanged) {op.preparedSelection = display.input.prepareSelection();} + } + + function endOperation_W2 (op) { + var cm = op.cm; + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) {setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);} + cm.display.maxLineChanged = false; + } + + if (op.preparedSelection) {cm.display.input.showSelection(op.preparedSelection);} + if (op.updatedDisplay) {setDocumentHeight(cm, op.barMeasure);} + if (op.updatedDisplay || op.startHeight != cm.doc.height) {updateScrollbars(cm, op.barMeasure);} + + if (op.selectionChanged) restartBlink(cm); + + if (cm.state.focused && op.updateInput) {cm.display.input.reset(op.typing);} + if (op.focus && op.focus == activeElt()) ensureFocus(op.cm); + } + + function endOperation_finish (op) { + var cm = op.cm, display = cm.display, doc = cm.doc; + + if (op.updatedDisplay) postUpdateDisplay(cm, op.update); + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) {display.wheelStartX = display.wheelStartY = null;} + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); + display.scrollbars.setScrollTop(doc.scrollTop); + display.scroller.scrollTop = doc.scrollTop; + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft)); + display.scrollbars.setScrollLeft(doc.scrollLeft); + display.scroller.scrollLeft = doc.scrollLeft; + alignHorizontally(cm); + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) { + for (var i = 0; i < hidden.length; ++i) {if (!hidden[i].lines.length) signal(hidden[i], "hide");} + } + if (unhidden) { + for (var i = 0; i < unhidden.length; ++i) {if (unhidden[i].lines.length) signal(unhidden[i], "unhide");} + } + + if (display.wrapper.offsetHeight) {doc.scrollTop = cm.display.scroller.scrollTop;} + + // Fire change events, and delayed event handlers + if (op.changeObjs) {signal(cm, "changes", cm, op.changeObjs);} + if (op.update) {op.update.finish();} + } + + // Run the given function in an operation + function runInOp (cm, f) { + if (cm.curOp) return f(); + startOperation(cm); + try { return f(); } finally { endOperation(cm); } + } + // Wraps a function in an operation. Returns the wrapped function. + function operation (cm, f) { + return function () { + if (cm.curOp) return f.apply(cm, arguments); + startOperation(cm); + try { return f.apply(cm, arguments); } finally { endOperation(cm); } + }; + } + // Used to add methods to editor and doc instances, wrapping them in + // operations. + function methodOp (f) { + return function () { + if (this.curOp) return f.apply(this, arguments); + startOperation(this); + try { return f.apply(this, arguments); } finally { endOperation(this); } + }; + } + function docMethodOp (f) { + return function () { + var cm = this.cm; + if (!cm || cm.curOp) return f.apply(this, arguments); + startOperation(cm); + try { return f.apply(this, arguments); } finally { endOperation(cm); } + }; + } + + // VIEW TRACKING + + // These objects are used to represent the visible (currently drawn) + // part of the document. A LineView may correspond to multiple + // logical lines, if those are connected by collapsed ranges. + function LineView (doc, line, lineN) { + // The starting line + this.line = line; + // Continuing lines, if any + this.rest = visualLineContinued(line); + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + + // Create a range of LineView objects for the given lines. + function buildViewArray (cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + + // Updates the display.view data structure for a given change to the + // document. From and to are in pre-change coordinates. Lendiff is + // the amount of lines added or subtracted by the change. This is + // used for changes that span multiple lines, or change the way + // lines are divided into visual lines. regLineChange (below) + // registers single-line changes. + function regChange (cm, from, to, lendiff) { + if (from == null) from = cm.doc.first; + if (to == null) to = cm.doc.first + cm.doc.size; + if (!lendiff) lendiff = 0; + + var display = cm.display; + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) {display.updateLineNumbers = from;} + + cm.curOp.viewChanged = true; + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) {resetView(cm);} + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm); + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut = viewCuttingPoint(cm, from, from, -1); + if (cut) { + display.view = display.view.slice(0, cut.index); + display.viewTo = cut.lineN; + } else { + resetView(cm); + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) {ext.lineN += lendiff;} else if (from < ext.lineN + ext.size) {display.externalMeasured = null;} + } + } + + // Register a change to a single line. Type must be one of "text", + // "gutter", "class", "widget" + function regLineChange (cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) {display.externalMeasured = null;} + + if (line < display.viewFrom || line >= display.viewTo) return; + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) return; + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) arr.push(type); + } + + // Clear the view. + function resetView (cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + + // Find the view element corresponding to a given line. Return null + // when the line isn't visible. + function findViewIndex (cm, n) { + if (n >= cm.display.viewTo) return null; + n -= cm.display.viewFrom; + if (n < 0) return null; + var view = cm.display.view; + for (var i = 0; i < view.length; i++) { + n -= view[i].size; + if (n < 0) return i; + } + } + + function viewCuttingPoint (cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) {return {index: index, lineN: newN};} + for (var i = 0, n = cm.display.viewFrom; i < index; i++) {n += view[i].size;} + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) return null; + diff = (n + view[index].size) - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) return null; + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return {index: index, lineN: newN}; + } + + // Force the view to cover a given range, adding empty view element + // or clipping off existing ones as needed. + function adjustView (cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) {display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);} else if (display.viewFrom < from) {display.view = display.view.slice(findViewIndex(cm, from));} + display.viewFrom = from; + if (display.viewTo < to) {display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));} else if (display.viewTo > to) {display.view = display.view.slice(0, findViewIndex(cm, to));} + } + display.viewTo = to; + } + + // Count the number of lines in the view whose DOM representation is + // out of date (or nonexistent). + function countDirtyView (cm) { + var view = cm.display.view, dirty = 0; + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; + } + return dirty; + } + + // EVENT HANDLERS + + // Attach the necessary event handlers when initializing the editor + function registerEventHandlers (cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) { + on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) return; + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); + } else {on(d.scroller, "dblclick", function (e) { signalDOMEvent(cm, e) || e_preventDefault(e); });} + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) on(d.scroller, "contextmenu", function (e) {onContextMenu(cm, e);}); + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0}; + function finishTouch () { + if (d.activeTouch) { + touchFinished = setTimeout(function () {d.activeTouch = null;}, 1000); + prevTouch = d.activeTouch; + prevTouch.end = +new Date; + } + } + function isMouseLikeTouchEvent (e) { + if (e.touches.length != 1) return false; + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway (touch, other) { + if (other.left == null) return true; + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function (e) { + if (!isMouseLikeTouchEvent(e)) { + clearTimeout(touchFinished); + var now = +new Date; + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null}; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function () { + if (d.activeTouch) d.activeTouch.moved = true; + }); + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range; + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + {range = new Range(pos, pos);} else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + {range = cm.findWordAt(pos);} else // Triple tap + {range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));} + cm.setSelection(range.anchor, range.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) {onScrollWheel(cm, e);}); + on(d.scroller, "DOMMouseScroll", function (e) {onScrollWheel(cm, e);}); + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + d.dragFunctions = { + simple: function (e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, + start: function (e) {onDragStart(cm, e);}, + drop: operation(cm, onDrop) + }; + + var inp = d.input.getField(); + on(inp, "keyup", function (e) { onKeyUp.call(cm, e); }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", bind(onFocus, cm)); + on(inp, "blur", bind(onBlur, cm)); + } + + function dragDropChanged (cm, value, old) { + var wasOn = old && old != CodeMirror.Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.simple); + toggle(cm.display.scroller, "dragover", funcs.simple); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + + // Called when the window resizes + function onResize (cm) { + var d = cm.display; + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) {return;} + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + + // MOUSE EVENTS + + // Return true when the given mouse event happened in a widget + function eventInWidget (display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) {return true;} + } + } + + // Given a mouse event, find the corresponding position. If liberal + // is false, it checks whether a gutter or scrollbar was clicked, + // and returns null if it was. forRect is used by rectangular + // selections, and tries to estimate a character position even for + // coordinates beyond the right of the text. + function posFromMouse (cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; + + var x, y, space = display.lineSpace.getBoundingClientRect(); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top; } catch (e) { return null; } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords; + } + + // A mouse down can be a single click, double click, triple click, + // start of selection drag, start of text drag, new cursor + // (ctrl-click), rectangle drag (alt-drag), or xwin + // middle-click-paste. Or it might be a click on something we should + // not interfere with, such as a scrollbar or widget. + function onMouseDown (e) { + var cm = this, display = cm.display; + if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return; + display.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false; + setTimeout(function () {display.scroller.draggable = true;}, 100); + } + return; + } + if (clickInGutter(cm, e)) return; + var start = posFromMouse(cm, e); + window.focus(); + + switch (e_button(e)) { + case 1: + if (start) {leftButtonDown(cm, e, start);} else if (e_target(e) == display.scroller) {e_preventDefault(e);} + break; + case 2: + if (webkit) cm.state.lastMiddleDown = +new Date; + if (start) extendSelection(cm.doc, start); + setTimeout(function () {display.input.focus();}, 20); + e_preventDefault(e); + break; + case 3: + if (captureRightClick) onContextMenu(cm, e); + else delayBlurEvent(cm); + break; + } + } + + var lastClick, lastDoubleClick; + function leftButtonDown (cm, e, start) { + if (ie) setTimeout(bind(ensureFocus, cm), 0); + else cm.curOp.focus = activeElt(); + + var now = +new Date, type; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple"; + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double"; + lastDoubleClick = {time: now, pos: start}; + } else { + type = "single"; + lastClick = {time: now, pos: start}; + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; + if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) {leftButtonStartDrag(cm, e, start, modifier);} else {leftButtonSelect(cm, e, start, type, modifier);} + } + + // Start a text drag. When it ends, see if any dragging actually + // happen, and treat as a click if it didn't. + function leftButtonStartDrag (cm, e, start, modifier) { + var display = cm.display, startTime = +new Date; + var dragEnd = operation(cm, function (e2) { + if (webkit) display.scroller.draggable = false; + cm.state.draggingText = false; + off(document, "mouseup", dragEnd); + off(display.scroller, "drop", dragEnd); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + if (!modifier && +new Date - 200 < startTime) {extendSelection(cm.doc, start);} + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) {setTimeout(function () {document.body.focus(); display.input.focus();}, 20);} else {display.input.focus();} + } + }); + // Let the drag handler handle this. + if (webkit) display.scroller.draggable = true; + cm.state.draggingText = dragEnd; + // IE's approach to draggable + if (display.scroller.dragDrop) display.scroller.dragDrop(); + on(document, "mouseup", dragEnd); + on(display.scroller, "drop", dragEnd); + } + + // Normal selection, as opposed to text dragging. + function leftButtonSelect (cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc; + e_preventDefault(e); + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) {ourRange = ranges[ourIndex];} else {ourRange = new Range(start, start);} + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + + if (e.altKey) { + type = "rect"; + if (!addNew) ourRange = new Range(start, start); + start = posFromMouse(cm, e, true, true); + ourIndex = -1; + } else if (type == "double") { + var word = cm.findWordAt(start); + if (cm.display.shift || doc.extend) {ourRange = extendRange(doc, ourRange, word.anchor, word.head);} else {ourRange = word;} + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); + if (cm.display.shift || doc.extend) {ourRange = extendRange(doc, ourRange, line.anchor, line.head);} else {ourRange = line;} + } else { + ourRange = extendRange(doc, ourRange, start); + } + + if (!addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0)); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + + var lastPos = start; + function extendTo (pos) { + if (cmp(lastPos, pos) == 0) return; + lastPos = pos; + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) {ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));} else if (text.length > leftPos) {ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));} + } + if (!ranges.length) ranges.push(new Range(start, start)); + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var anchor = oldRange.anchor, head = pos; + if (type != "single") { + if (type == "double") {var range = cm.findWordAt(pos);} else {var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));} + if (cmp(range.anchor, anchor) > 0) { + head = range.head; + anchor = minPos(oldRange.from(), range.anchor); + } else { + head = range.anchor; + anchor = maxPos(oldRange.to(), range.head); + } + } + var ranges = startSel.ranges.slice(0); + ranges[ourIndex] = new Range(clipPos(doc, anchor), head); + setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend (e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, type == "rect"); + if (!cur) return; + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) {setTimeout(operation(cm, function () {if (counter == curCount) extend(e);}), 150);} + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) { + setTimeout(operation(cm, function () { + if (counter != curCount) return; + display.scroller.scrollTop += outside; + extend(e); + }), 50); + } + } + } + + function done (e) { + counter = Infinity; + e_preventDefault(e); + display.input.focus(); + off(document, "mousemove", move); + off(document, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function (e) { + if (!e_button(e)) done(e); + else extend(e); + }); + var up = operation(cm, done); + on(document, "mousemove", move); + on(document, "mouseup", up); + } + + // Determines whether an event happened in the gutter, and fires the + // handlers for the corresponding event. + function gutterEvent (cm, e, type, prevent, signalfn) { + try { var mX = e.clientX, mY = e.clientY; } catch(e) { return false; } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; + if (prevent) e_preventDefault(e); + + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + + if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.options.gutters[i]; + signalfn(cm, type, cm, line, gutter, e); + return e_defaultPrevented(e); + } + } + } + + function clickInGutter (cm, e) { + return gutterEvent(cm, e, "gutterClick", true, signalLater); + } + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop (e) { + var cm = this; + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {return;} + e_preventDefault(e); + if (ie) lastDrop = +new Date; + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || isReadOnly(cm)) return; + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function (file, i) { + var reader = new FileReader; + reader.onload = operation(cm, function () { + text[i] = reader.result; + if (++read == n) { + pos = clipPos(cm.doc, pos); + var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); + } + }); + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(function () {cm.display.input.focus();}, 20); + return; + } + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) {var selected = cm.listSelections();} + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { + for (var i = 0; i < selected.length; ++i) {replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");} + } + cm.replaceSelection(text, "around", "paste"); + cm.display.input.focus(); + } + } catch(e) {} + } + } + + function onDragStart (cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; + + e.dataTransfer.setData("Text", cm.getSelection()); + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) img.parentNode.removeChild(img); + } + } + + // SCROLL EVENTS + + // Sync the scrollable area and scrollbars, ensure the viewport + // covers the visible area. + function setScrollTop (cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) return; + cm.doc.scrollTop = val; + if (!gecko) updateDisplaySimple(cm, {top: val}); + if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (gecko) updateDisplaySimple(cm); + startWorker(cm, 100); + } + // Sync scroller and scrollbar, ensure the gutter elements are + // aligned. + function setScrollLeft (cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; + cm.display.scrollbars.setScrollLeft(val); + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) wheelPixelsPerUnit = -.53; + else if (gecko) wheelPixelsPerUnit = 15; + else if (chrome) wheelPixelsPerUnit = -.7; + else if (safari) wheelPixelsPerUnit = -1 / 3; + + var wheelEventDelta = function (e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; + else if (dy == null) dy = e.wheelDelta; + return {x: dx, y: dy}; + }; + CodeMirror.wheelEventPixels = function (e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + }; + + function onScrollWheel (cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + if (!(dx && scroll.scrollWidth > scroll.clientWidth || + dy && scroll.scrollHeight > scroll.clientHeight)) return; + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy) {setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));} + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); + e_preventDefault(e); + display.wheelStartX = null; // Abort measurement, if in progress + return; + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) top = Math.max(0, top + pixels - 50); + else bot = Math.min(cm.doc.height, bot + pixels + 50); + updateDisplaySimple(cm, {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function () { + if (display.wheelStartX == null) return; + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) return; + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + // KEY EVENTS + + // Run a handler that was bound to a key. + function doHandleBinding (cm, bound, dropShift) { + if (typeof bound === "string") { + bound = commands[bound]; + if (!bound) return false; + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (isReadOnly(cm)) cm.state.suppressEdits = true; + if (dropShift) cm.display.shift = false; + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + + function lookupKeyForEditor (cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); + if (result) return result; + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm); + } + + var stopSeq = new Delayed; + function dispatchKey (cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) return "handled"; + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + name = seq + " " + name; + } + var result = lookupKeyForEditor(cm, name, handle); + + if (result == "multi") {cm.state.keySeq = name;} + if (result == "handled") {signalLater(cm, "keyHandled", cm, name, e);} + + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e); + return true; + } + return !!result; + } + + // Handle a key from the keydown event. + function handleKeyBinding (cm, e) { + var name = keyName(e, true); + if (!name) return false; + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) {return doHandleBinding(cm, b, true);}) + || dispatchKey(cm, name, e, function (b) { + if (typeof b === "string" ? /^go[A-Z]/.test(b) : b.motion) {return doHandleBinding(cm, b);} + }); + } + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }); + + } + + // Handle a key from the keypress event + function handleCharBinding (cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, + function (b) { return doHandleBinding(cm, b, true); }); + } + + var lastStoppedKey = null; + function onKeyDown (e) { + var cm = this; + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) return; + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) {cm.replaceSelection("", null, "cut");} + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) {showCrossHair(cm);} + } + + function showCrossHair (cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + + function up (e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + + function onKeyUp (e) { + if (e.keyCode == 16) this.doc.sel.shift = false; + signalDOMEvent(this, e); + } + + function onKeyPress (e) { + var cm = this; + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (handleCharBinding(cm, e, ch)) return; + cm.display.input.onKeyPress(e); + } + + // FOCUS/BLUR EVENTS + + function delayBlurEvent (cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function () { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + onBlur(cm); + } + }, 100); + } + + function onFocus (cm) { + if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; + + if (cm.options.readOnly == "nocursor") return; + if (!cm.state.focused) { + signal(cm, "focus", cm); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) setTimeout(function () { cm.display.input.reset(true); }, 20); // Issue #1730 + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur (cm) { + if (cm.state.delayingBlurEvent) return; + + if (cm.state.focused) { + signal(cm, "blur", cm); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function () {if (!cm.state.focused) cm.display.shift = false;}, 150); + } + + // CONTEXT MENU HANDLING + + // To make the context menu work, we need to briefly unhide the + // textarea (making it as unobtrusive as possible) to let the + // right-click take effect on it. + function onContextMenu (cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; + cm.display.input.onContextMenu(e); + } + + function contextMenuInGutter (cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) return false; + return gutterEvent(cm, e, "gutterContextMenu", false, signal); + } + + // UPDATING + + // Compute the position of the end of a change (its 'to' property + // refers to the pre-change end). + var changeEnd = CodeMirror.changeEnd = function (change) { + if (!change.text) return change.to; + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); + }; + + // Adjust a position to refer to the post-change position of the + // same text, or the end of the change if the change covers it. + function adjustForChange (pos, change) { + if (cmp(pos, change.from) < 0) return pos; + if (cmp(pos, change.to) <= 0) return changeEnd(change); + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; + return Pos(line, ch); + } + + function computeSelAfterChange (doc, change) { + var out = []; + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))); + } + return normalizeSelection(out, doc.sel.primIndex); + } + + function offsetPos (pos, old, nw) { + if (pos.line == old.line) {return Pos(nw.line, pos.ch - old.ch + nw.ch);} + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + + // Used by replaceSelections to allow moving the selection to the + // start or around the replaced test. Hint may be "start" or "around". + function computeReplacedSel (doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; + out[i] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex); + } + + // Allow "beforeChange" event handlers to influence a change + function filterChange (doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { this.canceled = true; } + }; + if (update) { + obj.update = function (from, to, text, origin) { + if (from) this.from = clipPos(doc, from); + if (to) this.to = clipPos(doc, to); + if (text) this.text = text; + if (origin !== undefined) this.origin = origin; + }; + } + signal(doc, "beforeChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); + + if (obj.canceled) return null; + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; + } + + // Apply a change to a document, and add it to the document's + // history, and propagating it to all linked documents. + function makeChange (doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); + if (doc.cm.state.suppressEdits) return; + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) return; + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 0; --i) {makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});} + } else { + makeChangeInner(doc, change); + } + } + + function makeChangeInner (doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + // Revert a change stored in a document's history. + function makeChangeFromHistory (doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits) return; + + var hist = doc.history, event, selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + for (var i = 0; i < source.length; i++) { + event = source[i]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) {break;} + } + if (i == source.length) return; + hist.lastOrigin = hist.lastSelOrigin = null; + + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}); + return; + } + selAfter = event; + } else break; + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({changes: antiChanges, generation: hist.generation}); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + for (var i = event.changes.length - 1; i >= 0; --i) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return; + } + + antiChanges.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); + var rebased = []; + + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + } + } + + // Sub-views need their line numbers shifted when text is added + // above or below them in the parent document. + function shiftDoc (doc, distance) { + if (distance == 0) return; + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function (range) { + return new Range(Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch)); + }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) {regLineChange(doc.cm, l, "gutter");} + } + } + + // More lower-level change function, handling only a single document + // (not linked ones). + function makeChangeSingleDoc (doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) {return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);} + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) return; + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) selAfter = computeSelAfterChange(doc, change); + if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); + else updateDoc(doc, change, spans); + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + } + + // Handle the interaction of a change to a document with the editor + // that this document is part of. + function makeChangeSingleDocInEditor (cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + + if (doc.sel.contains(change.from, change.to) > -1) {signalCursorActivity(cm);} + + updateDoc(doc, change, spans, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) cm.curOp.updateMaxLine = true; + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + if (change.full) {regChange(cm);} else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) {regLineChange(cm, from.line, "text");} else {regChange(cm, from.line, to.line + 1, lendiff);} + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) signalLater(cm, "change", cm, obj); + if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); + } + cm.display.selForContextMenu = null; + } + + function replaceRange (doc, code, from, to, origin) { + if (!to) to = from; + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } + if (typeof code === "string") code = splitLines(code); + makeChange(doc, {from: from, to: to, text: code, origin: origin}); + } + + // SCROLLING THINGS INTO VIEW + + // If an editor sits on the top or bottom of the window, partially + // scrolled out of view, this ensures that the cursor is visible. + function maybeScrollWindow (cm, coords) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) return; + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + if (coords.top + box.top < 0) doScroll = true; + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + + coords.left + "px; width: 2px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + + // Scroll a given position into view (immediately), verifying that + // it actually became visible (as line heights are accurately + // measured, the position of something may 'drift' during drawing). + function scrollPosIntoView (cm, pos, end, margin) { + if (margin == null) margin = 0; + for (var limit = 0; limit < 5; limit++) { + var changed = false, coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), + Math.min(coords.top, endCoords.top) - margin, + Math.max(coords.left, endCoords.left), + Math.max(coords.bottom, endCoords.bottom) + margin); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; + } + if (!changed) break; + } + return coords; + } + + // Scroll a given set of coordinates into view (immediately). + function scrollIntoView (cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); + if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); + if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); + } + + // Calculate a new scroll position needed to scroll the given + // rectangle into view. Returns an object with scrollTop and + // scrollLeft properties. When these are undefined, the + // vertical/horizontal position does not need to be adjusted. + function calculateScrollPos (cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (y1 < 0) y1 = 0; + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen = displayHeight(cm), result = {}; + if (y2 - y1 > screen) y2 = y1 + screen; + var docBottom = cm.doc.height + paddingVert(display); + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1; + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); + if (newTop != screentop) result.scrollTop = newTop; + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); + var tooWide = x2 - x1 > screenw; + if (tooWide) x2 = x1 + screenw; + if (x1 < 10) {result.scrollLeft = 0;} else if (x1 < screenleft) {result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));} else if (x2 > screenw + screenleft - 3) {result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;} + return result; + } + + // Store a relative adjustment to the scroll position in the current + // operation (to be applied when the operation finishes). + function addToScrollPos (cm, left, top) { + if (left != null || top != null) resolveScrollToPos(cm); + if (left != null) {cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;} + if (top != null) {cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;} + } + + // Make sure that at the end of the operation the current cursor is + // shown. + function ensureCursorVisible (cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(), from = cur, to = cur; + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; + to = Pos(cur.line, cur.ch + 1); + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; + } + + // When an operation has its scrollToPos property set, and another + // scroll action is applied before the end of the operation, this + // 'simulates' scrolling that position into view in a cheap way, so + // that the effect of intermediate scroll commands is not ignored. + function resolveScrollToPos (cm) { + var range = cm.curOp.scrollToPos; + if (range) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); + var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), + Math.min(from.top, to.top) - range.margin, + Math.max(from.right, to.right), + Math.max(from.bottom, to.bottom) + range.margin); + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + } + + // API UTILITIES + + // Indent the given line. The how parameter can be "smart", + // "add"/null, "subtract", or "prev". When aggressive is false + // (typically set to true for forced single-line indents), empty + // lines are not indented, and places where the mode returns Pass + // are left alone. + function indentLine (cm, n, how, aggressive) { + var doc = cm.doc, state; + if (how == null) how = "add"; + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) how = "prev"; + else state = getStateBefore(cm, n); + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) line.stateAfter = null; + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) return; + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); + else indentation = 0; + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how === "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) {for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}} + if (pos < indentation) indentString += spaceStr(indentation - pos); + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i, new Range(pos, pos)); + break; + } + } + + } + + // Utility for applying a change to a line by handle or number, + // returning the number and optionally registering the line as + // changed. + function changeLine (doc, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle === "number") line = getLine(doc, clipLine(doc, handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); + return line; + } + + // Helper for deleting text near the selection(s), used to implement + // backspace, delete, and similar functionality. + function deleteNearSelection (cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } + } + kill.push(toKill); + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) {replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");} + ensureCursorVisible(cm); + }); + } + + // Used for horizontal relative motion. Dir is -1 or 1 (left or + // right), unit can be "char", "column" (like char, but doesn't + // cross line boundaries), "word" (across next word), or "group" (to + // the start of next group of word or non-word-non-whitespace + // chars). The visually param controls whether, in right-to-left + // text, direction 1 means to move towards the next index in the + // string, or towards the character to the right of the current + // position. The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosH (doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir; + var lineObj = getLine(doc, line); + var possible = true; + function findNextLine () { + var l = line + dir; + if (l < doc.first || l >= doc.first + doc.size) return (possible = false); + line = l; + return lineObj = getLine(doc, l); + } + function moveOnce (boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); + else ch = dir < 0 ? lineObj.text.length : 0; + } else return (possible = false); + } else ch = next; + return true; + } + + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true; ; first = false) { + if (dir < 0 && !moveOnce(!first)) break; + var cur = lineObj.text.charAt(ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p"; + if (group && !first && !type) type = "s"; + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce();} + break; + } + + if (type) sawType = type; + if (dir > 0 && !moveOnce(!first)) break; + } + } + var result = skipAtomic(doc, Pos(line, ch), origDir, true); + if (!possible) result.hitSide = true; + return result; + } + + // For relative vertical movement. Dir may be -1 or 1. Unit can be + // "page" or "line". The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosV (cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + for (;;) { + var target = coordsChar(cm, x, y); + if (!target.outside) break; + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } + y += dir * 5; + } + return target; + } + + // EDITOR METHODS + + // The publicly visible API. Note that methodOp(f) means + // 'wrap f in an operation, performed on its `this` parameter'. + + // This is not the complete set of editor methods. Most of the + // methods defined on the Doc type are also injected into + // CodeMirror.prototype, for backwards compatibility and + // convenience. + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function () {window.focus(); this.display.input.focus();}, + + setOption: function (option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") return; + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) {operation(this, optionHandlers[option])(this, value, old);} + }, + + getOption: function (option) {return this.options[option];}, + getDoc: function () {return this.doc;}, + + addKeyMap: function (map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); + }, + removeKeyMap: function (map) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) { + if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1); + return true; + } + } + }, + + addOverlay: methodOp(function (spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) throw new Error("Overlays may not be stateful."); + this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function (spec) { + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec === "string" && cur.name == spec) { + overlays.splice(i, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + + indentLine: methodOp(function (n, dir, aggressive) { + if (typeof dir !== "string" && typeof dir !== "number") { + if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); + }), + indentSelection: methodOp(function (how) { + var ranges = this.doc.sel.ranges, end = -1; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (!range.empty()) { + var from = range.from(), to = range.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) {indentLine(this, j, how);} + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) {replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);} + } else if (range.head.line > end) { + indentLine(this, range.head.line, how, true); + end = range.head.line; + if (i == this.doc.sel.primIndex) ensureCursorVisible(this); + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function (pos, precise) { + return takeToken(this, pos, precise); + }, + + getLineTokens: function (line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + + getTokenTypeAt: function (pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) type = styles[2]; + else { + for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; + else if (styles[mid * 2 + 1] < ch) before = mid + 1; + else { type = styles[mid * 2 + 2]; break; } + } + } + var cut = type ? type.indexOf("cm-overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + + getModeAt: function (pos) { + var mode = this.doc.mode; + if (!mode.innerMode) return mode; + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + + getHelper: function (pos, type) { + return this.getHelpers(pos, type)[0]; + }, + + getHelpers: function (pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) return found; + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] === "string") { + if (help[mode[type]]) found.push(help[mode[type]]); + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]]; + if (val) found.push(val); + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i = 0; i < help._global.length; i++) { + var cur = help._global[i]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) {found.push(cur.val);} + } + return found; + }, + + getStateAfter: function (line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line); + return getStateBefore(this, line + 1, precise); + }, + + cursorCoords: function (start, mode) { + var pos, range = this.doc.sel.primary(); + if (start == null) pos = range.head; + else if (typeof start === "object") pos = clipPos(this.doc, start); + else pos = start ? range.from() : range.to(); + return cursorCoords(this, pos, mode || "page"); + }, + + charCoords: function (pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + + coordsChar: function (coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + + lineAtHeight: function (height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function (line, mode) { + var end = false, lineObj; + if (typeof line === "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) line = this.doc.first; + else if (line > last) { line = last; end = true; } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + + defaultTextHeight: function () { return textHeight(this.display); }, + defaultCharWidth: function () { return charWidth(this.display); }, + + setGutterMarker: methodOp(function (line, gutterID, value) { + return changeLine(this.doc, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) line.gutterMarkers = null; + return true; + }); + }), + + clearGutter: methodOp(function (gutterID) { + var cm = this, doc = cm.doc, i = doc.first; + doc.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + line.gutterMarkers[gutterID] = null; + regLineChange(cm, i, "gutter"); + if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; + } + ++i; + }); + }), + + lineInfo: function (line) { + if (typeof line === "number") { + if (!isLine(this.doc, line)) return null; + var n = line; + line = getLine(this.doc, line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets}; + }, + + getViewport: function () { return {from: this.display.viewFrom, to: this.display.viewTo};}, + + addWidget: function (pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) {top = pos.top - node.offsetHeight;} else if (pos.bottom + node.offsetHeight <= vspace) {top = pos.bottom;} + if (left + node.offsetWidth > hspace) {left = hspace - node.offsetWidth;} + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = left + "px"; + } + if (scroll) {scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);} + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + + execCommand: function (cmd) { + if (commands.hasOwnProperty(cmd)) {return commands[cmd](this);} + }, + + triggerElectric: methodOp(function (text) { triggerElectric(this, text); }), + + findPosH: function (from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) break; + } + return cur; + }, + + moveH: methodOp(function (dir, unit) { + var cm = this; + cm.extendSelectionsBy(function (range) { + if (cm.display.shift || cm.doc.extend || range.empty()) {return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);} + return dir < 0 ? range.from() : range.to(); + }, sel_move); + }), + + deleteH: methodOp(function (dir, unit) { + var sel = this.doc.sel, doc = this.doc; + if (sel.somethingSelected()) {doc.replaceSelection("", null, "+delete");} else { + deleteNearSelection(this, function (range) { + var other = findPosH(doc, range.head, dir, unit, false); + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; + }); + } + }), + + findPosV: function (from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) x = coords.left; + else coords.left = x; + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) break; + } + return cur; + }, + + moveV: methodOp(function (dir, unit) { + var cm = this, doc = this.doc, goals = []; + var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function (range) { + if (collapse) {return dir < 0 ? range.from() : range.to();} + var headPos = cursorCoords(cm, range.head, "div"); + if (range.goalColumn != null) headPos.left = range.goalColumn; + goals.push(headPos.left); + var pos = findPosV(cm, headPos, dir, unit); + if (unit == "page" && range == doc.sel.primary()) {addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);} + return pos; + }, sel_move); + if (goals.length) { + for (var i = 0; i < doc.sel.ranges.length; i++) {doc.sel.ranges[i].goalColumn = goals[i];} + } + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function (pos) { + var doc = this.doc, line = getLine(doc, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function (ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function (ch) {return /\s/.test(ch);} + : function (ch) {return !/\s/.test(ch) && !isWordChar(ch);}; + while (start > 0 && check(line.charAt(start - 1))) --start; + while (end < line.length && check(line.charAt(end))) ++end; + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + + toggleOverwrite: function (value) { + if (value != null && value == this.state.overwrite) return; + if (this.state.overwrite = !this.state.overwrite) {addClass(this.display.cursorDiv, "CodeMirror-overwrite");} else {rmClass(this.display.cursorDiv, "CodeMirror-overwrite");} + + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function () { return this.display.input.getField() == activeElt(); }, + + scrollTo: methodOp(function (x, y) { + if (x != null || y != null) resolveScrollToPos(this); + if (x != null) this.curOp.scrollLeft = x; + if (y != null) this.curOp.scrollTop = y; + }), + getScrollInfo: function () { + var scroller = this.display.scroller; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; + }, + + scrollIntoView: methodOp(function (range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null}; + if (margin == null) margin = this.options.cursorScrollMargin; + } else if (typeof range === "number") { + range = {from: Pos(range, 0), to: null}; + } else if (range.from == null) { + range = {from: range, to: null}; + } + if (!range.to) range.to = range.from; + range.margin = margin || 0; + + if (range.from.line != null) { + resolveScrollToPos(this); + this.curOp.scrollToPos = range; + } else { + var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), + Math.min(range.from.top, range.to.top) - range.margin, + Math.max(range.from.right, range.to.right), + Math.max(range.from.bottom, range.to.bottom) + range.margin); + this.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + }), + + setSize: methodOp(function (width, height) { + var cm = this; + function interpret (val) { + return typeof val === "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + } + if (width != null) cm.display.wrapper.style.width = interpret(width); + if (height != null) cm.display.wrapper.style.height = interpret(height); + if (cm.options.lineWrapping) clearLineMeasurementCache(this); + var lineNo = cm.display.viewFrom; + cm.doc.iter(lineNo, cm.display.viewTo, function (line) { + if (line.widgets) { + for (var i = 0; i < line.widgets.length; i++) {if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }} + } + ++lineNo; + }); + cm.curOp.forceUpdate = true; + signal(cm, "refresh", this); + }), + + operation: function (f) {return runInOp(this, f);}, + + refresh: methodOp(function () { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) {estimateLineHeights(this);} + signal(this, "refresh", this); + }), + + swapDoc: methodOp(function (doc) { + var old = this.doc; + old.cm = null; + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + this.scrollTo(doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + + getInputField: function () {return this.display.input.getField();}, + getWrapperElement: function () {return this.display.wrapper;}, + getScrollerElement: function () {return this.display.scroller;}, + getGutterElement: function () {return this.display.gutters;} + }; + eventMixin(CodeMirror); + + // OPTION DEFAULTS + + // The default configuration options. + var defaults = CodeMirror.defaults = {}; + // Functions to run when options are changed. + var optionHandlers = CodeMirror.optionHandlers = {}; + + function option (name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) { + optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; + } + } + + // Passed to option handlers when there is no old value. + var Init = CodeMirror.Init = {toString: function () {return "CodeMirror.Init";}}; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { + cm.setValue(val); + }, true); + option("mode", null, function (cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function (cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); + if (old != CodeMirror.Init) cm.refresh(); + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) {cm.refresh();}, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function (cm) { + themeChanged(cm); + guttersChanged(cm); + }, true); + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val); + var prev = old != CodeMirror.Init && getKeyMap(old); + if (prev && prev.detach) prev.detach(cm, next); + if (next.attach) next.attach(cm, prev || null); + }); + option("extraKeys", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function (cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function (cm) {updateScrollbars(cm);}, true); + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function (cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("firstLineNumber", 1, guttersChanged, true); + option("lineNumberFormatter", function (integer) {return integer;}, guttersChanged, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + cm.display.disabled = true; + } else { + cm.display.disabled = false; + if (!val) cm.display.input.reset(); + } + }); + option("disableInput", false, function (cm, val) {if (!val) cm.display.input.reset();}, true); + option("dragDrop", true, dragDropChanged); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function (cm, val) {cm.doc.history.undoDepth = val;}); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function (cm) {cm.refresh();}, true); + option("maxHighlightLength", 10000, resetModeState, true); + option("moveInputWithCursor", true, function (cm, val) { + if (!val) cm.display.input.resetPosition(); + }); + + option("tabindex", null, function (cm, val) { + cm.display.input.getField().tabIndex = val || ""; + }); + option("autofocus", null); + + // MODE DEFINITION AND QUERYING + + // Known modes, by name and by MIME + var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + CodeMirror.defineMode = function (name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) {mode.dependencies = Array.prototype.slice.call(arguments, 2);} + modes[name] = mode; + }; + + CodeMirror.defineMIME = function (mime, spec) { + mimeModes[mime] = spec; + }; + + // Given a MIME type, a {name, ...options} config object, or a name + // string, return a mode config object. + CodeMirror.resolveMode = function (spec) { + if (typeof spec === "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name === "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found === "string") found = {name: found}; + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec === "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return CodeMirror.resolveMode("application/xml"); + } + if (typeof spec === "string") return {name: spec}; + return spec || {name: "null"}; + }; + + // Given a mode spec (anything that resolveMode accepts), find and + // initialize an actual mode object. + CodeMirror.getMode = function (options, spec) { + var spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return CodeMirror.getMode(options, "text/plain"); + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) continue; + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) modeObj.helperType = spec.helperType; + if (spec.modeProps) { + for (var prop in spec.modeProps) {modeObj[prop] = spec.modeProps[prop];} + } + + return modeObj; + }; + + // Minimal default mode. + CodeMirror.defineMode("null", function () { + return {token: function (stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + // This can be used to attach properties to mode objects from + // outside the actual mode definition. + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function (mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + }; + + // EXTENSIONS + + CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.defineOption = option; + + var initHooks = []; + CodeMirror.defineInitHook = function (f) {initHooks.push(f);}; + + var helpers = CodeMirror.helpers = {}; + CodeMirror.registerHelper = function (type, name, value) { + if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; + helpers[type][name] = value; + }; + CodeMirror.registerGlobalHelper = function (type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value); + helpers[type]._global.push({pred: predicate, val: value}); + }; + + // MODE STATE HANDLING + + // Utility functions for working with state. Exported because nested + // modes need to do this for their inner modes. + + var copyState = CodeMirror.copyState = function (mode, state) { + if (state === true) return state; + if (mode.copyState) return mode.copyState(state); + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) val = val.concat([]); + nstate[n] = val; + } + return nstate; + }; + + var startState = CodeMirror.startState = function (mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + }; + + // Given a mode and a state (for that mode), find the inner mode and + // state at the position that the state refers to. + CodeMirror.innerMode = function (mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + if (!info || info.mode == mode) break; + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // STANDARD COMMANDS + + // Commands are parameter-less actions that can be performed on an + // editor, mostly used for keybindings. + var commands = CodeMirror.commands = { + selectAll: function (cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, + singleSelection: function (cm) { + cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function (cm) { + deleteNearSelection(cm, function (range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length; + if (range.head.ch == len && range.head.line < cm.lastLine()) {return {from: range.head, to: Pos(range.head.line + 1, 0)};} + return {from: range.head, to: Pos(range.head.line, len)}; + } + return {from: range.from(), to: range.to()}; + + }); + }, + deleteLine: function (cm) { + deleteNearSelection(cm, function (range) { + return {from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; + }); + }, + delLineLeft: function (cm) { + deleteNearSelection(cm, function (range) { + return {from: Pos(range.from().line, 0), to: range.from()}; + }); + }, + delWrappedLineLeft: function (cm) { + deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var leftPos = cm.coordsChar({left: 0, top: top}, "div"); + return {from: leftPos, to: range.from()}; + }); + }, + delWrappedLineRight: function (cm) { + deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + return {from: range.from(), to: rightPos }; + }); + }, + undo: function (cm) {cm.undo();}, + redo: function (cm) {cm.redo();}, + undoSelection: function (cm) {cm.undoSelection();}, + redoSelection: function (cm) {cm.redoSelection();}, + goDocStart: function (cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, + goDocEnd: function (cm) {cm.extendSelection(Pos(cm.lastLine()));}, + goLineStart: function (cm) { + cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1}); + }, + goLineStartSmart: function (cm) { + cm.extendSelectionsBy(function (range) { + return lineStartSmart(cm, range.head); + }, {origin: "+move", bias: 1}); + }, + goLineEnd: function (cm) { + cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1}); + }, + goLineRight: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + }, sel_move); + }, + goLineLeft: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: 0, top: top}, "div"); + }, sel_move); + }, + goLineLeftSmart: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var pos = cm.coordsChar({left: 0, top: top}, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); + return pos; + }, sel_move); + }, + goLineUp: function (cm) {cm.moveV(-1, "line");}, + goLineDown: function (cm) {cm.moveV(1, "line");}, + goPageUp: function (cm) {cm.moveV(-1, "page");}, + goPageDown: function (cm) {cm.moveV(1, "page");}, + goCharLeft: function (cm) {cm.moveH(-1, "char");}, + goCharRight: function (cm) {cm.moveH(1, "char");}, + goColumnLeft: function (cm) {cm.moveH(-1, "column");}, + goColumnRight: function (cm) {cm.moveH(1, "column");}, + goWordLeft: function (cm) {cm.moveH(-1, "word");}, + goGroupRight: function (cm) {cm.moveH(1, "group");}, + goGroupLeft: function (cm) {cm.moveH(-1, "group");}, + goWordRight: function (cm) {cm.moveH(1, "word");}, + delCharBefore: function (cm) {cm.deleteH(-1, "char");}, + delCharAfter: function (cm) {cm.deleteH(1, "char");}, + delWordBefore: function (cm) {cm.deleteH(-1, "word");}, + delWordAfter: function (cm) {cm.deleteH(1, "word");}, + delGroupBefore: function (cm) {cm.deleteH(-1, "group");}, + delGroupAfter: function (cm) {cm.deleteH(1, "group");}, + indentAuto: function (cm) {cm.indentSelection("smart");}, + indentMore: function (cm) {cm.indentSelection("add");}, + indentLess: function (cm) {cm.indentSelection("subtract");}, + insertTab: function (cm) {cm.replaceSelection("\t");}, + insertSoftTab: function (cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); + } + cm.replaceSelections(spaces); + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.execCommand("insertTab"); + }, + transposeChars: function (cm) { + runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = []; + for (var i = 0; i < ranges.length; i++) { + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); + } + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function (cm) { + runInOp(cm, function () { + var len = cm.listSelections().length; + for (var i = 0; i < len; i++) { + var range = cm.listSelections()[i]; + cm.replaceRange("\n", range.anchor, range.head, "+input"); + cm.indentLine(range.from().line + 1, null, true); + ensureCursorVisible(cm); + } + }); + }, + toggleOverwrite: function (cm) {cm.toggleOverwrite();} + }; + + + // STANDARD KEYMAPS + + var keyMap = CodeMirror.keyMap = {}; + + keyMap.basic = { + Left: "goCharLeft", Right: "goCharRight", Up: "goLineUp", Down: "goLineDown", + End: "goLineEnd", Home: "goLineStartSmart", PageUp: "goPageUp", PageDown: "goPageDown", + Delete: "delCharAfter", Backspace: "delCharBefore", "Shift-Backspace": "delCharBefore", + Tab: "defaultTab", "Shift-Tab": "indentAuto", + Enter: "newlineAndIndent", Insert: "toggleOverwrite", + Esc: "singleSelection" + }; + // Note that the save and find-related commands aren't defined by + // default. User code or addons can define them. Unknown commands + // are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" + }; + // Very basic readline/emacs-style bindings, which are standard on Mac. + keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + + // KEYMAP DISPATCH + + function normalizeKeyName (name) { + var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; + else if (/^a(lt)?$/i.test(mod)) alt = true; + else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; + else if (/^s(hift)$/i.test(mod)) shift = true; + else throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) name = "Alt-" + name; + if (ctrl) name = "Ctrl-" + name; + if (cmd) name = "Cmd-" + name; + if (shift) name = "Shift-" + name; + return name; + } + + // This is a kludge to keep keymaps mostly working as raw objects + // (backwards compatibility) while at the same time support features + // like normalization and multi-stroke key bindings. It compiles a + // new normalized keymap, and then updates the old object to reflect + // this. + CodeMirror.normalizeKeyMap = function (keymap) { + var copy = {}; + for (var keyname in keymap) { + if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; + if (value == "...") { delete keymap[keyname]; continue; } + + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i = 0; i < keys.length; i++) { + var val, name; + if (i == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) copy[name] = val; + else if (prev != val) throw new Error("Inconsistent bindings for " + name); + } + delete keymap[keyname]; + } + } + for (var prop in copy) keymap[prop] = copy[prop]; + return keymap; + }; + + var lookupKey = CodeMirror.lookupKey = function (key, map, handle, context) { + map = getKeyMap(map); + var found = map.call ? map.call(key, context) : map[key]; + if (found === false) return "nothing"; + if (found === "...") return "multi"; + if (found != null && handle(found)) return "handled"; + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") {return lookupKey(key, map.fallthrough, handle, context);} + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context); + if (result) return result; + } + } + }; + + // Modifier key presses don't count as 'real' key presses for the + // purpose of keymap fallthrough. + var isModifierKey = CodeMirror.isModifierKey = function (value) { + var name = typeof value === "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + }; + + // Look up the name of a key as indicated by an event object. + var keyName = CodeMirror.keyName = function (event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) return false; + var base = keyNames[event.keyCode], name = base; + if (name == null || event.altGraphKey) return false; + if (event.altKey && base != "Alt") name = "Alt-" + name; + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; + if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; + return name; + }; + + function getKeyMap (val) { + return typeof val === "string" ? keyMap[val] : val; + } + + // FROMTEXTAREA + + CodeMirror.fromTextArea = function (textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) {options.tabindex = textarea.tabIndex;} + if (!options.placeholder && textarea.placeholder) {options.placeholder = textarea.placeholder;} + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save () {textarea.value = cm.getValue();} + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form, realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function () { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + options.finishInit = function (cm) { + cm.save = save; + cm.getTextArea = function () { return textarea; }; + cm.toTextArea = function () { + cm.toTextArea = isNaN; // Prevent this from being ran twice + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (typeof textarea.form.submit === "function") {textarea.form.submit = realSubmit;} + } + }; + }; + + textarea.style.display = "none"; + var cm = CodeMirror(function (node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + return cm; + }; + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + var StringStream = CodeMirror.StringStream = function (string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + }; + + StringStream.prototype = { + eol: function () {return this.pos >= this.string.length;}, + sol: function () {return this.pos == this.lineStart;}, + peek: function () {return this.string.charAt(this.pos) || undefined;}, + next: function () { + if (this.pos < this.string.length) {return this.string.charAt(this.pos++);} + }, + eat: function (match) { + var ch = this.string.charAt(this.pos); + if (typeof match === "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function (match) { + var start = this.pos; + while (this.eat(match)) {} + return this.pos > start; + }, + eatSpace: function () { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function () {this.pos = this.string.length;}, + skipTo: function (ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function (n) {this.pos -= n;}, + column: function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + indentation: function () { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + match: function (pattern, consume, caseInsensitive) { + if (typeof pattern === "string") { + var cased = function (str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function () {return this.string.slice(this.start, this.pos);}, + hideFirstChars: function (n, inner) { + this.lineStart += n; + try { return inner(); } finally { this.lineStart -= n; } + } + }; + + // TEXTMARKERS + + // Created with markText and setBookmark methods. A TextMarker is a + // handle that can be used to clear or find a marked position in the + // document. Line objects hold arrays (markedSpans) containing + // {from, to, marker} object pointing to such marker objects, and + // indicating that such a marker is present on that line. Multiple + // lines may point to the same marker when it spans across lines. + // The spans will have null for their from/to properties when the + // marker continues beyond the start/end of the line. Markers have + // links back to the lines they currently touch. + + var nextMarkerId = 0; + + var TextMarker = CodeMirror.TextMarker = function (doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + eventMixin(TextMarker); + + // Clear the marker. + TextMarker.prototype.clear = function () { + if (this.explicitlyCleared) return; + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) startOperation(cm); + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) signalLater(this, "clear", found.from, found.to); + } + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); + else if (cm) { + if (span.to != null) max = lineNo(line); + if (span.from != null) min = lineNo(line); + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) {updateLineHeight(line, textHeight(cm.display));} + } + if (cm && this.collapsed && !cm.options.lineWrapping) { + for (var i = 0; i < this.lines.length; ++i) { + var visual = visualLine(this.lines[i]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + } + + if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) reCheckSelection(cm.doc); + } + if (cm) signalLater(cm, "markerCleared", cm, this); + if (withOp) endOperation(cm); + if (this.parent) this.parent.clear(); + }; + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + TextMarker.prototype.find = function (side, lineObj) { + if (side == null && this.type == "bookmark") side = 1; + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) return from; + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) return to; + } + } + return from && {from: from, to: to}; + }; + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + TextMarker.prototype.changed = function () { + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) return; + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) {updateLineHeight(line, line.height + dHeight);} + } + }); + }; + + TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) {(op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);} + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + + // Collapsed markers have unique ids, in order to be able to order + // them, which is needed for uniquely determining an outer marker + // when they overlap (they may nest, but not partially overlap). + var nextMarkerId = 0; + + // Create a marker, wire it up to the right lines, and + function markText (doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) return markTextShared(doc, from, to, options, type); + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); + + var marker = new TextMarker(doc, type), diff = cmp(from, to); + if (options) copyObj(options, marker, false); + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) {return marker;} + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true; + marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); + if (options.insertLeft) marker.widgetNode.insertLeft = true; + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) {throw new Error("Inserting collapsed marker partially overlapping an existing one");} + sawCollapsedSpans = true; + } + + if (marker.addToHistory) {addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);} + + var curLine = from.line, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) {updateMaxLine = true;} + if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)); + ++curLine; + }); + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { + doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) updateLineHeight(line, 0); + }); + } + + if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function () { marker.clear(); }); + + if (marker.readOnly) { + sawReadOnlySpans = true; + if (doc.history.done.length || doc.history.undone.length) {doc.clearHistory();} + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + // Sync editor state + if (updateMaxLine) cm.curOp.updateMaxLine = true; + if (marker.collapsed) {regChange(cm, from.line, to.line + 1);} else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) {for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");} + if (marker.atomic) reCheckSelection(cm.doc); + signalLater(cm, "markerAdded", cm, marker); + } + return marker; + } + + // SHARED TEXTMARKERS + + // A shared marker spans multiple linked documents. It is + // implemented as a meta-marker-object controlling multiple normal + // markers. + var SharedTextMarker = CodeMirror.SharedTextMarker = function (markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i = 0; i < markers.length; ++i) {markers[i].parent = this;} + }; + eventMixin(SharedTextMarker); + + SharedTextMarker.prototype.clear = function () { + if (this.explicitlyCleared) return; + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) {this.markers[i].clear();} + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj); + }; + + function markTextShared (doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function (doc) { + if (widget) options.widgetNode = widget.cloneNode(true); + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) {if (doc.linked[i].isParent) return;} + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + + function findSharedMarkers (doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), + function (m) { return m.parent; }); + } + + function copySharedMarkers (doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find(); + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + + function detachSharedMarkers (markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function (d) { linked.push(d); }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + } + } + + // TEXTMARKER SPANS + + function MarkedSpan (marker, from, to) { + this.marker = marker; + this.from = from; this.to = to; + } + + // Search an array of spans for a span matching the given marker. + function getMarkedSpanFor (spans, marker) { + if (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) return span; + } + } + } + // Remove a span from an array, returning undefined if no spans are + // left (we don't store arrays for lines without spans). + function removeMarkedSpan (spans, span) { + for (var r, i = 0; i < spans.length; ++i) {if (spans[i] != span) (r || (r = [])).push(spans[i]);} + return r; + } + // Add a span to a line. + function addMarkedSpan (line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + span.marker.attachLine(line); + } + + // Used for the algorithm that adjusts markers for a change in the + // document. These functions cut an array of spans at a given + // character position, returning an array of remaining chunks (or + // undefined if nothing remains). + function markedSpansBefore (old, startCh, isInsert) { + if (old) { + for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } + } + return nw; + } + function markedSpansAfter (old, endCh, isInsert) { + if (old) { + for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)); + } + } + } + return nw; + } + + // Given a change object, compute the new set of marker spans that + // cover the line in which the change took place. Removes spans + // entirely within the change, reconnects spans belonging to the + // same marker that appear on both sides of the change, and cuts off + // spans partially within the change. Returns an array of span + // arrays with one element for each line in (after) the change. + function stretchSpansOverChange (doc, change) { + if (change.full) return null; + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) return null; + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) span.to = startCh; + else if (sameLine) span.to = found.to == null ? null : found.to + offset; + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i = 0; i < last.length; ++i) { + var span = last[i]; + if (span.to != null) span.to += offset; + if (span.from == null) { + var found = getMarkedSpanFor(first, span.marker); + if (!found) { + span.from = offset; + if (sameLine) (first || (first = [])).push(span); + } + } else { + span.from += offset; + if (sameLine) (first || (first = [])).push(span); + } + } + } + // Make sure we didn't create any zero-length spans + if (first) first = clearEmptySpans(first); + if (last && last != first) last = clearEmptySpans(last); + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) { + for (var i = 0; i < first.length; ++i) { + if (first[i].to == null) {(gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));} + } + } + for (var i = 0; i < gap; ++i) {newMarkers.push(gapMarkers);} + newMarkers.push(last); + } + return newMarkers; + } + + // Remove spans that are empty and don't have a clearWhenEmpty + // option of false. + function clearEmptySpans (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) {spans.splice(i--, 1);} + } + if (!spans.length) return null; + return spans; + } + + // Used for un/re-doing changes from the history. Combines the + // result of computing the existing spans with the set of spans that + // existed in the history (so that deleting around a span and then + // undoing brings back the span). + function mergeOldSpans (doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) return stretched; + if (!stretched) return old; + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) {if (oldCur[k].marker == span.marker) continue spans;} + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old; + } + + // Used to 'clip' out readOnly ranges when making a change. + function removeReadOnlyRanges (doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) {(markers || (markers = [])).push(mark);} + } + } + }); + if (!markers) return null; + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) {newParts.push({from: p.from, to: m.from});} + if (dto > 0 || !mk.inclusiveRight && !dto) {newParts.push({from: m.to, to: p.to});} + parts.splice.apply(parts, newParts); + j += newParts.length - 1; + } + } + return parts; + } + + // Connect or disconnect spans from a line. + function detachMarkedSpans (line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) {spans[i].marker.detachLine(line);} + line.markedSpans = null; + } + function attachMarkedSpans (line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) {spans[i].marker.attachLine(line);} + line.markedSpans = spans; + } + + // Helpers used when computing which overlapping collapsed span + // counts as the larger one. + function extraLeft (marker) { return marker.inclusiveLeft ? -1 : 0; } + function extraRight (marker) { return marker.inclusiveRight ? 1 : 0; } + + // Returns a number indicating which of two overlapping collapsed + // spans is larger (and thus includes the other). Falls back to + // comparing ids when the spans cover exactly the same range. + function compareCollapsedMarkers (a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) return lenDiff; + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) return -fromCmp; + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) return toCmp; + return b.id - a.id; + } + + // Find out whether a line ends or starts in a collapsed span. If + // so, return the marker for that span. + function collapsedSpanAtSide (line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { + for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {found = sp.marker;} + } + } + return found; + } + function collapsedSpanAtStart (line) { return collapsedSpanAtSide(line, true); } + function collapsedSpanAtEnd (line) { return collapsedSpanAtSide(line, false); } + + // Test whether there exists a collapsed span that partially + // overlaps (covers the start or end, but not both) of a new span. + // Such overlap is not allowed. + function conflictingCollapsedRange (doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (!sp.marker.collapsed) continue; + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; + if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || + fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) {return true;} + } + } + } + + // A visual line is a line as drawn on the screen. Folding, for + // example, can cause multiple logical lines to appear on the same + // visual line. This finds the start of the visual line that the + // given line is part of (usually that is the line itself). + function visualLine (line) { + var merged; + while (merged = collapsedSpanAtStart(line)) {line = merged.find(-1, true).line;} + return line; + } + + // Returns an array of logical lines that continue the visual line + // started by the argument, or undefined if there are no such lines. + function visualLineContinued (line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + + // Get the line number of the start of the visual line that the + // given line number is part of. + function visualLineNo (doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line); + if (line == vis) return lineN; + return lineNo(vis); + } + // Get the line number of the start of the next visual line after + // the given line. + function visualLineEndNo (doc, lineN) { + if (lineN > doc.lastLine()) return lineN; + var line = getLine(doc, lineN), merged; + if (!lineIsHidden(doc, line)) return lineN; + while (merged = collapsedSpanAtEnd(line)) {line = merged.find(1, true).line;} + return lineNo(line) + 1; + } + + // Compute whether a line is hidden. Lines count as hidden when they + // are part of a visual line that starts with another line, or when + // they are entirely covered by collapsed, non-widget span. + function lineIsHidden (doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) continue; + if (sp.from == null) return true; + if (sp.marker.widgetNode) continue; + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) {return true;} + } + } + } + function lineIsHiddenInner (doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) {return true;} + for (var sp, i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) return true; + } + } + + // LINE WIDGETS + + // Line widgets are block elements displayed above or below a line. + + var LineWidget = CodeMirror.LineWidget = function (doc, node, options) { + if (options) { + for (var opt in options) { + if (options.hasOwnProperty(opt)) {this[opt] = options[opt];} + } + } + this.doc = doc; + this.node = node; + }; + eventMixin(LineWidget); + + function adjustScrollWhenAboveVisible (cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) {addToScrollPos(cm, null, diff);} + } + + LineWidget.prototype.clear = function () { + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) return; + for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); + if (!ws.length) line.widgets = null; + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + } + }; + LineWidget.prototype.changed = function () { + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) return; + updateLineHeight(line, line.height + diff); + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + }); + } + }; + + function widgetHeight (widget) { + if (widget.height != null) return widget.height; + var cm = widget.doc.cm; + if (!cm) return 0; + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) {parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";} + if (widget.noHScroll) {parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";} + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.offsetHeight; + } + + function addLineWidget (doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) cm.display.alignWidgets = true; + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) widgets.push(widget); + else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) addToScrollPos(cm, null, widget.height); + cm.curOp.forceUpdate = true; + } + return true; + }); + return widget; + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + var Line = CodeMirror.Line = function (text, markedSpans, estimateHeight) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight ? estimateHeight(this) : 1; + }; + eventMixin(Line); + Line.prototype.lineNo = function () { return lineNo(this); }; + + // Change the content (text, markers) of a line. Automatically + // invalidates cached information and tries to re-estimate the + // line's height. + function updateLine (line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + if (line.order != null) line.order = null; + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) updateLineHeight(line, estHeight); + } + + // Detach a line from the document tree and its markers. + function cleanUpLine (line) { + line.parent = null; + detachMarkedSpans(line); + } + + function extractLineClasses (type, output) { + if (type) { + for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) break; + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop] == null) {output[prop] = lineClass[2];} else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) {output[prop] += " " + lineClass[2];} + } + } + return type; + } + + function callBlankLine (mode, state) { + if (mode.blankLine) return mode.blankLine(state); + if (!mode.innerMode) return; + var inner = CodeMirror.innerMode(mode, state); + if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); + } + + function readToken (mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; + var style = mode.token(stream, state); + if (stream.pos > stream.start) return style; + } + throw new Error("Mode " + mode.name + " failed to advance stream."); + } + + // Utility for getTokenAt and getLineTokens + function takeToken (cm, pos, precise, asArray) { + function getObj (copy) { + return {start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state}; + } + + var doc = cm.doc, mode = doc.mode, style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize), tokens; + if (asArray) tokens = []; + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, state); + if (asArray) tokens.push(getObj(true)); + } + return asArray ? tokens : getObj(); + } + + // Run the given mode's parser over a line, calling f for each token. + function runMode (cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) processLine(cm, text, state, stream.pos); + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) style = "m-" + (style ? mName + " " + style : mName); + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 50000); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 characters + var pos = Math.min(stream.pos, curStart + 50000); + f(pos, curStyle); + curStart = pos; + } + } + + // Compute a style array (an array starting with a mode generation + // -- for invalidation -- followed by pairs of end positions and + // style strings), which is used to highlight the tokens on the + // line. + function highlightLine (cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {}; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function (end, style) { + st.push(end, style); + }, lineClasses, forceToEnd); + + // Run overlays, adjust style array. + for (var o = 0; o < cm.state.overlays.length; ++o) { + var overlay = cm.state.overlays[o], i = 1, at = 0; + runMode(cm, line.text, overlay.mode, true, function (end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) {st.splice(i, 1, end, st[i + 1], i_end);} + i += 2; + at = Math.min(end, i_end); + } + if (!style) return; + if (overlay.opaque) { + st.splice(start, i - start, end, "cm-overlay " + style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start + 1]; + st[start + 1] = (cur ? cur + " " : "") + "cm-overlay " + style; + } + } + }, lineClasses); + } + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; + } + + function getLineStyles (cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); + line.styles = result.styles; + if (result.classes) line.styleClasses = result.classes; + else if (line.styleClasses) line.styleClasses = null; + if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; + } + return line.styles; + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. Used for lines that + // aren't currently visible. + function processLine (cm, text, state, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize); + stream.start = stream.pos = startAt || 0; + if (text == "") callBlankLine(mode, state); + while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { + readToken(mode, stream, state); + stream.start = stream.pos; + } + } + + // Convert a style as returned by a mode (either null, or a string + // containing one or more styles) to a CSS style. This is cached, + // and also looks for line-wide styles. + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle (style, options) { + if (!style || /^\s*$/.test(style)) return null; + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + + // Render the DOM representation of the text of a line. Also builds + // up a 'line map', which points at the DOM nodes that represent + // specific stretches of text, and is used by the measuring code. + // The returned object contains the DOM node, this map, and + // information about line-wide styles that were set by the mode. + function buildLineContent (cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; + lineView.measure = {}; + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order; + builder.pos = 0; + builder.addToken = buildToken; + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) {builder.addToken = buildTokenBadBidi(builder.addToken, order);} + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) {builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");} + if (line.styleClasses.textClass) {builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");} + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) {builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));} + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + + // See issue #2901 + if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className)) {builder.content.className = "cm-tab-wrap-hack";} + + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) {builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");} + + return builder; + } + + function defaultSpecialCharPlaceholder (ch) { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + + // Build up the DOM representation for a single token, and add it to + // the line map. Takes care to render special characters separately. + function buildToken (builder, text, style, startStyle, endStyle, title, css) { + if (!text) return; + var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + if (!special.test(text)) { + builder.col += text.length; + var content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) mustWrap = true; + builder.pos += text.length; + } else { + var content = document.createDocumentFragment(), pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt.setAttribute("role", "presentation"); + txt.setAttribute("cm-text", "\t"); + builder.col += tabWidth; + } else { + var txt = builder.cm.options.specialCharPlaceholder(m[0]); + txt.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt); + builder.pos++; + } + } + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || ""; + if (startStyle) fullStyle += startStyle; + if (endStyle) fullStyle += endStyle; + var token = elt("span", [content], fullStyle, css); + if (title) token.title = title; + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + + function splitSpaces (old) { + var out = " "; + for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; + out += " "; + return out; + } + + // Work around nonsense dimensions being reported for stretches of + // right-to-left text. + function buildTokenBadBidi (inner, order) { + return function (builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (;;) { + // Find the part that overlaps with the start of this text + for (var i = 0; i < order.length; i++) { + var part = order[i]; + if (part.to > start && part.from <= start) break; + } + if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + }; + } + + function buildCollapsedSpan (builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) builder.map.push(builder.pos, builder.pos + size, widget); + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) {widget = builder.content.appendChild(document.createElement("span"));} + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent (line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i = 1; i < styles.length; i += 2) {builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i + 1], builder.cm.options));} + return; + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = ""; + collapsed = null; nextChange = Infinity; + var foundBookmarks = []; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) spanStyle += " " + m.className; + if (m.css) css = m.css; + if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; + if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; + if (m.title && !title) title = m.title; + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) {collapsed = sp;} + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null); + if (collapsed.to == null) return; + if (collapsed.to == pos) collapsed = false; + } + if (!collapsed && foundBookmarks.length) { + for (var j = 0; j < foundBookmarks.length; ++j) {buildCollapsedSpan(builder, 0, foundBookmarks[j]);} + } + } + if (pos >= len) break; + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = interpretTokenStyle(styles[i++], builder.cm.options); + } + } + } + + // DOCUMENT DATA STRUCTURE + + // By default, updates that start and end at the beginning of a line + // are treated specially, in order to make the association of line + // widgets and marker elements with the text behave more intuitive. + function isWholeLineUpdate (doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore); + } + + // Perform a change on the document data structure. + function updateDoc (doc, change, markedSpans, estimateHeight) { + function spansFor (n) {return markedSpans ? markedSpans[n] : null;} + function update (line, text, spans) { + updateLine(line, text, spans, estimateHeight); + signalLater(line, "change", line, change); + } + function linesFor (start, end) { + for (var i = start, result = []; i < end; ++i) {result.push(new Line(text[i], spansFor(i), estimateHeight));} + return result; + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) doc.remove(from.line, nlines); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added = linesFor(1, text.length - 1); + added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added = linesFor(1, text.length - 1); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1); + doc.insert(from.line + 1, added); + } + + signalLater(doc, "change", doc, change); + } + + // The document is represented as a BTree consisting of leaves, with + // chunk of lines in them, and branches, with up to ten leaves or + // other branch nodes below them. The top node is always a branch + // node, and is the document object itself (meaning it has + // additional methods and properties). + // + // All nodes have parent links. The tree is used both to go from + // line numbers to line objects, and to go from objects to numbers. + // It also indexes by height, and is used to convert between height + // and line object, and to find the total height of the document. + // + // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + + function LeafChunk (lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, height = 0; i < lines.length; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function () { return this.lines.length; }, + // Remove the n lines at offset 'at'. + removeInner: function (at, n) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function (lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function (at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0; i < lines.length; ++i) lines[i].parent = this; + }, + // Used to iterate over a part of the tree. + iterN: function (at, n, op) { + for (var e = at + n; at < e; ++at) {if (op(this.lines[at])) return true;} + } + }; + + function BranchChunk (children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0; i < children.length; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function () { return this.size; }, + removeInner: function (at, n) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) break; + at = 0; + } else at -= sz; + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function (lines) { + for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); + }, + insertInner: function (at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + while (child.lines.length > 50) { + var spilled = child.lines.splice(child.lines.length - 25, 25); + var newleaf = new LeafChunk(spilled); + child.height -= newleaf.height; + this.children.splice(i + 1, 0, newleaf); + newleaf.parent = this; + } + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function () { + if (this.children.length <= 10) return; + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function (at, n, op) { + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) return true; + if ((n -= used) == 0) break; + at = 0; + } else at -= sz; + } + } + }; + + var nextDocId = 0; + var Doc = CodeMirror.Doc = function (text, mode, firstLine) { + if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); + if (firstLine == null) firstLine = 0; + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.frontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + + if (typeof text === "string") text = splitLines(text); + updateDoc(this, {from: start, to: start, text: text}); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function (from, to, op) { + if (op) this.iterN(from - this.first, to - from, op); + else this.iterN(this.first, this.first + this.size, from); + }, + + // Non-public interface for adding and removing lines. + insert: function (at, lines) { + var height = 0; + for (var i = 0; i < lines.length; ++i) height += lines[i].height; + this.insertInner(at - this.first, lines, height); + }, + remove: function (at, n) { this.removeInner(at - this.first, n); }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function (lineSep, lineFilter) { + var lines = getLines(this, this.first, this.first + this.size, lineFilter); + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + setValue: docMethodOp(function (code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: splitLines(code), origin: "setValue", full: true}, true); + setSelection(this, simpleSelection(top)); + }), + replaceRange: function (code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function (from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + + getLine: function (line) {var l = this.getLineHandle(line); return l && l.text;}, + + getLineHandle: function (line) {if (isLine(this, line)) return getLine(this, line);}, + getLineNumber: function (line) {return lineNo(line);}, + + getLineHandleVisualStart: function (line) { + if (typeof line === "number") line = getLine(this, line); + return visualLine(line); + }, + + lineCount: function () {return this.size;}, + firstLine: function () {return this.first;}, + lastLine: function () {return this.first + this.size - 1;}, + + clipPos: function (pos) {return clipPos(this, pos);}, + + getCursor: function (start) { + var range = this.sel.primary(), pos; + if (start == null || start == "head") pos = range.head; + else if (start == "anchor") pos = range.anchor; + else if (start == "end" || start == "to" || start === false) pos = range.to(); + else pos = range.from(); + return pos; + }, + listSelections: function () { return this.sel.ranges; }, + somethingSelected: function () {return this.sel.somethingSelected();}, + + setCursor: docMethodOp(function (line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line === "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function (anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function (head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function (heads, options) { + extendSelections(this, clipPosArray(this, heads, options)); + }), + extendSelectionsBy: docMethodOp(function (f, options) { + extendSelections(this, map(this.sel.ranges, f), options); + }), + setSelections: docMethodOp(function (ranges, primary, options) { + if (!ranges.length) return; + for (var i = 0, out = []; i < ranges.length; i++) { + out[i] = new Range(clipPos(this, ranges[i].anchor), + clipPos(this, ranges[i].head)); + } + if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); + setSelection(this, normalizeSelection(out, primary), options); + }), + addSelection: docMethodOp(function (anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); + }), + + getSelection: function (lineSep) { + var ranges = this.sel.ranges, lines; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + getSelections: function (lineSep) { + var parts = [], ranges = this.sel.ranges; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + if (lineSep !== false) sel = sel.join(lineSep || "\n"); + parts[i] = sel; + } + return parts; + }, + replaceSelection: function (code, collapse, origin) { + var dup = []; + for (var i = 0; i < this.sel.ranges.length; i++) {dup[i] = code;} + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function (code, collapse, origin) { + var changes = [], sel = this.sel; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin}; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i = changes.length - 1; i >= 0; i--) {makeChange(this, changes[i]);} + if (newSel) setSelectionReplaceHistory(this, newSel); + else if (this.cm) ensureCursorVisible(this.cm); + }), + undo: docMethodOp(function () {makeChangeFromHistory(this, "undo");}), + redo: docMethodOp(function () {makeChangeFromHistory(this, "redo");}), + undoSelection: docMethodOp(function () {makeChangeFromHistory(this, "undo", true);}), + redoSelection: docMethodOp(function () {makeChangeFromHistory(this, "redo", true);}), + + setExtending: function (val) {this.extend = val;}, + getExtending: function () {return this.extend;}, + + historySize: function () { + var hist = this.history, done = 0, undone = 0; + for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; + for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; + return {undo: done, redo: undone}; + }, + clearHistory: function () {this.history = new History(this.history.maxGeneration);}, + + markClean: function () { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function (forceSplit) { + if (forceSplit) {this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;} + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + + getHistory: function () { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)}; + }, + setHistory: function (histData) { + var hist = this.history = new History(this.history.maxGeneration); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + + addLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop]) line[prop] = cls; + else if (classTest(cls).test(line[prop])) return false; + else line[prop] += " " + cls; + return true; + }); + }), + removeLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) return false; + else if (cls == null) line[prop] = null; + else { + var found = cur.match(classTest(cls)); + if (!found) return false; + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + + addLineWidget: docMethodOp(function (handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function (widget) { widget.clear(); }, + + markText: function (from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); + }, + setBookmark: function (pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function (pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) {markers.push(span.marker.parent || span.marker);} + } + } + return markers; + }, + findMarks: function (from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to); + var found = [], lineNo = from.line; + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans; + if (spans) { + for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + if (!(lineNo == from.line && from.ch > span.to || + span.from == null && lineNo != from.line || + lineNo == to.line && span.from > to.ch) && + (!filter || filter(span.marker))) {found.push(span.marker.parent || span.marker);} + } + } + ++lineNo; + }); + return found; + }, + getAllMarks: function () { + var markers = []; + this.iter(function (line) { + var sps = line.markedSpans; + if (sps) { + for (var i = 0; i < sps.length; ++i) {if (sps[i].from != null) markers.push(sps[i].marker);} + } + }); + return markers; + }, + + posFromIndex: function (off) { + var ch, lineNo = this.first; + this.iter(function (line) { + var sz = line.text.length + 1; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos(this, Pos(lineNo, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) return 0; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + 1; + }); + return index; + }, + + copy: function (copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + + linkedDoc: function (options) { + if (!options) options = {}; + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) from = options.from; + if (options.to != null && options.to < to) to = options.to; + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); + if (options.sharedHist) copy.history = this.history; + (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function (other) { + if (other instanceof CodeMirror) other = other.doc; + if (this.linked) { + for (var i = 0; i < this.linked.length; ++i) { + var link = this.linked[i]; + if (link.doc != other) continue; + this.linked.splice(i, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } + } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function (doc) {splitIds.push(doc.id);}, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function (f) {linkedDocs(this, f);}, + + getMode: function () {return this.mode;}, + getEditor: function () {return this.cm;} + }); + + // Public alias. + Doc.prototype.eachLine = Doc.prototype.iter; + + // Set up methods on CodeMirror's prototype to redirect to the editor's document. + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { + if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { + CodeMirror.prototype[prop] = (function (method) { + return function () {return method.apply(this.doc, arguments);}; + })(Doc.prototype[prop]); + } + } + + eventMixin(Doc); + + // Call f for all linked documents. + function linkedDocs (doc, f, sharedHistOnly) { + function propagate (doc, skip, sharedHist) { + if (doc.linked) { + for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) continue; + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) continue; + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } + } + } + propagate(doc, null, true); + } + + // Attach a document to an editor. + function attachDoc (cm, doc) { + if (doc.cm) throw new Error("This document is already in use."); + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + if (!cm.options.lineWrapping) findMaxLine(cm); + cm.options.mode = doc.modeOption; + regChange(cm); + } + + // LINE UTILITIES + + // Find the line object corresponding to the given line number. + function getLine (doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); + for (var chunk = doc; !chunk.lines;) { + for (var i = 0; ; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break; } + n -= sz; + } + } + return chunk.lines[n]; + } + + // Get the part of a document between two positions, as an array of + // strings. + function getBetween (doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text; + if (n == end.line) text = text.slice(0, end.ch); + if (n == start.line) text = text.slice(start.ch); + out.push(text); + ++n; + }); + return out; + } + // Get the lines between from and to, as array of strings. + function getLines (doc, from, to, lineFilter) { + var out = []; + doc.iter(from, to, function (line) { + var text = line.text; + if(lineFilter) { + text = lineFilter(line); + } + out.push(text); + }); + return out; + } + + // Update the height of a line, propagating the height change + // upwards to parent nodes. + function updateLineHeight (line, height) { + var diff = height - line.height; + if (diff) for (var n = line; n; n = n.parent) n.height += diff; + } + + // Given a line object, find its line number by walking up through + // its parent links. + function lineNo (line) { + if (line.parent == null) return null; + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0; ; ++i) { + if (chunk.children[i] == cur) break; + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first; + } + + // Find the line at the given vertical position, using the height + // information in the document tree. + function lineAtHeight (chunk, h) { + var n = chunk.first; + outer: do { + for (var i = 0; i < chunk.children.length; ++i) { + var child = chunk.children[i], ch = child.height; + if (h < ch) { chunk = child; continue outer; } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + + + // Find the height above the given line. + function heightAtLine (lineObj) { + lineObj = visualLine(lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) break; + else h += line.height; + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i = 0; i < p.children.length; ++i) { + var cur = p.children[i]; + if (cur == chunk) break; + else h += cur.height; + } + } + return h; + } + + // Get the bidi ordering for the given line (and cache it). Returns + // false for lines that are fully left-to-right, and an array of + // BidiSpan objects otherwise. + function getOrder (line) { + var order = line.order; + if (order == null) order = line.order = bidiOrdering(line.text); + return order; + } + + // HISTORY + + function History (startGen) { + // Arrays of change events and selections. Doing something adds an + // event to done and clears undo. Undoing moves events from done + // to undone, redoing moves them in the other direction. + this.done = []; this.undone = []; + this.undoDepth = Infinity; + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1; + } + + // Create a history change event from an updateDoc-style change + // object. + function historyChangeFromChange (doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function (doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); + return histChange; + } + + // Pop all selection events off the end of a history array. Stop at + // a change event. + function clearSelectionEvents (array) { + while (array.length) { + var last = lst(array); + if (last.ranges) array.pop(); + else break; + } + } + + // Find the top change event in the history. Pop off selection + // events that are in the way. + function lastChangeEvent (hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + + // Register a change in the history. Merges changes that are within + // a single operation, ore are close together with an origin that + // allows merging (starting with "+") into a single event. + function addChangeToHistory (doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur; + + if ((hist.lastOp == opId || + hist.lastOrigin == change.origin && change.origin && + ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || + change.origin.charAt(0) == "*")) && + (cur = lastChangeEvent(hist, hist.lastOp == opId))) { + // Merge this change into the last event + var last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done); + if (!before || !before.ranges) {pushSelectionToHistory(doc.sel, hist.done);} + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation}; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) hist.done.shift(); + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + + if (!last) signal(doc, "historyAdded"); + } + + function selectionEventCanBeMerged (doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || + ch == "+" && + prev.ranges.length == sel.ranges.length && + prev.somethingSelected() == sel.somethingSelected() && + new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); + } + + // Called whenever the selection changes, sets the new selection as + // the pending selection in the history, and pushes the old pending + // selection into the 'done' array when it was significantly + // different (in number of selected ranges, emptiness, or time). + function addSelectionToHistory (doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin; + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || + (origin && hist.lastSelOrigin == origin && + (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) {hist.done[hist.done.length - 1] = sel;} else {pushSelectionToHistory(sel, hist.done);} + + hist.lastSelTime = +new Date; + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) {clearSelectionEvents(hist.undone);} + } + + function pushSelectionToHistory (sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) {dest.push(sel);} + } + + // Used to store marked span information in the history. + function attachLocalSpans (doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) {(existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;} + ++n; + }); + } + + // When un/re-doing restores text containing marked spans, those + // that have been explicitly cleared should not be restored. + function removeClearedSpans (spans) { + if (!spans) return null; + for (var i = 0, out; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } else if (out) out.push(spans[i]); + } + return !out ? spans : out.length ? out : null; + } + + // Retrieve and filter the old marked spans stored in a change event. + function getOldSpans (doc, change) { + var found = change["spans_" + doc.id]; + if (!found) return null; + for (var i = 0, nw = []; i < change.text.length; ++i) {nw.push(removeClearedSpans(found[i]));} + return nw; + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray (events, newGroup, instantiateSel) { + for (var i = 0, copy = []; i < events.length; ++i) { + var event = events[i]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, newChanges = []; + copy.push({changes: newChanges}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m; + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) { + for (var prop in change) { + if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } + } + } + } + } + return copy; + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSelSingle (pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray (array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue; + } + for (var j = 0; j < sub.changes.length; ++j) { + var cur = sub.changes[j]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } + } + } + + function rebaseHist (hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // EVENT UTILITIES + + // Due to the fact that we still support jurassic IE versions, some + // compatibility wrappers are needed. + + var e_preventDefault = CodeMirror.e_preventDefault = function (e) { + if (e.preventDefault) e.preventDefault(); + else e.returnValue = false; + }; + var e_stopPropagation = CodeMirror.e_stopPropagation = function (e) { + if (e.stopPropagation) e.stopPropagation(); + else e.cancelBubble = true; + }; + function e_defaultPrevented (e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + var e_stop = CodeMirror.e_stop = function (e) {e_preventDefault(e); e_stopPropagation(e);}; + + function e_target (e) {return e.target || e.srcElement;} + function e_button (e) { + var b = e.which; + if (b == null) { + if (e.button & 1) b = 1; + else if (e.button & 2) b = 3; + else if (e.button & 4) b = 2; + } + if (mac && e.ctrlKey && b == 1) b = 3; + return b; + } + + // EVENT HANDLING + + // Lightweight event framework. on/off also work on DOM nodes, + // registering native DOM handlers. + + var on = CodeMirror.on = function (emitter, type, f) { + if (emitter.addEventListener) {emitter.addEventListener(type, f, false);} else if (emitter.attachEvent) {emitter.attachEvent("on" + type, f);} else { + var map = emitter._handlers || (emitter._handlers = {}); + var arr = map[type] || (map[type] = []); + arr.push(f); + } + }; + + var off = CodeMirror.off = function (emitter, type, f) { + if (emitter.removeEventListener) {emitter.removeEventListener(type, f, false);} else if (emitter.detachEvent) {emitter.detachEvent("on" + type, f);} else { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + for (var i = 0; i < arr.length; ++i) {if (arr[i] == f) { arr.splice(i, 1); break; }} + } + }; + + var signal = CodeMirror.signal = function (emitter, type /* , values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); + }; + + var orphanDelayedCallbacks = null; + + // Often, we want to signal events at a point where we are in the + // middle of some work, but don't want the handler to start calling + // other methods on the editor, which might be in an inconsistent + // state or simply not expect any other events to happen. + // signalLater looks whether there are any handlers, and schedules + // them to be executed when the last operation ends, or, if no + // operation is active, when a timeout fires. + function signalLater (emitter, type /* , values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + function bnd (f) {return function () {f.apply(null, args);};} + for (var i = 0; i < arr.length; ++i) {list.push(bnd(arr[i]));} + } + + function fireOrphanDelayed () { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) delayed[i](); + } + + // The DOM events that CodeMirror handles can be overridden by + // registering a (non-DOM) handler on the editor for the event name, + // and preventDefault-ing the event in that handler. + function signalDOMEvent (cm, e, override) { + if (typeof e === "string") {e = {type: e, preventDefault: function () { this.defaultPrevented = true; }};} + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + + function signalCursorActivity (cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) return; + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i = 0; i < arr.length; ++i) { + if (indexOf(set, arr[i]) == -1) {set.push(arr[i]);} + } + } + + function hasHandler (emitter, type) { + var arr = emitter._handlers && emitter._handlers[type]; + return arr && arr.length > 0; + } + + // Add on and off methods to a constructor's prototype, to make + // registering events on such objects more convenient. + function eventMixin (ctor) { + ctor.prototype.on = function (type, f) {on(this, type, f);}; + ctor.prototype.off = function (type, f) {off(this, type, f);}; + } + + // MISC UTILITIES + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerGap = 30; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = CodeMirror.Pass = {toString: function () {return "CodeMirror.Pass";}}; + + // Reused option objects for setSelection & friends + var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; + + function Delayed () {this.id = null;} + Delayed.prototype.set = function (ms, f) { + clearTimeout(this.id); + this.id = setTimeout(f, ms); + }; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + var countColumn = CodeMirror.countColumn = function (string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = startIndex || 0, n = startValue || 0; ;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) {return n + (end - i);} + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } + }; + + // The inverse of countColumn -- find the offset that corresponds to + // a particular column. + function findColumn (string, goal, tabSize) { + for (var pos = 0, col = 0; ;) { + var nextTab = string.indexOf("\t", pos); + if (nextTab == -1) nextTab = string.length; + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) {return pos + Math.min(skipped, goal - col);} + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) return pos; + } + } + + var spaceStrs = [""]; + function spaceStr (n) { + while (spaceStrs.length <= n) {spaceStrs.push(lst(spaceStrs) + " ");} + return spaceStrs[n]; + } + + function lst (arr) { return arr[arr.length - 1]; } + + var selectInput = function (node) { node.select(); }; + if (ios) // Mobile Safari apparently has a bug where select() is broken. + {selectInput = function (node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };} else if (ie) // Suppress mysterious IE10 errors + {selectInput = function (node) { try { node.select(); } catch(_e) {} };} + + function indexOf (array, elt) { + for (var i = 0; i < array.length; ++i) {if (array[i] == elt) return i;} + return -1; + } + function map (array, f) { + var out = []; + for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); + return out; + } + + function nothing () {} + + function createObj (base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) copyObj(props, inst); + return inst; + } + + function copyObj (obj, target, overwrite) { + if (!target) target = {}; + for (var prop in obj) { + if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) {target[prop] = obj[prop];} + } + return target; + } + + function bind (f) { + var args = Array.prototype.slice.call(arguments, 1); + return function () {return f.apply(null, args);}; + } + + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + var isWordCharBasic = CodeMirror.isWordChar = function (ch) { + return /\w/.test(ch) || ch > "\x80" && + (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); + }; + function isWordChar (ch, helper) { + if (!helper) return isWordCharBasic(ch); + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; + return helper.test(ch); + } + + function isEmpty (obj) { + for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; + return true; + } + + // Extending unicode characters. A series of a non-extending char + + // any number of extending chars is treated as a single unit as far + // as editing and measuring is concerned. This is not fully correct, + // since some scripts/font/browsers also treat other configurations + // of code points as a group. + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar (ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } + + // DOM UTILITIES + + function elt (tag, content, className, style) { + var e = document.createElement(tag); + if (className) e.className = className; + if (style) e.style.cssText = style; + if (typeof content === "string") e.appendChild(document.createTextNode(content)); + else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + + var range; + if (document.createRange) { + range = function (node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + } else { + range = function (node, start, end) { + var r = document.body.createTextRange(); + try { r.moveToElementText(node.parentNode); } catch(e) { return r; } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + } + + function removeChildren (e) { + for (var count = e.childNodes.length; count > 0; --count) {e.removeChild(e.firstChild);} + return e; + } + + function removeChildrenAndAdd (parent, e) { + return removeChildren(parent).appendChild(e); + } + + var contains = CodeMirror.contains = function (parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + {child = child.parentNode;} + if (parent.contains) {return parent.contains(child);} + do { + if (child.nodeType == 11) child = child.host; + if (child == parent) return true; + } while (child = child.parentNode); + }; + + function activeElt () { return document.activeElement; } + // Older versions of IE throws unspecified error when touching + // document.activeElement in some cases (during loading, in iframe) + if (ie && ie_version < 11) { + activeElt = function () { + try { return document.activeElement; } catch(e) { return document.body; } + }; + } + + function classTest (cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } + var rmClass = CodeMirror.rmClass = function (node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + var addClass = CodeMirror.addClass = function (node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; + }; + function joinClasses (a, b) { + var as = a.split(" "); + for (var i = 0; i < as.length; i++) {if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];} + return b; + } + + // WINDOW-WIDE EVENTS + + // These must be handled carefully, because naively registering a + // handler for each editor will cause the editors to never be + // garbage collected. + + function forEachCodeMirror (f) { + if (!document.body.getElementsByClassName) return; + var byClass = document.body.getElementsByClassName("CodeMirror"); + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) f(cm); + } + } + + var globalsRegistered = false; + function ensureGlobalHandlers () { + if (globalsRegistered) return; + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers () { + // When the window resizes, we need to refresh active editors. + var resizeTimer; + on(window, "resize", function () { + if (resizeTimer == null) { + resizeTimer = setTimeout(function () { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + } + }); + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { + forEachCodeMirror(onBlur); + }); + } + + // FEATURE DETECTION + + // Detect drag-and-drop + var dragAndDrop = function () { + // There is *some* kind of drag-and-drop support in IE6-8, but I + // couldn't get it to work yet. + if (ie && ie_version < 9) return false; + var div = elt("div"); + return "draggable" in div || "dragDrop" in div; + }(); + + var zwspSupported; + function zeroWidthElement (measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) {zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);} + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + + // Feature-detect IE's crummy client rect reporting for bidi text + var badBidiRects; + function hasBadBidiRects (measure) { + if (badBidiRects != null) return badBidiRects; + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) + var r1 = range(txt, 1, 2).getBoundingClientRect(); + return badBidiRects = (r1.right - r0.right < 3); + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) nl = string.length; + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function (string) {return string.split(/\r\n?|\n/);}; + + var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } + } : function (te) { + try {var range = te.ownerDocument.selection.createRange();} catch(e) {} + if (!range || range.parentElement() != te) return false; + return range.compareEndPoints("StartToEnd", range) != 0; + }; + + var hasCopyEvent = (function () { + var e = elt("div"); + if ("oncopy" in e) return true; + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy === "function"; + })(); + + var badZoomedRects = null; + function hasBadZoomedRects (measure) { + if (badZoomedRects != null) return badZoomedRects; + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + + // KEY NAMES + + var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; + CodeMirror.keyNames = keyNames; + (function () { + // Number keys + for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); + // Alphabetic keys + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + // Function keys + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + + // BIDI HELPERS + + function iterateBidiSections (order, from, to, f) { + if (!order) return f(from, to, "ltr"); + var found = false; + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); + found = true; + } + } + if (!found) f(from, to, "ltr"); + } + + function bidiLeft (part) { return part.level % 2 ? part.to : part.from; } + function bidiRight (part) { return part.level % 2 ? part.from : part.to; } + + function lineLeft (line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } + function lineRight (line) { + var order = getOrder(line); + if (!order) return line.text.length; + return bidiRight(lst(order)); + } + + function lineStart (cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) lineN = lineNo(visual); + var order = getOrder(visual); + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); + return Pos(lineN, ch); + } + function lineEnd (cm, lineN) { + var merged, line = getLine(cm.doc, lineN); + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + lineN = null; + } + var order = getOrder(line); + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); + return Pos(lineN == null ? lineNo(line) : lineN, ch); + } + function lineStartSmart (cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS); + } + return start; + } + + function compareBidiLevel (order, a, b) { + var linedir = order[0].level; + if (a == linedir) return true; + if (b == linedir) return false; + return a < b; + } + var bidiOther; + function getBidiPartAt (order, pos) { + bidiOther = null; + for (var i = 0, found; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < pos && cur.to > pos) return i; + if ((cur.from == pos || cur.to == pos)) { + if (found == null) { + found = i; + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + if (cur.from != cur.to) bidiOther = found; + return i; + } else { + if (cur.from != cur.to) bidiOther = i; + return found; + } + } + } + return found; + } + + function moveInLine (line, pos, dir, byUnit) { + if (!byUnit) return pos + dir; + do pos += dir; + while (pos > 0 && isExtendingChar(line.text.charAt(pos))); + return pos; + } + + // This is needed in order to move 'visually' through bi-directional + // text -- i.e., pressing left should make the cursor go left, even + // when in RTL text. The tricky part is the 'jumps', where RTL and + // LTR text touch each other. This often requires the cursor offset + // to move more than one unit, in order to visually move one unit. + function moveVisually (line, start, dir, byUnit) { + var bidi = getOrder(line); + if (!bidi) return moveLogically(line, start, dir, byUnit); + var pos = getBidiPartAt(bidi, start), part = bidi[pos]; + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); + + for (;;) { + if (target > part.from && target < part.to) return target; + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) return target; + part = bidi[pos += dir]; + return (dir > 0) == part.level % 2 ? part.to : part.from; + } + part = bidi[pos += dir]; + if (!part) return null; + if ((dir > 0) == part.level % 2) {target = moveInLine(line, part.to, -1, byUnit);} else {target = moveInLine(line, part.from, 1, byUnit);} + + } + } + + function moveLogically (line, start, dir, byUnit) { + var target = start + dir; + if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; + return target < 0 || target > line.text.length ? null : target; + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function () { + // Character types for codepoints 0 to 0xff + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + // Character types for codepoints 0x600 to 0x6ff + var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; + function charType (code) { + if (code <= 0xf7) return lowTypes.charAt(code); + else if (0x590 <= code && code <= 0x5f4) return "R"; + else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); + else if (0x6ee <= code && code <= 0x8ac) return "r"; + else if (0x2000 <= code && code <= 0x200b) return "w"; + else if (code == 0x200c) return "b"; + return "L"; + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L"; + + function BidiSpan (level, from, to) { + this.level = level; + this.from = from; this.to = to; + } + + return function (str) { + if (!bidiRE.test(str)) return false; + var len = str.length, types = []; + for (var i = 0, type; i < len; ++i) {types.push(type = charType(str.charCodeAt(i)));} + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i = 0, prev = outerType; i < len; ++i) { + var type = types[i]; + if (type == "m") types[i] = prev; + else prev = type; + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (type == "1" && cur == "r") types[i] = "n"; + else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i = 1, prev = types[0]; i < len - 1; ++i) { + var type = types[i]; + if (type == "+" && prev == "1" && types[i + 1] == "1") types[i] = "1"; + else if (type == "," && prev == types[i + 1] && + (prev == "1" || prev == "n")) types[i] = prev; + prev = type; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i = 0; i < len; ++i) { + var type = types[i]; + if (type == ",") types[i] = "N"; + else if (type == "%") { + for (var end = i + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i && types[i - 1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (cur == "L" && type == "1") types[i] = "L"; + else if (isStrong.test(type)) cur = type; + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i = 0; i < len; ++i) { + if (isNeutral.test(types[i])) { + for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} + var before = (i ? types[i - 1] : outerType) == "L"; + var after = (end < len ? types[end] : outerType) == "L"; + var replace = before || after ? "L" : "R"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i = 0; i < len;) { + if (countsAsLeft.test(types[i])) { + var start = i; + for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} + order.push(new BidiSpan(0, start, i)); + } else { + var pos = i, at = order.length; + for (++i; i < len && types[i] != "L"; ++i) {} + for (var j = pos; j < i;) { + if (countsAsNum.test(types[j])) { + if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); + var nstart = j; + for (++j; j < i && countsAsNum.test(types[j]); ++j) {} + order.splice(at, 0, new BidiSpan(2, nstart, j)); + pos = j; + } else ++j; + } + if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + if (order[0].level == 2) {order.unshift(new BidiSpan(1, order[0].to, order[0].to));} + if (order[0].level != lst(order).level) {order.push(new BidiSpan(order[0].level, len, len));} + + return order; + }; + })(); + + // THE END + + CodeMirror.version = "5.4.1"; + + return CodeMirror; +});(function (mod) { + mod(CodeMirror); +})(function (CodeMirror) { + var Pos = CodeMirror.Pos; + + function forEach (arr, f) { + for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); + } + + function arrayContains (arr, item) { + if (!Array.prototype.indexOf) { + var i = arr.length; + while (i--) { + if (arr[i] === item) { + return true; + } + } + return false; + } + return arr.indexOf(item) != -1; + } + + function scriptHint (editor, keywords, getToken, options) { + // Find the token at the cursor + var cur = editor.getCursor(), token = getToken(editor, cur); + if (/\b(?:string)\b/.test(token.type)) { + return; + } + token.state = CodeMirror.innerMode(editor.getMode(), token.state).state; + + if (!/^[\w$_]*$/.test(token.string)) { + token = { + start: cur.ch, end: cur.ch, string: "", state: token.state, + type: token.string == "." ? "property" : null }; } else if (token.end > cur.ch) { token.end = cur.ch; @@ -39566,25 +39344,25 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and }; } - function getFormulaKeywords() { + function getFormulaKeywords () { return BI.FormulaCollections; } - function formulaHint(editor, options) { + function formulaHint (editor, options) { return scriptHint(editor, getFormulaKeywords(), function (e, cur) { return e.getTokenAt(cur); }, options); - }; + } CodeMirror.registerHelper("hint", "formula", formulaHint); - function getCompletions(token, context, keywords, options) { + function getCompletions (token, context, keywords, options) { var found = [], start = token.string; if (!start) { return found; } - function maybeAdd(str) { + function maybeAdd (str) { if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) { found.push(str); } @@ -39602,44 +39380,44 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and })(function (CodeMirror) { "use strict"; - CodeMirror.defineMode('formula', function () { - function wordObj(words) { + CodeMirror.defineMode("formula", function () { + function wordObj (words) { var o = {}; for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; return o; } - var atoms = wordObj(['false', 'true']); + var atoms = wordObj(["false", "true"]); var keywords = wordObj(BI.FormulaCollections); - function tokenBase(stream, state) { + function tokenBase (stream, state) { if (stream.eatSpace()) { return null; } var ch = stream.next(); - if (ch === '"' || ch === '\'') { + if (ch === "\"" || ch === "'") { nextUntilUnescaped(stream, ch); return "string"; } - if (ch === '\u200b') { + if (ch === "\u200b") { nextUntilUnescaped(stream, ch); return "field"; } if (/[\[\],\(\)]/.test(ch)) { - return 'bracket'; + return "bracket"; } // richie:暂时不需要解析操作符号 - //if (/[+\-*\/=<>!&|]/.test(ch)) { + // if (/[+\-*\/=<>!&|]/.test(ch)) { // return 'operator'; - //} - //if (/\d|\d./.test(ch)) { + // } + // if (/\d|\d./.test(ch)) { // stream.eatWhile(/\d|\./); // if (stream.eol() || !/\w/.test(stream.peek())) { // return 'number'; // } - //} + // } @@ -39654,7 +39432,7 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and return null; } - function nextUntilUnescaped(stream, end) { + function nextUntilUnescaped (stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next === end && !escaped) { @@ -39665,7 +39443,7 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and return escaped; } - function tokenize(stream, state) { + function tokenize (stream, state) { return (state.tokens[0] || tokenBase)(stream, state); } @@ -39713,7 +39491,7 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and completion.update(true); }); - function Completion(cm, options) { + function Completion (cm, options) { this.cm = cm; this.options = this.buildOptions(options); this.widget = null; @@ -39729,8 +39507,8 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and } var requestAnimationFrame = window.requestAnimationFrame || function (fn) { - return setTimeout(fn, 1000 / 60); - }; + return setTimeout(fn, 1000 / 60); + }; var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; Completion.prototype = { @@ -39755,16 +39533,16 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and else { this.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); - if(completion.isKeyword === true){ - }else{ - var to = this.cm.getCursor(); - this.cm.markText(completion.from || data.from, to, {className: "#function", atomic: true}); - this.cm.replaceSelection("() "); - to = this.cm.getCursor(); - to.ch = to.ch - 2; - this.cm.setCursor(to); - this.cm.focus(); - } + if(completion.isKeyword === true) { + }else{ + var to = this.cm.getCursor(); + this.cm.markText(completion.from || data.from, to, {className: "#function", atomic: true}); + this.cm.replaceSelection("() "); + to = this.cm.getCursor(); + to.ch = to.ch - 2; + this.cm.setCursor(to); + this.cm.focus(); + } } CodeMirror.signal(data, "pick", completion); this.close(); @@ -39822,20 +39600,22 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and var editor = this.cm.options.hintOptions; var out = {}; for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; - if (editor) for (var prop in editor) - if (editor[prop] !== undefined) out[prop] = editor[prop]; - if (options) for (var prop in options) - if (options[prop] !== undefined) out[prop] = options[prop]; + if (editor) { + for (var prop in editor) {if (editor[prop] !== undefined) out[prop] = editor[prop];} + } + if (options) { + for (var prop in options) {if (options[prop] !== undefined) out[prop] = options[prop];} + } return out; } }; - function getText(completion) { - if (typeof completion == "string") return completion; - else return completion.text; + function getText (completion) { + if (typeof completion === "string") return completion; + return completion.text; } - function buildKeyMap(completion, handle) { + function buildKeyMap (completion, handle) { var baseMap = { Up: function () { handle.moveFocus(-1); @@ -39862,38 +39642,40 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and var custom = completion.options.customKeys; var ourMap = custom ? {} : baseMap; - function addBinding(key, val) { + function addBinding (key, val) { var bound; - if (typeof val != "string") + if (typeof val !== "string") { bound = function (cm) { return val(cm, handle); }; + } // This mechanism is deprecated - else if (baseMap.hasOwnProperty(val)) - bound = baseMap[val]; - else - bound = val; + else if (baseMap.hasOwnProperty(val)) {bound = baseMap[val];} else {bound = val;} ourMap[key] = bound; } - if (custom) - for (var key in custom) if (custom.hasOwnProperty(key)) - addBinding(key, custom[key]); + if (custom) { + for (var key in custom) { + if (custom.hasOwnProperty(key)) {addBinding(key, custom[key]);} + } + } var extra = completion.options.extraKeys; - if (extra) - for (var key in extra) if (extra.hasOwnProperty(key)) - addBinding(key, extra[key]); + if (extra) { + for (var key in extra) { + if (extra.hasOwnProperty(key)) {addBinding(key, extra[key]);} + } + } return ourMap; } - function getHintElement(hintsElement, el) { + function getHintElement (hintsElement, el) { while (el && el != hintsElement) { if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; el = el.parentNode; } } - function Widget(completion, data) { + function Widget (completion, data) { this.completion = completion; this.data = data; this.picked = false; @@ -40048,19 +39830,13 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and }, changeActive: function (i, avoidWrap) { - if (i >= this.data.list.length) - i = avoidWrap ? this.data.list.length - 1 : 0; - else if (i < 0) - i = avoidWrap ? 0 : this.data.list.length - 1; + if (i >= this.data.list.length) {i = avoidWrap ? this.data.list.length - 1 : 0;} else if (i < 0) {i = avoidWrap ? 0 : this.data.list.length - 1;} if (this.selectedHint == i) return; var node = this.hints.childNodes[this.selectedHint]; node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); node = this.hints.childNodes[this.selectedHint = i]; node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; - if (node.offsetTop < this.hints.scrollTop) - this.hints.scrollTop = node.offsetTop - 3; - else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) - this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; + if (node.offsetTop < this.hints.scrollTop) {this.hints.scrollTop = node.offsetTop - 3;} else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) {this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;} CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); }, @@ -40088,15 +39864,16 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and var found = []; for (var i = 0; i < options.words.length; i++) { var word = options.words[i]; - if (word.slice(0, token.string.length) == token.string) - found.push(word); + if (word.slice(0, token.string.length) == token.string) {found.push(word);} } - if (found.length) return { - list: found, - from: CodeMirror.Pos(cur.line, token.start), - to: CodeMirror.Pos(cur.line, token.end) - }; + if (found.length) { + return { + list: found, + from: CodeMirror.Pos(cur.line, token.start), + to: CodeMirror.Pos(cur.line, token.end) + }; + } }); CodeMirror.commands.autocomplete = CodeMirror.showHint; @@ -40122,9 +39899,9 @@ BI.shortcut('bi.el', BI.EL);// CodeMirror, copyright (c) by Marijn Haverbeke and BI.FormulaEditor = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.FormulaEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-formula-editor bi-card', - watermark: '', - value: '', + baseCls: "bi-formula-editor bi-card", + watermark: "", + value: "", fieldTextValueMap: {}, showHint: true, lineHeight: 2 @@ -40137,8 +39914,8 @@ BI.FormulaEditor = BI.inherit(BI.Single, { textWrapping: true, lineWrapping: true, lineNumbers: false, - mode: 'formula', - //解决插入字段由括号或其他特殊字符包围时分裂的bug + mode: "formula", + // 解决插入字段由括号或其他特殊字符包围时分裂的bug specialChars: /[\u0000-\u001f\u007f\u00ad\u200c-\u200f\u2028\u2029\ufeff]/ }); o.lineHeight === 1 ? this.element.addClass("codemirror-low-line-height") : this.element.addClass("codemirror-high-line-height"); @@ -40148,7 +39925,7 @@ BI.FormulaEditor = BI.inherit(BI.Single, { CodeMirror.showHint(cm, CodeMirror.formulaHint, {completeSingle: false}); } BI.nextTick(function () { - self.fireEvent(BI.FormulaEditor.EVENT_CHANGE) + self.fireEvent(BI.FormulaEditor.EVENT_CHANGE); }); }); @@ -40230,10 +40007,10 @@ BI.FormulaEditor = BI.inherit(BI.Single, { */ insertField: function (field) { var from = this.editor.getCursor(); - //解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 - this.editor.replaceSelection('\u200b' + field + '\u200b'); + // 解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 + this.editor.replaceSelection("\u200b" + field + "\u200b"); var to = this.editor.getCursor(); - this.editor.markText(from, to, {className: 'fieldName', atomic: true, startStyle: "start", endStyle: "end"}); + this.editor.markText(from, to, {className: "fieldName", atomic: true, startStyle: "start", endStyle: "end"}); this.editor.replaceSelection(" "); this.editor.focus(); }, @@ -40282,7 +40059,7 @@ BI.FormulaEditor = BI.inherit(BI.Single, { _.forEach(line.markedSpans, function (i, ms) { switch (i.marker.className) { case "fieldName": - //因为插入字段的时候首尾加了不可见字符,所以首尾缩进一个字符 + // 因为插入字段的时候首尾加了不可见字符,所以首尾缩进一个字符 var dId = fieldMap[value.substr(i.from + 1, i.to - i.from - 2)]; if (!fields.contains(dId)) { fields.push(dId); @@ -40399,28 +40176,28 @@ $.extend(BI, { BI.delay(function () { toast.element.slideUp(500, function () { toast.destroy(); - }) - }, 5000) - }) + }); + }, 5000); + }); }, _show: function (hasCancel, title, message, callback) { - $mask = $('
    ').css({ - position: 'absolute', - 'zIndex': BI.zIndex_tip - 2, + $mask = $("
    ").css({ + position: "absolute", + zIndex: BI.zIndex_tip - 2, top: 0, left: 0, right: 0, bottom: 0, opacity: 0.5 - }).appendTo('body'); - $pop = $('
    ').css({ - position: 'absolute', - 'zIndex': BI.zIndex_tip - 1, + }).appendTo("body"); + $pop = $("
    ").css({ + position: "absolute", + zIndex: BI.zIndex_tip - 1, top: 0, left: 0, right: 0, bottom: 0 - }).appendTo('body'); + }).appendTo("body"); var close = function () { messageShow.destroy(); $mask.remove(); @@ -40429,10 +40206,10 @@ $.extend(BI, { if (hasCancel === true) { controlItems.push({ el: { - type: 'bi.button', + type: "bi.button", text: BI.i18nText("BI-Basic_Cancel"), height: 30, - level: 'ignore', + level: "ignore", handler: function () { close(); if (BI.isFunction(callback)) { @@ -40444,7 +40221,7 @@ $.extend(BI, { } controlItems.push({ el: { - type: 'bi.button', + type: "bi.button", text: BI.i18nText("BI-Basic_OK"), height: 30, handler: function () { @@ -40457,31 +40234,31 @@ $.extend(BI, { }); var conf = { element: $pop, - type: 'bi.center_adapt', + type: "bi.center_adapt", items: [ { - type: 'bi.border', - cls: 'bi-message-content bi-card', + type: "bi.border", + cls: "bi-message-content bi-card", items: { - 'north': { + north: { el: { - type: 'bi.border', - cls: 'bi-message-title bi-background', + type: "bi.border", + cls: "bi-message-title bi-background", items: { center: { el: { - type: 'bi.label', + type: "bi.label", text: title || BI.i18nText("BI-Basic_Prompt"), - textAlign: 'left', + textAlign: "left", hgap: 20, height: 50 } }, east: { el: { - type: 'bi.icon_button', - cls: 'bi-message-close close-font', -// height: 50, + type: "bi.icon_button", + cls: "bi-message-close close-font", + // height: 50, handler: function () { close(); } @@ -40492,7 +40269,7 @@ $.extend(BI, { }, height: 50 }, - 'center': { + center: { el: { type: "bi.text", cls: "bi-message-text", @@ -40503,12 +40280,12 @@ $.extend(BI, { text: message } }, - 'south': { + south: { el: { type: "bi.absolute", items: [{ el: { - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", hgap: 5, items: controlItems }, @@ -40549,8 +40326,8 @@ BI.GridView = BI.inherit(BI.Widget, { overflowY: true, overscanColumnCount: 0, overscanRowCount: 0, - rowHeightGetter: BI.emptyFn, //number类型或function类型 - columnWidthGetter: BI.emptyFn, //number类型或function类型 + rowHeightGetter: BI.emptyFn, // number类型或function类型 + columnWidthGetter: BI.emptyFn, // number类型或function类型 // estimatedColumnSize: 100, //columnWidthGetter为function时必设 // estimatedRowSize: 30, //rowHeightGetter为function时必设 scrollLeft: 0, @@ -40607,7 +40384,7 @@ BI.GridView = BI.inherit(BI.Widget, { return { overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount) - } + }; }, _calculateChildrenToRender: function () { @@ -40632,7 +40409,7 @@ BI.GridView = BI.inherit(BI.Widget, { this._renderedRowStartIndex = visibleRowIndices.start; this._renderedRowStopIndex = visibleRowIndices.stop; - var overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex) + var overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex); var overscanRowIndices = this._getOverscanIndices(this.rowCount, overscanRowCount, this._renderedRowStartIndex, this._renderedRowStopIndex); @@ -40641,7 +40418,7 @@ BI.GridView = BI.inherit(BI.Widget, { var rowStartIndex = overscanRowIndices.overscanStartIndex; var rowStopIndex = overscanRowIndices.overscanStopIndex; - //算区间size + // 算区间size var minRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStartIndex); var minColumnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnStartIndex); var maxRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStopIndex); @@ -40650,7 +40427,7 @@ BI.GridView = BI.inherit(BI.Widget, { var left = minColumnDatum.offset + horizontalOffsetAdjustment; var bottom = maxRowDatum.offset + verticalOffsetAdjustment + maxRowDatum.size; var right = maxColumnDatum.offset + horizontalOffsetAdjustment + maxColumnDatum.size; - //如果滚动的区间并没有超出渲染的范围 + // 如果滚动的区间并没有超出渲染的范围 if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { return; } @@ -40714,7 +40491,7 @@ BI.GridView = BI.inherit(BI.Widget, { count++; } } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (self.renderedKeys[i]) { @@ -40733,15 +40510,15 @@ BI.GridView = BI.inherit(BI.Widget, { deleteArray.push(key[2]); }); BI.each(deleteArray, function (i, index) { - //性能优化,不调用destroy方法防止触发destroy事件 + // 性能优化,不调用destroy方法防止触发destroy事件 self.renderedCells[index].el._destroy(); }); var addedItems = []; BI.each(addSet, function (index, key) { - addedItems.push(renderedCells[key[2]]) + addedItems.push(renderedCells[key[2]]); }); this.container.addItems(addedItems); - //拦截父子级关系 + // 拦截父子级关系 this.container._children = renderedWidgets; this.container.attr("items", renderedCells); this.renderedCells = renderedCells; @@ -40783,7 +40560,7 @@ BI.GridView = BI.inherit(BI.Widget, { this._rowSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.rowCount, o.rowHeightGetter, o.estimatedRowSize); this._calculateChildrenToRender(); - //元素未挂载时不能设置scrollTop + // 元素未挂载时不能设置scrollTop try { this.element.scrollTop(o.scrollTop); this.element.scrollLeft(o.scrollLeft); @@ -40814,11 +40591,11 @@ BI.GridView = BI.inherit(BI.Widget, { }, setColumnCount: function (columnCount) { - this.options.columnCount = columnCount + this.options.columnCount = columnCount; }, setRowCount: function (rowCount) { - this.options.rowCount = rowCount + this.options.rowCount = rowCount; }, setOverflowX: function (b) { @@ -40826,7 +40603,7 @@ BI.GridView = BI.inherit(BI.Widget, { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; BI.nextTick(function () { - self.element.css({overflowX: !!b ? "auto" : "hidden"}); + self.element.css({overflowX: b ? "auto" : "hidden"}); }); } }, @@ -40836,7 +40613,7 @@ BI.GridView = BI.inherit(BI.Widget, { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; BI.nextTick(function () { - self.element.css({overflowY: !!b ? "auto" : "hidden"}); + self.element.css({overflowY: b ? "auto" : "hidden"}); }); } }, @@ -40865,7 +40642,7 @@ BI.GridView = BI.inherit(BI.Widget, { this.options.estimatedRowSize = height; }, - //重新计算children + // 重新计算children _reRange: function () { this.renderRange = {}; }, @@ -40894,7 +40671,7 @@ BI.GridView = BI.inherit(BI.Widget, { } }); BI.GridView.EVENT_SCROLL = "EVENT_SCROLL"; -BI.shortcut('bi.grid_view', BI.GridView);/** +BI.shortcut("bi.grid_view", BI.GridView);/** * floatBox弹出层, * @class BI.FloatBox * @extends BI.Widget @@ -40905,7 +40682,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { baseCls: "bi-float-box bi-card", width: 600, height: 500 - }) + }); }, _init: function () { BI.FloatBox.superclass._init.apply(this, arguments); @@ -40931,19 +40708,19 @@ BI.FloatBox = BI.inherit(BI.Widget, { if (ui.position.top < 0) { ui.position.top = 0; } - //BI-12134 没有什么特别好的方法 + // BI-12134 没有什么特别好的方法 BI.Resizers._resize(); } }); this._south = BI.createWidget(); BI.createWidget({ - type: 'bi.border', + type: "bi.border", element: this, items: { - 'north': { + north: { el: { - type: 'bi.border', - cls: 'bi-message-title bi-background', + type: "bi.border", + cls: "bi-message-title bi-background", items: { center: { el: { @@ -40959,8 +40736,8 @@ BI.FloatBox = BI.inherit(BI.Widget, { }, east: { el: { - type: 'bi.icon_button', - cls: 'bi-message-close close-font', + type: "bi.icon_button", + cls: "bi-message-close close-font", height: 50, handler: function () { self.currentSectionProvider.close(); @@ -40972,7 +40749,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { }, height: 50 }, - 'center': { + center: { el: { type: "bi.absolute", items: [{ @@ -40984,7 +40761,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { }] } }, - 'south': { + south: { el: { type: "bi.absolute", items: [{ @@ -40998,7 +40775,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { height: 60 } } - }) + }); }, populate: function (sectionProvider) { @@ -41012,7 +40789,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { sectionProvider.rebuildSouth(this._south); sectionProvider.on(BI.PopoverSection.EVENT_CLOSE, function () { self.close(); - }) + }); }, show: function () { @@ -41055,9 +40832,9 @@ BI.PopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.PopupView.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-popup-view", - maxWidth: 'auto', + maxWidth: "auto", minWidth: 100, - //maxHeight: 200, + // maxHeight: 200, minHeight: 25, lgap: 0, rgap: 0, @@ -41065,16 +40842,16 @@ BI.PopupView = BI.inherit(BI.Widget, { bgap: 0, vgap: 0, hgap: 0, - direction: BI.Direction.Top, //工具栏的方向 - stopEvent: false,//是否停止mousedown、mouseup事件 - stopPropagation: false, //是否停止mousedown、mouseup向上冒泡 + direction: BI.Direction.Top, // 工具栏的方向 + stopEvent: false, // 是否停止mousedown、mouseup事件 + stopPropagation: false, // 是否停止mousedown、mouseup向上冒泡 logic: { dynamic: true }, - tool: false, //自定义工具栏 - tabs: [], //导航栏 - buttons: [], //toolbar栏 + tool: false, // 自定义工具栏 + tabs: [], // 导航栏 + buttons: [], // toolbar栏 el: { type: "bi.button_group", @@ -41085,28 +40862,28 @@ BI.PopupView = BI.inherit(BI.Widget, { type: "bi.vertical" }] } - }) + }); }, _init: function () { BI.PopupView.superclass._init.apply(this, arguments); var self = this, o = this.options; var fn = function (e) { - e.stopPropagation(); - }, stop = function (e) { - e.stopEvent(); - return false; - }; + e.stopPropagation(); + }, stop = function (e) { + e.stopEvent(); + return false; + }; this.element.css({ "z-index": BI.zIndex_popup, "min-width": o.minWidth + "px", "max-width": o.maxWidth + "px" - }).bind({"click": fn}); + }).bind({click: fn}); this.element.bind("mousewheel", fn); - o.stopPropagation && this.element.bind({"mousedown": fn, "mouseup": fn, "mouseover": fn}); - o.stopEvent && this.element.bind({"mousedown": stop, "mouseup": stop, "mouseover": stop}); + o.stopPropagation && this.element.bind({mousedown: fn, mouseup: fn, mouseover: fn}); + o.stopEvent && this.element.bind({mousedown: stop, mouseup: stop, mouseover: stop}); this.tool = this._createTool(); this.tab = this._createTab(); this.view = this._createView(); @@ -41151,7 +40928,7 @@ BI.PopupView = BI.inherit(BI.Widget, { if (false === o.tool) { return; } - return BI.createWidget(o.tool) + return BI.createWidget(o.tool); }, _createTab: function () { @@ -41164,7 +40941,7 @@ BI.PopupView = BI.inherit(BI.Widget, { cls: "list-view-tab", height: 25, items: o.tabs - }) + }); }, _createToolBar: function () { @@ -41182,7 +40959,7 @@ BI.PopupView = BI.inherit(BI.Widget, { shadow: true, isShadowShowingOnSelected: true }) - }) + }); }, getView: function () { @@ -41203,7 +40980,7 @@ BI.PopupView = BI.inherit(BI.Widget, { tabHeight = this.tab ? (this.tab.attr("height") || 25) : 0, toolHeight = ((this.tool && this.tool.attr("height")) || 25) * ((this.tool && this.tool.isVisible()) ? 1 : 0); this.view.resetHeight ? this.view.resetHeight(h - tbHeight - tabHeight - toolHeight - 2) : - this.view.element.css({"max-height": (h - tbHeight - tabHeight - toolHeight - 2) + "px"}) + this.view.element.css({"max-height": (h - tbHeight - tabHeight - toolHeight - 2) + "px"}); }, setValue: function (selectedValues) { @@ -41232,7 +41009,7 @@ BI.SearcherView = BI.inherit(BI.Pane, { tipText: BI.i18nText("BI-No_Select"), chooseType: BI.Selection.Single, - matcher: {//完全匹配的构造器 + matcher: {// 完全匹配的构造器 type: "bi.button_group", behaviors: { redmark: function () { @@ -41256,7 +41033,7 @@ BI.SearcherView = BI.inherit(BI.Pane, { type: "bi.vertical" }] } - }) + }); }, _init: function () { @@ -41391,7 +41168,7 @@ BI.ListView = BI.inherit(BI.Widget, { } }, o.el)], element: this - } + }; }, mounted: function () { @@ -41462,7 +41239,7 @@ BI.ListView = BI.inherit(BI.Widget, { this.restore(); } }); -BI.shortcut('bi.list_view', BI.ListView); +BI.shortcut("bi.list_view", BI.ListView); /** * 表示当前对象 @@ -41510,7 +41287,7 @@ BI.VirtualList = BI.inherit(BI.Widget, { } }], element: this - } + }; }, mounted: function () { @@ -41641,7 +41418,7 @@ BI.VirtualList = BI.inherit(BI.Widget, { this.restore(); } }); -BI.shortcut('bi.virtual_list', BI.VirtualList); +BI.shortcut("bi.virtual_list", BI.VirtualList); /** * 分页控件 @@ -41661,35 +41438,35 @@ BI.Pager = BI.inherit(BI.Widget, { vgap: 0 }], - dynamicShow: true, //是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 - //dynamicShow为false时以下两个有用 - dynamicShowFirstLast: false,//是否动态显示首页、尾页 - dynamicShowPrevNext: false,//是否动态显示上一页、下一页 - pages: false, //总页数 + dynamicShow: true, // 是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 + // dynamicShow为false时以下两个有用 + dynamicShowFirstLast: false, // 是否动态显示首页、尾页 + dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 + pages: false, // 总页数 curr: function () { return 1; - }, //初始化当前页 - groups: 0, //连续显示分页数 - jump: BI.emptyFn, //分页的回调函数 + }, // 初始化当前页 + groups: 0, // 连续显示分页数 + jump: BI.emptyFn, // 分页的回调函数 - first: false, //是否显示首页 - last: false, //是否显示尾页 + first: false, // 是否显示首页 + last: false, // 是否显示尾页 prev: "上一页", next: "下一页", firstPage: 1, - lastPage: function () { //在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: function () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, - hasPrev: BI.emptyFn, //pages不可用时有效 - hasNext: BI.emptyFn //pages不可用时有效 - }) + hasPrev: BI.emptyFn, // pages不可用时有效 + hasNext: BI.emptyFn // pages不可用时有效 + }); }, _init: function () { BI.Pager.superclass._init.apply(this, arguments); var self = this; this.currPage = BI.result(this.options, "curr"); - //翻页太灵敏 + // 翻页太灵敏 // this._lock = false; // this._debouce = BI.debounce(function () { // self._lock = false; @@ -41716,17 +41493,17 @@ BI.Pager = BI.inherit(BI.Widget, { groups > pages && (groups = pages); } - //计算当前组 + // 计算当前组 dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); - //当前页非首页,则输出上一页 + // 当前页非首页,则输出上一页 if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) { if (BI.isKey(prev)) { view.push({ text: prev, value: "prev", disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) - }) + }); } else { view.push(BI.extend({ disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) @@ -41734,7 +41511,7 @@ BI.Pager = BI.inherit(BI.Widget, { } } - //当前组非首组,则输出首页 + // 当前组非首组,则输出首页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { view.push({ text: first, @@ -41750,14 +41527,14 @@ BI.Pager = BI.inherit(BI.Widget, { } } - //输出当前页组 + // 输出当前页组 dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; dict.end = dict.index > 1 ? (function () { var max = curr + (groups - dict.poor - 1); return max > pages ? pages : max; }()) : groups; - if (dict.end - dict.start < groups - 1) { //最后一组状态 + if (dict.end - dict.start < groups - 1) { // 最后一组状态 dict.start = dict.end - groups + 1; } var s = dict.start, e = dict.end; @@ -41771,16 +41548,16 @@ BI.Pager = BI.inherit(BI.Widget, { text: s, value: s, selected: true - }) + }); } else { view.push({ text: s, value: s - }) + }); } } - //总页数大于连续分页数,且当前组最大页小于总页,输出尾页 + // 总页数大于连续分页数,且当前组最大页小于总页,输出尾页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0) { view.push({ @@ -41793,27 +41570,27 @@ BI.Pager = BI.inherit(BI.Widget, { text: last, value: "last", disabled: !(pages > groups && dict.end < pages && groups !== 0) - }) + }); } - //当前页不为尾页时,输出下一页 + // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { if (BI.isKey(next)) { if (pages === false) { - return {text: next, value: "next", disabled: o.hasNext(curr) === false} + return {text: next, value: "next", disabled: o.hasNext(curr) === false}; } return (dict.flow && curr === pages) ? - {text: next, value: "next", disabled: true} + {text: next, value: "next", disabled: true} : - {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; - } else { - return BI.extend({ - disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) - }, next); + {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; } + return BI.extend({ + disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) + }, next); + }())); } @@ -41947,7 +41724,7 @@ BI.A = BI.inherit(BI.Text, { target: "_blank", el: null, element: "" - }) + }); }, _init: function () { var o = this.options; @@ -41967,15 +41744,15 @@ BI.shortcut("bi.a", BI.A);/** * @type {*|void|Object} */ BI.LoadingBar = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.LoadingBar.superclass._defaultConfig.apply(this, arguments); return BI.extend( conf, { - baseCls : (conf.baseCls ||"")+' bi-loading-bar bi-tips', + baseCls: (conf.baseCls || "") + " bi-loading-bar bi-tips", height: 30, handler: BI.emptyFn - }) + }); }, - _init : function() { + _init: function () { BI.LoadingBar.superclass._init.apply(this, arguments); var self = this; this.loaded = BI.createWidget({ @@ -41984,25 +41761,25 @@ BI.LoadingBar = BI.inherit(BI.Single, { text: BI.i18nText("BI-Load_More"), width: 120, handler: this.options.handler - }) - this.loaded.on(BI.Controller.EVENT_CHANGE, function(type){ + }); + this.loaded.on(BI.Controller.EVENT_CHANGE, function (type) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); this.loading = BI.createWidget({ type: "bi.layout", width: this.options.height, - height:this.options.height, + height: this.options.height, cls: "loading-background cursor-default" - }) + }); var loaded = BI.createWidget({ type: "bi.center_adapt", items: [this.loaded] - }) + }); var loading = BI.createWidget({ type: "bi.center_adapt", items: [this.loading] - }) + }); this.cardLayout = BI.createWidget({ type: "bi.card", element: this, @@ -42013,28 +41790,28 @@ BI.LoadingBar = BI.inherit(BI.Single, { el: loading, cardName: "loading" }] - }) + }); this.invisible(); }, - _reset: function(){ + _reset: function () { this.visible(); this.loaded.setText(BI.i18nText("BI-Load_More")); this.loaded.enable(); }, - setLoaded: function(){ + setLoaded: function () { this._reset(); this.cardLayout.showCardByName("loaded"); }, - setEnd: function(){ + setEnd: function () { this.setLoaded(); this.loaded.setText(BI.i18nText("BI-No_More_Data")); this.loaded.disable(); }, - setLoading: function(){ + setLoading: function () { this._reset(); this.cardLayout.showCardByName("loading"); } @@ -42052,17 +41829,17 @@ BI.IconButton = BI.inherit(BI.BasicButton, { baseCls: (conf.baseCls || "") + " bi-icon-button horizon-center", iconWidth: null, iconHeight: null - }) + }); }, _init: function () { BI.IconButton.superclass._init.apply(this, arguments); var o = this.options; this.element.css({ - textAlign: 'center' + textAlign: "center" }); this.icon = BI.createWidget({ - type: 'bi.icon', + type: "bi.icon", width: o.iconWidth, height: o.iconHeight }); @@ -42072,11 +41849,11 @@ BI.IconButton = BI.inherit(BI.BasicButton, { type: "bi.default", element: this, items: [this.icon] - }) + }); } else { BI.createWidget({ element: this, - type: 'bi.center_adapt', + type: "bi.center_adapt", items: [this.icon] }); } @@ -42105,7 +41882,7 @@ BI.ImageButton = BI.inherit(BI.BasicButton, { src: "", iconWidth: "100%", iconHeight: "100%" - }) + }); }, _init: function () { @@ -42122,14 +41899,14 @@ BI.ImageButton = BI.inherit(BI.BasicButton, { type: "bi.center_adapt", element: this, items: [this.image] - }) + }); } else { BI.createWidget({ type: "bi.adaptive", element: this, items: [this.image], scrollable: false - }) + }); } }, @@ -42191,15 +41968,15 @@ BI.shortcut("bi.image_button", BI.ImageButton);(function ($) { _defaultConfig: function (props) { var conf = BI.Button.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { - baseCls: (conf.baseCls || "") + ' bi-button', + baseCls: (conf.baseCls || "") + " bi-button", minWidth: (props.block === true || props.clear === true) ? 0 : 90, shadow: props.clear !== true, isShadowShowingOnSelected: true, readonly: true, iconClass: "", - level: 'common', - block: false, //是否块状显示,即不显示边框,没有最小宽度的限制 - clear: false, //是否去掉边框和背景 + level: "common", + block: false, // 是否块状显示,即不显示边框,没有最小宽度的限制 + clear: false, // 是否去掉边框和背景 textAlign: "center", whiteSpace: "nowrap", forceCenter: false, @@ -42211,7 +41988,7 @@ BI.shortcut("bi.image_button", BI.ImageButton);(function ($) { bgap: 0, lgap: 0, rgap: 0 - }) + }); }, _init: function () { @@ -42246,7 +42023,7 @@ BI.shortcut("bi.image_button", BI.ImageButton);(function ($) { type: "bi.horizontal", items: [this.icon, this.text] }] - }) + }); } else { this.text = BI.createWidget({ type: "bi.label", @@ -42317,7 +42094,7 @@ BI.shortcut("bi.image_button", BI.ImageButton);(function ($) { BI.Button.superclass.destroy.apply(this, arguments); } }); - BI.shortcut('bi.button', BI.Button); + BI.shortcut("bi.button", BI.Button); BI.Button.EVENT_CHANGE = "EVENT_CHANGE"; })(jQuery);/** * guy @@ -42341,7 +42118,7 @@ BI.TextButton = BI.inherit(BI.BasicButton, { rgap: 0, text: "", py: "" - }) + }); }, _init: function () { @@ -42436,7 +42213,7 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconIconTextItem.superclass._init.apply(this, arguments); @@ -42445,7 +42222,7 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { type: "bi.layout", width: o.blankWidth, height: o.height - }) + }); this.text = BI.createWidget({ type: "bi.label", cls: "list-item-text", @@ -42558,7 +42335,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconTextIconItem.superclass._init.apply(this, arguments); @@ -42574,7 +42351,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); var icon1 = BI.createWidget({ type: "bi.center_adapt", @@ -42588,7 +42365,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { height: o.iconHeight } }] - }) + }); BI.createWidget({ type: "bi.absolute", element: this, @@ -42610,7 +42387,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { bottom: 0, right: 0 }] - }) + }); BI.createWidget(BI.extend({ element: this @@ -42694,7 +42471,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconTextItem.superclass._init.apply(this, arguments); @@ -42702,7 +42479,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { var blank = BI.createWidget({ type: "bi.layout", width: o.blankWidth - }) + }); this.text = BI.createWidget({ type: "bi.label", cls: "list-item-text", @@ -42715,7 +42492,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); this.icon = BI.createWidget({ type: "bi.center_adapt", width: c.commonWidth, @@ -42806,7 +42583,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextIconItem.superclass._init.apply(this, arguments); @@ -42822,7 +42599,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); var icon1 = BI.createWidget({ type: "bi.center_adapt", @@ -42836,11 +42613,11 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { height: o.iconHeight } }] - }) + }); var blank = BI.createWidget({ type: "bi.layout", width: c.commonWidth - }) + }); BI.createWidget({ type: "bi.absolute", element: this, @@ -42861,7 +42638,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { bottom: 0, right: 0 }] - }) + }); BI.createWidget(BI.extend({ element: this @@ -42938,7 +42715,7 @@ BI.IconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextItem.superclass._init.apply(this, arguments); @@ -43045,7 +42822,7 @@ BI.TextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextIconItem.superclass._init.apply(this, arguments); @@ -43076,321 +42853,321 @@ BI.TextIconItem = BI.inherit(BI.BasicButton, { }] }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection("left", this.text, this.icon) - })))); - }, - - doClick: function () { - BI.TextIconItem.superclass.doClick.apply(this, arguments); - if (this.isValid()) { - this.fireEvent(BI.TextIconItem.EVENT_CHANGE, this.getValue(), this); - } - }, - - setValue: function () { - if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); - } - }, - - getValue: function () { - return this.text.getValue(); - }, - - setText: function () { - this.text.setText.apply(this.text, arguments); - }, - - getText: function () { - return this.text.getText(); - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, - - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, - - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, - - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - } -}); -BI.TextIconItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_icon_item", BI.TextIconItem);/** - * guy - * 一个button和一行数 组成的一行listitem - * - * Created by GUY on 2015/9/9. - * @class BI.TextItem - * @extends BI.BasicButton - */ -BI.TextItem = BI.inherit(BI.BasicButton, { - - _defaultConfig: function () { - var conf = BI.TextItem.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-text-item", - textAlign: "left", - whiteSpace: "nowrap", - textHgap: 0, - textVgap: 0, - textLgap: 0, - textRgap: 0 - }) - }, - _init: function () { - BI.TextItem.superclass._init.apply(this, arguments); - var o = this.options; - this.text = BI.createWidget({ - type: "bi.label", - element: this, - textAlign: o.textAlign, - whiteSpace: o.whiteSpace, - textHeight: o.whiteSpace == "nowrap" ? o.height : o.textHeight, - height: o.height, - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - py: o.py - }); - }, - - doClick: function () { - BI.TextItem.superclass.doClick.apply(this, arguments); - if (this.isValid()) { - this.fireEvent(BI.TextItem.EVENT_CHANGE, this.getValue(), this); - } - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, - - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, - - doHighLight: function () { - this.text.doHighLight.apply(this.text, arguments); - }, - - unHighLight: function () { - this.text.unHighLight.apply(this.text, arguments); - }, - - setValue: function () { - if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); - } - }, - - getValue: function () { - return this.text.getValue(); - }, - - setText: function () { - this.text.setText.apply(this.text, arguments); - }, - - getText: function () { - return this.text.getText(); - } -}); -BI.TextItem.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.text_item", BI.TextItem);/** - * guy - * Created by GUY on 2015/9/9. - * @class BI.IconTextIconNode - * @extends BI.NodeButton - */ -BI.IconTextIconNode = BI.inherit(BI.NodeButton, { - _const: { - commonWidth: 25 - }, - - _defaultConfig: function () { - var conf = BI.IconTextIconNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-icon-text-icon-node", - logic: { - dynamic: false - }, - iconCls1: "close-ha-font", - iconCls2: "close-ha-font", - iconHeight: null, - iconWidth: null, - textHgap: 0, - textVgap: 0, - textLgap: 0, - textRgap: 0 - }) - }, - _init: function () { - BI.IconTextIconNode.superclass._init.apply(this, arguments); - var o = this.options, c = this._const; - this.text = BI.createWidget({ - type: "bi.label", - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - height: o.height - }) - - var icon1 = BI.createWidget({ - type: "bi.center_adapt", - cls: o.iconCls1, - width: c.commonWidth, - height: o.height, - items: [{ - el: { - type: "bi.icon", - width: o.iconWidth, - height: o.iconHeight - } - }] - }) - var blank = BI.createWidget({ - type: "bi.layout", - width: c.commonWidth, - height: o.height - }) - BI.createWidget({ - type: "bi.absolute", - element: this, - items: [{ - el: { - type: "bi.center_adapt", - cls: o.iconCls2, - width: c.commonWidth, - items: [{ - el: { - type: "bi.icon", - width: o.iconWidth, - height: o.iconHeight - } - }] - }, - top: 0, - bottom: 0, - right: 0 - }] - }) - - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection("left", icon1, this.text, blank) - })))); - }, - - doClick: function () { - BI.IconTextIconNode.superclass.doClick.apply(this, arguments); - if (this.isValid()) { - this.fireEvent(BI.IconTextIconNode.EVENT_CHANGE, this.getValue(), this); - } - }, - - doRedMark: function () { - this.text.doRedMark.apply(this.text, arguments); - }, - - unRedMark: function () { - this.text.unRedMark.apply(this.text, arguments); - }, - - setValue: function () { - if (!this.isReadOnly()) { - this.text.setValue.apply(this.text, arguments); - } - }, - - getValue: function () { - return this.text.getValue(); - }, - - setText: function () { - this.text.setText.apply(this.text, arguments); - }, - - getText: function () { - return this.text.getText(); - } -}); -BI.IconTextIconNode.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.icon_text_icon_node", BI.IconTextIconNode);/** - * guy - * Created by GUY on 2015/9/9. - * @class BI.IconTextNode - * @extends BI.NodeButton - */ -BI.IconTextNode = BI.inherit(BI.NodeButton, { - _const: { - commonWidth: 25 - }, - - _defaultConfig: function () { - var conf = BI.IconTextNode.superclass._defaultConfig.apply(this, arguments); - return BI.extend(conf, { - baseCls: (conf.baseCls || "") + " bi-icon-text-node", - logic: { - dynamic: false - }, - cls: "close-ha-font", - iconHeight: null, - iconWidth: null, - textHgap: 0, - textVgap: 0, - textLgap: 0, - textRgap: 0 - }) - }, - _init: function () { - BI.IconTextNode.superclass._init.apply(this, arguments); - var o = this.options, c = this._const; - this.text = BI.createWidget({ - type: "bi.label", - cls: "list-item-text", - textAlign: "left", - hgap: o.textHgap, - vgap: o.textVgap, - lgap: o.textLgap, - rgap: o.textRgap, - text: o.text, - value: o.value, - keyword: o.keyword, - height: o.height - }) - this.icon = BI.createWidget({ - type: "bi.center_adapt", - width: c.commonWidth, - height: o.height, - items: [{ - el: { - type: "bi.icon", - width: o.iconWidth, - height: o.iconHeight - } - }] - }) - + BI.createWidget(BI.extend({ + element: this + }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, { + items: BI.LogicFactory.createLogicItemsByDirection("left", this.text, this.icon) + })))); + }, + + doClick: function () { + BI.TextIconItem.superclass.doClick.apply(this, arguments); + if (this.isValid()) { + this.fireEvent(BI.TextIconItem.EVENT_CHANGE, this.getValue(), this); + } + }, + + setValue: function () { + if (!this.isReadOnly()) { + this.text.setValue.apply(this.text, arguments); + } + }, + + getValue: function () { + return this.text.getValue(); + }, + + setText: function () { + this.text.setText.apply(this.text, arguments); + }, + + getText: function () { + return this.text.getText(); + }, + + doRedMark: function () { + this.text.doRedMark.apply(this.text, arguments); + }, + + unRedMark: function () { + this.text.unRedMark.apply(this.text, arguments); + }, + + doHighLight: function () { + this.text.doHighLight.apply(this.text, arguments); + }, + + unHighLight: function () { + this.text.unHighLight.apply(this.text, arguments); + } +}); +BI.TextIconItem.EVENT_CHANGE = "EVENT_CHANGE"; +BI.shortcut("bi.text_icon_item", BI.TextIconItem);/** + * guy + * 一个button和一行数 组成的一行listitem + * + * Created by GUY on 2015/9/9. + * @class BI.TextItem + * @extends BI.BasicButton + */ +BI.TextItem = BI.inherit(BI.BasicButton, { + + _defaultConfig: function () { + var conf = BI.TextItem.superclass._defaultConfig.apply(this, arguments); + return BI.extend(conf, { + baseCls: (conf.baseCls || "") + " bi-text-item", + textAlign: "left", + whiteSpace: "nowrap", + textHgap: 0, + textVgap: 0, + textLgap: 0, + textRgap: 0 + }); + }, + _init: function () { + BI.TextItem.superclass._init.apply(this, arguments); + var o = this.options; + this.text = BI.createWidget({ + type: "bi.label", + element: this, + textAlign: o.textAlign, + whiteSpace: o.whiteSpace, + textHeight: o.whiteSpace == "nowrap" ? o.height : o.textHeight, + height: o.height, + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + py: o.py + }); + }, + + doClick: function () { + BI.TextItem.superclass.doClick.apply(this, arguments); + if (this.isValid()) { + this.fireEvent(BI.TextItem.EVENT_CHANGE, this.getValue(), this); + } + }, + + doRedMark: function () { + this.text.doRedMark.apply(this.text, arguments); + }, + + unRedMark: function () { + this.text.unRedMark.apply(this.text, arguments); + }, + + doHighLight: function () { + this.text.doHighLight.apply(this.text, arguments); + }, + + unHighLight: function () { + this.text.unHighLight.apply(this.text, arguments); + }, + + setValue: function () { + if (!this.isReadOnly()) { + this.text.setValue.apply(this.text, arguments); + } + }, + + getValue: function () { + return this.text.getValue(); + }, + + setText: function () { + this.text.setText.apply(this.text, arguments); + }, + + getText: function () { + return this.text.getText(); + } +}); +BI.TextItem.EVENT_CHANGE = "EVENT_CHANGE"; +BI.shortcut("bi.text_item", BI.TextItem);/** + * guy + * Created by GUY on 2015/9/9. + * @class BI.IconTextIconNode + * @extends BI.NodeButton + */ +BI.IconTextIconNode = BI.inherit(BI.NodeButton, { + _const: { + commonWidth: 25 + }, + + _defaultConfig: function () { + var conf = BI.IconTextIconNode.superclass._defaultConfig.apply(this, arguments); + return BI.extend(conf, { + baseCls: (conf.baseCls || "") + " bi-icon-text-icon-node", + logic: { + dynamic: false + }, + iconCls1: "close-ha-font", + iconCls2: "close-ha-font", + iconHeight: null, + iconWidth: null, + textHgap: 0, + textVgap: 0, + textLgap: 0, + textRgap: 0 + }); + }, + _init: function () { + BI.IconTextIconNode.superclass._init.apply(this, arguments); + var o = this.options, c = this._const; + this.text = BI.createWidget({ + type: "bi.label", + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height + }); + + var icon1 = BI.createWidget({ + type: "bi.center_adapt", + cls: o.iconCls1, + width: c.commonWidth, + height: o.height, + items: [{ + el: { + type: "bi.icon", + width: o.iconWidth, + height: o.iconHeight + } + }] + }); + var blank = BI.createWidget({ + type: "bi.layout", + width: c.commonWidth, + height: o.height + }); + BI.createWidget({ + type: "bi.absolute", + element: this, + items: [{ + el: { + type: "bi.center_adapt", + cls: o.iconCls2, + width: c.commonWidth, + items: [{ + el: { + type: "bi.icon", + width: o.iconWidth, + height: o.iconHeight + } + }] + }, + top: 0, + bottom: 0, + right: 0 + }] + }); + + BI.createWidget(BI.extend({ + element: this + }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, { + items: BI.LogicFactory.createLogicItemsByDirection("left", icon1, this.text, blank) + })))); + }, + + doClick: function () { + BI.IconTextIconNode.superclass.doClick.apply(this, arguments); + if (this.isValid()) { + this.fireEvent(BI.IconTextIconNode.EVENT_CHANGE, this.getValue(), this); + } + }, + + doRedMark: function () { + this.text.doRedMark.apply(this.text, arguments); + }, + + unRedMark: function () { + this.text.unRedMark.apply(this.text, arguments); + }, + + setValue: function () { + if (!this.isReadOnly()) { + this.text.setValue.apply(this.text, arguments); + } + }, + + getValue: function () { + return this.text.getValue(); + }, + + setText: function () { + this.text.setText.apply(this.text, arguments); + }, + + getText: function () { + return this.text.getText(); + } +}); +BI.IconTextIconNode.EVENT_CHANGE = "EVENT_CHANGE"; +BI.shortcut("bi.icon_text_icon_node", BI.IconTextIconNode);/** + * guy + * Created by GUY on 2015/9/9. + * @class BI.IconTextNode + * @extends BI.NodeButton + */ +BI.IconTextNode = BI.inherit(BI.NodeButton, { + _const: { + commonWidth: 25 + }, + + _defaultConfig: function () { + var conf = BI.IconTextNode.superclass._defaultConfig.apply(this, arguments); + return BI.extend(conf, { + baseCls: (conf.baseCls || "") + " bi-icon-text-node", + logic: { + dynamic: false + }, + cls: "close-ha-font", + iconHeight: null, + iconWidth: null, + textHgap: 0, + textVgap: 0, + textLgap: 0, + textRgap: 0 + }); + }, + _init: function () { + BI.IconTextNode.superclass._init.apply(this, arguments); + var o = this.options, c = this._const; + this.text = BI.createWidget({ + type: "bi.label", + cls: "list-item-text", + textAlign: "left", + hgap: o.textHgap, + vgap: o.textVgap, + lgap: o.textLgap, + rgap: o.textRgap, + text: o.text, + value: o.value, + keyword: o.keyword, + height: o.height + }); + this.icon = BI.createWidget({ + type: "bi.center_adapt", + width: c.commonWidth, + height: o.height, + items: [{ + el: { + type: "bi.icon", + width: o.iconWidth, + height: o.iconHeight + } + }] + }); + BI.createWidget(BI.extend({ element: this }, BI.LogicFactory.createLogic("horizontal", BI.extend(o.logic, { @@ -43456,7 +43233,7 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextIconNode.superclass._init.apply(this, arguments); @@ -43473,7 +43250,7 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); this.icon = BI.createWidget({ type: "bi.center_adapt", width: c.commonWidth, @@ -43547,7 +43324,7 @@ BI.TextNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextNode.superclass._init.apply(this, arguments); @@ -43613,12 +43390,12 @@ BI.shortcut("bi.text_node", BI.TextNode);/** BI.CodeEditor = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-code-editor', - value: '', + baseCls: "bi-code-editor", + value: "", watermark: "", lineHeight: 2, readOnly: false, - //参数显示值构造函数 + // 参数显示值构造函数 paramFormatter: function (v) { return v; } @@ -43632,13 +43409,13 @@ BI.CodeEditor = BI.inherit(BI.Single, { lineWrapping: true, lineNumbers: false, readOnly: o.readOnly, - //解决插入字段由括号或其他特殊字符包围时分裂的bug + // 解决插入字段由括号或其他特殊字符包围时分裂的bug specialChars: /[\u0000-\u001f\u007f\u00ad\u200c-\u200f\u2028\u2029\ufeff]/ }); o.lineHeight === 1 ? this.element.addClass("codemirror-low-line-height") : this.element.addClass("codemirror-high-line-height"); this.editor.on("change", function (cm, change) { BI.nextTick(function () { - self.fireEvent(BI.CodeEditor.EVENT_CHANGE) + self.fireEvent(BI.CodeEditor.EVENT_CHANGE); }); }); @@ -43664,7 +43441,7 @@ BI.CodeEditor = BI.inherit(BI.Single, { // self.editor.execCommand("goLineEnd"); // }); - //水印 + // 水印 this.watermark = BI.createWidget({ type: "bi.label", text: o.watermark, @@ -43702,7 +43479,7 @@ BI.CodeEditor = BI.inherit(BI.Single, { _setEnable: function (b) { BI.CodeEditor.superclass._setEnable.apply(this, arguments); - this.editor.setOption("readOnly", b === true ? false : "nocursor") + this.editor.setOption("readOnly", b === true ? false : "nocursor"); }, _checkWaterMark: function () { @@ -43718,12 +43495,12 @@ BI.CodeEditor = BI.inherit(BI.Single, { var value = param; param = this.options.paramFormatter(param); var from = this.editor.getCursor(); - //解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 - this.editor.replaceSelection('\u200b' + param + '\u200b'); + // 解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 + this.editor.replaceSelection("\u200b" + param + "\u200b"); var to = this.editor.getCursor(); - var options = {className: 'param', atomic: true}; + var options = {className: "param", atomic: true}; if (BI.isNotNull(param.match(/^$/))) { - options.className = 'error-param'; + options.className = "error-param"; } options.value = value; this.editor.markText(from, to, options); @@ -43740,16 +43517,16 @@ BI.CodeEditor = BI.inherit(BI.Single, { return this.editor.getValue("\n", function (line) { var rawText = line.text, value = line.text, num = 0; value.text = rawText; - //根据插入位置不同,line.markedSpan可能是乱序的 + // 根据插入位置不同,line.markedSpan可能是乱序的 _.forEach(_.sortBy(line.markedSpans, "from"), function (i, ms) { switch (i.marker.className) { case "param": case "error-param": var fieldNameLength = i.to - i.from; value = value.substr(0, i.from + num) + "$\{" + i.marker.value + "\}" + value.substr(i.to + num, value.length); - //加上${}的偏移 + // 加上${}的偏移 num += 3; - //加上实际值和显示值的长度差的偏移 + // 加上实际值和显示值的长度差的偏移 num += (i.marker.value.length - fieldNameLength); break; } @@ -43823,7 +43600,7 @@ BI.Editor = BI.inherit(BI.Single, { rgap: 0, tgap: 0, bgap: 0, - //title,warningTitle这两个属性没用 + // title,warningTitle这两个属性没用 tipType: "warning", inputType: "text", validationChecker: BI.emptyFn, @@ -43831,7 +43608,7 @@ BI.Editor = BI.inherit(BI.Single, { allowBlank: false, watermark: "", errorText: "" - }) + }); }, _init: function () { @@ -43847,12 +43624,12 @@ BI.Editor = BI.inherit(BI.Single, { allowBlank: o.allowBlank })); this.editor.element.css({ - "width": "100%", - "height": "100%", - "border": "none", - "outline": "none", - "padding": "0", - "margin": "0" + width: "100%", + height: "100%", + border: "none", + outline: "none", + padding: "0", + margin: "0" }); if (BI.isKey(this.options.watermark)) { this.watermark = BI.createWidget({ @@ -44140,10 +43917,10 @@ BI.MultifileEditor = BI.inherit(BI.Single, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-multifile-editor", multiple: false, - maxSize: -1,//1024 * 1024 + maxSize: -1, // 1024 * 1024 accept: "", url: "" - }) + }); }, _init: function () { @@ -44223,8 +44000,8 @@ BI.shortcut("bi.multifile_editor", BI.MultifileEditor);/** BI.TextAreaEditor = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.TextAreaEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-textarea-editor bi-card', - value: '' + baseCls: "bi-textarea-editor bi-card", + value: "" }); }, _init: function () { @@ -44237,7 +44014,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { height: "100%", cls: "bi-textarea textarea-editor-content display-block" }); - this.content.element.css({"resize": "none"}); + this.content.element.css({resize: "none"}); BI.createWidget({ type: "bi.absolute", element: this, @@ -44308,7 +44085,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { self.focus(); }); BI.createWidget({ - type: 'bi.absolute', + type: "bi.absolute", element: this, items: [{ el: this.watermark, @@ -44316,7 +44093,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { top: 0, right: 0 }] - }) + }); } else { this.watermark.setText(o.watermark); this.watermark.setValid(!o.invalid); @@ -44360,7 +44137,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { this.element.css(style); this.content.element.css(BI.extend({}, style, { color: style.color || BI.DOM.getContrastColor(BI.DOM.isRGBColor(style.backgroundColor) ? BI.DOM.rgb2hex(style.backgroundColor) : style.backgroundColor) - })) + })); }, getStyle: function () { @@ -44387,7 +44164,7 @@ BI.Icon = BI.inherit(BI.Single, { return BI.extend(conf, { tagName: "i", baseCls: (conf.baseCls || "") + " x-icon b-font horizon-center display-block" - }) + }); }, _init: function () { BI.Icon.superclass._init.apply(this, arguments); @@ -44410,7 +44187,7 @@ BI.Iframe = BI.inherit(BI.Single, { src: "", width: "100%", height: "100%" - }) + }); }, _init: function () { @@ -44438,11 +44215,11 @@ BI.Iframe = BI.inherit(BI.Single, { }, getWidth: function () { - return this.options.width + return this.options.width; }, getHeight: function () { - return this.options.height + return this.options.height; } }); @@ -44462,7 +44239,7 @@ BI.Img = BI.inherit(BI.Single, { src: "", width: "100%", height: "100%" - }) + }); }, _init: function () { @@ -44488,8 +44265,8 @@ BI.shortcut("bi.img", BI.Img); * @type {*|void|Object} */ BI.Checkbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.Checkbox.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.Checkbox.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-checkbox check-box-icon", selected: false, @@ -44498,16 +44275,16 @@ BI.Checkbox = BI.inherit(BI.IconButton, { height: 16, iconWidth: 16, iconHeight: 16 - }) + }); }, - _init : function() { + _init: function () { BI.Checkbox.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.Checkbox.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.Checkbox.EVENT_CHANGE); } } @@ -45141,9 +44918,9 @@ BI.Input = BI.inherit(BI.Single, { baseCls: (conf.baseCls || "") + " bi-input display-block", element: "", validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn,//按确定键能否退出编辑 + quitChecker: BI.emptyFn, // 按确定键能否退出编辑 allowBlank: false - }) + }); }, _init: function () { @@ -45170,8 +44947,8 @@ BI.Input = BI.inherit(BI.Single, { } }) .on("input propertychange", function (e) { - //这个事件在input的属性发生改变的时候就会触发(class的变化也算) - if(BI.isNotNull(e.keyCode)){ + // 这个事件在input的属性发生改变的时候就会触发(class的变化也算) + if(BI.isNotNull(e.keyCode)) { inputEventValid = true; self._keydown_ = true; _keydown(e.keyCode); @@ -45207,7 +44984,7 @@ BI.Input = BI.inherit(BI.Single, { } else { blur(); } - function blur() { + function blur () { if (!self.isValid() && self.options.quitChecker.apply(self, [BI.trim(self.getValue())]) !== false) { self.element.val(self._lastValidValue ? self._lastValidValue : ""); self._checkValidationOnValueChange(); @@ -45249,7 +45026,7 @@ BI.Input = BI.inherit(BI.Single, { this.fireEvent(BI.Input.EVENT_START); } } - if (ctrlKey === true && keyCode === 86) {//ctrlKey+V + if (ctrlKey === true && keyCode === 86) {// ctrlKey+V this._valueChange(); } else { if (keyCode == BI.KeyCode.ENTER) { @@ -45287,7 +45064,7 @@ BI.Input = BI.inherit(BI.Single, { } }, - //初始状态 + // 初始状态 _defaultState: function () { if (this.getValue() == "") { this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); @@ -45419,8 +45196,8 @@ BI.shortcut("bi.input", BI.Input);/** * @type {*|void|Object} */ BI.Radio = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.Radio.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.Radio.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-radio radio-icon", selected: false, @@ -45429,16 +45206,16 @@ BI.Radio = BI.inherit(BI.IconButton, { height: 16, iconWidth: 16, iconHeight: 16 - }) + }); }, - _init : function() { + _init: function () { BI.Radio.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.Radio.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.Radio.EVENT_CHANGE); } } @@ -45455,8 +45232,8 @@ BI.Label = BI.inherit(BI.Single, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-label", textAlign: "center", - whiteSpace: "nowrap", //normal or nowrap - forceCenter: false, //是否无论如何都要居中, 不考虑超出边界的情况, 在未知宽度和高度时有效 + whiteSpace: "nowrap", // normal or nowrap + forceCenter: false, // 是否无论如何都要居中, 不考虑超出边界的情况, 在未知宽度和高度时有效 textWidth: null, textHeight: null, hgap: 0, @@ -45468,7 +45245,7 @@ BI.Label = BI.inherit(BI.Single, { text: "", py: "", keyword: "" - }) + }); }, _createJson: function () { @@ -45673,7 +45450,7 @@ BI.Label = BI.inherit(BI.Single, { type: "bi.layout", element: this.text, scrollable: o.whiteSpace === "normal" - }) + }); }, _createNotCenterEl: function () { @@ -45791,7 +45568,7 @@ BI.Label = BI.inherit(BI.Single, { return; } if (o.whiteSpace == "normal") { - this.text = BI.createWidget(json) + this.text = BI.createWidget(json); BI.createWidget({ type: "bi.vertical_adapt", scrollable: o.whiteSpace === "normal", @@ -45871,7 +45648,7 @@ BI.Label = BI.inherit(BI.Single, { type: "bi.layout", element: this.text, scrollable: o.whiteSpace === "normal" - }) + }); }, doRedMark: function () { @@ -45900,7 +45677,7 @@ BI.Label = BI.inherit(BI.Single, { }, setStyle: function (css) { - this.text.setStyle(css) + this.text.setStyle(css); }, setValue: function (v) { @@ -45921,19 +45698,19 @@ BI.shortcut("bi.label", BI.Label);/** * @extends BI.Text */ BI.Link = BI.inherit(BI.Label, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Link.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-link", href: "", target: "_blank" - }) + }); }, - _createJson: function(){ + _createJson: function () { var o = this.options; return { - type:"bi.a", + type: "bi.a", textAlign: o.textAlign, whiteSpace: o.whiteSpace, lineHeight: o.textHeight, @@ -45946,7 +45723,7 @@ BI.Link = BI.inherit(BI.Label, { }; }, - _init : function() { + _init: function () { BI.Link.superclass._init.apply(this, arguments); } }); @@ -45959,30 +45736,30 @@ BI.shortcut("bi.link", BI.Link);/** * @type {*|void|Object} */ BI.Bubble = BI.inherit(BI.Tip, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend(BI.Bubble.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-bubble", direction: "top", text: "", height: 35 - }) + }); }, - _init : function() { + _init: function () { BI.Bubble.superclass._init.apply(this, arguments); var fn = function (e) { e.stopPropagation(); e.stopEvent(); return false; }; - this.element.bind({"click": fn, "mousedown": fn, "mouseup": fn, "mouseover": fn, "mouseenter": fn, "mouseleave": fn, "mousemove": fn}); + this.element.bind({click: fn, mousedown: fn, mouseup: fn, mouseover: fn, mouseenter: fn, mouseleave: fn, mousemove: fn}); BI.createWidget({ type: "bi.left", element: this, items: [this["_" + this.options.direction]()] - }) + }); }, - _createBubbleText: function(){ + _createBubbleText: function () { return (this.text = BI.createWidget({ type: "bi.label", cls: "bubble-text", @@ -45992,7 +45769,7 @@ BI.Bubble = BI.inherit(BI.Tip, { })); }, - _top: function(){ + _top: function () { return BI.createWidget({ type: "bi.vertical", items: [{ @@ -46004,10 +45781,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, height: 3 }] - }) + }); }, - _bottom: function(){ + _bottom: function () { return BI.createWidget({ type: "bi.vertical", items: [{ @@ -46019,10 +45796,10 @@ BI.Bubble = BI.inherit(BI.Tip, { el: this._createBubbleText(), height: 30 }] - }) + }); }, - _left: function(){ + _left: function () { return BI.createWidget({ type: "bi.right", items: [{ @@ -46034,10 +45811,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, { el: this._createBubbleText() }] - }) + }); }, - _right: function(){ + _right: function () { return BI.createWidget({ type: "bi.left", items: [{ @@ -46049,10 +45826,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, { el: this._createBubbleText() }] - }) + }); }, - setText: function(text){ + setText: function (text) { this.text.setText(text); } }); @@ -46074,23 +45851,23 @@ BI.Toast = BI.inherit(BI.Tip, { return BI.extend(BI.Toast.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-toast", text: "", - level: "success",//success或warning + level: "success", // success或warning height: 30 - }) + }); }, _init: function () { BI.Toast.superclass._init.apply(this, arguments); var o = this.options; this.element.css({ minWidth: this._const.minWidth + "px" - }) + }); this.element.addClass("toast-" + o.level); var fn = function (e) { e.stopPropagation(); e.stopEvent(); return false; }; - this.element.bind({"click": fn, "mousedown": fn, "mouseup": fn, "mouseover": fn, "mouseenter": fn, "mouseleave": fn, "mousemove": fn}); + this.element.bind({click: fn, mousedown: fn, mouseup: fn, mouseover: fn, mouseenter: fn, mouseleave: fn, mousemove: fn}); this.text = BI.createWidget({ type: "bi.label", @@ -46098,10 +45875,10 @@ BI.Toast = BI.inherit(BI.Tip, { text: o.text, height: 30, hgap: this._const.hgap - }) + }); }, - setWidth: function(width){ + setWidth: function (width) { this.element.width(width); }, @@ -46126,11 +45903,11 @@ BI.Tooltip = BI.inherit(BI.Tip, { return BI.extend(BI.Tooltip.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-tooltip", text: "", - level: "success",//success或warning + level: "success", // success或warning stopEvent: false, stopPropagation: false, height: 20 - }) + }); }, _init: function () { BI.Tooltip.superclass._init.apply(this, arguments); @@ -46141,13 +45918,13 @@ BI.Tooltip = BI.inherit(BI.Tip, { o.stopEvent && e.stopEvent(); }; this.element.bind({ - "click": fn, - "mousedown": fn, - "mouseup": fn, - "mouseover": fn, - "mouseenter": fn, - "mouseleave": fn, - "mousemove": fn + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn }); var texts = (o.text + "").split("\n"); @@ -46163,9 +45940,9 @@ BI.Tooltip = BI.inherit(BI.Tip, { whiteSpace: "normal", text: text, textHeight: 16 - } + }; }) - }) + }); } else { this.text = BI.createWidget({ type: "bi.label", @@ -46200,622 +45977,604 @@ BI.shortcut("bi.tooltip", BI.Tooltip);/** * @abstract */ BI.Trigger = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Trigger.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-trigger cursor-pointer", height: 24 - }) + }); }, - _init : function() { + _init: function () { BI.Trigger.superclass._init.apply(this, arguments); }, - setKey: function(){ + setKey: function () { }, - getKey: function(){ + getKey: function () { } });// CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE -(function(mod) { - mod(CodeMirror); -})(function(CodeMirror) { - - var tables; - var defaultTable; - var keywords; - var identifierQuote; - var CONS = { - QUERY_DIV: ";", - ALIAS_KEYWORD: "AS" - }; - var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos; - - function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" } - - function getKeywords(editor) { - var mode = editor.doc.modeOption; - if (mode === "sql") mode = "text/x-sql"; - return CodeMirror.resolveMode(mode).keywords; - } - - function getIdentifierQuote(editor) { - var mode = editor.doc.modeOption; - if (mode === "sql") mode = "text/x-sql"; - return CodeMirror.resolveMode(mode).identifierQuote || "`"; - } - - function getText(item) { - return typeof item == "string" ? item : item.text; - } - - function wrapTable(name, value) { - if (isArray(value)) value = {columns: value} - if (!value.text) value.text = name - return value - } - - function parseTables(input) { - var result = {} - if (isArray(input)) { - for (var i = input.length - 1; i >= 0; i--) { - var item = input[i] - result[getText(item).toUpperCase()] = wrapTable(getText(item), item) - } - } else if (input) { - for (var name in input) - result[name.toUpperCase()] = wrapTable(name, input[name]) - } - return result - } - - function getTable(name) { - return tables[name.toUpperCase()] - } - - function shallowClone(object) { - var result = {}; - for (var key in object) if (object.hasOwnProperty(key)) - result[key] = object[key]; - return result; - } - - function match(string, word) { - if (BI.isNotEmptyString(string) && word.length !== string.length) { - var len = string.length; - var sub = getText(word).substr(0, len); - return string.toUpperCase() === sub.toUpperCase(); - } - } - - function addMatches(result, search, wordlist, formatter) { - if (isArray(wordlist)) { - for (var i = 0; i < wordlist.length; i++) - if (match(search, wordlist[i])) result.push(formatter(wordlist[i], i)); - } else { - for (var word in wordlist) if (wordlist.hasOwnProperty(word)) { - var val = wordlist[word] - if (!val || val === true) - val = word - else - val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text - if (match(search, val)) result.push(formatter(val)) - } - } - } - - function cleanName(name) { +(function (mod) { + mod(CodeMirror); +})(function (CodeMirror) { + + var tables; + var defaultTable; + var keywords; + var identifierQuote; + var CONS = { + QUERY_DIV: ";", + ALIAS_KEYWORD: "AS" + }; + var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos; + + function isArray (val) { return Object.prototype.toString.call(val) == "[object Array]"; } + + function getKeywords (editor) { + var mode = editor.doc.modeOption; + if (mode === "sql") mode = "text/x-sql"; + return CodeMirror.resolveMode(mode).keywords; + } + + function getIdentifierQuote (editor) { + var mode = editor.doc.modeOption; + if (mode === "sql") mode = "text/x-sql"; + return CodeMirror.resolveMode(mode).identifierQuote || "`"; + } + + function getText (item) { + return typeof item === "string" ? item : item.text; + } + + function wrapTable (name, value) { + if (isArray(value)) value = {columns: value}; + if (!value.text) value.text = name; + return value; + } + + function parseTables (input) { + var result = {}; + if (isArray(input)) { + for (var i = input.length - 1; i >= 0; i--) { + var item = input[i]; + result[getText(item).toUpperCase()] = wrapTable(getText(item), item); + } + } else if (input) { + for (var name in input) {result[name.toUpperCase()] = wrapTable(name, input[name]);} + } + return result; + } + + function getTable (name) { + return tables[name.toUpperCase()]; + } + + function shallowClone (object) { + var result = {}; + for (var key in object) { + if (object.hasOwnProperty(key)) {result[key] = object[key];} + } + return result; + } + + function match (string, word) { + if (BI.isNotEmptyString(string) && word.length !== string.length) { + var len = string.length; + var sub = getText(word).substr(0, len); + return string.toUpperCase() === sub.toUpperCase(); + } + } + + function addMatches (result, search, wordlist, formatter) { + if (isArray(wordlist)) { + for (var i = 0; i < wordlist.length; i++) {if (match(search, wordlist[i])) result.push(formatter(wordlist[i], i));} + } else { + for (var word in wordlist) { + if (wordlist.hasOwnProperty(word)) { + var val = wordlist[word]; + if (!val || val === true) {val = word;} else {val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text;} + if (match(search, val)) result.push(formatter(val)); + } + } + } + } + + function cleanName (name) { // Get rid name from identifierQuote and preceding dot(.) - if (name.charAt(0) == ".") { - name = name.substr(1); - } - // replace doublicated identifierQuotes with single identifierQuotes - // and remove single identifierQuotes - var nameParts = name.split(identifierQuote+identifierQuote); - for (var i = 0; i < nameParts.length; i++) - nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote,"g"), ""); - return nameParts.join(identifierQuote); - } - - function insertIdentifierQuotes(name) { - var nameParts = getText(name).split("."); - for (var i = 0; i < nameParts.length; i++) - nameParts[i] = identifierQuote + + if (name.charAt(0) == ".") { + name = name.substr(1); + } + // replace doublicated identifierQuotes with single identifierQuotes + // and remove single identifierQuotes + var nameParts = name.split(identifierQuote + identifierQuote); + for (var i = 0; i < nameParts.length; i++) {nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote, "g"), "");} + return nameParts.join(identifierQuote); + } + + function insertIdentifierQuotes (name) { + var nameParts = getText(name).split("."); + for (var i = 0; i < nameParts.length; i++) { + nameParts[i] = identifierQuote + // doublicate identifierQuotes - nameParts[i].replace(new RegExp(identifierQuote,"g"), identifierQuote+identifierQuote) + + nameParts[i].replace(new RegExp(identifierQuote, "g"), identifierQuote + identifierQuote) + identifierQuote; - var escaped = nameParts.join("."); - if (typeof name == "string") return escaped; - name = shallowClone(name); - name.text = escaped; - return name; - } - - function nameCompletion(cur, token, result, editor) { + } + var escaped = nameParts.join("."); + if (typeof name === "string") return escaped; + name = shallowClone(name); + name.text = escaped; + return name; + } + + function nameCompletion (cur, token, result, editor) { // Try to complete table, column names and return start position of completion - var useIdentifierQuotes = false; - var nameParts = []; - var start = token.start; - var cont = true; - while (cont) { - cont = (token.string.charAt(0) == "."); - useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote); - - start = token.start; - nameParts.unshift(cleanName(token.string)); - - token = editor.getTokenAt(Pos(cur.line, token.start)); - if (token.string == ".") { - cont = true; - token = editor.getTokenAt(Pos(cur.line, token.start)); - } - } - - // Try to complete table names - var string = nameParts.join("."); - addMatches(result, string, tables, function(w) { - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); + var useIdentifierQuotes = false; + var nameParts = []; + var start = token.start; + var cont = true; + while (cont) { + cont = (token.string.charAt(0) == "."); + useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote); - // Try to complete columns from defaultTable - addMatches(result, string, defaultTable, function(w) { - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); + start = token.start; + nameParts.unshift(cleanName(token.string)); - // Try to complete columns - string = nameParts.pop(); - var table = nameParts.join("."); - - var alias = false; - var aliasTable = table; - // Check if table is available. If not, find table by Alias - if (!getTable(table)) { - var oldTable = table; - table = findTableByAlias(table, editor); - if (table !== oldTable) alias = true; - } - - var columns = getTable(table); - if (columns && columns.columns) - columns = columns.columns; - - if (columns) { - addMatches(result, string, columns, function(w) { - var tableInsert = table; - if (alias == true) tableInsert = aliasTable; - if (typeof w == "string") { - w = tableInsert + "." + w; - } else { - w = shallowClone(w); - w.text = tableInsert + "." + w.text; - } - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); - } - - return start; - } - - function eachWord(lineText, f) { - var words = lineText.split(/\s+/) - for (var i = 0; i < words.length; i++) - if (words[i]) f(words[i].replace(/[,;]/g, '')) - } - - function findTableByAlias(alias, editor) { - var doc = editor.doc; - var fullQuery = doc.getValue(); - var aliasUpperCase = alias.toUpperCase(); - var previousWord = ""; - var table = ""; - var separator = []; - var validRange = { - start: Pos(0, 0), - end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length) - }; + token = editor.getTokenAt(Pos(cur.line, token.start)); + if (token.string == ".") { + cont = true; + token = editor.getTokenAt(Pos(cur.line, token.start)); + } + } - //add separator - var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV); - while(indexOfSeparator != -1) { - separator.push(doc.posFromIndex(indexOfSeparator)); - indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1); - } - separator.unshift(Pos(0, 0)); - separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length)); - - //find valid range - var prevItem = null; - var current = editor.getCursor() - for (var i = 0; i < separator.length; i++) { - if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) { - validRange = {start: prevItem, end: separator[i]}; - break; - } - prevItem = separator[i]; - } - - var query = doc.getRange(validRange.start, validRange.end, false); - - for (var i = 0; i < query.length; i++) { - var lineText = query[i]; - eachWord(lineText, function(word) { - var wordUpperCase = word.toUpperCase(); - if (wordUpperCase === aliasUpperCase && getTable(previousWord)) - table = previousWord; - if (wordUpperCase !== CONS.ALIAS_KEYWORD) - previousWord = word; - }); - if (table) break; - } - return table; - } - - CodeMirror.registerHelper("hint", "sql", function(editor, options) { - tables = parseTables(options && options.tables) - var defaultTableName = options && options.defaultTable; - var disableKeywords = options && options.disableKeywords; - defaultTable = defaultTableName && getTable(defaultTableName); - keywords = getKeywords(editor); - var keywordsCount = BI.size(keywords); - var functions = []; - var desc = {}; - var cur = editor.getCursor(); - var token = editor.getTokenAt(cur); - BI.each(BI.FormulaCollections, function(idx, formula){ - if(formula.lastIndexOf(token.string, 0) == 0 && !BI.contains(functions, formula)){ - functions.push(formula); - } - }); - BI.each(BI.FormulaJson, function(idx, formula){ - desc[formula.name.toLowerCase()] = formula.def; - }); - keywords = BI.concat(BI.keys(keywords), functions); - identifierQuote = getIdentifierQuote(editor); + // Try to complete table names + var string = nameParts.join("."); + addMatches(result, string, tables, function (w) { + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + + // Try to complete columns from defaultTable + addMatches(result, string, defaultTable, function (w) { + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + + // Try to complete columns + string = nameParts.pop(); + var table = nameParts.join("."); - if (defaultTableName && !defaultTable) - defaultTable = findTableByAlias(defaultTableName, editor); + var alias = false; + var aliasTable = table; + // Check if table is available. If not, find table by Alias + if (!getTable(table)) { + var oldTable = table; + table = findTableByAlias(table, editor); + if (table !== oldTable) alias = true; + } + + var columns = getTable(table); + if (columns && columns.columns) {columns = columns.columns;} - defaultTable = defaultTable || []; + if (columns) { + addMatches(result, string, columns, function (w) { + var tableInsert = table; + if (alias == true) tableInsert = aliasTable; + if (typeof w === "string") { + w = tableInsert + "." + w; + } else { + w = shallowClone(w); + w.text = tableInsert + "." + w.text; + } + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + } - if (defaultTable.columns) - defaultTable = defaultTable.columns; + return start; + } - var result = []; - var start, end, search; - if (token.end > cur.ch) { - token.end = cur.ch; - token.string = token.string.slice(0, cur.ch - token.start); + function eachWord (lineText, f) { + var words = lineText.split(/\s+/); + for (var i = 0; i < words.length; i++) {if (words[i]) f(words[i].replace(/[,;]/g, ""));} } - if (token.string.match(/^[.`"\w@]\w*$/)) { - search = token.string; - start = token.start; - end = token.end; - } else { - start = end = cur.ch; - search = ""; + function findTableByAlias (alias, editor) { + var doc = editor.doc; + var fullQuery = doc.getValue(); + var aliasUpperCase = alias.toUpperCase(); + var previousWord = ""; + var table = ""; + var separator = []; + var validRange = { + start: Pos(0, 0), + end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length) + }; + + // add separator + var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV); + while(indexOfSeparator != -1) { + separator.push(doc.posFromIndex(indexOfSeparator)); + indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator + 1); + } + separator.unshift(Pos(0, 0)); + separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length)); + + // find valid range + var prevItem = null; + var current = editor.getCursor(); + for (var i = 0; i < separator.length; i++) { + if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) { + validRange = {start: prevItem, end: separator[i]}; + break; + } + prevItem = separator[i]; + } + + var query = doc.getRange(validRange.start, validRange.end, false); + + for (var i = 0; i < query.length; i++) { + var lineText = query[i]; + eachWord(lineText, function (word) { + var wordUpperCase = word.toUpperCase(); + if (wordUpperCase === aliasUpperCase && getTable(previousWord)) {table = previousWord;} + if (wordUpperCase !== CONS.ALIAS_KEYWORD) {previousWord = word;} + }); + if (table) break; + } + return table; } - if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) { - start = nameCompletion(cur, token, result, editor); - } else { - addMatches(result, search, tables, function(w) {return w}); - addMatches(result, search, defaultTable, function(w) {return w}); - if (!disableKeywords) - addMatches(result, search, keywords, function(w, i) { - var isKeyword = i < keywordsCount; - return { - isKeyword: isKeyword, - text: w - // description: desc[w] || "SQL关键字", - // className: isKeyword ? "sql-keyword" : "sql-fr-function", - // render: function (Element, self, data) { - // var label = BI.createWidget({ - // type: "bi.label", - // element: Element, - // text: data.displayText || getText(data) - // }); - // label.setTitle(data.description, { - // container: "body" - - // }); - // } - }; + + CodeMirror.registerHelper("hint", "sql", function (editor, options) { + tables = parseTables(options && options.tables); + var defaultTableName = options && options.defaultTable; + var disableKeywords = options && options.disableKeywords; + defaultTable = defaultTableName && getTable(defaultTableName); + keywords = getKeywords(editor); + var keywordsCount = BI.size(keywords); + var functions = []; + var desc = {}; + var cur = editor.getCursor(); + var token = editor.getTokenAt(cur); + BI.each(BI.FormulaCollections, function (idx, formula) { + if(formula.lastIndexOf(token.string, 0) == 0 && !BI.contains(functions, formula)) { + functions.push(formula); + } }); - } + BI.each(BI.FormulaJson, function (idx, formula) { + desc[formula.name.toLowerCase()] = formula.def; + }); + keywords = BI.concat(BI.keys(keywords), functions); + identifierQuote = getIdentifierQuote(editor); + + if (defaultTableName && !defaultTable) {defaultTable = findTableByAlias(defaultTableName, editor);} + + defaultTable = defaultTable || []; + + if (defaultTable.columns) {defaultTable = defaultTable.columns;} - return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)}; - }); + var result = []; + var start, end, search; + if (token.end > cur.ch) { + token.end = cur.ch; + token.string = token.string.slice(0, cur.ch - token.start); + } + + if (token.string.match(/^[.`"\w@]\w*$/)) { + search = token.string; + start = token.start; + end = token.end; + } else { + start = end = cur.ch; + search = ""; + } + if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) { + start = nameCompletion(cur, token, result, editor); + } else { + addMatches(result, search, tables, function (w) {return w;}); + addMatches(result, search, defaultTable, function (w) {return w;}); + if (!disableKeywords) { + addMatches(result, search, keywords, function (w, i) { + var isKeyword = i < keywordsCount; + return { + isKeyword: isKeyword, + text: w + // description: desc[w] || "SQL关键字", + // className: isKeyword ? "sql-keyword" : "sql-fr-function", + // render: function (Element, self, data) { + // var label = BI.createWidget({ + // type: "bi.label", + // element: Element, + // text: data.displayText || getText(data) + // }); + // label.setTitle(data.description, { + // container: "body" + + // }); + // } + }; + }); + } + } + + return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)}; + }); }); // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE -(function(mod) { +(function (mod) { mod(CodeMirror); -})(function(CodeMirror) { +})(function (CodeMirror) { "use strict"; -CodeMirror.defineMode("sql", function(config, parserConfig) { - "use strict"; + CodeMirror.defineMode("sql", function (config, parserConfig) { + "use strict"; - var client = parserConfig.client || {}, - atoms = parserConfig.atoms || {"false": true, "true": true, "null": true}, - builtin = parserConfig.builtin || {}, - keywords = parserConfig.keywords || {}, - operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/, - support = parserConfig.support || {}, - hooks = parserConfig.hooks || {}, - dateSQL = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true}, - functions = parserConfig.functions || {}; + var client = parserConfig.client || {}, + atoms = parserConfig.atoms || {false: true, true: true, null: true}, + builtin = parserConfig.builtin || {}, + keywords = parserConfig.keywords || {}, + operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/, + support = parserConfig.support || {}, + hooks = parserConfig.hooks || {}, + dateSQL = parserConfig.dateSQL || {date: true, time: true, timestamp: true}, + functions = parserConfig.functions || {}; - function tokenBase(stream, state) { - var ch = stream.next(); + function tokenBase (stream, state) { + var ch = stream.next(); - // call hooks from the mime type - if (hooks[ch]) { - var result = hooks[ch](stream, state); - if (result !== false) return result; - } + // call hooks from the mime type + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } - if (support.hexNumber && + if (support.hexNumber && ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) { - // hex - // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html - return "number"; - } else if (support.binaryNumber && + // hex + // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html + return "number"; + } else if (support.binaryNumber && (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) || (ch == "0" && stream.match(/^b[01]+/)))) { - // bitstring - // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html - return "number"; - } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { - // numbers - // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html - stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/); - support.decimallessFloat && stream.match(/^\.(?!\.)/); - return "number"; - } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { - // placeholders - return "variable-3"; - } else if (ch == "'" || (ch == '"' && support.doubleQuote)) { - // strings - // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html - state.tokenize = tokenLiteral(ch); - return state.tokenize(stream, state); - } else if ((((support.nCharCast && (ch == "n" || ch == "N")) + // bitstring + // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html + return "number"; + } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { + // numbers + // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html + stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/); + support.decimallessFloat && stream.match(/^\.(?!\.)/); + return "number"; + } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { + // placeholders + return "variable-3"; + } else if (ch == "'" || (ch == "\"" && support.doubleQuote)) { + // strings + // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html + state.tokenize = tokenLiteral(ch); + return state.tokenize(stream, state); + } else if ((((support.nCharCast && (ch == "n" || ch == "N")) || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) - && (stream.peek() == "'" || stream.peek() == '"'))) { - // charset casting: _utf8'str', N'str', n'str' - // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html - return "keyword"; - } else if (/^[\(\),\;\[\]]/.test(ch)) { - // no highlighting - return null; - } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { - // 1-line comment - stream.skipToEnd(); - return "comment"; - } else if ((support.commentHash && ch == "#") + && (stream.peek() == "'" || stream.peek() == "\""))) { + // charset casting: _utf8'str', N'str', n'str' + // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html + return "keyword"; + } else if (/^[\(\),\;\[\]]/.test(ch)) { + // no highlighting + return null; + } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { + // 1-line comment + stream.skipToEnd(); + return "comment"; + } else if ((support.commentHash && ch == "#") || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) { - // 1-line comments - // ref: https://kb.askmonty.org/en/comment-syntax/ - stream.skipToEnd(); - return "comment"; - } else if (ch == "/" && stream.eat("*")) { - // multi-line comments - // ref: https://kb.askmonty.org/en/comment-syntax/ - state.tokenize = tokenComment(1); - return state.tokenize(stream, state); - } else if (ch == ".") { - // .1 for 0.1 - if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) - return "number"; - if (stream.match(/^\.+/)) - return null - // .table_name (ODBC) - // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html - if (support.ODBCdotTable && stream.match(/^[\w\d_]+/)) - return "variable-2"; - } else if (operatorChars.test(ch)) { - // operators - stream.eatWhile(operatorChars); - return null; - } else if (ch == '{' && + // 1-line comments + // ref: https://kb.askmonty.org/en/comment-syntax/ + stream.skipToEnd(); + return "comment"; + } else if (ch == "/" && stream.eat("*")) { + // multi-line comments + // ref: https://kb.askmonty.org/en/comment-syntax/ + state.tokenize = tokenComment(1); + return state.tokenize(stream, state); + } else if (ch == ".") { + // .1 for 0.1 + if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {return "number";} + if (stream.match(/^\.+/)) {return null;} + // .table_name (ODBC) + // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html + if (support.ODBCdotTable && stream.match(/^[\w\d_]+/)) {return "variable-2";} + } else if (operatorChars.test(ch)) { + // operators + stream.eatWhile(operatorChars); + return null; + } else if (ch == "{" && (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) { - // dates (weird ODBC syntax) - // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html - return "number"; - } else { - stream.eatWhile(/^[_\w\d]/); - var word = stream.current().toLowerCase(); - // dates (standard SQL syntax) - // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html - if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) - return "number"; - if (atoms.hasOwnProperty(word)) return "atom"; - if (builtin.hasOwnProperty(word)) return "builtin"; - if (functions.hasOwnProperty(word) && stream.peek() === '(') return "function"; - if (keywords.hasOwnProperty(word)) return "keyword"; - if (client.hasOwnProperty(word)) return "string-2"; - return null; - } - } - - // 'string', with char specified in quote escaped by '\' - function tokenLiteral(quote) { - return function(stream, state) { - var escaped = false, ch; - while ((ch = stream.next()) != null) { - if (ch == quote && !escaped) { - state.tokenize = tokenBase; - break; - } - escaped = !escaped && ch == "\\"; - } - return "string"; - }; - } - function tokenComment(depth) { - return function(stream, state) { - var m = stream.match(/^.*?(\/\*|\*\/)/) - if (!m) stream.skipToEnd() - else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1) - else if (depth > 1) state.tokenize = tokenComment(depth - 1) - else state.tokenize = tokenBase - return "comment" - } - } - - function pushContext(stream, state, type) { - state.context = { - prev: state.context, - indent: stream.indentation(), - col: stream.column(), - type: type - }; - } + // dates (weird ODBC syntax) + // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html + return "number"; + } else { + stream.eatWhile(/^[_\w\d]/); + var word = stream.current().toLowerCase(); + // dates (standard SQL syntax) + // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html + if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) {return "number";} + if (atoms.hasOwnProperty(word)) return "atom"; + if (builtin.hasOwnProperty(word)) return "builtin"; + if (functions.hasOwnProperty(word) && stream.peek() === "(") return "function"; + if (keywords.hasOwnProperty(word)) return "keyword"; + if (client.hasOwnProperty(word)) return "string-2"; + return null; + } + } + + // 'string', with char specified in quote escaped by '\' + function tokenLiteral (quote) { + return function (stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && ch == "\\"; + } + return "string"; + }; + } + function tokenComment (depth) { + return function (stream, state) { + var m = stream.match(/^.*?(\/\*|\*\/)/); + if (!m) stream.skipToEnd(); + else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1); + else if (depth > 1) state.tokenize = tokenComment(depth - 1); + else state.tokenize = tokenBase; + return "comment"; + }; + } - function popContext(state) { - state.indent = state.context.indent; - state.context = state.context.prev; - } + function pushContext (stream, state, type) { + state.context = { + prev: state.context, + indent: stream.indentation(), + col: stream.column(), + type: type + }; + } - return { - startState: function() { - return {tokenize: tokenBase, context: null}; - }, + function popContext (state) { + state.indent = state.context.indent; + state.context = state.context.prev; + } - token: function(stream, state) { - if (stream.sol()) { - if (state.context && state.context.align == null) - state.context.align = false; - } - if (state.tokenize == tokenBase && stream.eatSpace()) return null; + return { + startState: function () { + return {tokenize: tokenBase, context: null}; + }, - var style = state.tokenize(stream, state); - if (style == "comment") return style; + token: function (stream, state) { + if (stream.sol()) { + if (state.context && state.context.align == null) {state.context.align = false;} + } + if (state.tokenize == tokenBase && stream.eatSpace()) return null; - if (state.context && state.context.align == null) - state.context.align = true; + var style = state.tokenize(stream, state); + if (style == "comment") return style; - var tok = stream.current(); - if (tok == "(") - pushContext(stream, state, ")"); - else if (tok == "[") - pushContext(stream, state, "]"); - else if (state.context && state.context.type == tok) - popContext(state); - return style; - }, + if (state.context && state.context.align == null) {state.context.align = true;} - indent: function(state, textAfter) { - var cx = state.context; - if (!cx) return CodeMirror.Pass; - var closing = textAfter.charAt(0) == cx.type; - if (cx.align) return cx.col + (closing ? 0 : 1); - else return cx.indent + (closing ? 0 : config.indentUnit); - }, + var tok = stream.current(); + if (tok == "(") {pushContext(stream, state, ")");} else if (tok == "[") {pushContext(stream, state, "]");} else if (state.context && state.context.type == tok) {popContext(state);} + return style; + }, - blockCommentStart: "/*", - blockCommentEnd: "*/", - lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--" - }; -}); + indent: function (state, textAfter) { + var cx = state.context; + if (!cx) return CodeMirror.Pass; + var closing = textAfter.charAt(0) == cx.type; + if (cx.align) return cx.col + (closing ? 0 : 1); + return cx.indent + (closing ? 0 : config.indentUnit); + }, -(function() { - "use strict"; - - // `identifier` - function hookIdentifier(stream) { - // MySQL/MariaDB identifiers - // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html - var ch; - while ((ch = stream.next()) != null) { - if (ch == "`" && !stream.eat("`")) return "variable-2"; - } - stream.backUp(stream.current().length - 1); - return stream.eatWhile(/\w/) ? "variable-2" : null; - } - - // "identifier" - function hookIdentifierDoublequote(stream) { - // Standard SQL /SQLite identifiers - // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier - // ref: http://sqlite.org/lang_keywords.html - var ch; - while ((ch = stream.next()) != null) { - if (ch == "\"" && !stream.eat("\"")) return "variable-2"; - } - stream.backUp(stream.current().length - 1); - return stream.eatWhile(/\w/) ? "variable-2" : null; - } - - // variable token - function hookVar(stream) { - // variables - // @@prefix.varName @varName - // varName can be quoted with ` or ' or " - // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html - if (stream.eat("@")) { - stream.match(/^session\./); - stream.match(/^local\./); - stream.match(/^global\./); - } - - if (stream.eat("'")) { - stream.match(/^.*'/); - return "variable-2"; - } else if (stream.eat('"')) { - stream.match(/^.*"/); - return "variable-2"; - } else if (stream.eat("`")) { - stream.match(/^.*`/); - return "variable-2"; - } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { - return "variable-2"; - } - return null; - }; - - // short client keyword token - function hookClient(stream) { - // \N means NULL - // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html - if (stream.eat("N")) { - return "atom"; - } - // \g, etc - // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html - return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; - } - - // these keywords are used by all SQL dialects (however, a mode can still overwrite it) - var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; - - // turn a space-separated list into an array - function set(str) { - var obj = {}, words = str.split(" "); - for (var i = 0; i < words.length; ++i) obj[words[i]] = true; - return obj; - } - - // A generic SQL Mode. It's not a standard, it just try to support what is generally supported - CodeMirror.defineMIME("text/x-sql", { - name: "sql", - keywords: set(sqlKeywords + "begin"), - builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"), - atoms: set("false true null unknown"), - operatorChars: /^[*+\-%<>!=]/, - dateSQL: set("date time timestamp"), - support: set("ODBCdotTable doubleQuote binaryNumber hexNumber"), - functions: BI.makeObject(BI.FormulaCollections, true) - }); -}()); + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--" + }; + }); + + (function () { + "use strict"; + + // `identifier` + function hookIdentifier (stream) { + // MySQL/MariaDB identifiers + // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html + var ch; + while ((ch = stream.next()) != null) { + if (ch == "`" && !stream.eat("`")) return "variable-2"; + } + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; + } + + // "identifier" + function hookIdentifierDoublequote (stream) { + // Standard SQL /SQLite identifiers + // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier + // ref: http://sqlite.org/lang_keywords.html + var ch; + while ((ch = stream.next()) != null) { + if (ch == "\"" && !stream.eat("\"")) return "variable-2"; + } + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; + } + + // variable token + function hookVar (stream) { + // variables + // @@prefix.varName @varName + // varName can be quoted with ` or ' or " + // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html + if (stream.eat("@")) { + stream.match(/^session\./); + stream.match(/^local\./); + stream.match(/^global\./); + } + + if (stream.eat("'")) { + stream.match(/^.*'/); + return "variable-2"; + } else if (stream.eat("\"")) { + stream.match(/^.*"/); + return "variable-2"; + } else if (stream.eat("`")) { + stream.match(/^.*`/); + return "variable-2"; + } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { + return "variable-2"; + } + return null; + } + + // short client keyword token + function hookClient (stream) { + // \N means NULL + // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html + if (stream.eat("N")) { + return "atom"; + } + // \g, etc + // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html + return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; + } + + // these keywords are used by all SQL dialects (however, a mode can still overwrite it) + var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; + + // turn a space-separated list into an array + function set (str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } + + // A generic SQL Mode. It's not a standard, it just try to support what is generally supported + CodeMirror.defineMIME("text/x-sql", { + name: "sql", + keywords: set(sqlKeywords + "begin"), + builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable doubleQuote binaryNumber hexNumber"), + functions: BI.makeObject(BI.FormulaCollections, true) + }); + }()); }); @@ -46853,8 +46612,8 @@ CodeMirror.defineMode("sql", function(config, parserConfig) { BI.SQLEditor = BI.inherit(BI.Widget, { _defaultConfig: function () { return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-sql-editor', - value: '', + baseCls: "bi-sql-editor", + value: "", lineHeight: 2, showHint: true }); @@ -46878,7 +46637,7 @@ BI.SQLEditor = BI.inherit(BI.Widget, { }); } BI.nextTick(function () { - self.fireEvent(BI.FormulaEditor.EVENT_CHANGE) + self.fireEvent(BI.FormulaEditor.EVENT_CHANGE); }); }); @@ -46891,7 +46650,7 @@ BI.SQLEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.FormulaEditor.EVENT_BLUR); }); - //水印 + // 水印 this.watermark = BI.createWidget({ type: "bi.label", text: BI.i18nText("Please_Enter_SQL"), @@ -46968,7 +46727,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I // └────────────────────────────────────────────────────────────┘ \\ (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("eve", function() { + define("eve", function () { return factory(); }); } else if (typeof exports === "object") { @@ -46976,7 +46735,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } else { glob.eve = factory(); } -}(this, function(){ +}(this, function () { var version = "0.4.2", has = "hasOwnProperty", separator = /[\.\/]/, @@ -46988,7 +46747,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I current_event, stop, events = {n: {}}, - /*\ + /* \ * eve [ method ] @@ -47018,10 +46777,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I errors = []; current_event = name; stop = 0; - for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) { - indexed.push(listeners[i].zIndex); - if (listeners[i].zIndex < 0) { - queue[listeners[i].zIndex] = listeners[i]; + for (var i = 0, ii = listeners.length; i < ii; i++) { + if ("zIndex" in listeners[i]) { + indexed.push(listeners[i].zIndex); + if (listeners[i].zIndex < 0) { + queue[listeners[i].zIndex] = listeners[i]; + } } } indexed.sort(numsort); @@ -47048,7 +46809,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (stop) { break; } - } while (l) + } while (l); } else { queue[l.zIndex] = l; } @@ -47065,7 +46826,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; // Undocumented. Debug only. eve._events = events; - /*\ + /* \ * eve.listeners [ method ] @@ -47109,7 +46870,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return out; }; - /*\ + /* \ * eve.on [ method ] ** @@ -47135,7 +46896,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ eve.on = function (name, f) { name = String(name); - if (typeof f != "function") { + if (typeof f !== "function") { return function () {}; } var names = name.split(separator), @@ -47145,8 +46906,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I e = e.hasOwnProperty(names[i]) && e[names[i]] || (e[names[i]] = {n: {}}); } e.f = e.f || []; - for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) { - return fun; + for (i = 0, ii = e.f.length; i < ii; i++) { + if (e.f[i] == f) { + return fun; + } } e.f.push(f); return function (zIndex) { @@ -47155,7 +46918,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } }; }; - /*\ + /* \ * eve.f [ method ] ** @@ -47177,7 +46940,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve.apply(null, [event, null].concat(attrs).concat([].slice.call(arguments, 0))); }; }; - /*\ + /* \ * eve.stop [ method ] ** @@ -47186,7 +46949,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve.stop = function () { stop = 1; }; - /*\ + /* \ * eve.nt [ method ] ** @@ -47206,7 +46969,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return current_event; }; - /*\ + /* \ * eve.nts [ method ] ** @@ -47218,7 +46981,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve.nts = function () { return current_event.split(separator); }; - /*\ + /* \ * eve.off [ method ] ** @@ -47230,7 +46993,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards - f (function) event handler function \*/ - /*\ + /* \ * eve.unbind [ method ] ** @@ -47256,8 +47019,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I splice.push(e[names[i]]); } } else { - for (key in e) if (e[has](key)) { - splice.push(e[key]); + for (key in e) { + if (e[has](key)) { + splice.push(e[key]); + } } } cur.splice.apply(cur, splice); @@ -47268,31 +47033,39 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I while (e.n) { if (f) { if (e.f) { - for (j = 0, jj = e.f.length; j < jj; j++) if (e.f[j] == f) { - e.f.splice(j, 1); - break; + for (j = 0, jj = e.f.length; j < jj; j++) { + if (e.f[j] == f) { + e.f.splice(j, 1); + break; + } } !e.f.length && delete e.f; } - for (key in e.n) if (e.n[has](key) && e.n[key].f) { - var funcs = e.n[key].f; - for (j = 0, jj = funcs.length; j < jj; j++) if (funcs[j] == f) { - funcs.splice(j, 1); - break; + for (key in e.n) { + if (e.n[has](key) && e.n[key].f) { + var funcs = e.n[key].f; + for (j = 0, jj = funcs.length; j < jj; j++) { + if (funcs[j] == f) { + funcs.splice(j, 1); + break; + } + } + !funcs.length && delete e.n[key].f; } - !funcs.length && delete e.n[key].f; } } else { delete e.f; - for (key in e.n) if (e.n[has](key) && e.n[key].f) { - delete e.n[key].f; + for (key in e.n) { + if (e.n[has](key) && e.n[key].f) { + delete e.n[key].f; + } } } e = e.n; } } }; - /*\ + /* \ * eve.once [ method ] ** @@ -47316,7 +47089,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; return eve.on(name, f2); }; - /*\ + /* \ * eve.version [ property (string) ] ** @@ -47340,7 +47113,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.core", ["eve"], function(eve) { + define("raphael.core", ["eve"], function (eve) { return factory(eve); }); } else if (typeof exports === "object") { @@ -47349,7 +47122,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I glob.Raphael = factory(glob.eve); } }(this, function (eve) { - /*\ + /* \ * Raphael [ method ] ** @@ -47399,22 +47172,22 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I | text: "Dump" | }]); \*/ - function R(first) { + function R (first) { if (R.is(first, "function")) { return loaded ? first() : eve.on("raphael.DOMload", first); } else if (R.is(first, array)) { return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first); - } else { - var args = Array.prototype.slice.call(arguments, 0); - if (R.is(args[args.length - 1], "function")) { - var f = args.pop(); - return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () { - f.call(R._engine.create[apply](R, args)); - }); - } else { - return R._engine.create[apply](R, arguments); - } } + var args = Array.prototype.slice.call(arguments, 0); + if (R.is(args[args.length - 1], "function")) { + var f = args.pop(); + return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () { + f.call(R._engine.create[apply](R, args)); + }); + } + return R._engine.create[apply](R, arguments); + + } R.version = "2.1.4"; R.eve = eve; @@ -47433,13 +47206,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I is: g.win.Raphael }, Paper = function () { - /*\ + /* \ * Paper.ca [ property (object) ] ** * Shortcut for @Paper.customAttributes \*/ - /*\ + /* \ * Paper.customAttributes [ property (object) ] ** @@ -47471,7 +47244,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I appendChild = "appendChild", apply = "apply", concat = "concat", - supportsTouch = ('ontouchstart' in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, //taken from Modernizr touch test + supportsTouch = ("ontouchstart" in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, // taken from Modernizr touch test E = "", S = " ", Str = String, @@ -47499,7 +47272,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I push = "push", ISURL = R._ISURL = /^url\(['"]?(.+?)['"]?\)$/i, colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i, - isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1}, + isnan = {NaN: 1, Infinity: 1, "-Infinity": 1}, bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/, round = math.round, setAttribute = "setAttribute", @@ -47516,8 +47289,8 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I cy: 0, fill: "#fff", "fill-opacity": 1, - font: '10px "Arial"', - "font-family": '"Arial"', + font: "10px \"Arial\"", + "font-family": "\"Arial\"", "font-size": "10", "font-style": "normal", "font-weight": 400, @@ -47623,12 +47396,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); }, - set : function(el) { + set: function (el) { var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); } }, - /*\ + /* \ * Raphael.mapPath [ method ] ** @@ -47657,7 +47430,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; R._g = g; - /*\ + /* \ * Raphael.type [ property (string) ] ** @@ -47667,21 +47440,21 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (R.type == "VML") { var d = g.doc.createElement("div"), b; - d.innerHTML = ''; + d.innerHTML = ""; b = d.firstChild; b.style.behavior = "url(#default#VML)"; - if (!(b && typeof b.adj == "object")) { + if (!(b && typeof b.adj === "object")) { return (R.type = E); } d = null; } - /*\ + /* \ * Raphael.svg [ property (boolean) ] ** * `true` if browser supports SVG. \*/ - /*\ + /* \ * Raphael.vml [ property (boolean) ] ** @@ -47689,7 +47462,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ R.svg = !(R.vml = R.type == "VML"); R._Paper = Paper; - /*\ + /* \ * Raphael.fn [ property (object) ] ** @@ -47718,7 +47491,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.fn = paperproto = Paper.prototype = R.prototype; R._id = 0; R._oid = 0; - /*\ + /* \ * Raphael.is [ method ] ** @@ -47737,24 +47510,26 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return o instanceof Array; } return (type == "null" && o === null) || - (type == typeof o && o !== null) || + (type === typeof o && o !== null) || (type == "object" && o === Object(o)) || (type == "array" && Array.isArray && Array.isArray(o)) || objectToString.call(o).slice(8, -1).toLowerCase() == type; }; - function clone(obj) { - if (typeof obj == "function" || Object(obj) !== obj) { + function clone (obj) { + if (typeof obj === "function" || Object(obj) !== obj) { return obj; } var res = new obj.constructor; - for (var key in obj) if (obj[has](key)) { - res[key] = clone(obj[key]); + for (var key in obj) { + if (obj[has](key)) { + res[key] = clone(obj[key]); + } } return res; } - /*\ + /* \ * Raphael.angle [ method ] ** @@ -47776,11 +47551,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return 0; } return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360; - } else { - return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); } + return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); + }; - /*\ + /* \ * Raphael.rad [ method ] ** @@ -47792,7 +47567,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.rad = function (deg) { return deg % 360 * PI / 180; }; - /*\ + /* \ * Raphael.deg [ method ] ** @@ -47802,9 +47577,9 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (number) angle in degrees. \*/ R.deg = function (rad) { - return Math.round ((rad * 180 / PI% 360)* 1000) / 1000; + return Math.round ((rad * 180 / PI % 360) * 1000) / 1000; }; - /*\ + /* \ * Raphael.snapTo [ method ] ** @@ -47819,8 +47594,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I tolerance = R.is(tolerance, "finite") ? tolerance : 10; if (R.is(values, array)) { var i = values.length; - while (i--) if (abs(values[i] - value) <= tolerance) { - return values[i]; + while (i--) { + if (abs(values[i] - value) <= tolerance) { + return values[i]; + } } } else { values = +values; @@ -47835,7 +47612,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return value; }; - /*\ + /* \ * Raphael.createUUID [ method ] ** @@ -47851,7 +47628,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return v.toString(16); }); - /*\ + /* \ * Raphael.setWindow [ method ] ** @@ -47947,7 +47724,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return rgb; }; - /*\ + /* \ * Raphael.color [ method ] ** @@ -48000,7 +47777,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I clr.toString = rgbtoString; return clr; }; - /*\ + /* \ * Raphael.hsb2rgb [ method ] ** @@ -48037,7 +47814,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; - /*\ + /* \ * Raphael.hsl2rgb [ method ] ** @@ -48078,7 +47855,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; - /*\ + /* \ * Raphael.rgb2hsb [ method ] ** @@ -48104,15 +47881,15 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I V = mmax(r, g, b); C = V - mmin(r, g, b); H = (C == 0 ? null : - V == r ? (g - b) / C : - V == g ? (b - r) / C + 2 : + V == r ? (g - b) / C : + V == g ? (b - r) / C + 2 : (r - g) / C + 4 ); H = ((H + 360) % 6) * 60 / 360; S = C == 0 ? 0 : C / V; return {h: H, s: S, b: V, toString: hsbtoString}; }; - /*\ + /* \ * Raphael.rgb2hsl [ method ] ** @@ -48141,24 +47918,26 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I H = (C == 0 ? null : M == r ? (g - b) / C : M == g ? (b - r) / C + 2 : - (r - g) / C + 4); + (r - g) / C + 4); H = ((H + 360) % 6) * 60 / 360; L = (M + m) / 2; S = (C == 0 ? 0 : L < .5 ? C / (2 * L) : - C / (2 - 2 * L)); + C / (2 - 2 * L)); return {h: H, s: S, l: L, toString: hsltoString}; }; R._path2string = function () { return this.join(",").replace(p2s, "$1"); }; - function repush(array, item) { - for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) { - return array.push(array.splice(i, 1)[0]); + function repush (array, item) { + for (var i = 0, ii = array.length; i < ii; i++) { + if (array[i] === item) { + return array.push(array.splice(i, 1)[0]); + } } } - function cacher(f, scope, postprocessor) { - function newf() { + function cacher (f, scope, postprocessor) { + function newf () { var arg = Array.prototype.slice.call(arguments, 0), args = arg.join("\u2400"), cache = newf.cache = newf.cache || {}, @@ -48190,11 +47969,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I img.src = src; }; - function clrToString() { + function clrToString () { return this.hex; } - /*\ + /* \ * Raphael.getRGB [ method ] ** @@ -48292,7 +48071,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString}; }, R); - /*\ + /* \ * Raphael.hsb [ method ] ** @@ -48306,7 +48085,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.hsb = cacher(function (h, s, b) { return R.hsb2rgb(h, s, b).hex; }); - /*\ + /* \ * Raphael.hsl [ method ] ** @@ -48320,7 +48099,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.hsl = cacher(function (h, s, l) { return R.hsl2rgb(h, s, l).hex; }); - /*\ + /* \ * Raphael.rgb [ method ] ** @@ -48332,10 +48111,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (string) hex representation of the colour. \*/ R.rgb = cacher(function (r, g, b) { - function round(x) { return (x + 0.5) | 0; } + function round (x) { return (x + 0.5) | 0; } return "#" + (16777216 | round(b) | (round(g) << 8) | (round(r) << 16)).toString(16).slice(1); }); - /*\ + /* \ * Raphael.getColor [ method ] ** @@ -48355,7 +48134,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return rgb.hex; }; - /*\ + /* \ * Raphael.getColor.reset [ method ] ** @@ -48366,7 +48145,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; // http://schepers.cc/getting-to-the-point - function catmullRom2bezier(crp, z) { + function catmullRom2bezier (crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [ @@ -48395,7 +48174,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, - (p[1].y + 6*p[2].y - p[3].y) / 6, + (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y ]); @@ -48403,7 +48182,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return d; } - /*\ + /* \ * Raphael.parsePathString [ method ] ** @@ -48442,10 +48221,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (name == "r") { data.push([b][concat](params)); - } else while (params.length >= paramCounts[name]) { - data.push([b][concat](params.splice(0, paramCounts[name]))); - if (!paramCounts[name]) { - break; + } else { + while (params.length >= paramCounts[name]) { + data.push([b][concat](params.splice(0, paramCounts[name]))); + if (!paramCounts[name]) { + break; + } } } }); @@ -48454,7 +48235,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I pth.arr = pathClone(data); return data; }; - /*\ + /* \ * Raphael.parseTransformString [ method ] ** @@ -48498,14 +48279,16 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; } setTimeout(function () { - for (var key in p) if (p[has](key) && key != ps) { - p[key].sleep--; - !p[key].sleep && delete p[key]; + for (var key in p) { + if (p[has](key) && key != ps) { + p[key].sleep--; + !p[key].sleep && delete p[key]; + } } }); return p[ps]; }; - /*\ + /* \ * Raphael.findDotsAtSegment [ method ] ** @@ -48573,7 +48356,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I alpha: alpha }; }; - /*\ + /* \ * Raphael.bezierBBox [ method ] ** @@ -48617,7 +48400,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I height: bbox.max.y - bbox.min.y }; }; - /*\ + /* \ * Raphael.isPointInsideBBox [ method ] ** @@ -48633,7 +48416,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.isPointInsideBBox = function (bbox, x, y) { return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2; }; - /*\ + /* \ * Raphael.isBBoxIntersect [ method ] ** @@ -48658,20 +48441,20 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; - function base3(t, p1, p2, p3, p4) { + function base3 (t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } - function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { + function bezlen (x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z == null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2, n = 12, - Tvalues = [-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816], - Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472], + Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816], + Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472], sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2, @@ -48682,7 +48465,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return z2 * sum; } - function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { + function getTatLen (x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } @@ -48699,7 +48482,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return t2; } - function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { + function intersect (x1, y1, x2, y2, x3, y3, x4, y4) { if ( mmax(x1, x2) < mmin(x3, x4) || mmin(x1, x2) > mmax(x3, x4) || @@ -48733,13 +48516,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return {x: px, y: py}; } - function inter(bez1, bez2) { + function inter (bez1, bez2) { return interHelper(bez1, bez2); } - function interCount(bez1, bez2) { + function interCount (bez1, bez2) { return interHelper(bez1, bez2, 1); } - function interHelper(bez1, bez2, justCount) { + function interHelper (bez1, bez2, justCount) { var bbox1 = R.bezierBBox(bez1), bbox2 = R.bezierBBox(bez2); if (!R.isBBoxIntersect(bbox1, bbox2)) { @@ -48794,7 +48577,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return res; } - /*\ + /* \ * Raphael.pathIntersection [ method ] ** @@ -48824,7 +48607,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.pathIntersectionNumber = function (path1, path2) { return interPathHelper(path1, path2, 1); }; - function interPathHelper(path1, path2, justCount) { + function interPathHelper (path1, path2, justCount) { path1 = R._path2curve(path1); path2 = R._path2curve(path2); var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2, @@ -48877,7 +48660,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return res; } - /*\ + /* \ * Raphael.isPointInsidePath [ method ] ** @@ -48900,7 +48683,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve("raphael.log", null, "Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object", methodname); }; }; - /*\ + /* \ * Raphael.pathBBox [ method ] ** @@ -49245,14 +49028,14 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4][concat](res); - } else { - res = [m2, m3, m4][concat](res).join()[split](","); - var newres = []; - for (var i = 0, ii = res.length; i < ii; i++) { - newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; - } - return newres; } + res = [m2, m3, m4][concat](res).join()[split](","); + var newres = []; + for (var i = 0, ii = res.length; i < ii; i++) { + newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; + } + return newres; + }, findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; @@ -49314,7 +49097,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, processPath = function (path, d, pcom) { - var nx, ny, tq = {T:1, Q:1}; + var nx, ny, tq = {T: 1, Q: 1}; if (!path) { return ["C", d.x, d.y, d.x, d.y, d.x, d.y]; } @@ -49331,8 +49114,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (pcom == "C" || pcom == "S") { // In "S" case we have to take into account, if the previous command is C/S. nx = d.x * 2 - d.bx; // And reflect the previous ny = d.y * 2 - d.by; // command's control point relative to the current point. - } - else { // or some else or nothing + } else { // or some else or nothing nx = d.x; ny = d.y; } @@ -49342,8 +49124,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (pcom == "Q" || pcom == "T") { // In "T" case we have to take into account, if the previous command is Q/T. d.qx = d.x * 2 - d.qx; // And make a reflection similar d.qy = d.y * 2 - d.qy; // to case "S". - } - else { // or something else or nothing + } else { // or something else or nothing d.qx = d.x; d.qy = d.y; } @@ -49374,8 +49155,8 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I pp[i].shift(); var pi = pp[i]; while (pi.length) { - pcoms1[i]="A"; // if created multiple C:s, their original seg is saved - p2 && (pcoms2[i]="A"); // the same as above + pcoms1[i] = "A"; // if created multiple C:s, their original seg is saved + p2 && (pcoms2[i] = "A"); // the same as above pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6))); } pp.splice(i, 1); @@ -49402,7 +49183,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (pfirst != "C") // C is not saved yet, because it may be result of conversion { pcoms1[i] = pfirst; // Save current path command - i && ( pcom = pcoms1[i-1]); // Get previous path command pcom + i && ( pcom = pcoms1[i - 1]); // Get previous path command pcom } p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath @@ -49414,14 +49195,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (p2) { // the same procedures is done to p2 p2[i] && (pfirst = p2[i][0]); - if (pfirst != "C") - { + if (pfirst != "C") { pcoms2[i] = pfirst; - i && (pcom = pcoms2[i-1]); + i && (pcom = pcoms2[i - 1]); } p2[i] = processPath(p2[i], attrs2, pcom); - if (pcoms2[i]!="A" && pfirst=="C") pcoms2[i]="C"; + if (pcoms2[i] != "A" && pfirst == "C") pcoms2[i] = "C"; fixArc(p2, i); } @@ -49525,7 +49305,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I el2.prev = el; el.next = el2; }, - /*\ + /* \ * Raphael.toMatrix [ method ] ** @@ -49550,7 +49330,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I extractTransform(el, transform); return el.matrix; }, - /*\ + /* \ * Raphael.transformPath [ method ] ** @@ -49641,7 +49421,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } } - /*\ + /* \ * Element.matrix [ property (object) ] ** @@ -49669,16 +49449,16 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I case "m": return [l, 1, 0, 0, 1, 0, 0]; case "r": if (item.length == 4) { return [l, 0, item[2], item[3]]; - } else { - return [l, 0]; } + return [l, 0]; + case "s": if (item.length == 5) { return [l, 1, 1, item[3], item[4]]; } else if (item.length == 3) { - return [l, 1, 1]; - } else { + return [l, 1, 1]; + } return [l, 1]; - } + } }, equaliseTransform = R._equaliseTransform = function (t1, t2) { @@ -49724,13 +49504,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I width: container.style.pixelWidth || container.offsetWidth, height: container.style.pixelHeight || container.offsetHeight }; - } else { - return { - container: container, - width: y, - height: w - }; } + return { + container: container, + width: y, + height: w + }; + } return { container: 1, @@ -49740,7 +49520,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I height: h }; }; - /*\ + /* \ * Raphael.pathToRelative [ method ] ** @@ -49753,7 +49533,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ R.pathToRelative = pathToRelative; R._engine = {}; - /*\ + /* \ * Raphael.path2curve [ method ] ** @@ -49765,7 +49545,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (array) array of segments. \*/ R.path2curve = path2curve; - /*\ + /* \ * Raphael.matrix [ method ] ** @@ -49784,7 +49564,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.matrix = function (a, b, c, d, e, f) { return new Matrix(a, b, c, d, e, f); }; - function Matrix(a, b, c, d, e, f) { + function Matrix (a, b, c, d, e, f) { if (a != null) { this.a = +a; this.b = +b; @@ -49802,7 +49582,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } } (function (matrixproto) { - /*\ + /* \ * Matrix.add [ method ] ** @@ -49843,7 +49623,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.e = out[0][2]; this.f = out[1][2]; }; - /*\ + /* \ * Matrix.invert [ method ] ** @@ -49855,7 +49635,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I x = me.a * me.d - me.b * me.c; return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x); }; - /*\ + /* \ * Matrix.clone [ method ] ** @@ -49865,7 +49645,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I matrixproto.clone = function () { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; - /*\ + /* \ * Matrix.translate [ method ] ** @@ -49877,7 +49657,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I matrixproto.translate = function (x, y) { this.add(1, 0, 0, 1, x, y); }; - /*\ + /* \ * Matrix.scale [ method ] ** @@ -49894,7 +49674,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.add(x, 0, 0, y, 0, 0); (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy); }; - /*\ + /* \ * Matrix.rotate [ method ] ** @@ -49913,7 +49693,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.add(cos, sin, -sin, cos, x, y); this.add(1, 0, 0, 1, -x, -y); }; - /*\ + /* \ * Matrix.x [ method ] ** @@ -49926,7 +49706,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I matrixproto.x = function (x, y) { return x * this.a + y * this.c + this.e; }; - /*\ + /* \ * Matrix.y [ method ] ** @@ -49944,7 +49724,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; matrixproto.toString = function () { return R.svg ? - "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : + "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join(); }; matrixproto.toFilter = function () { @@ -49955,15 +49735,15 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I matrixproto.offset = function () { return [this.e.toFixed(4), this.f.toFixed(4)]; }; - function norm(a) { + function norm (a) { return a[0] * a[0] + a[1] * a[1]; } - function normalize(a) { + function normalize (a) { var mag = math.sqrt(norm(a)); a[0] && (a[0] /= mag); a[1] && (a[1] /= mag); } - /*\ + /* \ * Matrix.split [ method ] ** @@ -50012,7 +49792,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I out.noRotation = !+out.shear.toFixed(9) && !out.rotate; return out; }; - /*\ + /* \ * Matrix.toTransformString [ method ] ** @@ -50028,9 +49808,9 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) + (s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) + (s.rotate ? "r" + [s.rotate, 0, 0] : E); - } else { - return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; } + return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; + }; })(Matrix.prototype); @@ -50087,8 +49867,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return function () { obj.removeEventListener(type, f, false); - if (supportsTouch && touchMap[type]) - obj.removeEventListener(touchMap[type], _f, false); + if (supportsTouch && touchMap[type]) {obj.removeEventListener(touchMap[type], _f, false);} return true; }; @@ -50166,7 +49945,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } drag = []; }, - /*\ + /* \ * Raphael.el [ property (object) ] ** @@ -50181,7 +49960,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I | paper.circle(100, 100, 20).red(); \*/ elproto = R.el = {}; - /*\ + /* \ * Element.click [ method ] ** @@ -50190,7 +49969,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unclick [ method ] ** @@ -50200,7 +49979,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.dblclick [ method ] ** @@ -50209,7 +49988,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.undblclick [ method ] ** @@ -50219,7 +49998,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mousedown [ method ] ** @@ -50228,7 +50007,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmousedown [ method ] ** @@ -50238,7 +50017,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mousemove [ method ] ** @@ -50247,7 +50026,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmousemove [ method ] ** @@ -50257,7 +50036,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mouseout [ method ] ** @@ -50266,7 +50045,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseout [ method ] ** @@ -50276,7 +50055,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mouseover [ method ] ** @@ -50285,7 +50064,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseover [ method ] ** @@ -50295,7 +50074,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.mouseup [ method ] ** @@ -50304,7 +50083,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseup [ method ] ** @@ -50314,7 +50093,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.touchstart [ method ] ** @@ -50323,7 +50102,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchstart [ method ] ** @@ -50333,7 +50112,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.touchmove [ method ] ** @@ -50342,7 +50121,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchmove [ method ] ** @@ -50352,7 +50131,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.touchend [ method ] ** @@ -50361,7 +50140,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchend [ method ] ** @@ -50371,7 +50150,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ - /*\ + /* \ * Element.touchcancel [ method ] ** @@ -50380,7 +50159,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchcancel [ method ] ** @@ -50401,7 +50180,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R["un" + eventName] = elproto["un" + eventName] = function (fn) { var events = this.events || [], l = events.length; - while (l--){ + while (l--) { if (events[l].name == eventName && (R.is(fn, "undefined") || events[l].f == fn)) { events[l].unbind(); events.splice(l, 1); @@ -50413,7 +50192,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I })(events[i]); } - /*\ + /* \ * Element.data [ method ] ** @@ -50445,8 +50224,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (arguments.length == 1) { if (R.is(key, "object")) { - for (var i in key) if (key[has](i)) { - this.data(i, key[i]); + for (var i in key) { + if (key[has](i)) { + this.data(i, key[i]); + } } return this; } @@ -50458,11 +50239,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return this; }; - elproto.datum = function(){ + elproto.datum = function () { return arguments.length == 0 ? this._bindData : ((this._bindData = arguments[0]), this); }; - /*\ + /* \ * Element.removeData [ method ] ** @@ -50480,7 +50261,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Element.getData [ method ] ** @@ -50490,7 +50271,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I elproto.getData = function () { return clone(eldata[this.id] || {}); }; - /*\ + /* \ * Element.hover [ method ] ** @@ -50505,7 +50286,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I elproto.hover = function (f_in, f_out, scope_in, scope_out) { return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in); }; - /*\ + /* \ * Element.unhover [ method ] ** @@ -50519,7 +50300,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return this.unmouseover(f_in).unmouseout(f_out); }; var draggable = []; - /*\ + /* \ * Element.drag [ method ] ** @@ -50550,7 +50331,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) @Element \*/ elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) { - function start(e) { + function start (e) { (e.originalEvent || e).preventDefault(); var x = e.clientX, y = e.clientY, @@ -50583,7 +50364,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.mousedown(start); return this; }; - /*\ + /* \ * Element.onDragOver [ method ] ** @@ -50594,7 +50375,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I elproto.onDragOver = function (f) { f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id); }; - /*\ + /* \ * Element.undrag [ method ] ** @@ -50602,15 +50383,17 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ elproto.undrag = function () { var i = draggable.length; - while (i--) if (draggable[i].el == this) { - this.unmousedown(draggable[i].start); - draggable.splice(i, 1); - eve.unbind("raphael.drag.*." + this.id); + while (i--) { + if (draggable[i].el == this) { + this.unmousedown(draggable[i].start); + draggable.splice(i, 1); + eve.unbind("raphael.drag.*." + this.id); + } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); drag = []; }; - /*\ + /* \ * Paper.circle [ method ] ** @@ -50631,7 +50414,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.rect [ method ] * @@ -50657,7 +50440,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.ellipse [ method ] ** @@ -50679,7 +50462,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.path [ method ] ** @@ -50717,7 +50500,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.image [ method ] ** @@ -50740,7 +50523,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.text [ method ] ** @@ -50761,7 +50544,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.set [ method ] ** @@ -50786,7 +50569,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I out["type"] = "set"; return out; }; - /*\ + /* \ * Paper.setStart [ method ] ** @@ -50803,7 +50586,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I paperproto.setStart = function (set) { this.__set__ = set || this.set(); }; - /*\ + /* \ * Paper.setFinish [ method ] ** @@ -50816,7 +50599,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I delete this.__set__; return out; }; - /*\ + /* \ * Paper.getSize [ method ] ** @@ -50831,7 +50614,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I height: container.offsetHeight }; }; - /*\ + /* \ * Paper.setSize [ method ] ** @@ -50845,7 +50628,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I paperproto.setSize = function (width, height) { return R._engine.setSize.call(this, width, height); }; - /*\ + /* \ * Paper.setViewBox [ method ] ** @@ -50863,20 +50646,20 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I paperproto.setViewBox = function (x, y, w, h, fit) { return R._engine.setViewBox.call(this, x, y, w, h, fit); }; - /*\ + /* \ * Paper.top [ property ] ** * Points to the topmost element on the paper \*/ - /*\ + /* \ * Paper.bottom [ property ] ** * Points to the bottom element on the paper \*/ paperproto.top = paperproto.bottom = null; - /*\ + /* \ * Paper.raphael [ property ] ** @@ -50896,7 +50679,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I x: left }; }; - /*\ + /* \ * Paper.getElementByPoint [ method ] ** @@ -50936,7 +50719,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return target; }; - /*\ + /* \ * Paper.getElementsByBBox [ method ] ** @@ -50957,7 +50740,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return set; }; - /*\ + /* \ * Paper.getById [ method ] ** @@ -50978,7 +50761,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return null; }; - /*\ + /* \ * Paper.forEach [ method ] ** @@ -51006,7 +50789,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Paper.getElementsByPoint [ method ] ** @@ -51027,13 +50810,13 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); return set; }; - function x_y() { + function x_y () { return this.x + S + this.y; } - function x_y_w_h() { + function x_y_w_h () { return this.x + S + this.y + S + this.width + " \xd7 " + this.height; } - /*\ + /* \ * Element.isPointInside [ method ] ** @@ -51047,12 +50830,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I \*/ elproto.isPointInside = function (x, y) { var rp = this.realPath = getPath[this.type](this); - if (this.attr('transform') && this.attr('transform').length) { - rp = R.transformPath(rp, this.attr('transform')); + if (this.attr("transform") && this.attr("transform").length) { + rp = R.transformPath(rp, this.attr("transform")); } return R.isPointInsidePath(rp, x, y); }; - /*\ + /* \ * Element.getBBox [ method ] ** @@ -51096,7 +50879,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return _.bbox; }; - /*\ + /* \ * Element.clone [ method ] ** @@ -51111,7 +50894,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Element.glow [ method ] ** @@ -51166,9 +50949,9 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) { if (length == null) { return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y); - } else { - return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); } + return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); + }, getLengthFactory = function (istotal, subpath) { return function (path, length, onlystart) { @@ -51214,7 +50997,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var getTotalLength = getLengthFactory(1), getPointAtLength = getLengthFactory(), getSubpathsAtLength = getLengthFactory(0, 1); - /*\ + /* \ * Raphael.getTotalLength [ method ] ** @@ -51227,7 +51010,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (number) length. \*/ R.getTotalLength = getTotalLength; - /*\ + /* \ * Raphael.getPointAtLength [ method ] ** @@ -51246,7 +51029,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I o } \*/ R.getPointAtLength = getPointAtLength; - /*\ + /* \ * Raphael.getSubpath [ method ] ** @@ -51267,7 +51050,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var a = getSubpathsAtLength(path, to, 1); return from ? getSubpathsAtLength(a, from).end : a; }; - /*\ + /* \ * Element.getTotalLength [ method ] ** @@ -51286,7 +51069,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return getTotalLength(path); }; - /*\ + /* \ * Element.getPointAtLength [ method ] ** @@ -51311,7 +51094,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return getPointAtLength(path, length); }; - /*\ + /* \ * Element.getPath [ method ] ** @@ -51333,7 +51116,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return path; }; - /*\ + /* \ * Element.getSubpath [ method ] ** @@ -51354,7 +51137,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return R.getSubpath(path, from, to); }; - /*\ + /* \ * Raphael.easing_formulas [ property ] ** @@ -51477,65 +51260,67 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (time < ms) { var pos = easing(time / ms); - for (var attr in from) if (from[has](attr)) { - switch (availableAnimAttrs[attr]) { - case nu: - now = +from[attr] + pos * ms * diff[attr]; - break; - case "colour": - now = "rgb(" + [ + for (var attr in from) { + if (from[has](attr)) { + switch (availableAnimAttrs[attr]) { + case nu: + now = +from[attr] + pos * ms * diff[attr]; + break; + case "colour": + now = "rgb(" + [ upto255(round(from[attr].r + pos * ms * diff[attr].r)), upto255(round(from[attr].g + pos * ms * diff[attr].g)), upto255(round(from[attr].b + pos * ms * diff[attr].b)) ].join(",") + ")"; - break; - case "path": - now = []; - for (var i = 0, ii = from[attr].length; i < ii; i++) { - now[i] = [from[attr][i][0]]; - for (var j = 1, jj = from[attr][i].length; j < jj; j++) { - now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j]; - } - now[i] = now[i].join(S); - } - now = now.join(S); - break; - case "transform": - if (diff[attr].real) { + break; + case "path": now = []; - for (i = 0, ii = from[attr].length; i < ii; i++) { + for (var i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; - for (j = 1, jj = from[attr][i].length; j < jj; j++) { - now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; + for (var j = 1, jj = from[attr][i].length; j < jj; j++) { + now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j]; } + now[i] = now[i].join(S); } - } else { - var get = function (i) { - return +from[attr][i] + pos * ms * diff[attr][i]; - }; - // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; - now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; - } - break; - case "csv": - if (attr == "clip-rect") { + now = now.join(S); + break; + case "transform": + if (diff[attr].real) { + now = []; + for (i = 0, ii = from[attr].length; i < ii; i++) { + now[i] = [from[attr][i][0]]; + for (j = 1, jj = from[attr][i].length; j < jj; j++) { + now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; + } + } + } else { + var get = function (i) { + return +from[attr][i] + pos * ms * diff[attr][i]; + }; + // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; + now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; + } + break; + case "csv": + if (attr == "clip-rect") { + now = []; + i = 4; + while (i--) { + now[i] = +from[attr][i] + pos * ms * diff[attr][i]; + } + } + break; + default: + var from2 = [][concat](from[attr]); now = []; - i = 4; + i = that.paper.customAttributes[attr].length; while (i--) { - now[i] = +from[attr][i] + pos * ms * diff[attr][i]; + now[i] = +from2[i] + pos * ms * diff[attr][i]; } - } - break; - default: - var from2 = [][concat](from[attr]); - now = []; - i = that.paper.customAttributes[attr].length; - while (i--) { - now[i] = +from2[i] + pos * ms * diff[attr][i]; - } - break; + break; + } + set[attr] = now; } - set[attr] = now; } that.attr(set); (function (id, that, anim) { @@ -51544,8 +51329,8 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); })(that.id, that, e.anim); } else { - (function(f, el, a) { - setTimeout(function() { + (function (f, el, a) { + setTimeout(function () { eve("raphael.anim.frame." + el.id, el, a); eve("raphael.anim.finish." + el.id, el, a); R.is(f, "function") && f.call(el); @@ -51554,8 +51339,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I that.attr(to); animationElements.splice(l--, 1); if (e.repeat > 1 && !e.next) { - for (key in to) if (to[has](key)) { - init[key] = e.totalOrigin[key]; + for (key in to) { + if (to[has](key)) { + init[key] = e.totalOrigin[key]; + } } e.el.attr(init); runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1); @@ -51570,7 +51357,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I upto255 = function (color) { return color > 255 ? 255 : color < 0 ? 0 : color; }; - /*\ + /* \ * Element.animateWith [ method ] ** @@ -51613,21 +51400,21 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I // status = element.status(anim); // return this.animate(a).status(a, status * anim.ms / a.ms); }; - function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) { + function CubicBezierAtTime (t, p1x, p1y, p2x, p2y, duration) { var cx = 3 * p1x, bx = 3 * (p2x - p1x) - cx, ax = 1 - cx - bx, cy = 3 * p1y, by = 3 * (p2y - p1y) - cy, ay = 1 - cy - by; - function sampleCurveX(t) { + function sampleCurveX (t) { return ((ax * t + bx) * t + cx) * t; } - function solve(x, epsilon) { + function solve (x, epsilon) { var t = solveCurveX(x, epsilon); return ((ay * t + by) * t + cy) * t; } - function solveCurveX(x, epsilon) { + function solveCurveX (x, epsilon) { var t0, t1, t2, x2, d2, i; for(t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; @@ -51669,15 +51456,17 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id); return this; }; - function Animation(anim, ms) { + function Animation (anim, ms) { var percents = [], newAnim = {}; this.ms = ms; this.times = 1; if (anim) { - for (var attr in anim) if (anim[has](attr)) { - newAnim[toFloat(attr)] = anim[attr]; - percents.push(toFloat(attr)); + for (var attr in anim) { + if (anim[has](attr)) { + newAnim[toFloat(attr)] = anim[attr]; + percents.push(toFloat(attr)); + } } percents.sort(sortByNumber); } @@ -51685,7 +51474,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.top = percents[percents.length - 1]; this.percents = percents; } - /*\ + /* \ * Animation.delay [ method ] ** @@ -51706,7 +51495,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I a.del = +delay || 0; return a; }; - /*\ + /* \ * Animation.repeat [ method ] ** @@ -51724,7 +51513,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I a.times = math.floor(mmax(times, 0)) || 1; return a; }; - function runAnimation(anim, element, percent, status, totalOrigin, times) { + function runAnimation (anim, element, percent, status, totalOrigin, times) { percent = toFloat(percent); var params, isInAnim, @@ -51770,76 +51559,77 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return; } if (!isInAnim) { - for (var attr in params) if (params[has](attr)) { - if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) { - from[attr] = element.attr(attr); - (from[attr] == null) && (from[attr] = availableAttrs[attr]); - to[attr] = params[attr]; - switch (availableAnimAttrs[attr]) { - case nu: - diff[attr] = (to[attr] - from[attr]) / ms; - break; - case "colour": - from[attr] = R.getRGB(from[attr]); - var toColour = R.getRGB(to[attr]); - diff[attr] = { - r: (toColour.r - from[attr].r) / ms, - g: (toColour.g - from[attr].g) / ms, - b: (toColour.b - from[attr].b) / ms - }; - break; - case "path": - var pathes = path2curve(from[attr], to[attr]), - toPath = pathes[1]; - from[attr] = pathes[0]; - diff[attr] = []; - for (i = 0, ii = from[attr].length; i < ii; i++) { - diff[attr][i] = [0]; - for (var j = 1, jj = from[attr][i].length; j < jj; j++) { - diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; - } - } - break; - case "transform": - var _ = element._, - eq = equaliseTransform(_[attr], to[attr]); - if (eq) { - from[attr] = eq.from; - to[attr] = eq.to; + for (var attr in params) { + if (params[has](attr)) { + if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) { + from[attr] = element.attr(attr); + (from[attr] == null) && (from[attr] = availableAttrs[attr]); + to[attr] = params[attr]; + switch (availableAnimAttrs[attr]) { + case nu: + diff[attr] = (to[attr] - from[attr]) / ms; + break; + case "colour": + from[attr] = R.getRGB(from[attr]); + var toColour = R.getRGB(to[attr]); + diff[attr] = { + r: (toColour.r - from[attr].r) / ms, + g: (toColour.g - from[attr].g) / ms, + b: (toColour.b - from[attr].b) / ms + }; + break; + case "path": + var pathes = path2curve(from[attr], to[attr]), + toPath = pathes[1]; + from[attr] = pathes[0]; diff[attr] = []; - diff[attr].real = true; for (i = 0, ii = from[attr].length; i < ii; i++) { - diff[attr][i] = [from[attr][i][0]]; - for (j = 1, jj = from[attr][i].length; j < jj; j++) { - diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; + diff[attr][i] = [0]; + for (var j = 1, jj = from[attr][i].length; j < jj; j++) { + diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; } } - } else { - var m = (element.matrix || new Matrix), - to2 = { - _: {transform: _.transform}, - getBBox: function () { - return element.getBBox(1); + break; + case "transform": + var _ = element._, + eq = equaliseTransform(_[attr], to[attr]); + if (eq) { + from[attr] = eq.from; + to[attr] = eq.to; + diff[attr] = []; + diff[attr].real = true; + for (i = 0, ii = from[attr].length; i < ii; i++) { + diff[attr][i] = [from[attr][i][0]]; + for (j = 1, jj = from[attr][i].length; j < jj; j++) { + diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; } - }; - from[attr] = [ - m.a, - m.b, - m.c, - m.d, - m.e, - m.f - ]; - extractTransform(to2, to[attr]); - to[attr] = to2._.transform; - diff[attr] = [ - (to2.matrix.a - m.a) / ms, - (to2.matrix.b - m.b) / ms, - (to2.matrix.c - m.c) / ms, - (to2.matrix.d - m.d) / ms, - (to2.matrix.e - m.e) / ms, - (to2.matrix.f - m.f) / ms - ]; + } + } else { + var m = (element.matrix || new Matrix), + to2 = { + _: {transform: _.transform}, + getBBox: function () { + return element.getBBox(1); + } + }; + from[attr] = [ + m.a, + m.b, + m.c, + m.d, + m.e, + m.f + ]; + extractTransform(to2, to[attr]); + to[attr] = to2._.transform; + diff[attr] = [ + (to2.matrix.a - m.a) / ms, + (to2.matrix.b - m.b) / ms, + (to2.matrix.c - m.c) / ms, + (to2.matrix.d - m.d) / ms, + (to2.matrix.e - m.e) / ms, + (to2.matrix.f - m.f) / ms + ]; // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy]; // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }}; // extractTransform(to2, to[attr]); @@ -51850,30 +51640,31 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I // (to2._.dx - _.dx) / ms, // (to2._.dy - _.dy) / ms // ]; - } - break; - case "csv": - var values = Str(params[attr])[split](separator), - from2 = Str(from[attr])[split](separator); - if (attr == "clip-rect") { - from[attr] = from2; + } + break; + case "csv": + var values = Str(params[attr])[split](separator), + from2 = Str(from[attr])[split](separator); + if (attr == "clip-rect") { + from[attr] = from2; + diff[attr] = []; + i = from2.length; + while (i--) { + diff[attr][i] = (values[i] - from[attr][i]) / ms; + } + } + to[attr] = values; + break; + default: + values = [][concat](params[attr]); + from2 = [][concat](from[attr]); diff[attr] = []; - i = from2.length; + i = element.paper.customAttributes[attr].length; while (i--) { - diff[attr][i] = (values[i] - from[attr][i]) / ms; + diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms; } - } - to[attr] = values; - break; - default: - values = [][concat](params[attr]); - from2 = [][concat](from[attr]); - diff[attr] = []; - i = element.paper.customAttributes[attr].length; - while (i--) { - diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms; - } - break; + break; + } } } } @@ -51930,7 +51721,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } eve("raphael.anim.start." + element.id, element, anim); } - /*\ + /* \ * Raphael.animation [ method ] ** @@ -51959,33 +51750,35 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var p = {}, json, attr; - for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { - json = true; - p[attr] = params[attr]; + for (attr in params) { + if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { + json = true; + p[attr] = params[attr]; + } } if (!json) { // if percent-like syntax is used and end-of-all animation callback used - if(callback){ + if(callback) { // find the last one var lastKey = 0; - for(var i in params){ + for(var i in params) { var percent = toInt(i); - if(params[has](i) && percent > lastKey){ + if(params[has](i) && percent > lastKey) { lastKey = percent; } } - lastKey += '%'; + lastKey += "%"; // if already defined callback in the last keyframe, skip !params[lastKey].callback && (params[lastKey].callback = callback); } return new Animation(params, ms); - } else { - easing && (p.easing = easing); - callback && (p.callback = callback); - return new Animation({100: p}, ms); } + easing && (p.easing = easing); + callback && (p.callback = callback); + return new Animation({100: p}, ms); + }; - /*\ + /* \ * Element.animate [ method ] ** @@ -52012,7 +51805,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I runAnimation(anim, element, anim.percents[0], null, element.attr()); return element; }; - /*\ + /* \ * Element.setTime [ method ] ** @@ -52034,7 +51827,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Element.status [ method ] ** @@ -52063,27 +51856,27 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (value != null) { runAnimation(anim, this, -1, mmin(value, 1)); return this; - } else { - len = animationElements.length; - for (; i < len; i++) { - e = animationElements[i]; - if (e.el.id == this.id && (!anim || e.anim == anim)) { - if (anim) { - return e.status; - } - out.push({ - anim: e.anim, - status: e.status - }); + } + len = animationElements.length; + for (; i < len; i++) { + e = animationElements[i]; + if (e.el.id == this.id && (!anim || e.anim == anim)) { + if (anim) { + return e.status; } + out.push({ + anim: e.anim, + status: e.status + }); } - if (anim) { - return 0; - } - return out; } + if (anim) { + return 0; + } + return out; + }; - /*\ + /* \ * Element.pause [ method ] ** @@ -52096,14 +51889,16 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) original element \*/ elproto.pause = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) { - animationElements[i].paused = true; + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) { + animationElements[i].paused = true; + } } } return this; }; - /*\ + /* \ * Element.resume [ method ] ** @@ -52116,16 +51911,18 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) original element \*/ elproto.resume = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - var e = animationElements[i]; - if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { - delete e.paused; - this.status(e.anim, e.status); + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + var e = animationElements[i]; + if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { + delete e.paused; + this.status(e.anim, e.status); + } } } return this; }; - /*\ + /* \ * Element.stop [ method ] ** @@ -52138,16 +51935,20 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (object) original element \*/ elproto.stop = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) { - animationElements.splice(i--, 1); + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) { + animationElements.splice(i--, 1); + } } } return this; }; - function stopAnimation(paper) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.paper == paper) { - animationElements.splice(i--, 1); + function stopAnimation (paper) { + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.paper == paper) { + animationElements.splice(i--, 1); + } } } eve.on("raphael.remove", stopAnimation); @@ -52171,7 +51972,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } }, setproto = Set.prototype; - /*\ + /* \ * Set.push [ method ] ** @@ -52191,7 +51992,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Set.pop [ method ] ** @@ -52202,7 +52003,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.length && delete this[this.length--]; return this.items.pop(); }; - /*\ + /* \ * Set.forEach [ method ] ** @@ -52224,15 +52025,17 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - for (var method in elproto) if (elproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname][apply](el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname][apply](el, arg); + }); + }; + })(method); + } } setproto.attr = function (name, value) { if (name && R.is(name, array) && R.is(name[0], "object")) { @@ -52246,7 +52049,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return this; }; - /*\ + /* \ * Set.clear [ method ] ** @@ -52257,7 +52060,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.pop(); } }; - /*\ + /* \ * Set.splice [ method ] ** @@ -52296,7 +52099,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return new Set(todel); }; - /*\ + /* \ * Set.exclude [ method ] ** @@ -52308,9 +52111,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I = (boolean) `true` if object was found & removed from the set \*/ setproto.exclude = function (el) { - for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) { - this.splice(i, 1); - return true; + for (var i = 0, ii = this.length; i < ii; i++) { + if (this[i] == el) { + this.splice(i, 1); + return true; + } } }; setproto.animate = function (params, ms, easing, callback) { @@ -52347,12 +52152,14 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I y = [], x2 = [], y2 = []; - for (var i = this.items.length; i--;) if (!this.items[i].removed) { - var box = this.items[i].getBBox(); - x.push(box.x); - y.push(box.y); - x2.push(box.x + box.width); - y2.push(box.y + box.height); + for (var i = this.items.length; i--;) { + if (!this.items[i].removed) { + var box = this.items[i].getBBox(); + x.push(box.x); + y.push(box.y); + x2.push(box.x + box.width); + y2.push(box.y + box.height); + } } x = mmin[apply](0, x); y = mmin[apply](0, y); @@ -52378,12 +52185,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return "Rapha\xebl\u2018s set"; }; - setproto.glow = function(glowConfig) { + setproto.glow = function (glowConfig) { var ret = this.paper.set(); - this.forEach(function(shape, index){ + this.forEach(function (shape, index) { var g = shape.glow(glowConfig); - if(g != null){ - g.forEach(function(shape2, index2){ + if(g != null) { + g.forEach(function (shape2, index2) { ret.push(shape2); }); } @@ -52392,7 +52199,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; - /*\ + /* \ * Set.isPointInside [ method ] ** @@ -52415,7 +52222,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return isPointInside; }; - /*\ + /* \ * Raphael.registerFont [ method ] ** @@ -52441,8 +52248,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I glyphs: {} }, family = font.face["font-family"]; - for (var prop in font.face) if (font.face[has](prop)) { - fontcopy.face[prop] = font.face[prop]; + for (var prop in font.face) { + if (font.face[has](prop)) { + fontcopy.face[prop] = font.face[prop]; + } } if (this.fonts[family]) { this.fonts[family].push(fontcopy); @@ -52451,25 +52260,29 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (!font.svg) { fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10); - for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) { - var path = font.glyphs[glyph]; - fontcopy.glyphs[glyph] = { - w: path.w, - k: {}, - d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) { - return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M"; - }) + "z" - }; - if (path.k) { - for (var k in path.k) if (path[has](k)) { - fontcopy.glyphs[glyph].k[k] = path.k[k]; + for (var glyph in font.glyphs) { + if (font.glyphs[has](glyph)) { + var path = font.glyphs[glyph]; + fontcopy.glyphs[glyph] = { + w: path.w, + k: {}, + d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) { + return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M"; + }) + "z" + }; + if (path.k) { + for (var k in path.k) { + if (path[has](k)) { + fontcopy.glyphs[glyph].k[k] = path.k[k]; + } + } } } } } return font; }; - /*\ + /* \ * Paper.getFont [ method ] ** @@ -52495,10 +52308,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var font = R.fonts[family]; if (!font) { var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i"); - for (var fontName in R.fonts) if (R.fonts[has](fontName)) { - if (name.test(fontName)) { - font = R.fonts[fontName]; - break; + for (var fontName in R.fonts) { + if (R.fonts[has](fontName)) { + if (name.test(fontName)) { + font = R.fonts[fontName]; + break; + } } } } @@ -52513,7 +52328,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } return thefont; }; - /*\ + /* \ * Paper.print [ method ] ** @@ -52574,7 +52389,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); }; - /*\ + /* \ * Paper.add [ method ] ** @@ -52616,7 +52431,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return res; }; - /*\ + /* \ * Raphael.format [ method ] ** @@ -52642,7 +52457,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I })); return token || E; }; - /*\ + /* \ * Raphael.fullfill [ method ] ** @@ -52676,7 +52491,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (name in res) { res = res[name]; } - typeof res == "function" && isFunc && (res = res()); + typeof res === "function" && isFunc && (res = res()); } }); res = (res == null || res == obj ? all : res) + ""; @@ -52688,7 +52503,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); }; })(); - /*\ + /* \ * Raphael.ninja [ method ] ** @@ -52706,7 +52521,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael; return R; }; - /*\ + /* \ * Raphael.st [ property (object) ] ** @@ -52734,14 +52549,14 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html (function (doc, loaded, f) { - if (doc.readyState == null && doc.addEventListener){ + if (doc.readyState == null && doc.addEventListener) { doc.addEventListener(loaded, f = function () { doc.removeEventListener(loaded, f, false); doc.readyState = "complete"; }, false); doc.readyState = "loading"; } - function isLoaded() { + function isLoaded () { (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload"); } isLoaded(); @@ -52762,7 +52577,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.svg", ["raphael.core"], function(raphael) { + define("raphael.svg", ["raphael.core"], function (raphael) { return factory(raphael); }); } else if (typeof exports === "object") { @@ -52770,7 +52585,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } else { factory(glob.Raphael); } -}(this, function(R) { +}(this, function (R) { if (R && !R.svg) { return; } @@ -52801,14 +52616,16 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; var $ = function (el, attr) { if (attr) { - if (typeof el == "string") { + if (typeof el === "string") { el = $(el); } - for (var key in attr) if (attr[has](key)) { - if (key.substring(0, 6) == "xlink:") { - el.setAttributeNS(xlink, key.substring(6), Str(attr[key])); - } else { - el.setAttribute(key, Str(attr[key])); + for (var key in attr) { + if (attr[has](key)) { + if (key.substring(0, 6) == "xlink:") { + el.setAttributeNS(xlink, key.substring(6), Str(attr[key])); + } else { + el.setAttribute(key, Str(attr[key])); + } } } } else { @@ -53040,9 +52857,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I delete o._.arrows[se + "Type"]; delete o._.arrows[se + "String"]; } - for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) { - var item = R._g.doc.getElementById(attr); - item && item.parentNode.removeChild(item); + for (attr in markerCounter) { + if (markerCounter[has](attr) && !markerCounter[attr]) { + var item = R._g.doc.getElementById(attr); + item && item.parentNode.removeChild(item); + } } } }, @@ -53069,8 +52888,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt; } $(o.node, {"stroke-dasharray": dashes.join(",")}); - } - else { + } else { $(o.node, {"stroke-dasharray": "none"}); } }, @@ -53356,10 +53174,12 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } } else { tspans = node.getElementsByTagName("tspan"); - for (i = 0, ii = tspans.length; i < ii; i++) if (i) { - $(tspans[i], {dy: fontSize * leading, x: a.x}); - } else { - $(tspans[0], {dy: 0}); + for (i = 0, ii = tspans.length; i < ii; i++) { + if (i) { + $(tspans[i], {dy: fontSize * leading, x: a.x}); + } else { + $(tspans[0], {dy: 0}); + } } } $(node, {x: a.x, y: a.y}); @@ -53371,14 +53191,14 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I getRealNode = function (node) { if (node.parentNode && node.parentNode.tagName.toLowerCase() === "a") { return node.parentNode; - } else { - return node; } + return node; + }, Element = function (node, svg) { var X = 0, Y = 0; - /*\ + /* \ * Element.node [ property (object) ] ** @@ -53393,7 +53213,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I | }; \*/ this[0] = this.node = node; - /*\ + /* \ * Element.raphael [ property (object) ] ** @@ -53406,7 +53226,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I | } \*/ node.raphael = true; - /*\ + /* \ * Element.id [ property (number) ] ** @@ -53417,7 +53237,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I node.raphaelid = this.id; this.matrix = R.matrix(); this.realPath = null; - /*\ + /* \ * Element.paper [ property (object) ] ** @@ -53441,7 +53261,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I dirty: 1 }; !svg.bottom && (svg.bottom = this); - /*\ + /* \ * Element.prev [ property (object) ] ** @@ -53450,7 +53270,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.prev = svg.top; svg.top && (svg.top.next = this); svg.top = this; - /*\ + /* \ * Element.next [ property (object) ] ** @@ -53475,7 +53295,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }); return p; }; - /*\ + /* \ * Element.rotate [ method ] ** @@ -53508,7 +53328,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.transform(this._.transform.concat([["r", deg, cx, cy]])); return this; }; - /*\ + /* \ * Element.scale [ method ] ** @@ -53544,7 +53364,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.transform(this._.transform.concat([["s", sx, sy, cx, cy]])); return this; }; - /*\ + /* \ * Element.translate [ method ] ** @@ -53568,7 +53388,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.transform(this._.transform.concat([["t", dx, dy]])); return this; }; - /*\ + /* \ * Element.transform [ method ] ** @@ -53623,7 +53443,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I return this; }; - /*\ + /* \ * Element.hide [ method ] ** @@ -53634,7 +53454,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if(!this.removed) this.node.style.display = "none"; return this; }; - /*\ + /* \ * Element.show [ method ] ** @@ -53645,7 +53465,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if(!this.removed) this.node.style.display = ""; return this; }; - /*\ + /* \ * Element.remove [ method ] ** @@ -53670,7 +53490,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.removeData(); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } this.removed = true; }; @@ -53683,7 +53503,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I containerStyle; if (this.paper.canvas.parentElement) { containerStyle = this.paper.canvas.parentElement.style; - } //IE10+ can't find parentElement + } // IE10+ can't find parentElement else if (this.paper.canvas.parentNode) { containerStyle = this.paper.canvas.parentNode.style; } @@ -53702,17 +53522,17 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I y: this.node.clientTop, width: this.node.clientWidth, height: this.node.clientHeight - } + }; } finally { bbox = bbox || {}; - if(canvasHidden){ + if(canvasHidden) { containerStyle.display = "none"; } } hide && this.hide(); return bbox; }; - /*\ + /* \ * Element.attr [ method ] ** @@ -53799,8 +53619,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (name == null) { var res = {}; - for (var a in this.attrs) if (this.attrs[has](a)) { - res[a] = this.attrs[a]; + for (var a in this.attrs) { + if (this.attrs[has](a)) { + res[a] = this.attrs[a]; + } } res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient; res.transform = this._.transform; @@ -53843,17 +53665,21 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I for (var key in params) { eve("raphael.attr." + key + "." + this.id, this, params[key]); } - for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { - var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); - this.attrs[key] = params[key]; - for (var subkey in par) if (par[has](subkey)) { - params[subkey] = par[subkey]; + for (key in this.paper.customAttributes) { + if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { + var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); + this.attrs[key] = params[key]; + for (var subkey in par) { + if (par[has](subkey)) { + params[subkey] = par[subkey]; + } + } } } setFillAndStroke(this, params); return this; }; - /*\ + /* \ * Element.toFront [ method ] ** @@ -53870,7 +53696,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I svg.top != this && R._tofront(this, svg); return this; }; - /*\ + /* \ * Element.toBack [ method ] ** @@ -53888,7 +53714,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I var svg = this.paper; return this; }; - /*\ + /* \ * Element.insertAfter [ method ] ** @@ -53910,7 +53736,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R._insertafter(this, element, this.paper); return this; }; - /*\ + /* \ * Element.insertBefore [ method ] ** @@ -54094,7 +53920,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this._viewBox = [x, y, w, h, !!fit]; return this; }; - /*\ + /* \ * Paper.renderfix [ method ] ** @@ -54126,7 +53952,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } } }; - /*\ + /* \ * Paper.clear [ method ] ** @@ -54143,7 +53969,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I c.appendChild(this.desc); c.appendChild(this.defs = $("defs")); }; - /*\ + /* \ * Paper.remove [ method ] ** @@ -54153,19 +53979,21 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve("raphael.remove", this); this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } }; var setproto = R.st; - for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname].apply(el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method) && !setproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname].apply(el, arg); + }); + }; + })(method); + } } })); @@ -54181,7 +54009,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.vml", ["raphael.core"], function(raphael) { + define("raphael.vml", ["raphael.core"], function (raphael) { return factory(raphael); }); } else if (typeof exports === "object") { @@ -54189,7 +54017,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } else { factory(glob.Raphael); } -}(this, function(R) { +}(this, function (R) { if (R && !R.vml) { return; } @@ -54342,8 +54170,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I res = o; - for (var par in params) if (params[has](par)) { - a[par] = params[par]; + for (var par in params) { + if (params[has](par)) { + a[par] = params[par]; + } } if (newpath) { a.path = R._getPath[o.type](o); @@ -54398,7 +54228,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I if (o.textpath) { var textpathStyle = o.textpath.style; params.font && (textpathStyle.font = params.font); - params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"'); + params["font-family"] && (textpathStyle.fontFamily = "\"" + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + "\""); params["font-size"] && (textpathStyle.fontSize = params["font-size"]); params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]); params["font-style"] && (textpathStyle.fontStyle = params["font-style"]); @@ -54531,9 +54361,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I ("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1)); var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"]; - for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) { - res._.dirty = 1; - break; + for (var d = 0, dd = dirtyattrs.length; d < dd; d++) { + if (dirtyattrs[d] in params) { + res._.dirty = 1; + break; + } } // text-anchor emulation @@ -54763,12 +54595,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I }; // Needed to fix the vml setViewBox issues elproto.auxGetBBox = R.el.getBBox; - elproto.getBBox = function(){ + elproto.getBBox = function () { var b = this.auxGetBBox(); - if (this.paper && this.paper._viewBoxShift) - { + if (this.paper && this.paper._viewBoxShift) { var c = {}; - var z = 1/this.paper._viewBoxShift.scale; + var z = 1 / this.paper._viewBoxShift.scale; c.x = b.x - this.paper._viewBoxShift.dx; c.x *= z; c.y = b.y - this.paper._viewBoxShift.dy; @@ -54802,7 +54633,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I this.node.parentNode.removeChild(this.node); this.shape && this.shape.parentNode.removeChild(this.shape); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } this.removed = true; }; @@ -54812,8 +54643,10 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I } if (name == null) { var res = {}; - for (var a in this.attrs) if (this.attrs[has](a)) { - res[a] = this.attrs[a]; + for (var a in this.attrs) { + if (this.attrs[has](a)) { + res[a] = this.attrs[a]; + } } res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient; res.transform = this._.transform; @@ -54854,11 +54687,15 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I eve("raphael.attr." + key + "." + this.id, this, params[key]); } if (params) { - for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { - var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); - this.attrs[key] = params[key]; - for (var subkey in par) if (par[has](subkey)) { - params[subkey] = par[subkey]; + for (key in this.paper.customAttributes) { + if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { + var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); + this.attrs[key] = params[key]; + for (var subkey in par) { + if (par[has](subkey)) { + params[subkey] = par[subkey]; + } + } } } // this.paper.canvas.style.display = "none"; @@ -55108,11 +54945,11 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I try { !doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml"); createNode = function (tagName) { - return doc.createElement(''); + return doc.createElement(""); }; } catch (e) { createNode = function (tagName) { - return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">'); + return doc.createElement("<" + tagName + " xmlns=\"urn:schemas-microsoft.com:vml\" class=\"rvml\">"); }; } }; @@ -55172,21 +55009,23 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I R.eve("raphael.remove", this); this.canvas.parentNode.removeChild(this.canvas); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } return true; }; var setproto = R.st; - for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname].apply(el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method) && !setproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname].apply(el, arg); + }); + }; + })(method); + } } })); @@ -55201,7 +55040,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael", ["raphael.core", "raphael.svg", "raphael.vml"], function(Raphael) { + define("raphael", ["raphael.core", "raphael.svg", "raphael.vml"], function (Raphael) { return factory(Raphael); }); } else if (typeof exports === "object") { @@ -55212,7 +55051,7 @@ BI.shortcut("bi.sql_editor", BI.SQLEditor);// Copyright (c) 2013 Adobe Systems I module.exports = factory(raphael); } else { - //glob.Raphael = factory(glob.Raphael); + // glob.Raphael = factory(glob.Raphael); } }(this, function (Raphael) { return Raphael.ninja(); @@ -55228,7 +55067,7 @@ BI.Svg = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Svg.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-svg" - }) + }); }, _init: function () { @@ -55236,7 +55075,7 @@ BI.Svg = BI.inherit(BI.Widget, { this.paper = Raphael(this.element[0]); this.element.css("overflow", "hidden"); - $(this.paper.canvas).width("100%").height("100%").css({"left": "0", "top": "0"}).appendTo(this.element); + $(this.paper.canvas).width("100%").height("100%").css({left: "0", top: "0"}).appendTo(this.element); this.top = this.paper.top; this.bottom = this.paper.bottom; @@ -55340,12 +55179,12 @@ BI.NativeTableScrollbar = BI.inherit(BI.Widget, { defaultPosition: 0, position: 0, size: 0 - }) + }); }, render: function () { var self = this, o = this.options; - //把滚动台size改掉 + // 把滚动台size改掉 this.element.width(36); var throttle = BI.throttle(function () { @@ -55364,7 +55203,7 @@ BI.NativeTableScrollbar = BI.inherit(BI.Widget, { self.inner = _ref; } }] - } + }; }, mounted: function () { @@ -55416,12 +55255,12 @@ BI.NativeTableHorizontalScrollbar = BI.inherit(BI.Widget, { contentSize: 0, position: 0, size: 0 - }) + }); }, render: function () { var self = this, o = this.options; - //把滚动台size改掉 + // 把滚动台size改掉 this.element.height(36); var throttle = BI.throttle(function () { @@ -55440,7 +55279,7 @@ BI.NativeTableHorizontalScrollbar = BI.inherit(BI.Widget, { self.inner = _ref; } }] - } + }; }, setContentSize: function (contentSize) { @@ -55490,7 +55329,7 @@ BI.TableCell = BI.inherit(BI.Widget, { baseCls: "bi-table-cell", textAlign: "left", text: "" - }) + }); }, _init: function () { @@ -55504,7 +55343,7 @@ BI.TableCell = BI.inherit(BI.Widget, { text: this.options.text, value: this.options.value, lgap: 5 - }) + }); } }); @@ -55525,7 +55364,7 @@ BI.CollectionTableCell = BI.inherit(BI.Widget, { _left: 0, _top: 0, cell: {} - }) + }); }, _init: function () { @@ -55838,7 +55677,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { overflow: "scroll", overflowX: "scroll", overflowY: "scroll" - }) + }); }; this.topLeft.setWidth(otlw); @@ -55896,7 +55735,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { _digest: function () { var o = this.options; var freezeColLength = this._getFreezeColLength(); - //如果表头位置不够,取消表头冻结 + // 如果表头位置不够,取消表头冻结 if (this._getFreezeHeaderHeight() <= 0) { this.topLeftItems = []; this.topRightItems = []; @@ -55986,7 +55825,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { var isNeedMergeCol = o.mergeRule(cache[i][j], cache[i][j - 1]); if (isNeedMergeCol && isNeedMergeRow) { continue; - //mergeRow(i, j);//优先合并列 + // mergeRow(i, j);//优先合并列 } if (isNeedMergeCol) { mergeCol(i, j); @@ -56011,7 +55850,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { col: item.item._col, width: item.item._width, height: item.item._height - } + }; }); }, @@ -56121,7 +55960,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { this._restore(); } }); -BI.shortcut('bi.collection_table', BI.CollectionTable);/** +BI.shortcut("bi.collection_table", BI.CollectionTable);/** * QuickCollectionTable * * Created by GUY on 2016/1/12. @@ -56188,25 +56027,25 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { _shouldHandleLeftX: function (delta) { if (delta > 0) { return this.bottomLeftCollection.getScrollLeft() < this.bottomLeftCollection.getMaxScrollLeft(); - } else { - return this.bottomLeftCollection.getScrollLeft() > 0; } + return this.bottomLeftCollection.getScrollLeft() > 0; + }, _shouldHandleRightX: function (delta) { if (delta > 0) { return this.bottomRightCollection.getScrollLeft() < this.bottomRightCollection.getMaxScrollLeft(); - } else { - return this.bottomRightCollection.getScrollLeft() > 0; } + return this.bottomRightCollection.getScrollLeft() > 0; + }, _shouldHandleY: function (delta) { if (delta > 0) { return this.bottomRightCollection.getScrollTop() < this.bottomRightCollection.getMaxScrollTop(); - } else { - return this.bottomRightCollection.getScrollTop() > 0; } + return this.bottomRightCollection.getScrollTop() > 0; + }, _onWheelLeft: function (deltaX, deltaY) { @@ -56240,7 +56079,7 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { _populateTable: function () { var self = this, o = this.options; var regionSize = this.getRegionSize(), totalLeftColumnSize = 0, totalRightColumnSize = 0, totalColumnSize = 0, - summaryColumnSizeArray = [] + summaryColumnSizeArray = []; BI.each(o.columnSize, function (i, size) { if (o.isNeedFreeze === true && o.freezeCols.contains(i)) { totalLeftColumnSize += size; @@ -56311,7 +56150,7 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { this.bottomRightCollection.populate(rightItems); } }); -BI.shortcut('bi.quick_collection_table', BI.QuickCollectionTable);/** +BI.shortcut("bi.quick_collection_table", BI.QuickCollectionTable);/** * * 表格单元格 * @@ -56330,7 +56169,7 @@ BI.GridTableCell = BI.inherit(BI.Widget, { _left: 0, _top: 0, cell: {} - }) + }); }, _init: function () { @@ -56691,7 +56530,7 @@ BI.GridTable = BI.inherit(BI.Widget, { overflow: "scroll", overflowX: "scroll", overflowY: "scroll" - }) + }); }; this.topLeft.setWidth(otlw); @@ -56847,7 +56686,7 @@ BI.GridTable = BI.inherit(BI.Widget, { this._restore(); } }); -BI.shortcut('bi.grid_table', BI.GridTable);/** +BI.shortcut("bi.grid_table", BI.GridTable);/** * QuickGridTable * * Created by GUY on 2016/1/12. @@ -56914,25 +56753,25 @@ BI.QuickGridTable = BI.inherit(BI.GridTable, { _shouldHandleLeftX: function (delta) { if (delta > 0) { return this.bottomLeftGrid.getScrollLeft() < this.bottomLeftGrid.getMaxScrollLeft(); - } else { - return this.bottomLeftGrid.getScrollLeft() > 0; } + return this.bottomLeftGrid.getScrollLeft() > 0; + }, _shouldHandleRightX: function (delta) { if (delta > 0) { return this.bottomRightGrid.getScrollLeft() < this.bottomRightGrid.getMaxScrollLeft(); - } else { - return this.bottomRightGrid.getScrollLeft() > 0; } + return this.bottomRightGrid.getScrollLeft() > 0; + }, _shouldHandleY: function (delta) { if (delta > 0) { return this.bottomRightGrid.getScrollTop() < this.bottomRightGrid.getMaxScrollTop(); - } else { - return this.bottomRightGrid.getScrollTop() > 0; } + return this.bottomRightGrid.getScrollTop() > 0; + }, _onWheelLeft: function (deltaX, deltaY) { @@ -57069,7 +56908,7 @@ BI.QuickGridTable = BI.inherit(BI.GridTable, { this.bottomRightGrid.populate(rightItems); } }); -BI.shortcut('bi.quick_grid_table', BI.QuickGridTable);/** +BI.shortcut("bi.quick_grid_table", BI.QuickGridTable);/** * * 表格滚动条 * @@ -57096,7 +56935,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { orientation: "vertical", position: 0, size: 0 - }) + }); }, render: function () { @@ -57121,7 +56960,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { mounted: function () { var self = this, o = this.options; - var onWheel = o.orientation === 'horizontal' ? this._onWheelX : this._onWheelY; + var onWheel = o.orientation === "horizontal" ? this._onWheelX : this._onWheelY; this._wheelHandler = new BI.WheelHandler( BI.bind(onWheel, this), BI.bind(this._shouldHandleX, this), @@ -57154,7 +56993,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { }, _isHorizontal: function () { - return this.options.orientation === 'horizontal' + return this.options.orientation === "horizontal"; }, _getScale: function () { @@ -57180,13 +57019,13 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { }, _shouldHandleX: function (delta) { - return this.options.orientation === 'horizontal' ? + return this.options.orientation === "horizontal" ? this._shouldHandleChange(delta) : false; }, _shouldHandleY: function (delta) { - return this.options.orientation !== 'horizontal' ? + return this.options.orientation !== "horizontal" ? this._shouldHandleChange(delta) : false; }, @@ -57420,7 +57259,7 @@ BI.GridTableHorizontalScrollbar = BI.inherit(BI.Widget, { contentSize: 0, position: 0, size: 0 - }) + }); }, _init: function () { @@ -57501,7 +57340,7 @@ BI.TableHeaderCell = BI.inherit(BI.Widget, { return BI.extend(BI.TableHeaderCell.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-table-header-cell", text: "" - }) + }); }, _init: function () { @@ -57513,7 +57352,7 @@ BI.TableHeaderCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); @@ -57532,16 +57371,16 @@ BI.Table = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Table.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-table", - logic: { //冻结的页面布局逻辑 + logic: { // 冻结的页面布局逻辑 dynamic: false }, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 - mergeRule: function (row1, row2) { //合并规则, 默认相等时合并 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 + mergeRule: function (row1, row2) { // 合并规则, 默认相等时合并 return BI.isEqual(row1, row2); }, @@ -57554,8 +57393,8 @@ BI.Table = BI.inherit(BI.Widget, { header: [], footer: false, - items: [] //二维数组 - }) + items: [] // 二维数组 + }); }, _calculateWidth: function (width) { @@ -57845,17 +57684,17 @@ BI.Table = BI.inherit(BI.Widget, { var regionColumnSize = o.regionColumnSize; if (o.freezeCols.length === 0) { - regionColumnSize = isRight ? ['fill', 0] : [0, 'fill']; + regionColumnSize = isRight ? ["fill", 0] : [0, "fill"]; } else if (o.freezeCols.length >= o.columnSize.length) { - regionColumnSize = isRight ? [0, 'fill'] : ['fill', 0]; + regionColumnSize = isRight ? [0, "fill"] : ["fill", 0]; } this.partitions = BI.createWidget(BI.extend({ element: this }, BI.LogicFactory.createLogic("table", BI.extend({}, o.logic, { rows: 2, columns: 2, - columnSize: regionColumnSize || (isRight ? ['fill', leftWidth] : [leftWidth, 'fill']), - rowSize: [headerHeight, 'fill'], + columnSize: regionColumnSize || (isRight ? ["fill", leftWidth] : [leftWidth, "fill"]), + rowSize: [headerHeight, "fill"], items: [[{ el: this.topLeft }, { @@ -57884,7 +57723,7 @@ BI.Table = BI.inherit(BI.Widget, { scroll(this.scrollBottomRight.element, this.scrollTopRight.element, this.scrollBottomLeft.element); // scroll(this.scrollBottomLeft.element, this.scrollTopLeft.element, this.scrollBottomRight.element); - function scroll(scrollElement, scrollTopElement, otherElement) { + function scroll (scrollElement, scrollTopElement, otherElement) { scrollElement.scroll(function (e) { otherElement.scrollTop(scrollElement.scrollTop()); scrollTopElement.scrollLeft(scrollElement.scrollLeft()); @@ -57961,10 +57800,10 @@ BI.Table = BI.inherit(BI.Widget, { createOneEl(i, j); } }); - function mergeRow(i, j) { + function mergeRow (i, j) { var height = (preCol[j].attr("height") | 0) + rowSize + 1; preCol[j].attr("height", height).css("height", height); - //preCW[j].element.css("height", height); + // preCW[j].element.css("height", height); var rowspan = ((preCol[j].attr("rowspan") || 1) | 0) + 1; preCol[j].attr("rowspan", rowspan); preCol[j].__mergeRows.pushDistinct(i); @@ -57972,7 +57811,7 @@ BI.Table = BI.inherit(BI.Widget, { Ws[i][j] = preCW[j]; } - function mergeCol(i, j) { + function mergeCol (i, j) { if (columnSize[j]) { var width = preRow[i].attr("width") | 0; if (width > 1.05 && columnSize[j]) { @@ -57981,7 +57820,7 @@ BI.Table = BI.inherit(BI.Widget, { width--; } } else { - width = width + columnSize[j] + width = width + columnSize[j]; } width = self._calculateWidth(width); preRow[i].attr("width", width).css("width", width); @@ -57994,14 +57833,14 @@ BI.Table = BI.inherit(BI.Widget, { Ws[i][j] = preRW[i]; } - function createOneEl(r, c) { + function createOneEl (r, c) { var width = self._calculateWidth(columnSize[c]); if (width > 1.05 && c === columnSize.length - 1) { width--; } var height = self._calculateHeight(rowSize); var td = $("").attr("height", height) - .attr("width", width).css({"width": width, "height": height, "position": "relative"}) + .attr("width", width).css({width: width, height: height, position: "relative"}) .addClass((c & 1) === 0 ? "odd-col" : "even-col") .addClass(r === 0 ? "first-row" : "") .addClass(c === 0 ? "first-col" : "") @@ -58172,12 +58011,12 @@ BI.Table = BI.inherit(BI.Widget, { } else { (isRight ? left : right)[i].push(cell); } - }) + }); }); return { left: left, right: right - } + }; }, _table: function () { @@ -58185,7 +58024,7 @@ BI.Table = BI.inherit(BI.Widget, { type: "bi.layout", tagName: "table", cls: "table", - attribute: {"cellspacing": 0, "cellpadding": 0} + attribute: {cellspacing: 0, cellpadding: 0} }); }, @@ -58339,7 +58178,7 @@ BI.Table = BI.inherit(BI.Widget, { } }); } - }) + }); }; run(topleft); run(topright); @@ -58599,21 +58438,21 @@ BI.Table = BI.inherit(BI.Widget, { if (o.isNeedFreeze === true) { if (BI.size(this.bottomLeftBodyTds) > 0 || BI.size(this.bottomRightBodyTds) > 0) { if (!BI.any(this.bottomLeftBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.bottomLeftBodyTds[0], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.bottomLeftBodyTds[0]) - 1) { @@ -58623,21 +58462,21 @@ BI.Table = BI.inherit(BI.Widget, { }); } if (!BI.any(this.bottomRightBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.bottomRightBodyTds[0], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.bottomRightBodyTds[0]) - 1) { @@ -58649,21 +58488,21 @@ BI.Table = BI.inherit(BI.Widget, { return columnSize; } if (!BI.any(this.topLeftBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.topLeftBodyTds[BI.size(this.topLeftBodyTds) - 1], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.topLeftBodyTds[BI.size(self.topLeftBodyTds) - 1]) - 1) { @@ -58673,21 +58512,21 @@ BI.Table = BI.inherit(BI.Widget, { }); } if (!BI.any(this.topRightBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.topRightBodyTds[BI.size(this.topRightBodyTds) - 1], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.topRightBodyTds[BI.size(self.topRightBodyTds) - 1]) - 1) { @@ -58810,7 +58649,7 @@ BI.Table = BI.inherit(BI.Widget, { } }); } - }) + }); }; run(topleft); run(topright); @@ -58923,7 +58762,7 @@ BI.Table = BI.inherit(BI.Widget, { o.regionColumnSize = columnSize; if (o.freezeCols.length === 0) { if (o.isNeedFreeze) { - this.partitions.attr("columnSize", this._isRightFreeze() ? ['fill', 0] : [0, 'fill']); + this.partitions.attr("columnSize", this._isRightFreeze() ? ["fill", 0] : [0, "fill"]); this.partitions.resize(); } else { this.tableContainer.element.width(columnSize[0]); @@ -58937,7 +58776,7 @@ BI.Table = BI.inherit(BI.Widget, { } } else { if (o.isNeedFreeze) { - this.partitions.attr("columnSize", this._isRightFreeze() ? [0, 'fill'] : ['fill', 0]); + this.partitions.attr("columnSize", this._isRightFreeze() ? [0, "fill"] : ["fill", 0]); this.partitions.resize(); } else { this.tableContainer.element.width(columnSize[0]); @@ -58994,9 +58833,9 @@ BI.Table = BI.inherit(BI.Widget, { if (o.isNeedFreeze) { if (o.freezeCols.length < o.columnSize.length) { return [this.scrollTopRight.element[0].scrollHeight, this.scrollBottomRight.element[0].scrollHeight]; - } else { - return [this.scrollTopLeft.element[0].scrollHeight, this.scrollBottomLeft.element[0].scrollHeight]; } + return [this.scrollTopLeft.element[0].scrollHeight, this.scrollBottomLeft.element[0].scrollHeight]; + } return [this.scrollBottomRight.element[0].scrollHeight]; }, @@ -59089,14 +58928,14 @@ BI.Table = BI.inherit(BI.Widget, { topRight: this.topRightBodyItems, bottomLeft: this.bottomLeftBodyItems, bottomRight: this.bottomRightBodyItems - } - } else { - return { - header: this.headerItems, - body: this.bodyItems, - footer: this.footerItems - } + }; } + return { + header: this.headerItems, + body: this.bodyItems, + footer: this.footerItems + }; + }, populate: function (items, header) { @@ -59143,7 +58982,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { start: BI.emptyFn, resize: BI.emptyFn, stop: BI.emptyFn - }) + }); }, _init: function () { @@ -59154,7 +58993,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { var startDrag = false; var size = 0, offset = 0, defaultSize = o.width; - function optimizeSize(s) { + function optimizeSize (s) { var optSize = BI.clamp(s, o.minSize, o.maxSize || Number.MAX_VALUE); // if (o.suitableSize) { // if (Math.abs(o.suitableSize - optSize) < 5) { @@ -59223,7 +59062,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { top: 0, bottom: 0 }] - }) + }); }, setWidth: function (width) { @@ -59258,7 +59097,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { isResizeAdapt: false, headerRowSize: 25, rowSize: 25, - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, columnSize: [], @@ -59268,7 +59107,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { header: [], items: [], regionColumnSize: [] - }) + }); }, _init: function () { @@ -59457,7 +59296,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { self.resizer.setVisible(true); var height = o.headerRowSize + self._getRegionRowSize()[1]; self.resizer.setHeight(height); - //TODO 不知道为什么加入这段代码会使得列宽调整出问题 + // TODO 不知道为什么加入这段代码会使得列宽调整出问题 // if (o.minColumnSize[j]) { // if (size === o.minColumnSize[j]) { // self.resizer.element.addClass("suitable"); @@ -59528,7 +59367,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { setWidth: function (width) { BI.ResizableTable.superclass.setWidth.apply(this, arguments); - this.table.setWidth(width) + this.table.setWidth(width); }, setHeight: function (height) { @@ -59631,7 +59470,7 @@ BI.CustomTree = BI.inherit(BI.Widget, { type: "bi.vertical" }] } - }) + }); }, _init: function () { @@ -59666,7 +59505,7 @@ BI.CustomTree = BI.inherit(BI.Widget, { item.popup.expander = BI.deepClone(o.expander); item.items = item.popup.items = node.children; item.itemsCreator = item.popup.itemsCreator = function (op) { - if (BI.isNotNull(op.node)) {//从子节点传过来的itemsCreator直接向上传递 + if (BI.isNotNull(op.node)) {// 从子节点传过来的itemsCreator直接向上传递 return o.itemsCreator.apply(self, arguments); } var args = Array.prototype.slice.call(arguments, 0); @@ -59682,7 +59521,7 @@ BI.CustomTree = BI.inherit(BI.Widget, { return items; }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.tree = BI.createWidget(o.el, { @@ -59701,10 +59540,10 @@ BI.CustomTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.CustomTree.EVENT_CHANGE, val, obj); } - }) + }); }, - //生成树方法 + // 生成树方法 stroke: function (nodes) { this.populate.apply(this, arguments); }, @@ -59717,1750 +59556,1747 @@ BI.CustomTree = BI.inherit(BI.Widget, { this.tree.populate.apply(this.tree, args); }, - setValue: function (v) { - this.tree && this.tree.setValue(v); - }, + setValue: function (v) { + this.tree && this.tree.setValue(v); + }, + + getValue: function () { + return this.tree ? this.tree.getValue() : []; + }, + + getAllButtons: function () { + return this.tree ? this.tree.getAllButtons() : []; + }, + + getAllLeaves: function () { + return this.tree ? this.tree.getAllLeaves() : []; + }, + + getNodeById: function (id) { + return this.tree && this.tree.getNodeById(id); + }, + + getNodeByValue: function (id) { + return this.tree && this.tree.getNodeByValue(id); + }, + + empty: function () { + this.tree.empty(); + } +}); +BI.CustomTree.EVENT_CHANGE = "EVENT_CHANGE"; + +BI.shortcut("bi.custom_tree", BI.CustomTree);/* + * JQuery zTree core v3.5.18 + * http://zTree.me/ + * + * Copyright (c) 2010 Hunter.z + * + * Licensed same as jquery - MIT License + * http://www.opensource.org/licenses/mit-license.php + * + * email: hunter.z@263.net + * Date: 2015-06-18 + */ +(function ($) { + var settings = {}, roots = {}, caches = {}, + // default consts of core + _consts = { + className: { + BUTTON: "button", + LEVEL: "level", + ICO_LOADING: "ico_loading", + SWITCH: "switch" + }, + event: { + NODECREATED: "ztree_nodeCreated", + CLICK: "ztree_click", + EXPAND: "ztree_expand", + COLLAPSE: "ztree_collapse", + ASYNC_SUCCESS: "ztree_async_success", + ASYNC_ERROR: "ztree_async_error", + REMOVE: "ztree_remove", + SELECTED: "ztree_selected", + UNSELECTED: "ztree_unselected" + }, + id: { + A: "_a", + ICON: "_ico", + SPAN: "_span", + SWITCH: "_switch", + UL: "_ul" + }, + line: { + ROOT: "root", + ROOTS: "roots", + CENTER: "center", + BOTTOM: "bottom", + NOLINE: "noline", + LINE: "line" + }, + folder: { + OPEN: "open", + CLOSE: "close", + DOCU: "docu" + }, + node: { + CURSELECTED: "curSelectedNode" + } + }, + // default setting of core + _setting = { + treeId: "", + treeObj: null, + view: { + addDiyDom: null, + autoCancelSelected: true, + dblClickExpand: true, + expandSpeed: "fast", + fontCss: {}, + nameIsHTML: false, + selectedMulti: true, + showIcon: true, + showLine: true, + showTitle: true, + txtSelectedEnable: false + }, + data: { + key: { + children: "children", + name: "name", + title: "", + url: "url" + }, + simpleData: { + enable: false, + idKey: "id", + pIdKey: "pId", + rootPId: null + }, + keep: { + parent: false, + leaf: false + } + }, + async: { + enable: false, + contentType: "application/x-www-form-urlencoded", + type: "post", + dataType: "text", + url: "", + autoParam: [], + otherParam: [], + dataFilter: null + }, + callback: { + beforeAsync: null, + beforeClick: null, + beforeDblClick: null, + beforeRightClick: null, + beforeMouseDown: null, + beforeMouseUp: null, + beforeExpand: null, + beforeCollapse: null, + beforeRemove: null, + + onAsyncError: null, + onAsyncSuccess: null, + onNodeCreated: null, + onClick: null, + onDblClick: null, + onRightClick: null, + onMouseDown: null, + onMouseUp: null, + onExpand: null, + onCollapse: null, + onRemove: null + } + }, + // default root of core + // zTree use root to save full data + _initRoot = function (setting) { + var r = data.getRoot(setting); + if (!r) { + r = {}; + data.setRoot(setting, r); + } + r[setting.data.key.children] = []; + r.expandTriggerFlag = false; + r.curSelectedList = []; + r.noSelection = true; + r.createdNodes = []; + r.zId = 0; + r._ver = (new Date()).getTime(); + }, + // default cache of core + _initCache = function (setting) { + var c = data.getCache(setting); + if (!c) { + c = {}; + data.setCache(setting, c); + } + c.nodes = []; + c.doms = []; + }, + // default bindEvent of core + _bindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.bind(c.NODECREATED, function (event, treeId, node) { + tools.apply(setting.callback.onNodeCreated, [event, treeId, node]); + }); + + o.bind(c.CLICK, function (event, srcEvent, treeId, node, clickFlag) { + tools.apply(setting.callback.onClick, [srcEvent, treeId, node, clickFlag]); + }); + + o.bind(c.EXPAND, function (event, treeId, node) { + tools.apply(setting.callback.onExpand, [event, treeId, node]); + }); + + o.bind(c.COLLAPSE, function (event, treeId, node) { + tools.apply(setting.callback.onCollapse, [event, treeId, node]); + }); + + o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) { + tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]); + }); + + o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { + tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); + }); + + o.bind(c.REMOVE, function (event, treeId, treeNode) { + tools.apply(setting.callback.onRemove, [event, treeId, treeNode]); + }); + + o.bind(c.SELECTED, function (event, srcEvent, treeId, node) { + tools.apply(setting.callback.onSelected, [srcEvent, treeId, node]); + }); + o.bind(c.UNSELECTED, function (event, srcEvent, treeId, node) { + tools.apply(setting.callback.onUnSelected, [srcEvent, treeId, node]); + }); + }, + _unbindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.unbind(c.NODECREATED) + .unbind(c.CLICK) + .unbind(c.EXPAND) + .unbind(c.COLLAPSE) + .unbind(c.ASYNC_SUCCESS) + .unbind(c.ASYNC_ERROR) + .unbind(c.REMOVE) + .unbind(c.SELECTED) + .unbind(c.UNSELECTED); + }, + // default event proxy of core + _eventProxy = function (event) { + var target = event.target, + setting = data.getSetting(event.data.treeId), + tId = "", node = null, + nodeEventType = "", treeEventType = "", + nodeEventCallback = null, treeEventCallback = null, + tmp = null; + + if (tools.eqs(event.type, "mousedown")) { + treeEventType = "mousedown"; + } else if (tools.eqs(event.type, "mouseup")) { + treeEventType = "mouseup"; + } else if (tools.eqs(event.type, "contextmenu")) { + treeEventType = "contextmenu"; + } else if (tools.eqs(event.type, "click")) { + if (tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.SWITCH) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "switchNode"; + } else { + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) { + tId = tools.getNodeMainDom(tmp).id; + nodeEventType = "clickNode"; + } + } + } else if (tools.eqs(event.type, "dblclick")) { + treeEventType = "dblclick"; + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) { + tId = tools.getNodeMainDom(tmp).id; + nodeEventType = "switchNode"; + } + } + if (treeEventType.length > 0 && tId.length == 0) { + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) {tId = tools.getNodeMainDom(tmp).id;} + } + // event to node + if (tId.length > 0) { + node = data.getNodeCache(setting, tId); + switch (nodeEventType) { + case "switchNode" : + if (!node.isParent) { + nodeEventType = ""; + } else if (tools.eqs(event.type, "click") + || (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) { + nodeEventCallback = handler.onSwitchNode; + } else { + nodeEventType = ""; + } + break; + case "clickNode" : + nodeEventCallback = handler.onClickNode; + break; + } + } + // event to zTree + switch (treeEventType) { + case "mousedown" : + treeEventCallback = handler.onZTreeMousedown; + break; + case "mouseup" : + treeEventCallback = handler.onZTreeMouseup; + break; + case "dblclick" : + treeEventCallback = handler.onZTreeDblclick; + break; + case "contextmenu" : + treeEventCallback = handler.onZTreeContextmenu; + break; + } + var proxyResult = { + stop: false, + node: node, + nodeEventType: nodeEventType, + nodeEventCallback: nodeEventCallback, + treeEventType: treeEventType, + treeEventCallback: treeEventCallback + }; + return proxyResult; + }, + // default init node of core + _initNode = function (setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { + if (!n) return; + var r = data.getRoot(setting), + childKey = setting.data.key.children; + n.level = level; + n.tId = setting.treeId + "_" + (++r.zId); + n.parentTId = parentNode ? parentNode.tId : null; + n.open = (typeof n.open === "string") ? tools.eqs(n.open, "true") : !!n.open; + if (n[childKey] && n[childKey].length > 0) { + n.isParent = true; + n.zAsync = true; + } else { + n.isParent = (typeof n.isParent === "string") ? tools.eqs(n.isParent, "true") : !!n.isParent; + n.open = (n.isParent && !setting.async.enable) ? n.open : false; + n.zAsync = !n.isParent; + } + n.isFirstNode = isFirstNode; + n.isLastNode = isLastNode; + n.getParentNode = function () {return data.getNodeCache(setting, n.parentTId);}; + n.getPreNode = function () {return data.getPreNode(setting, n);}; + n.getNextNode = function () {return data.getNextNode(setting, n);}; + n.isAjaxing = false; + data.fixPIdKeyValue(setting, n); + }, + _init = { + bind: [_bindEvent], + unbind: [_unbindEvent], + caches: [_initCache], + nodes: [_initNode], + proxys: [_eventProxy], + roots: [_initRoot], + beforeA: [], + afterA: [], + innerBeforeA: [], + innerAfterA: [], + zTreeTools: [] + }, + // method of operate data + data = { + addNodeCache: function (setting, node) { + data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = node; + }, + getNodeCacheId: function (tId) { + return tId.substring(tId.lastIndexOf("_") + 1); + }, + addAfterA: function (afterA) { + _init.afterA.push(afterA); + }, + addBeforeA: function (beforeA) { + _init.beforeA.push(beforeA); + }, + addInnerAfterA: function (innerAfterA) { + _init.innerAfterA.push(innerAfterA); + }, + addInnerBeforeA: function (innerBeforeA) { + _init.innerBeforeA.push(innerBeforeA); + }, + addInitBind: function (bindEvent) { + _init.bind.push(bindEvent); + }, + addInitUnBind: function (unbindEvent) { + _init.unbind.push(unbindEvent); + }, + addInitCache: function (initCache) { + _init.caches.push(initCache); + }, + addInitNode: function (initNode) { + _init.nodes.push(initNode); + }, + addInitProxy: function (initProxy, isFirst) { + if (isFirst) { + _init.proxys.splice(0, 0, initProxy); + } else { + _init.proxys.push(initProxy); + } + }, + addInitRoot: function (initRoot) { + _init.roots.push(initRoot); + }, + addNodesData: function (setting, parentNode, nodes) { + var childKey = setting.data.key.children; + if (!parentNode[childKey]) parentNode[childKey] = []; + if (parentNode[childKey].length > 0) { + parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false; + view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]); + } + parentNode.isParent = true; + parentNode[childKey] = parentNode[childKey].concat(nodes); + }, + addSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + if (!data.isSelectedNode(setting, node)) { + root.curSelectedList.push(node); + } + }, + addCreatedNode: function (setting, node) { + if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { + var root = data.getRoot(setting); + root.createdNodes.push(node); + } + }, + addZTreeTools: function (zTreeTools) { + _init.zTreeTools.push(zTreeTools); + }, + exSetting: function (s) { + $.extend(true, _setting, s); + }, + fixPIdKeyValue: function (setting, node) { + if (setting.data.simpleData.enable) { + node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; + } + }, + getAfterA: function (setting, node, array) { + for (var i = 0, j = _init.afterA.length; i < j; i++) { + _init.afterA[i].apply(this, arguments); + } + }, + getBeforeA: function (setting, node, array) { + for (var i = 0, j = _init.beforeA.length; i < j; i++) { + _init.beforeA[i].apply(this, arguments); + } + }, + getInnerAfterA: function (setting, node, array) { + for (var i = 0, j = _init.innerAfterA.length; i < j; i++) { + _init.innerAfterA[i].apply(this, arguments); + } + }, + getInnerBeforeA: function (setting, node, array) { + for (var i = 0, j = _init.innerBeforeA.length; i < j; i++) { + _init.innerBeforeA[i].apply(this, arguments); + } + }, + getCache: function (setting) { + return caches[setting.treeId]; + }, + getNextNode: function (setting, node) { + if (!node) return null; + var childKey = setting.data.key.children, + p = node.parentTId ? node.getParentNode() : data.getRoot(setting); + for (var i = 0, l = p[childKey].length - 1; i <= l; i++) { + if (p[childKey][i] === node) { + return (i == l ? null : p[childKey][i + 1]); + } + } + return null; + }, + getNodeByParam: function (setting, nodes, key, value) { + if (!nodes || !key) return null; + var childKey = setting.data.key.children; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i][key] == value) { + return nodes[i]; + } + var tmp = data.getNodeByParam(setting, nodes[i][childKey], key, value); + if (tmp) return tmp; + } + return null; + }, + getNodeCache: function (setting, tId) { + if (!tId) return null; + var n = caches[setting.treeId].nodes[data.getNodeCacheId(tId)]; + return n ? n : null; + }, + getNodeName: function (setting, node) { + var nameKey = setting.data.key.name; + return "" + node[nameKey]; + }, + getNodeTitle: function (setting, node) { + var t = setting.data.key.title === "" ? setting.data.key.name : setting.data.key.title; + return "" + node[t]; + }, + getNodes: function (setting) { + return data.getRoot(setting)[setting.data.key.children]; + }, + getNodesByParam: function (setting, nodes, key, value) { + if (!nodes || !key) return []; + var childKey = setting.data.key.children, + result = []; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i][key] == value) { + result.push(nodes[i]); + } + result = result.concat(data.getNodesByParam(setting, nodes[i][childKey], key, value)); + } + return result; + }, + getNodesByParamFuzzy: function (setting, nodes, key, value) { + if (!nodes || !key) return []; + var childKey = setting.data.key.children, + result = []; + value = value.toLowerCase(); + for (var i = 0, l = nodes.length; i < l; i++) { + if (typeof nodes[i][key] === "string" && nodes[i][key].toLowerCase().indexOf(value) > -1) { + result.push(nodes[i]); + } + result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value)); + } + return result; + }, + getNodesByFilter: function (setting, nodes, filter, isSingle, invokeParam) { + if (!nodes) return (isSingle ? null : []); + var childKey = setting.data.key.children, + result = isSingle ? null : []; + for (var i = 0, l = nodes.length; i < l; i++) { + if (tools.apply(filter, [nodes[i], invokeParam], false)) { + if (isSingle) {return nodes[i];} + result.push(nodes[i]); + } + var tmpResult = data.getNodesByFilter(setting, nodes[i][childKey], filter, isSingle, invokeParam); + if (isSingle && !!tmpResult) {return tmpResult;} + result = isSingle ? tmpResult : result.concat(tmpResult); + } + return result; + }, + getPreNode: function (setting, node) { + if (!node) return null; + var childKey = setting.data.key.children, + p = node.parentTId ? node.getParentNode() : data.getRoot(setting); + for (var i = 0, l = p[childKey].length; i < l; i++) { + if (p[childKey][i] === node) { + return (i == 0 ? null : p[childKey][i - 1]); + } + } + return null; + }, + getRoot: function (setting) { + return setting ? roots[setting.treeId] : null; + }, + getRoots: function () { + return roots; + }, + getSetting: function (treeId) { + return settings[treeId]; + }, + getSettings: function () { + return settings; + }, + getZTreeTools: function (treeId) { + var r = this.getRoot(this.getSetting(treeId)); + return r ? r.treeTools : null; + }, + initCache: function (setting) { + for (var i = 0, j = _init.caches.length; i < j; i++) { + _init.caches[i].apply(this, arguments); + } + }, + initNode: function (setting, level, node, parentNode, preNode, nextNode) { + for (var i = 0, j = _init.nodes.length; i < j; i++) { + _init.nodes[i].apply(this, arguments); + } + }, + initRoot: function (setting) { + for (var i = 0, j = _init.roots.length; i < j; i++) { + _init.roots[i].apply(this, arguments); + } + }, + isSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + for (var i = 0, j = root.curSelectedList.length; i < j; i++) { + if(node === root.curSelectedList[i]) return true; + } + return false; + }, + removeNodeCache: function (setting, node) { + var childKey = setting.data.key.children; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + arguments.callee(setting, node[childKey][i]); + } + } + data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = null; + }, + removeSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + for (var i = 0, j = root.curSelectedList.length; i < j; i++) { + if(node === root.curSelectedList[i] || !data.getNodeCache(setting, root.curSelectedList[i].tId)) { + root.curSelectedList.splice(i, 1); + i--; j--; + } + } + }, + setCache: function (setting, cache) { + caches[setting.treeId] = cache; + }, + setRoot: function (setting, root) { + roots[setting.treeId] = root; + }, + setZTreeTools: function (setting, zTreeTools) { + for (var i = 0, j = _init.zTreeTools.length; i < j; i++) { + _init.zTreeTools[i].apply(this, arguments); + } + }, + transformToArrayFormat: function (setting, nodes) { + if (!nodes) return []; + var childKey = setting.data.key.children, + r = []; + if (tools.isArray(nodes)) { + for (var i = 0, l = nodes.length; i < l; i++) { + r.push(nodes[i]); + if (nodes[i][childKey]) {r = r.concat(data.transformToArrayFormat(setting, nodes[i][childKey]));} + } + } else { + r.push(nodes); + if (nodes[childKey]) {r = r.concat(data.transformToArrayFormat(setting, nodes[childKey]));} + } + return r; + }, + transformTozTreeFormat: function (setting, sNodes) { + var i, l, + key = setting.data.simpleData.idKey, + parentKey = setting.data.simpleData.pIdKey, + childKey = setting.data.key.children; + if (!key || key == "" || !sNodes) return []; + + if (tools.isArray(sNodes)) { + var r = []; + var tmpMap = []; + for (i = 0, l = sNodes.length; i < l; i++) { + tmpMap[sNodes[i][key]] = sNodes[i]; + } + for (i = 0, l = sNodes.length; i < l; i++) { + if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) { + if (!tmpMap[sNodes[i][parentKey]][childKey]) {tmpMap[sNodes[i][parentKey]][childKey] = [];} + tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]); + } else { + r.push(sNodes[i]); + } + } + return r; + } + return [sNodes]; + + } + }, + // method of event proxy + event = { + bindEvent: function (setting) { + for (var i = 0, j = _init.bind.length; i < j; i++) { + _init.bind[i].apply(this, arguments); + } + }, + unbindEvent: function (setting) { + for (var i = 0, j = _init.unbind.length; i < j; i++) { + _init.unbind[i].apply(this, arguments); + } + }, + bindTree: function (setting) { + var eventParam = { + treeId: setting.treeId + }, + o = setting.treeObj; + if (!setting.view.txtSelectedEnable) { + // for can't select text + o.bind("selectstart", function (e) { + var node; + var n = e.originalEvent.srcElement.nodeName.toLowerCase(); + return (n === "input" || n === "textarea" ); + }).css({ + "-moz-user-select": "-moz-none" + }); + } + o.bind("click", eventParam, event.proxy); + o.bind("dblclick", eventParam, event.proxy); + o.bind("mouseover", eventParam, event.proxy); + o.bind("mouseout", eventParam, event.proxy); + o.bind("mousedown", eventParam, event.proxy); + o.bind("mouseup", eventParam, event.proxy); + o.bind("contextmenu", eventParam, event.proxy); + }, + unbindTree: function (setting) { + var o = setting.treeObj; + o.unbind("click", event.proxy) + .unbind("dblclick", event.proxy) + .unbind("mouseover", event.proxy) + .unbind("mouseout", event.proxy) + .unbind("mousedown", event.proxy) + .unbind("mouseup", event.proxy) + .unbind("contextmenu", event.proxy); + }, + doProxy: function (e) { + var results = []; + for (var i = 0, j = _init.proxys.length; i < j; i++) { + var proxyResult = _init.proxys[i].apply(this, arguments); + results.push(proxyResult); + if (proxyResult.stop) { + break; + } + } + return results; + }, + proxy: function (e) { + var setting = data.getSetting(e.data.treeId); + if (!tools.uCanDo(setting, e)) return true; + var results = event.doProxy(e), + r = true, x = false; + for (var i = 0, l = results.length; i < l; i++) { + var proxyResult = results[i]; + if (proxyResult.nodeEventCallback) { + x = true; + r = proxyResult.nodeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; + } + if (proxyResult.treeEventCallback) { + x = true; + r = proxyResult.treeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; + } + } + return r; + } + }, + // method of event handler + handler = { + onSwitchNode: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (node.open) { + if (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false) return true; + data.getRoot(setting).expandTriggerFlag = true; + view.switchNode(setting, node); + } else { + if (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false) return true; + data.getRoot(setting).expandTriggerFlag = true; + view.switchNode(setting, node); + } + return true; + }, + onClickNode: function (event, node) { + var setting = data.getSetting(event.data.treeId), + clickFlag = ( (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey)) && data.isSelectedNode(setting, node)) ? 0 : (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey) && setting.view.selectedMulti) ? 2 : 1; + if (tools.apply(setting.callback.beforeClick, [setting.treeId, node, clickFlag], true) == false) return true; + if (clickFlag === 0) { + view.cancelPreSelectedNode(setting, node); + } else { + view.selectNode(setting, node, clickFlag === 2); + } + setting.treeObj.trigger(consts.event.CLICK, [event, setting.treeId, node, clickFlag]); + return true; + }, + onZTreeMousedown: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeMouseDown, [setting.treeId, node], true)) { + tools.apply(setting.callback.onMouseDown, [event, setting.treeId, node]); + } + return true; + }, + onZTreeMouseup: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeMouseUp, [setting.treeId, node], true)) { + tools.apply(setting.callback.onMouseUp, [event, setting.treeId, node]); + } + return true; + }, + onZTreeDblclick: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeDblClick, [setting.treeId, node], true)) { + tools.apply(setting.callback.onDblClick, [event, setting.treeId, node]); + } + return true; + }, + onZTreeContextmenu: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeRightClick, [setting.treeId, node], true)) { + tools.apply(setting.callback.onRightClick, [event, setting.treeId, node]); + } + return (typeof setting.callback.onRightClick) !== "function"; + } + }, + // method of tools for zTree + tools = { + apply: function (fun, param, defaultValue) { + if ((typeof fun) === "function") { + return fun.apply(zt, param ? param : []); + } + return defaultValue; + }, + canAsync: function (setting, node) { + var childKey = setting.data.key.children; + return (setting.async.enable && node && node.isParent && !(node.zAsync || (node[childKey] && node[childKey].length > 0))); + }, + clone: function (obj) { + if (obj === null) return null; + var o = tools.isArray(obj) ? [] : {}; + for(var i in obj) { + o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]); + } + return o; + }, + eqs: function (str1, str2) { + return str1.toLowerCase() === str2.toLowerCase(); + }, + isArray: function (arr) { + return Object.prototype.toString.apply(arr) === "[object Array]"; + }, + $: function (node, exp, setting) { + if (!!exp && typeof exp !== "string") { + setting = exp; + exp = ""; + } + if (typeof node === "string") { + return $(node, setting ? setting.treeObj.get(0).ownerDocument : null); + } + return $("#" + node.tId + exp, setting ? setting.treeObj : null); + + }, + getMDom: function (setting, curDom, targetExpr) { + if (!curDom) return null; + while (curDom && curDom.id !== setting.treeId) { + for (var i = 0, l = targetExpr.length; curDom.tagName && i < l; i++) { + if (tools.eqs(curDom.tagName, targetExpr[i].tagName) && curDom.getAttribute(targetExpr[i].attrName) !== null) { + return curDom; + } + } + curDom = curDom.parentNode; + } + return null; + }, + getNodeMainDom: function (target) { + return ($(target).parent("li").get(0) || $(target).parentsUntil("li").parent().get(0)); + }, + isChildOrSelf: function (dom, parentId) { + return ( $(dom).closest("#" + parentId).length > 0 ); + }, + uCanDo: function (setting, e) { + return true; + } + }, + // method of operate ztree dom + view = { + addNodes: function (setting, parentNode, newNodes, isSilent) { + if (setting.data.keep.leaf && parentNode && !parentNode.isParent) { + return; + } + if (!tools.isArray(newNodes)) { + newNodes = [newNodes]; + } + if (setting.data.simpleData.enable) { + newNodes = data.transformTozTreeFormat(setting, newNodes); + } + if (parentNode) { + var target_switchObj = $$(parentNode, consts.id.SWITCH, setting), + target_icoObj = $$(parentNode, consts.id.ICON, setting), + target_ulObj = $$(parentNode, consts.id.UL, setting); + + if (!parentNode.open) { + view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE); + view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); + parentNode.open = false; + target_ulObj.css({ + display: "none" + }); + } + + data.addNodesData(setting, parentNode, newNodes); + view.createNodes(setting, parentNode.level + 1, newNodes, parentNode); + if (!isSilent) { + view.expandCollapseParentNode(setting, parentNode, true); + } + } else { + data.addNodesData(setting, data.getRoot(setting), newNodes); + view.createNodes(setting, 0, newNodes, null); + } + }, + appendNodes: function (setting, level, nodes, parentNode, initFlag, openFlag) { + if (!nodes) return []; + var html = [], + childKey = setting.data.key.children; + for (var i = 0, l = nodes.length; i < l; i++) { + var node = nodes[i]; + if (initFlag) { + var tmpPNode = (parentNode) ? parentNode : data.getRoot(setting), + tmpPChild = tmpPNode[childKey], + isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)), + isLastNode = (i == (nodes.length - 1)); + data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); + data.addNodeCache(setting, node); + } + + var childHtml = []; + if (node[childKey] && node[childKey].length > 0) { + // make child html first, because checkType + childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open); + } + if (openFlag) { + + view.makeDOMNodeMainBefore(html, setting, node); + view.makeDOMNodeLine(html, setting, node); + data.getBeforeA(setting, node, html); + view.makeDOMNodeNameBefore(html, setting, node); + data.getInnerBeforeA(setting, node, html); + view.makeDOMNodeIcon(html, setting, node); + data.getInnerAfterA(setting, node, html); + view.makeDOMNodeNameAfter(html, setting, node); + data.getAfterA(setting, node, html); + if (node.isParent && node.open) { + view.makeUlHtml(setting, node, html, childHtml.join("")); + } + view.makeDOMNodeMainAfter(html, setting, node); + data.addCreatedNode(setting, node); + } + } + return html; + }, + appendParentULDom: function (setting, node) { + var html = [], + nObj = $$(node, setting); + if (!nObj.get(0) && !!node.parentTId) { + view.appendParentULDom(setting, node.getParentNode()); + nObj = $$(node, setting); + } + var ulObj = $$(node, consts.id.UL, setting); + if (ulObj.get(0)) { + ulObj.remove(); + } + var childKey = setting.data.key.children, + childHtml = view.appendNodes(setting, node.level + 1, node[childKey], node, false, true); + view.makeUlHtml(setting, node, html, childHtml.join("")); + nObj.append(html.join("")); + }, + asyncNode: function (setting, node, isSilent, callback) { + var i, l; + if (node && !node.isParent) { + tools.apply(callback); + return false; + } else if (node && node.isAjaxing) { + return false; + } else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) { + tools.apply(callback); + return false; + } + if (node) { + node.isAjaxing = true; + var icoObj = $$(node, consts.id.ICON, setting); + icoObj.attr({style: "", class: consts.className.BUTTON + " " + consts.className.ICO_LOADING}); + } + + var tmpParam = {}; + for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) { + var pKey = setting.async.autoParam[i].split("="), spKey = pKey; + if (pKey.length > 1) { + spKey = pKey[1]; + pKey = pKey[0]; + } + tmpParam[spKey] = node[pKey]; + } + if (tools.isArray(setting.async.otherParam)) { + for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) { + tmpParam[setting.async.otherParam[i]] = setting.async.otherParam[i + 1]; + } + } else { + for (var p in setting.async.otherParam) { + tmpParam[p] = setting.async.otherParam[p]; + } + } + + var _tmpV = data.getRoot(setting)._ver; + $.ajax({ + contentType: setting.async.contentType, + cache: false, + type: setting.async.type, + url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), + data: tmpParam, + dataType: setting.async.dataType, + success: function (msg) { + if (_tmpV != data.getRoot(setting)._ver) { + return; + } + var newNodes = []; + try { + if (!msg || msg.length == 0) { + newNodes = []; + } else if (typeof msg === "string") { + newNodes = eval("(" + msg + ")"); + } else { + newNodes = msg; + } + } catch(err) { + newNodes = msg; + } + + if (node) { + node.isAjaxing = null; + node.zAsync = true; + } + view.setNodeLineIcos(setting, node); + if (newNodes && newNodes !== "") { + newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); + view.addNodes(setting, node, newNodes ? tools.clone(newNodes) : [], !!isSilent); + } else { + view.addNodes(setting, node, [], !!isSilent); + } + setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]); + tools.apply(callback); + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + if (_tmpV != data.getRoot(setting)._ver) { + return; + } + if (node) node.isAjaxing = null; + view.setNodeLineIcos(setting, node); + setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); + } + }); + return true; + }, + cancelPreSelectedNode: function (setting, node, excludeNode) { + var list = data.getRoot(setting).curSelectedList, + i, n; + for (i = list.length - 1; i >= 0; i--) { + n = list[i]; + if (node === n || (!node && (!excludeNode || excludeNode !== n))) { + $$(n, consts.id.A, setting).removeClass(consts.node.CURSELECTED); + if (node) { + data.removeSelectedNode(setting, node); + setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); + break; + } else { + list.splice(i, 1); + setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); + } + } + } + }, + createNodeCallback: function (setting) { + if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { + var root = data.getRoot(setting); + while (root.createdNodes.length > 0) { + var node = root.createdNodes.shift(); + tools.apply(setting.view.addDiyDom, [setting.treeId, node]); + if (setting.callback.onNodeCreated) { + setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]); + } + } + } + }, + createNodes: function (setting, level, nodes, parentNode) { + if (!nodes || nodes.length == 0) return; + var root = data.getRoot(setting), + childKey = setting.data.key.children, + openFlag = !parentNode || parentNode.open || !!$$(parentNode[childKey][0], setting).get(0); + root.createdNodes = []; + var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag); + if (!parentNode) { + setting.treeObj.append(zTreeHtml.join("")); + } else { + var ulObj = $$(parentNode, consts.id.UL, setting); + if (ulObj.get(0)) { + ulObj.append(zTreeHtml.join("")); + } + } + view.createNodeCallback(setting); + }, + destroy: function (setting) { + if (!setting) return; + data.initCache(setting); + data.initRoot(setting); + event.unbindTree(setting); + event.unbindEvent(setting); + setting.treeObj.empty(); + delete settings[setting.treeId]; + }, + expandCollapseNode: function (setting, node, expandFlag, animateFlag, callback) { + var root = data.getRoot(setting), + childKey = setting.data.key.children; + if (!node) { + tools.apply(callback, []); + return; + } + if (root.expandTriggerFlag) { + var _callback = callback; + callback = function () { + if (_callback) _callback(); + if (node.open) { + setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]); + } else { + setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]); + } + }; + root.expandTriggerFlag = false; + } + if (!node.open && node.isParent && ((!$$(node, consts.id.UL, setting).get(0)) || (node[childKey] && node[childKey].length > 0 && !$$(node[childKey][0], setting).get(0)))) { + view.appendParentULDom(setting, node); + view.createNodeCallback(setting); + } + if (node.open == expandFlag) { + tools.apply(callback, []); + return; + } + var ulObj = $$(node, consts.id.UL, setting), + switchObj = $$(node, consts.id.SWITCH, setting), + icoObj = $$(node, consts.id.ICON, setting); + + if (node.isParent) { + node.open = !node.open; + if (node.iconOpen && node.iconClose) { + icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); + } + + if (node.open) { + view.replaceSwitchClass(node, switchObj, consts.folder.OPEN); + view.replaceIcoClass(node, icoObj, consts.folder.OPEN); + if (animateFlag == false || setting.view.expandSpeed == "") { + ulObj.show(); + tools.apply(callback, []); + } else { + if (node[childKey] && node[childKey].length > 0) { + ulObj.slideDown(setting.view.expandSpeed, callback); + } else { + ulObj.show(); + tools.apply(callback, []); + } + } + } else { + view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); + view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); + if (animateFlag == false || setting.view.expandSpeed == "" || !(node[childKey] && node[childKey].length > 0)) { + ulObj.hide(); + tools.apply(callback, []); + } else { + ulObj.slideUp(setting.view.expandSpeed, callback); + } + } + } else { + tools.apply(callback, []); + } + }, + expandCollapseParentNode: function (setting, node, expandFlag, animateFlag, callback) { + if (!node) return; + if (!node.parentTId) { + view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback); + return; + } + view.expandCollapseNode(setting, node, expandFlag, animateFlag); + + if (node.parentTId) { + view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback); + } + }, + expandCollapseSonNode: function (setting, node, expandFlag, animateFlag, callback) { + var root = data.getRoot(setting), + childKey = setting.data.key.children, + treeNodes = (node) ? node[childKey] : root[childKey], + selfAnimateSign = (node) ? false : animateFlag, + expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; + data.getRoot(setting).expandTriggerFlag = false; + if (treeNodes) { + for (var i = 0, l = treeNodes.length; i < l; i++) { + if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); + } + } + data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; + view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback ); + }, + isSelectedNode: function (setting, node) { + if (!node) { + return false; + } + var list = data.getRoot(setting).curSelectedList, + i; + for (i = list.length - 1; i >= 0; i--) { + if (node === list[i]) { + return true; + } + } + return false; + }, + makeDOMNodeIcon: function (html, setting, node) { + var nameStr = data.getNodeName(setting, node), + name = setting.view.nameIsHTML ? nameStr : nameStr.replace(/&/g, "&").replace(//g, ">"); + html.push("", name, ""); + }, + makeDOMNodeLine: function (html, setting, node) { + html.push(""); + }, + makeDOMNodeMainAfter: function (html, setting, node) { + html.push("
  • "); + }, + makeDOMNodeMainBefore: function (html, setting, node) { + html.push("
  • "); + }, + makeDOMNodeNameAfter: function (html, setting, node) { + html.push(""); + }, + makeDOMNodeNameBefore: function (html, setting, node) { + var title = data.getNodeTitle(setting, node), + url = view.makeNodeUrl(setting, node), + fontcss = view.makeNodeFontCss(setting, node), + fontStyle = []; + for (var f in fontcss) { + fontStyle.push(f, ":", fontcss[f], ";"); + } + html.push(" 0) ? "href='" + url + "'" : ""), " target='", view.makeNodeTarget(node), "' style='", fontStyle.join(""), + "'"); + if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && title) {html.push("title='", title.replace(/'/g, "'").replace(//g, ">"), "'");} + html.push(">"); + }, + makeNodeFontCss: function (setting, node) { + var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); + return (fontCss && ((typeof fontCss) !== "function")) ? fontCss : {}; + }, + makeNodeIcoClass: function (setting, node) { + var icoCss = ["ico"]; + if (!node.isAjaxing) { + icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0]; + if (node.isParent) { + icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); + } else { + icoCss.push(consts.folder.DOCU); + } + } + return consts.className.BUTTON + " " + icoCss.join("_"); + }, + makeNodeIcoStyle: function (setting, node) { + var icoStyle = []; + if (!node.isAjaxing) { + var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon; + if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); + if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { + icoStyle.push("width:0px;height:0px;"); + } + } + return icoStyle.join(""); + }, + makeNodeLineClass: function (setting, node) { + var lineClass = []; + if (setting.view.showLine) { + if (node.level == 0 && node.isFirstNode && node.isLastNode) { + lineClass.push(consts.line.ROOT); + } else if (node.level == 0 && node.isFirstNode) { + lineClass.push(consts.line.ROOTS); + } else if (node.isLastNode) { + lineClass.push(consts.line.BOTTOM); + } else { + lineClass.push(consts.line.CENTER); + } + } else { + lineClass.push(consts.line.NOLINE); + } + if (node.isParent) { + lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); + } else { + lineClass.push(consts.folder.DOCU); + } + return view.makeNodeLineClassEx(node) + lineClass.join("_"); + }, + makeNodeLineClassEx: function (node) { + return consts.className.BUTTON + " " + consts.className.LEVEL + node.level + " " + consts.className.SWITCH + " "; + }, + makeNodeTarget: function (node) { + return (node.target || "_blank"); + }, + makeNodeUrl: function (setting, node) { + var urlKey = setting.data.key.url; + return node[urlKey] ? node[urlKey] : null; + }, + makeUlHtml: function (setting, node, html, content) { + html.push("
      "); + html.push(content); + html.push("
    "); + }, + makeUlLineClass: function (setting, node) { + return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : ""); + }, + removeChildNodes: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children, + nodes = node[childKey]; + if (!nodes) return; + + for (var i = 0, l = nodes.length; i < l; i++) { + data.removeNodeCache(setting, nodes[i]); + } + data.removeSelectedNode(setting); + delete node[childKey]; + + if (!setting.data.keep.parent) { + node.isParent = false; + node.open = false; + var tmp_switchObj = $$(node, consts.id.SWITCH, setting), + tmp_icoObj = $$(node, consts.id.ICON, setting); + view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU); + view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU); + $$(node, consts.id.UL, setting).remove(); + } else { + $$(node, consts.id.UL, setting).empty(); + } + }, + setFirstNode: function (setting, parentNode) { + var childKey = setting.data.key.children, childLength = parentNode[childKey].length; + if ( childLength > 0) { + parentNode[childKey][0].isFirstNode = true; + } + }, + setLastNode: function (setting, parentNode) { + var childKey = setting.data.key.children, childLength = parentNode[childKey].length; + if ( childLength > 0) { + parentNode[childKey][childLength - 1].isLastNode = true; + } + }, + removeNode: function (setting, node) { + var root = data.getRoot(setting), + childKey = setting.data.key.children, + parentNode = (node.parentTId) ? node.getParentNode() : root; + + node.isFirstNode = false; + node.isLastNode = false; + node.getPreNode = function () {return null;}; + node.getNextNode = function () {return null;}; - getValue: function () { - return this.tree ? this.tree.getValue() : []; - }, + if (!data.getNodeCache(setting, node.tId)) { + return; + } - getAllButtons: function () { - return this.tree ? this.tree.getAllButtons() : []; - }, + $$(node, setting).remove(); + data.removeNodeCache(setting, node); + data.removeSelectedNode(setting, node); - getAllLeaves: function () { - return this.tree ? this.tree.getAllLeaves() : []; - }, + for (var i = 0, l = parentNode[childKey].length; i < l; i++) { + if (parentNode[childKey][i].tId == node.tId) { + parentNode[childKey].splice(i, 1); + break; + } + } + view.setFirstNode(setting, parentNode); + view.setLastNode(setting, parentNode); + + var tmp_ulObj, tmp_switchObj, tmp_icoObj, + childLength = parentNode[childKey].length; + + // repair nodes old parent + if (!setting.data.keep.parent && childLength == 0) { + // old parentNode has no child nodes + parentNode.isParent = false; + parentNode.open = false; + tmp_ulObj = $$(parentNode, consts.id.UL, setting); + tmp_switchObj = $$(parentNode, consts.id.SWITCH, setting); + tmp_icoObj = $$(parentNode, consts.id.ICON, setting); + view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU); + view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU); + tmp_ulObj.css("display", "none"); + + } else if (setting.view.showLine && childLength > 0) { + // old parentNode has child nodes + var newLast = parentNode[childKey][childLength - 1]; + tmp_ulObj = $$(newLast, consts.id.UL, setting); + tmp_switchObj = $$(newLast, consts.id.SWITCH, setting); + tmp_icoObj = $$(newLast, consts.id.ICON, setting); + if (parentNode == root) { + if (parentNode[childKey].length == 1) { + // node was root, and ztree has only one root after move node + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT); + } else { + var tmp_first_switchObj = $$(parentNode[childKey][0], consts.id.SWITCH, setting); + view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS); + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); + } + } else { + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); + } + tmp_ulObj.removeClass(consts.line.LINE); + } + }, + replaceIcoClass: function (node, obj, newName) { + if (!obj || node.isAjaxing) return; + var tmpName = obj.attr("class"); + if (tmpName == undefined) return; + var tmpList = tmpName.split("_"); + switch (newName) { + case consts.folder.OPEN: + case consts.folder.CLOSE: + case consts.folder.DOCU: + tmpList[tmpList.length - 1] = newName; + break; + } + obj.attr("class", tmpList.join("_")); + }, + replaceSwitchClass: function (node, obj, newName) { + if (!obj) return; + var tmpName = obj.attr("class"); + if (tmpName == undefined) return; + var tmpList = tmpName.split("_"); + switch (newName) { + case consts.line.ROOT: + case consts.line.ROOTS: + case consts.line.CENTER: + case consts.line.BOTTOM: + case consts.line.NOLINE: + tmpList[0] = view.makeNodeLineClassEx(node) + newName; + break; + case consts.folder.OPEN: + case consts.folder.CLOSE: + case consts.folder.DOCU: + tmpList[1] = newName; + break; + } + obj.attr("class", tmpList.join("_")); + if (newName !== consts.folder.DOCU) { + obj.removeAttr("disabled"); + } else { + obj.attr("disabled", "disabled"); + } + }, + selectNode: function (setting, node, addFlag) { + if (!addFlag) { + view.cancelPreSelectedNode(setting, null, node); + } + $$(node, consts.id.A, setting).addClass(consts.node.CURSELECTED); + data.addSelectedNode(setting, node); + setting.treeObj.trigger(consts.event.SELECTED, [event, setting.treeId, node]); + }, + setNodeFontCss: function (setting, treeNode) { + var aObj = $$(treeNode, consts.id.A, setting), + fontCss = view.makeNodeFontCss(setting, treeNode); + if (fontCss) { + aObj.css(fontCss); + } + }, + setNodeLineIcos: function (setting, node) { + if (!node) return; + var switchObj = $$(node, consts.id.SWITCH, setting), + ulObj = $$(node, consts.id.UL, setting), + icoObj = $$(node, consts.id.ICON, setting), + ulLine = view.makeUlLineClass(setting, node); + if (ulLine.length == 0) { + ulObj.removeClass(consts.line.LINE); + } else { + ulObj.addClass(ulLine); + } + switchObj.attr("class", view.makeNodeLineClass(setting, node)); + if (node.isParent) { + switchObj.removeAttr("disabled"); + } else { + switchObj.attr("disabled", "disabled"); + } + icoObj.removeAttr("style"); + icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); + icoObj.attr("class", view.makeNodeIcoClass(setting, node)); + }, + setNodeName: function (setting, node) { + var title = data.getNodeTitle(setting, node), + nObj = $$(node, consts.id.SPAN, setting); + nObj.empty(); + if (setting.view.nameIsHTML) { + nObj.html(data.getNodeName(setting, node)); + } else { + nObj.text(data.getNodeName(setting, node)); + } + if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle)) { + var aObj = $$(node, consts.id.A, setting); + aObj.attr("title", !title ? "" : title); + } + }, + setNodeTarget: function (setting, node) { + var aObj = $$(node, consts.id.A, setting); + aObj.attr("target", view.makeNodeTarget(node)); + }, + setNodeUrl: function (setting, node) { + var aObj = $$(node, consts.id.A, setting), + url = view.makeNodeUrl(setting, node); + if (url == null || url.length == 0) { + aObj.removeAttr("href"); + } else { + aObj.attr("href", url); + } + }, + switchNode: function (setting, node) { + if (node.open || !tools.canAsync(setting, node)) { + view.expandCollapseNode(setting, node, !node.open); + } else if (setting.async.enable) { + if (!view.asyncNode(setting, node)) { + view.expandCollapseNode(setting, node, !node.open); + return; + } + } else if (node) { + view.expandCollapseNode(setting, node, !node.open); + } + } + }; + // zTree defind + $.fn.zTree = { + consts: _consts, + _z: { + tools: tools, + view: view, + event: event, + data: data + }, + getZTreeObj: function (treeId) { + var o = data.getZTreeTools(treeId); + return o ? o : null; + }, + destroy: function (treeId) { + if (!!treeId && treeId.length > 0) { + view.destroy(data.getSetting(treeId)); + } else { + for(var s in settings) { + view.destroy(settings[s]); + } + } + }, + init: function (obj, zSetting, zNodes) { + var setting = tools.clone(_setting); + $.extend(true, setting, zSetting); + setting.treeId = obj.attr("id"); + setting.treeObj = obj; + setting.treeObj.empty(); + settings[setting.treeId] = setting; + // For some older browser,(e.g., ie6) + if(typeof document.body.style.maxHeight === "undefined") { + setting.view.expandSpeed = ""; + } + data.initRoot(setting); + var root = data.getRoot(setting), + childKey = setting.data.key.children; + zNodes = zNodes ? tools.clone(tools.isArray(zNodes) ? zNodes : [zNodes]) : []; + if (setting.data.simpleData.enable) { + root[childKey] = data.transformTozTreeFormat(setting, zNodes); + } else { + root[childKey] = zNodes; + } + + data.initCache(setting); + event.unbindTree(setting); + event.bindTree(setting); + event.unbindEvent(setting); + event.bindEvent(setting); + + var zTreeTools = { + setting: setting, + addNodes: function (parentNode, newNodes, isSilent) { + if (!newNodes) return null; + if (!parentNode) parentNode = null; + if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null; + var xNewNodes = tools.clone(tools.isArray(newNodes) ? newNodes : [newNodes]); + function addCallback () { + view.addNodes(setting, parentNode, xNewNodes, (isSilent == true)); + } - getNodeById: function (id) { - return this.tree && this.tree.getNodeById(id); - }, + if (tools.canAsync(setting, parentNode)) { + view.asyncNode(setting, parentNode, isSilent, addCallback); + } else { + addCallback(); + } + return xNewNodes; + }, + cancelSelectedNode: function (node) { + view.cancelPreSelectedNode(setting, node); + }, + destroy: function () { + view.destroy(setting); + }, + expandAll: function (expandFlag) { + expandFlag = !!expandFlag; + view.expandCollapseSonNode(setting, null, expandFlag, true); + return expandFlag; + }, + expandNode: function (node, expandFlag, sonSign, focus, callbackFlag) { + if (!node || !node.isParent) return null; + if (expandFlag !== true && expandFlag !== false) { + expandFlag = !node.open; + } + callbackFlag = !!callbackFlag; - getNodeByValue: function (id) { - return this.tree && this.tree.getNodeByValue(id); - }, + if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) { + return null; + } else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) { + return null; + } + if (expandFlag && node.parentTId) { + view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, false); + } + if (expandFlag === node.open && !sonSign) { + return null; + } - empty: function () { - this.tree.empty(); - } -}); -BI.CustomTree.EVENT_CHANGE = "EVENT_CHANGE"; + data.getRoot(setting).expandTriggerFlag = callbackFlag; + if (!tools.canAsync(setting, node) && sonSign) { + view.expandCollapseSonNode(setting, node, expandFlag, true, function () { + if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e) {}} + }); + } else { + node.open = !expandFlag; + view.switchNode(this.setting, node); + if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e) {}} + } + return expandFlag; + }, + getNodes: function () { + return data.getNodes(setting); + }, + getNodeByParam: function (key, value, parentNode) { + if (!key) return null; + return data.getNodeByParam(setting, parentNode ? parentNode[setting.data.key.children] : data.getNodes(setting), key, value); + }, + getNodeByTId: function (tId) { + return data.getNodeCache(setting, tId); + }, + getNodesByParam: function (key, value, parentNode) { + if (!key) return null; + return data.getNodesByParam(setting, parentNode ? parentNode[setting.data.key.children] : data.getNodes(setting), key, value); + }, + getNodesByParamFuzzy: function (key, value, parentNode) { + if (!key) return null; + return data.getNodesByParamFuzzy(setting, parentNode ? parentNode[setting.data.key.children] : data.getNodes(setting), key, value); + }, + getNodesByFilter: function (filter, isSingle, parentNode, invokeParam) { + isSingle = !!isSingle; + if (!filter || (typeof filter !== "function")) return (isSingle ? null : []); + return data.getNodesByFilter(setting, parentNode ? parentNode[setting.data.key.children] : data.getNodes(setting), filter, isSingle, invokeParam); + }, + getNodeIndex: function (node) { + if (!node) return null; + var childKey = setting.data.key.children, + parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); + for (var i = 0, l = parentNode[childKey].length; i < l; i++) { + if (parentNode[childKey][i] == node) return i; + } + return -1; + }, + getSelectedNodes: function () { + var r = [], list = data.getRoot(setting).curSelectedList; + for (var i = 0, l = list.length; i < l; i++) { + r.push(list[i]); + } + return r; + }, + isSelectedNode: function (node) { + return data.isSelectedNode(setting, node); + }, + reAsyncChildNodes: function (parentNode, reloadType, isSilent) { + if (!this.setting.async.enable) return; + var isRoot = !parentNode; + if (isRoot) { + parentNode = data.getRoot(setting); + } + if (reloadType == "refresh") { + var childKey = this.setting.data.key.children; + for (var i = 0, l = parentNode[childKey] ? parentNode[childKey].length : 0; i < l; i++) { + data.removeNodeCache(setting, parentNode[childKey][i]); + } + data.removeSelectedNode(setting); + parentNode[childKey] = []; + if (isRoot) { + this.setting.treeObj.empty(); + } else { + var ulObj = $$(parentNode, consts.id.UL, setting); + ulObj.empty(); + } + } + view.asyncNode(this.setting, isRoot ? null : parentNode, !!isSilent); + }, + refresh: function () { + this.setting.treeObj.empty(); + var root = data.getRoot(setting), + nodes = root[setting.data.key.children]; + data.initRoot(setting); + root[setting.data.key.children] = nodes; + data.initCache(setting); + view.createNodes(setting, 0, root[setting.data.key.children]); + }, + removeChildNodes: function (node) { + if (!node) return null; + var childKey = setting.data.key.children, + nodes = node[childKey]; + view.removeChildNodes(setting, node); + return nodes ? nodes : null; + }, + removeNode: function (node, callbackFlag) { + if (!node) return; + callbackFlag = !!callbackFlag; + if (callbackFlag && tools.apply(setting.callback.beforeRemove, [setting.treeId, node], true) == false) return; + view.removeNode(setting, node); + if (callbackFlag) { + this.setting.treeObj.trigger(consts.event.REMOVE, [setting.treeId, node]); + } + }, + selectNode: function (node, addFlag) { + if (!node) return; + if (tools.uCanDo(setting)) { + addFlag = setting.view.selectedMulti && addFlag; + if (node.parentTId) { + view.expandCollapseParentNode(setting, node.getParentNode(), true, false, function () { + try{$$(node, setting).focus().blur();}catch(e) {} + }); + } else { + try{$$(node, setting).focus().blur();}catch(e) {} + } + view.selectNode(setting, node, addFlag); + } + }, + transformTozTreeNodes: function (simpleNodes) { + return data.transformTozTreeFormat(setting, simpleNodes); + }, + transformToArray: function (nodes) { + return data.transformToArrayFormat(setting, nodes); + }, + updateNode: function (node, checkTypeFlag) { + if (!node) return; + var nObj = $$(node, setting); + if (nObj.get(0) && tools.uCanDo(setting)) { + view.setNodeName(setting, node); + view.setNodeTarget(setting, node); + view.setNodeUrl(setting, node); + view.setNodeLineIcos(setting, node); + view.setNodeFontCss(setting, node); + } + } + }; + root.treeTools = zTreeTools; + data.setZTreeTools(setting, zTreeTools); -BI.shortcut("bi.custom_tree", BI.CustomTree);/* - * JQuery zTree core v3.5.18 - * http://zTree.me/ - * - * Copyright (c) 2010 Hunter.z - * - * Licensed same as jquery - MIT License - * http://www.opensource.org/licenses/mit-license.php - * - * email: hunter.z@263.net - * Date: 2015-06-18 - */ -(function($){ - var settings = {}, roots = {}, caches = {}, - //default consts of core - _consts = { - className: { - BUTTON: "button", - LEVEL: "level", - ICO_LOADING: "ico_loading", - SWITCH: "switch" - }, - event: { - NODECREATED: "ztree_nodeCreated", - CLICK: "ztree_click", - EXPAND: "ztree_expand", - COLLAPSE: "ztree_collapse", - ASYNC_SUCCESS: "ztree_async_success", - ASYNC_ERROR: "ztree_async_error", - REMOVE: "ztree_remove", - SELECTED: "ztree_selected", - UNSELECTED: "ztree_unselected" - }, - id: { - A: "_a", - ICON: "_ico", - SPAN: "_span", - SWITCH: "_switch", - UL: "_ul" - }, - line: { - ROOT: "root", - ROOTS: "roots", - CENTER: "center", - BOTTOM: "bottom", - NOLINE: "noline", - LINE: "line" - }, - folder: { - OPEN: "open", - CLOSE: "close", - DOCU: "docu" - }, - node: { - CURSELECTED: "curSelectedNode" - } - }, - //default setting of core - _setting = { - treeId: "", - treeObj: null, - view: { - addDiyDom: null, - autoCancelSelected: true, - dblClickExpand: true, - expandSpeed: "fast", - fontCss: {}, - nameIsHTML: false, - selectedMulti: true, - showIcon: true, - showLine: true, - showTitle: true, - txtSelectedEnable: false - }, - data: { - key: { - children: "children", - name: "name", - title: "", - url: "url" - }, - simpleData: { - enable: false, - idKey: "id", - pIdKey: "pId", - rootPId: null - }, - keep: { - parent: false, - leaf: false - } - }, - async: { - enable: false, - contentType: "application/x-www-form-urlencoded", - type: "post", - dataType: "text", - url: "", - autoParam: [], - otherParam: [], - dataFilter: null - }, - callback: { - beforeAsync:null, - beforeClick:null, - beforeDblClick:null, - beforeRightClick:null, - beforeMouseDown:null, - beforeMouseUp:null, - beforeExpand:null, - beforeCollapse:null, - beforeRemove:null, - - onAsyncError:null, - onAsyncSuccess:null, - onNodeCreated:null, - onClick:null, - onDblClick:null, - onRightClick:null, - onMouseDown:null, - onMouseUp:null, - onExpand:null, - onCollapse:null, - onRemove:null - } - }, - //default root of core - //zTree use root to save full data - _initRoot = function (setting) { - var r = data.getRoot(setting); - if (!r) { - r = {}; - data.setRoot(setting, r); - } - r[setting.data.key.children] = []; - r.expandTriggerFlag = false; - r.curSelectedList = []; - r.noSelection = true; - r.createdNodes = []; - r.zId = 0; - r._ver = (new Date()).getTime(); - }, - //default cache of core - _initCache = function(setting) { - var c = data.getCache(setting); - if (!c) { - c = {}; - data.setCache(setting, c); - } - c.nodes = []; - c.doms = []; - }, - //default bindEvent of core - _bindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.bind(c.NODECREATED, function (event, treeId, node) { - tools.apply(setting.callback.onNodeCreated, [event, treeId, node]); - }); - - o.bind(c.CLICK, function (event, srcEvent, treeId, node, clickFlag) { - tools.apply(setting.callback.onClick, [srcEvent, treeId, node, clickFlag]); - }); - - o.bind(c.EXPAND, function (event, treeId, node) { - tools.apply(setting.callback.onExpand, [event, treeId, node]); - }); - - o.bind(c.COLLAPSE, function (event, treeId, node) { - tools.apply(setting.callback.onCollapse, [event, treeId, node]); - }); - - o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) { - tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]); - }); - - o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { - tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); - }); - - o.bind(c.REMOVE, function (event, treeId, treeNode) { - tools.apply(setting.callback.onRemove, [event, treeId, treeNode]); - }); - - o.bind(c.SELECTED, function (event, srcEvent, treeId, node) { - tools.apply(setting.callback.onSelected, [srcEvent, treeId, node]); - }); - o.bind(c.UNSELECTED, function (event, srcEvent, treeId, node) { - tools.apply(setting.callback.onUnSelected, [srcEvent, treeId, node]); - }); - }, - _unbindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.unbind(c.NODECREATED) - .unbind(c.CLICK) - .unbind(c.EXPAND) - .unbind(c.COLLAPSE) - .unbind(c.ASYNC_SUCCESS) - .unbind(c.ASYNC_ERROR) - .unbind(c.REMOVE) - .unbind(c.SELECTED) - .unbind(c.UNSELECTED); - }, - //default event proxy of core - _eventProxy = function(event) { - var target = event.target, - setting = data.getSetting(event.data.treeId), - tId = "", node = null, - nodeEventType = "", treeEventType = "", - nodeEventCallback = null, treeEventCallback = null, - tmp = null; - - if (tools.eqs(event.type, "mousedown")) { - treeEventType = "mousedown"; - } else if (tools.eqs(event.type, "mouseup")) { - treeEventType = "mouseup"; - } else if (tools.eqs(event.type, "contextmenu")) { - treeEventType = "contextmenu"; - } else if (tools.eqs(event.type, "click")) { - if (tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.SWITCH) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "switchNode"; - } else { - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) { - tId = tools.getNodeMainDom(tmp).id; - nodeEventType = "clickNode"; - } - } - } else if (tools.eqs(event.type, "dblclick")) { - treeEventType = "dblclick"; - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) { - tId = tools.getNodeMainDom(tmp).id; - nodeEventType = "switchNode"; - } - } - if (treeEventType.length > 0 && tId.length == 0) { - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) {tId = tools.getNodeMainDom(tmp).id;} - } - // event to node - if (tId.length>0) { - node = data.getNodeCache(setting, tId); - switch (nodeEventType) { - case "switchNode" : - if (!node.isParent) { - nodeEventType = ""; - } else if (tools.eqs(event.type, "click") - || (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) { - nodeEventCallback = handler.onSwitchNode; - } else { - nodeEventType = ""; - } - break; - case "clickNode" : - nodeEventCallback = handler.onClickNode; - break; - } - } - // event to zTree - switch (treeEventType) { - case "mousedown" : - treeEventCallback = handler.onZTreeMousedown; - break; - case "mouseup" : - treeEventCallback = handler.onZTreeMouseup; - break; - case "dblclick" : - treeEventCallback = handler.onZTreeDblclick; - break; - case "contextmenu" : - treeEventCallback = handler.onZTreeContextmenu; - break; - } - var proxyResult = { - stop: false, - node: node, - nodeEventType: nodeEventType, - nodeEventCallback: nodeEventCallback, - treeEventType: treeEventType, - treeEventCallback: treeEventCallback - }; - return proxyResult - }, - //default init node of core - _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { - if (!n) return; - var r = data.getRoot(setting), - childKey = setting.data.key.children; - n.level = level; - n.tId = setting.treeId + "_" + (++r.zId); - n.parentTId = parentNode ? parentNode.tId : null; - n.open = (typeof n.open == "string") ? tools.eqs(n.open, "true") : !!n.open; - if (n[childKey] && n[childKey].length > 0) { - n.isParent = true; - n.zAsync = true; - } else { - n.isParent = (typeof n.isParent == "string") ? tools.eqs(n.isParent, "true") : !!n.isParent; - n.open = (n.isParent && !setting.async.enable) ? n.open : false; - n.zAsync = !n.isParent; - } - n.isFirstNode = isFirstNode; - n.isLastNode = isLastNode; - n.getParentNode = function() {return data.getNodeCache(setting, n.parentTId);}; - n.getPreNode = function() {return data.getPreNode(setting, n);}; - n.getNextNode = function() {return data.getNextNode(setting, n);}; - n.isAjaxing = false; - data.fixPIdKeyValue(setting, n); - }, - _init = { - bind: [_bindEvent], - unbind: [_unbindEvent], - caches: [_initCache], - nodes: [_initNode], - proxys: [_eventProxy], - roots: [_initRoot], - beforeA: [], - afterA: [], - innerBeforeA: [], - innerAfterA: [], - zTreeTools: [] - }, - //method of operate data - data = { - addNodeCache: function(setting, node) { - data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = node; - }, - getNodeCacheId: function(tId) { - return tId.substring(tId.lastIndexOf("_")+1); - }, - addAfterA: function(afterA) { - _init.afterA.push(afterA); - }, - addBeforeA: function(beforeA) { - _init.beforeA.push(beforeA); - }, - addInnerAfterA: function(innerAfterA) { - _init.innerAfterA.push(innerAfterA); - }, - addInnerBeforeA: function(innerBeforeA) { - _init.innerBeforeA.push(innerBeforeA); - }, - addInitBind: function(bindEvent) { - _init.bind.push(bindEvent); - }, - addInitUnBind: function(unbindEvent) { - _init.unbind.push(unbindEvent); - }, - addInitCache: function(initCache) { - _init.caches.push(initCache); - }, - addInitNode: function(initNode) { - _init.nodes.push(initNode); - }, - addInitProxy: function(initProxy, isFirst) { - if (!!isFirst) { - _init.proxys.splice(0,0,initProxy); - } else { - _init.proxys.push(initProxy); - } - }, - addInitRoot: function(initRoot) { - _init.roots.push(initRoot); - }, - addNodesData: function(setting, parentNode, nodes) { - var childKey = setting.data.key.children; - if (!parentNode[childKey]) parentNode[childKey] = []; - if (parentNode[childKey].length > 0) { - parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false; - view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]); - } - parentNode.isParent = true; - parentNode[childKey] = parentNode[childKey].concat(nodes); - }, - addSelectedNode: function(setting, node) { - var root = data.getRoot(setting); - if (!data.isSelectedNode(setting, node)) { - root.curSelectedList.push(node); - } - }, - addCreatedNode: function(setting, node) { - if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { - var root = data.getRoot(setting); - root.createdNodes.push(node); - } - }, - addZTreeTools: function(zTreeTools) { - _init.zTreeTools.push(zTreeTools); - }, - exSetting: function(s) { - $.extend(true, _setting, s); - }, - fixPIdKeyValue: function(setting, node) { - if (setting.data.simpleData.enable) { - node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; - } - }, - getAfterA: function(setting, node, array) { - for (var i=0, j=_init.afterA.length; i-1) { - result.push(nodes[i]); - } - result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value)); - } - return result; - }, - getNodesByFilter: function(setting, nodes, filter, isSingle, invokeParam) { - if (!nodes) return (isSingle ? null : []); - var childKey = setting.data.key.children, - result = isSingle ? null : []; - for (var i = 0, l = nodes.length; i < l; i++) { - if (tools.apply(filter, [nodes[i], invokeParam], false)) { - if (isSingle) {return nodes[i];} - result.push(nodes[i]); - } - var tmpResult = data.getNodesByFilter(setting, nodes[i][childKey], filter, isSingle, invokeParam); - if (isSingle && !!tmpResult) {return tmpResult;} - result = isSingle ? tmpResult : result.concat(tmpResult); - } - return result; - }, - getPreNode: function(setting, node) { - if (!node) return null; - var childKey = setting.data.key.children, - p = node.parentTId ? node.getParentNode() : data.getRoot(setting); - for (var i=0, l=p[childKey].length; i 0))); - }, - clone: function (obj){ - if (obj === null) return null; - var o = tools.isArray(obj) ? [] : {}; - for(var i in obj){ - o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]); - } - return o; - }, - eqs: function(str1, str2) { - return str1.toLowerCase() === str2.toLowerCase(); - }, - isArray: function(arr) { - return Object.prototype.toString.apply(arr) === "[object Array]"; - }, - $: function(node, exp, setting) { - if (!!exp && typeof exp != "string") { - setting = exp; - exp = ""; - } - if (typeof node == "string") { - return $(node, setting ? setting.treeObj.get(0).ownerDocument : null); - } else { - return $("#" + node.tId + exp, setting ? setting.treeObj : null); - } - }, - getMDom: function (setting, curDom, targetExpr) { - if (!curDom) return null; - while (curDom && curDom.id !== setting.treeId) { - for (var i=0, l=targetExpr.length; curDom.tagName && i 0 ); - }, - uCanDo: function(setting, e) { - return true; - } - }, - //method of operate ztree dom - view = { - addNodes: function(setting, parentNode, newNodes, isSilent) { - if (setting.data.keep.leaf && parentNode && !parentNode.isParent) { - return; - } - if (!tools.isArray(newNodes)) { - newNodes = [newNodes]; - } - if (setting.data.simpleData.enable) { - newNodes = data.transformTozTreeFormat(setting, newNodes); - } - if (parentNode) { - var target_switchObj = $$(parentNode, consts.id.SWITCH, setting), - target_icoObj = $$(parentNode, consts.id.ICON, setting), - target_ulObj = $$(parentNode, consts.id.UL, setting); - - if (!parentNode.open) { - view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE); - view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); - parentNode.open = false; - target_ulObj.css({ - "display": "none" - }); - } - - data.addNodesData(setting, parentNode, newNodes); - view.createNodes(setting, parentNode.level + 1, newNodes, parentNode); - if (!isSilent) { - view.expandCollapseParentNode(setting, parentNode, true); - } - } else { - data.addNodesData(setting, data.getRoot(setting), newNodes); - view.createNodes(setting, 0, newNodes, null); - } - }, - appendNodes: function(setting, level, nodes, parentNode, initFlag, openFlag) { - if (!nodes) return []; - var html = [], - childKey = setting.data.key.children; - for (var i = 0, l = nodes.length; i < l; i++) { - var node = nodes[i]; - if (initFlag) { - var tmpPNode = (parentNode) ? parentNode: data.getRoot(setting), - tmpPChild = tmpPNode[childKey], - isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)), - isLastNode = (i == (nodes.length - 1)); - data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); - data.addNodeCache(setting, node); - } - - var childHtml = []; - if (node[childKey] && node[childKey].length > 0) { - //make child html first, because checkType - childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open); - } - if (openFlag) { - - view.makeDOMNodeMainBefore(html, setting, node); - view.makeDOMNodeLine(html, setting, node); - data.getBeforeA(setting, node, html); - view.makeDOMNodeNameBefore(html, setting, node); - data.getInnerBeforeA(setting, node, html); - view.makeDOMNodeIcon(html, setting, node); - data.getInnerAfterA(setting, node, html); - view.makeDOMNodeNameAfter(html, setting, node); - data.getAfterA(setting, node, html); - if (node.isParent && node.open) { - view.makeUlHtml(setting, node, html, childHtml.join('')); - } - view.makeDOMNodeMainAfter(html, setting, node); - data.addCreatedNode(setting, node); - } - } - return html; - }, - appendParentULDom: function(setting, node) { - var html = [], - nObj = $$(node, setting); - if (!nObj.get(0) && !!node.parentTId) { - view.appendParentULDom(setting, node.getParentNode()); - nObj = $$(node, setting); - } - var ulObj = $$(node, consts.id.UL, setting); - if (ulObj.get(0)) { - ulObj.remove(); - } - var childKey = setting.data.key.children, - childHtml = view.appendNodes(setting, node.level+1, node[childKey], node, false, true); - view.makeUlHtml(setting, node, html, childHtml.join('')); - nObj.append(html.join('')); - }, - asyncNode: function(setting, node, isSilent, callback) { - var i, l; - if (node && !node.isParent) { - tools.apply(callback); - return false; - } else if (node && node.isAjaxing) { - return false; - } else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) { - tools.apply(callback); - return false; - } - if (node) { - node.isAjaxing = true; - var icoObj = $$(node, consts.id.ICON, setting); - icoObj.attr({"style":"", "class":consts.className.BUTTON + " " + consts.className.ICO_LOADING}); - } - - var tmpParam = {}; - for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) { - var pKey = setting.async.autoParam[i].split("="), spKey = pKey; - if (pKey.length>1) { - spKey = pKey[1]; - pKey = pKey[0]; - } - tmpParam[spKey] = node[pKey]; - } - if (tools.isArray(setting.async.otherParam)) { - for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) { - tmpParam[setting.async.otherParam[i]] = setting.async.otherParam[i + 1]; - } - } else { - for (var p in setting.async.otherParam) { - tmpParam[p] = setting.async.otherParam[p]; - } - } - - var _tmpV = data.getRoot(setting)._ver; - $.ajax({ - contentType: setting.async.contentType, - cache: false, - type: setting.async.type, - url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), - data: tmpParam, - dataType: setting.async.dataType, - success: function(msg) { - if (_tmpV != data.getRoot(setting)._ver) { - return; - } - var newNodes = []; - try { - if (!msg || msg.length == 0) { - newNodes = []; - } else if (typeof msg == "string") { - newNodes = eval("(" + msg + ")"); - } else { - newNodes = msg; - } - } catch(err) { - newNodes = msg; - } - - if (node) { - node.isAjaxing = null; - node.zAsync = true; - } - view.setNodeLineIcos(setting, node); - if (newNodes && newNodes !== "") { - newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); - view.addNodes(setting, node, !!newNodes ? tools.clone(newNodes) : [], !!isSilent); - } else { - view.addNodes(setting, node, [], !!isSilent); - } - setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]); - tools.apply(callback); - }, - error: function(XMLHttpRequest, textStatus, errorThrown) { - if (_tmpV != data.getRoot(setting)._ver) { - return; - } - if (node) node.isAjaxing = null; - view.setNodeLineIcos(setting, node); - setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); - } - }); - return true; - }, - cancelPreSelectedNode: function (setting, node, excludeNode) { - var list = data.getRoot(setting).curSelectedList, - i, n; - for (i=list.length-1; i>=0; i--) { - n = list[i]; - if (node === n || (!node && (!excludeNode || excludeNode !== n))) { - $$(n, consts.id.A, setting).removeClass(consts.node.CURSELECTED); - if (node) { - data.removeSelectedNode(setting, node); - setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); - break; - } else { - list.splice(i, 1); - setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); - } - } - } - }, - createNodeCallback: function(setting) { - if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { - var root = data.getRoot(setting); - while (root.createdNodes.length>0) { - var node = root.createdNodes.shift(); - tools.apply(setting.view.addDiyDom, [setting.treeId, node]); - if (!!setting.callback.onNodeCreated) { - setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]); - } - } - } - }, - createNodes: function(setting, level, nodes, parentNode) { - if (!nodes || nodes.length == 0) return; - var root = data.getRoot(setting), - childKey = setting.data.key.children, - openFlag = !parentNode || parentNode.open || !!$$(parentNode[childKey][0], setting).get(0); - root.createdNodes = []; - var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag); - if (!parentNode) { - setting.treeObj.append(zTreeHtml.join('')); - } else { - var ulObj = $$(parentNode, consts.id.UL, setting); - if (ulObj.get(0)) { - ulObj.append(zTreeHtml.join('')); - } - } - view.createNodeCallback(setting); - }, - destroy: function(setting) { - if (!setting) return; - data.initCache(setting); - data.initRoot(setting); - event.unbindTree(setting); - event.unbindEvent(setting); - setting.treeObj.empty(); - delete settings[setting.treeId]; - }, - expandCollapseNode: function(setting, node, expandFlag, animateFlag, callback) { - var root = data.getRoot(setting), - childKey = setting.data.key.children; - if (!node) { - tools.apply(callback, []); - return; - } - if (root.expandTriggerFlag) { - var _callback = callback; - callback = function(){ - if (_callback) _callback(); - if (node.open) { - setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]); - } else { - setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]); - } - }; - root.expandTriggerFlag = false; - } - if (!node.open && node.isParent && ((!$$(node, consts.id.UL, setting).get(0)) || (node[childKey] && node[childKey].length>0 && !$$(node[childKey][0], setting).get(0)))) { - view.appendParentULDom(setting, node); - view.createNodeCallback(setting); - } - if (node.open == expandFlag) { - tools.apply(callback, []); - return; - } - var ulObj = $$(node, consts.id.UL, setting), - switchObj = $$(node, consts.id.SWITCH, setting), - icoObj = $$(node, consts.id.ICON, setting); - - if (node.isParent) { - node.open = !node.open; - if (node.iconOpen && node.iconClose) { - icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); - } - - if (node.open) { - view.replaceSwitchClass(node, switchObj, consts.folder.OPEN); - view.replaceIcoClass(node, icoObj, consts.folder.OPEN); - if (animateFlag == false || setting.view.expandSpeed == "") { - ulObj.show(); - tools.apply(callback, []); - } else { - if (node[childKey] && node[childKey].length > 0) { - ulObj.slideDown(setting.view.expandSpeed, callback); - } else { - ulObj.show(); - tools.apply(callback, []); - } - } - } else { - view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); - view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); - if (animateFlag == false || setting.view.expandSpeed == "" || !(node[childKey] && node[childKey].length > 0)) { - ulObj.hide(); - tools.apply(callback, []); - } else { - ulObj.slideUp(setting.view.expandSpeed, callback); - } - } - } else { - tools.apply(callback, []); - } - }, - expandCollapseParentNode: function(setting, node, expandFlag, animateFlag, callback) { - if (!node) return; - if (!node.parentTId) { - view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback); - return; - } else { - view.expandCollapseNode(setting, node, expandFlag, animateFlag); - } - if (node.parentTId) { - view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback); - } - }, - expandCollapseSonNode: function(setting, node, expandFlag, animateFlag, callback) { - var root = data.getRoot(setting), - childKey = setting.data.key.children, - treeNodes = (node) ? node[childKey]: root[childKey], - selfAnimateSign = (node) ? false : animateFlag, - expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; - data.getRoot(setting).expandTriggerFlag = false; - if (treeNodes) { - for (var i = 0, l = treeNodes.length; i < l; i++) { - if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); - } - } - data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; - view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback ); - }, - isSelectedNode: function (setting, node) { - if (!node) { - return false; - } - var list = data.getRoot(setting).curSelectedList, - i; - for (i=list.length-1; i>=0; i--) { - if (node === list[i]) { - return true; - } - } - return false; - }, - makeDOMNodeIcon: function(html, setting, node) { - var nameStr = data.getNodeName(setting, node), - name = setting.view.nameIsHTML ? nameStr : nameStr.replace(/&/g,'&').replace(//g,'>'); - html.push("",name,""); - }, - makeDOMNodeLine: function(html, setting, node) { - html.push(""); - }, - makeDOMNodeMainAfter: function(html, setting, node) { - html.push("
  • "); - }, - makeDOMNodeMainBefore: function(html, setting, node) { - html.push("
  • "); - }, - makeDOMNodeNameAfter: function(html, setting, node) { - html.push(""); - }, - makeDOMNodeNameBefore: function(html, setting, node) { - var title = data.getNodeTitle(setting, node), - url = view.makeNodeUrl(setting, node), - fontcss = view.makeNodeFontCss(setting, node), - fontStyle = []; - for (var f in fontcss) { - fontStyle.push(f, ":", fontcss[f], ";"); - } - html.push(" 0) ? "href='" + url + "'" : ""), " target='",view.makeNodeTarget(node),"' style='", fontStyle.join(''), - "'"); - if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && title) {html.push("title='", title.replace(/'/g,"'").replace(//g,'>'),"'");} - html.push(">"); - }, - makeNodeFontCss: function(setting, node) { - var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); - return (fontCss && ((typeof fontCss) != "function")) ? fontCss : {}; - }, - makeNodeIcoClass: function(setting, node) { - var icoCss = ["ico"]; - if (!node.isAjaxing) { - icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0]; - if (node.isParent) { - icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); - } else { - icoCss.push(consts.folder.DOCU); - } - } - return consts.className.BUTTON + " " + icoCss.join('_'); - }, - makeNodeIcoStyle: function(setting, node) { - var icoStyle = []; - if (!node.isAjaxing) { - var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon; - if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); - if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { - icoStyle.push("width:0px;height:0px;"); - } - } - return icoStyle.join(''); - }, - makeNodeLineClass: function(setting, node) { - var lineClass = []; - if (setting.view.showLine) { - if (node.level == 0 && node.isFirstNode && node.isLastNode) { - lineClass.push(consts.line.ROOT); - } else if (node.level == 0 && node.isFirstNode) { - lineClass.push(consts.line.ROOTS); - } else if (node.isLastNode) { - lineClass.push(consts.line.BOTTOM); - } else { - lineClass.push(consts.line.CENTER); - } - } else { - lineClass.push(consts.line.NOLINE); - } - if (node.isParent) { - lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); - } else { - lineClass.push(consts.folder.DOCU); - } - return view.makeNodeLineClassEx(node) + lineClass.join('_'); - }, - makeNodeLineClassEx: function(node) { - return consts.className.BUTTON + " " + consts.className.LEVEL + node.level + " " + consts.className.SWITCH + " "; - }, - makeNodeTarget: function(node) { - return (node.target || "_blank"); - }, - makeNodeUrl: function(setting, node) { - var urlKey = setting.data.key.url; - return node[urlKey] ? node[urlKey] : null; - }, - makeUlHtml: function(setting, node, html, content) { - html.push("
      "); - html.push(content); - html.push("
    "); - }, - makeUlLineClass: function(setting, node) { - return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : ""); - }, - removeChildNodes: function(setting, node) { - if (!node) return; - var childKey = setting.data.key.children, - nodes = node[childKey]; - if (!nodes) return; - - for (var i = 0, l = nodes.length; i < l; i++) { - data.removeNodeCache(setting, nodes[i]); - } - data.removeSelectedNode(setting); - delete node[childKey]; - - if (!setting.data.keep.parent) { - node.isParent = false; - node.open = false; - var tmp_switchObj = $$(node, consts.id.SWITCH, setting), - tmp_icoObj = $$(node, consts.id.ICON, setting); - view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU); - view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU); - $$(node, consts.id.UL, setting).remove(); - } else { - $$(node, consts.id.UL, setting).empty(); - } - }, - setFirstNode: function(setting, parentNode) { - var childKey = setting.data.key.children, childLength = parentNode[childKey].length; - if ( childLength > 0) { - parentNode[childKey][0].isFirstNode = true; - } - }, - setLastNode: function(setting, parentNode) { - var childKey = setting.data.key.children, childLength = parentNode[childKey].length; - if ( childLength > 0) { - parentNode[childKey][childLength - 1].isLastNode = true; - } - }, - removeNode: function(setting, node) { - var root = data.getRoot(setting), - childKey = setting.data.key.children, - parentNode = (node.parentTId) ? node.getParentNode() : root; - - node.isFirstNode = false; - node.isLastNode = false; - node.getPreNode = function() {return null;}; - node.getNextNode = function() {return null;}; - - if (!data.getNodeCache(setting, node.tId)) { - return; - } - - $$(node, setting).remove(); - data.removeNodeCache(setting, node); - data.removeSelectedNode(setting, node); - - for (var i = 0, l = parentNode[childKey].length; i < l; i++) { - if (parentNode[childKey][i].tId == node.tId) { - parentNode[childKey].splice(i, 1); - break; - } - } - view.setFirstNode(setting, parentNode); - view.setLastNode(setting, parentNode); - - var tmp_ulObj,tmp_switchObj,tmp_icoObj, - childLength = parentNode[childKey].length; - - //repair nodes old parent - if (!setting.data.keep.parent && childLength == 0) { - //old parentNode has no child nodes - parentNode.isParent = false; - parentNode.open = false; - tmp_ulObj = $$(parentNode, consts.id.UL, setting); - tmp_switchObj = $$(parentNode, consts.id.SWITCH, setting); - tmp_icoObj = $$(parentNode, consts.id.ICON, setting); - view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU); - view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU); - tmp_ulObj.css("display", "none"); - - } else if (setting.view.showLine && childLength > 0) { - //old parentNode has child nodes - var newLast = parentNode[childKey][childLength - 1]; - tmp_ulObj = $$(newLast, consts.id.UL, setting); - tmp_switchObj = $$(newLast, consts.id.SWITCH, setting); - tmp_icoObj = $$(newLast, consts.id.ICON, setting); - if (parentNode == root) { - if (parentNode[childKey].length == 1) { - //node was root, and ztree has only one root after move node - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT); - } else { - var tmp_first_switchObj = $$(parentNode[childKey][0], consts.id.SWITCH, setting); - view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS); - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); - } - } else { - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); - } - tmp_ulObj.removeClass(consts.line.LINE); - } - }, - replaceIcoClass: function(node, obj, newName) { - if (!obj || node.isAjaxing) return; - var tmpName = obj.attr("class"); - if (tmpName == undefined) return; - var tmpList = tmpName.split("_"); - switch (newName) { - case consts.folder.OPEN: - case consts.folder.CLOSE: - case consts.folder.DOCU: - tmpList[tmpList.length-1] = newName; - break; - } - obj.attr("class", tmpList.join("_")); - }, - replaceSwitchClass: function(node, obj, newName) { - if (!obj) return; - var tmpName = obj.attr("class"); - if (tmpName == undefined) return; - var tmpList = tmpName.split("_"); - switch (newName) { - case consts.line.ROOT: - case consts.line.ROOTS: - case consts.line.CENTER: - case consts.line.BOTTOM: - case consts.line.NOLINE: - tmpList[0] = view.makeNodeLineClassEx(node) + newName; - break; - case consts.folder.OPEN: - case consts.folder.CLOSE: - case consts.folder.DOCU: - tmpList[1] = newName; - break; - } - obj.attr("class", tmpList.join("_")); - if (newName !== consts.folder.DOCU) { - obj.removeAttr("disabled"); - } else { - obj.attr("disabled", "disabled"); - } - }, - selectNode: function(setting, node, addFlag) { - if (!addFlag) { - view.cancelPreSelectedNode(setting, null, node); - } - $$(node, consts.id.A, setting).addClass(consts.node.CURSELECTED); - data.addSelectedNode(setting, node); - setting.treeObj.trigger(consts.event.SELECTED, [event, setting.treeId, node]); - }, - setNodeFontCss: function(setting, treeNode) { - var aObj = $$(treeNode, consts.id.A, setting), - fontCss = view.makeNodeFontCss(setting, treeNode); - if (fontCss) { - aObj.css(fontCss); - } - }, - setNodeLineIcos: function(setting, node) { - if (!node) return; - var switchObj = $$(node, consts.id.SWITCH, setting), - ulObj = $$(node, consts.id.UL, setting), - icoObj = $$(node, consts.id.ICON, setting), - ulLine = view.makeUlLineClass(setting, node); - if (ulLine.length==0) { - ulObj.removeClass(consts.line.LINE); - } else { - ulObj.addClass(ulLine); - } - switchObj.attr("class", view.makeNodeLineClass(setting, node)); - if (node.isParent) { - switchObj.removeAttr("disabled"); - } else { - switchObj.attr("disabled", "disabled"); - } - icoObj.removeAttr("style"); - icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); - icoObj.attr("class", view.makeNodeIcoClass(setting, node)); - }, - setNodeName: function(setting, node) { - var title = data.getNodeTitle(setting, node), - nObj = $$(node, consts.id.SPAN, setting); - nObj.empty(); - if (setting.view.nameIsHTML) { - nObj.html(data.getNodeName(setting, node)); - } else { - nObj.text(data.getNodeName(setting, node)); - } - if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle)) { - var aObj = $$(node, consts.id.A, setting); - aObj.attr("title", !title ? "" : title); - } - }, - setNodeTarget: function(setting, node) { - var aObj = $$(node, consts.id.A, setting); - aObj.attr("target", view.makeNodeTarget(node)); - }, - setNodeUrl: function(setting, node) { - var aObj = $$(node, consts.id.A, setting), - url = view.makeNodeUrl(setting, node); - if (url == null || url.length == 0) { - aObj.removeAttr("href"); - } else { - aObj.attr("href", url); - } - }, - switchNode: function(setting, node) { - if (node.open || !tools.canAsync(setting, node)) { - view.expandCollapseNode(setting, node, !node.open); - } else if (setting.async.enable) { - if (!view.asyncNode(setting, node)) { - view.expandCollapseNode(setting, node, !node.open); - return; - } - } else if (node) { - view.expandCollapseNode(setting, node, !node.open); - } - } - }; - // zTree defind - $.fn.zTree = { - consts : _consts, - _z : { - tools: tools, - view: view, - event: event, - data: data - }, - getZTreeObj: function(treeId) { - var o = data.getZTreeTools(treeId); - return o ? o : null; - }, - destroy: function(treeId) { - if (!!treeId && treeId.length > 0) { - view.destroy(data.getSetting(treeId)); - } else { - for(var s in settings) { - view.destroy(settings[s]); - } - } - }, - init: function(obj, zSetting, zNodes) { - var setting = tools.clone(_setting); - $.extend(true, setting, zSetting); - setting.treeId = obj.attr("id"); - setting.treeObj = obj; - setting.treeObj.empty(); - settings[setting.treeId] = setting; - //For some older browser,(e.g., ie6) - if(typeof document.body.style.maxHeight === "undefined") { - setting.view.expandSpeed = ""; - } - data.initRoot(setting); - var root = data.getRoot(setting), - childKey = setting.data.key.children; - zNodes = zNodes ? tools.clone(tools.isArray(zNodes)? zNodes : [zNodes]) : []; - if (setting.data.simpleData.enable) { - root[childKey] = data.transformTozTreeFormat(setting, zNodes); - } else { - root[childKey] = zNodes; - } - - data.initCache(setting); - event.unbindTree(setting); - event.bindTree(setting); - event.unbindEvent(setting); - event.bindEvent(setting); - - var zTreeTools = { - setting : setting, - addNodes : function(parentNode, newNodes, isSilent) { - if (!newNodes) return null; - if (!parentNode) parentNode = null; - if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null; - var xNewNodes = tools.clone(tools.isArray(newNodes)? newNodes: [newNodes]); - function addCallback() { - view.addNodes(setting, parentNode, xNewNodes, (isSilent==true)); - } - - if (tools.canAsync(setting, parentNode)) { - view.asyncNode(setting, parentNode, isSilent, addCallback); - } else { - addCallback(); - } - return xNewNodes; - }, - cancelSelectedNode : function(node) { - view.cancelPreSelectedNode(setting, node); - }, - destroy : function() { - view.destroy(setting); - }, - expandAll : function(expandFlag) { - expandFlag = !!expandFlag; - view.expandCollapseSonNode(setting, null, expandFlag, true); - return expandFlag; - }, - expandNode : function(node, expandFlag, sonSign, focus, callbackFlag) { - if (!node || !node.isParent) return null; - if (expandFlag !== true && expandFlag !== false) { - expandFlag = !node.open; - } - callbackFlag = !!callbackFlag; - - if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) { - return null; - } else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) { - return null; - } - if (expandFlag && node.parentTId) { - view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, false); - } - if (expandFlag === node.open && !sonSign) { - return null; - } - - data.getRoot(setting).expandTriggerFlag = callbackFlag; - if (!tools.canAsync(setting, node) && sonSign) { - view.expandCollapseSonNode(setting, node, expandFlag, true, function() { - if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e){}} - }); - } else { - node.open = !expandFlag; - view.switchNode(this.setting, node); - if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e){}} - } - return expandFlag; - }, - getNodes : function() { - return data.getNodes(setting); - }, - getNodeByParam : function(key, value, parentNode) { - if (!key) return null; - return data.getNodeByParam(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodeByTId : function(tId) { - return data.getNodeCache(setting, tId); - }, - getNodesByParam : function(key, value, parentNode) { - if (!key) return null; - return data.getNodesByParam(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodesByParamFuzzy : function(key, value, parentNode) { - if (!key) return null; - return data.getNodesByParamFuzzy(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodesByFilter: function(filter, isSingle, parentNode, invokeParam) { - isSingle = !!isSingle; - if (!filter || (typeof filter != "function")) return (isSingle ? null : []); - return data.getNodesByFilter(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), filter, isSingle, invokeParam); - }, - getNodeIndex : function(node) { - if (!node) return null; - var childKey = setting.data.key.children, - parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); - for (var i=0, l = parentNode[childKey].length; i < l; i++) { - if (parentNode[childKey][i] == node) return i; - } - return -1; - }, - getSelectedNodes : function() { - var r = [], list = data.getRoot(setting).curSelectedList; - for (var i=0, l=list.length; i 0) { - view.createNodes(setting, 0, root[childKey]); - } else if (setting.async.enable && setting.async.url && setting.async.url !== '') { - view.asyncNode(setting); - } - return zTreeTools; - } - }; - - var zt = $.fn.zTree, - $$ = tools.$, - consts = zt.consts; + if (root[childKey] && root[childKey].length > 0) { + view.createNodes(setting, 0, root[childKey]); + } else if (setting.async.enable && setting.async.url && setting.async.url !== "") { + view.asyncNode(setting); + } + return zTreeTools; + } + }; + + var zt = $.fn.zTree, + $$ = tools.$, + consts = zt.consts; })(jQuery);/* * JQuery zTree excheck v3.5.18 * http://zTree.me/ @@ -61473,621 +61309,621 @@ BI.shortcut("bi.custom_tree", BI.CustomTree);/* * email: hunter.z@263.net * Date: 2015-06-18 */ -(function($){ - //default consts of excheck - var _consts = { - event: { - CHECK: "ztree_check" - }, - id: { - CHECK: "_check" - }, - checkbox: { - STYLE: "checkbox", - DEFAULT: "chk", - DISABLED: "disable", - FALSE: "false", - TRUE: "true", - FULL: "full", - PART: "part", - FOCUS: "focus" - }, - radio: { - STYLE: "radio", - TYPE_ALL: "all", - TYPE_LEVEL: "level" - } - }, - //default setting of excheck - _setting = { - check: { - enable: false, - autoCheckTrigger: false, - chkStyle: _consts.checkbox.STYLE, - nocheckInherit: false, - chkDisabledInherit: false, - radioType: _consts.radio.TYPE_LEVEL, - chkboxType: { - "Y": "ps", - "N": "ps" - } - }, - data: { - key: { - checked: "checked" - } - }, - callback: { - beforeCheck:null, - onCheck:null - } - }, - //default root of excheck - _initRoot = function (setting) { - var r = data.getRoot(setting); - r.radioCheckedList = []; - }, - //default cache of excheck - _initCache = function(treeId) {}, - //default bind event of excheck - _bindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.bind(c.CHECK, function (event, srcEvent, treeId, node) { - event.srcEvent = srcEvent; - tools.apply(setting.callback.onCheck, [event, treeId, node]); - }); - }, - _unbindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.unbind(c.CHECK); - }, - //default event proxy of excheck - _eventProxy = function(e) { - var target = e.target, - setting = data.getSetting(e.data.treeId), - tId = "", node = null, - nodeEventType = "", treeEventType = "", - nodeEventCallback = null, treeEventCallback = null; - - if (tools.eqs(e.type, "mouseover")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "mouseoverCheck"; - } - } else if (tools.eqs(e.type, "mouseout")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "mouseoutCheck"; - } - } else if (tools.eqs(e.type, "click")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "checkNode"; - } - } - if (tId.length>0) { - node = data.getNodeCache(setting, tId); - switch (nodeEventType) { - case "checkNode" : - nodeEventCallback = _handler.onCheckNode; - break; - case "mouseoverCheck" : - nodeEventCallback = _handler.onMouseoverCheck; - break; - case "mouseoutCheck" : - nodeEventCallback = _handler.onMouseoutCheck; - break; - } - } - var proxyResult = { - stop: nodeEventType === "checkNode", - node: node, - nodeEventType: nodeEventType, - nodeEventCallback: nodeEventCallback, - treeEventType: treeEventType, - treeEventCallback: treeEventCallback - }; - return proxyResult - }, - //default init node of excheck - _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { - if (!n) return; - var checkedKey = setting.data.key.checked; - if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); - n[checkedKey] = !!n[checkedKey]; - n.checkedOld = n[checkedKey]; - if (typeof n.nocheck == "string") n.nocheck = tools.eqs(n.nocheck, "true"); - n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); - if (typeof n.chkDisabled == "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); - n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); - if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); - n.halfCheck = !!n.halfCheck; - n.check_Child_State = -1; - n.check_Focus = false; - n.getCheckStatus = function() {return data.getCheckStatus(setting, n);}; - - if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey] ) { - var r = data.getRoot(setting); - r.radioCheckedList.push(n); - } - }, - //add dom for check - _beforeA = function(setting, node, html) { - var checkedKey = setting.data.key.checked; - if (setting.check.enable) { - data.makeChkFlag(setting, node); - html.push(""); - } - }, - //update zTreeObj, add method of check - _zTreeTools = function(setting, zTreeTools) { - zTreeTools.checkNode = function(node, checked, checkTypeFlag, callbackFlag) { - var checkedKey = this.setting.data.key.checked; - if (node.chkDisabled === true) return; - if (checked !== true && checked !== false) { - checked = !node[checkedKey]; - } - callbackFlag = !!callbackFlag; - - if (node[checkedKey] === checked && !checkTypeFlag) { - return; - } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { - return; - } - if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { - node[checkedKey] = checked; - var checkObj = $$(node, consts.id.CHECK, this.setting); - if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); - view.setChkClass(this.setting, checkObj, node); - view.repairParentChkClassWithSelf(this.setting, node); - if (callbackFlag) { - this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); - } - } - } - - zTreeTools.checkAllNodes = function(checked) { - view.repairAllChk(this.setting, !!checked); - } - - zTreeTools.getCheckedNodes = function(checked) { - var childKey = this.setting.data.key.children; - checked = (checked !== false); - return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); - } - - zTreeTools.getChangeCheckedNodes = function() { - var childKey = this.setting.data.key.children; - return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); - } - - zTreeTools.setChkDisabled = function(node, disabled, inheritParent, inheritChildren) { - disabled = !!disabled; - inheritParent = !!inheritParent; - inheritChildren = !!inheritChildren; - view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); - view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); - } - - var _updateNode = zTreeTools.updateNode; - zTreeTools.updateNode = function(node, checkTypeFlag) { - if (_updateNode) _updateNode.apply(zTreeTools, arguments); - if (!node || !this.setting.check.enable) return; - var nObj = $$(node, this.setting); - if (nObj.get(0) && tools.uCanDo(this.setting)) { - var checkObj = $$(node, consts.id.CHECK, this.setting); - if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); - view.setChkClass(this.setting, checkObj, node); - view.repairParentChkClassWithSelf(this.setting, node); - } - } - }, - //method of operate data - _data = { - getRadioCheckedList: function(setting) { - var checkedList = data.getRoot(setting).radioCheckedList; - for (var i=0, j=checkedList.length; i -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) - }; - return r; - }, - getTreeCheckedNodes: function(setting, nodes, checked, results) { - if (!nodes) return []; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); - results = !results ? [] : results; - for (var i = 0, l = nodes.length; i < l; i++) { - if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { - results.push(nodes[i]); - if(onlyOne) { - break; - } - } - data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); - if(onlyOne && results.length > 0) { - break; - } - } - return results; - }, - getTreeChangeCheckedNodes: function(setting, nodes, results) { - if (!nodes) return []; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked; - results = !results ? [] : results; - for (var i = 0, l = nodes.length; i < l; i++) { - if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { - results.push(nodes[i]); - } - data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); - } - return results; - }, - makeChkFlag: function(setting, node) { - if (!node) return; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - chkFlag = -1; - if (node[childKey]) { - for (var i = 0, l = node[childKey].length; i < l; i++) { - var cNode = node[childKey][i]; - var tmp = -1; - if (setting.check.chkStyle == consts.radio.STYLE) { - if (cNode.nocheck === true || cNode.chkDisabled === true) { - tmp = cNode.check_Child_State; - } else if (cNode.halfCheck === true) { - tmp = 2; - } else if (cNode[checkedKey]) { - tmp = 2; - } else { - tmp = cNode.check_Child_State > 0 ? 2:0; - } - if (tmp == 2) { - chkFlag = 2; break; - } else if (tmp == 0){ - chkFlag = 0; - } - } else if (setting.check.chkStyle == consts.checkbox.STYLE) { - if (cNode.nocheck === true || cNode.chkDisabled === true) { - tmp = cNode.check_Child_State; - } else if (cNode.halfCheck === true) { - tmp = 1; - } else if (cNode[checkedKey] ) { - tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; - } else { - tmp = (cNode.check_Child_State > 0) ? 1 : 0; - } - if (tmp === 1) { - chkFlag = 1; break; - } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { - chkFlag = 1; break; - } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { - chkFlag = 1; break; - } else if (tmp > -1) { - chkFlag = tmp; - } - } - } - } - node.check_Child_State = chkFlag; - } - }, - //method of event proxy - _event = { - - }, - //method of event handler - _handler = { - onCheckNode: function (event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkedKey = setting.data.key.checked; - if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; - node[checkedKey] = !node[checkedKey]; - view.checkNodeRelation(setting, node); - var checkObj = $$(node, consts.id.CHECK, setting); - view.setChkClass(setting, checkObj, node); - view.repairParentChkClassWithSelf(setting, node); - setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); - return true; - }, - onMouseoverCheck: function(event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkObj = $$(node, consts.id.CHECK, setting); - node.check_Focus = true; - view.setChkClass(setting, checkObj, node); - return true; - }, - onMouseoutCheck: function(event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkObj = $$(node, consts.id.CHECK, setting); - node.check_Focus = false; - view.setChkClass(setting, checkObj, node); - return true; - } - }, - //method of tools for zTree - _tools = { - - }, - //method of operate ztree dom - _view = { - checkNodeRelation: function(setting, node) { - var pNode, i, l, - childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - r = consts.radio; - if (setting.check.chkStyle == r.STYLE) { - var checkedList = data.getRadioCheckedList(setting); - if (node[checkedKey]) { - if (setting.check.radioType == r.TYPE_ALL) { - for (i = checkedList.length-1; i >= 0; i--) { - pNode = checkedList[i]; - if (pNode[checkedKey] && pNode != node) { - pNode[checkedKey] = false; - checkedList.splice(i, 1); - - view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); - if (pNode.parentTId != node.parentTId) { - view.repairParentChkClassWithSelf(setting, pNode); - } - } - } - checkedList.push(node); - } else { - var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); - for (i = 0, l = parentNode[childKey].length; i < l; i++) { - pNode = parentNode[childKey][i]; - if (pNode[checkedKey] && pNode != node) { - pNode[checkedKey] = false; - view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); - } - } - } - } else if (setting.check.radioType == r.TYPE_ALL) { - for (i = 0, l = checkedList.length; i < l; i++) { - if (node == checkedList[i]) { - checkedList.splice(i, 1); - break; - } - } - } - - } else { - if (node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { - view.setSonNodeCheckBox(setting, node, true); - } - if (!node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.N.indexOf("s") > -1)) { - view.setSonNodeCheckBox(setting, node, false); - } - if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { - view.setParentNodeCheckBox(setting, node, true); - } - if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { - view.setParentNodeCheckBox(setting, node, false); - } - } - }, - makeChkClass: function(setting, node) { - var checkedKey = setting.data.key.checked, - c = consts.checkbox, r = consts.radio, - fullStyle = ""; - if (node.chkDisabled === true) { - fullStyle = c.DISABLED; - } else if (node.halfCheck) { - fullStyle = c.PART; - } else if (setting.check.chkStyle == r.STYLE) { - fullStyle = (node.check_Child_State < 1)? c.FULL:c.PART; - } else { - fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL:c.PART) : ((node.check_Child_State < 1)? c.FULL:c.PART); - } - var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; - chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; - return consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; - }, - repairAllChk: function(setting, checked) { - if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { - var checkedKey = setting.data.key.checked, - childKey = setting.data.key.children, - root = data.getRoot(setting); - for (var i = 0, l = root[childKey].length; i 0) { - view.repairParentChkClass(setting, node[childKey][0]); - } else { - view.repairParentChkClass(setting, node); - } - }, - repairSonChkDisabled: function(setting, node, chkDisabled, inherit) { - if (!node) return; - var childKey = setting.data.key.children; - if (node.chkDisabled != chkDisabled) { - node.chkDisabled = chkDisabled; - } - view.repairChkClass(setting, node); - if (node[childKey] && inherit) { - for (var i = 0, l = node[childKey].length; i < l; i++) { - var sNode = node[childKey][i]; - view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); - } - } - }, - repairParentChkDisabled: function(setting, node, chkDisabled, inherit) { - if (!node) return; - if (node.chkDisabled != chkDisabled && inherit) { - node.chkDisabled = chkDisabled; - } - view.repairChkClass(setting, node); - view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); - }, - setChkClass: function(setting, obj, node) { - if (!obj) return; - if (node.nocheck === true) { - obj.hide(); - } else { - obj.show(); - } - obj.attr('class', view.makeChkClass(setting, node)); - }, - setParentNodeCheckBox: function(setting, node, value, srcNode) { - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - checkObj = $$(node, consts.id.CHECK, setting); - if (!srcNode) srcNode = node; - data.makeChkFlag(setting, node); - if (node.nocheck !== true && node.chkDisabled !== true) { - node[checkedKey] = value; - view.setChkClass(setting, checkObj, node); - if (setting.check.autoCheckTrigger && node != srcNode) { - setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); - } - } - if (node.parentTId) { - var pSign = true; - if (!value) { - var pNodes = node.getParentNode()[childKey]; - for (var i = 0, l = pNodes.length; i < l; i++) { - if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) +(function ($) { + // default consts of excheck + var _consts = { + event: { + CHECK: "ztree_check" + }, + id: { + CHECK: "_check" + }, + checkbox: { + STYLE: "checkbox", + DEFAULT: "chk", + DISABLED: "disable", + FALSE: "false", + TRUE: "true", + FULL: "full", + PART: "part", + FOCUS: "focus" + }, + radio: { + STYLE: "radio", + TYPE_ALL: "all", + TYPE_LEVEL: "level" + } + }, + // default setting of excheck + _setting = { + check: { + enable: false, + autoCheckTrigger: false, + chkStyle: _consts.checkbox.STYLE, + nocheckInherit: false, + chkDisabledInherit: false, + radioType: _consts.radio.TYPE_LEVEL, + chkboxType: { + Y: "ps", + N: "ps" + } + }, + data: { + key: { + checked: "checked" + } + }, + callback: { + beforeCheck: null, + onCheck: null + } + }, + // default root of excheck + _initRoot = function (setting) { + var r = data.getRoot(setting); + r.radioCheckedList = []; + }, + // default cache of excheck + _initCache = function (treeId) {}, + // default bind event of excheck + _bindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.bind(c.CHECK, function (event, srcEvent, treeId, node) { + event.srcEvent = srcEvent; + tools.apply(setting.callback.onCheck, [event, treeId, node]); + }); + }, + _unbindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.unbind(c.CHECK); + }, + // default event proxy of excheck + _eventProxy = function (e) { + var target = e.target, + setting = data.getSetting(e.data.treeId), + tId = "", node = null, + nodeEventType = "", treeEventType = "", + nodeEventCallback = null, treeEventCallback = null; + + if (tools.eqs(e.type, "mouseover")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "mouseoverCheck"; + } + } else if (tools.eqs(e.type, "mouseout")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "mouseoutCheck"; + } + } else if (tools.eqs(e.type, "click")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "checkNode"; + } + } + if (tId.length > 0) { + node = data.getNodeCache(setting, tId); + switch (nodeEventType) { + case "checkNode" : + nodeEventCallback = _handler.onCheckNode; + break; + case "mouseoverCheck" : + nodeEventCallback = _handler.onMouseoverCheck; + break; + case "mouseoutCheck" : + nodeEventCallback = _handler.onMouseoutCheck; + break; + } + } + var proxyResult = { + stop: nodeEventType === "checkNode", + node: node, + nodeEventType: nodeEventType, + nodeEventCallback: nodeEventCallback, + treeEventType: treeEventType, + treeEventCallback: treeEventCallback + }; + return proxyResult; + }, + // default init node of excheck + _initNode = function (setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { + if (!n) return; + var checkedKey = setting.data.key.checked; + if (typeof n[checkedKey] === "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); + n[checkedKey] = !!n[checkedKey]; + n.checkedOld = n[checkedKey]; + if (typeof n.nocheck === "string") n.nocheck = tools.eqs(n.nocheck, "true"); + n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); + if (typeof n.chkDisabled === "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); + n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); + if (typeof n.halfCheck === "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); + n.halfCheck = !!n.halfCheck; + n.check_Child_State = -1; + n.check_Focus = false; + n.getCheckStatus = function () {return data.getCheckStatus(setting, n);}; + + if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey] ) { + var r = data.getRoot(setting); + r.radioCheckedList.push(n); + } + }, + // add dom for check + _beforeA = function (setting, node, html) { + var checkedKey = setting.data.key.checked; + if (setting.check.enable) { + data.makeChkFlag(setting, node); + html.push(""); + } + }, + // update zTreeObj, add method of check + _zTreeTools = function (setting, zTreeTools) { + zTreeTools.checkNode = function (node, checked, checkTypeFlag, callbackFlag) { + var checkedKey = this.setting.data.key.checked; + if (node.chkDisabled === true) return; + if (checked !== true && checked !== false) { + checked = !node[checkedKey]; + } + callbackFlag = !!callbackFlag; + + if (node[checkedKey] === checked && !checkTypeFlag) { + return; + } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { + return; + } + if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { + node[checkedKey] = checked; + var checkObj = $$(node, consts.id.CHECK, this.setting); + if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); + view.setChkClass(this.setting, checkObj, node); + view.repairParentChkClassWithSelf(this.setting, node); + if (callbackFlag) { + this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); + } + } + }; + + zTreeTools.checkAllNodes = function (checked) { + view.repairAllChk(this.setting, !!checked); + }; + + zTreeTools.getCheckedNodes = function (checked) { + var childKey = this.setting.data.key.children; + checked = (checked !== false); + return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); + }; + + zTreeTools.getChangeCheckedNodes = function () { + var childKey = this.setting.data.key.children; + return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); + }; + + zTreeTools.setChkDisabled = function (node, disabled, inheritParent, inheritChildren) { + disabled = !!disabled; + inheritParent = !!inheritParent; + inheritChildren = !!inheritChildren; + view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); + view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); + }; + + var _updateNode = zTreeTools.updateNode; + zTreeTools.updateNode = function (node, checkTypeFlag) { + if (_updateNode) _updateNode.apply(zTreeTools, arguments); + if (!node || !this.setting.check.enable) return; + var nObj = $$(node, this.setting); + if (nObj.get(0) && tools.uCanDo(this.setting)) { + var checkObj = $$(node, consts.id.CHECK, this.setting); + if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); + view.setChkClass(this.setting, checkObj, node); + view.repairParentChkClassWithSelf(this.setting, node); + } + }; + }, + // method of operate data + _data = { + getRadioCheckedList: function (setting) { + var checkedList = data.getRoot(setting).radioCheckedList; + for (var i = 0, j = checkedList.length; i < j; i++) { + if(!data.getNodeCache(setting, checkedList[i].tId)) { + checkedList.splice(i, 1); + i--; j--; + } + } + return checkedList; + }, + getCheckStatus: function (setting, node) { + if (!setting.check.enable || node.nocheck || node.chkDisabled) return null; + var checkedKey = setting.data.key.checked, + r = { + checked: node[checkedKey], + half: node.halfCheck ? node.halfCheck : (setting.check.chkStyle == consts.radio.STYLE ? (node.check_Child_State === 2) : (node[checkedKey] ? (node.check_Child_State > -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) + }; + return r; + }, + getTreeCheckedNodes: function (setting, nodes, checked, results) { + if (!nodes) return []; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); + results = !results ? [] : results; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { + results.push(nodes[i]); + if(onlyOne) { + break; + } + } + data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); + if(onlyOne && results.length > 0) { + break; + } + } + return results; + }, + getTreeChangeCheckedNodes: function (setting, nodes, results) { + if (!nodes) return []; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked; + results = !results ? [] : results; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { + results.push(nodes[i]); + } + data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); + } + return results; + }, + makeChkFlag: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + chkFlag = -1; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + var cNode = node[childKey][i]; + var tmp = -1; + if (setting.check.chkStyle == consts.radio.STYLE) { + if (cNode.nocheck === true || cNode.chkDisabled === true) { + tmp = cNode.check_Child_State; + } else if (cNode.halfCheck === true) { + tmp = 2; + } else if (cNode[checkedKey]) { + tmp = 2; + } else { + tmp = cNode.check_Child_State > 0 ? 2 : 0; + } + if (tmp == 2) { + chkFlag = 2; break; + } else if (tmp == 0) { + chkFlag = 0; + } + } else if (setting.check.chkStyle == consts.checkbox.STYLE) { + if (cNode.nocheck === true || cNode.chkDisabled === true) { + tmp = cNode.check_Child_State; + } else if (cNode.halfCheck === true) { + tmp = 1; + } else if (cNode[checkedKey] ) { + tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; + } else { + tmp = (cNode.check_Child_State > 0) ? 1 : 0; + } + if (tmp === 1) { + chkFlag = 1; break; + } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { + chkFlag = 1; break; + } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { + chkFlag = 1; break; + } else if (tmp > -1) { + chkFlag = tmp; + } + } + } + } + node.check_Child_State = chkFlag; + } + }, + // method of event proxy + _event = { + + }, + // method of event handler + _handler = { + onCheckNode: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkedKey = setting.data.key.checked; + if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; + node[checkedKey] = !node[checkedKey]; + view.checkNodeRelation(setting, node); + var checkObj = $$(node, consts.id.CHECK, setting); + view.setChkClass(setting, checkObj, node); + view.repairParentChkClassWithSelf(setting, node); + setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); + return true; + }, + onMouseoverCheck: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkObj = $$(node, consts.id.CHECK, setting); + node.check_Focus = true; + view.setChkClass(setting, checkObj, node); + return true; + }, + onMouseoutCheck: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkObj = $$(node, consts.id.CHECK, setting); + node.check_Focus = false; + view.setChkClass(setting, checkObj, node); + return true; + } + }, + // method of tools for zTree + _tools = { + + }, + // method of operate ztree dom + _view = { + checkNodeRelation: function (setting, node) { + var pNode, i, l, + childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + r = consts.radio; + if (setting.check.chkStyle == r.STYLE) { + var checkedList = data.getRadioCheckedList(setting); + if (node[checkedKey]) { + if (setting.check.radioType == r.TYPE_ALL) { + for (i = checkedList.length - 1; i >= 0; i--) { + pNode = checkedList[i]; + if (pNode[checkedKey] && pNode != node) { + pNode[checkedKey] = false; + checkedList.splice(i, 1); + + view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); + if (pNode.parentTId != node.parentTId) { + view.repairParentChkClassWithSelf(setting, pNode); + } + } + } + checkedList.push(node); + } else { + var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); + for (i = 0, l = parentNode[childKey].length; i < l; i++) { + pNode = parentNode[childKey][i]; + if (pNode[checkedKey] && pNode != node) { + pNode[checkedKey] = false; + view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); + } + } + } + } else if (setting.check.radioType == r.TYPE_ALL) { + for (i = 0, l = checkedList.length; i < l; i++) { + if (node == checkedList[i]) { + checkedList.splice(i, 1); + break; + } + } + } + + } else { + if (node[checkedKey] && (!node[childKey] || node[childKey].length == 0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { + view.setSonNodeCheckBox(setting, node, true); + } + if (!node[checkedKey] && (!node[childKey] || node[childKey].length == 0 || setting.check.chkboxType.N.indexOf("s") > -1)) { + view.setSonNodeCheckBox(setting, node, false); + } + if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { + view.setParentNodeCheckBox(setting, node, true); + } + if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { + view.setParentNodeCheckBox(setting, node, false); + } + } + }, + makeChkClass: function (setting, node) { + var checkedKey = setting.data.key.checked, + c = consts.checkbox, r = consts.radio, + fullStyle = ""; + if (node.chkDisabled === true) { + fullStyle = c.DISABLED; + } else if (node.halfCheck) { + fullStyle = c.PART; + } else if (setting.check.chkStyle == r.STYLE) { + fullStyle = (node.check_Child_State < 1) ? c.FULL : c.PART; + } else { + fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL : c.PART) : ((node.check_Child_State < 1) ? c.FULL : c.PART); + } + var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; + chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; + return consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; + }, + repairAllChk: function (setting, checked) { + if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { + var checkedKey = setting.data.key.checked, + childKey = setting.data.key.children, + root = data.getRoot(setting); + for (var i = 0, l = root[childKey].length; i < l; i++) { + var node = root[childKey][i]; + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = checked; + } + view.setSonNodeCheckBox(setting, node, checked); + } + } + }, + repairChkClass: function (setting, node) { + if (!node) return; + data.makeChkFlag(setting, node); + if (node.nocheck !== true) { + var checkObj = $$(node, consts.id.CHECK, setting); + view.setChkClass(setting, checkObj, node); + } + }, + repairParentChkClass: function (setting, node) { + if (!node || !node.parentTId) return; + var pNode = node.getParentNode(); + view.repairChkClass(setting, pNode); + view.repairParentChkClass(setting, pNode); + }, + repairParentChkClassWithSelf: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children; + if (node[childKey] && node[childKey].length > 0) { + view.repairParentChkClass(setting, node[childKey][0]); + } else { + view.repairParentChkClass(setting, node); + } + }, + repairSonChkDisabled: function (setting, node, chkDisabled, inherit) { + if (!node) return; + var childKey = setting.data.key.children; + if (node.chkDisabled != chkDisabled) { + node.chkDisabled = chkDisabled; + } + view.repairChkClass(setting, node); + if (node[childKey] && inherit) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + var sNode = node[childKey][i]; + view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); + } + } + }, + repairParentChkDisabled: function (setting, node, chkDisabled, inherit) { + if (!node) return; + if (node.chkDisabled != chkDisabled && inherit) { + node.chkDisabled = chkDisabled; + } + view.repairChkClass(setting, node); + view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); + }, + setChkClass: function (setting, obj, node) { + if (!obj) return; + if (node.nocheck === true) { + obj.hide(); + } else { + obj.show(); + } + obj.attr("class", view.makeChkClass(setting, node)); + }, + setParentNodeCheckBox: function (setting, node, value, srcNode) { + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + checkObj = $$(node, consts.id.CHECK, setting); + if (!srcNode) srcNode = node; + data.makeChkFlag(setting, node); + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = value; + view.setChkClass(setting, checkObj, node); + if (setting.check.autoCheckTrigger && node != srcNode) { + setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + } + } + if (node.parentTId) { + var pSign = true; + if (!value) { + var pNodes = node.getParentNode()[childKey]; + for (var i = 0, l = pNodes.length; i < l; i++) { + if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) || ((pNodes[i].nocheck === true || pNodes[i].chkDisabled === true) && pNodes[i].check_Child_State > 0)) { - pSign = false; - break; - } - } - } - if (pSign) { - view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); - } - } - }, - setSonNodeCheckBox: function(setting, node, value, srcNode) { - if (!node) return; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - checkObj = $$(node, consts.id.CHECK, setting); - if (!srcNode) srcNode = node; - - var hasDisable = false; - if (node[childKey]) { - for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { - var sNode = node[childKey][i]; - view.setSonNodeCheckBox(setting, sNode, value, srcNode); - if (sNode.chkDisabled === true) hasDisable = true; - } - } - - if (node != data.getRoot(setting) && node.chkDisabled !== true) { - if (hasDisable && node.nocheck !== true) { - data.makeChkFlag(setting, node); - } - if (node.nocheck !== true && node.chkDisabled !== true) { - node[checkedKey] = value; - if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; - } else { - node.check_Child_State = -1; - } - view.setChkClass(setting, checkObj, node); - if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { - setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); - } - } - - } - }, - - _z = { - tools: _tools, - view: _view, - event: _event, - data: _data - }; - $.extend(true, $.fn.zTree.consts, _consts); - $.extend(true, $.fn.zTree._z, _z); - - var zt = $.fn.zTree, - tools = zt._z.tools, - consts = zt.consts, - view = zt._z.view, - data = zt._z.data, - event = zt._z.event, - $$ = tools.$; - - data.exSetting(_setting); - data.addInitBind(_bindEvent); - data.addInitUnBind(_unbindEvent); - data.addInitCache(_initCache); - data.addInitNode(_initNode); - data.addInitProxy(_eventProxy, true); - data.addInitRoot(_initRoot); - data.addBeforeA(_beforeA); - data.addZTreeTools(_zTreeTools); - - var _createNodes = view.createNodes; - view.createNodes = function(setting, level, nodes, parentNode) { - if (_createNodes) _createNodes.apply(view, arguments); - if (!nodes) return; - view.repairParentChkClassWithSelf(setting, parentNode); - } - var _removeNode = view.removeNode; - view.removeNode = function(setting, node) { - var parentNode = node.getParentNode(); - if (_removeNode) _removeNode.apply(view, arguments); - if (!node || !parentNode) return; - view.repairChkClass(setting, parentNode); - view.repairParentChkClass(setting, parentNode); - } - - var _appendNodes = view.appendNodes; - view.appendNodes = function(setting, level, nodes, parentNode, initFlag, openFlag) { - var html = ""; - if (_appendNodes) { - html = _appendNodes.apply(view, arguments); - } - if (parentNode) { - data.makeChkFlag(setting, parentNode); - } - return html; - } + pSign = false; + break; + } + } + } + if (pSign) { + view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); + } + } + }, + setSonNodeCheckBox: function (setting, node, value, srcNode) { + if (!node) return; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + checkObj = $$(node, consts.id.CHECK, setting); + if (!srcNode) srcNode = node; + + var hasDisable = false; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { + var sNode = node[childKey][i]; + view.setSonNodeCheckBox(setting, sNode, value, srcNode); + if (sNode.chkDisabled === true) hasDisable = true; + } + } + + if (node != data.getRoot(setting) && node.chkDisabled !== true) { + if (hasDisable && node.nocheck !== true) { + data.makeChkFlag(setting, node); + } + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = value; + if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; + } else { + node.check_Child_State = -1; + } + view.setChkClass(setting, checkObj, node); + if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { + setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + } + } + + } + }, + + _z = { + tools: _tools, + view: _view, + event: _event, + data: _data + }; + $.extend(true, $.fn.zTree.consts, _consts); + $.extend(true, $.fn.zTree._z, _z); + + var zt = $.fn.zTree, + tools = zt._z.tools, + consts = zt.consts, + view = zt._z.view, + data = zt._z.data, + event = zt._z.event, + $$ = tools.$; + + data.exSetting(_setting); + data.addInitBind(_bindEvent); + data.addInitUnBind(_unbindEvent); + data.addInitCache(_initCache); + data.addInitNode(_initNode); + data.addInitProxy(_eventProxy, true); + data.addInitRoot(_initRoot); + data.addBeforeA(_beforeA); + data.addZTreeTools(_zTreeTools); + + var _createNodes = view.createNodes; + view.createNodes = function (setting, level, nodes, parentNode) { + if (_createNodes) _createNodes.apply(view, arguments); + if (!nodes) return; + view.repairParentChkClassWithSelf(setting, parentNode); + }; + var _removeNode = view.removeNode; + view.removeNode = function (setting, node) { + var parentNode = node.getParentNode(); + if (_removeNode) _removeNode.apply(view, arguments); + if (!node || !parentNode) return; + view.repairChkClass(setting, parentNode); + view.repairParentChkClass(setting, parentNode); + }; + + var _appendNodes = view.appendNodes; + view.appendNodes = function (setting, level, nodes, parentNode, initFlag, openFlag) { + var html = ""; + if (_appendNodes) { + html = _appendNodes.apply(view, arguments); + } + if (parentNode) { + data.makeChkFlag(setting, parentNode); + } + return html; + }; })(jQuery);/** * 可以改变图标的button * @@ -62108,16 +61944,16 @@ BI.IconChangeButton = BI.inherit(BI.Single, { stopEvent: false, stopPropagation: false, selected: false, - once: false, //点击一次选中有效,再点无效 - forceSelected: false, //点击即选中, 选中了就不会被取消 - forceNotSelected: false, //无论怎么点击都不会被选中 - disableSelected: false, //使能选中 + once: false, // 点击一次选中有效,再点无效 + forceSelected: false, // 点击即选中, 选中了就不会被取消 + forceNotSelected: false, // 无论怎么点击都不会被选中 + disableSelected: false, // 使能选中 shadow: false, - isShadowShowingOnSelected: false, //选中状态下是否显示阴影 + isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 trigger: null, handler: BI.emptyFn - }) + }); }, _init: function () { @@ -62176,8 +62012,8 @@ BI.shortcut("bi.icon_change_button", BI.IconChangeButton);/** * @type {*|void|Object} */ BI.HalfIconButton = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.HalfIconButton.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.HalfIconButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-half-icon-button check-half-select-icon", height: 16, @@ -62185,16 +62021,16 @@ BI.HalfIconButton = BI.inherit(BI.IconButton, { iconWidth: 16, iconHeight: 16, selected: false - }) + }); }, - _init : function() { + _init: function () { BI.HalfIconButton.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.HalfIconButton.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.HalfIconButton.EVENT_CHANGE); } } @@ -62243,7 +62079,7 @@ BI.MultiSelectItem = BI.inherit(BI.BasicButton, { logic: { dynamic: false } - }) + }); }, _init: function () { BI.MultiSelectItem.superclass._init.apply(this, arguments); @@ -62317,7 +62153,7 @@ BI.SingleSelectIconTextItem = BI.inherit(BI.Single, { iconClass: "", hgap: 10, height: 25 - }) + }); }, _init: function () { BI.SingleSelectIconTextItem.superclass._init.apply(this, arguments); @@ -62374,7 +62210,7 @@ BI.SingleSelectItem = BI.inherit(BI.BasicButton, { hgap: 10, height: 25, textAlign: "left" - }) + }); }, _init: function () { BI.SingleSelectItem.superclass._init.apply(this, arguments); @@ -62425,7 +62261,7 @@ BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, { }, hgap: 10, height: 25 - }) + }); }, _init: function () { BI.SingleSelectRadioItem.superclass._init.apply(this, arguments); @@ -62578,7 +62414,7 @@ BI.FirstPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.FirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -62663,7 +62499,7 @@ BI.IconArrowNode = BI.inherit(BI.NodeButton, { iconHeight: 13, iconWidth: 13, iconCls: "" - }) + }); }, _init: function () { BI.IconArrowNode.superclass._init.apply(this, arguments); @@ -62759,7 +62595,7 @@ BI.LastPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.LastPlusGroupNode.superclass._init.apply(this, arguments); @@ -62839,7 +62675,7 @@ BI.MidPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MidPlusGroupNode.superclass._init.apply(this, arguments); @@ -62906,7 +62742,7 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro var conf = BI.MultiLayerIconArrowNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-icon-arrow-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, @@ -62914,7 +62750,7 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro iconHeight: 13, iconWidth: 13, iconCls: "" - }) + }); }, _init: function () { BI.MultiLayerIconArrowNode.superclass._init.apply(this, arguments); @@ -62922,9 +62758,9 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro this.node = BI.createWidget({ type: "bi.icon_arrow_node", iconCls: o.iconCls, - //logic: { + // logic: { // dynamic: true - //}, + // }, id: o.id, pId: o.pId, open: o.open, @@ -62947,7 +62783,7 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro type: "bi.layout", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -62955,7 +62791,7 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, isOnce: function () { @@ -63008,7 +62844,7 @@ BI.PlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.PlusGroupNode.superclass._init.apply(this, arguments); @@ -63084,7 +62920,7 @@ BI.TriangleGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.TriangleGroupNode.superclass._init.apply(this, arguments); @@ -63142,7 +62978,7 @@ BI.TriangleGroupNode = BI.inherit(BI.NodeButton, { this.checkbox.setSelected(v); }, - setText: function(text){ + setText: function (text) { BI.TriangleGroupNode.superclass.setText.apply(this, arguments); this.text.setText(text); } @@ -63164,7 +63000,7 @@ BI.FirstTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.FirstTreeLeafItem.superclass._init.apply(this, arguments); @@ -63262,7 +63098,7 @@ BI.shortcut("bi.first_tree_leaf_item", BI.FirstTreeLeafItem);BI.IconTreeLeafItem iconWidth: 16, iconHeight: 16, iconCls: "" - }) + }); }, _init: function () { @@ -63354,7 +63190,7 @@ BI.LastTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.LastTreeLeafItem.superclass._init.apply(this, arguments); @@ -63457,7 +63293,7 @@ BI.MidTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.MidTreeLeafItem.superclass._init.apply(this, arguments); @@ -63557,7 +63393,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { iconCls: "", iconHeight: 14, iconWidth: 12 - }) + }); }, _init: function () { BI.MultiLayerIconTreeLeafItem.superclass._init.apply(this, arguments); @@ -63578,7 +63414,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { iconHeight: o.iconHeight }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -63590,7 +63426,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { type: "bi.layout", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -63635,7 +63471,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { this.item.setSelected(v); }, - getValue: function(){ + getValue: function () { return this.options.value; } }); @@ -63647,7 +63483,7 @@ BI.shortcut("bi.multilayer_icon_tree_leaf_item", BI.MultiLayerIconTreeLeafItem); * @extends BI.BasicButton */ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend(BI.TreeTextLeafItem.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-tree-text-leaf-item bi-list-item-active", id: "", @@ -63656,9 +63492,9 @@ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { hgap: 0, lgap: 0, rgap: 0 - }) + }); }, - _init : function() { + _init: function () { BI.TreeTextLeafItem.superclass._init.apply(this, arguments); var self = this, o = this.options; this.text = BI.createWidget({ @@ -63680,30 +63516,30 @@ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { items: [{ el: this.text }] - }) + }); }, - doRedMark: function(){ + doRedMark: function () { this.text.doRedMark.apply(this.text, arguments); }, - unRedMark: function(){ + unRedMark: function () { this.text.unRedMark.apply(this.text, arguments); }, - doHighLight: function(){ + doHighLight: function () { this.text.doHighLight.apply(this.text, arguments); }, - unHighLight: function(){ + unHighLight: function () { this.text.unHighLight.apply(this.text, arguments); }, - getId: function(){ + getId: function () { return this.options.id; }, - getPId: function(){ + getPId: function () { return this.options.pId; } }); @@ -63721,12 +63557,12 @@ BI.Calendar = BI.inherit(BI.Widget, { logic: { dynamic: false }, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 year: 2015, - month: 7, //7表示八月 + month: 7, // 7表示八月 day: 25 - }) + }); }, _dateCreator: function (Y, M, D) { @@ -63772,7 +63608,7 @@ BI.Calendar = BI.inherit(BI.Widget, { } td.text = DD; items.push(td); - }) + }); return items; }, @@ -63784,13 +63620,13 @@ BI.Calendar = BI.inherit(BI.Widget, { type: "bi.label", height: 25, text: value - } - }) + }; + }); var title = BI.createWidget({ type: "bi.button_group", height: 25, items: items - }) + }); var days = this._dateCreator(o.year, o.month, o.day); items = []; items.push(days.slice(0, 7)); @@ -63812,7 +63648,7 @@ BI.Calendar = BI.inherit(BI.Widget, { height: 25, value: o.year + "-" + o.month + "-" + td.text, disabled: td.lastMonth || td.nextMonth || td.disabled - //selected: td.currentDay + // selected: td.currentDay }); }); }); @@ -63829,7 +63665,7 @@ BI.Calendar = BI.inherit(BI.Widget, { }); this.days.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); BI.createWidget(BI.extend({ element: this @@ -63866,7 +63702,7 @@ BI.Calendar = BI.inherit(BI.Widget, { year: date[0] | 0, month: date[1] | 0, day: date[2] | 0 - } + }; } }); @@ -63878,22 +63714,22 @@ BI.extend(BI.Calendar, { page += json.month - month; return page; }, - getDateJSONByPage: function(v){ + getDateJSONByPage: function (v) { var months = Date.getDate().getMonth(); var page = v; - //对当前page做偏移,使到当前年初 + // 对当前page做偏移,使到当前年初 page = page + months; var year = BI.parseInt(page / 12); - if(page < 0 && page % 12 !== 0){ + if(page < 0 && page % 12 !== 0) { year--; } var month = page >= 0 ? (page % 12) : ((12 + page % 12) % 12); return { year: Date.getDate().getFullYear() + year, month: month - } + }; } }); @@ -63912,10 +63748,10 @@ BI.YearCalendar = BI.inherit(BI.Widget, { logic: { dynamic: false }, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 year: null - }) + }); }, _yearCreator: function (Y) { @@ -63940,7 +63776,7 @@ BI.YearCalendar = BI.inherit(BI.Widget, { this.currentYear = Date.getDate().getFullYear(); var years = this._yearCreator(o.year || this.currentYear); - //纵向排列年 + // 纵向排列年 var len = years.length, tyears = BI.makeArray(len, ""); var map = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; BI.each(years, function (i, y) { @@ -64018,11 +63854,11 @@ BI.YearCalendar = BI.inherit(BI.Widget, { return this.years.getValue()[0]; } }); -//类方法 +// 类方法 BI.extend(BI.YearCalendar, { INTERVAL: 12, - //获取显示的第一年 + // 获取显示的第一年 getStartYear: function (year) { var cur = Date.getDate().getFullYear(); return year - ((year - cur + 3) % BI.YearCalendar.INTERVAL + 12) % BI.YearCalendar.INTERVAL; @@ -64050,7 +63886,7 @@ BI.ComplexCanvas = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.ComplexCanvas.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-complex-canvas" - }) + }); }, @@ -64065,7 +63901,7 @@ BI.ComplexCanvas = BI.inherit(BI.Widget, { }); }, - //绘制树枝节点 + // 绘制树枝节点 branch: function (x0, y0, x1, y1, x2, y2) { var self = this, args = [].slice.call(arguments); if (args.length <= 5) { @@ -64134,18 +63970,18 @@ BI.shortcut("bi.complex_canvas", BI.ComplexCanvas);/** * Created by roy on 15/10/16. * 上箭头与下箭头切换的树节点 */ -BI.ArrowTreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{ - _defaultConfig:function(){ - return BI.extend(BI.ArrowTreeGroupNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{ - extraCls:"bi-arrow-tree-group-node", +BI.ArrowTreeGroupNodeCheckbox = BI.inherit(BI.IconButton, { + _defaultConfig: function () { + return BI.extend(BI.ArrowTreeGroupNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { + extraCls: "bi-arrow-tree-group-node", iconWidth: 13, iconHeight: 13 }); }, - _init:function(){ - BI.ArrowTreeGroupNodeCheckbox.superclass._init.apply(this,arguments); + _init: function () { + BI.ArrowTreeGroupNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.ArrowTreeGroupNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.removeClass("column-next-page-h-font").addClass("column-pre-page-h-font"); @@ -64154,27 +63990,27 @@ BI.ArrowTreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{ } } }); -BI.shortcut("bi.arrow_tree_group_node_checkbox",BI.ArrowTreeGroupNodeCheckbox);/** +BI.shortcut("bi.arrow_tree_group_node_checkbox", BI.ArrowTreeGroupNodeCheckbox);/** * 十字型的树节点 * @class BI.CheckingMarkNode * @extends BI.IconButton */ BI.CheckingMarkNode = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.CheckingMarkNode.superclass._defaultConfig.apply(this, arguments), { extraCls: "check-mark-font", iconWidth: 13, iconHeight: 13 }); }, - _init:function() { + _init: function () { BI.CheckingMarkNode.superclass._init.apply(this, arguments); this.setSelected(this.options.selected); }, - setSelected: function(v){ + setSelected: function (v) { BI.CheckingMarkNode.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("check-mark-font"); } else { this.element.removeClass("check-mark-font"); @@ -64187,20 +64023,20 @@ BI.shortcut("bi.checking_mark_node", BI.CheckingMarkNode);/** * @extends BI.IconButton */ BI.FirstTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.FirstTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type2", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.FirstTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.FirstTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type2"); } else { this.element.removeClass("tree-expand-icon-type2"); @@ -64213,20 +64049,20 @@ BI.shortcut("bi.first_tree_node_checkbox", BI.FirstTreeNodeCheckbox);/** * @extends BI.IconButton */ BI.LastTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.LastTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type4", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.LastTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.LastTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type3"); } else { this.element.removeClass("tree-expand-icon-type3"); @@ -64239,20 +64075,20 @@ BI.shortcut("bi.last_tree_node_checkbox", BI.LastTreeNodeCheckbox);/** * @extends BI.IconButton */ BI.MidTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.MidTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type3", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.MidTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.MidTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type3"); } else { this.element.removeClass("tree-expand-icon-type3"); @@ -64266,18 +64102,18 @@ BI.shortcut("bi.mid_tree_node_checkbox", BI.MidTreeNodeCheckbox);/** * @extends BI.IconButton */ BI.TreeGroupNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.TreeGroupNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-node-triangle-collapse-font", iconWidth: 13, iconHeight: 13 }); }, - _init:function() { + _init: function () { BI.TreeGroupNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.TreeGroupNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.removeClass("tree-node-triangle-collapse-font").addClass("tree-node-triangle-expand-font"); @@ -64292,18 +64128,18 @@ BI.shortcut("bi.tree_group_node_checkbox", BI.TreeGroupNodeCheckbox);/** * @extends BI.IconButton */ BI.TreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.TreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type1", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.TreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.TreeNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.addClass("tree-expand-icon-type1"); @@ -64312,55 +64148,55 @@ BI.TreeNodeCheckbox = BI.inherit(BI.IconButton, { } } }); -BI.shortcut("bi.tree_node_checkbox", BI.TreeNodeCheckbox);/*! +BI.shortcut("bi.tree_node_checkbox", BI.TreeNodeCheckbox);/* ! * clipboard.js v1.6.1 * https://zenorocha.github.io/clipboard.js * * Licensed MIT © Zeno Rocha */ -try {//IE8下会抛错 +try {// IE8下会抛错 (function (f) { if (typeof exports === "object" && typeof module !== "undefined") { - module.exports = f() + module.exports = f(); } else if (typeof define === "function" && define.amd) { - define([], f) + define([], f); } else { var g; if (typeof window !== "undefined") { - g = window + g = window; } else if (typeof global !== "undefined") { - g = global + g = global; } else if (typeof self !== "undefined") { - g = self + g = self; } else { - g = this + g = this; } - g.Clipboard = f() + g.Clipboard = f(); } })(function () { var define, module, exports; - return (function e(t, n, r) { - function s(o, u) { + return (function e (t, n, r) { + function s (o, u) { if (!n[o]) { if (!t[o]) { - var a = typeof require == "function" && require; + 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 + 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 s(n ? n : e); + }, l, l.exports, e, t, n, r); } - return n[o].exports + return n[o].exports; } - var i = typeof require == "function" && require; + var i = typeof require === "function" && require; for (var o = 0; o < r.length; o++)s(r[o]); - return s + return s; })({ 1: [function (require, module, exports) { var DOCUMENT_NODE_TYPE = 9; @@ -64368,7 +64204,7 @@ try {//IE8下会抛错 /** * A polyfill for Element.matches() */ - if (typeof Element !== 'undefined' && !Element.prototype.matches) { + if (typeof Element !== "undefined" && !Element.prototype.matches) { var proto = Element.prototype; proto.matches = proto.matchesSelector || @@ -64385,7 +64221,7 @@ try {//IE8下会抛错 * @param {String} selector * @return {Function} */ - function closest(element, selector) { + function closest (element, selector) { while (element && element.nodeType !== DOCUMENT_NODE_TYPE) { if (element.matches(selector)) return element; element = element.parentNode; @@ -64395,7 +64231,7 @@ try {//IE8下会抛错 module.exports = closest; }, {}], 2: [function (require, module, exports) { - var closest = require('./closest'); + var closest = require("./closest"); /** * Delegates event to a selector. @@ -64407,7 +64243,7 @@ try {//IE8下会抛错 * @param {Boolean} useCapture * @return {Object} */ - function delegate(element, selector, type, callback, useCapture) { + function delegate (element, selector, type, callback, useCapture) { var listenerFn = listener.apply(this, arguments); element.addEventListener(type, listenerFn, useCapture); @@ -64416,7 +64252,7 @@ try {//IE8下会抛错 destroy: function () { element.removeEventListener(type, listenerFn, useCapture); } - } + }; } /** @@ -64428,14 +64264,14 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Function} */ - function listener(element, selector, type, callback) { + function listener (element, selector, type, callback) { return function (e) { e.delegateTarget = closest(e.target, selector); if (e.delegateTarget) { callback.call(element, e); } - } + }; } module.exports = delegate; @@ -64463,8 +64299,8 @@ try {//IE8下会抛错 var type = Object.prototype.toString.call(value); return value !== undefined - && (type === '[object NodeList]' || type === '[object HTMLCollection]') - && ('length' in value) + && (type === "[object NodeList]" || type === "[object HTMLCollection]") + && ("length" in value) && (value.length === 0 || exports.node(value[0])); }; @@ -64475,7 +64311,7 @@ try {//IE8下会抛错 * @return {Boolean} */ exports.string = function (value) { - return typeof value === 'string' + return typeof value === "string" || value instanceof String; }; @@ -64488,12 +64324,12 @@ try {//IE8下会抛错 exports.fn = function (value) { var type = Object.prototype.toString.call(value); - return type === '[object Function]'; + return type === "[object Function]"; }; }, {}], 4: [function (require, module, exports) { - var is = require('./is'); - var delegate = require('delegate'); + var is = require("./is"); + var delegate = require("delegate"); /** * Validates all params and calls the right @@ -64504,31 +64340,29 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listen(target, type, callback) { + function listen (target, type, callback) { if (!target && !type && !callback) { - throw new Error('Missing required arguments'); + throw new Error("Missing required arguments"); } if (!is.string(type)) { - throw new TypeError('Second argument must be a String'); + throw new TypeError("Second argument must be a String"); } if (!is.fn(callback)) { - throw new TypeError('Third argument must be a Function'); + throw new TypeError("Third argument must be a Function"); } if (is.node(target)) { return listenNode(target, type, callback); - } - else if (is.nodeList(target)) { + } else if (is.nodeList(target)) { return listenNodeList(target, type, callback); - } - else if (is.string(target)) { + } else if (is.string(target)) { return listenSelector(target, type, callback); } - else { - throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList'); - } + + throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList"); + } /** @@ -64540,14 +64374,14 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenNode(node, type, callback) { + function listenNode (node, type, callback) { node.addEventListener(type, callback); return { destroy: function () { node.removeEventListener(type, callback); } - } + }; } /** @@ -64559,7 +64393,7 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenNodeList(nodeList, type, callback) { + function listenNodeList (nodeList, type, callback) { Array.prototype.forEach.call(nodeList, function (node) { node.addEventListener(type, callback); }); @@ -64570,7 +64404,7 @@ try {//IE8下会抛错 node.removeEventListener(type, callback); }); } - } + }; } /** @@ -64582,39 +64416,37 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenSelector(selector, type, callback) { + function listenSelector (selector, type, callback) { return delegate(document.body, selector, type, callback); } module.exports = listen; - }, {"./is": 3, "delegate": 2}], 5: [function (require, module, exports) { - function select(element) { + }, {"./is": 3, delegate: 2}], 5: [function (require, module, exports) { + function select (element) { var selectedText; - if (element.nodeName === 'SELECT') { + if (element.nodeName === "SELECT") { element.focus(); selectedText = element.value; - } - else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') { - var isReadOnly = element.hasAttribute('readonly'); + } else if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") { + var isReadOnly = element.hasAttribute("readonly"); if (!isReadOnly) { - element.setAttribute('readonly', ''); + element.setAttribute("readonly", ""); } element.select(); element.setSelectionRange(0, element.value.length); if (!isReadOnly) { - element.removeAttribute('readonly'); + element.removeAttribute("readonly"); } selectedText = element.value; - } - else { - if (element.hasAttribute('contenteditable')) { + } else { + if (element.hasAttribute("contenteditable")) { element.focus(); } @@ -64634,7 +64466,7 @@ try {//IE8下会抛错 module.exports = select; }, {}], 6: [function (require, module, exports) { - function E() { + function E () { // Keep this empty so it's easier to inherit from // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) } @@ -64654,12 +64486,12 @@ try {//IE8下会抛错 once: function (name, callback, ctx) { var self = this; - function listener() { + function listener () { self.off(name, listener); callback.apply(ctx, arguments); - }; + } - listener._ = callback + listener._ = callback; return this.on(name, listener, ctx); }, @@ -64683,8 +64515,7 @@ try {//IE8下会抛错 if (evts && callback) { for (var i = 0, len = evts.length; i < len; i++) { - if (evts[i].fn !== callback && evts[i].fn._ !== callback) - liveEvents.push(evts[i]); + if (evts[i].fn !== callback && evts[i].fn._ !== callback) {liveEvents.push(evts[i]);} } } @@ -64705,9 +64536,9 @@ try {//IE8下会抛错 }, {}], 7: [function (require, module, exports) { (function (global, factory) { if (typeof define === "function" && define.amd) { - define(['module', 'select'], factory); + define(["module", "select"], factory); } else if (typeof exports !== "undefined") { - factory(module, require('select')); + factory(module, require("select")); } else { var mod = { exports: {} @@ -64716,13 +64547,13 @@ try {//IE8下会抛错 global.clipboardAction = mod.exports; } })(this, function (module, _select) { - 'use strict'; + "use strict"; var _select2 = _interopRequireDefault(_select); - function _interopRequireDefault(obj) { + function _interopRequireDefault (obj) { return obj && obj.__esModule ? obj : { - "default": obj + default: obj }; } @@ -64732,14 +64563,14 @@ try {//IE8下会抛错 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - function _classCallCheck(instance, Constructor) { + function _classCallCheck (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { - function defineProperties(target, props) { + function defineProperties (target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; @@ -64760,7 +64591,7 @@ try {//IE8下会抛错 /** * @param {Object} options */ - function ClipboardAction(options) { + function ClipboardAction (options) { _classCallCheck(this, ClipboardAction); this.resolveOptions(options); @@ -64774,8 +64605,8 @@ try {//IE8下会抛错 _createClass(ClipboardAction, [{ - key: 'resolveOptions', - value: function resolveOptions() { + key: "resolveOptions", + value: function resolveOptions () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.action = options.action; @@ -64784,11 +64615,11 @@ try {//IE8下会抛错 this.text = options.text; this.trigger = options.trigger; - this.selectedText = ''; + this.selectedText = ""; } }, { - key: 'initSelection', - value: function initSelection() { + key: "initSelection", + value: function initSelection () { if (this.text) { this.selectFake(); } else if (this.target) { @@ -64796,34 +64627,34 @@ try {//IE8下会抛错 } } }, { - key: 'selectFake', - value: function selectFake() { + key: "selectFake", + value: function selectFake () { var _this = this; - var isRTL = document.documentElement.getAttribute('dir') == 'rtl'; + var isRTL = document.documentElement.getAttribute("dir") == "rtl"; this.removeFake(); this.fakeHandlerCallback = function () { return _this.removeFake(); }; - this.fakeHandler = document.body.addEventListener('click', this.fakeHandlerCallback) || true; + this.fakeHandler = document.body.addEventListener("click", this.fakeHandlerCallback) || true; - this.fakeElem = document.createElement('textarea'); + this.fakeElem = document.createElement("textarea"); // Prevent zooming on iOS - this.fakeElem.style.fontSize = '12pt'; + this.fakeElem.style.fontSize = "12pt"; // Reset box model - this.fakeElem.style.border = '0'; - this.fakeElem.style.padding = '0'; - this.fakeElem.style.margin = '0'; + this.fakeElem.style.border = "0"; + this.fakeElem.style.padding = "0"; + this.fakeElem.style.margin = "0"; // Move element out of screen horizontally - this.fakeElem.style.position = 'absolute'; - this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px'; + this.fakeElem.style.position = "absolute"; + this.fakeElem.style[isRTL ? "right" : "left"] = "-9999px"; // Move element to the same position vertically var yPosition = window.pageYOffset || document.documentElement.scrollTop; - this.fakeElem.style.top = yPosition + 'px'; + this.fakeElem.style.top = yPosition + "px"; - this.fakeElem.setAttribute('readonly', ''); + this.fakeElem.setAttribute("readonly", ""); this.fakeElem.value = this.text; document.body.appendChild(this.fakeElem); @@ -64832,10 +64663,10 @@ try {//IE8下会抛错 this.copyText(); } }, { - key: 'removeFake', - value: function removeFake() { + key: "removeFake", + value: function removeFake () { if (this.fakeHandler) { - document.body.removeEventListener('click', this.fakeHandlerCallback); + document.body.removeEventListener("click", this.fakeHandlerCallback); this.fakeHandler = null; this.fakeHandlerCallback = null; } @@ -64846,14 +64677,14 @@ try {//IE8下会抛错 } } }, { - key: 'selectTarget', - value: function selectTarget() { + key: "selectTarget", + value: function selectTarget () { this.selectedText = (0, _select2["default"])(this.target); this.copyText(); } }, { - key: 'copyText', - value: function copyText() { + key: "copyText", + value: function copyText () { var succeeded = void 0; try { @@ -64865,9 +64696,9 @@ try {//IE8下会抛错 this.handleResult(succeeded); } }, { - key: 'handleResult', - value: function handleResult(succeeded) { - this.emitter.emit(succeeded ? 'success' : 'error', { + key: "handleResult", + value: function handleResult (succeeded) { + this.emitter.emit(succeeded ? "success" : "error", { action: this.action, text: this.selectedText, trigger: this.trigger, @@ -64875,8 +64706,8 @@ try {//IE8下会抛错 }); } }, { - key: 'clearSelection', - value: function clearSelection() { + key: "clearSelection", + value: function clearSelection () { if (this.target) { this.target.blur(); } @@ -64884,44 +64715,44 @@ try {//IE8下会抛错 window.getSelection().removeAllRanges(); } }, { - key: 'destroy', - value: function destroy() { + key: "destroy", + value: function destroy () { this.removeFake(); } }, { - key: 'action', - set: function set() { - var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'copy'; + key: "action", + set: function set () { + var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "copy"; this._action = action; - if (this._action !== 'copy' && this._action !== 'cut') { - throw new Error('Invalid "action" value, use either "copy" or "cut"'); + if (this._action !== "copy" && this._action !== "cut") { + throw new Error("Invalid \"action\" value, use either \"copy\" or \"cut\""); } }, - get: function get() { + get: function get () { return this._action; } }, { - key: 'target', - set: function set(target) { + key: "target", + set: function set (target) { if (target !== undefined) { - if (target && (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target.nodeType === 1) { - if (this.action === 'copy' && target.hasAttribute('disabled')) { - throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute'); + if (target && (typeof target === "undefined" ? "undefined" : _typeof(target)) === "object" && target.nodeType === 1) { + if (this.action === "copy" && target.hasAttribute("disabled")) { + throw new Error("Invalid \"target\" attribute. Please use \"readonly\" instead of \"disabled\" attribute"); } - if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) { - throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes'); + if (this.action === "cut" && (target.hasAttribute("readonly") || target.hasAttribute("disabled"))) { + throw new Error("Invalid \"target\" attribute. You can't cut text from elements with \"readonly\" or \"disabled\" attributes"); } this._target = target; } else { - throw new Error('Invalid "target" value, use a valid Element'); + throw new Error("Invalid \"target\" value, use a valid Element"); } } }, - get: function get() { + get: function get () { return this._target; } }]); @@ -64932,12 +64763,12 @@ try {//IE8下会抛错 module.exports = ClipboardAction; }); - }, {"select": 5}], 8: [function (require, module, exports) { + }, {select: 5}], 8: [function (require, module, exports) { (function (global, factory) { if (typeof define === "function" && define.amd) { - define(['module', './clipboard-action', 'tiny-emitter', 'good-listener'], factory); + define(["module", "./clipboard-action", "tiny-emitter", "good-listener"], factory); } else if (typeof exports !== "undefined") { - factory(module, require('./clipboard-action'), require('tiny-emitter'), require('good-listener')); + factory(module, require("./clipboard-action"), require("tiny-emitter"), require("good-listener")); } else { var mod = { exports: {} @@ -64946,7 +64777,7 @@ try {//IE8下会抛错 global.clipboard = mod.exports; } })(this, function (module, _clipboardAction, _tinyEmitter, _goodListener) { - 'use strict'; + "use strict"; var _clipboardAction2 = _interopRequireDefault(_clipboardAction); @@ -64954,20 +64785,20 @@ try {//IE8下会抛错 var _goodListener2 = _interopRequireDefault(_goodListener); - function _interopRequireDefault(obj) { + function _interopRequireDefault (obj) { return obj && obj.__esModule ? obj : { - "default": obj + default: obj }; } - function _classCallCheck(instance, Constructor) { + function _classCallCheck (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { - function defineProperties(target, props) { + function defineProperties (target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; @@ -64984,7 +64815,7 @@ try {//IE8下会抛错 }; }(); - function _possibleConstructorReturn(self, call) { + function _possibleConstructorReturn (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } @@ -64992,7 +64823,7 @@ try {//IE8下会抛错 return call && (typeof call === "object" || typeof call === "function") ? call : self; } - function _inherits(subClass, superClass) { + function _inherits (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } @@ -65015,7 +64846,7 @@ try {//IE8下会抛错 * @param {String|HTMLElement|HTMLCollection|NodeList} trigger * @param {Object} options */ - function Clipboard(trigger, options) { + function Clipboard (trigger, options) { _classCallCheck(this, Clipboard); var _this = _possibleConstructorReturn(this, (Clipboard.__proto__ || Object.getPrototypeOf(Clipboard)).call(this)); @@ -65033,26 +64864,26 @@ try {//IE8下会抛错 _createClass(Clipboard, [{ - key: 'resolveOptions', - value: function resolveOptions() { + key: "resolveOptions", + value: function resolveOptions () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - this.action = typeof options.action === 'function' ? options.action : this.defaultAction; - this.target = typeof options.target === 'function' ? options.target : this.defaultTarget; - this.text = typeof options.text === 'function' ? options.text : this.defaultText; + this.action = typeof options.action === "function" ? options.action : this.defaultAction; + this.target = typeof options.target === "function" ? options.target : this.defaultTarget; + this.text = typeof options.text === "function" ? options.text : this.defaultText; } }, { - key: 'listenClick', - value: function listenClick(trigger) { + key: "listenClick", + value: function listenClick (trigger) { var _this2 = this; - this.listener = (0, _goodListener2["default"])(trigger, 'click', function (e) { + this.listener = (0, _goodListener2["default"])(trigger, "click", function (e) { return _this2.onClick(e); }); } }, { - key: 'onClick', - value: function onClick(e) { + key: "onClick", + value: function onClick (e) { var trigger = e.delegateTarget || e.currentTarget; if (this.clipboardAction) { @@ -65068,27 +64899,27 @@ try {//IE8下会抛错 }); } }, { - key: 'defaultAction', - value: function defaultAction(trigger) { - return getAttributeValue('action', trigger); + key: "defaultAction", + value: function defaultAction (trigger) { + return getAttributeValue("action", trigger); } }, { - key: 'defaultTarget', - value: function defaultTarget(trigger) { - var selector = getAttributeValue('target', trigger); + key: "defaultTarget", + value: function defaultTarget (trigger) { + var selector = getAttributeValue("target", trigger); if (selector) { return document.querySelector(selector); } } }, { - key: 'defaultText', - value: function defaultText(trigger) { - return getAttributeValue('text', trigger); + key: "defaultText", + value: function defaultText (trigger) { + return getAttributeValue("text", trigger); } }, { - key: 'destroy', - value: function destroy() { + key: "destroy", + value: function destroy () { this.listener.destroy(); if (this.clipboardAction) { @@ -65097,11 +64928,11 @@ try {//IE8下会抛错 } } }], [{ - key: 'isSupported', - value: function isSupported() { - var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut']; + key: "isSupported", + value: function isSupported () { + var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ["copy", "cut"]; - var actions = typeof action === 'string' ? [action] : action; + var actions = typeof action === "string" ? [action] : action; var support = !!document.queryCommandSupported; actions.forEach(function (action) { @@ -65120,8 +64951,8 @@ try {//IE8下会抛错 * @param {String} suffix * @param {Element} element */ - function getAttributeValue(suffix, element) { - var attribute = 'data-clipboard-' + suffix; + function getAttributeValue (suffix, element) { + var attribute = "data-clipboard-" + suffix; if (!element.hasAttribute(attribute)) { return; @@ -65134,7 +64965,7 @@ try {//IE8下会抛错 }); }, {"./clipboard-action": 7, "good-listener": 4, "tiny-emitter": 6}] - }, {}, [8])(8) + }, {}, [8])(8); }); } catch (e) { /* @@ -65153,11 +64984,11 @@ try {//IE8下会抛错 $.fn.zclip = function (params) { - if (typeof params == "object" && !params.length) { + if (typeof params === "object" && !params.length) { var settings = $.extend({ - path: 'ZeroClipboard.swf', + path: "ZeroClipboard.swf", copy: null, beforeCopy: null, afterCopy: null, @@ -65172,62 +65003,62 @@ try {//IE8下会抛错 var o = $(this); - if (o.is(':visible') && (typeof settings.copy == 'string' || $.isFunction(settings.copy))) { + if (o.is(":visible") && (typeof settings.copy === "string" || $.isFunction(settings.copy))) { ZeroClipboard.setMoviePath(settings.path); var clip = new ZeroClipboard.Client(); if ($.isFunction(settings.copy)) { - o.bind('zClip_copy', settings.copy); + o.bind("zClip_copy", settings.copy); } if ($.isFunction(settings.beforeCopy)) { - o.bind('zClip_beforeCopy', settings.beforeCopy); + o.bind("zClip_beforeCopy", settings.beforeCopy); } if ($.isFunction(settings.afterCopy)) { - o.bind('zClip_afterCopy', settings.afterCopy); + o.bind("zClip_afterCopy", settings.afterCopy); } clip.setHandCursor(settings.setHandCursor); clip.setCSSEffects(settings.setCSSEffects); - clip.addEventListener('mouseOver', function (client) { - o.trigger('mouseenter'); + clip.addEventListener("mouseOver", function (client) { + o.trigger("mouseenter"); }); - clip.addEventListener('mouseOut', function (client) { - o.trigger('mouseleave'); + clip.addEventListener("mouseOut", function (client) { + o.trigger("mouseleave"); }); - clip.addEventListener('mouseDown', function (client) { + clip.addEventListener("mouseDown", function (client) { - o.trigger('mousedown'); + o.trigger("mousedown"); if (!$.isFunction(settings.copy)) { clip.setText(settings.copy); } else { - clip.setText(o.triggerHandler('zClip_copy')); + clip.setText(o.triggerHandler("zClip_copy")); } if ($.isFunction(settings.beforeCopy)) { - o.trigger('zClip_beforeCopy'); + o.trigger("zClip_beforeCopy"); } }); - clip.addEventListener('complete', function (client, text) { + clip.addEventListener("complete", function (client, text) { if ($.isFunction(settings.afterCopy)) { - o.trigger('zClip_afterCopy'); + o.trigger("zClip_afterCopy"); } else { if (text.length > 500) { text = text.substr(0, 500) + "...\n\n(" + (text.length - 500) + " characters not shown)"; } - o.removeClass('hover'); + o.removeClass("hover"); alert("Copied text to clipboard:\n\n " + text); } if (settings.clickAfter) { - o.trigger('click'); + o.trigger("click"); } }); @@ -65235,7 +65066,7 @@ try {//IE8下会抛错 clip.glue(o[0], o.parent()[0]); - $(window).bind('load resize', function () { + $(window).bind("load resize", function () { clip.reposition(); }); @@ -65244,25 +65075,25 @@ try {//IE8下会抛错 }); - } else if (typeof params == "string") { + } else if (typeof params === "string") { return this.each(function () { var o = $(this); params = params.toLowerCase(); - var zclipId = o.data('zclipId'); - var clipElm = $('#' + zclipId + '.zclip'); + var zclipId = o.data("zclipId"); + var clipElm = $("#" + zclipId + ".zclip"); if (params == "remove") { clipElm.remove(); - o.removeClass('active hover'); + o.removeClass("active hover"); } else if (params == "hide") { clipElm.hide(); - o.removeClass('active hover'); + o.removeClass("active hover"); } else if (params == "show") { @@ -65274,38 +65105,38 @@ try {//IE8下会抛错 } - } + }; })(jQuery); -// ZeroClipboard -// Simple Set Clipboard System -// Author: Joseph Huckaby + // ZeroClipboard + // Simple Set Clipboard System + // Author: Joseph Huckaby var ZeroClipboard = { version: "1.0.7", clients: {}, // registered upload clients on page, indexed by id - moviePath: 'ZeroClipboard.swf', + moviePath: "ZeroClipboard.swf", // URL to movie nextId: 1, // ID of next movie $: function (thingy) { // simple DOM lookup utility function - if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); + if (typeof(thingy) === "string") thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function () { - this.style.display = 'none'; + this.style.display = "none"; }; thingy.show = function () { - this.style.display = ''; + this.style.display = ""; }; thingy.addClass = function (name) { this.removeClass(name); - this.className += ' ' + name; + this.className += " " + name; }; thingy.removeClass = function (name) { var classes = this.className.split(/\s+/); @@ -65318,7 +65149,7 @@ try {//IE8下会抛错 } if (idx > -1) { classes.splice(idx, 1); - this.className = classes.join(' '); + this.className = classes.join(" "); } return this; }; @@ -65370,7 +65201,7 @@ try {//IE8下会抛错 // unique ID this.id = ZeroClipboard.nextId++; - this.movieId = 'ZeroClipboardMovie_' + this.id; + this.movieId = "ZeroClipboardMovie_" + this.id; // register client with singleton to receive flash events ZeroClipboard.register(this.id, this); @@ -65388,7 +65219,7 @@ try {//IE8下会抛错 // whether movie is ready to receive events or not movie: null, // reference to movie object - clipText: '', + clipText: "", // text to copy to clipboard handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor @@ -65407,29 +65238,29 @@ try {//IE8下会抛错 zIndex = parseInt(this.domElement.style.zIndex, 10) + 1; } - if (typeof(appendElem) == 'string') { + if (typeof(appendElem) === "string") { appendElem = ZeroClipboard.$(appendElem); - } else if (typeof(appendElem) == 'undefined') { - appendElem = document.getElementsByTagName('body')[0]; + } else if (typeof(appendElem) === "undefined") { + appendElem = document.getElementsByTagName("body")[0]; } // find X/Y position of domElement var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem); // create floating DIV above element - this.div = document.createElement('div'); + this.div = document.createElement("div"); this.div.className = "zclip"; this.div.id = "zclip-" + this.movieId; - $(this.domElement).data('zclipId', 'zclip-' + this.movieId); + $(this.domElement).data("zclipId", "zclip-" + this.movieId); var style = this.div.style; - style.position = 'absolute'; - style.left = '' + box.left + 'px'; - style.top = '' + box.top + 'px'; - style.width = '' + box.width + 'px'; - style.height = '' + box.height + 'px'; + style.position = "absolute"; + style.left = "" + box.left + "px"; + style.top = "" + box.top + "px"; + style.width = "" + box.width + "px"; + style.height = "" + box.height + "px"; style.zIndex = zIndex; - if (typeof(stylesToAdd) == 'object') { + if (typeof(stylesToAdd) === "object") { for (addedStyle in stylesToAdd) { style[addedStyle] = stylesToAdd[addedStyle]; } @@ -65443,16 +65274,16 @@ try {//IE8下会抛错 getHTML: function (width, height) { // return HTML for movie - var html = ''; - var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; + var html = ""; + var flashvars = "id=" + this.id + "&width=" + width + "&height=" + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag - var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; - html += ''; + var protocol = location.href.match(/^https/i) ? "https://" : "http://"; + html += ""; } else { // all other browsers get an EMBED tag - html += ''; + html += ""; } return html; }, @@ -65460,7 +65291,7 @@ try {//IE8下会抛错 hide: function () { // temporarily hide floater offscreen if (this.div) { - this.div.style.left = '-2000px'; + this.div.style.left = "-2000px"; } }, @@ -65473,13 +65304,13 @@ try {//IE8下会抛错 // destroy control and floater if (this.domElement && this.div) { this.hide(); - this.div.innerHTML = ''; + this.div.innerHTML = ""; - var body = document.getElementsByTagName('body')[0]; + var body = document.getElementsByTagName("body")[0]; try { body.removeChild(this.div); } catch (e) { - ; + } this.domElement = null; @@ -65498,8 +65329,8 @@ try {//IE8下会抛错 if (this.domElement && this.div) { var box = ZeroClipboard.getDOMObjectPosition(this.domElement); var style = this.div.style; - style.left = '' + box.left + 'px'; - style.top = '' + box.top + 'px'; + style.left = "" + box.left + "px"; + style.top = "" + box.top + "px"; } }, @@ -65514,7 +65345,7 @@ try {//IE8下会抛错 addEventListener: function (eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel - eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + eventName = eventName.toString().toLowerCase().replace(/^on/, ""); if (!this.handlers[eventName]) { this.handlers[eventName] = []; } @@ -65536,18 +65367,18 @@ try {//IE8下会抛错 receiveEvent: function (eventName, args) { // receive event from flash - eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + eventName = eventName.toString().toLowerCase().replace(/^on/, ""); // special behavior for certain events switch (eventName) { - case 'load': + case "load": // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout(function () { - self.receiveEvent('load', null); + self.receiveEvent("load", null); }, 1); return; } @@ -65556,7 +65387,7 @@ try {//IE8下会抛错 if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout(function () { - self.receiveEvent('load', null); + self.receiveEvent("load", null); }, 100); this.ready = true; return; @@ -65573,11 +65404,11 @@ try {//IE8下会抛错 } break; - case 'mouseover': + case "mouseover": if (this.domElement && this.cssEffects) { - this.domElement.addClass('hover'); + this.domElement.addClass("hover"); if (this.recoverActive) { - this.domElement.addClass('active'); + this.domElement.addClass("active"); } @@ -65586,27 +65417,27 @@ try {//IE8下会抛错 break; - case 'mouseout': + case "mouseout": if (this.domElement && this.cssEffects) { this.recoverActive = false; - if (this.domElement.hasClass('active')) { - this.domElement.removeClass('active'); + if (this.domElement.hasClass("active")) { + this.domElement.removeClass("active"); this.recoverActive = true; } - this.domElement.removeClass('hover'); + this.domElement.removeClass("hover"); } break; - case 'mousedown': + case "mousedown": if (this.domElement && this.cssEffects) { - this.domElement.addClass('active'); + this.domElement.addClass("active"); } break; - case 'mouseup': + case "mouseup": if (this.domElement && this.cssEffects) { - this.domElement.removeClass('active'); + this.domElement.removeClass("active"); this.recoverActive = false; } break; @@ -65615,13 +65446,13 @@ try {//IE8下会抛错 for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; - if (typeof(func) == 'function') { + if (typeof(func) === "function") { // actual function reference func(this, args); - } else if ((typeof(func) == 'object') && (func.length == 2)) { + } else if ((typeof(func) === "object") && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][func[1]](this, args); - } else if (typeof(func) == 'string') { + } else if (typeof(func) === "string") { // name of function window[func](this, args); } @@ -65642,7 +65473,7 @@ BI.ClipBoard = BI.inherit(BI.BasicButton, { extraCls: "bi-clipboard", copy: BI.emptyFn, afterCopy: BI.emptyFn - }) + }); }, _init: function () { @@ -65657,7 +65488,7 @@ BI.ClipBoard = BI.inherit(BI.BasicButton, { return BI.isFunction(o.copy) ? o.copy() : o.copy; } }); - this.clipboard.on("success", o.afterCopy) + this.clipboard.on("success", o.afterCopy); } else { this.element.zclip({ path: BI.resourceURL + "/ZeroClipboard.swf", @@ -65687,7 +65518,7 @@ BI.CustomColorChooser = BI.inherit(BI.Widget, { baseCls: "bi-custom-color-chooser", width: 227, height: 245 - }) + }); }, _init: function () { @@ -65728,7 +65559,7 @@ BI.CustomColorChooser = BI.inherit(BI.Widget, { }], height: 215 }] - }) + }); }, setValue: function (color) { @@ -65754,7 +65585,7 @@ BI.ColorChooser = BI.inherit(BI.Widget, { return BI.extend(BI.ColorChooser.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-color-chooser", el: {} - }) + }); }, _init: function () { @@ -65806,7 +65637,7 @@ BI.ColorChooser = BI.inherit(BI.Widget, { this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { self.fireEvent(BI.ColorChooser.EVENT_CHANGE, arguments); - }) + }); }, isViewVisible: function () { @@ -65844,7 +65675,7 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { baseCls: "bi-color-chooser-popup", width: 200, height: 145 - }) + }); }, _init: function () { @@ -65992,7 +65823,7 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { el: this.more, height: 20 }] - }) + }); }, setStoreColors: function (colors) { @@ -66000,13 +65831,13 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { var items = BI.map(colors, function (i, color) { return { value: color - } + }; }); BI.count(colors.length, 8, function (i) { items.push({ value: "", disabled: true - }) + }); }); this.storeColors.populate([items]); } @@ -66038,7 +65869,7 @@ BI.ColorChooserTrigger = BI.inherit(BI.Trigger, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-color-chooser-trigger", height: 30 - }) + }); }, _init: function () { @@ -66081,7 +65912,7 @@ BI.ColorChooserTrigger = BI.inherit(BI.Trigger, { if (color === "") { this.colorContainer.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-background"); } else if (color === "transparent") { - this.colorContainer.element.css("background-color", "").removeClass("auto-color-background").addClass("trans-color-background") + this.colorContainer.element.css("background-color", "").removeClass("auto-color-background").addClass("trans-color-background"); } else { this.colorContainer.element.css({"background-color": color}).removeClass("auto-color-background").removeClass("trans-color-background"); } @@ -66101,7 +65932,7 @@ BI.ColorPickerButton = BI.inherit(BI.BasicButton, { var conf = BI.ColorPickerButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-color-picker-button bi-background bi-border-top bi-border-left" - }) + }); }, _init: function () { @@ -66140,10 +65971,10 @@ BI.ColorPickerButton = BI.inherit(BI.BasicButton, { setSelected: function (b) { BI.ColorPickerButton.superclass.setSelected.apply(this, arguments); - if (!!b) { + if (b) { this._createMask(); } - BI.Maskers[!!b ? "show" : "hide"](this.getName()); + BI.Maskers[b ? "show" : "hide"](this.getName()); } }); BI.ColorPickerButton.EVENT_CHANGE = "ColorPickerButton.EVENT_CHANGE"; @@ -66160,7 +65991,7 @@ BI.ColorPicker = BI.inherit(BI.Widget, { return BI.extend(BI.ColorPicker.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-color-picker", items: null - }) + }); }, _items: [ @@ -66314,11 +66145,11 @@ BI.ColorPicker = BI.inherit(BI.Widget, { }); this.colors.on(BI.ButtonGroup.EVENT_CHANGE, function () { self.fireEvent(BI.ColorPicker.EVENT_CHANGE, arguments); - }) + }); }, - populate: function(items){ - var args =[].slice.call(arguments); + populate: function (items) { + var args = [].slice.call(arguments); args[0] = BI.createItems(items, { type: "bi.color_picker_button", once: false @@ -66349,7 +66180,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { baseCls: "bi-color-picker-editor", // width: 200, height: 20 - }) + }); }, _init: function () { @@ -66431,7 +66262,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { element: this, items: [{ el: this.colorShow, - width: 'fill' + width: "fill" }, { el: RGB[0], lgap: 10, @@ -66466,7 +66297,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { }, width: 18 }] - }) + }); }, setValue: function (color) { @@ -66500,7 +66331,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { r: this.R.getValue(), g: this.G.getValue(), b: this.B.getValue() - })) + })); } }); BI.ColorPickerEditor.EVENT_CHANGE = "ColorPickerEditor.EVENT_CHANGE"; @@ -66518,7 +66349,7 @@ BI.Farbtastic = BI.inherit(BI.Widget, { baseCls: "bi-farbtastic", width: 195, height: 195 - }) + }); }, _init: function () { @@ -66561,159 +66392,157 @@ BI.shortcut("bi.farbtastic", BI.Farbtastic);/** */ jQuery.fn.farbtastic = function (callback) { - $.farbtastic(this, callback); - return this; + $.farbtastic(this, callback); + return this; }; jQuery.farbtastic = function (container, callback) { - var container = $(container).get(0); - return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback)); -} + var container = $(container).get(0); + return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback)); +}; jQuery._farbtastic = function (container, callback) { - // Store farbtastic object - var fb = this; - - // Insert markup - $(container).html('
    '); - var e = $('.farbtastic', container); - fb.wheel = $('.wheel', container).get(0); - // Dimensions - fb.radius = 84; - fb.square = 100; - fb.width = 194; - - // Fix background PNGs in IE6 - if (navigator.appVersion.match(/MSIE [0-6]\./)) { - $('*', e).each(function () { - if (this.currentStyle.backgroundImage != 'none') { - var image = this.currentStyle.backgroundImage; - image = this.currentStyle.backgroundImage.substring(5, image.length - 2); - $(this).css({ - 'backgroundImage': 'none', - 'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" - }); - } - }); - } + // Store farbtastic object + var fb = this; + + // Insert markup + $(container).html("
    "); + var e = $(".farbtastic", container); + fb.wheel = $(".wheel", container).get(0); + // Dimensions + fb.radius = 84; + fb.square = 100; + fb.width = 194; + + // Fix background PNGs in IE6 + if (navigator.appVersion.match(/MSIE [0-6]\./)) { + $("*", e).each(function () { + if (this.currentStyle.backgroundImage != "none") { + var image = this.currentStyle.backgroundImage; + image = this.currentStyle.backgroundImage.substring(5, image.length - 2); + $(this).css({ + backgroundImage: "none", + filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" + }); + } + }); + } - /** + /** * Link to the given element(s) or callback. */ - fb.linkTo = function (callback) { + fb.linkTo = function (callback) { // Unbind previous nodes - if (typeof fb.callback == 'object') { - $(fb.callback).unbind('keyup', fb.updateValue); - } + if (typeof fb.callback === "object") { + $(fb.callback).unbind("keyup", fb.updateValue); + } - // Reset color - fb.color = null; + // Reset color + fb.color = null; - // Bind callback or elements - if (typeof callback == 'function') { - fb.callback = callback; - } - else if (typeof callback == 'object' || typeof callback == 'string') { - fb.callback = $(callback); - fb.callback.bind('keyup', fb.updateValue); - if (fb.callback.get(0).value) { - fb.setColor(fb.callback.get(0).value); - } - } - return this; - } - fb.updateValue = function (event) { - if (this.value && this.value != fb.color) { - fb.setColor(this.value); - } - } + // Bind callback or elements + if (typeof callback === "function") { + fb.callback = callback; + } else if (typeof callback === "object" || typeof callback === "string") { + fb.callback = $(callback); + fb.callback.bind("keyup", fb.updateValue); + if (fb.callback.get(0).value) { + fb.setColor(fb.callback.get(0).value); + } + } + return this; + }; + fb.updateValue = function (event) { + if (this.value && this.value != fb.color) { + fb.setColor(this.value); + } + }; - /** + /** * Change color with HTML syntax #123456 */ - fb.setColor = function (color) { - var unpack = fb.unpack(color); - if (fb.color != color && unpack) { - fb.color = color; - fb.rgb = unpack; - fb.hsl = fb.RGBToHSL(fb.rgb); - fb.updateDisplay(); - } - return this; - } + fb.setColor = function (color) { + var unpack = fb.unpack(color); + if (fb.color != color && unpack) { + fb.color = color; + fb.rgb = unpack; + fb.hsl = fb.RGBToHSL(fb.rgb); + fb.updateDisplay(); + } + return this; + }; - /** + /** * Change color with HSL triplet [0..1, 0..1, 0..1] */ - fb.setHSL = function (hsl) { - fb.hsl = hsl; - fb.rgb = fb.HSLToRGB(hsl); - fb.color = fb.pack(fb.rgb); - fb.updateDisplay(); - return this; - } + fb.setHSL = function (hsl) { + fb.hsl = hsl; + fb.rgb = fb.HSLToRGB(hsl); + fb.color = fb.pack(fb.rgb); + fb.updateDisplay(); + return this; + }; - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// - /** + /** * Retrieve the coordinates of the given event relative to the center * of the widget. */ - fb.widgetCoords = function (event) { - var x, y; - var el = event.target || event.srcElement; - var reference = fb.wheel; - - if (typeof event.offsetX != 'undefined') { - // Use offset coordinates and find common offsetParent - var pos = { x: event.offsetX, y: event.offsetY }; - - // Send the coordinates upwards through the offsetParent chain. - var e = el; - while (e) { - e.mouseX = pos.x; - e.mouseY = pos.y; - pos.x += e.offsetLeft; - pos.y += e.offsetTop; - e = e.offsetParent; - } - - // Look for the coordinates starting from the wheel widget. - var e = reference; - var offset = { x: 0, y: 0 } - while (e) { - if (typeof e.mouseX != 'undefined') { - x = e.mouseX - offset.x; - y = e.mouseY - offset.y; - break; - } - offset.x += e.offsetLeft; - offset.y += e.offsetTop; - e = e.offsetParent; - } - - // Reset stored coordinates - e = el; - while (e) { - e.mouseX = undefined; - e.mouseY = undefined; - e = e.offsetParent; - } - } - else { - // Use absolute coordinates - var pos = fb.absolutePosition(reference); - x = (event.pageX || 0*(event.clientX + $('html').get(0).scrollLeft)) - pos.x; - y = (event.pageY || 0*(event.clientY + $('html').get(0).scrollTop)) - pos.y; - } - // Subtract distance to middle - return { x: x - fb.width / 2, y: y - fb.width / 2 }; - } - - /** + fb.widgetCoords = function (event) { + var x, y; + var el = event.target || event.srcElement; + var reference = fb.wheel; + + if (typeof event.offsetX !== "undefined") { + // Use offset coordinates and find common offsetParent + var pos = { x: event.offsetX, y: event.offsetY }; + + // Send the coordinates upwards through the offsetParent chain. + var e = el; + while (e) { + e.mouseX = pos.x; + e.mouseY = pos.y; + pos.x += e.offsetLeft; + pos.y += e.offsetTop; + e = e.offsetParent; + } + + // Look for the coordinates starting from the wheel widget. + var e = reference; + var offset = { x: 0, y: 0 }; + while (e) { + if (typeof e.mouseX !== "undefined") { + x = e.mouseX - offset.x; + y = e.mouseY - offset.y; + break; + } + offset.x += e.offsetLeft; + offset.y += e.offsetTop; + e = e.offsetParent; + } + + // Reset stored coordinates + e = el; + while (e) { + e.mouseX = undefined; + e.mouseY = undefined; + e = e.offsetParent; + } + } else { + // Use absolute coordinates + var pos = fb.absolutePosition(reference); + x = (event.pageX || 0 * (event.clientX + $("html").get(0).scrollLeft)) - pos.x; + y = (event.pageY || 0 * (event.clientY + $("html").get(0).scrollTop)) - pos.y; + } + // Subtract distance to middle + return { x: x - fb.width / 2, y: y - fb.width / 2 }; + }; + + /** * Mousedown handler */ - fb.click = function (event) { + fb.click = function (event) { // Capture mouse // if (!document.dragging) { // $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup); @@ -66721,171 +66550,168 @@ jQuery._farbtastic = function (container, callback) { // } // Check which area is being dragged - var pos = fb.widgetCoords(event); - fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; + var pos = fb.widgetCoords(event); + fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; - // Process - fb.mousemove(event); - return false; - } + // Process + fb.mousemove(event); + return false; + }; - /** + /** * Mousemove handler */ - fb.mousemove = function (event) { + fb.mousemove = function (event) { // Get coordinates relative to color picker center - var pos = fb.widgetCoords(event); + var pos = fb.widgetCoords(event); - // Set new HSL parameters - if (fb.circleDrag) { - var hue = Math.atan2(pos.x, -pos.y) / 6.28; - if (hue < 0) hue += 1; - fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); - } - else { - var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); - var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); - fb.setHSL([fb.hsl[0], sat, lum]); - } - return false; - } + // Set new HSL parameters + if (fb.circleDrag) { + var hue = Math.atan2(pos.x, -pos.y) / 6.28; + if (hue < 0) hue += 1; + fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); + } else { + var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); + var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); + fb.setHSL([fb.hsl[0], sat, lum]); + } + return false; + }; - /** + /** * Mouseup handler */ - // fb.mouseup = function () { - // // Uncapture mouse - // $(document).unbind('mousemove', fb.mousemove); - // $(document).unbind('mouseup', fb.mouseup); - // document.dragging = false; - // } - - /** + // fb.mouseup = function () { + // // Uncapture mouse + // $(document).unbind('mousemove', fb.mousemove); + // $(document).unbind('mouseup', fb.mouseup); + // document.dragging = false; + // } + + /** * Update the markers and styles */ - fb.updateDisplay = function () { + fb.updateDisplay = function () { // Markers - var angle = fb.hsl[0] * 6.28; - $('.h-marker', e).css({ - left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px', - top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px' - }); + var angle = fb.hsl[0] * 6.28; + $(".h-marker", e).css({ + left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + "px", + top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + "px" + }); - $('.sl-marker', e).css({ - left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px', - top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px' - }); + $(".sl-marker", e).css({ + left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + "px", + top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + "px" + }); - // Saturation/Luminance gradient - $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); + // Saturation/Luminance gradient + $(".color", e).css("backgroundColor", fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); - // Linked elements or callback - if (typeof fb.callback == 'object') { - // Set background/foreground color - $(fb.callback).css({ - backgroundColor: fb.color, - color: fb.hsl[2] > 0.5 ? '#000' : '#fff' - }); + // Linked elements or callback + if (typeof fb.callback === "object") { + // Set background/foreground color + $(fb.callback).css({ + backgroundColor: fb.color, + color: fb.hsl[2] > 0.5 ? "#000" : "#fff" + }); - // Change linked value - $(fb.callback).each(function() { - if (this.value && this.value != fb.color) { - this.value = fb.color; + // Change linked value + $(fb.callback).each(function () { + if (this.value && this.value != fb.color) { + this.value = fb.color; + } + }); + } else if (typeof fb.callback === "function") { + fb.callback.call(fb, fb.color); } - }); - } - else if (typeof fb.callback == 'function') { - fb.callback.call(fb, fb.color); - } - } + }; - /** + /** * Get absolute position of element */ - fb.absolutePosition = function (el) { - var r = { x: el.offsetLeft, y: el.offsetTop }; - // Resolve relative to offsetParent - if (el.offsetParent) { - var tmp = fb.absolutePosition(el.offsetParent); - r.x += tmp.x; - r.y += tmp.y; - } - return r; - }; - - /* Various color utility functions */ - fb.pack = function (rgb) { - var r = Math.round(rgb[0] * 255); - var g = Math.round(rgb[1] * 255); - var b = Math.round(rgb[2] * 255); - return '#' + (r < 16 ? '0' : '') + r.toString(16) + - (g < 16 ? '0' : '') + g.toString(16) + - (b < 16 ? '0' : '') + b.toString(16); - } - - fb.unpack = function (color) { - if (color.length == 7) { - return [parseInt('0x' + color.substring(1, 3)) / 255, - parseInt('0x' + color.substring(3, 5)) / 255, - parseInt('0x' + color.substring(5, 7)) / 255]; - } - else if (color.length == 4) { - return [parseInt('0x' + color.substring(1, 2)) / 15, - parseInt('0x' + color.substring(2, 3)) / 15, - parseInt('0x' + color.substring(3, 4)) / 15]; - } - } - - fb.HSLToRGB = function (hsl) { - var m1, m2, r, g, b; - var h = hsl[0], s = hsl[1], l = hsl[2]; - m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s; - m1 = l * 2 - m2; - return [this.hueToRGB(m1, m2, h+0.33333), - this.hueToRGB(m1, m2, h), - this.hueToRGB(m1, m2, h-0.33333)]; - } - - fb.hueToRGB = function (m1, m2, h) { - h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); - if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; - if (h * 2 < 1) return m2; - if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; - return m1; - } - - fb.RGBToHSL = function (rgb) { - var min, max, delta, h, s, l; - var r = rgb[0], g = rgb[1], b = rgb[2]; - min = Math.min(r, Math.min(g, b)); - max = Math.max(r, Math.max(g, b)); - delta = max - min; - l = (min + max) / 2; - s = 0; - if (l > 0 && l < 1) { - s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); - } - h = 0; - if (delta > 0) { - if (max == r && max != g) h += (g - b) / delta; - if (max == g && max != b) h += (2 + (b - r) / delta); - if (max == b && max != r) h += (4 + (r - g) / delta); - h /= 6; - } - return [h, s, l]; - } - - // Install mousedown handler (the others are set on the document on-demand) - $('*', e).click(fb.click); + fb.absolutePosition = function (el) { + var r = { x: el.offsetLeft, y: el.offsetTop }; + // Resolve relative to offsetParent + if (el.offsetParent) { + var tmp = fb.absolutePosition(el.offsetParent); + r.x += tmp.x; + r.y += tmp.y; + } + return r; + }; + + /* Various color utility functions */ + fb.pack = function (rgb) { + var r = Math.round(rgb[0] * 255); + var g = Math.round(rgb[1] * 255); + var b = Math.round(rgb[2] * 255); + return "#" + (r < 16 ? "0" : "") + r.toString(16) + + (g < 16 ? "0" : "") + g.toString(16) + + (b < 16 ? "0" : "") + b.toString(16); + }; + + fb.unpack = function (color) { + if (color.length == 7) { + return [parseInt("0x" + color.substring(1, 3)) / 255, + parseInt("0x" + color.substring(3, 5)) / 255, + parseInt("0x" + color.substring(5, 7)) / 255]; + } else if (color.length == 4) { + return [parseInt("0x" + color.substring(1, 2)) / 15, + parseInt("0x" + color.substring(2, 3)) / 15, + parseInt("0x" + color.substring(3, 4)) / 15]; + } + }; + + fb.HSLToRGB = function (hsl) { + var m1, m2, r, g, b; + var h = hsl[0], s = hsl[1], l = hsl[2]; + m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; + m1 = l * 2 - m2; + return [this.hueToRGB(m1, m2, h + 0.33333), + this.hueToRGB(m1, m2, h), + this.hueToRGB(m1, m2, h - 0.33333)]; + }; + + fb.hueToRGB = function (m1, m2, h) { + h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); + if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; + if (h * 2 < 1) return m2; + if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; + return m1; + }; + + fb.RGBToHSL = function (rgb) { + var min, max, delta, h, s, l; + var r = rgb[0], g = rgb[1], b = rgb[2]; + min = Math.min(r, Math.min(g, b)); + max = Math.max(r, Math.max(g, b)); + delta = max - min; + l = (min + max) / 2; + s = 0; + if (l > 0 && l < 1) { + s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); + } + h = 0; + if (delta > 0) { + if (max == r && max != g) h += (g - b) / delta; + if (max == g && max != b) h += (2 + (b - r) / delta); + if (max == b && max != r) h += (4 + (r - g) / delta); + h /= 6; + } + return [h, s, l]; + }; + + // Install mousedown handler (the others are set on the document on-demand) + $("*", e).click(fb.click); // Init color - fb.setColor('#000000'); + fb.setColor("#000000"); - // Set linked elements/callback - if (callback) { - fb.linkTo(callback); - } -}/** + // Set linked elements/callback + if (callback) { + fb.linkTo(callback); + } +};/** * Created by GUY on 2017/2/8. * * @class BI.BubbleCombo @@ -66900,20 +66726,20 @@ BI.BubbleCombo = BI.inherit(BI.Widget, { baseCls: "bi-bubble-combo", trigger: "click", toggle: true, - direction: "bottom", //top||bottom||left||right||top,left||top,right||bottom,left||bottom,right + direction: "bottom", // top||bottom||left||right||top,left||top,right||bottom,left||bottom,right isDefaultInit: false, destroyWhenHide: false, - isNeedAdjustHeight: true,//是否需要高度调整 + isNeedAdjustHeight: true, // 是否需要高度调整 isNeedAdjustWidth: true, stopPropagation: false, - adjustLength: 0,//调整的距离 + adjustLength: 0, // 调整的距离 // adjustXOffset: 0, // adjustYOffset: 10, hideChecker: BI.emptyFn, - offsetStyle: "left", //left,right,center + offsetStyle: "left", // left,right,center el: {}, popup: {} - }) + }); }, _init: function () { BI.BubbleCombo.superclass._init.apply(this, arguments); @@ -67030,7 +66856,7 @@ BI.BubbleCombo = BI.inherit(BI.Widget, { type: "bi.absolute", element: this, items: [pos] - }) + }); }, _createLeftTriangle: function () { @@ -67117,7 +66943,7 @@ BI.BubblePopupView = BI.inherit(BI.PopupView, { var config = BI.BubblePopupView.superclass._defaultConfig.apply(this, arguments); return BI.extend(config, { baseCls: config.baseCls + " bi-bubble-popup-view" - }) + }); }, _init: function () { BI.BubblePopupView.superclass._init.apply(this, arguments); @@ -67170,7 +66996,7 @@ BI.BubblePopupView = BI.inherit(BI.PopupView, { type: "bi.absolute", element: this, items: [pos] - }) + }); }, hideLine: function () { @@ -67191,7 +67017,7 @@ BI.BubblePopupBarView = BI.inherit(BI.BubblePopupView, { return BI.extend(BI.BubblePopupBarView.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-bubble-bar-popup-view", buttons: [{value: BI.i18nText(BI.i18nText("BI-Basic_Sure"))}, {value: BI.i18nText("BI-Basic_Cancel"), level: "ignore"}] - }) + }); }, _init: function () { BI.BubblePopupBarView.superclass._init.apply(this, arguments); @@ -67201,20 +67027,20 @@ BI.BubblePopupBarView = BI.inherit(BI.BubblePopupView, { var items = []; BI.each(o.buttons.reverse(), function (i, buttonOpt) { - if(BI.isWidget(buttonOpt)){ + if(BI.isWidget(buttonOpt)) { items.push(buttonOpt); }else{ items.push(BI.extend({ - type: 'bi.button', + type: "bi.button", height: 30, handler: function (v) { self.fireEvent(BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON, v); } - }, buttonOpt)) + }, buttonOpt)); } }); return BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", height: 40, hgap: 10, bgap: 10, @@ -67238,7 +67064,7 @@ BI.EditorIconCheckCombo = BI.inherit(BI.Widget, { allowBlank: true, watermark: "", errorText: "" - }) + }); }, _init: function () { @@ -67313,15 +67139,15 @@ BI.IconCombo = BI.inherit(BI.Widget, { el: {}, popup: {}, minWidth: 100, - maxWidth: 'auto', + maxWidth: "auto", maxHeight: 300, direction: "bottom", - adjustLength: 3,//调整的距离 + adjustLength: 3, // 调整的距离 adjustXOffset: 0, adjustYOffset: 0, offsetStyle: "left", chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE - }) + }); }, _init: function () { @@ -67527,11 +67353,11 @@ BI.IconComboTrigger = BI.inherit(BI.Trigger, { var iconClass = ""; v = BI.isArray(v) ? v[0] : v; if (BI.any(this.options.items, function (i, item) { - if (v === item.value) { - iconClass = item.iconClass; - return true; - } - })) { + if (v === item.value) { + iconClass = item.iconClass; + return true; + } + })) { this.button.setIcon(iconClass); this.button.setSelected(true); this.down.setSelected(true); @@ -67680,7 +67506,7 @@ BI.StaticCombo = BI.inherit(BI.Widget, { el: {}, items: [], chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE - }) + }); }, _init: function () { @@ -67818,7 +67644,7 @@ BI.SmallTextValueCheckCombo = BI.inherit(BI.Widget, { height: 24, chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, text: "" - }) + }); }, _init: function () { @@ -68009,7 +67835,7 @@ BI.SmallTextValueCombo = BI.inherit(BI.Widget, { chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, el: {}, text: "" - }) + }); }, _init: function () { @@ -68126,7 +67952,7 @@ BI.TextValueDownListCombo = BI.inherit(BI.Widget, { return BI.extend(BI.TextValueDownListCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-text-value-down-list-combo", height: 30 - }) + }); }, _init: function () { @@ -68168,7 +67994,7 @@ BI.TextValueDownListCombo = BI.inherit(BI.Widget, { BI.each(BI.flatten(this.options.items), function (idx, item) { if (BI.has(item, "el")) { BI.each(item.children, function (id, it) { - self.valueMap[it.value] = {value: item.el.value, childValue: it.value} + self.valueMap[it.value] = {value: item.el.value, childValue: it.value}; }); } else { self.valueMap[item.value] = {value: item.value}; @@ -68223,12 +68049,12 @@ BI.DownListSelectTextTrigger = BI.inherit(BI.Trigger, { }); }, - _formatItemArray: function(){ + _formatItemArray: function () { var sourceArray = BI.flatten(BI.deepClone(this.options.items)); var targetArray = []; - BI.each(sourceArray, function(idx, item){ - if(BI.has(item, "el")){ - BI.each(item.children, function(id, it){ + BI.each(sourceArray, function (idx, item) { + if(BI.has(item, "el")) { + BI.each(item.children, function (id, it) { it.text = item.el.text + "(" + it.text + ")"; }); targetArray = BI.concat(targetArray, item.children); @@ -68320,34 +68146,34 @@ BI.ClearEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.ClearEditor.EVENT_KEY_DOWN, v); }); this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.ClearEditor.EVENT_SPACE) + self.fireEvent(BI.ClearEditor.EVENT_SPACE); }); this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.ClearEditor.EVENT_BACKSPACE) + self.fireEvent(BI.ClearEditor.EVENT_BACKSPACE); }); this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.ClearEditor.EVENT_VALID) + self.fireEvent(BI.ClearEditor.EVENT_VALID); }); this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.ClearEditor.EVENT_ERROR) + self.fireEvent(BI.ClearEditor.EVENT_ERROR); }); this.editor.on(BI.Editor.EVENT_ENTER, function () { self.fireEvent(BI.ClearEditor.EVENT_ENTER); }); this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.ClearEditor.EVENT_RESTRICT) + self.fireEvent(BI.ClearEditor.EVENT_RESTRICT); }); this.editor.on(BI.Editor.EVENT_EMPTY, function () { self._checkClear(); - self.fireEvent(BI.ClearEditor.EVENT_EMPTY) + self.fireEvent(BI.ClearEditor.EVENT_EMPTY); }); this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.ClearEditor.EVENT_REMOVE) + self.fireEvent(BI.ClearEditor.EVENT_REMOVE); }); this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.ClearEditor.EVENT_CONFIRM) + self.fireEvent(BI.ClearEditor.EVENT_CONFIRM); }); this.editor.on(BI.Editor.EVENT_START, function () { self.fireEvent(BI.ClearEditor.EVENT_START); @@ -68439,7 +68265,7 @@ BI.ShelterEditor = BI.inherit(BI.Widget, { errorText: "", height: 24, textAlign: "left" - }) + }); }, _init: function () { @@ -68695,7 +68521,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { value: "", text: "", height: 24 - }) + }); }, _init: function () { @@ -68734,7 +68560,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignInitialEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignInitialEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ @@ -68907,7 +68733,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { return { value: this.editor.getValue(), text: this.options.text - } + }; }, getState: function () { @@ -68962,7 +68788,7 @@ BI.SignEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -69001,7 +68827,7 @@ BI.SignEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ @@ -69220,7 +69046,7 @@ BI.StateEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -69494,7 +69320,7 @@ BI.SimpleStateEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -69734,7 +69560,7 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { _defaultConfig: function () { return BI.extend(BI.BarPopoverSection.superclass._defaultConfig.apply(this, arguments), { btns: [BI.i18nText(BI.i18nText("BI-Basic_Sure")), BI.i18nText(BI.i18nText("BI-Basic_Cancel"))] - }) + }); }, _init: function () { @@ -69744,7 +69570,7 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { rebuildSouth: function (south) { var self = this, o = this.options; this.sure = BI.createWidget({ - type: 'bi.button', + type: "bi.button", text: this.options.btns[0], warningTitle: o.warningTitle, height: 30, @@ -69755,24 +69581,24 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { } }); this.cancel = BI.createWidget({ - type: 'bi.button', + type: "bi.button", text: this.options.btns[1], height: 30, value: 1, - level: 'ignore', + level: "ignore", handler: function (v) { self.close(v); } }); BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", element: south, lgap: 10, items: [this.cancel, this.sure] }); }, - setConfirmButtonEnable: function(v){ + setConfirmButtonEnable: function (v) { this.sure.setEnable(!!v); } });/** @@ -69788,7 +69614,7 @@ BI.MultiPopupView = BI.inherit(BI.PopupView, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-multi-list-view", buttons: [BI.i18nText("BI-Basic_Sure")] - }) + }); }, _init: function () { @@ -69801,12 +69627,12 @@ BI.MultiPopupView = BI.inherit(BI.PopupView, { return; } - var text = []; //构造[{text:content},……] + var text = []; // 构造[{text:content},……] BI.each(o.buttons, function (idx, item) { text.push({ text: item, value: idx - }) + }); }); this.buttongroup = BI.createWidget({ @@ -69851,7 +69677,7 @@ BI.PopupPanel = BI.inherit(BI.MultiPopupView, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-popup-panel", title: "" - }) + }); }, _init: function () { @@ -69923,7 +69749,7 @@ BI.ListPane = BI.inherit(BI.Pane, { el: { type: "bi.button_group" } - }) + }); }, _init: function () { BI.ListPane.superclass._init.apply(this, arguments); @@ -69938,7 +69764,7 @@ BI.ListPane = BI.inherit(BI.Pane, { if (op.times === 1) { self.empty(); BI.nextTick(function () { - self.loading() + self.loading(); }); } o.itemsCreator(op, function () { @@ -70006,7 +69832,7 @@ BI.ListPane = BI.inherit(BI.Pane, { populate: function (items) { var self = this, o = this.options; - if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {//接管loader的populate方法 + if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 this.button_group.attr("itemsCreator").apply(this, [{times: 1}, function () { if (arguments.length === 0) { throw new Error("参数不能为空"); @@ -70073,32 +69899,32 @@ BI.shortcut("bi.list_pane", BI.ListPane);/** * @class BI.Panel * @extends BI.Widget */ -BI.Panel = BI.inherit(BI.Widget,{ - _defaultConfig : function(){ - return BI.extend(BI.Panel.superclass._defaultConfig.apply(this,arguments),{ +BI.Panel = BI.inherit(BI.Widget, { + _defaultConfig: function () { + return BI.extend(BI.Panel.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-panel bi-border", - title:"", - titleButtons:[], - el:{}, - logic:{ + title: "", + titleButtons: [], + el: {}, + logic: { dynamic: false } }); }, - _init:function(){ - BI.Panel.superclass._init.apply(this,arguments); + _init: function () { + BI.Panel.superclass._init.apply(this, arguments); var o = this.options; BI.createWidget(BI.extend({ element: this }, BI.LogicFactory.createLogic("vertical", BI.extend(o.logic, { items: BI.LogicFactory.createLogicItemsByDirection("top", this._createTitle() - ,this.options.el) + , this.options.el) })))); }, - _createTitle:function(){ + _createTitle: function () { var self = this, o = this.options; this.text = BI.createWidget({ type: "bi.label", @@ -70108,19 +69934,19 @@ BI.Panel = BI.inherit(BI.Widget,{ }); this.button_group = BI.createWidget({ - type:"bi.button_group", + type: "bi.button_group", items: o.titleButtons, layouts: [{ type: "bi.center_adapt", - lgap:10 + lgap: 10 }] }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function(){ + this.button_group.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.ButtonGroup.EVENT_CHANGE, function(value, obj){ + this.button_group.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { self.fireEvent(BI.Panel.EVENT_CHANGE, value, obj); }); @@ -70140,13 +69966,13 @@ BI.Panel = BI.inherit(BI.Widget,{ }; }, - setTitle: function(title){ + setTitle: function (title) { this.text.setValue(title); } }); BI.Panel.EVENT_CHANGE = "Panel.EVENT_CHANGE"; -BI.shortcut("bi.panel",BI.Panel);/** +BI.shortcut("bi.panel", BI.Panel);/** * 选择列表 * * Created by GUY on 2015/11/1. @@ -70158,7 +69984,7 @@ BI.SelectList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SelectList.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-select-list", - direction: BI.Direction.Top,//toolbar的位置 + direction: BI.Direction.Top, // toolbar的位置 logic: { dynamic: true }, @@ -70172,13 +69998,13 @@ BI.SelectList = BI.inherit(BI.Widget, { el: { type: "bi.list_pane" } - }) + }); }, _init: function () { BI.SelectList.superclass._init.apply(this, arguments); var self = this, o = this.options; - //全选 + // 全选 this.toolbar = BI.createWidget(o.toolbar); this.allSelected = false; this.toolbar.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { @@ -70289,13 +70115,13 @@ BI.SelectList = BI.inherit(BI.Widget, { value: this.list.getValue(), assist: this.list.getNotSelectedValue() }; - } else { - return { - type: BI.ButtonGroup.CHOOSE_TYPE_ALL, - value: this.list.getNotSelectedValue(), - assist: this.list.getValue() - }; } + return { + type: BI.ButtonGroup.CHOOSE_TYPE_ALL, + value: this.list.getNotSelectedValue(), + assist: this.list.getValue() + }; + }, empty: function () { @@ -70317,7 +70143,7 @@ BI.SelectList = BI.inherit(BI.Widget, { resetHeight: function (h) { var toolHeight = ( this.toolbar.element.outerHeight() || 25) * ( this.toolbar.isVisible() ? 1 : 0); this.list.resetHeight ? this.list.resetHeight(h - toolHeight) : - this.list.element.css({"max-height": h - toolHeight + "px"}) + this.list.element.css({"max-height": h - toolHeight + "px"}); }, setNotSelectedValue: function () { @@ -70369,7 +70195,7 @@ BI.LazyLoader = BI.inherit(BI.Widget, { return BI.extend(BI.LazyLoader.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-lazy-loader", el: {} - }) + }); }, _init: function () { @@ -70379,7 +70205,7 @@ BI.LazyLoader = BI.inherit(BI.Widget, { this.loader = BI.createWidget({ type: "bi.loader", element: this, - //下面是button_group的属性 + // 下面是button_group的属性 el: o.el, itemsCreator: function (options, populate) { @@ -70391,8 +70217,8 @@ BI.LazyLoader = BI.inherit(BI.Widget, { }); this.loader.on(BI.Loader.EVENT_CHANGE, function (obj) { - self.fireEvent(BI.LazyLoader.EVENT_CHANGE, obj) - }) + self.fireEvent(BI.LazyLoader.EVENT_CHANGE, obj); + }); }, _getNextItems: function (options) { var self = this, o = this.options; @@ -70471,9 +70297,9 @@ BI.ListLoader = BI.inherit(BI.Widget, { return BI.extend(BI.ListLoader.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-list-loader", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -70482,11 +70308,11 @@ BI.ListLoader = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, next: {}, hasNext: BI.emptyFn - }) + }); }, _nextLoad: function () { @@ -70530,7 +70356,7 @@ BI.ListLoader = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self._nextLoad(); } - }) + }); } BI.createWidget({ @@ -70555,7 +70381,7 @@ BI.ListLoader = BI.inherit(BI.Widget, { return !!o.hasNext.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, addItems: function (items) { @@ -70665,9 +70491,9 @@ BI.SortList = BI.inherit(BI.Widget, { return BI.extend(BI.SortList.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-sort-list", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -70676,14 +70502,14 @@ BI.SortList = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, next: {}, hasNext: BI.emptyFn - //containment: this.element, - //connectWith: ".bi-sort-list", - }) + // containment: this.element, + // connectWith: ".bi-sort-list", + }); }, _init: function () { @@ -70730,7 +70556,7 @@ BI.SortList = BI.inherit(BI.Widget, { "margin-right": $currentItem.css("margin-right"), "margin-top": $currentItem.css("margin-top"), "margin-bottom": $currentItem.css("margin-bottom"), - "margin": $currentItem.css("margin") + margin: $currentItem.css("margin") }); return holder.element; }, @@ -70839,10 +70665,10 @@ BI.AllCountPager = BI.inherit(BI.Widget, { return BI.extend(BI.AllCountPager.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-all-count-pager", height: 30, - pages: 1, //必选项 - curr: 1, //初始化当前页, pages为数字时可用, - count: 1 //总行数 - }) + pages: 1, // 必选项 + curr: 1, // 初始化当前页, pages为数字时可用, + count: 1 // 总行数 + }); }, _init: function () { BI.AllCountPager.superclass._init.apply(this, arguments); @@ -70948,7 +70774,7 @@ BI.AllCountPager = BI.inherit(BI.Widget, { element: this, columnSize: ["", 35, 40, 36], items: [count, this.editor, this.allPages, this.pager] - }) + }); }, alwaysShowPager: true, @@ -71010,8 +70836,8 @@ BI.DirectionPager = BI.inherit(BI.Widget, { baseCls: "bi-direction-pager", height: 30, horizontal: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -71019,15 +70845,15 @@ BI.DirectionPager = BI.inherit(BI.Widget, { lastPage: BI.emptyFn }, vertical: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, firstPage: 1, lastPage: BI.emptyFn } - }) + }); }, _init: function () { BI.DirectionPager.superclass._init.apply(this, arguments); @@ -71295,35 +71121,35 @@ BI.DetailPager = BI.inherit(BI.Widget, { vgap: 0 }], - dynamicShow: true, //是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 - //dynamicShow为false时以下两个有用 - dynamicShowFirstLast: false,//是否动态显示首页、尾页 - dynamicShowPrevNext: false,//是否动态显示上一页、下一页 - pages: false, //总页数 + dynamicShow: true, // 是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 + // dynamicShow为false时以下两个有用 + dynamicShowFirstLast: false, // 是否动态显示首页、尾页 + dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 + pages: false, // 总页数 curr: function () { return 1; - }, //初始化当前页 - groups: 0, //连续显示分页数 - jump: BI.emptyFn, //分页的回调函数 + }, // 初始化当前页 + groups: 0, // 连续显示分页数 + jump: BI.emptyFn, // 分页的回调函数 - first: false, //是否显示首页 - last: false, //是否显示尾页 + first: false, // 是否显示首页 + last: false, // 是否显示尾页 prev: "上一页", next: "下一页", firstPage: 1, - lastPage: function () { //在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: function () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, - hasPrev: BI.emptyFn, //pages不可用时有效 - hasNext: BI.emptyFn //pages不可用时有效 - }) + hasPrev: BI.emptyFn, // pages不可用时有效 + hasNext: BI.emptyFn // pages不可用时有效 + }); }, _init: function () { BI.DetailPager.superclass._init.apply(this, arguments); var self = this; this.currPage = BI.result(this.options, "curr"); - //翻页太灵敏 + // 翻页太灵敏 this._lock = false; this._debouce = BI.debounce(function () { self._lock = false; @@ -71350,17 +71176,17 @@ BI.DetailPager = BI.inherit(BI.Widget, { groups > pages && (groups = pages); } - //计算当前组 + // 计算当前组 dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); - //当前页非首页,则输出上一页 + // 当前页非首页,则输出上一页 if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) { if (BI.isKey(prev)) { view.push({ text: prev, value: "prev", disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) - }) + }); } else { view.push(BI.extend({ disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) @@ -71368,7 +71194,7 @@ BI.DetailPager = BI.inherit(BI.Widget, { } } - //当前组非首组,则输出首页 + // 当前组非首组,则输出首页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { view.push({ text: first, @@ -71384,14 +71210,14 @@ BI.DetailPager = BI.inherit(BI.Widget, { } } - //输出当前页组 + // 输出当前页组 dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; dict.end = dict.index > 1 ? (function () { var max = curr + (groups - dict.poor - 1); return max > pages ? pages : max; }()) : groups; - if (dict.end - dict.start < groups - 1) { //最后一组状态 + if (dict.end - dict.start < groups - 1) { // 最后一组状态 dict.start = dict.end - groups + 1; } var s = dict.start, e = dict.end; @@ -71405,16 +71231,16 @@ BI.DetailPager = BI.inherit(BI.Widget, { text: s, value: s, selected: true - }) + }); } else { view.push({ text: s, value: s - }) + }); } } - //总页数大于连续分页数,且当前组最大页小于总页,输出尾页 + // 总页数大于连续分页数,且当前组最大页小于总页,输出尾页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0) { view.push({ @@ -71427,27 +71253,27 @@ BI.DetailPager = BI.inherit(BI.Widget, { text: last, value: "last", disabled: !(pages > groups && dict.end < pages && groups !== 0) - }) + }); } - //当前页不为尾页时,输出下一页 + // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { if (BI.isKey(next)) { if (pages === false) { - return {text: next, value: "next", disabled: o.hasNext(curr) === false} + return {text: next, value: "next", disabled: o.hasNext(curr) === false}; } return (dict.flow && curr === pages) ? - {text: next, value: "next", disabled: true} + {text: next, value: "next", disabled: true} : - {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; - } else { - return BI.extend({ - disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) - }, next); + {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; } + return BI.extend({ + disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) + }, next); + }())); } @@ -71723,7 +71549,7 @@ BI.RichEditorParamAction = BI.inherit(BI.RichEditorAction, { keydown: function (e) { var o = this.options; var sel = this._get$Sel(); - if (e.keyCode === 229) {//中文输入法 + if (e.keyCode === 229) {// 中文输入法 if (this._isParam(sel)) { this._addBlank(sel); e.stopEvent(); @@ -71840,7 +71666,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** type: "bi.layout", height: 1 }, this.instance = this.addInstance()] - }) + }); }, addInstance: function () { @@ -71873,7 +71699,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** // return false; } } while (t = t.parentNode); - this.fireEvent('blur', t); + this.fireEvent("blur", t); this.lastSelectedInstance = this.selectedInstance; this.selectedInstance = null; // return false; @@ -71894,7 +71720,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** BI.NicEditor.EVENT_SELECTED = "selected"; BI.NicEditor.EVENT_BLUR = "blur"; BI.NicEditor.EVENT_KEYDOWN = "keydown"; - BI.shortcut('bi.nic_editor', BI.NicEditor); + BI.shortcut("bi.nic_editor", BI.NicEditor); var prefix = "niceditor-"; @@ -71915,7 +71741,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** outline: "none" }).html(o.value); - this.element.css("maxHeight", (o.maxHeight) ? o.maxHeight + 'px' : null); + this.element.css("maxHeight", (o.maxHeight) ? o.maxHeight + "px" : null); this.e = BI.createWidget({ type: "bi.layout", @@ -71941,12 +71767,12 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** // this.setContent("
    "); } this.instanceDoc = document.defaultView; - this.elm.element.on('mousedown', BI.bind(this.selected, this)); - this.elm.element.on('keydown', BI.bind(this.keyDown, this)); - this.elm.element.on('focus', BI.bind(this.selected, this)); - this.elm.element.on('blur', BI.bind(this.blur, this)); - this.elm.element.on('keyup', BI.bind(this.selected, this)); - this.ne.fireEvent('add'); + this.elm.element.on("mousedown", BI.bind(this.selected, this)); + this.elm.element.on("keydown", BI.bind(this.keyDown, this)); + this.elm.element.on("focus", BI.bind(this.selected, this)); + this.elm.element.on("blur", BI.bind(this.blur, this)); + this.elm.element.on("keyup", BI.bind(this.selected, this)); + this.ne.fireEvent("add"); }, disable: function () { @@ -71992,9 +71818,9 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** } } return contain; - } else { - return (this.getSel().type == "Control") ? r.item(0) : r.parentElement(); } + return (this.getSel().type == "Control") ? r.item(0) : r.parentElement(); + }, saveRng: function () { @@ -72016,7 +71842,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** } rng = document.selection.createRange(); - rng.moveStart('character', -el.innerText.length); + rng.moveStart("character", -el.innerText.length); var text = rng.text; for (var i = 0; i < el.innerText.length; i++) { if (el.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) { @@ -72040,7 +71866,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** }, keyDown: function (e, t) { - this.ne.fireEvent('keydown', e); + this.ne.fireEvent("keydown", e); }, selected: function (e) { @@ -72052,25 +71878,25 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** var selInstance = this.ne.selectedInstance; if (selInstance != this) { if (selInstance) { - this.ne.fireEvent('blur', e); + this.ne.fireEvent("blur", e); } this.ne.selectedInstance = this; - this.ne.fireEvent('focus', e); + this.ne.fireEvent("focus", e); } - this.ne.fireEvent('selected', e); + this.ne.fireEvent("selected", e); this.isFocused = true; - this.elm.element.addClass(prefix + 'selected'); + this.elm.element.addClass(prefix + "selected"); } // return false; }, blur: function () { this.isFocused = false; - this.elm.element.removeClass(prefix + 'selected'); + this.elm.element.removeClass(prefix + "selected"); }, saveContent: function () { - this.ne.fireEvent('save'); + this.ne.fireEvent("save"); this.e.element.value(this.getContent()); }, @@ -72080,13 +71906,13 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** getContent: function () { this.content = this.getElm().element.html(); - this.ne.fireEvent('get'); + this.ne.fireEvent("get"); return this.content; }, setContent: function (e) { this.content = e; - this.ne.fireEvent('set'); + this.ne.fireEvent("set"); this.elm.element.html(this.content); }, @@ -72135,7 +71961,7 @@ BI.RichEditorBackgroundChooserTrigger = BI.inherit(BI.Widget, { top: 7, left: 2 }] - }) + }); }, setValue: function (color) { @@ -72146,7 +71972,7 @@ BI.RichEditorBackgroundChooserTrigger = BI.inherit(BI.Widget, { return this.font.element.css("color"); } }); -BI.shortcut('bi.rich_editor_background_color_chooser_trigger', BI.RichEditorBackgroundChooserTrigger);/** +BI.shortcut("bi.rich_editor_background_color_chooser_trigger", BI.RichEditorBackgroundChooserTrigger);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorAlignCenterButton @@ -72183,7 +72009,7 @@ BI.RichEditorAlignCenterButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_center_button", BI.RichEditorAlignCenterButton)/** +BI.shortcut("bi.rich_editor_align_center_button", BI.RichEditorAlignCenterButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorAlignLeftButton @@ -72220,7 +72046,7 @@ BI.RichEditorAlignLeftButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_left_button", BI.RichEditorAlignLeftButton)/** +BI.shortcut("bi.rich_editor_align_left_button", BI.RichEditorAlignLeftButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorAlignRightButton @@ -72257,7 +72083,7 @@ BI.RichEditorAlignRightButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_right_button", BI.RichEditorAlignRightButton)/** +BI.shortcut("bi.rich_editor_align_right_button", BI.RichEditorAlignRightButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorBoldButton @@ -72297,7 +72123,7 @@ BI.RichEditorBoldButton = BI.inherit(BI.RichEditorAction, { this.bold.setSelected(false); } }); -BI.shortcut("bi.rich_editor_bold_button", BI.RichEditorBoldButton)/** +BI.shortcut("bi.rich_editor_bold_button", BI.RichEditorBoldButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorItalicButton @@ -72337,7 +72163,7 @@ BI.RichEditorItalicButton = BI.inherit(BI.RichEditorAction, { this.italic.setSelected(false); } }); -BI.shortcut("bi.rich_editor_italic_button", BI.RichEditorItalicButton)/** +BI.shortcut("bi.rich_editor_italic_button", BI.RichEditorItalicButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorParamButton @@ -72364,7 +72190,7 @@ BI.RichEditorParamButton = BI.inherit(BI.RichEditorParamAction, { width: 30 }); this.param.on(BI.Button.EVENT_CHANGE, function () { - self.addParam("参数") + self.addParam("参数"); }); }, activate: function () { @@ -72373,7 +72199,7 @@ BI.RichEditorParamButton = BI.inherit(BI.RichEditorParamAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_param_button", BI.RichEditorParamButton)/** +BI.shortcut("bi.rich_editor_param_button", BI.RichEditorParamButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorItalicButton @@ -72413,7 +72239,7 @@ BI.RichEditorUnderlineButton = BI.inherit(BI.RichEditorAction, { this.underline.setSelected(false); } }); -BI.shortcut("bi.rich_editor_underline_button", BI.RichEditorUnderlineButton)/** +BI.shortcut("bi.rich_editor_underline_button", BI.RichEditorUnderlineButton);/** * 颜色选择trigger * * Created by GUY on 2015/11/26. @@ -72453,7 +72279,7 @@ BI.RichEditorColorChooserTrigger = BI.inherit(BI.Widget, { top: 7, left: 2 }] - }) + }); }, setValue: function (color) { @@ -72464,7 +72290,7 @@ BI.RichEditorColorChooserTrigger = BI.inherit(BI.Widget, { return this.font.element.css("color"); } }); -BI.shortcut('bi.rich_editor_color_chooser_trigger', BI.RichEditorColorChooserTrigger);/** +BI.shortcut("bi.rich_editor_color_chooser_trigger", BI.RichEditorColorChooserTrigger);/** * 颜色选择 * * Created by GUY on 2015/11/26. @@ -72558,7 +72384,7 @@ BI.RichEditorColorChooser = BI.inherit(BI.RichEditorAction, { this.colorchooser.setValue(""); } }); -BI.shortcut('bi.rich_editor_color_chooser', BI.RichEditorColorChooser);/** +BI.shortcut("bi.rich_editor_color_chooser", BI.RichEditorColorChooser);/** * 字体大小选择 * * Created by GUY on 2015/11/26. @@ -72699,7 +72525,7 @@ BI.RichEditor = BI.inherit(BI.Widget, { } }); BI.RichEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.rich_editor', BI.RichEditor);/** +BI.shortcut("bi.rich_editor", BI.RichEditor);/** * 分段控件使用的button * * Created by GUY on 2015/9/7. @@ -72711,19 +72537,19 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { _defaultConfig: function () { var conf = BI.SegmentButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { - baseCls: (conf.baseCls || "") + ' bi-segment-button bi-list-item-active', + baseCls: (conf.baseCls || "") + " bi-segment-button bi-list-item-active", shadow: true, readonly: true, hgap: 5 - }) + }); }, _init: function () { BI.SegmentButton.superclass._init.apply(this, arguments); var opts = this.options, self = this; - //if (BI.isNumber(opts.height) && BI.isNull(opts.lineHeight)) { + // if (BI.isNumber(opts.height) && BI.isNull(opts.lineHeight)) { // this.element.css({lineHeight : (opts.height - 2) + 'px'}); - //} + // } this.text = BI.createWidget({ type: "bi.label", element: this, @@ -72732,7 +72558,7 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { text: opts.text, value: opts.value, hgap: opts.hgap - }) + }); }, setSelected: function () { @@ -72748,7 +72574,7 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { BI.SegmentButton.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.segment_button', BI.SegmentButton);/** +BI.shortcut("bi.segment_button", BI.SegmentButton);/** * 单选按钮组 * * Created by GUY on 2015/9/7. @@ -72779,13 +72605,13 @@ BI.Segment = BI.inherit(BI.Widget, { type: "bi.center" } ] - }) + }); this.buttonGroup.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments) + self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); this.buttonGroup.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { - self.fireEvent(BI.Segment.EVENT_CHANGE, value, obj) - }) + self.fireEvent(BI.Segment.EVENT_CHANGE, value, obj); + }); }, setValue: function (v) { @@ -72801,7 +72627,7 @@ BI.Segment = BI.inherit(BI.Widget, { } }); BI.Segment.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.segment', BI.Segment);/** +BI.shortcut("bi.segment", BI.Segment);/** * 自适应宽度的表格 * * Created by GUY on 2016/2/3. @@ -72821,11 +72647,11 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, isNeedResize: true, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -72838,9 +72664,9 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { regionColumnSize: [], header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -72875,7 +72701,7 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -72942,7 +72768,7 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { freezeCols: freezeCols, columnSize: columnSize, regionColumnSize: regionColumnSize - } + }; }, _populate: function () { @@ -73028,7 +72854,7 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { BI.AdaptiveTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.adaptive_table', BI.AdaptiveTable);/** +BI.shortcut("bi.adaptive_table", BI.AdaptiveTable);/** * * 层级树状结构的表格 * @@ -73044,13 +72870,13 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { el: { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -73063,7 +72889,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { regionColumnSize: [], - //行表头 + // 行表头 rowHeaderCreator: null, headerCellStyleGetter: BI.emptyFn, @@ -73074,14 +72900,14 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { footer: false, items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -73103,16 +72929,16 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { var deep = this._getHDeep(); if (deep <= 0) { newHeader.unshift(o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }); + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }); } else { newHeader[0] = o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }; + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }; } result.push(newHeader); } @@ -73123,7 +72949,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { var self = this, o = this.options; var result = []; - function track(node, layer) { + function track (node, layer) { node.type || (node.type = "bi.layer_tree_table_cell"); node.layer = layer; var next = [node]; @@ -73150,7 +72976,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { return o.summaryCellStyleGetter(true); } }].concat(node.values); - result.push(next) + result.push(next); } }); return BI.DynamicSummaryTreeTable.formatSummaryItems(result, header, o.crossItems, 1); @@ -73218,7 +73044,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { minColumnSize: this._formatColumns(minColumnSize, deep), maxColumnSize: this._formatColumns(maxColumnSize, deep), freezeCols: this._formatFreezeCols() - } + }; }, _init: function () { @@ -73378,13 +73204,13 @@ BI.DynamicSummaryTreeTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -73405,14 +73231,14 @@ BI.DynamicSummaryTreeTable = BI.inherit(BI.Widget, { footer: false, items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -73590,7 +73416,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { formatHorizontalItems: function (nodes, deep, isCross, styleGetter) { var result = []; - function track(store, node) { + function track (store, node) { var next; if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { @@ -73614,7 +73440,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { text: BI.i18nText("BI-Summary_Values"), type: "bi.table_style_cell", styleGetter: function () { - return styleGetter(store === -1) + return styleGetter(store === -1); } }; for (var i = next.length; i < deep; i++) { @@ -73661,7 +73487,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { BI.each(nodes, function (i, node) { track(-1, node); }); - //填充空位 + // 填充空位 BI.each(result, function (i, line) { var last = BI.last(line); for (var j = line.length; j < deep; j++) { @@ -73672,11 +73498,11 @@ BI.extend(BI.DynamicSummaryTreeTable, { }, formatSummaryItems: function (items, header, crossItems, deep) { - //求纵向需要去除的列 + // 求纵向需要去除的列 var cols = []; var leaf = 0; - function track(node) { + function track (node) { if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { track(child); @@ -73712,7 +73538,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { BI.each(items, function (i, node) { var nNode = node.slice(); BI.removeAt(nNode, cols); - nItems.push(nNode);; + nItems.push(nNode); }); header = nHeader; items = nItems; @@ -73732,7 +73558,7 @@ BI.LayerTreeTableCell = BI.inherit(BI.Widget, { baseCls: "bi-layer-tree-table-cell", layer: 0, text: "" - }) + }); }, _init: function () { @@ -73748,7 +73574,7 @@ BI.LayerTreeTableCell = BI.inherit(BI.Widget, { value: o.value, lgap: 5 + 30 * o.layer, rgap: 5 - }) + }); } }); @@ -73768,13 +73594,13 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, - isNeedResize: false,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: false, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -73796,14 +73622,14 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { header: [], items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -73825,16 +73651,16 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { var deep = this._getHDeep(); if (deep <= 0) { newHeader.unshift(o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }); + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }); } else { newHeader[0] = o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }; + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }; } result.push(newHeader); } @@ -73845,7 +73671,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { var self = this, o = this.options; var result = []; - function track(node, layer) { + function track (node, layer) { node.type || (node.type = "bi.layer_tree_table_cell"); node.layer = layer; var next = [node]; @@ -73870,7 +73696,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { return o.summaryCellStyleGetter(true); } }].concat(node.values); - result.push(next) + result.push(next); } }); return result; @@ -73918,7 +73744,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { minColumnSize: this._formatColumns(o.minColumnSize, deep), maxColumnSize: this._formatColumns(o.maxColumnSize, deep), freezeCols: this._formatFreezeCols() - } + }; }, _init: function () { @@ -74114,7 +73940,7 @@ BI.TableStyleCell = BI.inherit(BI.Single, { this._digestStyle(); } }); -BI.shortcut('bi.table_style_cell', BI.TableStyleCell);/** +BI.shortcut("bi.table_style_cell", BI.TableStyleCell);/** * * 树状结构的表格 * @@ -74129,12 +73955,12 @@ BI.TableTree = BI.inherit(BI.Widget, { el: { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -74153,14 +73979,14 @@ BI.TableTree = BI.inherit(BI.Widget, { header: [], items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -74222,7 +74048,7 @@ BI.TableTree = BI.inherit(BI.Widget, { return { header: header, items: items - } + }; }, setWidth: function (width) { @@ -74331,7 +74157,7 @@ BI.extend(BI.TableTree, { var self = this; var result = []; - function track(store, node) { + function track (store, node) { var next; if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { @@ -74350,12 +74176,12 @@ BI.extend(BI.TableTree, { } else { next = []; } - if (/**(store == -1 || node.children.length > 1) &&**/ BI.isNotEmptyArray(node.values)) { + if (/** (store == -1 || node.children.length > 1) &&**/ BI.isNotEmptyArray(node.values)) { var summary = { text: BI.i18nText("BI-Summary_Values"), type: "bi.table_style_cell", styleGetter: function () { - return styleGetter(store === -1) + return styleGetter(store === -1); } }; for (var i = next.length; i < deep; i++) { @@ -74403,7 +74229,7 @@ BI.extend(BI.TableTree, { BI.each(nodes, function (i, node) { track(-1, node); }); - //填充空位 + // 填充空位 BI.each(result, function (i, line) { var last = BI.last(line); for (var j = line.length; j < deep; j++) { @@ -74419,7 +74245,7 @@ BI.extend(BI.TableTree, { }, maxDeep: function (nodes) { - function track(deep, node) { + function track (deep, node) { var d = deep; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { @@ -74451,14 +74277,14 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { return BI.extend(BI.MultiSelectBar.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-multi-select-bar", height: 25, - text: BI.i18nText('BI-Select_All'), + text: BI.i18nText("BI-Select_All"), isAllCheckedBySelectedValue: BI.emptyFn, - //手动控制选中 + // 手动控制选中 disableSelected: true, isHalfCheckedBySelectedValue: function (selectedValues) { return selectedValues.length > 0; } - }) + }); }, _init: function () { BI.MultiSelectBar.superclass._init.apply(this, arguments); @@ -74517,7 +74343,7 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { this.half.invisible(); }, - //自己手动控制选中 + // 自己手动控制选中 beforeClick: function () { var isHalf = this.isHalfSelected(), isSelected = this.isSelected(); if (isHalf === true) { @@ -74573,10 +74399,10 @@ BI.BranchRelation = BI.inherit(BI.Widget, { baseCls: "bi-branch-relation-tree", items: [], - centerOffset: 0,//重心偏移量 + centerOffset: 0, // 重心偏移量 direction: BI.Direction.Bottom, align: BI.VerticalAlign.Top - }) + }); }, _init: function () { @@ -74584,11 +74410,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { this.populate(this.options.items); }, - //树分层 + // 树分层 _stratification: function () { var levels = []; this.tree.recursion(function (node, route) { - //node.isRoot = route.length <= 1; + // node.isRoot = route.length <= 1; node.leaf = node.isLeaf(); if (!levels[route.length - 1]) { levels[route.length - 1] = []; @@ -74598,11 +74424,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return levels; }, - //计算所有节点的叶子结点个数 + // 计算所有节点的叶子结点个数 _calculateLeaves: function () { var count = 0; - function track(node) { + function track (node) { var c = 0; if (node.isLeaf()) { return 1; @@ -74618,7 +74444,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return count; }, - //树平移 + // 树平移 _translate: function (levels) { var adjust = []; var maxLevel = levels.length; @@ -74629,16 +74455,16 @@ BI.BranchRelation = BI.inherit(BI.Widget, { BI.each(nodes, function (j, node) { if (node.isLeaf() && i < maxLevel - 1) { var newNode = new BI.Node(BI.UUID()); - //newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; + // newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; newNode.isNew = true; - //把node向下一层移 + // 把node向下一层移 var tar = 0; if (j > 0) { var c = nodes[j - 1].getLastChild(); tar = levels[i + 1].indexOf(c) + 1; } levels[i + 1].splice(tar, 0, node); - //新增一个临时树节点 + // 新增一个临时树节点 var index = node.parent.getChildIndex(node.id); node.parent.removeChildByIndex(index); node.parent.addChild(newNode, index); @@ -74648,12 +74474,12 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } else { adjust[i].push(node); } - }) + }); }); return adjust; }, - //树补白 + // 树补白 _fill: function (levels) { var adjust = []; var maxLevel = levels.length; @@ -74668,23 +74494,23 @@ BI.BranchRelation = BI.inherit(BI.Widget, { newNode.width = node.width; newNode.height = node.height; newNode.isNew = true; - //把node向下一层移 + // 把node向下一层移 var tar = 0; if (j > 0) { var c = nodes[j - 1].getLastChild(); tar = levels[i + 1].indexOf(c) + 1; } levels[i + 1].splice(tar, 0, newNode); - //新增一个临时树节点 + // 新增一个临时树节点 node.addChild(newNode); } adjust[i].push(node); - }) + }); }); return adjust; }, - //树调整 + // 树调整 _adjust: function (adjust) { while (true) { var isAllNeedAjust = false; @@ -74708,7 +74534,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { node.addChild(c); }); var newNode = new BI.Node(BI.UUID()); - //newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; + // newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; newNode.isNew = true; var index = node.parent.getChildIndex(node.id); node.parent.removeChildByIndex(index); @@ -74717,11 +74543,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { isAllNeedAjust = true; } } - }) + }); }); if (isAllNeedAjust === false) { break; - } else {//树重构 + } else {// 树重构 adjust = this._stratification(); } } @@ -74732,7 +74558,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var o = this.options; var width = 0; - function track1(node) { + function track1 (node) { var w = 0; if (node.isLeaf()) { return node.width; @@ -74743,7 +74569,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return w; } - function track2(node) { + function track2 (node) { var w = 0; if (node.isLeaf()) { return node.height; @@ -74772,7 +74598,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var o = this.options; var height = 0; - function track1(node) { + function track1 (node) { var h = 0; BI.each(node.getChildren(), function (i, child) { h = Math.max(h, track1(child)); @@ -74780,7 +74606,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return h + (node.height || 0); } - function track2(node) { + function track2 (node) { var h = 0; BI.each(node.getChildren(), function (i, child) { h = Math.max(h, track2(child)); @@ -74802,23 +74628,23 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var height = this._calculateHeight(); var levelCount = levels.length; var allLeavesCount = this._calculateLeaves(); - //计算坐标 + // 计算坐标 var xy = {}; var levelHeight = height / levelCount; BI.each(levels, function (i, nodes) { - //计算权重 + // 计算权重 var weights = []; BI.each(nodes, function (j, node) { weights[j] = (node.get("leaves") || 1) / allLeavesCount; }); BI.each(nodes, function (j, node) { - //求前j个元素的权重 + // 求前j个元素的权重 var weight = BI.sum(weights.slice(0, j)); - //求坐标 + // 求坐标 var x = weight * width + weights[j] * width / 2; var y = i * levelHeight + levelHeight / 2; xy[node.id] = {x: x, y: y}; - }) + }); }); return xy; }, @@ -74847,7 +74673,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Bottom: @@ -74868,7 +74694,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Left: @@ -74889,7 +74715,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Right: @@ -74910,7 +74736,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; } @@ -74922,14 +74748,14 @@ BI.BranchRelation = BI.inherit(BI.Widget, { levels = levels.reverse(); } var xy = this._calculateXY(levels); - //画图 + // 画图 this._stroke(levels, xy); }, _isNeedAdjust: function () { var o = this.options; return o.direction === BI.Direction.Top && o.align === BI.VerticalAlign.Bottom || o.direction === BI.Direction.Bottom && o.align === BI.VerticalAlign.Top - || o.direction === BI.Direction.Left && o.align === BI.HorizontalAlign.Right || o.direction === BI.Direction.Right && o.align === BI.HorizontalAlign.Left + || o.direction === BI.Direction.Left && o.align === BI.HorizontalAlign.Right || o.direction === BI.Direction.Right && o.align === BI.HorizontalAlign.Left; }, setValue: function (value) { @@ -74963,9 +74789,9 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } } return r; - } else { - return [sNodes]; } + return [sNodes]; + }, populate: function (items) { @@ -74980,13 +74806,13 @@ BI.BranchRelation = BI.inherit(BI.Widget, { type: "bi.svg" }); - //树分层 + // 树分层 var levels = this._stratification(); if (this._isNeedAdjust()) { - //树平移 + // 树平移 var adjust = this._translate(levels); - //树调整 + // 树调整 adjust = this._adjust(adjust); this._createBranches(adjust); @@ -75025,7 +74851,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { }] }, items: items - }] + }]; } else { items = [{ type: "bi.branch_tree", @@ -75040,7 +74866,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { }] }, items: items - }] + }]; } BI.createWidget({ type: "bi.adaptive", @@ -75072,7 +74898,7 @@ BI.HandStandBranchExpander = BI.inherit(BI.Widget, { }, el: {type: "bi.label"}, popup: {} - }) + }); }, _init: function () { @@ -75130,7 +74956,7 @@ BI.BranchExpander = BI.inherit(BI.Widget, { }, el: {}, popup: {} - }) + }); }, _init: function () { @@ -75187,7 +75013,7 @@ BI.HandStandBranchTree = BI.inherit(BI.Widget, { expander: {}, el: {}, items: [] - }) + }); }, _init: function () { BI.HandStandBranchTree.superclass._init.apply(this, arguments); @@ -75211,10 +75037,10 @@ BI.HandStandBranchTree = BI.inherit(BI.Widget, { }, o.el), items: this.options.items }); - this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function(){ + this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function () { self.fireEvent(BI.HandStandBranchTree.EVENT_CHANGE, arguments); }); - this.branchTree.on(BI.Controller.EVENT_CHANGE, function(){ + this.branchTree.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); }, @@ -75241,7 +75067,7 @@ BI.BranchTree = BI.inherit(BI.Widget, { expander: {}, el: {}, items: [] - }) + }); }, _init: function () { BI.BranchTree.superclass._init.apply(this, arguments); @@ -75265,10 +75091,10 @@ BI.BranchTree = BI.inherit(BI.Widget, { }, o.el), items: this.options.items }); - this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function(){ + this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function () { self.fireEvent(BI.BranchTree.EVENT_CHANGE, arguments); }); - this.branchTree.on(BI.Controller.EVENT_CHANGE, function(){ + this.branchTree.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); }, @@ -75292,13 +75118,13 @@ BI.DisplayTree = BI.inherit(BI.TreeView, { _defaultConfig: function () { return BI.extend(BI.DisplayTree.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-display-tree" - }) + }); }, _init: function () { BI.DisplayTree.superclass._init.apply(this, arguments); }, - //配置属性 + // 配置属性 _configSetting: function () { var setting = { view: { @@ -75321,7 +75147,7 @@ BI.DisplayTree = BI.inherit(BI.TreeView, { } }; - function beforeCollapse(treeId, treeNode) { + function beforeCollapse (treeId, treeNode) { return false; } @@ -75367,7 +75193,7 @@ BI.LevelTree = BI.inherit(BI.Widget, { }, expander: {}, items: [] - }) + }); }, _init: function () { @@ -75419,7 +75245,7 @@ BI.LevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -75449,10 +75275,10 @@ BI.LevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.LevelTree.EVENT_CHANGE, arguments); } - }) + }); }, - //生成树方法 + // 生成树方法 stroke: function (nodes) { this.tree.stroke.apply(this.tree, arguments); }, @@ -75497,7 +75323,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { baseCls: "bi-simple-tree", itemsCreator: BI.emptyFn, items: null - }) + }); }, _init: function () { BI.SimpleTreeView.superclass._init.apply(this, arguments); @@ -75578,7 +75404,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { } else { track(node); } - }) + }); }; track(val); return result; @@ -75597,7 +75423,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { if (node.isLeaf()) { result.push(node.value); } - }) + }); } }); return result; @@ -75653,7 +75479,7 @@ BI.EditorTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -75709,7 +75535,7 @@ BI.IconTrigger = BI.inherit(BI.Trigger, { }); } }); -BI.shortcut('bi.icon_trigger', BI.IconTrigger);/** +BI.shortcut("bi.icon_trigger", BI.IconTrigger);/** * 文字trigger * * Created by GUY on 2015/9/15. @@ -75747,7 +75573,7 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", ref: function (_ref) { self.wrapper = _ref; }, @@ -75762,12 +75588,12 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { }, width: o.triggerWidth || o.height }, - { - el: this.text - }, { - el: this.trigerButton, - width: o.triggerWidth || o.height - } + { + el: this.text + }, { + el: this.trigerButton, + width: o.triggerWidth || o.height + } ] }); }, @@ -75781,13 +75607,13 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { var o = this.options; this.icon.setIcon(iconCls); var iconItem = this.wrapper.attr("items")[0]; - if(BI.isNull(iconCls) || BI.isEmptyString(iconCls)){ - if(iconItem.width !== 0){ + if(BI.isNull(iconCls) || BI.isEmptyString(iconCls)) { + if(iconItem.width !== 0) { iconItem.width = 0; this.wrapper.resize(); } }else{ - if(iconItem.width !== (o.triggerWidth || o.height)){ + if(iconItem.width !== (o.triggerWidth || o.height)) { iconItem.width = (o.triggerWidth || o.height); this.wrapper.resize(); } @@ -75892,7 +75718,7 @@ BI.TextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.text @@ -76055,7 +75881,7 @@ BI.SmallTextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.text @@ -76087,7 +75913,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { return BI.extend(BI.SequenceTableTreeNumber.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-sequence-table-tree-number", isNeedFreeze: false, - startSequence: 1,//开始的序号 + startSequence: 1, // 开始的序号 scrollTop: 0, headerRowSize: 25, rowSize: 25, @@ -76095,9 +75921,9 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { sequenceHeaderCreator: null, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -76142,7 +75968,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { el: this.scrollContainer }] }); - //缓存第一行对应的序号 + // 缓存第一行对应的序号 this.start = this.options.startSequence; this.cache = {}; this._nextState(); @@ -76155,8 +75981,8 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { var start = this.start; var cnt = this.start; - function track(node) { - //如果已经有缓存了就不改计数了,复杂表会出现这种情况 + function track (node) { + // 如果已经有缓存了就不改计数了,复杂表会出现这种情况 self.cache[node.text || node.value] || (self.cache[node.text || node.value] = cnt); cnt++; } @@ -76169,7 +75995,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { start = cnt = self.cache[child.text || child.value]; } } - track(child) + track(child); }); } }); @@ -76200,13 +76026,13 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { var result = []; var count = this._getStart(nodes); - function getLeafCount(node) { + function getLeafCount (node) { var cnt = 0; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { cnt += getLeafCount(child); }); - if (/**node.children.length > 1 && **/BI.isNotEmptyArray(node.values)) { + if (/** node.children.length > 1 && **/BI.isNotEmptyArray(node.values)) { cnt++; } } else { @@ -76367,7 +76193,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { } : function (key) { return function () { return o.sequenceCellStyleGetter(key); - } + }; }(numbers[key].index) }, numbers[key])); renderedCells.push({ @@ -76379,7 +76205,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { } }); - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (BI.deepContains(self.renderedKeys, key)) { @@ -76402,7 +76228,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { }); var addedItems = []; BI.each(addSet, function (index) { - addedItems.push(renderedCells[index]) + addedItems.push(renderedCells[index]); }); BI.createWidget({ type: "bi.absolute", @@ -76494,7 +76320,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { this._populate(); } }); -BI.shortcut('bi.sequence_table_tree_number', BI.SequenceTableTreeNumber);/** +BI.shortcut("bi.sequence_table_tree_number", BI.SequenceTableTreeNumber);/** * 自适应布局 * * 1、resize @@ -76566,7 +76392,7 @@ BI.AdaptiveArrangement = BI.inherit(BI.Widget, { var self = this, o = this.options; item.element.css("zIndex", ++this.zIndex); item.element.mousedown(function () { - self._setSelect(item) + self._setSelect(item); }); }, @@ -76792,7 +76618,7 @@ BI.AdaptiveArrangement.EVENT_ELEMENT_RESIZE = "AdaptiveArrangement.EVENT_ELEMENT BI.AdaptiveArrangement.EVENT_ELEMENT_STOP_RESIZE = "AdaptiveArrangement.EVENT_ELEMENT_STOP_RESIZE"; BI.AdaptiveArrangement.EVENT_RESIZE = "AdaptiveArrangement.EVENT_RESIZE"; BI.AdaptiveArrangement.EVENT_SCROLL = "AdaptiveArrangement.EVENT_SCROLL"; -BI.shortcut('bi.adaptive_arrangement', BI.AdaptiveArrangement);/** +BI.shortcut("bi.adaptive_arrangement", BI.AdaptiveArrangement);/** * Arrangement的block面板 * * Created by GUY on 2016/3/1. @@ -76807,7 +76633,7 @@ BI.ArrangementBlock = BI.inherit(BI.Widget, { }); } }); -BI.shortcut('bi.arrangement_block', BI.ArrangementBlock);/** +BI.shortcut("bi.arrangement_block", BI.ArrangementBlock);/** * Arrangement的drop面板 * * Created by GUY on 2016/3/1. @@ -76822,7 +76648,7 @@ BI.ArrangementDroppable = BI.inherit(BI.Widget, { }); } }); -BI.shortcut('bi.arrangement_droppable', BI.ArrangementDroppable);/** +BI.shortcut("bi.arrangement_droppable", BI.ArrangementDroppable);/** * 布局 * * Created by GUY on 2016/2/23. @@ -76886,7 +76712,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { } }, - ////初始化操作//// + // //初始化操作//// _calculateRegions: function (items) { var self = this, o = this.options; this.regions = {}; @@ -76916,7 +76742,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return num1 >= num2 || this._isEqual(num1, num2); }, - //获取占有的最大Region + // 获取占有的最大Region _getRegionOccupied: function (regions) { var self = this, o = this.options; if (BI.size(regions || this.regions) <= 0) { @@ -76925,7 +76751,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: 0, width: 0, height: 0 - } + }; } var minLeft = BI.MAX, maxLeft = BI.MIN, minTop = BI.MAX, maxTop = BI.MIN; BI.each(regions || this.regions, function (id, region) { @@ -76939,10 +76765,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: minTop, width: maxLeft - minLeft, height: maxTop - minTop - } + }; }, - //两个区域的交叉面积 + // 两个区域的交叉面积 _getCrossArea: function (region1, region2) { if (region1.left <= region2.left) { if (region1.top <= region2.top) { @@ -76980,7 +76806,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return 0; }, - //是否有覆盖的组件 + // 是否有覆盖的组件 _isRegionOverlay: function (regions) { var reg = []; BI.each(regions || this.regions, function (id, region) { @@ -77008,7 +76834,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return false; }, - //布局是否是优良的 + // 布局是否是优良的 _isArrangeFine: function (regions) { switch (this.options.layoutType) { case BI.Arrangement.LAYOUT_TYPE.FREE: @@ -77062,24 +76888,24 @@ BI.Arrangement = BI.inherit(BI.Widget, { return clone; }, - //测试合法性 + // 测试合法性 _test: function (regions) { var self = this; return !BI.any(regions || this.regions, function (i, region) { if (BI.isNaN(region.width) || BI.isNaN(region.height) || region.width <= 21 || region.height <= 21) { return true; } - }) + }); }, _getScrollOffset: function () { return { left: this.container.element[0].scrollLeft, top: this.container.element[0].scrollTop - } + }; }, - ////操作//// + // //操作//// _createOneRegion: function (item) { var el = BI.createWidget(item.el); el.setVisible(true); @@ -77090,7 +76916,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { width: item.width, height: item.height, el: el - } + }; }, _applyRegion: function (regions) { @@ -77170,10 +76996,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: size.top, width: size.width, height: size.height - }) + }); }, - //Grid + // Grid _getOneWidthPortion: function () { return this.getClientWidth() / BI.Arrangement.PORTION; }, @@ -77208,7 +77034,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { y: topPortion, w: widthPortion, h: heightPortion - } + }; }, _getBlockPositionAndSize: function (position) { @@ -77228,7 +77054,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { BI.each(regions || this.regions, function (id, region) { result.push(BI.extend(self._getGridPositionAndSize(region), { i: region.id - })) + })); }); return result; }, @@ -77281,10 +77107,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { } var movingUp = y && l.y > y; - if (typeof x === 'number') { + if (typeof x === "number") { l.x = x; } - if (typeof y === 'number') { + if (typeof y === "number") { l.y = y; } l.moved = true; @@ -77314,7 +77140,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return layout; - function getAllCollisions(layout, layoutItem) { + function getAllCollisions (layout, layoutItem) { return BI.filter(layout, function (i, l) { return self._collides(l, layoutItem); }); @@ -77358,14 +77184,14 @@ BI.Arrangement = BI.inherit(BI.Widget, { }, _moveElementAwayFromCollision: function (layout, collidesWith, - itemToMove, isUserAction) { + itemToMove, isUserAction) { if (isUserAction) { var fakeItem = { x: itemToMove.x, y: itemToMove.y, w: itemToMove.w, h: itemToMove.h, - i: '-1' + i: "-1" }; fakeItem.y = Math.max(collidesWith.y - itemToMove.h, 0); if (!this._getFirstCollision(layout, fakeItem)) { @@ -77411,14 +77237,14 @@ BI.Arrangement = BI.inherit(BI.Widget, { return out; - function getStatics(layout) { + function getStatics (layout) { return BI.filter(layout, function (i, l) { return l._static; }); } }, - ////公有方法//// + // //公有方法//// getRegionByName: function (name) { var obj = {}; obj[name] = this.regions[name]; @@ -77457,7 +77283,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { this.block.setVisible(false); }, - ////公有操作//// + // //公有操作//// setLayoutType: function (type) { var self = this, o = this.options; if (type !== o.layoutType) { @@ -77482,7 +77308,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return { x: BI.parseFloat(BI.contentFormat((occupied.left + occupied.width) / width, "#.##;-#.##")), y: BI.parseFloat(BI.contentFormat((occupied.top + occupied.height) / height, "#.##;-#.##")) - } + }; }, addRegion: function (region, position) { @@ -77701,7 +77527,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { })); return function () { self.arrangement.setVisible(false); - } + }; }, scrollTo: function (scroll) { @@ -77720,13 +77546,13 @@ BI.Arrangement = BI.inherit(BI.Widget, { if (this._isArrangeFine()) { var width = this.getClientWidth(); var xRatio = (ratio.x || 1) * width / (occupied.left + occupied.width); - //var yRatio = ratio.y * height / (occupied.top + occupied.height); + // var yRatio = ratio.y * height / (occupied.top + occupied.height); var regions = this._cloneRegion(); BI.each(regions, function (i, region) { region.left = region.left * xRatio; - //region.top = region.top * yRatio; + // region.top = region.top * yRatio; region.width = region.width * xRatio; - //region.height = region.height * yRatio; + // region.height = region.height * yRatio; }); if (this._test(regions)) { this._modifyRegion(regions); @@ -77748,7 +77574,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { region.width = region.width * xRatio; region.top = region.top * yRatio; region.height = region.height * yRatio; - //做一下自适应布局到网格布局的兼容 + // 做一下自适应布局到网格布局的兼容 var perWidth = self._getOneWidthPortion(); var widthPortion = Math.round(region.width / perWidth); var leftPortion = Math.round(region.left / perWidth); @@ -77823,7 +77649,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { } store[row][col] = region; }); - //非4的倍数 + // 非4的倍数 // if (count % 4 !== 0) { // var lasts = store[rows - 1]; // var perWidth = width / (count % 4); @@ -77879,7 +77705,7 @@ BI.extend(BI.Arrangement, { FREE: 1 } }); -BI.shortcut('bi.arrangement', BI.Arrangement);/** +BI.shortcut("bi.arrangement", BI.Arrangement);/** * 日期控件中的月份下拉框 * * Created by GUY on 2015/9/7. @@ -77887,13 +77713,13 @@ BI.shortcut('bi.arrangement', BI.Arrangement);/** * @extends BI.Trigger */ BI.MonthDateCombo = BI.inherit(BI.Trigger, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.MonthDateCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-month-combo", height: 25 }); }, - _init: function() { + _init: function () { BI.MonthDateCombo.superclass._init.apply(this, arguments); var self = this, o = this.options; @@ -77905,9 +77731,9 @@ BI.MonthDateCombo = BI.inherit(BI.Trigger, { type: "bi.month_popup" }); - this.popup.on(BI.YearPopup.EVENT_CHANGE, function(){ + this.popup.on(BI.YearPopup.EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); - }) + }); this.combo = BI.createWidget({ @@ -77922,24 +77748,24 @@ BI.MonthDateCombo = BI.inherit(BI.Trigger, { stopPropagation: false, el: this.popup } - }) - this.combo.on(BI.Combo.EVENT_CHANGE, function(){ + }); + this.combo.on(BI.Combo.EVENT_CHANGE, function () { self.combo.hideView(); self.fireEvent(BI.MonthDateCombo.EVENT_CHANGE); }); }, - setValue: function(v){ + setValue: function (v) { this.trigger.setValue(v + 1); this.popup.setValue(v); }, - getValue: function(){ + getValue: function () { return this.popup.getValue(); } }); BI.MonthDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.month_date_combo', BI.MonthDateCombo);/** +BI.shortcut("bi.month_date_combo", BI.MonthDateCombo);/** * 年份下拉框 * * Created by GUY on 2015/9/7. @@ -77947,15 +77773,15 @@ BI.shortcut('bi.month_date_combo', BI.MonthDateCombo);/** * @extends BI.Trigger */ BI.YearDateCombo = BI.inherit(BI.Trigger, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.YearDateCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-combo", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 25 }); }, - _init: function() { + _init: function () { BI.YearDateCombo.superclass._init.apply(this, arguments); var self = this, o = this.options; @@ -77969,11 +77795,11 @@ BI.YearDateCombo = BI.inherit(BI.Trigger, { max: o.max }); - this.popup.on(BI.YearPopup.EVENT_CHANGE, function(){ + this.popup.on(BI.YearPopup.EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); self.combo.hideView(); self.fireEvent(BI.YearDateCombo.EVENT_CHANGE); - }) + }); this.combo = BI.createWidget({ @@ -77988,23 +77814,23 @@ BI.YearDateCombo = BI.inherit(BI.Trigger, { stopPropagation: false, el: this.popup } - }) - this.combo.on(BI.Combo.EVENT_CHANGE, function(){ + }); + this.combo.on(BI.Combo.EVENT_CHANGE, function () { self.fireEvent(BI.YearDateCombo.EVENT_CHANGE); - }) + }); }, - setValue: function(v){ + setValue: function (v) { this.trigger.setValue(v); this.popup.setValue(v); }, - getValue: function(){ + getValue: function () { return this.popup.getValue(); } }); BI.YearDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.year_date_combo', BI.YearDateCombo);/** +BI.shortcut("bi.year_date_combo", BI.YearDateCombo);/** * Created by GUY on 2015/9/7. * @class BI.DatePicker * @extends BI.Widget @@ -78015,9 +77841,9 @@ BI.DatePicker = BI.inherit(BI.Widget, { return BI.extend(conf, { baseCls: "bi-date-picker bi-background", height: 25, - min: '1900-01-01', //最小日期 - max: '2099-12-31' //最大日期 - }) + min: "1900-01-01", // 最小日期 + max: "2099-12-31" // 最大日期 + }); }, _init: function () { @@ -78036,12 +77862,12 @@ BI.DatePicker = BI.inherit(BI.Widget, { self.setValue({ year: self.year.getValue() - 1, month: 11 - }) + }); } else { self.setValue({ year: self.year.getValue(), month: self.month.getValue() - 1 - }) + }); } self.fireEvent(BI.DatePicker.EVENT_CHANGE); self._checkLeftValid(); @@ -78060,12 +77886,12 @@ BI.DatePicker = BI.inherit(BI.Widget, { self.setValue({ year: self.year.getValue() + 1, month: 0 - }) + }); } else { self.setValue({ year: self.year.getValue(), month: self.month.getValue() + 1 - }) + }); } self.fireEvent(BI.DatePicker.EVENT_CHANGE); self._checkLeftValid(); @@ -78083,7 +77909,7 @@ BI.DatePicker = BI.inherit(BI.Widget, { month: self.month.getValue() }); self.fireEvent(BI.DatePicker.EVENT_CHANGE); - }) + }); this.month = BI.createWidget({ type: "bi.month_date_combo" }); @@ -78112,11 +77938,11 @@ BI.DatePicker = BI.inherit(BI.Widget, { el: this.right, width: 25 }] - }) + }); this.setValue({ year: this._year, month: this._month - }) + }); }, _checkLeftValid: function () { @@ -78148,10 +77974,10 @@ BI.DatePicker = BI.inherit(BI.Widget, { return { year: this.year.getValue(), month: this.month.getValue() - } + }; } }); -BI.DatePicker.EVENT_CHANGE = "EVENT_CHANGE" +BI.DatePicker.EVENT_CHANGE = "EVENT_CHANGE"; BI.shortcut("bi.date_picker", BI.DatePicker);/** * Created by GUY on 2015/9/7. * @class BI.DateCalendarPopup @@ -78162,10 +77988,10 @@ BI.DateCalendarPopup = BI.inherit(BI.Widget, { var conf = BI.DateCalendarPopup.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: "bi-date-calendar-popup", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 selectedTime: null - }) + }); }, _createNav: function (v) { @@ -78181,7 +78007,7 @@ BI.DateCalendarPopup = BI.inherit(BI.Widget, { month: date.month, day: this.selectedTime.day }); - return calendar + return calendar; }, _init: function () { @@ -78262,13 +78088,13 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { iconHeight: 13 }, - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.DateTriangleTrigger.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-date-triangle-trigger pull-down-ha-font cursor-pointer", height: 25 }); }, - _init: function() { + _init: function () { BI.DateTriangleTrigger.superclass._init.apply(this, arguments); var o = this.options, c = this._const; this.text = BI.createWidget({ @@ -78278,7 +78104,7 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { text: o.text, value: o.value, height: c.height - }) + }); this.icon = BI.createWidget({ type: "bi.icon", width: c.iconWidth, @@ -78294,30 +78120,30 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { height: c.height, items: [this.text, this.icon] }] - }) + }); }, - setValue: function(v){ + setValue: function (v) { this.text.setValue(v); }, - getValue: function(){ + getValue: function () { return this.text.getValue(); }, - setText: function(v){ + setText: function (v) { this.text.setText(v); }, - getText: function(){ + getText: function () { return this.item.getText(); }, - getKey: function(){ + getKey: function () { } }); -BI.shortcut('bi.date_triangle_trigger', BI.DateTriangleTrigger);/** +BI.shortcut("bi.date_triangle_trigger", BI.DateTriangleTrigger);/** * 日期下拉框 * * Created by GUY on 2015/9/7. @@ -78364,7 +78190,7 @@ BI.DateCombo = BI.inherit(BI.Widget, { el: this.popup, stopPropagation: false } - }) + }); }, setValue: function (v) { @@ -78376,7 +78202,7 @@ BI.DateCombo = BI.inherit(BI.Widget, { return this.popup.getValue(); } }); -BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigger, { +BI.shortcut("bi.date_combo", BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigger, { _const: { hgap: 4, vgap: 2, @@ -78387,8 +78213,8 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge _defaultConfig: function () { return BI.extend(BI.DateTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-date-trigger", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24 }); }, @@ -78402,10 +78228,10 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge var date = v.match(/\d+/g); self._autoAppend(v, date); return self._dateCheck(v) && Date.checkLegal(v) && self._checkVoid({ - year: date[0], - month: date[1], - day: date[2] - }); + year: date[0], + month: date[1], + day: date[2] + }); }, quitChecker: function () { return false; @@ -78422,7 +78248,7 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge } }); this.editor.on(BI.SignEditor.EVENT_KEY_DOWN, function () { - self.fireEvent(BI.DateTrigger.EVENT_KEY_DOWN) + self.fireEvent(BI.DateTrigger.EVENT_KEY_DOWN); }); this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { self.fireEvent(BI.DateTrigger.EVENT_FOCUS); @@ -78446,7 +78272,7 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge var date = value.split("-"); self.store_value = { type: BI.DateTrigger.MULTI_DATE_CALENDAR, - value:{ + value: { year: date[0] | 0, month: date[1] - 1, day: date[2] | 0 @@ -78475,7 +78301,7 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge }, { el: this.editor }] - }) + }); }, _dateCheck: function (date) { return Date.parseDateTime(date, "%Y-%x-%d").print("%Y-%x-%d") == date || Date.parseDateTime(date, "%Y-%X-%d").print("%Y-%X-%d") == date || Date.parseDateTime(date, "%Y-%x-%e").print("%Y-%x-%e") == date || Date.parseDateTime(date, "%Y-%X-%e").print("%Y-%X-%e") == date; @@ -78514,7 +78340,7 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge this.store_value = v; if (BI.isNotNull(v)) { type = v.type || BI.DateTrigger.MULTI_DATE_CALENDAR; value = v.value; - if(BI.isNull(value)){ + if(BI.isNull(value)) { value = v; } } @@ -78699,10 +78525,10 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { var conf = BI.DatePaneWidget.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: "bi-date-pane", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 selectedTime: null - }) + }); }, _init: function () { BI.DatePaneWidget.superclass._init.apply(this, arguments); @@ -78713,9 +78539,9 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { this._month = this.today.getMonth(); this.selectedTime = o.selectedTime || { - year: this._year, - month: this._month - }; + year: this._year, + month: this._month + }; this.datePicker = BI.createWidget({ type: "bi.date_picker", @@ -78776,7 +78602,7 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { return { year: today.getFullYear(), month: today.getMonth() - } + }; }, _setCalenderValue: function (date) { @@ -78798,7 +78624,7 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { this.calendar.empty(); this._setCalenderValue(this._getNewCurrentDate()); } else { - this._setCalenderValue(timeOb) + this._setCalenderValue(timeOb); } }, @@ -78826,7 +78652,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { }, _defaultConfig: function () { return BI.extend(BI.DateTimeCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-date-time-combo bi-border', + baseCls: "bi-date-time-combo bi-border", width: 200, height: 24 }); @@ -78844,7 +78670,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { second: date.getSeconds() }; this.trigger = BI.createWidget({ - type: 'bi.date_time_trigger', + type: "bi.date_time_trigger", min: this.constants.DATE_MIN_VALUE, max: this.constants.DATE_MAX_VALUE }); @@ -78872,7 +78698,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { self.fireEvent(BI.DateTimeCombo.EVENT_CHANGE); }); this.combo = BI.createWidget({ - type: 'bi.combo', + type: "bi.combo", toggle: false, isNeedAdjustHeight: false, isNeedAdjustWidth: false, @@ -78921,7 +78747,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { left: 0 }] }] - }) + }); }, setValue: function (v) { @@ -78942,14 +78768,14 @@ BI.DateTimeCombo.EVENT_CANCEL = "EVENT_CANCEL"; BI.DateTimeCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.DateTimeCombo.EVENT_CHANGE = "EVENT_CHANGE"; BI.DateTimeCombo.EVENT_BEFORE_POPUPVIEW = "BI.DateTimeCombo.EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.date_time_combo', BI.DateTimeCombo); +BI.shortcut("bi.date_time_combo", BI.DateTimeCombo); /** * Created by Urthur on 2017/7/14. */ BI.DateTimePopup = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.DateTimePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-date-time-popup', + baseCls: "bi-date-time-popup", width: 268, height: 290 }); @@ -78958,9 +78784,9 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { BI.DateTimePopup.superclass._init.apply(this, arguments); var self = this, opts = this.options; this.cancelButton = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", forceCenter: true, - cls: 'multidate-popup-button bi-border-top bi-border-right', + cls: "multidate-popup-button bi-border-top bi-border-right", shadow: true, text: BI.i18nText("BI-Basic_Cancel") }); @@ -78971,7 +78797,7 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { this.okButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'multidate-popup-button bi-border-top', + cls: "multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_OK") }); @@ -79112,13 +78938,13 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { hour: this.hour.getValue(), minute: this.minute.getValue(), second: this.second.getValue() - } + }; } }); BI.DateTimePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; BI.DateTimePopup.BUTTON_CANCEL_EVENT_CHANGE = "BUTTON_CANCEL_EVENT_CHANGE"; BI.DateTimePopup.CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE"; -BI.shortcut('bi.date_time_popup', BI.DateTimePopup); +BI.shortcut("bi.date_time_popup", BI.DateTimePopup); /** * Created by Urthur on 2017/7/14. */ @@ -79128,7 +78954,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { baseCls: "bi-date-time-select bi-border", max: 23, min: 0 - }) + }); }, _init: function () { @@ -79139,11 +78965,11 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { value: this._alertInEditorValue(o.min), allowBlank: false, errorText: BI.i18nText("BI-Please_Input_Natural_Number"), - validationChecker: function(v){ + validationChecker: function (v) { return BI.isNaturalNumber(v); } }); - this.editor.on(BI.TextEditor.EVENT_CONFIRM, function(){ + this.editor.on(BI.TextEditor.EVENT_CONFIRM, function () { self._finetuning(0); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -79151,7 +78977,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { type: "bi.icon_button", cls: "column-pre-page-h-font top-button bi-border-left bi-border-bottom" }); - this.topBtn.on(BI.IconButton.EVENT_CHANGE, function(){ + this.topBtn.on(BI.IconButton.EVENT_CHANGE, function () { self._finetuning(1); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -79159,7 +78985,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { type: "bi.icon_button", cls: "column-next-page-h-font bottom-button bi-border-left" }); - this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function(){ + this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function () { self._finetuning(-1); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -79187,28 +79013,28 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { }); }, - _alertOutEditorValue: function(v){ - if (v > this.options.max){ + _alertOutEditorValue: function (v) { + if (v > this.options.max) { v = this.options.min; } - if (v < this.options.min){ - v = this.options.max + if (v < this.options.min) { + v = this.options.max; } return BI.parseInt(v); }, - _alertInEditorValue: function(v){ - if (v > this.options.max){ + _alertInEditorValue: function (v) { + if (v > this.options.max) { v = this.options.min; } - if (v < this.options.min){ + if (v < this.options.min) { v = this.options.max; } v = v < 10 ? "0" + v : v; return v; }, - _finetuning: function(add){ + _finetuning: function (add) { var v = BI.parseInt(this._alertOutEditorValue(this.editor.getValue())); this.editor.setValue(this._alertInEditorValue(v + add)); }, @@ -79236,8 +79062,8 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { _defaultConfig: function () { return BI.extend(BI.DateTimeTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-date-time-trigger", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24, width: 200 }); @@ -79262,7 +79088,7 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { }, { el: this.text }] - }) + }); }, _printTime: function (v) { @@ -79272,11 +79098,11 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { setValue: function (v) { var self = this; var value = v, dateStr; - if(BI.isNull(value)){ + if(BI.isNull(value)) { value = Date.getDate(); dateStr = value.print("%Y-%X-%d %H:%M:%S"); } else { - var date = Date.getDate(value.year,value.month,value.day,value.hour,value.minute,value.second); + var date = Date.getDate(value.year, value.month, value.day, value.hour, value.minute, value.second); dateStr = date.print("%Y-%X-%d %H:%M:%S"); } @@ -79315,7 +79141,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { items: o.items }); this.pathChooser.on(BI.PathChooser.EVENT_CHANGE, function (start, index) { - //self._unselectAllArrows(); + // self._unselectAllArrows(); self._setValue(start, index); self.fireEvent(BI.DirectionPathChooser.EVENT_CHANGE); }); @@ -79335,7 +79161,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { }, _drawOneArrow: function (dot, direction) { - //0,1,2,3 上右下左 + // 0,1,2,3 上右下左 var lineColor = this._const.lineColor; var selectLineColor = this._const.selectLineColor; var svg = this.pathChooser.svg; @@ -79433,17 +79259,17 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { } } }); - }) + }); }); - function getXoffsetByRegionIndex(regionIndex, diregion) { + function getXoffsetByRegionIndex (regionIndex, diregion) { if (diregion === -1) { return 100 * (regionIndex + 1) - 20; } return 100 * regionIndex + 20; } - function getYByXoffset(dots, xoffset) { + function getYByXoffset (dots, xoffset) { var finded = BI.find(dots, function (i, dot) { if (i > 0) { if (dots[i - 1].x < xoffset && dots[i].x > xoffset) { @@ -79503,7 +79329,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { if (array.length > 0) { result.push(array); } - //画这n条路径 + // 画这n条路径 BI.each(result, function (idx, path) { var start = path[0]; var index = BI.findIndex(routes[start], function (idx, p) { @@ -79527,7 +79353,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { } }); BI.DirectionPathChooser.EVENT_CHANGE = "DirectionPathChooser.EVENT_CHANGE"; -BI.shortcut('bi.direction_path_chooser', BI.DirectionPathChooser);/** +BI.shortcut("bi.direction_path_chooser", BI.DirectionPathChooser);/** * Created by roy on 15/8/14. */ BI.DownListCombo = BI.inherit(BI.Widget, { @@ -79542,7 +79368,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { trigger: "click", container: null, el: {} - }) + }); }, _init: function () { @@ -79567,7 +79393,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { this.downlistcombo = BI.createWidget({ element: this, - type: 'bi.combo', + type: "bi.combo", trigger: o.trigger, isNeedAdjustWidth: false, container: o.container, @@ -79607,7 +79433,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { this.popupview.setValue(v); }, getValue: function () { - return this.popupview.getValue() + return this.popupview.getValue(); } }); BI.DownListCombo.EVENT_CHANGE = "EVENT_CHANGE"; @@ -79629,7 +79455,7 @@ BI.DownListGroup = BI.inherit(BI.Widget, { el: {} } ] - }) + }); }, _init: function () { BI.DownListGroup.superclass._init.apply(this, arguments); @@ -79639,7 +79465,7 @@ BI.DownListGroup = BI.inherit(BI.Widget, { element: this, type: "bi.button_tree", items: o.items, - chooseType: 0,//0单选,1多选 + chooseType: 0, // 0单选,1多选 layouts: [{ type: "bi.vertical", hgap: 0, @@ -79651,17 +79477,17 @@ BI.DownListGroup = BI.inherit(BI.Widget, { if(type === BI.Events.CLICK) { self.fireEvent(BI.DownListGroup.EVENT_CHANGE, arguments); } - }) + }); }, - getValue:function(){ + getValue: function () { return this.downlistgroup.getValue(); }, - setValue:function(v){ + setValue: function (v) { this.downlistgroup.setValue(v); } -}) +}); BI.DownListGroup.EVENT_CHANGE = "EVENT_CHANGE"; BI.shortcut("bi.down_list_group", BI.DownListGroup);BI.DownListItem = BI.inherit(BI.Single, { _defaultConfig: function () { @@ -79680,7 +79506,7 @@ BI.shortcut("bi.down_list_group", BI.DownListGroup);BI.DownListItem = BI.inherit textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.DownListItem.superclass._init.apply(this, arguments); @@ -79752,7 +79578,7 @@ BI.shortcut("bi.down_list_item", BI.DownListItem);BI.DownListGroupItem = BI.inhe // invalid: true, iconCls1: "dot-e-font", iconCls2: "pull-right-e-font" - }) + }); }, _init: function () { BI.DownListGroupItem.superclass._init.apply(this, arguments); @@ -79808,7 +79634,7 @@ BI.shortcut("bi.down_list_item", BI.DownListItem);BI.DownListGroupItem = BI.inhe } }, function () { if (self.isEnabled()) { - self.dishover() + self.dishover(); } }); }, @@ -79848,10 +79674,10 @@ BI.shortcut("bi.down_list_item", BI.DownListItem);BI.DownListGroupItem = BI.inhe if (BI.contains(o.childValues, value)) { self.icon1.setSelected(true); return true; - } else { - self.icon1.setSelected(false); } - }) + self.icon1.setSelected(false); + + }); } }); BI.DownListGroupItem.EVENT_CHANGE = "EVENT_CHANGE"; @@ -79876,7 +79702,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { baseCls: "bi-down-list-popup", items: [], chooseType: BI.Selection.Multi - }) + }); }, _init: function () { BI.DownListPopup.superclass._init.apply(this, arguments); @@ -79903,7 +79729,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { var changedValue = value; if (BI.isNotNull(self.childValueMap[value])) { changedValue = self.childValueMap[value]; - self.fireEvent(BI.DownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, self.fatherValueMap[value]) + self.fireEvent(BI.DownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, self.fatherValueMap[value]); } else { self.fireEvent(BI.DownListPopup.EVENT_CHANGE, changedValue, object); } @@ -79979,7 +79805,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { self.childValueMap[self._createChildValue(fatherValue, childValue)] = childValue; child.value = self._createChildValue(fatherValue, childValue); item.el.childValues.push(child.value); - }) + }); } else { item.type = "bi.down_list_item"; item.title = item.title || item.text; @@ -79987,7 +79813,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { item.isNeedAdjustWidth = false; item.logic = { dynamic: true - } + }; } var el_done = {}; el_done.el = item; @@ -79996,7 +79822,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { if (self._isGroup(item_done.items)) { BI.each(item_done.items, function (i, item) { self.singleValues.push(item.el.value); - }) + }); } result.push(item_done); @@ -80030,7 +79856,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { }, _createChildValue: function (fatherValue, childValue) { - return fatherValue + "_" + childValue + return fatherValue + "_" + childValue; }, populate: function (items) { @@ -80052,14 +79878,14 @@ BI.DownListPopup = BI.inherit(BI.Pane, { var self = this; var valueArray = []; BI.each(valueItem, function (i, item) { - var value; - if (BI.isNotNull(item.childValue)) { - value = self._createChildValue(item.value, item.childValue); - } else { - value = item.value; - } - valueArray.push(value); + var value; + if (BI.isNotNull(item.childValue)) { + value = self._createChildValue(item.value, item.childValue); + } else { + value = item.value; } + valueArray.push(value); + } ); this.popup.setValue(valueArray); }, @@ -80170,34 +79996,34 @@ BI.SearchEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.SearchEditor.EVENT_KEY_DOWN, v); }); this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_SPACE) + self.fireEvent(BI.SearchEditor.EVENT_SPACE); }); this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_BACKSPACE) + self.fireEvent(BI.SearchEditor.EVENT_BACKSPACE); }); this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.SearchEditor.EVENT_VALID) + self.fireEvent(BI.SearchEditor.EVENT_VALID); }); this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.SearchEditor.EVENT_ERROR) + self.fireEvent(BI.SearchEditor.EVENT_ERROR); }); this.editor.on(BI.Editor.EVENT_ENTER, function () { self.fireEvent(BI.SearchEditor.EVENT_ENTER); }); this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.SearchEditor.EVENT_RESTRICT) + self.fireEvent(BI.SearchEditor.EVENT_RESTRICT); }); this.editor.on(BI.Editor.EVENT_EMPTY, function () { self._checkClear(); - self.fireEvent(BI.SearchEditor.EVENT_EMPTY) + self.fireEvent(BI.SearchEditor.EVENT_EMPTY); }); this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.SearchEditor.EVENT_REMOVE) + self.fireEvent(BI.SearchEditor.EVENT_REMOVE); }); this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.SearchEditor.EVENT_CONFIRM) + self.fireEvent(BI.SearchEditor.EVENT_CONFIRM); }); this.editor.on(BI.Editor.EVENT_START, function () { self.fireEvent(BI.SearchEditor.EVENT_START); @@ -80314,7 +80140,7 @@ BI.TextEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -80488,7 +80314,7 @@ BI.FileManagerButtonGroup = BI.inherit(BI.Widget, { return BI.extend(BI.FileManagerButtonGroup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-button_group", items: [] - }) + }); }, _init: function () { @@ -80567,7 +80393,7 @@ BI.FileManager = BI.inherit(BI.Widget, { baseCls: "bi-file-manager", el: {}, items: [] - }) + }); }, _init: function () { @@ -80582,7 +80408,7 @@ BI.FileManager = BI.inherit(BI.Widget, { items: BI.deepClone(items) }); this.nav.on(BI.FileManagerNav.EVENT_CHANGE, function (value, obj) { - if (value == "-1") {//根节点 + if (value == "-1") {// 根节点 self.populate({children: self.tree.toJSON()}); } else { var node = self.tree.search(obj.attr("id")); @@ -80680,7 +80506,7 @@ BI.FileManagerFileItem = BI.inherit(BI.Single, { return BI.extend(BI.FileManagerFileItem.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-file-item bi-list-item bi-border-bottom", height: 30 - }) + }); }, _init: function () { @@ -80718,10 +80544,10 @@ BI.FileManagerFileItem = BI.inherit(BI.Single, { value: o.value } }] - }) + }); }, - getAllLeaves: function(){ + getAllLeaves: function () { return [this.options.value]; }, @@ -80747,7 +80573,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { return BI.extend(BI.FileManagerFolderItem.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-folder-item bi-list-item bi-border-bottom", height: 30 - }) + }); }, _init: function () { @@ -80796,7 +80622,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { }, { el: this.button }] - }) + }); }, setAllSelected: function (v) { @@ -80806,7 +80632,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { setHalfSelected: function (v) { this.checked.setHalfSelected(v); - if(!v){ + if(!v) { this.selectValue = []; } }, @@ -80840,7 +80666,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { var res = []; this.tree.traverse(function (node) { if (node.isLeaf()) { - res.push(node.get("data").value) + res.push(node.get("data").value); } }); return res; @@ -80900,7 +80726,7 @@ BI.FileManagerList = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-list", el: {}, items: [] - }) + }); }, _init: function () { @@ -80961,7 +80787,7 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-nav-button", selected: false, height: 40 - }) + }); }, _init: function () { @@ -80990,8 +80816,8 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { height: o.height }); var path = svg.path("M0,0L15,20L0,40").attr({ - "stroke": c.select_color, - "fill": o.selected ? c.select_color : c.normal_color + stroke: c.select_color, + fill: o.selected ? c.select_color : c.normal_color }); this.button.on(BI.TextButton.EVENT_CHANGE, function () { if (this.isSelected()) { @@ -81014,7 +80840,7 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { top: 0, bottom: 0 }] - }) + }); }, isSelected: function () { @@ -81048,7 +80874,7 @@ BI.FileManagerNav = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-nav bi-border-left", height: 40, items: [] - }) + }); }, _init: function () { @@ -81122,7 +80948,7 @@ BI.FileManagerNav = BI.inherit(BI.Widget, { return ids; }, - refreshTreeData: function(items){ + refreshTreeData: function (items) { this.tree.initTree(BI.Tree.transformToTreeFormat(items)); this.tree.getRoot().set("data", { text: BI.i18nText("BI-Created_By_Me"), @@ -81232,7 +81058,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { top: top, middle: middle, bottom: bottom - } + }; }, _getRegionClientPosition: function (name) { @@ -81244,7 +81070,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { width: region.width, height: region.height, id: region.id - } + }; }, _vAlign: function (position, regions) { @@ -81370,14 +81196,14 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { _drawOneTag: function (start, end) { var s = BI.createWidget({ type: "bi.icon_button", - //invisible: true, + // invisible: true, width: 13, height: 13, cls: "drag-tag-font interactive-arrangement-dragtag-icon" }); var e = BI.createWidget({ type: "bi.icon_button", - //invisible: true, + // invisible: true, width: 13, height: 13, cls: "drag-tag-font interactive-arrangement-dragtag-icon" @@ -81385,7 +81211,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { if (this._isEqual(start.left, end.left)) { var line = BI.createWidget({ type: "bi.layout", - //invisible: true, + // invisible: true, cls: "interactive-arrangement-dragtag-line", width: 1, height: Math.abs(start.top - end.top) @@ -81393,7 +81219,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { } else { var line = BI.createWidget({ type: "bi.layout", - //invisible: true, + // invisible: true, cls: "interactive-arrangement-dragtag-line", height: 1, width: Math.abs(start.left - end.left) @@ -81489,7 +81315,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { return position; }, - //position不动 变size + // position不动 变size getSize: function (name, position, size) { var regions = this.getAllRegions(); var me; @@ -81629,7 +81455,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { return function () { callback(); self.stopDraw(); - } + }; }, scrollInterval: function () { @@ -81691,7 +81517,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { }); BI.InteractiveArrangement.EVENT_RESIZE = "InteractiveArrangement.EVENT_RESIZE"; BI.InteractiveArrangement.EVENT_SCROLL = "InteractiveArrangement.EVENT_SCROLL"; -BI.shortcut('bi.interactive_arrangement', BI.InteractiveArrangement);/** +BI.shortcut("bi.interactive_arrangement", BI.InteractiveArrangement);/** * Created by zcf on 2016/9/26. */ BI.IntervalSlider = BI.inherit(BI.Widget, { @@ -81710,7 +81536,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { baseCls: "bi-interval-slider bi-slider-track", digit: false, unit: "" - }) + }); }, _init: function () { @@ -81760,7 +81586,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var v = BI.parseFloat(this.getValue()); self.valueOne = v; var percent = self._getPercentByValue(v); - var significantPercent = BI.parseFloat(percent.toFixed(1));//分成1000份 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 分成1000份 self._setLabelOnePosition(significantPercent); self._setSliderOnePosition(significantPercent); self._setBlueTrack(); @@ -81825,10 +81651,10 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }, - this._createLabelWrapper(), - this._createSliderWrapper() + this._createLabelWrapper(), + this._createSliderWrapper() ] - }) + }); }, _rePosBySizeAfterMove: function (size, isLeft) { @@ -81838,7 +81664,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var v = this._getValueByPercent(significantPercent); v = this._assertValue(v); v = o.digit === false ? v : v.toFixed(o.digit); - if(isLeft){ + if(isLeft) { this._setLabelOnePosition(significantPercent); this._setSliderOnePosition(significantPercent); this.labelOne.setValue(v); @@ -81884,7 +81710,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { self.fireEvent(BI.IntervalSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -81892,7 +81718,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -81923,7 +81749,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { top: 0, left: 0, width: "100%" - } + }; }, _createSliderWrapper: function () { @@ -81952,7 +81778,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { top: 20, left: 0, width: "100%" - } + }; }, _createTrackWrapper: function () { @@ -81982,18 +81808,18 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { var o = this.options; var valid = false; - //像90.这样的既不属于整数又不属于小数,是不合法的值 + // 像90.这样的既不属于整数又不属于小数,是不合法的值 var dotText = (v + "").split(".")[1]; if (BI.isEmptyString(dotText)) { }else{ if (BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max)) { - if(o.digit === false){ + if(o.digit === false) { valid = true; }else{ dotText = dotText || ""; @@ -82009,43 +81835,43 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var labelTwoLeft = this.labelTwo.element[0].offsetLeft; if (labelOneLeft <= labelTwoLeft) { if ((labelTwoLeft - labelOneLeft) < 90) { - this.labelTwo.element.css({"top": 40}); + this.labelTwo.element.css({top: 40}); } else { - this.labelTwo.element.css({"top": 0}); + this.labelTwo.element.css({top: 0}); } } else { if ((labelOneLeft - labelTwoLeft) < 90) { - this.labelTwo.element.css({"top": 40}); + this.labelTwo.element.css({top: 40}); } else { - this.labelTwo.element.css({"top": 0}); + this.labelTwo.element.css({top: 0}); } } }, _setLabelOnePosition: function (percent) { - this.labelOne.element.css({"left": percent + "%"}); + this.labelOne.element.css({left: percent + "%"}); this._checkOverlap(); }, _setLabelTwoPosition: function (percent) { - this.labelTwo.element.css({"left": percent + "%"}); + this.labelTwo.element.css({left: percent + "%"}); this._checkOverlap(); }, _setSliderOnePosition: function (percent) { - this.sliderOne.element.css({"left": percent + "%"}); + this.sliderOne.element.css({left: percent + "%"}); }, _setSliderTwoPosition: function (percent) { - this.sliderTwo.element.css({"left": percent + "%"}); + this.sliderTwo.element.css({left: percent + "%"}); }, _setBlueTrackLeft: function (percent) { - this.blueTrack.element.css({"left": percent + "%"}); + this.blueTrack.element.css({left: percent + "%"}); }, _setBlueTrackWidth: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setBlueTrack: function () { @@ -82082,21 +81908,21 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, - //其中取max-min后保留4为有效数字后的值的小数位数为最终value的精度 - _getValueByPercent: function (percent) {//return (((max-min)*percent)/100+min) + // 其中取max-min后保留4为有效数字后的值的小数位数为最终value的精度 + _getValueByPercent: function (percent) {// return (((max-min)*percent)/100+min) var sub = this.calculation.accurateSubtraction(this.max, this.min); var mul = this.calculation.accurateMultiplication(sub, percent); var div = this.calculation.accurateDivisionTenExponent(mul, 2); - if(this.precision < 0){ + if(this.precision < 0) { var value = BI.parseFloat(this.calculation.accurateAddition(div, this.min)); var reduceValue = Math.round(this.calculation.accurateDivisionTenExponent(value, -this.precision)); return this.calculation.accurateMultiplication(reduceValue, Math.pow(10, -this.precision)); - }else{ - return BI.parseFloat(this.calculation.accurateAddition(div, this.min).toFixed(this.precision)); } + return BI.parseFloat(this.calculation.accurateAddition(div, this.min).toFixed(this.precision)); + }, _getPercentByValue: function (v) { @@ -82109,31 +81935,31 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { }, _getPrecision: function () { - //计算每一份值的精度(最大值和最小值的差值保留4为有效数字后的精度) - //如果差值的整数位数大于4,toPrecision(4)得到的是科学计数法123456 => 1.235e+5 - //返回非负值: 保留的小数位数 - //返回负值: 保留的10^n精度中的n + // 计算每一份值的精度(最大值和最小值的差值保留4为有效数字后的精度) + // 如果差值的整数位数大于4,toPrecision(4)得到的是科学计数法123456 => 1.235e+5 + // 返回非负值: 保留的小数位数 + // 返回负值: 保留的10^n精度中的n var sub = this.calculation.accurateSubtraction(this.max, this.min); var pre = sub.toPrecision(4); - //科学计数法 + // 科学计数法 var eIndex = pre.indexOf("e"); var arr = []; - if(eIndex > -1){ + if(eIndex > -1) { arr = pre.split("e"); var decimalPartLength = BI.size(arr[0].split(".")[1]); var sciencePartLength = BI.parseInt(arr[1].substring(1)); return decimalPartLength - sciencePartLength; - }else{ - arr = pre.split("."); - return arr.length > 1 ? arr[1].length : 0; } + arr = pre.split("."); + return arr.length > 1 ? arr[1].length : 0; + }, _assertValue: function (value) { - if(value <= this.min){ - return this.min + if(value <= this.min) { + return this.min; } - if(value >= this.max){ + if(value >= this.max) { return this.max; } return value; @@ -82141,10 +81967,10 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { getValue: function () { if (this.valueOne <= this.valueTwo) { - return {min: this.valueOne, max: this.valueTwo} - } else { - return {min: this.valueTwo, max: this.valueOne} + return {min: this.valueOne, max: this.valueTwo}; } + return {min: this.valueTwo, max: this.valueOne}; + }, setMinAndMax: function (v) { @@ -82207,7 +82033,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { } else { this.labelOne.setValue(this.min); this.labelTwo.setValue(this.max); - this._setAllPosition(0, 100) + this._setAllPosition(0, 100); } } } @@ -82222,7 +82048,7 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.AccurateCalculationModel.superclass._defaultConfig.apply(this, arguments), { baseCls: "" - }) + }); }, _init: function () { @@ -82243,16 +82069,16 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { } var magnitudeDiff = stringNumber1.numDecimalLength - stringNumber2.numDecimalLength; if (magnitudeDiff > 0) { - var needAddZero = stringNumber2 + var needAddZero = stringNumber2; } else { var needAddZero = stringNumber1; magnitudeDiff = (0 - magnitudeDiff); } for (var i = 0; i < magnitudeDiff; i++) { if (needAddZero.numDecimal === "0" && i === 0) { - continue + continue; } - needAddZero.numDecimal += "0" + needAddZero.numDecimal += "0"; } }, @@ -82268,25 +82094,25 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var numDecimalLength = numStrArray[1].length; } return { - "numInteger": numInteger, - "numDecimal": numDecimal, - "numDecimalLength": numDecimalLength - } + numInteger: numInteger, + numDecimal: numDecimal, + numDecimalLength: numDecimalLength + }; }, - _accurateSubtraction: function (num1, num2) {//num1-num2 && num1>num2 + _accurateSubtraction: function (num1, num2) {// num1-num2 && num1>num2 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) - BI.parseInt(stringNumber2.numInteger); - //小数部分 + // 小数部分 this._formatDecimal(stringNumber1, stringNumber2); var decimalMaxLength = getDecimalMaxLength(stringNumber1, stringNumber2); if (BI.parseInt(stringNumber1.numDecimal) >= BI.parseInt(stringNumber2.numDecimal)) { var decimalResultTemp = (BI.parseInt(stringNumber1.numDecimal) - BI.parseInt(stringNumber2.numDecimal)).toString(); var decimalResult = addZero(decimalResultTemp, decimalMaxLength); - } else {//否则借位 + } else {// 否则借位 integerResult--; var borrow = this._getMagnitude(decimalMaxLength); var decimalResultTemp = (borrow + BI.parseInt(stringNumber1.numDecimal) - BI.parseInt(stringNumber2.numDecimal)).toString(); @@ -82295,62 +82121,62 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var result = integerResult + "." + decimalResult; return BI.parseFloat(result); - function getDecimalMaxLength(num1, num2) { + function getDecimalMaxLength (num1, num2) { if (num1.numDecimal.length >= num2.numDecimal.length) { - return num1.numDecimal.length + return num1.numDecimal.length; } - return num2.numDecimal.length + return num2.numDecimal.length; } - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, - _accurateAddition: function (num1, num2) {//加法结合律 + _accurateAddition: function (num1, num2) {// 加法结合律 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) + BI.parseInt(stringNumber2.numInteger); - //小数部分 + // 小数部分 this._formatDecimal(stringNumber1, stringNumber2); var decimalResult = (BI.parseInt(stringNumber1.numDecimal) + BI.parseInt(stringNumber2.numDecimal)).toString(); if (decimalResult !== "0") { if (decimalResult.length <= stringNumber1.numDecimal.length) { - decimalResult = addZero(decimalResult, stringNumber1.numDecimal.length) + decimalResult = addZero(decimalResult, stringNumber1.numDecimal.length); } else { - integerResult++;//进一 + integerResult++;// 进一 decimalResult = decimalResult.slice(1); } } var result = integerResult + "." + decimalResult; return BI.parseFloat(result); - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, - _accurateMultiplication: function (num1, num2) {//乘法分配律 + _accurateMultiplication: function (num1, num2) {// 乘法分配律 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) * BI.parseInt(stringNumber2.numInteger); - //num1的小数和num2的整数 + // num1的小数和num2的整数 var dec1Int2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numDecimal) * BI.parseInt(stringNumber2.numInteger), stringNumber1.numDecimalLength); - //num1的整数和num2的小数 + // num1的整数和num2的小数 var int1dec2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numInteger) * BI.parseInt(stringNumber2.numDecimal), stringNumber2.numDecimalLength); - //小数*小数 + // 小数*小数 var dec1dec2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numDecimal) * BI.parseInt(stringNumber2.numDecimal), (stringNumber1.numDecimalLength + stringNumber2.numDecimalLength)); return this._accurateAddition(this._accurateAddition(this._accurateAddition(integerResult, dec1Int2), int1dec2), dec1dec2); @@ -82368,63 +82194,63 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var result = integerResult + "." + partDecimalResult + stringNumber.numDecimal; return BI.parseFloat(result); - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, accurateSubtraction: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { if (num1 >= num2) { - return this._accurateSubtraction(num1, num2) + return this._accurateSubtraction(num1, num2); } - return -this._accurateSubtraction(num2, num1) + return -this._accurateSubtraction(num2, num1); } if (num1 >= 0 && num2 < 0) { - return this._accurateAddition(num1, -num2) + return this._accurateAddition(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return -this._accurateAddition(-num1, num2) + return -this._accurateAddition(-num1, num2); } if (num1 < 0 && num2 < 0) { if (num1 >= num2) { - return this._accurateSubtraction(-num2, -num1) + return this._accurateSubtraction(-num2, -num1); } - return this._accurateSubtraction(-num1, -num2) + return this._accurateSubtraction(-num1, -num2); } }, accurateAddition: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { - return this._accurateAddition(num1, num2) + return this._accurateAddition(num1, num2); } if (num1 >= 0 && num2 < 0) { - return this.accurateSubtraction(num1, -num2) + return this.accurateSubtraction(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return this.accurateSubtraction(num2, -num1) + return this.accurateSubtraction(num2, -num1); } if (num1 < 0 && num2 < 0) { - return -this._accurateAddition(-num1, -num2) + return -this._accurateAddition(-num1, -num2); } }, accurateMultiplication: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { - return this._accurateMultiplication(num1, num2) + return this._accurateMultiplication(num1, num2); } if (num1 >= 0 && num2 < 0) { - return -this._accurateMultiplication(num1, -num2) + return -this._accurateMultiplication(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return -this._accurateMultiplication(-num1, num2) + return -this._accurateMultiplication(-num1, num2); } if (num1 < 0 && num2 < 0) { - return this._accurateMultiplication(-num1, -num2) + return this._accurateMultiplication(-num1, -num2); } }, @@ -82518,7 +82344,7 @@ BI.MonthCombo = BI.inherit(BI.Widget, { BI.MonthCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.MonthCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.month_combo', BI.MonthCombo);/** +BI.shortcut("bi.month_combo", BI.MonthCombo);/** * 月份展示面板 * * Created by GUY on 2015/9/2. @@ -82538,7 +82364,7 @@ BI.MonthPopup = BI.inherit(BI.Widget, { BI.MonthPopup.superclass._init.apply(this, arguments); var self = this, o = this.options; - //纵向排列月 + // 纵向排列月 var month = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; var items = []; items.push(month.slice(0, 2)); @@ -82588,7 +82414,7 @@ BI.MonthPopup = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MonthPopup.EVENT_CHANGE); } - }) + }); }, getValue: function () { @@ -82664,7 +82490,7 @@ BI.MonthTrigger = BI.inherit(BI.Trigger, { }); BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -82687,7 +82513,7 @@ BI.MonthTrigger = BI.inherit(BI.Trigger, { }); }, setValue: function (v) { - if(BI.isNotNull(v)){ + if(BI.isNotNull(v)) { this.editor.setState(v + 1); this.editor.setValue(v + 1); this.editor.setTitle(v + 1); @@ -82741,17 +82567,17 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { var self = this, opts = this.options; this.label = BI.createWidget({ - type: 'bi.label', + type: "bi.label", height: this.constants.itemHeight, textAlign: "left", text: BI.i18nText("BI-Multi_Date_Relative_Current_Time"), - cls: 'bi-multidate-inner-label bi-tips' + cls: "bi-multidate-inner-label bi-tips" }); this.radioGroup = BI.createWidget({ type: "bi.button_group", chooseType: 0, items: BI.createItems(this.dateConfig(), { - type: 'bi.multidate_segment', + type: "bi.multidate_segment", height: this.constants.itemHeight }), layouts: [{ @@ -82770,10 +82596,10 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { }); BI.createWidget({ element: this, - type: 'bi.center_adapt', + type: "bi.center_adapt", lgap: this.constants.lgap, items: [{ - type: 'bi.vertical', + type: "bi.vertical", items: [this.label, this.radioGroup] }] }); @@ -82785,7 +82611,7 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { return { type: type, value: value - } + }; }, _isTypeAvaliable: function (type) { @@ -82876,7 +82702,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { }, _defaultConfig: function () { return BI.extend(BI.MultiDateCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-combo bi-border', + baseCls: "bi-multidate-combo bi-border", height: 24 }); }, @@ -82887,7 +82713,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { var date = Date.getDate(); this.storeValue = null; this.trigger = BI.createWidget({ - type: 'bi.date_trigger', + type: "bi.date_trigger", min: this.constants.DATE_MIN_VALUE, max: this.constants.DATE_MAX_VALUE }); @@ -82968,11 +82794,11 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.popup.on(BI.MultiDatePopup.CALENDAR_EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); self.combo.hideView(); - //self.fireEvent(BI.MultiDateCombo.EVENT_CHANGE); + // self.fireEvent(BI.MultiDateCombo.EVENT_CHANGE); self.fireEvent(BI.MultiDateCombo.EVENT_CONFIRM); }); this.combo = BI.createWidget({ - type: 'bi.combo', + type: "bi.combo", toggle: false, isNeedAdjustHeight: false, isNeedAdjustWidth: false, @@ -83036,13 +82862,13 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { ref: function (_ref) { self.comboWrapper = _ref; } - }) + }); }, _checkDynamicValue: function (v) { var type = null; if (BI.isNotNull(v)) { - type = v.type + type = v.type; } switch (type) { case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV: @@ -83078,7 +82904,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.storeValue = v; this.popup.setValue(v); this.trigger.setValue(v); - this._checkDynamicValue(v) + this._checkDynamicValue(v); }, getValue: function () { return this.storeValue; @@ -83090,7 +82916,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.combo.hideView(); } }); -BI.shortcut('bi.multidate_combo', BI.MultiDateCombo); +BI.shortcut("bi.multidate_combo", BI.MultiDateCombo); BI.MultiDateCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.MultiDateCombo.EVENT_FOCUS = "EVENT_FOCUS"; @@ -83150,7 +82976,7 @@ BI.DayCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.DayCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-daycard' + baseCls: "bi-multidate-daycard" }); }, @@ -83165,24 +82991,24 @@ BI.DayCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Day_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Day_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY, - text: BI.i18nText("BI-Multi_Date_Today") - }]; + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Day_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY, + text: BI.i18nText("BI-Multi_Date_Today") + }]; }, defaultSelectedItem: function () { - return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV + return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV; } }); BI.DayCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.daycard', BI.DayCard); +BI.shortcut("bi.daycard", BI.DayCard); /** * 普通控件 * @@ -83192,7 +83018,7 @@ BI.shortcut('bi.daycard', BI.DayCard); BI.MonthCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.MonthCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-monthcard' + baseCls: "bi-multidate-monthcard" }); }, @@ -83207,21 +83033,21 @@ BI.MonthCard = BI.inherit(BI.MultiDateCard, { value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_PREV, text: BI.i18nText("BI-Multi_Date_Month_Prev") }, - { - isEditorExist: true, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER, - text: BI.i18nText("BI-Multi_Date_Month_Next") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Month_Begin") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Month_End") - }]; + { + isEditorExist: true, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER, + text: BI.i18nText("BI-Multi_Date_Month_Next") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Month_Begin") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Month_End") + }]; }, defaultSelectedItem: function () { @@ -83229,7 +83055,7 @@ BI.MonthCard = BI.inherit(BI.MultiDateCard, { } }); BI.MonthCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.monthcard', BI.MonthCard); +BI.shortcut("bi.monthcard", BI.MonthCard); /** * 日期控件 * @class BI.MultiDatePopup @@ -83255,7 +83081,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { }, _defaultConfig: function () { return BI.extend(BI.MultiDatePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-popup', + baseCls: "bi-multidate-popup", width: 268, height: 260 }); @@ -83265,9 +83091,9 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { var self = this, opts = this.options; this.storeValue = ""; this.textButton = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-label bi-border-left bi-border-right bi-border-top', + cls: "bi-multidate-popup-label bi-border-left bi-border-right bi-border-top", shadow: true, text: BI.i18nText("BI-Multi_Date_Today") }); @@ -83277,7 +83103,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { this.clearButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-button bi-border-top', + cls: "bi-multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_Clear") }); @@ -83287,7 +83113,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { this.okButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-button bi-border-top', + cls: "bi-multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_OK") }); @@ -83295,7 +83121,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { self.fireEvent(BI.MultiDatePopup.BUTTON_OK_EVENT_CHANGE); }); this.dateTab = BI.createWidget({ - type: 'bi.tab', + type: "bi.tab", tab: { cls: "bi-multidate-popup-tab bi-border-bottom", height: this.constants.tabHeight, @@ -83322,10 +83148,10 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { width: this.constants.tabWidth, textAlign: "center", height: this.constants.itemHeight, - cls: 'bi-multidate-popup-item bi-list-item-active' + cls: "bi-multidate-popup-item bi-list-item-active" }), layouts: [{ - type: 'bi.left' + type: "bi.left" }] }, cardCreator: function (v) { @@ -83350,7 +83176,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.year; case BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD: self.quarter = BI.createWidget({ - type: 'bi.quartercard' + type: "bi.quartercard" }); self.quarter.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.quarter, v); @@ -83358,7 +83184,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.quarter; case BI.MultiDateCombo.MULTI_DATE_MONTH_CARD: self.month = BI.createWidget({ - type: 'bi.monthcard' + type: "bi.monthcard" }); self.month.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.month, v); @@ -83366,7 +83192,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.month; case BI.MultiDateCombo.MULTI_DATE_WEEK_CARD: self.week = BI.createWidget({ - type: 'bi.weekcard' + type: "bi.weekcard" }); self.week.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.week, v); @@ -83374,7 +83200,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.week; case BI.MultiDateCombo.MULTI_DATE_DAY_CARD: self.day = BI.createWidget({ - type: 'bi.daycard' + type: "bi.daycard" }); self.day.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.day, v); @@ -83546,7 +83372,7 @@ BI.MultiDatePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; BI.MultiDatePopup.BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; BI.MultiDatePopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; BI.MultiDatePopup.CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE"; -BI.shortcut('bi.multidate_popup', BI.MultiDatePopup); +BI.shortcut("bi.multidate_popup", BI.MultiDatePopup); /** * 普通控件 * @@ -83557,7 +83383,7 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.QuarterCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-quartercard' + baseCls: "bi-multidate-quartercard" }); }, @@ -83572,21 +83398,21 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { isEditorExist: true, text: BI.i18nText("BI-Multi_Date_Quarter_Prev") }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER, - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Quarter_Next") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Quarter_Begin") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Quarter_End") - }] + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER, + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Quarter_Next") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Quarter_Begin") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Quarter_End") + }]; }, defaultSelectedItem: function () { @@ -83594,7 +83420,7 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { } }); BI.QuarterCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.quartercard', BI.QuarterCard); +BI.shortcut("bi.quartercard", BI.QuarterCard); /** * 普通控件 * @@ -83612,7 +83438,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.MultiDateSegment.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-segment', + baseCls: "bi-multidate-segment", text: "", height: 30, isEditorExist: true, @@ -83632,13 +83458,13 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); this.textEditor = BI.createWidget({ - type: 'bi.text_editor', + type: "bi.text_editor", value: this.constants.defaultEditorValue, title: function () { return self.textEditor.getValue(); }, tipType: "success", - cls: 'bi-multidate-editor', + cls: "bi-multidate-editor", width: this.constants.textWidth, height: this.constants.itemHeight }); @@ -83648,7 +83474,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { this.text = BI.createWidget({ type: "bi.label", textAlign: "left", - cls: 'bi-multidate-normal-label', + cls: "bi-multidate-normal-label", text: opts.text, height: this.constants.itemHeight }); @@ -83658,7 +83484,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { if (this.options.isEditorExist === true) { return BI.createWidget({ element: this, - type: 'bi.left', + type: "bi.left", items: [{ el: { type: "bi.center_adapt", @@ -83667,23 +83493,23 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { }, lgap: 0 }, - { - el: { - type: "bi.center_adapt", - items: [this.textEditor], - widgetName: 'textEditor' - }, - lgap: this.constants.maxGap + { + el: { + type: "bi.center_adapt", + items: [this.textEditor], + widgetName: "textEditor" }, - { - el: this.text, - lgap: this.constants.minGap - }] + lgap: this.constants.maxGap + }, + { + el: this.text, + lgap: this.constants.minGap + }] }); } return BI.createWidget({ element: this, - type: 'bi.left', + type: "bi.left", items: [{ el: { type: "bi.center_adapt", @@ -83692,11 +83518,11 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { }, lgap: 0 }, - { - el: this.text, - lgap: this.constants.maxGap - }] - }) + { + el: this.text, + lgap: this.constants.maxGap + }] + }); }, setSelected: function (v) { if (BI.isNotNull(this.radio)) { @@ -83721,7 +83547,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { } }); BI.MultiDateSegment.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multidate_segment', BI.MultiDateSegment);/** +BI.shortcut("bi.multidate_segment", BI.MultiDateSegment);/** * 普通控件 * * @class BI.WeekCard @@ -83730,7 +83556,7 @@ BI.shortcut('bi.multidate_segment', BI.MultiDateSegment);/** BI.WeekCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.WeekCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-weekcard' + baseCls: "bi-multidate-weekcard" }); }, @@ -83745,11 +83571,11 @@ BI.WeekCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Week_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Week_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER - }]; + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Week_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER + }]; }, defaultSelectedItem: function () { @@ -83757,7 +83583,7 @@ BI.WeekCard = BI.inherit(BI.MultiDateCard, { } }); BI.WeekCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.weekcard', BI.WeekCard); +BI.shortcut("bi.weekcard", BI.WeekCard); /** * 普通控件 * @@ -83767,7 +83593,7 @@ BI.shortcut('bi.weekcard', BI.WeekCard); BI.YearCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.YearCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-yearcard' + baseCls: "bi-multidate-yearcard" }); }, @@ -83782,21 +83608,21 @@ BI.YearCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Year_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Year_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN, - text: BI.i18nText("BI-Multi_Date_Year_Begin") - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END, - text: BI.i18nText("BI-Multi_Date_Year_End") - }] + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Year_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN, + text: BI.i18nText("BI-Multi_Date_Year_Begin") + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END, + text: BI.i18nText("BI-Multi_Date_Year_End") + }]; }, defaultSelectedItem: function () { @@ -83804,7 +83630,7 @@ BI.YearCard = BI.inherit(BI.MultiDateCard, { } }); BI.YearCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.yearcard', BI.YearCard); +BI.shortcut("bi.yearcard", BI.YearCard); /** * @class BI.MultiLayerSelectTreeCombo * @extends BI.Widget @@ -83887,7 +83713,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { isDefaultInit: false, items: [], itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -83939,7 +83765,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -83972,7 +83798,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MultiLayerSelectLevelTree.EVENT_CHANGE, arguments); } - }) + }); }, populate: function (nodes) { @@ -84026,7 +83852,7 @@ BI.MultiLayerSelectTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.multilayer_select_level_tree', + type: "bi.multilayer_select_level_tree", isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator @@ -84079,13 +83905,13 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-first-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -84118,7 +83944,7 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -84126,7 +83952,7 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, isOnce: function () { @@ -84173,13 +83999,13 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-last-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -84212,7 +84038,7 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -84220,7 +84046,7 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -84263,13 +84089,13 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-mid-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._init.apply(this, arguments); @@ -84302,7 +84128,7 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -84310,7 +84136,7 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -84428,7 +84254,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { isDefaultInit: false, items: [], itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -84480,7 +84306,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -84499,8 +84325,8 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { items: this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0), itemsCreator: function (op, callback) { o.itemsCreator(op, function (items) { - callback(BI.Tree.transformToTreeFormat(items), 0) - }) + callback(BI.Tree.transformToTreeFormat(items), 0); + }); }, el: { @@ -84516,7 +84342,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MultiLayerSingleLevelTree.EVENT_CHANGE, v); } - }) + }); }, populate: function (nodes) { @@ -84571,7 +84397,7 @@ BI.MultiLayerSingleTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.multilayer_single_level_tree', + type: "bi.multilayer_single_level_tree", isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator @@ -84624,12 +84450,12 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-first-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -84650,7 +84476,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -84663,7 +84489,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -84671,7 +84497,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -84707,12 +84533,12 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-last-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -84733,7 +84559,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -84746,7 +84572,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -84754,7 +84580,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -84790,12 +84616,12 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-mid-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._init.apply(this, arguments); @@ -84816,7 +84642,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -84829,7 +84655,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -84837,7 +84663,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -84878,7 +84704,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._init.apply(this, arguments); @@ -84898,7 +84724,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -84911,7 +84737,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -84919,7 +84745,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -84974,7 +84800,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._init.apply(this, arguments); @@ -84994,7 +84820,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -85007,7 +84833,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -85015,7 +84841,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -85070,7 +84896,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._init.apply(this, arguments); @@ -85090,7 +84916,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -85103,7 +84929,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -85111,7 +84937,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -85179,7 +85005,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { this.storeValue = {}; this.display = BI.createWidget({ - type: 'bi.display_selected_list', + type: "bi.display_selected_list", items: opts.items, itemsCreator: function (op, callback) { op = BI.extend(op || {}, { @@ -85193,7 +85019,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { text: txt, value: v, title: txt - } + }; }) }); return; @@ -85203,9 +85029,9 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }); this.continueSelect = BI.createWidget({ - type: 'bi.text_button', - text: BI.i18nText('BI-Continue_Select'), - cls: 'multi-select-check-selected bi-high-light' + type: "bi.text_button", + text: BI.i18nText("BI-Continue_Select"), + cls: "multi-select-check-selected bi-high-light" }); this.continueSelect.on(BI.TextButton.EVENT_CHANGE, function () { @@ -85213,18 +85039,18 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }); BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", element: this, items: [{ height: this.constants.height, el: { - type: 'bi.left', - cls: 'multi-select-continue-select', + type: "bi.left", + cls: "multi-select-continue-select", items: [ { el: { type: "bi.label", - text: BI.i18nText('BI-Selected_Data') + text: BI.i18nText("BI-Selected_Data") }, lgap: this.constants.lgap, tgap: this.constants.tgap @@ -85236,7 +85062,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }] } }, { - height: 'fill', + height: "fill", el: this.display }] }); @@ -85306,7 +85132,7 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { opts.itemsCreator(options, function (ob) { self.hasNext = !!ob.hasNext; callback(self._createItems(ob.items)); - }) + }); }, hasNext: function () { return self.hasNext; @@ -85316,8 +85142,8 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { _createItems: function (items) { return BI.createItems(items, { - type: 'bi.icon_text_item', - cls: 'cursor-default check-font display-list-item bi-tips', + type: "bi.icon_text_item", + cls: "cursor-default check-font display-list-item bi-tips", once: true, invalid: true, selected: true, @@ -85341,7 +85167,7 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { } }); -BI.shortcut('bi.display_selected_list', BI.DisplaySelectedList);/** +BI.shortcut("bi.display_selected_list", BI.DisplaySelectedList);/** * * @class BI.MultiSelectInsertCombo * @extends BI.Single @@ -85350,7 +85176,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiSelectInsertCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-insert-combo', + baseCls: "bi-multi-select-insert-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -85367,7 +85193,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { self.trigger.getCounter().setButtonChecked(self.storeValue); }; this.storeValue = {}; - //标记正在请求数据 + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -85386,7 +85212,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(BI.deepClone(self.getValue())); } callback.apply(self, arguments); @@ -85408,7 +85234,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { type: BI.Selection.Multi, value: [keyword] }, function () { - //如果在不选的状态下直接把该值添加进来 + // 如果在不选的状态下直接把该值添加进来 if (self.storeValue.type === BI.Selection.Multi) { self.storeValue.value.pushDistinct(keyword); } @@ -85417,7 +85243,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); // } }); this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -85464,7 +85290,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_select_popup_view', + type: "bi.multi_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -85511,10 +85337,10 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -85552,7 +85378,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -85582,7 +85408,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -85628,14 +85454,14 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { var self = this, o = this.options; adjust(); callback(); - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.MultiSelectInsertCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -85697,7 +85523,7 @@ BI.extend(BI.MultiSelectInsertCombo, { BI.MultiSelectInsertCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.multi_select_insert_combo', BI.MultiSelectInsertCombo);/** +BI.shortcut("bi.multi_select_insert_combo", BI.MultiSelectInsertCombo);/** * * @class BI.MultiSelectCombo * @extends BI.Single @@ -85706,7 +85532,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-combo', + baseCls: "bi-multi-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -85723,7 +85549,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { self.trigger.getCounter().setButtonChecked(self.storeValue); }; this.storeValue = {}; - //标记正在请求数据 + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -85742,7 +85568,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(BI.deepClone(self.getValue())); } callback.apply(self, arguments); @@ -85769,7 +85595,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -85816,7 +85642,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_select_popup_view', + type: "bi.multi_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -85863,10 +85689,10 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -85904,7 +85730,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -85934,7 +85760,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -85980,7 +85806,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -85999,17 +85825,17 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.storeValue.type === BI.Selection.All && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.Multi, value: [] - } + }; } else if (self.storeValue.type === BI.Selection.Multi && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.All, value: [] - } + }; } if (self.wants2Quit === true) { self.fireEvent(BI.MultiSelectCombo.EVENT_CONFIRM); @@ -86073,7 +85899,7 @@ BI.extend(BI.MultiSelectCombo, { BI.MultiSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.multi_select_combo', BI.MultiSelectCombo);/** +BI.shortcut("bi.multi_select_combo", BI.MultiSelectCombo);/** * 多选加载数据面板 * Created by guy on 15/11/2. * @class BI.MultiSelectLoader @@ -86083,7 +85909,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-loader', + baseCls: "bi-multi-select-loader", logic: { dynamic: true }, @@ -86145,7 +85971,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: self.storeValue.type === BI.Selection.Multi - } + }; }); if (BI.isKey(self._startValue) && !self.storeValue.value.contains(self._startValue)) { var txt = opts.valueFormatter(startValue) || startValue; @@ -86154,7 +85980,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { value: startValue, title: txt, selected: true - }) + }); } firstItems = self._createItems(json); } @@ -86184,7 +86010,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { logic: this.options.logic, height: 25, selected: this.isAllSelected() - }) + }); }, _scrollToTop: function () { @@ -86240,7 +86066,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { }); BI.MultiSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_loader', BI.MultiSelectLoader);/** +BI.shortcut("bi.multi_select_loader", BI.MultiSelectLoader);/** * 带加载的多选下拉面板 * @class BI.MultiSelectPopupView * @extends Widget @@ -86249,8 +86075,8 @@ BI.MultiSelectPopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectPopupView.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-popup-view', - maxWidth: 'auto', + baseCls: "bi-multi-select-popup-view", + maxWidth: "auto", minWidth: 135, maxHeight: 400, valueFormatter: BI.emptyFn, @@ -86277,7 +86103,7 @@ BI.MultiSelectPopupView = BI.inherit(BI.Widget, { minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.loader }); @@ -86330,7 +86156,7 @@ BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; BI.MultiSelectPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.shortcut('bi.multi_select_popup_view', BI.MultiSelectPopupView);/** +BI.shortcut("bi.multi_select_popup_view", BI.MultiSelectPopupView);/** * * 复选下拉框 * @class BI.MultiSelectTrigger @@ -86391,7 +86217,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { self.fireEvent(BI.MultiSelectTrigger.EVENT_CHANGE, arguments); }); this.numberCounter = BI.createWidget(o.switcher, { - type: 'bi.multi_select_check_selected_switcher', + type: "bi.multi_select_check_selected_switcher", valueFormatter: o.valueFormatter, itemsCreator: o.itemsCreator, adapter: o.adapter, @@ -86405,7 +86231,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapNumberCounter = BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", hgap: 4, items: [{ el: this.numberCounter @@ -86413,12 +86239,12 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: wrapNumberCounter, width: 0 @@ -86429,7 +86255,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {//自动调整宽度 + BI.nextTick(function () {// 自动调整宽度 wrapper.attr("items")[1].width = (b === true ? self.numberCounter.element.outerWidth() + 8 : 0); wrapper.resize(); }); @@ -86483,7 +86309,7 @@ BI.MultiSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.MultiSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.multi_select_trigger', BI.MultiSelectTrigger);/** +BI.shortcut("bi.multi_select_trigger", BI.MultiSelectTrigger);/** * 多选加载数据搜索loader面板 * Created by guy on 15/11/4. * @class BI.MultiSelectSearchLoader @@ -86493,7 +86319,7 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-search-loader', + baseCls: "bi-multi-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -86572,7 +86398,7 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: this.isAllSelected() - }) + }); }, isAllSelected: function () { @@ -86599,12 +86425,12 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: src.type === BI.Selection.All - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = BI.deepClone(v); this.button_group.setValue(v); }, @@ -86635,7 +86461,7 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.MultiSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_search_loader', BI.MultiSelectSearchLoader);/** +BI.shortcut("bi.multi_select_search_loader", BI.MultiSelectSearchLoader);/** * * 在搜索框中输入文本弹出的面板 * @class BI.MultiSelectSearchPane @@ -86666,8 +86492,8 @@ BI.MultiSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'multi-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "multi-select-toolbar", height: this.constants.height }); @@ -86745,12 +86571,12 @@ BI.shortcut("bi.multi_select_search_pane", BI.MultiSelectSearchPane);/** BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiSelectCheckSelectedButton.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-check-selected-button bi-high-light', + baseCls: "bi-multi-select-check-selected-button bi-high-light", itemsCreator: BI.emptyFn }); }, @@ -86759,11 +86585,11 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { BI.MultiSelectCheckSelectedButton.superclass._init.apply(this, arguments); var self = this; this.numberCounter = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", element: this, hgap: 4, text: "0", - textAlign: 'center', + textAlign: "center", textHeight: 15 }); this.numberCounter.on(BI.Controller.EVENT_CHANGE, function () { @@ -86793,17 +86619,17 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { type: BI.MultiSelectCombo.REQ_GET_DATA_LENGTH }, function (res) { var length = res.count - ob.value.length; - BI.nextTick(function(){ + BI.nextTick(function () { self.numberCounter.setText(length); self.setVisible(length > 0); }); }); return; } - BI.nextTick(function(){ + BI.nextTick(function () { self.numberCounter.setText(ob.value.length); self.setVisible(ob.value.length > 0); - }) + }); }, getValue: function () { @@ -86812,7 +86638,7 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { }); BI.MultiSelectCheckSelectedButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_check_selected_button', BI.MultiSelectCheckSelectedButton);/** +BI.shortcut("bi.multi_select_check_selected_button", BI.MultiSelectCheckSelectedButton);/** * 多选输入框 * Created by guy on 15/11/3. * @class BI.MultiSelectEditor @@ -86821,12 +86647,12 @@ BI.shortcut('bi.multi_select_check_selected_button', BI.MultiSelectCheckSelected BI.MultiSelectEditor = BI.inherit(BI.Widget, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiSelectEditor.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-editor', + baseCls: "bi-multi-select-editor", el: {} }); }, @@ -86835,10 +86661,10 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { BI.MultiSelectEditor.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.state_editor', + type: "bi.state_editor", element: this, height: o.height, - watermark: BI.i18nText('BI-Basic_Search'), + watermark: BI.i18nText("BI-Basic_Search"), allowBlank: true }); @@ -86874,16 +86700,16 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { var v = this.editor.getState(); if (BI.isArray(v) && v.length > 0) { return v[v.length - 1]; - } else { - return ""; } + return ""; + }, getKeywords: function () { var val = this.editor.getLastValidValue(); var keywords = val.match(/[\S]+/g); if (BI.isEndWithBlank(val)) { - return keywords.concat([' ']); + return keywords.concat([" "]); } return keywords; }, @@ -86893,7 +86719,7 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { } }); BI.MultiSelectEditor.EVENT_PAUSE = "MultiSelectEditor.EVENT_PAUSE"; -BI.shortcut('bi.multi_select_editor', BI.MultiSelectEditor);/** +BI.shortcut("bi.multi_select_editor", BI.MultiSelectEditor);/** * searcher * Created by guy on 15/11/3. * @class BI.MultiSelectSearcher @@ -86903,7 +86729,7 @@ BI.MultiSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-searcher', + baseCls: "bi-multi-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -86917,7 +86743,7 @@ BI.MultiSelectSearcher = BI.inherit(BI.Widget, { BI.MultiSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.multi_select_editor', + type: "bi.multi_select_editor", height: o.height }); @@ -87060,7 +86886,7 @@ BI.MultiSelectSearcher.EVENT_START = "EVENT_START"; BI.MultiSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.MultiSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.MultiSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.multi_select_searcher', BI.MultiSelectSearcher);/** +BI.shortcut("bi.multi_select_searcher", BI.MultiSelectSearcher);/** * 查看已选switcher * Created by guy on 15/11/3. * @class BI.MultiSelectCheckSelectedSwitcher @@ -87070,7 +86896,7 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectCheckSelectedSwitcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-check-selected-switcher', + baseCls: "bi-multi-select-check-selected-switcher", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, el: {}, @@ -87143,7 +86969,7 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { }, setButtonChecked: function (v) { - this.button.setValue(v) + this.button.setValue(v); }, getValue: function () { @@ -87157,16 +86983,16 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE = "MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE"; BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW = "MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.multi_select_check_selected_switcher', BI.MultiSelectCheckSelectedSwitcher);/** +BI.shortcut("bi.multi_select_check_selected_switcher", BI.MultiSelectCheckSelectedSwitcher);/** * Created by zcf_1 on 2017/5/2. */ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectInsertList.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-insert-list', + baseCls: "bi-multi-select-insert-list", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn - }) + }); }, _init: function () { BI.MultiSelectInsertList.superclass._init.apply(this, arguments); @@ -87192,8 +87018,8 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }); this.adapter.on(BI.MultiSelectLoader.EVENT_CHANGE, function () { self.storeValue = this.getValue(); - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); + assertShowValue(); + self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); }); this.searcherPane = BI.createWidget({ @@ -87235,7 +87061,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { self._showAdapter(); self._setStartValue(""); self.adapter.setValue(self.storeValue); - //需要刷新回到初始界面,否则搜索的结果不能放在最前面 + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 self.adapter.populate(); } }, { @@ -87248,7 +87074,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { value: [keyword] }, function () { if (self.storeValue.type === BI.Selection.Multi) { - self.storeValue.value.pushDistinct(keyword) + self.storeValue.value.pushDistinct(keyword); } self._showAdapter(); self.adapter.setValue(self.storeValue); @@ -87257,10 +87083,10 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { self.adapter.populate(); self._setStartValue(""); self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); - }) + }); } else { if (self.storeValue.type === BI.Selection.Multi) { - self.storeValue.value.pushDistinct(keyword) + self.storeValue.value.pushDistinct(keyword); } self._showAdapter(); self.adapter.setValue(self.storeValue); @@ -87329,7 +87155,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, _showAdapter: function () { @@ -87365,12 +87191,12 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }, function (ob) { self._allData = BI.pluck(ob.items, "value"); digest(self._allData); - }) + }); } else { - digest(this._allData) + digest(this._allData); } - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -87415,7 +87241,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); callback(); - }) + }); }, _join: function (res, callback) { @@ -87488,10 +87314,10 @@ BI.shortcut("bi.multi_select_insert_list", BI.MultiSelectInsertList);/** BI.MultiSelectList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectList.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-list', + baseCls: "bi-multi-select-list", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn - }) + }); }, _init: function () { BI.MultiSelectList.superclass._init.apply(this, arguments); @@ -87562,7 +87388,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { self._showAdapter(); self._setStartValue(""); self.adapter.setValue(self.storeValue); - //需要刷新回到初始界面,否则搜索的结果不能放在最前面 + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 self.adapter.populate(); } }, { @@ -87581,7 +87407,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { self.adapter.populate(); self._setStartValue(""); self.fireEvent(BI.MultiSelectList.EVENT_CHANGE); - }) + }); } } }, { @@ -87643,7 +87469,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, _showAdapter: function () { @@ -87679,12 +87505,12 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { }, function (ob) { self._allData = BI.pluck(ob.items, "value"); digest(self._allData); - }) + }); } else { - digest(this._allData) + digest(this._allData); } - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -87729,7 +87555,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -87747,17 +87573,17 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { callback(); } - function adjust() { + function adjust () { if (self.storeValue.type === BI.Selection.All && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.Multi, value: [] - } + }; } else if (self.storeValue.type === BI.Selection.Multi && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.All, value: [] - } + }; } } }, @@ -87832,9 +87658,9 @@ BI.shortcut("bi.multi_select_list", BI.MultiSelectList);/** BI.MultiSelectTree = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectTree.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-tree', + baseCls: "bi-multi-select-tree", itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -87856,7 +87682,7 @@ BI.MultiSelectTree = BI.inherit(BI.Widget, { self.fireEvent(BI.MultiSelectTree.EVENT_CHANGE); }); - //搜索中的时候用的是parttree,同adapter中的synctree不一样 + // 搜索中的时候用的是parttree,同adapter中的synctree不一样 this.searcherPane = BI.createWidget({ type: "bi.multi_tree_search_pane", cls: "bi-border-left bi-border-right bi-border-bottom", @@ -87939,7 +87765,7 @@ BI.MultiSelectTree = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, @@ -88007,10 +87833,10 @@ BI.MultiSelectTreePopup = BI.inherit(BI.Widget, { itemsCreator: o.itemsCreator }); this.popup.on(BI.TreeView.EVENT_AFTERINIT, function () { - self.fireEvent(BI.MultiSelectTreePopup.EVENT_AFTER_INIT) + self.fireEvent(BI.MultiSelectTreePopup.EVENT_AFTER_INIT); }); this.popup.on(BI.TreeView.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectTreePopup.EVENT_CHANGE) + self.fireEvent(BI.MultiSelectTreePopup.EVENT_CHANGE); }); }, @@ -88072,9 +87898,9 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { this.selectedValues = {}; var continueSelect = BI.createWidget({ - type: 'bi.text_button', - text: BI.i18nText('BI-Continue_Select'), - cls: 'multi-tree-check-selected' + type: "bi.text_button", + text: BI.i18nText("BI-Continue_Select"), + cls: "multi-tree-check-selected" }); continueSelect.on(BI.TextButton.EVENT_CHANGE, function () { opts.onClickContinueSelect(); @@ -88084,13 +87910,13 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { }); var backToPopup = BI.createWidget({ - type: 'bi.left', - cls: 'multi-tree-continue-select', + type: "bi.left", + cls: "multi-tree-continue-select", items: [ { el: { type: "bi.label", - text: BI.i18nText('BI-Selected_Data') + text: BI.i18nText("BI-Selected_Data") }, lgap: this.constants.lgap, tgap: this.constants.tgap @@ -88124,13 +87950,13 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { }); BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", element: this, items: [{ height: this.constants.height, el: backToPopup }, { - height: 'fill', + height: "fill", el: this.display }] }); @@ -88177,7 +88003,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiTreeCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-combo', + baseCls: "bi-multi-tree-combo", itemsCreator: BI.emptyFn, height: 25 }); @@ -88220,7 +88046,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_tree_popup_view', + type: "bi.multi_tree_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -88273,7 +88099,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { this.storeValue = {value: {}}; var change = false; - var clear = false; //标识当前是否点击了清空 + var clear = false; // 标识当前是否点击了清空 var isSearching = function () { return self.trigger.getSearcher().isSearching(); @@ -88297,7 +88123,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { }); }); - function showCounter() { + function showCounter () { if (isSearching()) { self.storeValue = {value: self.trigger.getValue()}; } else if (isPopupView()) { @@ -88393,7 +88219,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -88419,7 +88245,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { BI.MultiTreeCombo.EVENT_CONFIRM = "MultiTreeCombo.EVENT_CONFIRM"; -BI.shortcut('bi.multi_tree_combo', BI.MultiTreeCombo);/** +BI.shortcut("bi.multi_tree_combo", BI.MultiTreeCombo);/** * 带加载的多选下拉面板 * @class BI.MultiTreePopup * @extends BI.Pane @@ -88428,8 +88254,8 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { _defaultConfig: function () { return BI.extend(BI.MultiTreePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-popup', - maxWidth: 'auto', + baseCls: "bi-multi-tree-popup", + maxWidth: "auto", minWidth: 100, maxHeight: 400, onLoaded: BI.emptyFn @@ -88446,7 +88272,7 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { this.tree = BI.createWidget({ type: "bi.async_tree", height: 400, - cls:"popup-view-tree", + cls: "popup-view-tree", itemsCreator: opts.itemsCreator, onLoaded: opts.onLoaded }); @@ -88458,7 +88284,7 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { maxWidth: opts.maxWidth, minWidth: opts.minWidth, maxHeight: opts.maxHeight, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.tree }); @@ -88515,7 +88341,7 @@ BI.MultiTreePopup.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; BI.MultiTreePopup.EVENT_AFTERINIT = "EVENT_AFTERINIT"; -BI.shortcut('bi.multi_tree_popup_view', BI.MultiTreePopup);/** +BI.shortcut("bi.multi_tree_popup_view", BI.MultiTreePopup);/** * * 在搜索框中输入文本弹出的面板 * @class BI.MultiTreeSearchPane @@ -88596,12 +88422,12 @@ BI.shortcut("bi.multi_tree_search_pane", BI.MultiTreeSearchPane);/** BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiTreeCheckSelectedButton.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-check-selected-button', + baseCls: "bi-multi-tree-check-selected-button", itemsCreator: BI.emptyFn }); }, @@ -88610,20 +88436,20 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { BI.MultiTreeCheckSelectedButton.superclass._init.apply(this, arguments); var self = this; this.indicator = BI.createWidget({ - type: 'bi.icon_button', - cls: 'check-font trigger-check-selected', + type: "bi.icon_button", + cls: "check-font trigger-check-selected", width: 15, height: 15, stopPropagation: true }); this.checkSelected = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", cls: "trigger-check-selected", invisible: true, hgap: 4, text: this._const.checkSelected, - textAlign: 'center', + textAlign: "center", textHeight: 15 }); this.checkSelected.on(BI.Controller.EVENT_CHANGE, function () { @@ -88638,7 +88464,7 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { type: "bi.horizontal", element: this, items: [this.indicator, this.checkSelected] - }) + }); this.element.hover(function () { self.indicator.setVisible(false); @@ -88657,7 +88483,7 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { }); BI.MultiTreeCheckSelectedButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_tree_check_selected_button', BI.MultiTreeCheckSelectedButton);/** +BI.shortcut("bi.multi_tree_check_selected_button", BI.MultiTreeCheckSelectedButton);/** * searcher * Created by guy on 15/11/3. * @class BI.MultiTreeSearcher @@ -88667,7 +88493,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiTreeSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-searcher', + baseCls: "bi-multi-tree-searcher", itemsCreator: BI.emptyFn, popup: {}, @@ -88680,7 +88506,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { BI.MultiTreeSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget({ - type: 'bi.multi_select_editor', + type: "bi.multi_select_editor", height: o.height, el: { type: "bi.simple_state_editor", @@ -88775,7 +88601,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { this.editor.setState(text); } - function getChildrenNode(ob) { + function getChildrenNode (ob) { var text = ""; var index = 0, size = BI.size(ob); BI.each(ob, function (name, children) { @@ -88810,7 +88636,7 @@ BI.MultiTreeSearcher.EVENT_CHANGE = "EVENT_CHANGE"; BI.MultiTreeSearcher.EVENT_START = "EVENT_START"; BI.MultiTreeSearcher.EVENT_STOP = "EVENT_STOP"; BI.MultiTreeSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.shortcut('bi.multi_tree_searcher', BI.MultiTreeSearcher);/** +BI.shortcut("bi.multi_tree_searcher", BI.MultiTreeSearcher);/** * Created by windy on 2017/3/13. * 数值微调器 */ @@ -88828,7 +88654,7 @@ BI.NumberEditor = BI.inherit(BI.Widget, { allowBlank: false, errorText: "", step: 1 - }) + }); }, _init: function () { @@ -88892,7 +88718,7 @@ BI.NumberEditor = BI.inherit(BI.Widget, { }); }, - //微调 + // 微调 _finetuning: function (add) { var v = BI.parseFloat(this.getValue()); this.setValue(v.add(add)); @@ -88919,8 +88745,8 @@ BI.NumberEditor = BI.inherit(BI.Widget, { }); BI.NumberEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.NumberEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.number_editor", BI.NumberEditor);//小于号的值为:0,小于等于号的值为:1 -//closeMIn:最小值的符号,closeMax:最大值的符号 +BI.shortcut("bi.number_editor", BI.NumberEditor);// 小于号的值为:0,小于等于号的值为:1 +// closeMIn:最小值的符号,closeMax:最大值的符号 /** * Created by roy on 15/9/17. * @@ -88941,16 +88767,16 @@ BI.NumberInterval = BI.inherit(BI.Single, { numTip: "" }, _defaultConfig: function () { - var conf = BI.NumberInterval.superclass._defaultConfig.apply(this, arguments) + var conf = BI.NumberInterval.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-number-interval", height: 25, validation: "valid" - }) + }); }, _init: function () { var self = this, c = this.constants, o = this.options; - BI.NumberInterval.superclass._init.apply(this, arguments) + BI.NumberInterval.superclass._init.apply(this, arguments); this.smallEditor = BI.createWidget({ type: "bi.editor", height: o.height - 2, @@ -89025,21 +88851,21 @@ BI.NumberInterval = BI.inherit(BI.Single, { }] }); - //this.smallCombo = BI.createWidget({ + // this.smallCombo = BI.createWidget({ // type: "bi.number_interval_combo", // cls: "number-interval-small-combo", // height: o.height, // value: o.closemin ? 1 : 0, // offsetStyle: "left" - //}); + // }); // - //this.bigCombo = BI.createWidget({ + // this.bigCombo = BI.createWidget({ // type: "bi.number_interval_combo", // cls: "number-interval-big-combo", // height: o.height, // value: o.closemax ? 1 : 0, // offsetStyle: "left" - //}); + // }); this.smallCombo = BI.createWidget({ type: "bi.icon_combo", cls: "number-interval-small-combo bi-border", @@ -89169,42 +88995,42 @@ BI.NumberInterval = BI.inherit(BI.Single, { self.element.removeClass("number-error"); o.validation = "invalid"; return c.typeError; - } else { - if (BI.isEmptyString(self.smallEditor.getValue()) || BI.isEmptyString(self.bigEditor.getValue())) { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } else { - var smallValue = parseFloat(self.smallEditor.getValue()), bigValue = parseFloat(self.bigEditor.getValue()), - bigComboValue = self.bigCombo.getValue(), smallComboValue = self.smallCombo.getValue(); - if (bigComboValue[0] === c.less_equal && smallComboValue[0] === c.less_equal) { - if (smallValue > bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.numberError; - } else { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } - } else { - if (smallValue > bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.numberError; - } else if (smallValue === bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.signalError; - } else { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } - } + } + if (BI.isEmptyString(self.smallEditor.getValue()) || BI.isEmptyString(self.bigEditor.getValue())) { + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + } + var smallValue = parseFloat(self.smallEditor.getValue()), bigValue = parseFloat(self.bigEditor.getValue()), + bigComboValue = self.bigCombo.getValue(), smallComboValue = self.smallCombo.getValue(); + if (bigComboValue[0] === c.less_equal && smallComboValue[0] === c.less_equal) { + if (smallValue > bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.numberError; } - + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + } + if (smallValue > bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.numberError; + } else if (smallValue === bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.signalError; + } + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + + + + + }, _setTitle: function (v) { @@ -89235,10 +89061,10 @@ BI.NumberInterval = BI.inherit(BI.Single, { }); break; default : - return + return; } - }) + }); }, _setBlurEvent: function (w) { var c = this.constants, self = this; @@ -89259,18 +89085,18 @@ BI.NumberInterval = BI.inherit(BI.Single, { default: self._setTitle(""); } - }) + }); }, _setErrorEvent: function (w) { - var c = this.constants, self = this + var c = this.constants, self = this; w.on(BI.Editor.EVENT_ERROR, function () { self._checkValidation(); BI.Bubbles.show(c.typeError, BI.i18nText("BI-Numerical_Interval_Input_Data"), self, { offsetStyle: "center" }); self.fireEvent(BI.NumberInterval.EVENT_ERROR); - }) + }); }, @@ -89293,7 +89119,7 @@ BI.NumberInterval = BI.inherit(BI.Single, { default: self.fireEvent(BI.NumberInterval.EVENT_VALID); } - }) + }); }, @@ -89343,7 +89169,7 @@ BI.NumberInterval = BI.inherit(BI.Single, { self.fireEvent(BI.NumberInterval.EVENT_CHANGE); self.fireEvent(BI.NumberInterval.EVENT_VALID); } - }) + }); }, isStateValid: function () { @@ -89376,12 +89202,12 @@ BI.NumberInterval = BI.inherit(BI.Single, { this.bigTip.setVisible(false); }, - setNumTip: function(numTip) { + setNumTip: function (numTip) { this.smallTip.setText(numTip); this.bigTip.setText(numTip); }, - getNumTip: function() { + getNumTip: function () { return this.smallTip.getText(); }, @@ -89406,18 +89232,18 @@ BI.NumberInterval = BI.inherit(BI.Single, { if (!BI.isNull(data.closemin)) { if (data.closemin === true) { - combo_value = 1 + combo_value = 1; } else { - combo_value = 0 + combo_value = 0; } self.smallCombo.setValue(combo_value); } if (!BI.isNull(data.closemax)) { if (data.closemax === true) { - combo_value = 1 + combo_value = 1; } else { - combo_value = 0 + combo_value = 0; } self.bigCombo.setValue(combo_value); } @@ -89429,15 +89255,15 @@ BI.NumberInterval = BI.inherit(BI.Single, { value.min = self.smallEditor.getValue(); value.max = self.bigEditor.getValue(); if (minComboValue[0] === 0) { - value.closemin = false + value.closemin = false; } else { - value.closemin = true + value.closemin = true; } if (maxComboValue[0] === 0) { - value.closemax = false + value.closemax = false; } else { - value.closemax = true + value.closemax = true; } return value; } @@ -89459,7 +89285,7 @@ BI.PageTableCell = BI.inherit(BI.Widget, { baseCls: "bi-page-table-cell", text: "", title: "" - }) + }); }, _init: function () { @@ -89505,8 +89331,8 @@ BI.PageTable = BI.inherit(BI.Widget, { }, pager: { horizontal: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -89514,8 +89340,8 @@ BI.PageTable = BI.inherit(BI.Widget, { lastPage: BI.emptyFn }, vertical: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -89526,11 +89352,11 @@ BI.PageTable = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -89546,9 +89372,9 @@ BI.PageTable = BI.inherit(BI.Widget, { sequenceCellStyleGetter: BI.emptyFn, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -89589,7 +89415,7 @@ BI.PageTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -89641,7 +89467,7 @@ BI.PageTable = BI.inherit(BI.Widget, { right: 0, bottom: 0 }] - }) + }); }, setHPage: function (v) { @@ -89760,7 +89586,7 @@ BI.PageTable = BI.inherit(BI.Widget, { BI.PageTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.page_table', BI.PageTable);/** +BI.shortcut("bi.page_table", BI.PageTable);/** * 路径选择 * * Created by GUY on 2015/12/4. @@ -89778,7 +89604,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return BI.extend(BI.PathChooser.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-path-chooser", items: [] - }) + }); }, _init: function () { @@ -89792,7 +89618,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return { type: "bi.path_region", title: self.texts[region] || region - } + }; })); this.regionMap = {}; BI.each(regions, function (i, region) { @@ -89885,7 +89711,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { left: x - 6.5, top: y - 6.5 }] - }) + }); }, _drawLine: function (start, lines) { @@ -89897,7 +89723,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { this.pathes[start] = []; } var startRegionIndex = this.getRegionIndexById(start); - //start所在的位置,然后接着往下画其他的路径 + // start所在的位置,然后接着往下画其他的路径 var offset = this.regions[startRegionIndex].getIndexByValue(start); BI.each(lines, function (i, line) { self.pathes[start][i] = []; @@ -89916,14 +89742,14 @@ BI.PathChooser = BI.inherit(BI.Widget, { self.pathes[start][i].push({ x: sleft - 50, y: stop - }) + }); } else if (idx === 0) { radioStartX = sleft + 50; path += "M" + sleft + "," + stop; self.pathes[start][i].push({ x: sleft, y: stop - }) + }); } else { radioStartX = sleft + 50; path += "M" + sleft + "," + 47.5 + "L" + (sleft + 50) + "," + 47.5 + "L" + (sleft + 50) + "," + stop; @@ -89966,13 +89792,13 @@ BI.PathChooser = BI.inherit(BI.Widget, { var graph = self.svg.path(path) .attr({ stroke: idx === 0 ? self._const.selectLineColor : self._const.lineColor, - 'stroke-dasharray': '-' + "stroke-dasharray": "-" }); self.lines[start].push(graph); if (lines.length > 1) { self.lines[start][0].toFront(); } - //第一个元素无论有多少个都要显示radio + // 第一个元素无论有多少个都要显示radio if (BI.contains(self.start, start)) { self.lines[self.regions[0].getValueByIndex(0)][0].toFront(); } @@ -89999,7 +89825,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { self.regionIndexes[k].push(regionIndex); } }); - }) + }); }); BI.each(routes, function (k, route) { self._drawLine(k, route); @@ -90067,16 +89893,16 @@ BI.PathChooser = BI.inherit(BI.Widget, { if (parent.getChildIndex(item.value) === -1) { tree.addNode(parent, node); } - }) + }); }); - //算出区域列表 + // 算出区域列表 tree.traverse(function (node) { BI.each(node.getChildren(), function (i, child) { if (BI.contains(regions, child.get("region"))) { var index1 = BI.indexOf(regions, node.get("region")); var index2 = BI.indexOf(regions, child.get("region")); - //交换区域 + // 交换区域 if (index1 > index2) { var t = regions[index2]; for (var j = index2; j < index1; j++) { @@ -90091,14 +89917,14 @@ BI.PathChooser = BI.inherit(BI.Widget, { }); this._createRegions(regions); - //算出节点 + // 算出节点 BI.each(branches, function (k, branch) { if (branch < max) { delete branches[k]; } }); - //过滤节点 + // 过滤节点 var nodes = []; var n = tree.getRoot(); while (n && n.getChildrenLength() === 1) { @@ -90116,7 +89942,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { } }); - //填充节点 + // 填充节点 var routes = {}; var s, e; for (var i = 0, len = nodes.length; i < len + 1; i++) { @@ -90157,7 +89983,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return true; } } - }) + }); }); } this.routes = routes; @@ -90222,7 +90048,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { if (array.length > 0) { result.push(array); } - //画这n条路径 + // 画这n条路径 BI.each(result, function (idx, path) { var start = path[0]; var index = BI.findIndex(self.routes[start], function (idx, p) { @@ -90264,7 +90090,7 @@ BI.PathRegion = BI.inherit(BI.Widget, { baseCls: "bi-path-region bi-background", width: 80, title: "" - }) + }); }, _init: function () { @@ -90285,7 +90111,7 @@ BI.PathRegion = BI.inherit(BI.Widget, { bgap: 5, hgap: 10, items: [title] - }) + }); }, hasItem: function (val) { @@ -90392,10 +90218,10 @@ BI.PreviewTableCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); -BI.shortcut('bi.preview_table_cell', BI.PreviewTableCell);/** +BI.shortcut("bi.preview_table_cell", BI.PreviewTableCell);/** * 预览表 * * Created by GUY on 2015/12/25. @@ -90423,10 +90249,10 @@ BI.PreviewTableHeaderCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); -BI.shortcut('bi.preview_table_header_cell', BI.PreviewTableHeaderCell);/** +BI.shortcut("bi.preview_table_header_cell", BI.PreviewTableHeaderCell);/** * 预览表 * * Created by GUY on 2015/12/25. @@ -90490,11 +90316,11 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }); }, - //是否有自适应调节的列,即列宽为"" + // 是否有自适应调节的列,即列宽为"" _hasAdaptCol: function (columnSize) { return BI.any(columnSize, function (i, size) { return size === ""; - }) + }); }, _isPercentage: function (columnSize) { @@ -90504,7 +90330,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { _adjustColumns: function () { var self = this, o = this.options; if (o.isNeedFreeze === true) { - //如果存在百分比的情况 + // 如果存在百分比的情况 if (this._isPercentage(o.columnSize)) { if (this._hasAdaptCol(o.columnSize)) { var findCols = [], remain = 0; @@ -90541,7 +90367,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { this.table.setColumnSize(isRight ? (notFreezeSize.concat(freezeSize)) : (freezeSize.concat(notFreezeSize))); } } else { - //如果存在自适应宽度的列或者是百分比计算的列,需要将整个表宽设为100% + // 如果存在自适应宽度的列或者是百分比计算的列,需要将整个表宽设为100% if (this._hasAdaptCol(o.columnSize) || this._isPercentage(o.columnSize)) { this.table.setRegionColumnSize(["100%"]); } @@ -90585,11 +90411,11 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }, getScrollRegionColumnSize: function () { - return this.table.getScrollRegionColumnSize() + return this.table.getScrollRegionColumnSize(); }, getScrollRegionRowSize: function () { - return this.table.getScrollRegionRowSize() + return this.table.getScrollRegionRowSize(); }, hasVerticalScroll: function () { @@ -90601,7 +90427,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }, setLeftHorizontalScroll: function (scrollLeft) { - return this.table.setLeftHorizontalScroll(scrollLeft) + return this.table.setLeftHorizontalScroll(scrollLeft); }, setRightHorizontalScroll: function (scrollLeft) { @@ -90629,7 +90455,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { } }); BI.PreviewTable.EVENT_CHANGE = "PreviewTable.EVENT_CHANGE"; -BI.shortcut('bi.preview_table', BI.PreviewTable);/** +BI.shortcut("bi.preview_table", BI.PreviewTable);/** * 季度下拉框 * * Created by GUY on 2015/8/28. @@ -90713,7 +90539,7 @@ BI.QuarterCombo = BI.inherit(BI.Widget, { BI.QuarterCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.QuarterCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.quarter_combo', BI.QuarterCombo);/** +BI.shortcut("bi.quarter_combo", BI.QuarterCombo);/** * 季度展示面板 * * Created by GUY on 2015/9/2. @@ -90773,7 +90599,7 @@ BI.QuarterPopup = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MonthPopup.EVENT_CHANGE); } - }) + }); }, getValue: function () { @@ -90851,7 +90677,7 @@ BI.QuarterTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -90949,7 +90775,7 @@ BI.RelationViewItem = BI.inherit(BI.BasicButton, { this.element[b ? "addClass" : "removeClass"]("active"); } }); -BI.shortcut('bi.relation_view_item', BI.RelationViewItem);/** +BI.shortcut("bi.relation_view_item", BI.RelationViewItem);/** * 关联视图 * * Created by GUY on 2015/12/22. @@ -90983,7 +90809,7 @@ BI.RelationView = BI.inherit(BI.Widget, { widths[j] = BI.MIN; } widths[j] = Math.max(widths[j], obj.getWidth()); - }) + }); }); return widths; }, @@ -90993,7 +90819,7 @@ BI.RelationView = BI.inherit(BI.Widget, { BI.each(this.views, function (i, items) { BI.each(items, function (j, obj) { heights[i] = Math.max(heights[i], obj.getHeight()); - }) + }); }); return heights; }, @@ -91024,7 +90850,7 @@ BI.RelationView = BI.inherit(BI.Widget, { }); }, - previewRelationTables: function(relationTables, show) { + previewRelationTables: function (relationTables, show) { if (!show) { BI.each(this.storeViews, function (i, view) { view.toggleRegion(true); @@ -91061,7 +90887,7 @@ BI.RelationView = BI.inherit(BI.Widget, { type: "bi.svg" }); - //算出所有的区域和关联 + // 算出所有的区域和关联 var regions = this.regions = {}, relations = this.relations = {}; BI.each(items, function (i, item) { var pr = item.primary.region, fr = item.foreign && item.foreign.region; @@ -91085,7 +90911,7 @@ BI.RelationView = BI.inherit(BI.Widget, { } pr && fr && relations[pr][fr].push(item); }); - //求拓扑 + // 求拓扑 var topology = []; var rs = BI.clone(regions), store = {}; while (!BI.isEmpty(rs)) { @@ -91101,7 +90927,7 @@ BI.RelationView = BI.inherit(BI.Widget, { delete rs[k]; }); } - //构建视图 + // 构建视图 var views = this.views = {}, storeViews = this.storeViews = {}, indexes = this.indexes = {}; var verticals = []; BI.each(topology, function (i, items) { @@ -91138,16 +90964,16 @@ BI.RelationView = BI.inherit(BI.Widget, { verticals.push({ type: "bi.horizontal", items: horizontal - }) + }); }); - //求每一行的高度 + // 求每一行的高度 var heights = this._calculateHeights(); - //求每一列的宽度 + // 求每一列的宽度 var widths = this._calculateWidths(); - //求相对宽度和高度 + // 求相对宽度和高度 var offsetWidths = [0], offsetHeights = [0]; BI.each(heights, function (i, h) { if (i === 0) { @@ -91162,8 +90988,8 @@ BI.RelationView = BI.inherit(BI.Widget, { offsetWidths[i] = offsetWidths[i - 1] + widths[i - 1]; }); - //画线 - var lines = this.lines = {};//缓存所有的线 + // 画线 + var lines = this.lines = {};// 缓存所有的线 BI.each(relations, function (start, rs) { BI.each(rs, function (end, relation) { var startIndex = indexes[start], endIndex = indexes[end]; @@ -91227,7 +91053,7 @@ BI.RelationView = BI.inherit(BI.Widget, { } path += "M" + si.x + "," + si.y + "L" + ei.x + "," + ei.y; var line = lines[start][end] = self.svg.path(path) - .attr({"stroke": c.lineColor, "stroke-width": "2"}) + .attr({stroke: c.lineColor, "stroke-width": "2"}) .hover(function () { line.attr("stroke", c.selectLineColor).toFront(); storeViews[start].setValue(relation[0].primary.value); @@ -91267,7 +91093,7 @@ BI.RelationView = BI.inherit(BI.Widget, { }); BI.RelationView.EVENT_CHANGE = "RelationView.EVENT_CHANGE"; BI.RelationView.EVENT_PREVIEW = "EVENT_PREVIEW"; -BI.shortcut('bi.relation_view', BI.RelationView);/** +BI.shortcut("bi.relation_view", BI.RelationView);/** * Created by Young's on 2017/3/10. */ BI.RelationViewRegionContainer = BI.inherit(BI.Widget, { @@ -91324,7 +91150,7 @@ BI.RelationViewRegionContainer = BI.inherit(BI.Widget, { return this.region.getHeight(); }, - //获取上方开始划线的位置 + // 获取上方开始划线的位置 getTopLeftPosition: function () { return this.region.getTopLeftPosition(); }, @@ -91353,7 +91179,7 @@ BI.RelationViewRegionContainer = BI.inherit(BI.Widget, { v === true ? this.region.element.fadeIn() : this.region.element.fadeOut(); }, - setPreviewSelected: function(v) { + setPreviewSelected: function (v) { this.region.setPreviewSelected(v); } }); @@ -91404,11 +91230,11 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { value: o.value, textAlign: "left" }); - //title放body上 + // title放body上 if (BI.isKey(o.header)) { this.title.setTitle(o.header, { container: "body" - }) + }); } this.button_group = BI.createWidget({ @@ -91433,7 +91259,7 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { }], hgap: 25, vgap: 20 - }) + }); }, _createItems: function (items) { @@ -91449,7 +91275,7 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { self.setValue([]); self.fireEvent(BI.RelationViewRegion.EVENT_HOVER_OUT, item.value); } - }) + }); }); }, @@ -91469,54 +91295,54 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { return this.button_group.getAllButtons().length * 25 + 25 + 2 * 20 + 3; }, - //获取上方开始划线的位置 + // 获取上方开始划线的位置 getTopLeftPosition: function () { return { x: 25 + 10, y: 20 - } + }; }, getTopRightPosition: function () { return { x: this.getWidth() - 25 - 10, y: 20 - } + }; }, getBottomPosition: function () { return { x: 25 + 10, y: this.getHeight() - 20 - } + }; }, getLeftPosition: function () { return { x: 25, y: 20 + 10 - } + }; }, getRightPosition: function () { return { x: this.getWidth() - 25, y: 20 + 10 - } + }; }, setValue: function (v) { this.button_group.setValue(v); }, - setPreviewSelected: function(v) { + setPreviewSelected: function (v) { this.preview.setSelected(v); } }); BI.RelationViewRegion.EVENT_HOVER_IN = "RelationViewRegion.EVENT_HOVER_IN"; BI.RelationViewRegion.EVENT_HOVER_OUT = "RelationViewRegion.EVENT_HOVER_OUT"; BI.RelationViewRegion.EVENT_PREVIEW = "RelationViewRegion.EVENT_PREVIEW"; -BI.shortcut('bi.relation_view_region', BI.RelationViewRegion);/** +BI.shortcut("bi.relation_view_region", BI.RelationViewRegion);/** * 自适应宽度的表格 * * Created by GUY on 2016/2/3. @@ -91532,12 +91358,12 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.ResponisveTable.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-responsive-table", - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 - mergeRule: function (row1, row2) { //合并规则, 默认相等时合并 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 + mergeRule: function (row1, row2) { // 合并规则, 默认相等时合并 return BI.isEqual(row1, row2); }, @@ -91550,9 +91376,9 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { header: [], footer: false, - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -91583,7 +91409,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { header: o.header, footer: o.footer, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -91605,7 +91431,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { self.fireEvent(BI.Table.EVENT_TABLE_BEFORE_REGION_RESIZE, arguments); }); this.table.on(BI.Table.EVENT_TABLE_REGION_RESIZE, function () { - //important:在冻结并自适应列宽的情况下要随时变更表头宽度 + // important:在冻结并自适应列宽的情况下要随时变更表头宽度 if (o.isNeedResize === true && self._isAdaptiveColumn()) { self._resizeHeader(); } @@ -91635,7 +91461,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { if (o.isNeedFreeze === true) { var regionColumnSize = this.table.getRegionColumnSize(); var maxWidth = this.table.element.width(); - if (!regionColumnSize[0] || (regionColumnSize[0] === 'fill') || regionColumnSize[0] > maxWidth || regionColumnSize[1] > maxWidth) { + if (!regionColumnSize[0] || (regionColumnSize[0] === "fill") || regionColumnSize[0] > maxWidth || regionColumnSize[1] > maxWidth) { var freezeCols = o.freezeCols; if (freezeCols.length === 0) { this.table.setRegionColumnSize([0, "fill"]); @@ -91664,7 +91490,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { columnSizeRight.push(size); } }); - //因为有边框,所以加上数组长度的参数调整 + // 因为有边框,所以加上数组长度的参数调整 var sumLeft = BI.sum(columnSizeLeft) + columnSizeLeft.length, sumRight = BI.sum(columnSizeRight) + columnSizeRight.length; return { @@ -91672,7 +91498,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { sumRight: sumRight, left: columnSizeLeft, right: columnSizeRight - } + }; } return { size: columnSize, @@ -91687,7 +91513,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { _resizeHeader: function () { var self = this, o = this.options; if (o.isNeedFreeze === true) { - //若是当前处于自适应调节阶段 + // 若是当前处于自适应调节阶段 if (this._isAdaptiveColumn()) { var columnSize = this.table.getCalculateColumnSize(); this.table.setHeaderColumnSize(columnSize); @@ -91706,10 +91532,10 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { block = self._getBlockSize(); if (columnSizeLeft[columnSizeLeft.length - 1] < block.left[block.left.length - 1]) { - columnSizeLeft[columnSizeLeft.length - 1] = block.left[block.left.length - 1] + columnSizeLeft[columnSizeLeft.length - 1] = block.left[block.left.length - 1]; } if (columnSizeRight[columnSizeRight.length - 1] < block.right[block.right.length - 1]) { - columnSizeRight[columnSizeRight.length - 1] = block.right[block.right.length - 1] + columnSizeRight[columnSizeRight.length - 1] = block.right[block.right.length - 1]; } self.table.setColumnSize(columnSizeLeft.concat(columnSizeRight)); @@ -91729,7 +91555,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { block = this._getBlockSize(); if (size[size.length - 1] < block.size[block.size.length - 1]) { - size[size.length - 1] = block.size[block.size.length - 1] + size[size.length - 1] = block.size[block.size.length - 1]; } this.table.setColumnSize(size); } @@ -91877,7 +91703,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { } } }); -BI.shortcut('bi.responsive_table', BI.ResponisveTable);/** +BI.shortcut("bi.responsive_table", BI.ResponisveTable);/** * 加号表示的组节点 * Created by GUY on 2015/9/6. * @class BI.SelectTreeFirstPlusGroupNode @@ -91896,7 +91722,7 @@ BI.SelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -91980,7 +91806,7 @@ BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -91988,7 +91814,7 @@ BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { this.checkbox = BI.createWidget({ type: "bi.last_tree_node_checkbox", stopPropagation: true - }) + }); this.text = BI.createWidget({ type: "bi.label", textAlign: "left", @@ -92064,7 +91890,7 @@ BI.SelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeMidPlusGroupNode.superclass._init.apply(this, arguments); @@ -92322,7 +92148,7 @@ BI.SelectTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.level_tree', + type: "bi.level_tree", expander: { type: "bi.select_tree_expander", isDefaultInit: true @@ -92387,7 +92213,7 @@ BI.SequenceTableDynamicNumber = BI.inherit(BI.SequenceTableTreeNumber, { var result = []; var count = this._getStart(nodes); - function getLeafCount(node) { + function getLeafCount (node) { var cnt = 0; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { @@ -92434,7 +92260,7 @@ BI.SequenceTableDynamicNumber = BI.inherit(BI.SequenceTableTreeNumber, { return result; } }); -BI.shortcut('bi.sequence_table_dynamic_number', BI.SequenceTableDynamicNumber);/** +BI.shortcut("bi.sequence_table_dynamic_number", BI.SequenceTableDynamicNumber);/** * * Created by GUY on 2016/5/26. * @class BI.SequenceTableListNumber @@ -92447,16 +92273,16 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { baseCls: "bi-sequence-table-list-number", isNeedFreeze: false, scrollTop: 0, - startSequence: 1,//开始的序号 + startSequence: 1, // 开始的序号 headerRowSize: 25, rowSize: 25, sequenceHeaderCreator: null, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [], @@ -92577,7 +92403,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { styleGetter: function (index) { return function () { return o.sequenceCellStyleGetter(self.start + i - 1); - } + }; }(cnt) })); renderedCells.push({ @@ -92590,7 +92416,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { renderedKeys.push(this.start + i); } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (BI.deepContains(self.renderedKeys, key)) { @@ -92613,7 +92439,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { }); var addedItems = []; BI.each(addSet, function (index) { - addedItems.push(renderedCells[index]) + addedItems.push(renderedCells[index]); }); BI.createWidget({ type: "bi.absolute", @@ -92677,7 +92503,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { this._populate(); } }); -BI.shortcut('bi.sequence_table_list_number', BI.SequenceTableListNumber);/** +BI.shortcut("bi.sequence_table_list_number", BI.SequenceTableListNumber);/** * 带有序号的表格 * * Created by GUY on 2016/5/26. @@ -92698,11 +92524,11 @@ BI.SequenceTable = BI.inherit(BI.Widget, { isNeedResize: true, isResizeAdapt: false, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -92718,14 +92544,14 @@ BI.SequenceTable = BI.inherit(BI.Widget, { sequenceCellStyleGetter: BI.emptyFn, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [], showSequence: false, - startSequence: 1//开始的序号 + startSequence: 1// 开始的序号 }); }, @@ -92779,7 +92605,7 @@ BI.SequenceTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -92929,7 +92755,7 @@ BI.SequenceTable = BI.inherit(BI.Widget, { BI.SequenceTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.sequence_table', BI.SequenceTable);/** +BI.shortcut("bi.sequence_table", BI.SequenceTable);/** * 单选加载数据搜索loader面板 * Created by guy on 15/11/4. * @class BI.SingleSelectSearchLoader @@ -92939,7 +92765,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-search-loader', + baseCls: "bi-single-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -92996,7 +92822,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -93026,7 +92852,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: false - }) + }); }, _filterValues: function (src) { @@ -93049,12 +92875,12 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: false - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = v; this.button_group.setValue(v); }, @@ -93085,7 +92911,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_search_loader', BI.SingleSelectSearchLoader);/** +BI.shortcut("bi.single_select_search_loader", BI.SingleSelectSearchLoader);/** * * 在搜索框中输入文本弹出的面板 * @class BI.SingleSelectSearchPane @@ -93116,8 +92942,8 @@ BI.SingleSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'single-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "single-select-toolbar", height: this.constants.height }); @@ -93191,7 +93017,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-combo', + baseCls: "bi-single-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -93206,8 +93032,8 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { BI.isKey(self._startValue) && (self.storeValue = self._startValue); self.trigger.getSearcher().setState(self.storeValue); }; - this.storeValue = ''; - //标记正在请求数据 + this.storeValue = ""; + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -93226,7 +93052,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(self.getValue()); } callback.apply(self, arguments); @@ -93253,7 +93079,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -93290,7 +93116,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.single_select_popup_view', + type: "bi.single_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -93336,10 +93162,10 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -93376,7 +93202,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -93385,7 +93211,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, _makeMap: function (values) { @@ -93404,7 +93230,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -93450,7 +93276,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -93469,7 +93295,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -93510,7 +93336,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); }, @@ -93532,7 +93358,7 @@ BI.extend(BI.SingleSelectCombo, { BI.SingleSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.single_select_combo', BI.SingleSelectCombo);/** +BI.shortcut("bi.single_select_combo", BI.SingleSelectCombo);/** * 选择列表 * * Created by GUY on 2015/11/1. @@ -93541,130 +93367,130 @@ BI.shortcut('bi.single_select_combo', BI.SingleSelectCombo);/** */ BI.SingleSelectList = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.SingleSelectList.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-select-list", - direction: BI.Direction.Top,//toolbar的位置 - logic: { - dynamic: true - }, - items: [], - itemsCreator: BI.emptyFn, - hasNext: BI.emptyFn, - onLoaded: BI.emptyFn, - el: { - type: "bi.list_pane" - } - }) - }, - _init: function () { - BI.SingleSelectList.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _defaultConfig: function () { + return BI.extend(BI.SingleSelectList.superclass._defaultConfig.apply(this, arguments), { + baseCls: "bi-select-list", + direction: BI.Direction.Top, // toolbar的位置 + logic: { + dynamic: true + }, + items: [], + itemsCreator: BI.emptyFn, + hasNext: BI.emptyFn, + onLoaded: BI.emptyFn, + el: { + type: "bi.list_pane" + } + }); + }, + _init: function () { + BI.SingleSelectList.superclass._init.apply(this, arguments); + var self = this, o = this.options; - this.list = BI.createWidget(o.el, { - type: "bi.list_pane", - items: o.items, - itemsCreator: function (op, callback) { - o.itemsCreator(op, function (items) { - callback.apply(self, arguments); - }); - }, - onLoaded: o.onLoaded, - hasNext: o.hasNext - }); + this.list = BI.createWidget(o.el, { + type: "bi.list_pane", + items: o.items, + itemsCreator: function (op, callback) { + o.itemsCreator(op, function (items) { + callback.apply(self, arguments); + }); + }, + onLoaded: o.onLoaded, + hasNext: o.hasNext + }); - this.list.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (type === BI.Events.CLICK) { - self.fireEvent(BI.SingleSelectList.EVENT_CHANGE, value, obj); - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); + this.list.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { + if (type === BI.Events.CLICK) { + self.fireEvent(BI.SingleSelectList.EVENT_CHANGE, value, obj); + } + self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ - scrolly: true - }, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.list) - })))); + BI.createWidget(BI.extend({ + element: this + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ + scrolly: true + }, o.logic, { + items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.list) + })))); - }, + }, - hasPrev: function () { - return this.list.hasPrev(); - }, + hasPrev: function () { + return this.list.hasPrev(); + }, - hasNext: function () { - return this.list.hasNext(); - }, + hasNext: function () { + return this.list.hasNext(); + }, - prependItems: function (items) { - this.list.prependItems.apply(this.list, arguments); - }, + prependItems: function (items) { + this.list.prependItems.apply(this.list, arguments); + }, - addItems: function (items) { - this.list.addItems.apply(this.list, arguments); - }, + addItems: function (items) { + this.list.addItems.apply(this.list, arguments); + }, - setValue: function (v) { - this.list.setValue([v]); - }, + setValue: function (v) { + this.list.setValue([v]); + }, - getValue: function () { - return this.list.getValue()[0]; - }, + getValue: function () { + return this.list.getValue()[0]; + }, - empty: function () { - this.list.empty(); - }, + empty: function () { + this.list.empty(); + }, - populate: function (items) { - this.list.populate.apply(this.list, arguments); - }, + populate: function (items) { + this.list.populate.apply(this.list, arguments); + }, - resetHeight: function (h) { - this.list.resetHeight ? this.list.resetHeight(h) : - this.list.element.css({"max-height": h + "px"}) - }, + resetHeight: function (h) { + this.list.resetHeight ? this.list.resetHeight(h) : + this.list.element.css({"max-height": h + "px"}); + }, - setNotSelectedValue: function () { - this.list.setNotSelectedValue.apply(this.list, arguments); - }, + setNotSelectedValue: function () { + this.list.setNotSelectedValue.apply(this.list, arguments); + }, - getNotSelectedValue: function () { - return this.list.getNotSelectedValue(); - }, + getNotSelectedValue: function () { + return this.list.getNotSelectedValue(); + }, - getAllButtons: function () { - return this.list.getAllButtons(); - }, + getAllButtons: function () { + return this.list.getAllButtons(); + }, - getAllLeaves: function () { - return this.list.getAllLeaves(); - }, + getAllLeaves: function () { + return this.list.getAllLeaves(); + }, - getSelectedButtons: function () { - return this.list.getSelectedButtons(); - }, + getSelectedButtons: function () { + return this.list.getSelectedButtons(); + }, - getNotSelectedButtons: function () { - return this.list.getNotSelectedButtons(); - }, + getNotSelectedButtons: function () { + return this.list.getNotSelectedButtons(); + }, - getIndexByValue: function (value) { - return this.list.getIndexByValue(value); - }, + getIndexByValue: function (value) { + return this.list.getIndexByValue(value); + }, - getNodeById: function (id) { - return this.list.getNodeById(id); - }, + getNodeById: function (id) { + return this.list.getNodeById(id); + }, - getNodeByValue: function (value) { - return this.list.getNodeByValue(value); - } - }); - BI.SingleSelectList.EVENT_CHANGE = "EVENT_CHANGE"; - BI.shortcut("bi.single_select_list", BI.SingleSelectList);/** + getNodeByValue: function (value) { + return this.list.getNodeByValue(value); + } +}); +BI.SingleSelectList.EVENT_CHANGE = "EVENT_CHANGE"; +BI.shortcut("bi.single_select_list", BI.SingleSelectList);/** * 单选加载数据面板 * Created by guy on 15/11/2. * @class BI.SingleSelectLoader @@ -93674,7 +93500,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-loader', + baseCls: "bi-single-select-loader", logic: { dynamic: true }, @@ -93735,7 +93561,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -93765,7 +93591,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { logic: this.options.logic, height: 25, selected: false - }) + }); }, _scrollToTop: function () { @@ -93776,7 +93602,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, setStartValue: function (v) { @@ -93784,7 +93610,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.button_group.setValue(this.storeValue); }, @@ -93815,7 +93641,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_loader', BI.SingleSelectLoader);/** +BI.shortcut("bi.single_select_loader", BI.SingleSelectLoader);/** * 带加载的单选下拉面板 * @class BI.SingleSelectPopupView * @extends Widget @@ -93824,8 +93650,8 @@ BI.SingleSelectPopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectPopupView.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-popup-view', - maxWidth: 'auto', + baseCls: "bi-single-select-popup-view", + maxWidth: "auto", minWidth: 135, maxHeight: 400, valueFormatter: BI.emptyFn, @@ -93852,7 +93678,7 @@ BI.SingleSelectPopupView = BI.inherit(BI.Widget, { minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.loader }); @@ -93901,7 +93727,7 @@ BI.SingleSelectPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; BI.SingleSelectPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.shortcut('bi.single_select_popup_view', BI.SingleSelectPopupView);/** +BI.shortcut("bi.single_select_popup_view", BI.SingleSelectPopupView);/** * * 单选下拉框 * @class BI.SingleSelectTrigger @@ -93963,12 +93789,12 @@ BI.SingleSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: BI.createWidget(), width: 30 @@ -94010,7 +93836,7 @@ BI.SingleSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.single_select_trigger', BI.SingleSelectTrigger);/** +BI.shortcut("bi.single_select_trigger", BI.SingleSelectTrigger);/** * 单选输入框 * Created by guy on 15/11/3. * @class BI.SingleSelectEditor @@ -94019,12 +93845,12 @@ BI.shortcut('bi.single_select_trigger', BI.SingleSelectTrigger);/** BI.SingleSelectEditor = BI.inherit(BI.Widget, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.SingleSelectEditor.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-editor', + baseCls: "bi-single-select-editor", el: {} }); }, @@ -94033,10 +93859,10 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { BI.SingleSelectEditor.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.state_editor', + type: "bi.state_editor", element: this, height: o.height, - watermark: BI.i18nText('BI-Basic_Search'), + watermark: BI.i18nText("BI-Basic_Search"), allowBlank: true }); @@ -94072,16 +93898,16 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { var v = this.editor.getState(); if (BI.isArray(v) && v.length > 0) { return v[v.length - 1]; - } else { - return ""; } + return ""; + }, getKeywords: function () { var val = this.editor.getLastValidValue(); var keywords = val.match(/[\S]+/g); if (BI.isEndWithBlank(val)) { - return keywords.concat([' ']); + return keywords.concat([" "]); } return keywords; }, @@ -94091,7 +93917,7 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { } }); BI.SingleSelectEditor.EVENT_PAUSE = "SingleSelectEditor.EVENT_PAUSE"; -BI.shortcut('bi.single_select_editor', BI.SingleSelectEditor);/** +BI.shortcut("bi.single_select_editor", BI.SingleSelectEditor);/** * searcher * Created by guy on 15/11/3. * @class BI.SingleSelectSearcher @@ -94101,7 +93927,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-searcher', + baseCls: "bi-single-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -94115,7 +93941,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { BI.SingleSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.single_select_editor', + type: "bi.single_select_editor", height: o.height }); @@ -94197,11 +94023,11 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { setState: function (v) { var o = this.options; - v || (v = ''); - if (v === '') { + v || (v = ""); + if (v === "") { this.editor.setState(BI.Selection.None); } else { - this.editor.setState(o.valueFormatter(v + "") || (v + '')); + this.editor.setState(o.valueFormatter(v + "") || (v + "")); } }, @@ -94229,7 +94055,7 @@ BI.SingleSelectSearcher.EVENT_START = "EVENT_START"; BI.SingleSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.SingleSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.single_select_searcher', BI.SingleSelectSearcher);/** +BI.shortcut("bi.single_select_searcher", BI.SingleSelectSearcher);/** * 单选加载数据搜索loader面板 * Created by guy on 15/11/4. * @class BI.SingleSelectSearchLoader @@ -94239,7 +94065,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-search-loader', + baseCls: "bi-single-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -94296,7 +94122,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -94343,7 +94169,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: false - }) + }); }, _filterValues: function (src) { @@ -94366,12 +94192,12 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: false - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = v; this.button_group.setValue(v); }, @@ -94402,7 +94228,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_search_add_loader', BI.SingleSelectSearchLoader);/** +BI.shortcut("bi.single_select_search_add_loader", BI.SingleSelectSearchLoader);/** * * 在搜索框中输入文本弹出的面板 * @class BI.SingleSelectSearchPane @@ -94433,8 +94259,8 @@ BI.SingleSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'single-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "single-select-toolbar", height: this.constants.height }); @@ -94508,7 +94334,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-combo', + baseCls: "bi-single-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -94523,8 +94349,8 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { BI.isKey(self._startValue) && (self.storeValue = self._startValue); self.trigger.getSearcher().setState(self.storeValue); }; - this.storeValue = ''; - //标记正在请求数据 + this.storeValue = ""; + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -94543,7 +94369,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(self.getValue()); } callback.apply(self, arguments); @@ -94570,7 +94396,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -94607,7 +94433,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.single_select_popup_view', + type: "bi.single_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -94653,10 +94479,10 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -94693,7 +94519,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -94702,7 +94528,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, _makeMap: function (values) { @@ -94721,7 +94547,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -94767,7 +94593,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -94786,7 +94612,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -94827,7 +94653,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); }, @@ -94849,7 +94675,7 @@ BI.extend(BI.SingleSelectCombo, { BI.SingleSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.single_select_add_combo', BI.SingleSelectCombo);/** +BI.shortcut("bi.single_select_add_combo", BI.SingleSelectCombo);/** * * 单选下拉框 * @class BI.SingleSelectTrigger @@ -94911,12 +94737,12 @@ BI.SingleSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: BI.createWidget(), width: 30 @@ -94958,7 +94784,7 @@ BI.SingleSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.single_select_add_trigger', BI.SingleSelectTrigger);/** +BI.shortcut("bi.single_select_add_trigger", BI.SingleSelectTrigger);/** * searcher * Created by guy on 15/11/3. * @class BI.SingleSelectSearcher @@ -94968,7 +94794,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-searcher', + baseCls: "bi-single-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -94982,7 +94808,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { BI.SingleSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.single_select_editor', + type: "bi.single_select_editor", height: o.height }); @@ -95064,11 +94890,11 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { setState: function (v) { var o = this.options; - v || (v = ''); - if (v === '') { + v || (v = ""); + if (v === "") { this.editor.setState(BI.Selection.None); } else { - this.editor.setState(o.valueFormatter(v + "") || (v + '')); + this.editor.setState(o.valueFormatter(v + "") || (v + "")); } }, @@ -95096,7 +94922,7 @@ BI.SingleSelectSearcher.EVENT_START = "EVENT_START"; BI.SingleSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.SingleSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.single_select_add_searcher', BI.SingleSelectSearcher);/** +BI.shortcut("bi.single_select_add_searcher", BI.SingleSelectSearcher);/** * Created by User on 2017/11/16. */ BI.SignTextEditor = BI.inherit(BI.Widget, { @@ -95117,7 +94943,7 @@ BI.SignTextEditor = BI.inherit(BI.Widget, { errorText: "", text: "", height: 24 - }) + }); }, _init: function () { @@ -95156,7 +94982,7 @@ BI.SignTextEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignTextEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignTextEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ @@ -95390,13 +95216,13 @@ BI.SingleSlider = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -95472,7 +95298,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _draggable: function (widget) { @@ -95486,7 +95312,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setLabelPosition(significantPercent); self._setSliderPosition(significantPercent); @@ -95512,7 +95338,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -95520,7 +95346,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -95552,14 +95378,14 @@ BI.SingleSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { var o = this.options; var valid = false; if (BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max)) { - if(o.digit === false){ + if(o.digit === false) { valid = true; }else{ var dotText = (v + "").split(".")[1] || ""; @@ -95570,15 +95396,15 @@ BI.SingleSlider = BI.inherit(BI.Widget, { }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setLabelPosition: function (percent) { - this.label.element.css({"left": percent + "%"}); + this.label.element.css({left: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -95593,7 +95419,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { @@ -95720,13 +95546,13 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -95783,7 +95609,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _draggable: function (widget) { @@ -95797,7 +95623,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setLabelPosition(significantPercent); self._setSliderPosition(significantPercent); @@ -95823,7 +95649,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSliderLabel.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -95831,7 +95657,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -95863,23 +95689,23 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { - return BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max) + return BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max); }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setLabelPosition: function (percent) { - this.label.element.css({"left": percent + "%"}); + this.label.element.css({left: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -95894,7 +95720,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { @@ -96008,13 +95834,13 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -96050,7 +95876,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - } + }; }, _draggable: function (widget) { @@ -96064,7 +95890,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setSliderPosition(significantPercent); var v = self._getValueByPercent(significantPercent); @@ -96088,7 +95914,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -96096,7 +95922,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -96147,19 +95973,19 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { ref: function (ref) { self.track = ref; } - } + }; }, _checkValidation: function (v) { - return !(BI.isNull(v) || v < this.min || v > this.max) + return !(BI.isNull(v) || v < this.min || v > this.max); }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -96172,7 +95998,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { @@ -96328,7 +96154,7 @@ BI.SingleTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.level_tree', + type: "bi.level_tree", expander: { isDefaultInit: true }, @@ -96480,8 +96306,8 @@ BI.SwitchTree = BI.inherit(BI.Widget, { } }, - _removeIsParent: function(items) { - BI.each(items, function(i, item) { + _removeIsParent: function (items) { + BI.each(items, function (i, item) { BI.isNotNull(item.isParent) && delete item.isParent; }); return items; @@ -96537,7 +96363,7 @@ BI.SwitchTree.SelectType = { SingleSelect: BI.Selection.Single, MultiSelect: BI.Selection.Multi }; -BI.shortcut('bi.switch_tree', BI.SwitchTree); +BI.shortcut("bi.switch_tree", BI.SwitchTree); /** * Created by Baron on 2015/10/19. */ @@ -96555,7 +96381,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { var conf = BI.TimeInterval.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-time-interval" - }) + }); }, _init: function () { var self = this; @@ -96564,7 +96390,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { this.left = this._createCombo(); this.right = this._createCombo(); this.label = BI.createWidget({ - type: 'bi.label', + type: "bi.label", height: this.constants.height, width: this.constants.width, text: "-" @@ -96606,7 +96432,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { _createCombo: function () { var self = this; var combo = BI.createWidget({ - type: 'bi.multidate_combo' + type: "bi.multidate_combo" }); combo.on(BI.MultiDateCombo.EVENT_ERROR, function () { self._clearTitle(); @@ -96614,7 +96440,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { self.fireEvent(BI.TimeInterval.EVENT_ERROR); }); - combo.on(BI.MultiDateCombo.EVENT_VALID, function(){ + combo.on(BI.MultiDateCombo.EVENT_VALID, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -96630,7 +96456,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { } }); - combo.on(BI.MultiDateCombo.EVENT_FOCUS, function(){ + combo.on(BI.MultiDateCombo.EVENT_FOCUS, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -96650,7 +96476,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { self.left.hidePopupView(); self.right.hidePopupView(); }); - //combo.on(BI.MultiDateCombo.EVENT_CHANGE, function () { + // combo.on(BI.MultiDateCombo.EVENT_CHANGE, function () { // BI.Bubbles.hide("error"); // var smallDate = self.left.getKey(), bigDate = self.right.getKey(); // if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -96664,9 +96490,9 @@ BI.TimeInterval = BI.inherit(BI.Single, { // self._clearTitle(); // self.element.removeClass(self.constants.timeErrorCls); // } - //}); + // }); - combo.on(BI.MultiDateCombo.EVENT_CONFIRM, function(){ + combo.on(BI.MultiDateCombo.EVENT_CONFIRM, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -96690,14 +96516,14 @@ BI.TimeInterval = BI.inherit(BI.Single, { _check: function (smallDate, bigDate) { var smallObj = smallDate.match(/\d+/g), bigObj = bigDate.match(/\d+/g); return this._dateCheck(smallDate) && Date.checkLegal(smallDate) && this._checkVoid({ - year: smallObj[0], - month: smallObj[1], - day: smallObj[2] - }) && this._dateCheck(bigDate) && Date.checkLegal(bigDate) && this._checkVoid({ - year: bigObj[0], - month: bigObj[1], - day: bigObj[2] - }); + year: smallObj[0], + month: smallObj[1], + day: smallObj[2] + }) && this._dateCheck(bigDate) && Date.checkLegal(bigDate) && this._checkVoid({ + year: bigObj[0], + month: bigObj[1], + day: bigObj[2] + }); }, _compare: function (smallDate, bigDate) { smallDate = Date.parseDateTime(smallDate, "%Y-%X-%d").print("%Y-%X-%d"); @@ -96738,8 +96564,8 @@ BI.YearCombo = BI.inherit(BI.Widget, { return BI.extend(BI.YearCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-combo", behaviors: {}, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 25 }); }, @@ -96828,7 +96654,7 @@ BI.YearCombo = BI.inherit(BI.Widget, { }); BI.YearCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_combo', BI.YearCombo);/** +BI.shortcut("bi.year_combo", BI.YearCombo);/** * 年份展示面板 * * Created by GUY on 2015/9/2. @@ -96841,8 +96667,8 @@ BI.YearPopup = BI.inherit(BI.Widget, { return BI.extend(BI.YearPopup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-popup", behaviors: {}, - min: '1900-01-01', //最小日期 - max: '2099-12-31' //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31" // 最大日期 }); }, @@ -96951,8 +96777,8 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { _defaultConfig: function () { return BI.extend(BI.YearTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-year-trigger bi-border", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24 }); }, @@ -96973,7 +96799,7 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { vgap: c.vgap, allowBlank: true, errorText: c.errorText - }) + }); this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { self.fireEvent(BI.YearTrigger.EVENT_FOCUS); }); @@ -97001,7 +96827,7 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { }); BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -97104,7 +96930,7 @@ BI.YearMonthCombo = BI.inherit(BI.Widget, { }); BI.YearMonthCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearMonthCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_month_combo', BI.YearMonthCombo);/** +BI.shortcut("bi.year_month_combo", BI.YearMonthCombo);/** * 年份 + 月份下拉框 * * @class BI.YearQuarterCombo @@ -97171,7 +96997,7 @@ BI.YearQuarterCombo = BI.inherit(BI.Widget, { }); BI.YearQuarterCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearQuarterCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_quarter_combo', BI.YearQuarterCombo);/** +BI.shortcut("bi.year_quarter_combo", BI.YearQuarterCombo);/** * 简单的复选下拉框控件, 适用于数据量少的情况, 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值 * 封装了字段处理逻辑 * @@ -97218,7 +97044,7 @@ BI.AbstractAllValueChooser = BI.inherit(BI.Widget, { } else { call(this.items); } - function call(items) { + function call (items) { var keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); @@ -97227,7 +97053,7 @@ BI.AbstractAllValueChooser = BI.inherit(BI.Widget, { var search = BI.Func.getSearchResult(items, kw); items = search.matched.concat(search.finded); }); - if (options.selectedValues) {//过滤 + if (options.selectedValues) {// 过滤 var filter = BI.makeObject(options.selectedValues, true); items = BI.filter(items, function (i, ob) { return !filter[ob.value]; @@ -97277,7 +97103,7 @@ BI.AllValueChooserCombo = BI.inherit(BI.AbstractAllValueChooser, { this.items = o.items; } this.combo = BI.createWidget({ - type: 'bi.multi_select_combo', + type: "bi.multi_select_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -97310,7 +97136,7 @@ BI.AllValueChooserCombo = BI.inherit(BI.AbstractAllValueChooser, { } }); BI.AllValueChooserCombo.EVENT_CONFIRM = "AllValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.all_value_chooser_combo', BI.AllValueChooserCombo);/** +BI.shortcut("bi.all_value_chooser_combo", BI.AllValueChooserCombo);/** * 简单的复选下拉框控件, 适用于数据量少的情况, 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值 * 封装了字段处理逻辑 * @@ -97338,7 +97164,7 @@ BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, { this.items = o.items; } this.list = BI.createWidget({ - type: 'bi.multi_select_list', + type: "bi.multi_select_list", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -97371,7 +97197,7 @@ BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, { } }); BI.AllValueChooserPane.EVENT_CHANGE = "AllValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { +BI.shortcut("bi.all_value_chooser_pane", BI.AllValueChooserPane);BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { _const: { perPage: 100 @@ -97401,7 +97227,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree } else { call(); } - function call() { + function call () { switch (options.type) { case BI.TreeView.REQ_TYPE_INIT_DATA: self._reqInitTreeNode(options, callback); @@ -97438,7 +97264,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree items: result }); - function doCheck(parentValues, node, selected) { + function doCheck (parentValues, node, selected) { if (selected == null || BI.isEmpty(selected)) { BI.each(node.getChildren(), function (i, child) { var newParents = BI.clone(parentValues); @@ -97455,10 +97281,10 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree newParents.push(node.value); createOneJson(node, node.parent && node.parent.id, getCount(selected[k], newParents)); doCheck(newParents, node, selected[k]); - }) + }); } - function getCount(jo, parentValues) { + function getCount (jo, parentValues) { if (jo == null) { return 0; } @@ -97469,7 +97295,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return BI.size(jo); } - function createOneJson(node, pId, llen) { + function createOneJson (node, pId, llen) { result.push({ id: node.id, pId: pId, @@ -97496,15 +97322,15 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree callback(selectedValues); - function dealWithSelectedValues(selectedValues) { + function dealWithSelectedValues (selectedValues) { var p = parentValues.concat(notSelectedValue); - //存储的值中存在这个值就把它删掉 - //例如选中了中国-江苏-南京, 取消中国或江苏或南京 + // 存储的值中存在这个值就把它删掉 + // 例如选中了中国-江苏-南京, 取消中国或江苏或南京 if (canFindKey(selectedValues, p)) { - //如果搜索的值在父亲链中 + // 如果搜索的值在父亲链中 if (isSearchValueInParent(p)) { - //例如选中了 中国-江苏, 搜索江苏, 取消江苏 - //例如选中了 中国-江苏, 搜索江苏, 取消中国 + // 例如选中了 中国-江苏, 搜索江苏, 取消江苏 + // 例如选中了 中国-江苏, 搜索江苏, 取消中国 self._deleteNode(selectedValues, p); } else { var searched = []; @@ -97513,50 +97339,50 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree BI.each(searched, function (i, arr) { var node = self._getNode(selectedValues, arr); if (node) { - //例如选中了 中国-江苏-南京,搜索南京,取消中国 + // 例如选中了 中国-江苏-南京,搜索南京,取消中国 self._deleteNode(selectedValues, arr); } else { - //例如选中了 中国-江苏,搜索南京,取消中国 + // 例如选中了 中国-江苏,搜索南京,取消中国 expandSelectedValue(selectedValues, arr, BI.last(arr)); } - }) + }); } } } - //存储的值中不存在这个值,但父亲节点是全选的情况 - //例如选中了中国-江苏,取消南京 - //important 选中了中国-江苏,取消了江苏,但是搜索的是南京 + // 存储的值中不存在这个值,但父亲节点是全选的情况 + // 例如选中了中国-江苏,取消南京 + // important 选中了中国-江苏,取消了江苏,但是搜索的是南京 if (isChild(selectedValues, p)) { var result = [], finded = false; - //如果parentValues中有匹配的值,说明搜索结果不在当前值下 + // 如果parentValues中有匹配的值,说明搜索结果不在当前值下 if (isSearchValueInParent(p)) { finded = true; } else { - //从当前值开始搜 + // 从当前值开始搜 finded = search(parentValues, notSelectedValue, result); p = parentValues; } if (finded === true) { - //去掉点击的节点之后的结果集 + // 去掉点击的节点之后的结果集 expandSelectedValue(selectedValues, p, notSelectedValue); - //添加去掉搜索的结果集 + // 添加去掉搜索的结果集 if (result.length > 0) { BI.each(result, function (i, strs) { self._buildTree(selectedValues, strs); - }) + }); } } } } - function expandSelectedValue(selectedValues, parents, notSelectedValue) { + function expandSelectedValue (selectedValues, parents, notSelectedValue) { var next = selectedValues; var childrenCount = []; var path = []; - //去掉点击的节点之后的结果集 + // 去掉点击的节点之后的结果集 BI.some(parents, function (i, v) { var t = next[v]; if (t == null) { @@ -97568,7 +97394,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree var expanded = self._getChildren(split); path.push(split); childrenCount.push(expanded.length); - //如果只有一个值且取消的就是这个值 + // 如果只有一个值且取消的就是这个值 if (i === parents.length - 1 && expanded.length === 1 && expanded[0] === notSelectedValue) { for (var j = childrenCount.length - 1; j >= 0; j--) { if (childrenCount[j] === 1) { @@ -97597,7 +97423,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function search(parents, current, result, searched) { + function search (parents, current, result, searched) { var newParents = BI.clone(parents); newParents.push(current); if (self._isMatch(parents, current, keyword)) { @@ -97627,7 +97453,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return can; } - function isSearchValueInParent(parentValues) { + function isSearchValueInParent (parentValues) { for (var i = 0, len = parentValues.length; i < len; i++) { if (self._isMatch(parentValues.slice(0, parentValues.length - 1), parentValues[i], keyword)) { return true; @@ -97636,7 +97462,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return false; } - function canFindKey(selectedValues, parents) { + function canFindKey (selectedValues, parents) { var t = selectedValues; for (var i = 0; i < parents.length; i++) { var v = parents[i]; @@ -97648,7 +97474,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return true; } - function isChild(selectedValues, parents) { + function isChild (selectedValues, parents) { var t = selectedValues; for (var i = 0; i < parents.length; i++) { var v = parents[i]; @@ -97684,7 +97510,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); callback(jo); - function dealWithSelectedValues(selected, parents) { + function dealWithSelectedValues (selected, parents) { if (selected == null || BI.isEmpty(selected)) { return true; } @@ -97704,7 +97530,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return can && isAllSelected(selected, parents); } - function isAllSelected(selected, parents) { + function isAllSelected (selected, parents) { return BI.isEmpty(selected) || self._getChildCount(parents) === BI.size(selected); } }, @@ -97721,10 +97547,10 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree hasNext: output.length > self._const.perPage, items: result, lastSearchValue: BI.last(output) - }) + }); }); - function search() { + function search () { var children = self._getChildren([]); var start = children.length; if (lastSearchValue !== "") { @@ -97754,7 +97580,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return output; } - function nodeSearch(deep, parentValues, current, isAllSelect, result) { + function nodeSearch (deep, parentValues, current, isAllSelect, result) { if (self._isMatch(parentValues, current, keyword)) { var checked = isAllSelect || isSelected(parentValues, current); createOneJson(parentValues, current, false, checked, !isAllSelect && isHalf(parentValues, current), true, result); @@ -97783,8 +97609,8 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return [can, checked]; } - function createOneJson(parentValues, value, isOpen, checked, half, flag, result) { - var node = self._getTreeNode(parentValues, value) + function createOneJson (parentValues, value, isOpen, checked, half, flag, result) { + var node = self._getTreeNode(parentValues, value); result.push({ id: node.id, pId: node.pId, @@ -97799,7 +97625,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function isHalf(parentValues, value) { + function isHalf (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return null; @@ -97813,7 +97639,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function isAllSelected(parentValues, value) { + function isAllSelected (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return null; @@ -97827,7 +97653,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function isSelected(parentValues, value) { + function isSelected (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return false; @@ -97839,7 +97665,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function findSelectedObj(parentValues) { + function findSelectedObj (parentValues) { var find = selectedValues; if (find == null) { return null; @@ -97878,7 +97704,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree isParent: nodes[i].getChildrenLength() > 0, checked: state[0], halfCheck: state[1] - }) + }); } BI.nextTick(function () { callback({ @@ -97887,7 +97713,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); }); - function judgeState(parentValues, selected_value, checkState) { + function judgeState (parentValues, selected_value, checkState) { var checked = checkState.checked, half = checkState.half; if (parentValues.length > 0 && !checked) { return false; @@ -97895,7 +97721,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return (parentValues.length === 0 || (checked && half) && !BI.isEmpty(selected_value)); } - function dealWidthSelectedValue(parentValues, selectedValues) { + function dealWidthSelectedValue (parentValues, selectedValues) { var valueMap = {}; BI.each(parentValues, function (i, v) { selectedValues = selectedValues[v] || {}; @@ -97920,11 +97746,11 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return valueMap; } - function getCheckState(current, parentValues, valueMap, checkState) { + function getCheckState (current, parentValues, valueMap, checkState) { var checked = checkState.checked, half = checkState.half; var tempCheck = false, halfCheck = false; if (BI.has(valueMap, current)) { - //可能是半选 + // 可能是半选 if (valueMap[current][0] === 1) { var values = BI.clone(parentValues); values.push(current); @@ -97963,7 +97789,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree var pNode = this._getNode(selectedValues, p); if (pNode != null && pNode[name]) { delete pNode[name]; - //递归删掉空父节点 + // 递归删掉空父节点 while (p.length > 0 && BI.isEmpty(pNode)) { name = p[p.length - 1]; p = p.slice(0, p.length - 1); @@ -98054,7 +97880,7 @@ BI.TreeValueChooserCombo = BI.inherit(BI.AbstractTreeValueChooser, { this._initData(o.items); } this.combo = BI.createWidget({ - type: 'bi.multi_tree_combo', + type: "bi.multi_tree_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), width: o.width, @@ -98079,7 +97905,7 @@ BI.TreeValueChooserCombo = BI.inherit(BI.AbstractTreeValueChooser, { } }); BI.TreeValueChooserCombo.EVENT_CONFIRM = "TreeValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.tree_value_chooser_combo', BI.TreeValueChooserCombo);/** +BI.shortcut("bi.tree_value_chooser_combo", BI.TreeValueChooserCombo);/** * 简单的复选下拉树控件, 适用于数据量少的情况 * * Created by GUY on 2015/10/29. @@ -98100,7 +97926,7 @@ BI.TreeValueChooserPane = BI.inherit(BI.AbstractTreeValueChooser, { BI.TreeValueChooserPane.superclass._init.apply(this, arguments); var self = this, o = this.options; this.pane = BI.createWidget({ - type: 'bi.multi_select_tree', + type: "bi.multi_select_tree", element: this, itemsCreator: BI.bind(this._itemsCreator, this) }); @@ -98131,7 +97957,7 @@ BI.TreeValueChooserPane = BI.inherit(BI.AbstractTreeValueChooser, { } }); BI.TreeValueChooserPane.EVENT_CHANGE = "TreeValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.tree_value_chooser_pane', BI.TreeValueChooserPane);/** +BI.shortcut("bi.tree_value_chooser_pane", BI.TreeValueChooserPane);/** * 简单的复选下拉框控件, 适用于数据量少的情况 * 封装了字段处理逻辑 * @@ -98188,7 +98014,7 @@ BI.AbstractValueChooser = BI.inherit(BI.Widget, { } else { call(this.items); } - function call(items) { + function call (items) { var keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); @@ -98197,7 +98023,7 @@ BI.AbstractValueChooser = BI.inherit(BI.Widget, { var search = BI.Func.getSearchResult(items, kw); items = search.matched.concat(search.finded); }); - if (options.selectedValues) {//过滤 + if (options.selectedValues) {// 过滤 var filter = BI.makeObject(options.selectedValues, true); items = BI.filter(items, function (i, ob) { return !filter[ob.value]; @@ -98247,7 +98073,7 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { this.items = o.items; } this.combo = BI.createWidget({ - type: 'bi.multi_select_combo', + type: "bi.multi_select_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -98269,7 +98095,7 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { return { type: val.type, value: val.value - } + }; }, populate: function () { @@ -98277,7 +98103,7 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { } }); BI.ValueChooserCombo.EVENT_CONFIRM = "ValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.value_chooser_combo', BI.ValueChooserCombo);/** +BI.shortcut("bi.value_chooser_combo", BI.ValueChooserCombo);/** * 简单的复选下拉框控件, 适用于数据量少的情况 * 封装了字段处理逻辑 * @@ -98300,7 +98126,7 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { BI.ValueChooserPane.superclass._init.apply(this, arguments); var self = this, o = this.options; this.list = BI.createWidget({ - type: 'bi.multi_select_list', + type: "bi.multi_select_list", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this) @@ -98324,7 +98150,7 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { return { type: val.type, value: val.value - } + }; }, populate: function () { @@ -98332,13 +98158,13 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { } }); BI.ValueChooserPane.EVENT_CHANGE = "ValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ +BI.shortcut("bi.value_chooser_pane", BI.ValueChooserPane);(function () { var Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function (name, callback, context) { - if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; + if (!eventsApi(this, "on", name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); @@ -98348,7 +98174,7 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function (name, callback, context) { - if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; + if (!eventsApi(this, "once", name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function () { self.off(name, once); @@ -98363,7 +98189,7 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function (name, callback, context) { - if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; + if (!this._events || !eventsApi(this, "off", name, [callback, context])) return this; // Remove all callbacks for all events. if (!name && !callback && !context) { @@ -98420,7 +98246,7 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ trigger: function (name) { if (!this._events) return this; var args = slice.call(arguments, 1); - if (!eventsApi(this, 'trigger', name, args)) return this; + if (!eventsApi(this, "trigger", name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); @@ -98437,15 +98263,15 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // listening to. listenTo: function (obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); - var id = obj._listenId || (obj._listenId = _.uniqueId('l')); + var id = obj._listenId || (obj._listenId = _.uniqueId("l")); listeningTo[id] = obj; - if (!callback && typeof name === 'object') callback = this; + if (!callback && typeof name === "object") callback = this; obj.on(name, callback, this); return this; }, listenToOnce: function (obj, name, callback) { - if (typeof name === 'object') { + if (typeof name === "object") { for (var event in name) this.listenToOnce(obj, event, name[event]); return this; } @@ -98471,7 +98297,7 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; - if (!callback && typeof name === 'object') callback = this; + if (!callback && typeof name === "object") callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; @@ -98493,7 +98319,7 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ if (!name) return true; // Handle event maps. - if (typeof name === 'object') { + if (typeof name === "object") { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } @@ -98573,16 +98399,16 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; - name = ''; + name = ""; } if (!callback) callback = this[name]; var router = this; BI.history.route(route, function (fragment) { var args = router._extractParameters(route, fragment); if (router.execute(callback, args, name) !== false) { - router.trigger.apply(router, ['route:' + name].concat(args)); - router.trigger('route', name, args); - BI.history.trigger('route', router, name, args); + router.trigger.apply(router, ["route:" + name].concat(args)); + router.trigger("route", name, args); + BI.history.trigger("route", router, name, args); } }); return this; @@ -98605,7 +98431,7 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // routes can be defined at the bottom of the route map. _bindRoutes: function () { if (!this.routes) return; - this.routes = _.result(this, 'routes'); + this.routes = _.result(this, "routes"); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); @@ -98615,13 +98441,13 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function (route) { - route = route.replace(escapeRegExp, '\\$&') - .replace(optionalParam, '(?:$1)?') + route = route.replace(escapeRegExp, "\\$&") + .replace(optionalParam, "(?:$1)?") .replace(namedParam, function (match, optional) { - return optional ? match : '([^/?]+)'; + return optional ? match : "([^/?]+)"; }) - .replace(splatParam, '([^?]*?)'); - return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); + .replace(splatParam, "([^?]*?)"); + return new RegExp("^" + route + "(?:\\?([\\s\\S]*))?$"); }, // Given a route, and a URL fragment that it matches, return the array of @@ -98648,10 +98474,10 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // falls back to polling. var History = function () { this.handlers = []; - _.bindAll(this, 'checkUrl'); + _.bindAll(this, "checkUrl"); // Ensure that `History` can be used outside of the browser. - if (typeof window !== 'undefined') { + if (typeof window !== "undefined") { this.location = window.location; this.history = window.history; } @@ -98678,22 +98504,22 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // Are we at the app root? atRoot: function () { - var path = this.location.pathname.replace(/[^\/]$/, '$&/'); + var path = this.location.pathname.replace(/[^\/]$/, "$&/"); return path === this.root && !this.getSearch(); }, // In IE6, the hash fragment and search params are incorrect if the // fragment contains `?`. getSearch: function () { - var match = this.location.href.replace(/#.*/, '').match(/\?.+/); - return match ? match[0] : ''; + var match = this.location.href.replace(/#.*/, "").match(/\?.+/); + return match ? match[0] : ""; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function (window) { var match = (window || this).location.href.match(/#(.*)$/); - return match ? match[1] : ''; + return match ? match[1] : ""; }, // Get the pathname and search params, without the root. @@ -98701,7 +98527,7 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ var path = decodeURI(this.location.pathname + this.getSearch()); var root = this.root.slice(0, -1); if (!path.indexOf(root)) path = path.slice(root.length); - return path.charAt(0) === '/' ? path.slice(1) : path; + return path.charAt(0) === "/" ? path.slice(1) : path; }, // Get the cross-browser normalized URL fragment from the path or hash. @@ -98713,27 +98539,27 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ fragment = this.getHash(); } } - return fragment.replace(routeStripper, ''); + return fragment.replace(routeStripper, ""); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function (options) { - if (History.started) throw new Error('BI.history has already been started'); + if (History.started) throw new Error("BI.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? - this.options = _.extend({root: '/'}, this.options, options); + this.options = _.extend({root: "/"}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; - this._hasHashChange = 'onhashchange' in window; + this._hasHashChange = "onhashchange" in window; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); this.fragment = this.getFragment(); // Normalize root to always include a leading and trailing slash. - this.root = ('/' + this.root + '/').replace(rootStripper, '/'); + this.root = ("/" + this.root + "/").replace(rootStripper, "/"); // Transition from hashChange to pushState or vice versa if both are // requested. @@ -98742,8 +98568,8 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { - var root = this.root.slice(0, -1) || '/'; - this.location.replace(root + '#' + this.getPath()); + var root = this.root.slice(0, -1) || "/"; + this.location.replace(root + "#" + this.getPath()); // Return immediately as browser will do redirect to new url return true; @@ -98759,28 +98585,28 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // support the `hashchange` event, HTML5 history, or the user wants // `hashChange` but not `pushState`. if (!this._hasHashChange && this._wantsHashChange && (!this._wantsPushState || !this._hasPushState)) { - var iframe = document.createElement('iframe'); - iframe.src = 'javascript:0'; - iframe.style.display = 'none'; + var iframe = document.createElement("iframe"); + iframe.src = "javascript:0"; + iframe.style.display = "none"; iframe.tabIndex = -1; var body = document.body; // Using `appendChild` will throw on IE < 9 if the document is not ready. this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow; this.iframe.document.open().close(); - this.iframe.location.hash = '#' + this.fragment; + this.iframe.location.hash = "#" + this.fragment; } // Add a cross-platform `addEventListener` shim for older browsers. var addEventListener = window.addEventListener || function (eventName, listener) { - return attachEvent('on' + eventName, listener); + return attachEvent("on" + eventName, listener); }; // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._hasPushState) { - addEventListener('popstate', this.checkUrl, false); + addEventListener("popstate", this.checkUrl, false); } else if (this._wantsHashChange && this._hasHashChange && !this.iframe) { - addEventListener('hashchange', this.checkUrl, false); + addEventListener("hashchange", this.checkUrl, false); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } @@ -98793,14 +98619,14 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ stop: function () { // Add a cross-platform `removeEventListener` shim for older browsers. var removeEventListener = window.removeEventListener || function (eventName, listener) { - return detachEvent('on' + eventName, listener); + return detachEvent("on" + eventName, listener); }; // Remove window listeners. if (this._hasPushState) { - removeEventListener('popstate', this.checkUrl, false); + removeEventListener("popstate", this.checkUrl, false); } else if (this._wantsHashChange && this._hasHashChange && !this.iframe) { - removeEventListener('hashchange', this.checkUrl, false); + removeEventListener("hashchange", this.checkUrl, false); } // Clean up the iframe if necessary. @@ -98861,24 +98687,24 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ if (!options || options === true) options = {trigger: !!options}; // Normalize the fragment. - fragment = this.getFragment(fragment || ''); + fragment = this.getFragment(fragment || ""); // Don't include a trailing slash on the root. var root = this.root; - if (fragment === '' || fragment.charAt(0) === '?') { - root = root.slice(0, -1) || '/'; + if (fragment === "" || fragment.charAt(0) === "?") { + root = root.slice(0, -1) || "/"; } var url = root + fragment; // Strip the hash and decode for matching. - fragment = decodeURI(fragment.replace(pathStripper, '')); + fragment = decodeURI(fragment.replace(pathStripper, "")); if (this.fragment === fragment) return; this.fragment = fragment; // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { - this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); + this.history[options.replace ? "replaceState" : "pushState"]({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. @@ -98904,11 +98730,11 @@ BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane);;(function(){ // a new one to the browser history. _updateHash: function (location, fragment, replace) { if (replace) { - var href = location.href.replace(/(javascript:|#).*$/, ''); - location.replace(href + '#' + fragment); + var href = location.href.replace(/(javascript:|#).*$/, ""); + location.replace(href + "#" + fragment); } else { // Some browsers require that `hash` contains a leading #. - location.hash = '#' + fragment; + location.hash = "#" + fragment; } } diff --git a/dist/bundle.min.js b/dist/bundle.min.js index dc0bc4c41..7fca6bb69 100644 --- a/dist/bundle.min.js +++ b/dist/bundle.min.js @@ -22,15 +22,15 @@ this.startLen=this.cm.getLine(this.startPos.line).length;var c=this;a.on("cursor for(var b=this.element.height(),c=a.scrollTop-a.overscanHeight,d=a.scrollTop+b+a.overscanHeight,e=this.tree.greatestLowerBound(c),f=this.tree.leastUpperBound(d),g=[],h=0;he&&(g=e),d.index=Math.ceil((f+(g>1&&g!==e?1:0))/(0===g?1:g)),(!b.dynamicShow&&!b.dynamicShowPrevNext||f>1)&&j!==!1&&(BI.isKey(j)?c.push({text:j,value:"prev",disabled:e===!1?b.hasPrev(f)===!1:!(f>1&&j!==!1)}):c.push(BI.extend({disabled:e===!1?b.hasPrev(f)===!1:!(f>1&&j!==!1)},j))),(!b.dynamicShow&&!b.dynamicShowFirstLast||d.index>1&&0!==g)&&h&&(c.push({text:h,value:"first",disabled:!(d.index>1&&0!==g)}),d.index>1&&0!==g&&c.push({type:"bi.label",cls:"page-ellipsis",text:"…"})),d.poor=Math.floor((g-1)/2),d.start=d.index>1?f-d.poor:1,d.end=d.index>1?function(){var a=f+(g-d.poor-1);return a>e?e:a}():g,d.end-d.start1&&0!==g&&e>g&&d.endg&&d.endg&&d.endg&&d.end1},hasNext:function(a){a||(a=1);var b=this.options,c=this.options.pages;return c===!1?b.hasNext(a):ac?c:(d=BI.result(b,"firstPage"),ab.pages?b.pages:a,this.currPage=a;this._populate()},getValue:function(){var a=this.button_group.getValue()[0];switch(a){case"prev":return-1;case"next":return 1;case"first":return BI.MIN;case"last":return BI.MAX;default:return a}},attr:function(a,b){BI.Pager.superclass.attr.apply(this,arguments),"curr"===a&&(this.currPage=BI.result(this.options,"curr"))},populate:function(){this._populate()}}),BI.Pager.EVENT_CHANGE="EVENT_CHANGE",BI.Pager.EVENT_AFTER_POPULATE="EVENT_AFTER_POPULATE",BI.shortcut("bi.pager",BI.Pager),BI.A=BI.inherit(BI.Text,{_defaultConfig:function(){var a=BI.A.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-a display-block",href:"",target:"_blank",el:null,element:"
    "})},_init:function(){var a=this.options;BI.A.superclass._init.apply(this,arguments),this.element.attr({href:a.href,target:a.target}),a.el&&BI.createWidget(a.el,{element:this})}}),BI.shortcut("bi.a",BI.A),BI.LoadingBar=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.LoadingBar.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-loading-bar bi-tips",height:30,handler:BI.emptyFn})},_init:function(){BI.LoadingBar.superclass._init.apply(this,arguments);var a=this;this.loaded=BI.createWidget({type:"bi.text_button",cls:"loading-text bi-list-item-simple",text:BI.i18nText("BI-Load_More"),width:120,handler:this.options.handler}),this.loaded.on(BI.Controller.EVENT_CHANGE,function(b){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.loading=BI.createWidget({type:"bi.layout",width:this.options.height,height:this.options.height,cls:"loading-background cursor-default"});var b=BI.createWidget({type:"bi.center_adapt",items:[this.loaded]}),c=BI.createWidget({type:"bi.center_adapt",items:[this.loading]});this.cardLayout=BI.createWidget({type:"bi.card",element:this,items:[{el:b,cardName:"loaded"},{el:c,cardName:"loading"}]}),this.invisible()},_reset:function(){this.visible(),this.loaded.setText(BI.i18nText("BI-Load_More")),this.loaded.enable()},setLoaded:function(){this._reset(),this.cardLayout.showCardByName("loaded")},setEnd:function(){this.setLoaded(),this.loaded.setText(BI.i18nText("BI-No_More_Data")),this.loaded.disable()},setLoading:function(){this._reset(),this.cardLayout.showCardByName("loading")}}),BI.shortcut("bi.loading_bar",BI.LoadingBar),BI.IconButton=BI.inherit(BI.BasicButton,{_defaultConfig:function(){var a=BI.IconButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-icon-button horizon-center",iconWidth:null,iconHeight:null})},_init:function(){BI.IconButton.superclass._init.apply(this,arguments);var a=this.options;this.element.css({textAlign:"center"}),this.icon=BI.createWidget({type:"bi.icon",width:a.iconWidth,height:a.iconHeight}),BI.isNumber(a.height)&&a.height>0&&BI.isNull(a.iconWidth)&&BI.isNull(a.iconHeight)?(this.element.css("lineHeight",a.height+"px"),BI.createWidget({type:"bi.default",element:this,items:[this.icon]})):BI.createWidget({element:this,type:"bi.center_adapt",items:[this.icon]})},doClick:function(){BI.IconButton.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.IconButton.EVENT_CHANGE,this)}}),BI.IconButton.EVENT_CHANGE="IconButton.EVENT_CHANGE",BI.shortcut("bi.icon_button",BI.IconButton),BI.ImageButton=BI.inherit(BI.BasicButton,{_defaultConfig:function(){var a=BI.ImageButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-image-button",src:"",iconWidth:"100%",iconHeight:"100%"})},_init:function(){BI.ImageButton.superclass._init.apply(this,arguments);var a=this.options;this.image=BI.createWidget({type:"bi.img",width:a.iconWidth,height:a.iconHeight,src:a.src}),BI.isNumber(a.iconWidth)||BI.isNumber(a.iconHeight)?BI.createWidget({type:"bi.center_adapt",element:this,items:[this.image]}):BI.createWidget({type:"bi.adaptive",element:this,items:[this.image],scrollable:!1})},setWidth:function(a){BI.ImageButton.superclass.setWidth.apply(this,arguments),this.options.width=a},setHeight:function(a){BI.ImageButton.superclass.setHeight.apply(this,arguments),this.options.height=a},setImageWidth:function(a){this.image.setWidth(a)},setImageHeight:function(a){this.image.setHeight(a)},getImageWidth:function(){return this.image.element.width()},getImageHeight:function(){return this.image.element.height()},setSrc:function(a){this.options.src=a,this.image.setSrc(a)},getSrc:function(){return this.image.getSrc()},doClick:function(){BI.ImageButton.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.ImageButton.EVENT_CHANGE,this)}}),BI.ImageButton.EVENT_CHANGE="ImageButton.EVENT_CHANGE",BI.shortcut("bi.image_button",BI.ImageButton),function(a){BI.Button=BI.inherit(BI.BasicButton,{_defaultConfig:function(a){var b=BI.Button.superclass._defaultConfig.apply(this,arguments);return BI.extend(b,{baseCls:(b.baseCls||"")+" bi-button",minWidth:a.block===!0||a.clear===!0?0:90,shadow:a.clear!==!0,isShadowShowingOnSelected:!0,readonly:!0,iconClass:"",level:"common",block:!1,clear:!1,textAlign:"center",whiteSpace:"nowrap",forceCenter:!1,textWidth:null,textHeight:null,hgap:a.clear?0:10,vgap:0,tgap:0,bgap:0,lgap:0,rgap:0})},_init:function(){BI.Button.superclass._init.apply(this,arguments);var a=this.options;!BI.isNumber(a.height)||a.clear||a.block?this.element.css({lineHeight:a.height+"px"}):this.element.css({height:a.height+"px",lineHeight:a.height+"px"}),BI.isKey(a.iconClass)?(this.icon=BI.createWidget({type:"bi.icon",width:18}),this.text=BI.createWidget({type:"bi.label",text:a.text,value:a.value}),BI.createWidget({type:"bi.horizontal_auto",cls:"button-"+a.level+" "+a.iconClass,element:this,hgap:a.hgap,vgap:a.vgap,tgap:a.tgap,bgap:a.bgap,lgap:a.lgap,rgap:a.rgap,items:[{type:"bi.horizontal",items:[this.icon,this.text]}]})):this.text=BI.createWidget({type:"bi.label",cls:"button-"+a.level,textAlign:a.textAlign,whiteSpace:a.whiteSpace,forceCenter:a.forceCenter,textWidth:a.textWidth,textHeight:a.textHeight,hgap:a.hgap,vgap:a.vgap,tgap:a.tgap,bgap:a.bgap,lgap:a.lgap,rgap:a.rgap,element:this,text:a.text,value:a.value}),a.block===!0&&this.element.addClass("block"),a.clear===!0&&this.element.addClass("clear"),a.minWidth>0&&this.element.css({"min-width":a.minWidth+"px"})},doClick:function(){BI.Button.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.Button.EVENT_CHANGE,this)},setText:function(a){BI.Button.superclass.setText.apply(this,arguments),this.text.setText(a)},setValue:function(a){BI.Button.superclass.setValue.apply(this,arguments),this.isReadOnly()||this.text.setValue(a)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},destroy:function(){BI.Button.superclass.destroy.apply(this,arguments)}}),BI.shortcut("bi.button",BI.Button),BI.Button.EVENT_CHANGE="EVENT_CHANGE"}(jQuery),BI.TextButton=BI.inherit(BI.BasicButton,{_defaultConfig:function(){var a=BI.TextButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-text-button",textAlign:"center",whiteSpace:"nowrap",forceCenter:!1,textWidth:null,textHeight:null,hgap:0,lgap:0,rgap:0,text:"",py:""})},_init:function(){BI.TextButton.superclass._init.apply(this,arguments);var a=this.options;this.text=BI.createWidget({type:"bi.label",element:this,textAlign:a.textAlign,whiteSpace:a.whiteSpace,textWidth:a.textWidth,textHeight:a.textHeight,forceCenter:a.forceCenter,width:a.width,height:a.height,hgap:a.hgap,lgap:a.lgap,rgap:a.rgap,text:a.text,value:a.value,py:a.py})},doClick:function(){BI.TextButton.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.TextButton.EVENT_CHANGE,this.getValue(),this)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},setText:function(a){BI.TextButton.superclass.setText.apply(this,arguments),a=BI.isArray(a)?a.join(","):a,this.text.setText(a)},setStyle:function(a){this.text.setStyle(a)},setValue:function(a){BI.TextButton.superclass.setValue.apply(this,arguments),this.isReadOnly()||(a=BI.isArray(a)?a.join(","):a,this.text.setValue(a))}}),BI.TextButton.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_button",BI.TextButton),BI.BlankIconIconTextItem=BI.inherit(BI.BasicButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.BlankIconIconTextItem.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-blank-icon-text-item",logic:{dynamic:!1},iconCls1:"close-ha-font",iconCls2:"close-ha-font",blankWidth:0,iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.BlankIconIconTextItem.superclass._init.apply(this,arguments);var a=this.options,b=this._const,c=BI.createWidget({type:"bi.layout",width:a.blankWidth,height:a.height});this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height}),this.icon1=BI.createWidget({type:"bi.icon_button",cls:a.iconCls1,forceNotSelected:!0,width:b.commonWidth,height:a.height}),this.icon2=BI.createWidget({type:"bi.icon_button",cls:a.iconCls2,forceNotSelected:!0,width:b.commonWidth,height:a.height}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",c,this.icon1,this.icon2,this.text)}))))},doClick:function(){BI.BlankIconIconTextItem.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.BlankIconIconTextItem.EVENT_CHANGE,this.getValue(),this)},setSelected:function(a){BI.BlankIconIconTextItem.superclass.setSelected.apply(this,arguments),this.icon1.setSelected(a),this.icon2.setSelected(a)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)}}),BI.BlankIconIconTextItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.blank_icon_icon_text_item",BI.BlankIconIconTextItem),BI.BlankIconTextIconItem=BI.inherit(BI.BasicButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.BlankIconTextIconItem.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-blank-icon-text-icon-item",logic:{dynamic:!1},iconCls1:"close-ha-font",iconCls2:"close-ha-font",blankWidth:0,iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.BlankIconTextIconItem.superclass._init.apply(this,arguments);var a=this.options,b=this._const;this.text=BI.createWidget({type:"bi.label",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height});var c=BI.createWidget({type:"bi.center_adapt",cls:a.iconCls1,width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]});BI.createWidget({type:"bi.absolute",element:this,items:[{el:{type:"bi.center_adapt",cls:a.iconCls2,width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]},top:0,bottom:0,right:0}]}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",{type:"bi.layout",width:a.blankWidth},c,this.text,{type:"bi.layout",width:b.commonWidth})}))))},doClick:function(){BI.BlankIconTextIconItem.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.BlankIconTextIconItem.EVENT_CHANGE,this.getValue(),this)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()}}),BI.BlankIconTextIconItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.blank_icon_text_icon_item",BI.BlankIconTextIconItem),BI.BlankIconTextItem=BI.inherit(BI.BasicButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.BlankIconTextItem.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-blank-icon-text-item",logic:{dynamic:!1},cls:"close-ha-font",blankWidth:0,iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.BlankIconTextItem.superclass._init.apply(this,arguments);var a=this.options,b=this._const,c=BI.createWidget({type:"bi.layout",width:a.blankWidth});this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height}),this.icon=BI.createWidget({type:"bi.center_adapt",width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",c,this.icon,this.text)}))))},doClick:function(){BI.BlankIconTextItem.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.BlankIconTextItem.EVENT_CHANGE,this.getValue(),this)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)}}),BI.BlankIconTextItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.blank_icon_text_item",BI.BlankIconTextItem),BI.IconTextIconItem=BI.inherit(BI.BasicButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.IconTextIconItem.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-icon-text-icon-item",logic:{dynamic:!1},iconCls1:"close-ha-font",iconCls2:"close-ha-font",iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.IconTextIconItem.superclass._init.apply(this,arguments);var a=this.options,b=this._const;this.text=BI.createWidget({type:"bi.label",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height});var c=BI.createWidget({type:"bi.center_adapt",cls:a.iconCls1,width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]}),d=BI.createWidget({type:"bi.layout",width:b.commonWidth});BI.createWidget({type:"bi.absolute",element:this,items:[{el:{type:"bi.center_adapt",cls:a.iconCls2,width:b.commonWidth,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]},top:0,bottom:0,right:0}]}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",c,this.text,d)}))))},doClick:function(){BI.IconTextIconItem.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.IconTextIconItem.EVENT_CHANGE,this.getValue(),this)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()}}),BI.IconTextIconItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_text_icon_item",BI.IconTextIconItem),BI.IconTextItem=BI.inherit(BI.BasicButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.IconTextItem.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-icon-text-item",direction:BI.Direction.Left,logic:{dynamic:!1},iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.IconTextItem.superclass._init.apply(this,arguments);var a=this.options,b=this._const;this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height}),this.icon=BI.createWidget({type:"bi.center_adapt",width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(a.direction),BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection(a.direction,this.icon,this.text)}))))},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()},doClick:function(){BI.IconTextItem.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.IconTextItem.EVENT_CHANGE,this.getValue(),this)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)}}),BI.IconTextItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_text_item",BI.IconTextItem),BI.TextIconItem=BI.inherit(BI.BasicButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.TextIconItem.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-text-icon-item",logic:{dynamic:!1},cls:"close-ha-font",iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.TextIconItem.superclass._init.apply(this,arguments);var a=this.options,b=this._const;this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height}),this.icon=BI.createWidget({type:"bi.center_adapt",width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",this.text,this.icon)}))))},doClick:function(){BI.TextIconItem.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.TextIconItem.EVENT_CHANGE,this.getValue(),this)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)}}),BI.TextIconItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_icon_item",BI.TextIconItem),BI.TextItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){var a=BI.TextItem.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-text-item",textAlign:"left",whiteSpace:"nowrap",textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.TextItem.superclass._init.apply(this,arguments);var a=this.options;this.text=BI.createWidget({type:"bi.label",element:this,textAlign:a.textAlign,whiteSpace:a.whiteSpace,textHeight:"nowrap"==a.whiteSpace?a.height:a.textHeight,height:a.height,hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,py:a.py})},doClick:function(){BI.TextItem.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.TextItem.EVENT_CHANGE,this.getValue(),this)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()}}),BI.TextItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_item",BI.TextItem),BI.IconTextIconNode=BI.inherit(BI.NodeButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.IconTextIconNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-icon-text-icon-node",logic:{dynamic:!1},iconCls1:"close-ha-font",iconCls2:"close-ha-font",iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.IconTextIconNode.superclass._init.apply(this,arguments);var a=this.options,b=this._const;this.text=BI.createWidget({type:"bi.label",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height});var c=BI.createWidget({type:"bi.center_adapt",cls:a.iconCls1,width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]}),d=BI.createWidget({type:"bi.layout",width:b.commonWidth,height:a.height});BI.createWidget({type:"bi.absolute",element:this,items:[{el:{type:"bi.center_adapt",cls:a.iconCls2,width:b.commonWidth,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]},top:0,bottom:0,right:0}]}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",c,this.text,d)}))))},doClick:function(){BI.IconTextIconNode.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.IconTextIconNode.EVENT_CHANGE,this.getValue(),this)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()}}),BI.IconTextIconNode.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_text_icon_node",BI.IconTextIconNode),BI.IconTextNode=BI.inherit(BI.NodeButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.IconTextNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-icon-text-node",logic:{dynamic:!1},cls:"close-ha-font",iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.IconTextNode.superclass._init.apply(this,arguments);var a=this.options,b=this._const;this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height}),this.icon=BI.createWidget({type:"bi.center_adapt",width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",this.icon,this.text)}))))},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()},doClick:function(){BI.IconTextNode.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.IconTextNode.EVENT_CHANGE,this.getValue(),this)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)}}),BI.IconTextNode.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_text_node",BI.IconTextNode),BI.TextIconNode=BI.inherit(BI.NodeButton,{_const:{commonWidth:25},_defaultConfig:function(){var a=BI.TextIconNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-text-icon-node",logic:{dynamic:!1},cls:"close-ha-font",iconHeight:null,iconWidth:null,textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.TextIconNode.superclass._init.apply(this,arguments);var a=this.options,b=this._const;this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,height:a.height}),this.icon=BI.createWidget({type:"bi.center_adapt",width:b.commonWidth,height:a.height,items:[{el:{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}}]}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",this.text,this.icon)}))))}, doClick:function(){BI.TextIconNode.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.TextIconNode.EVENT_CHANGE,this.getValue(),this)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)}}),BI.TextIconNode.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_icon_node",BI.TextIconNode),BI.TextNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.TextNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-text-node",textAlign:"left",whiteSpace:"nowrap",textHgap:0,textVgap:0,textLgap:0,textRgap:0})},_init:function(){BI.TextNode.superclass._init.apply(this,arguments);var a=this.options;this.text=BI.createWidget({type:"bi.label",element:this,textAlign:a.textAlign,whiteSpace:a.whiteSpace,textHeight:"nowrap"==a.whiteSpace?a.height:a.textHeight,height:a.height,hgap:a.textHgap,vgap:a.textVgap,lgap:a.textLgap,rgap:a.textRgap,text:a.text,value:a.value,keyword:a.keyword,py:a.py})},doClick:function(){BI.TextNode.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.TextNode.EVENT_CHANGE,this.getValue(),this)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},setValue:function(){this.isReadOnly()||this.text.setValue.apply(this.text,arguments)},getValue:function(){return this.text.getValue()},setText:function(){this.text.setText.apply(this.text,arguments)},getText:function(){return this.text.getText()}}),BI.TextNode.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_node",BI.TextNode),BI.CodeEditor=BI.inherit(BI.Single,{_defaultConfig:function(){return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(),{baseCls:"bi-code-editor",value:"",watermark:"",lineHeight:2,readOnly:!1,paramFormatter:function(a){return a}})},_init:function(){BI.CodeEditor.superclass._init.apply(this,arguments);var a=this.options,b=this;this.editor=CodeMirror(this.element[0],{textWrapping:!0,lineWrapping:!0,lineNumbers:!1,readOnly:a.readOnly,specialChars:/[\u0000-\u001f\u007f\u00ad\u200c-\u200f\u2028\u2029\ufeff]/}),1===a.lineHeight?this.element.addClass("codemirror-low-line-height"):this.element.addClass("codemirror-high-line-height"),this.editor.on("change",function(a,c){BI.nextTick(function(){b.fireEvent(BI.CodeEditor.EVENT_CHANGE)})}),this.editor.on("focus",function(){b.watermark.setVisible(!1),b.fireEvent(BI.CodeEditor.EVENT_FOCUS)}),this.editor.on("blur",function(){b.watermark.setVisible(BI.isEmptyString(b.getValue())),b.fireEvent(BI.CodeEditor.EVENT_BLUR)}),this.watermark=BI.createWidget({type:"bi.label",text:a.watermark,cls:"bi-water-mark",whiteSpace:"nowrap",textAlign:"left"}),this.watermark.element.bind("mousedown",function(a){b.insertString(""),b.editor.focus(),a.stopEvent()}),this.watermark.element.bind("click",function(a){b.editor.focus(),a.stopEvent()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.watermark,top:0,left:5}]}),BI.isKey(a.value)&&BI.nextTick(function(){b.setValue(a.value)})},_setEnable:function(a){BI.CodeEditor.superclass._setEnable.apply(this,arguments),this.editor.setOption("readOnly",a!==!0&&"nocursor")},_checkWaterMark:function(){var a=this.options;BI.isEmptyString(this.editor.getValue())&&BI.isKey(a.watermark)?this.watermark&&this.watermark.visible():this.watermark&&this.watermark.invisible()},insertParam:function(a){var b=a;a=this.options.paramFormatter(a);var c=this.editor.getCursor();this.editor.replaceSelection("​"+a+"​");var d=this.editor.getCursor(),e={className:"param",atomic:!0};BI.isNotNull(a.match(/^$/))&&(e.className="error-param"),e.value=b,this.editor.markText(c,d,e),this.editor.replaceSelection(" "),this.editor.focus()},insertString:function(a){this.editor.replaceSelection(a),this.editor.focus()},getValue:function(){return this.editor.getValue("\n",function(a){var b=a.text,c=a.text,d=0;return c.text=b,_.forEach(_.sortBy(a.markedSpans,"from"),function(a,b){switch(a.marker.className){case"param":case"error-param":var e=a.to-a.from;c=c.substr(0,a.from+d)+"${"+a.marker.value+"}"+c.substr(a.to+d,c.length),d+=3,d+=a.marker.value.length-e}}),c})},_analyzeContent:function(a){var b=/\$[\{][^\}]*[\}]|[^\$\{]*[^\$\{]/g;return a.match(b)},setValue:function(a){var b,c=this;this.refresh(),c.editor.setValue(""),b=this._analyzeContent(a||""),BI.each(b,function(a,b){var d=/\$[\{][^\}]*[\}]/,e=b.match(d);BI.isNotEmptyArray(e)?c.insertParam(e[0].substring(2,b.length-1)):c.insertString(b)}),this._checkWaterMark()},focus:function(){this.editor.focus()},blur:function(){this.editor.getInputField().blur()},setStyle:function(a){this.style=a,this.element.css(a)},getStyle:function(){return this.style},refresh:function(){var a=this;BI.nextTick(function(){a.editor.refresh()})}}),BI.CodeEditor.EVENT_CHANGE="EVENT_CHANGE",BI.CodeEditor.EVENT_BLUR="EVENT_BLUR",BI.CodeEditor.EVENT_FOCUS="EVENT_FOCUS",BI.shortcut("bi.code_editor",BI.CodeEditor),BI.Editor=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.Editor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:"bi-editor",hgap:4,vgap:2,lgap:0,rgap:0,tgap:0,bgap:0,tipType:"warning",inputType:"text",validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,allowBlank:!1,watermark:"",errorText:""})},_init:function(){BI.Editor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=this.addWidget(BI.createWidget({type:"bi.input",element:"",root:!0,watermark:b.watermark,validationChecker:b.validationChecker,quitChecker:b.quitChecker,allowBlank:b.allowBlank})),this.editor.element.css({width:"100%",height:"100%",border:"none",outline:"none",padding:"0",margin:"0"}),BI.isKey(this.options.watermark)&&(this.watermark=BI.createWidget({type:"bi.label",cls:"bi-water-mark",text:this.options.watermark,forceCenter:!0,height:b.height-2*(b.vgap+b.tgap),whiteSpace:"nowrap",textAlign:"left"}),this.watermark.element.bind({mousedown:function(b){a.isEnabled()?a.editor.isEditing()||a.editor.focus():a.editor.isEditing()&&a.editor.blur(),b.stopEvent()}}),this.watermark.element.bind("click",function(b){a.isEnabled()?a.editor.isEditing()||a.editor.focus():a.editor.isEditing()&&a.editor.blur(),b.stopEvent()}),this.watermark.element.css({position:"absolute",left:"3px",right:"3px",top:"0px",bottom:"0px"}));var c=[{el:{type:"bi.default",items:this.watermark?[this.editor,this.watermark]:[this.editor]},left:b.hgap+b.lgap,right:b.hgap+b.rgap,top:b.vgap+b.tgap,bottom:b.vgap+b.bgap}];BI.createWidget({type:"bi.absolute",element:this,items:c}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.Input.EVENT_FOCUS,function(){a._checkError(),a.element.addClass("bi-editor-focus"),a.fireEvent(BI.Editor.EVENT_FOCUS,arguments)}),this.editor.on(BI.Input.EVENT_BLUR,function(){a.setErrorVisible(!1),a.element.removeClass("bi-editor-focus"),a.fireEvent(BI.Editor.EVENT_BLUR,arguments)}),this.editor.on(BI.Input.EVENT_CLICK,function(){a.fireEvent(BI.Editor.EVENT_CLICK,arguments)}),this.editor.on(BI.Input.EVENT_CHANGE,function(){a.fireEvent(BI.Editor.EVENT_CHANGE,arguments)}),this.editor.on(BI.Input.EVENT_KEY_DOWN,function(b){a.fireEvent(BI.Editor.EVENT_KEY_DOWN,arguments)}),this.editor.on(BI.Input.EVENT_QUICK_DOWN,function(b){a.watermark&&a.watermark.invisible()}),this.editor.on(BI.Input.EVENT_VALID,function(){a._checkWaterMark(),a.setErrorVisible(!1),a.fireEvent(BI.Editor.EVENT_VALID,arguments)}),this.editor.on(BI.Input.EVENT_ERROR,function(){a._checkWaterMark(),a.fireEvent(BI.Editor.EVENT_ERROR,arguments),a.setErrorVisible(a.isEditing())}),this.editor.on(BI.Input.EVENT_RESTRICT,function(){a._checkWaterMark();var b=a.setErrorVisible(!0);b&&b.element.fadeOut(100,function(){b.element.fadeIn(100)}),a.fireEvent(BI.Editor.EVENT_RESTRICT,arguments)}),this.editor.on(BI.Input.EVENT_EMPTY,function(){a._checkWaterMark(),a.fireEvent(BI.Editor.EVENT_EMPTY,arguments)}),this.editor.on(BI.Input.EVENT_ENTER,function(){a.fireEvent(BI.Editor.EVENT_ENTER,arguments)}),this.editor.on(BI.Input.EVENT_SPACE,function(){a.fireEvent(BI.Editor.EVENT_SPACE,arguments)}),this.editor.on(BI.Input.EVENT_BACKSPACE,function(){a.fireEvent(BI.Editor.EVENT_BACKSPACE,arguments)}),this.editor.on(BI.Input.EVENT_REMOVE,function(){a.fireEvent(BI.Editor.EVENT_REMOVE,arguments)}),this.editor.on(BI.Input.EVENT_START,function(){a.fireEvent(BI.Editor.EVENT_START,arguments)}),this.editor.on(BI.Input.EVENT_PAUSE,function(){a.fireEvent(BI.Editor.EVENT_PAUSE,arguments)}),this.editor.on(BI.Input.EVENT_STOP,function(){a.fireEvent(BI.Editor.EVENT_STOP,arguments)}),this.editor.on(BI.Input.EVENT_CONFIRM,function(){a.fireEvent(BI.Editor.EVENT_CONFIRM,arguments)}),this.element.click(function(a){return a.stopPropagation(),!1}),BI.isKey(this.options.value)||BI.isEmptyString(this.options.value)?this.setValue(this.options.value):this._checkWaterMark()},_checkToolTip:function(){var a=this.options,b=a.errorText;BI.isFunction(b)&&(b=b(this.editor.getValue())),BI.isKey(b)&&(!this.isEnabled()||this.isValid()||BI.Bubbles.has(this.getName())&&BI.Bubbles.get(this.getName()).isVisible()?this.setTitle(""):this.setTitle(b))},_checkError:function(){this.setErrorVisible(this.isEnabled()&&!this.isValid()),this._checkToolTip()},_checkWaterMark:function(){var a=this.options;!this.disabledWaterMark&&""===this.editor.getValue()&&BI.isKey(a.watermark)?this.watermark&&this.watermark.visible():this.watermark&&this.watermark.invisible()},setErrorText:function(a){this.options.errorText=a},getErrorText:function(){return this.options.errorText},setErrorVisible:function(a){var b=this.options,c=b.errorText;if(BI.isFunction(c)&&(c=c(this.editor.getValue())),!this.disabledError&&BI.isKey(c))return BI.Bubbles[a?"show":"hide"](this.getName(),c,this),this._checkToolTip(),BI.Bubbles.get(this.getName())},disableError:function(){this.disabledError=!0,this._checkError()},enableError:function(){this.disabledError=!1,this._checkError()},disableWaterMark:function(){this.disabledWaterMark=!0,this._checkWaterMark()},enableWaterMark:function(){this.disabledWaterMark=!1,this._checkWaterMark()},focus:function(){this.element.addClass("text-editor-focus"),this.editor.focus()},blur:function(){this.element.removeClass("text-editor-focus"),this.editor.blur()},selectAll:function(){this.editor.selectAll()},onKeyDown:function(a){this.editor.onKeyDown(a)},setValue:function(a){BI.Editor.superclass.setValue.apply(this,arguments),this.editor.setValue(a),this._checkError(),this._checkWaterMark()},getLastValidValue:function(){return this.editor.getLastValidValue()},resetLastValidValue:function(){this.editor.resetLastValidValue()},getValue:function(){return this.isValid()?BI.trim(this.editor.getValue()):BI.trim(this.editor.getLastValidValue())},isEditing:function(){return this.editor.isEditing()},isValid:function(){return this.editor.isValid()}}),BI.Editor.EVENT_CHANGE="EVENT_CHANGE",BI.Editor.EVENT_FOCUS="EVENT_FOCUS",BI.Editor.EVENT_BLUR="EVENT_BLUR",BI.Editor.EVENT_CLICK="EVENT_CLICK",BI.Editor.EVENT_KEY_DOWN="EVENT_KEY_DOWN",BI.Editor.EVENT_SPACE="EVENT_SPACE",BI.Editor.EVENT_BACKSPACE="EVENT_BACKSPACE",BI.Editor.EVENT_START="EVENT_START",BI.Editor.EVENT_PAUSE="EVENT_PAUSE",BI.Editor.EVENT_STOP="EVENT_STOP",BI.Editor.EVENT_CONFIRM="EVENT_CONFIRM",BI.Editor.EVENT_VALID="EVENT_VALID",BI.Editor.EVENT_ERROR="EVENT_ERROR",BI.Editor.EVENT_ENTER="EVENT_ENTER",BI.Editor.EVENT_RESTRICT="EVENT_RESTRICT",BI.Editor.EVENT_REMOVE="EVENT_REMOVE",BI.Editor.EVENT_EMPTY="EVENT_EMPTY",BI.shortcut("bi.editor",BI.Editor),BI.MultifileEditor=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.MultifileEditor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-multifile-editor",multiple:!1,maxSize:-1,accept:"",url:""})},_init:function(){var a=this,b=this.options;BI.MultifileEditor.superclass._init.apply(this,arguments),this.file=BI.createWidget({type:"bi.file",cls:"multifile-editor",width:"100%",height:"100%",name:b.name,url:b.url,multiple:b.multiple,accept:b.accept,maxSize:b.maxSize}),this.file.on(BI.File.EVENT_CHANGE,function(){a.fireEvent(BI.MultifileEditor.EVENT_CHANGE,arguments)}),this.file.on(BI.File.EVENT_UPLOADSTART,function(){a.fireEvent(BI.MultifileEditor.EVENT_UPLOADSTART,arguments)}),this.file.on(BI.File.EVENT_ERROR,function(){a.fireEvent(BI.MultifileEditor.EVENT_ERROR,arguments)}),this.file.on(BI.File.EVENT_PROGRESS,function(){a.fireEvent(BI.MultifileEditor.EVENT_PROGRESS,arguments)}),this.file.on(BI.File.EVENT_UPLOADED,function(){a.fireEvent(BI.MultifileEditor.EVENT_UPLOADED,arguments)}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:{type:"bi.adaptive",scrollable:!1,items:[this.file]},top:0,right:0,left:0,bottom:0}]})},select:function(){this.file.select()},getValue:function(){return this.file.getValue()},upload:function(){this.file.upload()},reset:function(){this.file.reset()}}),BI.MultifileEditor.EVENT_CHANGE="MultifileEditor.EVENT_CHANGE",BI.MultifileEditor.EVENT_UPLOADSTART="MultifileEditor.EVENT_UPLOADSTART",BI.MultifileEditor.EVENT_ERROR="MultifileEditor.EVENT_ERROR",BI.MultifileEditor.EVENT_PROGRESS="MultifileEditor.EVENT_PROGRESS",BI.MultifileEditor.EVENT_UPLOADED="MultifileEditor.EVENT_UPLOADED",BI.shortcut("bi.multifile_editor",BI.MultifileEditor),BI.TextAreaEditor=BI.inherit(BI.Single,{_defaultConfig:function(){return $.extend(BI.TextAreaEditor.superclass._defaultConfig.apply(),{baseCls:"bi-textarea-editor bi-card",value:""})},_init:function(){BI.TextAreaEditor.superclass._init.apply(this,arguments);var a=this.options,b=this;this.content=BI.createWidget({type:"bi.layout",tagName:"textarea",width:"100%",height:"100%",cls:"bi-textarea textarea-editor-content display-block"}),this.content.element.css({resize:"none"}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:{type:"bi.adaptive",items:[this.content]},left:0,right:3,top:0,bottom:5}]}),this.content.element.on("input propertychange",function(a){b._checkWaterMark(),b.fireEvent(BI.TextAreaEditor.EVENT_CHANGE)}),this.content.element.focus(function(){b.isValid()&&(b._focus(),b.fireEvent(BI.TextAreaEditor.EVENT_FOCUS)),$(document).bind("mousedown."+b.getName(),function(a){BI.DOM.isExist(b)&&!b.element.__isMouseInBounds__(a)&&($(document).unbind("mousedown."+b.getName()),b.content.element.blur())})}),this.content.element.blur(function(){b.isValid()&&(b._blur(),b.fireEvent(BI.TextAreaEditor.EVENT_BLUR)),$(document).unbind("mousedown."+b.getName())}),BI.isKey(a.value)&&b.setValue(a.value),BI.isNotNull(a.style)&&b.setValue(a.style),this._checkWaterMark()},_checkWaterMark:function(){var a=this,b=this.options,c=this.getValue();BI.isNotEmptyString(c)?(this.watermark&&this.watermark.destroy(),this.watermark=null):BI.isNotEmptyString(b.watermark)&&(this.watermark?(this.watermark.setText(b.watermark),this.watermark.setValid(!b.invalid),this.watermark.setEnable(!b.disabled)):(this.watermark=BI.createWidget({type:"bi.text_button",cls:"bi-water-mark",textAlign:"left",height:30,text:b.watermark,invalid:b.invalid,disabled:b.disabled}),this.watermark.on(BI.TextButton.EVENT_CHANGE,function(){a.focus()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.watermark,left:0,top:0,right:0}]})))},_focus:function(){this.content.element.addClass("textarea-editor-focus"),this._checkWaterMark()},_blur:function(){this.content.element.removeClass("textarea-editor-focus"),this._checkWaterMark()},focus:function(){this._focus(),this.content.element.focus()},blur:function(){this._blur(),this.content.element.blur()},getValue:function(){return this.content.element.val()},setValue:function(a){this.content.element.val(a),this._checkWaterMark()},setStyle:function(a){this.style=a,this.element.css(a),this.content.element.css(BI.extend({},a,{color:a.color||BI.DOM.getContrastColor(BI.DOM.isRGBColor(a.backgroundColor)?BI.DOM.rgb2hex(a.backgroundColor):a.backgroundColor)}))},getStyle:function(){return this.style},_setValid:function(a){BI.TextAreaEditor.superclass._setValid.apply(this,arguments)}}),BI.TextAreaEditor.EVENT_CHANGE="EVENT_CHANGE",BI.TextAreaEditor.EVENT_BLUR="EVENT_BLUR",BI.TextAreaEditor.EVENT_FOCUS="EVENT_FOCUS",BI.shortcut("bi.textarea_editor",BI.TextAreaEditor),BI.Icon=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.Icon.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{tagName:"i",baseCls:(a.baseCls||"")+" x-icon b-font horizon-center display-block"})},_init:function(){BI.Icon.superclass._init.apply(this,arguments),BI.isIE9Below()&&this.element.addClass("hack")}}),BI.shortcut("bi.icon",BI.Icon),BI.Iframe=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.Iframe.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-iframe",src:"",width:"100%",height:"100%"})},_init:function(){var a=this.options;this.options.element=$("'))}catch(e){var form=document.createElement("form"),iframe=handler.iframe||(handler.iframe=document.createElement("iframe"));form.setAttribute("enctype","multipart/form-data"),iframe.setAttribute("name",iframe.id=target),iframe.setAttribute("src",url)}with(iframe.style.position="absolute",iframe.style.left=iframe.style.top="-10000px",iframe.onload=onload,iframe.onerror=function(a){isFunction(handler.onerror)&&handler.onerror(rpe,a||window.event)},iframe.onreadystatechange=function(){/loaded|complete/i.test(iframe.readyState)?onload():isFunction(handler.onloadprogress)&&(rpe.loaded",name:"",url:"",multiple:!0,accept:"",maxSize:-1})},_init:function(){var a=this.options;BI.File.superclass._init.apply(this,arguments),a.multiple===!0&&this.element.attr("multiple","multiple"),this.element.attr("name",a.name||this.getName())},mounted:function(){var a=this,b=this.options,c=this.wrap=this._wrap(this.element[0],b.maxSize);c.onloadstart=function(b,c){a.fireEvent(BI.File.EVENT_UPLOADSTART,arguments)},c.onprogress=function(b,c){this.file.fileSize!==-1&&b.simulation,a.fireEvent(BI.File.EVENT_PROGRESS,{file:this.file,total:b.total,loaded:b.loaded,simulation:b.simulation})},c.onerror=function(){a.fireEvent(BI.File.EVENT_ERROR)},c.onload=function(b,c){var d=this;setTimeout(function(){d.clean(),d.hide(),a.fireEvent(BI.File.EVENT_UPLOADED)},1e3)},c.url=b.url?b.url:BI.servletURL+"?op=fr_attach&cmd=ah_upload",c.fileType=b.accept,c.attach_array=[],c.attach_names=[],c.attachNum=0},_events:function(a){var b=this;return event.add(a.dom.input,"change",function(){event.del(a.dom.input,"change",arguments.callee);for(var c=a.dom.input.cloneNode(!0),d=0,e=F(a.dom.input);d>0:-1,files:[],clean:function(){this.files=[]},upload:function(a){if(a)for(var b in a)this[b]=a[b];return sendFiles(this,this.maxSize),this},hide:function(){this.dom.disabled&&(this.dom.disabled=!1,this.dom.input.removeAttribute("disabled"))},show:function(a,b,c,d){this.dom.disabled||(this.dom.disabled=!0,this.dom.input.setAttribute("disabled","disabled"))}})},select:function(){$(this.wrap.dom.input).click()},upload:function(a){this.wrap.upload(a)},getValue:function(){return this.wrap.attach_array},reset:function(){this.wrap.attach_array=[],this.wrap.attach_names=[],this.wrap.attachNum=0},_setEnable:function(a){BI.File.superclass._setEnable.apply(this,arguments),a===!0?this.element.attr("disabled","disabled"):this.element.removeAttr("disabled")}}),BI.File.EVENT_CHANGE="BI.File.EVENT_CHANGE",BI.File.EVENT_UPLOADSTART="EVENT_UPLOADSTART",BI.File.EVENT_ERROR="EVENT_ERROR",BI.File.EVENT_PROGRESS="EVENT_PROGRESS",BI.File.EVENT_UPLOADED="EVENT_UPLOADED",BI.shortcut("bi.file",BI.File)}(),BI.Input=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.Input.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-input display-block",element:"",validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,allowBlank:!1})},_init:function(){BI.Input.superclass._init.apply(this,arguments);var a=this,b=!1,c=!1,d=BI.debounce(function(c){a.onKeyDown(c,b),a._keydown_=!1},300),e=BI.debounce(BI.bind(this._click,this),BI.EVENT_RESPONSE_TIME,!0);this._blurDebounce=BI.debounce(BI.bind(this._blur,this),BI.EVENT_RESPONSE_TIME,!0),this.element.keydown(function(d){c=!1,b=d.ctrlKey,a.fireEvent(BI.Input.EVENT_QUICK_DOWN)}).keyup(function(b){c&&b.keyCode===BI.KeyCode.ENTER||(a._keydown_=!0,d(b.keyCode))}).on("input propertychange",function(b){BI.isNotNull(b.keyCode)&&(c=!0,a._keydown_=!0,d(b.keyCode))}).click(function(a){a.stopPropagation(),e()}).mousedown(function(b){a.element.val(a.element.val())}).focusout(function(b){a._blurDebounce()})},_focus:function(){this.element.addClass("bi-input-focus"),this._checkValidationOnValueChange(),this._isEditing=!0,""==this.getValue()&&(this.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.EMPTY,this.getValue(),this),this.fireEvent(BI.Input.EVENT_EMPTY)),this.fireEvent(BI.Input.EVENT_FOCUS)},_blur:function(){function a(){b.isValid()||b.options.quitChecker.apply(b,[BI.trim(b.getValue())])===!1||(b.element.val(b._lastValidValue?b._lastValidValue:""),b._checkValidationOnValueChange(),b._defaultState()),b.element.removeClass("bi-input-focus"),b._isEditing=!1,b._start=!1,b.isValid()&&(b.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.CONFIRM,b.getValue(),b),b.fireEvent(BI.Input.EVENT_CONFIRM)),b.fireEvent(BI.Input.EVENT_BLUR)}var b=this;b._keydown_===!0?BI.delay(a,300):a()},_click:function(){this._isEditing!==!0&&(this._focus(),this.selectAll(),this.fireEvent(BI.Input.EVENT_CLICK))},onClick:function(){this._click()},onKeyDown:function(a,b){this.isValid()&&BI.trim(this._lastValidValue)===BI.trim(this.getValue())||this._checkValidationOnValueChange(),this.isValid()&&""!==BI.trim(this.getValue())&&((BI.trim(this.getValue())===this._lastValue||this._start&&null!=this._lastValue&&""!==this._lastValue)&&(this._pause!==!0||/(\s|\u00A0)$/.test(this.getValue()))||(this._start=!0,this._pause=!1,this.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.STARTEDIT,this.getValue(),this),this.fireEvent(BI.Input.EVENT_START))),b===!0&&86===a?this._valueChange():(a==BI.KeyCode.ENTER&&(this.isValid()||this.options.quitChecker.apply(this,[BI.trim(this.getValue())])!==!1?(this.blur(),this.fireEvent(BI.Input.EVENT_ENTER)):this.fireEvent(BI.Input.EVENT_RESTRICT)),a==BI.KeyCode.SPACE&&this.fireEvent(BI.Input.EVENT_SPACE),a==BI.KeyCode.BACKSPACE&&""==this._lastValue&&this.fireEvent(BI.Input.EVENT_REMOVE),a!=BI.KeyCode.BACKSPACE&&a!=BI.KeyCode.DELETE||this.fireEvent(BI.Input.EVENT_BACKSPACE)),this.fireEvent(BI.Input.EVENT_KEY_DOWN),BI.isEndWithBlank(this.getValue())?(this._pause=!0,this.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.PAUSE,"",this),this.fireEvent(BI.Input.EVENT_PAUSE),this._defaultState()):a!==BI.KeyCode.BACKSPACE&&a!==BI.KeyCode.DELETE||""!==BI.trim(this.getValue())||null===this._lastValue||""===BI.trim(this._lastValue)?this._valueChange():(this.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.STOPEDIT,this.getValue(),this),this.fireEvent(BI.Input.EVENT_STOP),this._valueChange())},_defaultState:function(){""==this.getValue()&&(this.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.EMPTY,this.getValue(),this),this.fireEvent(BI.Input.EVENT_EMPTY)),this._lastValue=this.getValue(),this._lastSubmitValue=null},_valueChange:function(){this.isValid()&&BI.trim(this.getValue())!==this._lastSubmitValue&&(this.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.CHANGE,this.getValue(),this), this.fireEvent(BI.Input.EVENT_CHANGE),this._lastSubmitValue=BI.trim(this.getValue())),""==this.getValue()&&(this.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.EMPTY,this.getValue(),this),this.fireEvent(BI.Input.EVENT_EMPTY)),this._lastValue=this.getValue()},_checkValidationOnValueChange:function(){var a=this.options,b=this.getValue();this.setValid(a.allowBlank===!0&&""==BI.trim(b)||BI.isNotEmptyString(BI.trim(b))&&(b===this._lastValidValue||a.validationChecker.apply(this,[BI.trim(b)])!==!1))},focus:function(){if(!this.element.is(":visible"))throw new Error("input输入框在不可见下不能focus");!this._isEditing==!0&&(this.element.focus(),this._focus(),this.selectAll())},blur:function(){if(!this.element.is(":visible"))throw new Error("input输入框在不可见下不能blur");this._isEditing===!0&&(this.element.blur(),this._blurDebounce())},selectAll:function(){if(!this.element.is(":visible"))throw new Error("input输入框在不可见下不能select");this.element.select(),this._isEditing=!0},setValue:function(a){this.element.val(a),BI.nextTick(BI.bind(function(){this._checkValidationOnValueChange(),this._defaultState(),this.isValid()&&(this._lastSubmitValue=this.getValue())},this))},getValue:function(){return this.element.val()||""},isEditing:function(){return this._isEditing},getLastValidValue:function(){return this._lastValidValue},_setValid:function(){BI.Input.superclass._setValid.apply(this,arguments),this.isValid()?(this._lastValidValue=this.getValue(),this.element.removeClass("bi-input-error"),this.fireEvent(BI.Input.EVENT_VALID,BI.trim(this.getValue()),this)):(this._lastValidValue===this.getValue()&&(this._lastValidValue=null),this.element.addClass("bi-input-error"),this.fireEvent(BI.Input.EVENT_ERROR,BI.trim(this.getValue()),this))},_setEnable:function(a){BI.Input.superclass._setEnable.apply(this,[a]),this.element[0].disabled=!a}}),BI.Input.EVENT_CHANGE="EVENT_CHANGE",BI.Input.EVENT_FOCUS="EVENT_FOCUS",BI.Input.EVENT_CLICK="EVENT_CLICK",BI.Input.EVENT_BLUR="EVENT_BLUR",BI.Input.EVENT_KEY_DOWN="EVENT_KEY_DOWN",BI.Input.EVENT_QUICK_DOWN="EVENT_QUICK_DOWN",BI.Input.EVENT_SPACE="EVENT_SPACE",BI.Input.EVENT_BACKSPACE="EVENT_BACKSPACE",BI.Input.EVENT_START="EVENT_START",BI.Input.EVENT_PAUSE="EVENT_PAUSE",BI.Input.EVENT_STOP="EVENT_STOP",BI.Input.EVENT_CONFIRM="EVENT_CONFIRM",BI.Input.EVENT_REMOVE="EVENT_REMOVE",BI.Input.EVENT_EMPTY="EVENT_EMPTY",BI.Input.EVENT_VALID="EVENT_VALID",BI.Input.EVENT_ERROR="EVENT_ERROR",BI.Input.EVENT_ENTER="EVENT_ENTER",BI.Input.EVENT_RESTRICT="EVENT_RESTRICT",BI.shortcut("bi.input",BI.Input),BI.Radio=BI.inherit(BI.IconButton,{_defaultConfig:function(){var a=BI.Radio.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-radio radio-icon",selected:!1,handler:BI.emptyFn,width:16,height:16,iconWidth:16,iconHeight:16})},_init:function(){BI.Radio.superclass._init.apply(this,arguments)},doClick:function(){BI.Radio.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.Radio.EVENT_CHANGE)}}),BI.Radio.EVENT_CHANGE="Radio.EVENT_CHANGE",BI.shortcut("bi.radio",BI.Radio),BI.Label=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.Label.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-label",textAlign:"center",whiteSpace:"nowrap",forceCenter:!1,textWidth:null,textHeight:null,hgap:0,vgap:0,lgap:0,rgap:0,tgap:0,bgap:0,text:"",py:"",keyword:""})},_createJson:function(){var a=this.options;return{type:"bi.text",textAlign:a.textAlign,whiteSpace:a.whiteSpace,lineHeight:a.textHeight,text:a.text,value:a.value,py:a.py,keyword:a.keyword}},_init:function(){BI.Label.superclass._init.apply(this,arguments),"center"===this.options.textAlign?this._createCenterEl():this._createNotCenterEl()},_createCenterEl:function(){var a=this.options,b=this._createJson();if(BI.isNumber(a.width)&&a.width>0){if(BI.isNumber(a.textWidth)&&a.textWidth>0){if(BI.isNumber(a.height)&&a.height>0){var c=(a.width-a.textWidth)/2;return BI.createWidget({type:"bi.adaptive",height:a.height,scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b),left:c+a.hgap+a.lgap,right:c+a.hgap+a.rgap,top:a.vgap+a.tgap,bottom:a.vgap+a.bgap}]}),void this.element.css({"line-height":a.height+"px"})}return b.width=a.textWidth,void BI.createWidget({type:"bi.center_adapt",scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b)}]})}return"normal"==a.whiteSpace?(this.text=BI.createWidget(b),void BI.createWidget({type:"bi.center_adapt",scrollable:"normal"===a.whiteSpace,hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap,element:this,items:[this.text]})):BI.isNumber(a.height)&&a.height>0?(this.element.css({"line-height":a.height+"px"}),void BI.createWidget({type:"bi.absolute",scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b),left:a.hgap+a.lgap,right:a.hgap+a.rgap,top:a.vgap+a.tgap,bottom:a.vgap+a.bgap}]})):(b.width=a.width-2*a.hgap,void BI.createWidget({type:"bi.center_adapt",scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b)}]}))}return BI.isNumber(a.textWidth)&&a.textWidth>0?(b.width=a.textWidth,void BI.createWidget({type:"bi.center_adapt",scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b)}]})):"normal"==a.whiteSpace?(this.text=BI.createWidget(b),void BI.createWidget({type:"bi.center_adapt",hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap,scrollable:"normal"===a.whiteSpace,element:this,items:[this.text]})):BI.isNumber(a.height)&&a.height>0?BI.isNumber(a.textHeight)&&a.textHeight>0?(this.element.css({"line-height":a.height+"px"}),void BI.createWidget({type:"bi.adaptive",height:a.height,scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b),left:a.hgap+a.lgap,right:a.hgap+a.rgap,top:a.vgap+a.tgap,bottom:a.vgap+a.bgap}]})):(BI.extend(b,{hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap}),this.element.css({"line-height":a.height+"px"}),this.text=BI.createWidget(BI.extend(b,{element:this})),void BI.createWidget({type:"bi.layout",element:this.text,scrollable:"normal"===a.whiteSpace})):(BI.extend(b,{hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap}),a.forceCenter?(this.text=BI.createWidget(b),void BI.createWidget({type:"bi.center_adapt",element:this,items:[this.text]})):(this.text=BI.createWidget(BI.extend(b,{element:this})),void BI.createWidget({type:"bi.layout",element:this.text,scrollable:"normal"===a.whiteSpace})))},_createNotCenterEl:function(){var a=this.options,b=this._createJson();return BI.isNumber(a.width)&&a.width>0?BI.isNumber(a.textWidth)&&a.textWidth>0?BI.isNumber(a.height)&&a.height>0?(BI.createWidget({type:"bi.adaptive",height:a.height,scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b),left:a.hgap+a.lgap,right:a.hgap+a.rgap,top:a.vgap+a.tgap,bottom:a.vgap+a.bgap}]}),void this.element.css({"line-height":a.height+"px"})):(b.width=a.textWidth,void BI.createWidget({type:"bi.vertical_adapt",scrollable:"normal"===a.whiteSpace,hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap,element:this,items:[{el:this.text=BI.createWidget(b)}]})):"normal"==a.whiteSpace?(this.text=BI.createWidget(b),void BI.createWidget({type:"bi.vertical_adapt",scrollable:"normal"===a.whiteSpace,hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap,element:this,items:[this.text]})):BI.isNumber(a.height)&&a.height>0?(this.element.css({"line-height":a.height+"px"}),void BI.createWidget({type:"bi.absolute",scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b),left:a.hgap+a.lgap,right:a.hgap+a.rgap,top:a.vgap+a.tgap,bottom:a.vgap+a.bgap}]})):(b.width=a.width-2*a.hgap-a.lgap-a.rgap,void BI.createWidget({type:"bi.vertical_adapt",scrollable:"normal"===a.whiteSpace,hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap,element:this,items:[{el:this.text=BI.createWidget(b)}]})):BI.isNumber(a.textWidth)&&a.textWidth>0?(b.width=a.textWidth,void BI.createWidget({type:"bi.vertical_adapt",scrollable:"normal"===a.whiteSpace,hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap,element:this,items:[{el:this.text=BI.createWidget(b)}]})):"normal"==a.whiteSpace?(this.text=BI.createWidget(b),void BI.createWidget({type:"bi.vertical_adapt",scrollable:"normal"===a.whiteSpace,hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap,element:this,items:[this.text]})):BI.isNumber(a.height)&&a.height>0?BI.isNumber(a.textHeight)&&a.textHeight>0?(this.element.css({"line-height":a.height+"px"}),void BI.createWidget({type:"bi.adaptive",height:a.height,scrollable:"normal"===a.whiteSpace,element:this,items:[{el:this.text=BI.createWidget(b),left:a.hgap+a.lgap,right:a.hgap+a.rgap,top:a.vgap+a.tgap,bottom:a.vgap+a.bgap}]})):(BI.extend(b,{hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap}),this.element.css({"line-height":a.height+"px"}),this.text=BI.createWidget(BI.extend(b,{element:this})),void BI.createWidget({type:"bi.layout",element:this.text,scrollable:"normal"===a.whiteSpace})):(BI.extend(b,{hgap:a.hgap,vgap:a.vgap,lgap:a.lgap,rgap:a.rgap,tgap:a.tgap,bgap:a.bgap}),a.forceCenter?(this.text=BI.createWidget(b),void BI.createWidget({type:"bi.vertical_adapt",element:this,items:[this.text]})):(this.text=BI.createWidget(BI.extend(b,{element:this})),void BI.createWidget({type:"bi.layout",element:this.text,scrollable:"normal"===a.whiteSpace})))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},setText:function(a){this.options.text=a,this.text.setText(a)},getText:function(){return this.options.text},setStyle:function(a){this.text.setStyle(a)},setValue:function(a){BI.Label.superclass.setValue.apply(this,arguments),this.isReadOnly()||this.text.setValue(a)},populate:function(){BI.Label.superclass.populate.apply(this,arguments)}}),BI.shortcut("bi.label",BI.Label),BI.Link=BI.inherit(BI.Label,{_defaultConfig:function(){var a=BI.Link.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-link",href:"",target:"_blank"})},_createJson:function(){var a=this.options;return{type:"bi.a",textAlign:a.textAlign,whiteSpace:a.whiteSpace,lineHeight:a.textHeight,text:a.text,keyword:a.keyword,value:a.value,py:a.py,href:a.href,target:a.target}},_init:function(){BI.Link.superclass._init.apply(this,arguments)}}),BI.shortcut("bi.link",BI.Link),BI.Bubble=BI.inherit(BI.Tip,{_defaultConfig:function(){return BI.extend(BI.Bubble.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-bubble",direction:"top",text:"",height:35})},_init:function(){BI.Bubble.superclass._init.apply(this,arguments);var a=function(a){return a.stopPropagation(),a.stopEvent(),!1};this.element.bind({click:a,mousedown:a,mouseup:a,mouseover:a,mouseenter:a,mouseleave:a,mousemove:a}),BI.createWidget({type:"bi.left",element:this,items:[this["_"+this.options.direction]()]})},_createBubbleText:function(){return this.text=BI.createWidget({type:"bi.label",cls:"bubble-text",text:this.options.text,hgap:10,height:30})},_top:function(){return BI.createWidget({type:"bi.vertical",items:[{el:this._createBubbleText(),height:30},{el:{type:"bi.layout"},height:3}]})},_bottom:function(){return BI.createWidget({type:"bi.vertical",items:[{el:{type:"bi.layout"},height:3},{el:this._createBubbleText(),height:30}]})},_left:function(){return BI.createWidget({type:"bi.right",items:[{el:{type:"bi.layout",width:3,height:30}},{el:this._createBubbleText()}]})},_right:function(){return BI.createWidget({type:"bi.left",items:[{el:{type:"bi.layout",width:3,height:30}},{el:this._createBubbleText()}]})},setText:function(a){this.text.setText(a)}}),BI.shortcut("bi.bubble",BI.Bubble),BI.Toast=BI.inherit(BI.Tip,{_const:{minWidth:200,hgap:20},_defaultConfig:function(){return BI.extend(BI.Toast.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-toast",text:"",level:"success",height:30})},_init:function(){BI.Toast.superclass._init.apply(this,arguments);var a=this.options;this.element.css({minWidth:this._const.minWidth+"px"}),this.element.addClass("toast-"+a.level);var b=function(a){return a.stopPropagation(),a.stopEvent(),!1};this.element.bind({click:b,mousedown:b,mouseup:b,mouseover:b,mouseenter:b,mouseleave:b,mousemove:b}),this.text=BI.createWidget({type:"bi.label",element:this,text:a.text,height:30,hgap:this._const.hgap})},setWidth:function(a){this.element.width(a)},setText:function(a){this.text.setText(a)}}),BI.shortcut("bi.toast",BI.Toast),BI.Tooltip=BI.inherit(BI.Tip,{_const:{hgap:10},_defaultConfig:function(){return BI.extend(BI.Tooltip.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-tooltip",text:"",level:"success",stopEvent:!1,stopPropagation:!1,height:20})},_init:function(){BI.Tooltip.superclass._init.apply(this,arguments);var a=this.options;this.element.addClass("tooltip-"+a.level);var b=function(b){a.stopPropagation&&b.stopPropagation(),a.stopEvent&&b.stopEvent()};this.element.bind({click:b,mousedown:b,mouseup:b,mouseover:b,mouseenter:b,mouseleave:b,mousemove:b});var c=(a.text+"").split("\n");c.length>1?BI.createWidget({type:"bi.vertical",element:this,hgap:this._const.hgap,items:BI.map(c,function(a,b){return{type:"bi.label",textAlign:"left",whiteSpace:"normal",text:b,textHeight:16}})}):this.text=BI.createWidget({type:"bi.label",element:this,textAlign:"left",whiteSpace:"normal",text:a.text,textHeight:20,hgap:this._const.hgap})},setWidth:function(a){this.element.width(a-2*this._const.hgap)},setText:function(a){this.text&&this.text.setText(a)},setLevel:function(a){this.element.removeClass("tooltip-success").removeClass("tooltip-warning"),this.element.addClass("tooltip-"+a)}}),BI.shortcut("bi.tooltip",BI.Tooltip),BI.Trigger=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.Trigger.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-trigger cursor-pointer",height:24})},_init:function(){BI.Trigger.superclass._init.apply(this,arguments)},setKey:function(){},getKey:function(){}}),function(a){a(CodeMirror)}(function(a){function b(a){return"[object Array]"==Object.prototype.toString.call(a)}function c(b){var c=b.doc.modeOption;return"sql"===c&&(c="text/x-sql"),a.resolveMode(c).keywords}function d(b){var c=b.doc.modeOption;return"sql"===c&&(c="text/x-sql"),a.resolveMode(c).identifierQuote||"`"}function e(a){return"string"==typeof a?a:a.text}function f(a,c){return b(c)&&(c={columns:c}),c.text||(c.text=a),c}function g(a){var c={};if(b(a))for(var d=a.length-1;d>=0;d--){var g=a[d];c[e(g).toUpperCase()]=f(e(g),g)}else if(a)for(var h in a)c[h.toUpperCase()]=f(h,a[h]);return c}function h(a){return q[a.toUpperCase()]}function i(a){var b={};for(var c in a)a.hasOwnProperty(c)&&(b[c]=a[c]);return b}function j(a,b){if(BI.isNotEmptyString(a)&&b.length!==a.length){var c=a.length,d=e(b).substr(0,c);return a.toUpperCase()===d.toUpperCase()}}function k(a,c,d,e){if(b(d))for(var f=0;f0)&&w(m,i[n])<=0){j={start:l,end:i[n]};break}l=i[n]}for(var p=c.getRange(j.start,j.end,!1),n=0;nm.ch&&(o.end=m.ch,o.string=o.string.slice(0,m.ch-o.start)),o.string.match(/^[.`"\w@]\w*$/)?(x=o.string,u=o.start,w=o.end):(u=w=m.ch,x=""),"."==x.charAt(0)||x.charAt(0)==t?u=n(m,o,y,a):(k(y,x,q,function(a){return a}),k(y,x,r,function(a){return a}),f||k(y,x,s,function(a,b){var c=b47&&c.charCodeAt(0)<58)return a.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/),n.decimallessFloat&&a.match(/^\.(?!\.)/),"number";if("?"==c&&(a.eatSpace()||a.eol()||a.eat(";")))return"variable-3";if("'"==c||'"'==c&&n.doubleQuote)return b.tokenize=e(c),b.tokenize(a,b);if((n.nCharCast&&("n"==c||"N"==c)||n.charsetCast&&"_"==c&&a.match(/[a-z][a-z0-9]*/i))&&("'"==a.peek()||'"'==a.peek()))return"keyword";if(/^[\(\),\;\[\]]/.test(c))return null;if(n.commentSlashSlash&&"/"==c&&a.eat("/"))return a.skipToEnd(),"comment";if(n.commentHash&&"#"==c||"-"==c&&a.eat("-")&&(!n.commentSpaceRequired||a.eat(" ")))return a.skipToEnd(),"comment";if("/"==c&&a.eat("*"))return b.tokenize=f(1),b.tokenize(a,b);if("."!=c){if(m.test(c))return a.eatWhile(m),null;if("{"==c&&(a.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/)||a.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/)))return"number";a.eatWhile(/^[_\w\d]/);var g=a.current().toLowerCase();return p.hasOwnProperty(g)&&(a.match(/^( )+'[^']*'/)||a.match(/^( )+"[^"]*"/))?"number":j.hasOwnProperty(g)?"atom":k.hasOwnProperty(g)?"builtin":q.hasOwnProperty(g)&&"("===a.peek()?"function":l.hasOwnProperty(g)?"keyword":i.hasOwnProperty(g)?"string-2":null}return n.zerolessFloat&&a.match(/^(?:\d+(?:e[+-]?\d+)?)/i)?"number":a.match(/^\.+/)?null:n.ODBCdotTable&&a.match(/^[\w\d_]+/)?"variable-2":void 0}function e(a){return function(b,c){for(var e,f=!1;null!=(e=b.next());){if(e==a&&!f){c.tokenize=d;break}f=!f&&"\\"==e}return"string"}}function f(a){return function(b,c){var e=b.match(/^.*?(\/\*|\*\/)/);return e?"/*"==e[1]?c.tokenize=f(a+1):a>1?c.tokenize=f(a-1):c.tokenize=d:b.skipToEnd(),"comment"}}function g(a,b,c){b.context={prev:b.context,indent:a.indentation(),col:a.column(),type:c}}function h(a){a.indent=a.context.indent,a.context=a.context.prev}var i=c.client||{},j=c.atoms||{"false":!0,"true":!0,"null":!0},k=c.builtin||{},l=c.keywords||{},m=c.operatorChars||/^[*+\-%<>!=&|~^]/,n=c.support||{},o=c.hooks||{},p=c.dateSQL||{date:!0,time:!0,timestamp:!0},q=c.functions||{};return{startState:function(){return{tokenize:d,context:null}},token:function(a,b){if(a.sol()&&b.context&&null==b.context.align&&(b.context.align=!1),b.tokenize==d&&a.eatSpace())return null;var c=b.tokenize(a,b);if("comment"==c)return c;b.context&&null==b.context.align&&(b.context.align=!0);var e=a.current();return"("==e?g(a,b,")"):"["==e?g(a,b,"]"):b.context&&b.context.type==e&&h(b),c},indent:function(c,d){var e=c.context;if(!e)return a.Pass;var f=d.charAt(0)==e.type;return e.align?e.col+(f?0:1):e.indent+(f?0:b.indentUnit)},blockCommentStart:"/*",blockCommentEnd:"*/",lineComment:n.commentSlashSlash?"//":n.commentHash?"#":"--"}}),function(){function b(a){for(var b={},c=a.split(" "),d=0;d!=]/,dateSQL:b("date time timestamp"),support:b("ODBCdotTable doubleQuote binaryNumber hexNumber"),functions:BI.makeObject(BI.FormulaCollections,!0)})}()}),BI.SQLEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(),{baseCls:"bi-sql-editor",value:"",lineHeight:2,showHint:!0})},_init:function(){BI.CodeEditor.superclass._init.apply(this,arguments);var a=this.options,b=this;this.editor=CodeMirror(this.element[0],{mode:"text/x-sql",textWrapping:!0,lineWrapping:!0,lineNumbers:!1}),1===a.lineHeight?this.element.addClass("codemirror-low-line-height"):this.element.addClass("codemirror-high-line-height"),this.editor.on("change",function(c,d){b._checkWaterMark(),a.showHint&&CodeMirror.showHint(c,CodeMirror.sqlHint,{completeSingle:!1}),BI.nextTick(function(){b.fireEvent(BI.FormulaEditor.EVENT_CHANGE)})}),this.editor.on("focus",function(){b._checkWaterMark(),b.fireEvent(BI.FormulaEditor.EVENT_FOCUS)}),this.editor.on("blur",function(){b.fireEvent(BI.FormulaEditor.EVENT_BLUR)}),this.watermark=BI.createWidget({type:"bi.label",text:BI.i18nText("Please_Enter_SQL"),cls:"bi-water-mark",whiteSpace:"nowrap",textAlign:"left"}),this.watermark.element.bind("mousedown",function(a){b.insertString(""),b.editor.focus(),a.stopEvent()}),this.watermark.element.bind("click",function(a){b.editor.focus(),a.stopEvent()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.watermark,top:0,left:5}]}),BI.isKey(a.value)&&BI.nextTick(function(){b.setValue(a.value)})},insertString:function(a){this.editor.replaceSelection(a),this.editor.focus()},_checkWaterMark:function(){var a=this.options;!this.disabledWaterMark&&BI.isEmptyString(this.editor.getValue())&&BI.isKey(a.watermark)?this.watermark&&this.watermark.visible():this.watermark&&this.watermark.invisible()},getValue:function(){return this.editor.getValue()},setValue:function(a){this.editor.setValue(a)}}),BI.shortcut("bi.sql_editor",BI.SQLEditor),function(a,b){"function"==typeof define&&define.amd?define("eve",function(){return b()}):"object"==typeof exports?module.exports=b():a.eve=b()}(this,function(){var a,b,c="0.4.2",d="hasOwnProperty",e=/[\.\/]/,f="*",g=function(){},h=function(a,b){return a-b},i={n:{}},j=function(c,d){c=String(c);var e,f=b,g=Array.prototype.slice.call(arguments,2),i=j.listeners(c),k=0,l=[],m={},n=[],o=a;a=c,b=0;for(var p=0,q=i.length;p=1e3&&delete h[i.shift()],i.push(g),h[g]=a[C](b,f),c?c(h[g]):h[g])}return e}function f(){return this.hex}function g(a,b){for(var c=[],d=0,e=a.length;e-2*!b>d;d+=2){var f=[{x:+a[d-2],y:+a[d-1]},{x:+a[d],y:+a[d+1]},{x:+a[d+2],y:+a[d+3]},{x:+a[d+4],y:+a[d+5]}];b?d?e-4==d?f[3]={x:+a[0],y:+a[1]}:e-2==d&&(f[2]={x:+a[0],y:+a[1]},f[3]={x:+a[2],y:+a[3]}):f[0]={x:+a[e-2],y:+a[e-1]}:e-4==d?f[3]=f[2]:d||(f[0]={x:+a[d],y:+a[d+1]}),c.push(["C",(-f[0].x+6*f[1].x+f[2].x)/6,(-f[0].y+6*f[1].y+f[2].y)/6,(f[1].x+6*f[2].x-f[3].x)/6,(f[1].y+6*f[2].y-f[3].y)/6,f[2].x,f[2].y])}return c}function h(a,b,c,d,e){var f=-3*b+9*c-9*d+3*e,g=a*f+6*b-12*c+6*d;return a*g-3*b+3*c}function i(a,b,c,d,e,f,g,i,j){null==j&&(j=1),j=j>1?1:j<0?0:j;for(var k=j/2,l=12,m=[-.1252,.1252,-.3678,.3678,-.5873,.5873,-.7699,.7699,-.9041,.9041,-.9816,.9816],n=[.2491,.2491,.2335,.2335,.2032,.2032,.1601,.1601,.1069,.1069,.0472,.0472],o=0,p=0;po;)m/=2,n+=(kN(e,g)||N(b,d)N(f,h))){var i=(a*d-b*c)*(e-g)-(a-c)*(e*h-f*g),j=(a*d-b*c)*(f-h)-(b-d)*(e*h-f*g),k=(a-c)*(f-h)-(b-d)*(e-g);if(k){var l=i/k,m=j/k,n=+l.toFixed(2),o=+m.toFixed(2);if(!(n<+O(a,c).toFixed(2)||n>+N(a,c).toFixed(2)||n<+O(e,g).toFixed(2)||n>+N(e,g).toFixed(2)||o<+O(b,d).toFixed(2)||o>+N(b,d).toFixed(2)||o<+O(f,h).toFixed(2)||o>+N(f,h).toFixed(2)))return{x:l,y:m}}}}function l(a,c,d){var e=b.bezierBBox(a),f=b.bezierBBox(c);if(!b.isBBoxIntersect(e,f))return d?0:[];for(var g=i.apply(0,a),h=i.apply(0,c),j=N(~~(g/5),1),l=N(~~(h/5),1),m=[],n=[],o={},p=d?0:[],q=0;q=0&&A<=1.001&&B>=0&&B<=1.001&&(d?p++:p.push({x:z.x,y:z.y,t1:O(A,1),t2:O(B,1)}))}}return p}function m(a,c,d){a=b._path2curve(a),c=b._path2curve(c);for(var e,f,g,h,i,j,k,m,n,o,p=d?0:[],q=0,r=a.length;qd)return d;for(;cf?c=e:d=e,e=(d-c)/2+c}return e}var j=3*b,k=3*(d-b)-j,l=1-j-k,m=3*c,n=3*(e-c)-m,o=1-m-n;return h(a,1/(200*f))}function q(a,b){var c=[],d={};if(this.ms=b,this.times=1,a){for(var e in a)a[y](e)&&(d[$(e)]=a[e],c.push($(e)));c.sort(ka)}this.anim=d,this.top=c[c.length-1],this.percents=c}function r(c,d,e,f,g,h){e=$(e);var i,j,k,l,m,o,q=c.ms,r={},s={},t={};if(f)for(w=0,x=fb.length;wf*c.top){e=c.percents[w],m=c.percents[w-1]||0,q=q/c.top*(e-m),l=c.percents[w+1],i=c.anim[e];break}f&&d.attr(c.anim[c.percents[w]])}if(i){if(j)j.initstatus=f,j.start=new Date-j.ms*f;else{for(var z in i)if(i[y](z)&&(ca[y](z)||d.paper.customAttributes[y](z)))switch(r[z]=d.attr(z),null==r[z]&&(r[z]=ba[z]),s[z]=i[z],ca[z]){case S:t[z]=(s[z]-r[z])/q;break;case"colour":r[z]=b.getRGB(r[z]);var A=b.getRGB(s[z]);t[z]={r:(A.r-r[z].r)/q,g:(A.g-r[z].g)/q,b:(A.b-r[z].b)/q};break;case"path":var B=Ia(r[z],s[z]),C=B[1];for(r[z]=B[0],t[z]=[],w=0,x=r[z].length;w',qa=ra.firstChild,qa.style.behavior="url(#default#VML)",!qa||"object"!=typeof qa.adj)return b.type=F;ra=null}b.svg=!(b.vml="VML"==b.type),b._Paper=B,b.fn=u=B.prototype=b.prototype,b._id=0,b._oid=0,b.is=function(a,b){return b=L.call(b),"finite"==b?!X[y](+a):"array"==b?a instanceof Array:"null"==b&&null===a||b==typeof a&&null!==a||"object"==b&&a===Object(a)||"array"==b&&Array.isArray&&Array.isArray(a)||V.call(a).slice(8,-1).toLowerCase()==b},b.angle=function(a,c,d,e,f,g){if(null==f){var h=a-d,i=c-e;return h||i?(180+180*M.atan2(-i,-h)/R+360)%360:0}return b.angle(a,c,f,g)-b.angle(d,e,f,g)},b.rad=function(a){return a%360*R/180},b.deg=function(a){return Math.round(180*a/R%360*1e3)/1e3},b.snapTo=function(a,c,d){if(d=b.is(d,"finite")?d:10,b.is(a,U)){for(var e=a.length;e--;)if(P(a[e]-c)<=d)return a[e]}else{a=+a;var f=c%a;if(fa-d)return c-f+a}return c};b.createUUID=function(a,b){return function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(a,b).toUpperCase()}}(/[xy]/g,function(a){var b=16*M.random()|0,c="x"==a?b:3&b|8;return c.toString(16)});b.setWindow=function(c){a("raphael.setWindow",b,z.win,c),z.win=c,z.doc=z.win.document,b._engine.initWin&&b._engine.initWin(z.win)};var sa=function(a){if(b.vml){var c,d=/^\s+|\s+$/g;try{var f=new ActiveXObject("htmlfile");f.write(""),f.close(),c=f.body}catch(g){c=createPopup().document.body}var h=c.createTextRange();sa=e(function(a){try{c.style.color=H(a).replace(d,F);var b=h.queryCommandValue("ForeColor");return b=(255&b)<<16|65280&b|(16711680&b)>>>16,"#"+("000000"+b.toString(16)).slice(-6)}catch(e){return"none"}})}else{var i=z.doc.createElement("i");i.title="Raphaël Colour Picker",i.style.display="none",z.doc.body.appendChild(i),sa=e(function(a){return i.style.color=a,z.doc.defaultView.getComputedStyle(i,F).getPropertyValue("color")})}return sa(a)},ta=function(){return"hsb("+[this.h,this.s,this.b]+")"},ua=function(){return"hsl("+[this.h,this.s,this.l]+")"},va=function(){return this.hex},wa=function(a,c,d){if(null==c&&b.is(a,"object")&&"r"in a&&"g"in a&&"b"in a&&(d=a.b,c=a.g,a=a.r),null==c&&b.is(a,T)){var e=b.getRGB(a);a=e.r,c=e.g,d=e.b}return(a>1||c>1||d>1)&&(a/=255,c/=255,d/=255),[a,c,d]},xa=function(a,c,d,e){a*=255,c*=255,d*=255;var f={r:a,g:c,b:d,hex:b.rgb(a,c,d),toString:va};return b.is(e,"finite")&&(f.opacity=e),f};b.color=function(a){var c;return b.is(a,"object")&&"h"in a&&"s"in a&&"b"in a?(c=b.hsb2rgb(a),a.r=c.r,a.g=c.g,a.b=c.b,a.hex=c.hex):b.is(a,"object")&&"h"in a&&"s"in a&&"l"in a?(c=b.hsl2rgb(a),a.r=c.r,a.g=c.g,a.b=c.b,a.hex=c.hex):(b.is(a,"string")&&(a=b.getRGB(a)),b.is(a,"object")&&"r"in a&&"g"in a&&"b"in a?(c=b.rgb2hsl(a),a.h=c.h,a.s=c.s,a.l=c.l,c=b.rgb2hsb(a),a.v=c.b):(a={hex:"none"},a.r=a.g=a.b=a.h=a.s=a.v=a.l=-1)),a.toString=va,a},b.hsb2rgb=function(a,b,c,d){this.is(a,"object")&&"h"in a&&"s"in a&&"b"in a&&(c=a.b,b=a.s,d=a.o,a=a.h),a*=360;var e,f,g,h,i;return a=a%360/60,i=c*b,h=i*(1-P(a%2-1)),e=f=g=c-i,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a],xa(e,f,g,d)},b.hsl2rgb=function(a,b,c,d){this.is(a,"object")&&"h"in a&&"s"in a&&"l"in a&&(c=a.l,b=a.s,a=a.h),(a>1||b>1||c>1)&&(a/=360,b/=100,c/=100),a*=360;var e,f,g,h,i;return a=a%360/60,i=2*b*(c<.5?c:1-c),h=i*(1-P(a%2-1)),e=f=g=c-i/2,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a],xa(e,f,g,d)},b.rgb2hsb=function(a,b,c){c=wa(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g;return f=N(a,b,c),g=f-O(a,b,c),d=0==g?null:f==a?(b-c)/g:f==b?(c-a)/g+2:(a-b)/g+4,d=(d+360)%6*60/360,e=0==g?0:g/f,{h:d,s:e,b:f,toString:ta}},b.rgb2hsl=function(a,b,c){c=wa(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g,h,i;return g=N(a,b,c),h=O(a,b,c),i=g-h,d=0==i?null:g==a?(b-c)/i:g==b?(c-a)/i+2:(a-b)/i+4,d=(d+360)%6*60/360,f=(g+h)/2,e=0==i?0:f<.5?i/(2*f):i/(2-2*f),{h:d,s:e,l:f,toString:ua}},b._path2string=function(){return this.join(",").replace(fa,"$1")};b._preload=function(a,b){var c=z.doc.createElement("img");c.style.cssText="position:absolute;left:-9999em;top:-9999em",c.onload=function(){b.call(this),this.onload=null,z.doc.body.removeChild(this)},c.onerror=function(){z.doc.body.removeChild(this)},z.doc.body.appendChild(c),c.src=a};b.getRGB=e(function(a){if(!a||(a=H(a)).indexOf("-")+1)return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:f};if("none"==a)return{r:-1,g:-1,b:-1,hex:"none",toString:f};!(ea[y](a.toLowerCase().substring(0,2))||"#"==a.charAt())&&(a=sa(a));var c,d,e,g,h,i,j=a.match(W);return j?(j[2]&&(e=_(j[2].substring(5),16),d=_(j[2].substring(3,5),16),c=_(j[2].substring(1,3),16)),j[3]&&(e=_((h=j[3].charAt(3))+h,16),d=_((h=j[3].charAt(2))+h,16),c=_((h=j[3].charAt(1))+h,16)),j[4]&&(i=j[4][I](da),c=$(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=$(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),e=$(i[2]),"%"==i[2].slice(-1)&&(e*=2.55),"rgba"==j[1].toLowerCase().slice(0,4)&&(g=$(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100)),j[5]?(i=j[5][I](da),c=$(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=$(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),e=$(i[2]),"%"==i[2].slice(-1)&&(e*=2.55),("deg"==i[0].slice(-3)||"°"==i[0].slice(-1))&&(c/=360),"hsba"==j[1].toLowerCase().slice(0,4)&&(g=$(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100),b.hsb2rgb(c,d,e,g)):j[6]?(i=j[6][I](da),c=$(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=$(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),e=$(i[2]),"%"==i[2].slice(-1)&&(e*=2.55),("deg"==i[0].slice(-3)||"°"==i[0].slice(-1))&&(c/=360),"hsla"==j[1].toLowerCase().slice(0,4)&&(g=$(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100),b.hsl2rgb(c,d,e,g)):(j={r:c,g:d,b:e,toString:f},j.hex="#"+(16777216|e|d<<8|c<<16).toString(16).slice(1),b.is(g,"finite")&&(j.opacity=g),j)):{r:-1,g:-1,b:-1,hex:"none",error:1,toString:f}},b),b.hsb=e(function(a,c,d){return b.hsb2rgb(a,c,d).hex}),b.hsl=e(function(a,c,d){return b.hsl2rgb(a,c,d).hex}),b.rgb=e(function(a,b,c){function d(a){return a+.5|0}return"#"+(16777216|d(c)|d(b)<<8|d(a)<<16).toString(16).slice(1)}),b.getColor=function(a){var b=this.getColor.start=this.getColor.start||{h:0,s:1,b:a||.75},c=this.hsb2rgb(b.h,b.s,b.b);return b.h+=.075,b.h>1&&(b.h=0,b.s-=.2,b.s<=0&&(this.getColor.start={h:0,s:1,b:b.b})),c.hex},b.getColor.reset=function(){delete this.start},b.parsePathString=function(a){if(!a)return null;var c=ya(a);if(c.arr)return Aa(c.arr);var d={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},e=[];return b.is(a,U)&&b.is(a[0],U)&&(e=Aa(a)),e.length||H(a).replace(ga,function(a,b,c){var f=[],g=b.toLowerCase();if(c.replace(ia,function(a,b){b&&f.push(+b)}),"m"==g&&f.length>2&&(e.push([b][D](f.splice(0,2))),g="l",b="m"==b?"l":"L"),"r"==g)e.push([b][D](f));else for(;f.length>=d[g]&&(e.push([b][D](f.splice(0,d[g]))),d[g]););}),e.toString=b._path2string,c.arr=Aa(e),e},b.parseTransformString=e(function(a){if(!a)return null;var c=[];return b.is(a,U)&&b.is(a[0],U)&&(c=Aa(a)),c.length||H(a).replace(ha,function(a,b,d){var e=[];L.call(b);d.replace(ia,function(a,b){b&&e.push(+b)}),c.push([b][D](e))}),c.toString=b._path2string,c});var ya=function(a){var b=ya.ps=ya.ps||{};return b[a]?b[a].sleep=100:b[a]={sleep:100},setTimeout(function(){for(var c in b)b[y](c)&&c!=a&&(b[c].sleep--,!b[c].sleep&&delete b[c])}),b[a]};b.findDotsAtSegment=function(a,b,c,d,e,f,g,h,i){var j=1-i,k=Q(j,3),l=Q(j,2),m=i*i,n=m*i,o=k*a+3*l*i*c+3*j*i*i*e+n*g,p=k*b+3*l*i*d+3*j*i*i*f+n*h,q=a+2*i*(c-a)+m*(e-2*c+a),r=b+2*i*(d-b)+m*(f-2*d+b),s=c+2*i*(e-c)+m*(g-2*e+c),t=d+2*i*(f-d)+m*(h-2*f+d),u=j*a+i*c,v=j*b+i*d,w=j*e+i*g,x=j*f+i*h,y=90-180*M.atan2(q-s,r-t)/R;return(q>s||r=a.x&&b<=a.x2&&c>=a.y&&c<=a.y2},b.isBBoxIntersect=function(a,c){var d=b.isPointInsideBBox;return d(c,a.x,a.y)||d(c,a.x2,a.y)||d(c,a.x,a.y2)||d(c,a.x2,a.y2)||d(a,c.x,c.y)||d(a,c.x2,c.y)||d(a,c.x,c.y2)||d(a,c.x2,c.y2)||(a.xc.x||c.xa.x)&&(a.yc.y||c.ya.y)},b.pathIntersection=function(a,b){return m(a,b)},b.pathIntersectionNumber=function(a,b){return m(a,b,1)},b.isPointInsidePath=function(a,c,d){var e=b.pathBBox(a);return b.isPointInsideBBox(e,c,d)&&m(a,[["M",c,d],["H",e.x2+10]],1)%2==1},b._removedFactory=function(b){return function(){a("raphael.log",null,"Raphaël: you are calling to method “"+b+"” of removed object",b)}};var za=b.pathBBox=function(a){var b=ya(a);if(b.bbox)return c(b.bbox);if(!a)return{x:0,y:0,width:0,height:0,x2:0,y2:0};a=Ia(a);for(var d,e=0,f=0,g=[],h=[],i=0,j=a.length;i1&&(s=M.sqrt(s),c=s*c,d=s*d);var t=c*c,u=d*d,v=(g==h?-1:1)*M.sqrt(P((t*u-t*r*r-u*q*q)/(t*r*r+u*q*q))),w=v*c*r/d+(a+i)/2,x=v*-d*q/c+(b+j)/2,y=M.asin(((b-x)/d).toFixed(9)),z=M.asin(((j-x)/d).toFixed(9));y=az&&(y-=2*R),!h&&z>y&&(z-=2*R)}var A=z-y;if(P(A)>m){var B=z,C=i,E=j;z=y+m*(h&&z>y?1:-1),i=w+c*M.cos(z),j=x+d*M.sin(z),o=Fa(i,j,c,d,f,0,h,C,E,[z,B,w,x])}A=z-y;var F=M.cos(y),G=M.sin(y),H=M.cos(z),J=M.sin(z),K=M.tan(A/4),L=4/3*c*K,N=4/3*d*K,O=[a,b],Q=[a+L*G,b-N*F],S=[i+L*J,j-N*H],T=[i,j];if(Q[0]=2*O[0]-Q[0],Q[1]=2*O[1]-Q[1],k)return[Q,S,T][D](o);o=[Q,S,T][D](o).join()[I](",");for(var U=[],V=0,W=o.length;V"1e12"&&(m=.5),P(n)>"1e12"&&(n=.5),m>0&&m<1&&(i=Ga(a,b,c,d,e,f,g,h,m),p.push(i.x),o.push(i.y)),n>0&&n<1&&(i=Ga(a,b,c,d,e,f,g,h,n),p.push(i.x),o.push(i.y)),j=f-2*d+b-(h-2*f+d),k=2*(d-b)-2*(f-d),l=b-d,m=(-k+M.sqrt(k*k-4*j*l))/2/j,n=(-k-M.sqrt(k*k-4*j*l))/2/j,P(m)>"1e12"&&(m=.5),P(n)>"1e12"&&(n=.5),m>0&&m<1&&(i=Ga(a,b,c,d,e,f,g,h,m),p.push(i.x),o.push(i.y)),n>0&&n<1&&(i=Ga(a,b,c,d,e,f,g,h,n),p.push(i.x),o.push(i.y)),{min:{x:O[C](0,p),y:O[C](0,o)},max:{x:N[C](0,p),y:N[C](0,o)}}}),Ia=b._path2curve=e(function(a,b){var c=!b&&ya(a);if(!b&&c.curve)return Aa(c.curve);for(var d=Ca(a),e=b&&Ca(b),f={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},g={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},h=(function(a,b,c){var d,e,f={T:1,Q:1};if(!a)return["C",b.x,b.y,b.x,b.y,b.x,b.y];switch(!(a[0]in f)&&(b.qx=b.qy=null),a[0]){case"M":b.X=a[1],b.Y=a[2];break;case"A":a=["C"][D](Fa[C](0,[b.x,b.y][D](a.slice(1))));break;case"S":"C"==c||"S"==c?(d=2*b.x-b.bx,e=2*b.y-b.by):(d=b.x,e=b.y),a=["C",d,e][D](a.slice(1));break;case"T":"Q"==c||"T"==c?(b.qx=2*b.x-b.qx,b.qy=2*b.y-b.qy):(b.qx=b.x,b.qy=b.y),a=["C"][D](Ea(b.x,b.y,b.qx,b.qy,a[1],a[2]));break;case"Q":b.qx=a[1],b.qy=a[2],a=["C"][D](Ea(b.x,b.y,a[1],a[2],a[3],a[4]));break;case"L":a=["C"][D](Da(b.x,b.y,a[1],a[2]));break;case"H":a=["C"][D](Da(b.x,b.y,a[1],b.y));break;case"V":a=["C"][D](Da(b.x,b.y,b.x,a[1]));break;case"Z":a=["C"][D](Da(b.x,b.y,b.X,b.Y))}return a}),i=function(a,b){if(a[b].length>7){a[b].shift();for(var c=a[b];c.length;)k[b]="A",e&&(l[b]="A"),a.splice(b++,0,["C"][D](c.splice(0,6)));a.splice(b,1),p=N(d.length,e&&e.length||0)}},j=function(a,b,c,f,g){a&&b&&"M"==a[g][0]&&"M"!=b[g][0]&&(b.splice(g,0,["M",f.x,f.y]),c.bx=0,c.by=0,c.x=a[g][1],c.y=a[g][2],p=N(d.length,e&&e.length||0))},k=[],l=[],m="",n="",o=0,p=N(d.length,e&&e.length||0);oe){if(c&&!m.start){if(k=_a(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n),l+=["C"+k.start.x,k.start.y,k.m.x,k.m.y,k.x,k.y],f)return l;m.start=l,l=["M"+k.x,k.y+"C"+k.n.x,k.n.y,k.end.x,k.end.y,i[5],i[6]].join(),n+=j,g=+i[5],h=+i[6];continue}if(!a&&!c)return k=_a(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n),{x:k.x,y:k.y,alpha:k.alpha}}n+=j,g=+i[5],h=+i[6]}l+=i.shift()+i}return m.end=l,k=a?n:c?m:b.findDotsAtSegment(g,h,i[0],i[1],i[2],i[3],i[4],i[5],1),k.alpha&&(k={x:k.x,y:k.y,alpha:k.alpha}),k}},bb=ab(1),cb=ab(),db=ab(0,1);b.getTotalLength=bb,b.getPointAtLength=cb,b.getSubpath=function(a,b,c){if(this.getTotalLength(a)-c<1e-6)return db(a,b).end;var d=db(a,c,1);return b?db(d,b).end:d},Xa.getTotalLength=function(){var a=this.getPath();if(a)return this.node.getTotalLength?this.node.getTotalLength():bb(a)},Xa.getPointAtLength=function(a){var b=this.getPath();if(b)return cb(b,a)},Xa.getPath=function(){var a,c=b._getPath[this.type];if("text"!=this.type&&"set"!=this.type)return c&&(a=c(this)),a},Xa.getSubpath=function(a,c){var d=this.getPath();if(d)return b.getSubpath(d,a,c)};var eb=b.easing_formulas={linear:function(a){return a},"<":function(a){return Q(a,1.7)},">":function(a){return Q(a,.48)},"<>":function(a){var b=.48-a/1.04,c=M.sqrt(.1734+b*b),d=c-b,e=Q(P(d),1/3)*(d<0?-1:1),f=-c-b,g=Q(P(f),1/3)*(f<0?-1:1),h=e+g+.5;return 3*(1-h)*h*h+h*h*h},backIn:function(a){var b=1.70158;return a*a*((b+1)*a-b)},backOut:function(a){a-=1;var b=1.70158;return a*a*((b+1)*a+b)+1},elastic:function(a){return a==!!a?a:Q(2,-10*a)*M.sin((a-.075)*(2*R)/.3)+1},bounce:function(a){var b,c=7.5625,d=2.75;return a<1/d?b=c*a*a:a<2/d?(a-=1.5/d,b=c*a*a+.75):a<2.5/d?(a-=2.25/d,b=c*a*a+.9375):(a-=2.625/d,b=c*a*a+.984375),b}};eb.easeIn=eb["ease-in"]=eb["<"],eb.easeOut=eb["ease-out"]=eb[">"],eb.easeInOut=eb["ease-in-out"]=eb["<>"],eb["back-in"]=eb.backIn,eb["back-out"]=eb.backOut;var fb=[],gb=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,16)},hb=function(){for(var c=+new Date,d=0;d1&&!e.next){for(g in m)m[y](g)&&(p[g]=e.totalOrigin[g]);e.el.attr(p),r(e.anim,e.el,e.anim.percents[0],null,e.totalOrigin,e.repeat-1)}e.next&&!e.stop&&r(e.anim,e.el,e.next,null,e.totalOrigin,e.repeat)}}}fb.length&&gb(hb)},ib=function(a){return a>255?255:a<0?0:a};Xa.animateWith=function(a,c,d,e,f,g){var h=this;if(h.removed)return g&&g.call(h),h;var i=d instanceof q?d:b.animation(d,e,f,g);r(i,h,i.percents[0],null,h.attr());for(var j=0,k=fb.length;ji&&(i=k)}i+="%",!a[i].callback&&(a[i].callback=e)}return new q(a,c)},Xa.animate=function(a,c,d,e){var f=this;if(f.removed)return e&&e.call(f),f;var g=a instanceof q?a:b.animation(a,c,d,e);return r(g,f,g.percents[0],null,f.attr()),f},Xa.setTime=function(a,b){return a&&null!=b&&this.status(a,O(b,a.ms)/a.ms),this},Xa.status=function(a,b){var c,d,e=[],f=0;if(null!=b)return r(a,this,-1,O(b,1)),this;for(c=fb.length;f.5)-1;i(m-.5,2)+i(n-.5,2)>.25&&(n=f.sqrt(.25-i(m-.5,2))*e+.5)&&.5!=n&&(n=n.toFixed(5)-1e-5*e)}return l}),e=e.split(/\s*\-\s*/),"linear"==j){var t=e.shift();if(t=-d(t),isNaN(t))return null;var u=[0,0,f.cos(a.rad(t)),f.sin(a.rad(t))],v=1/(g(h(u[2]),h(u[3]))||1);u[2]*=v,u[3]*=v,u[2]<0&&(u[0]=-u[2],u[2]=0),u[3]<0&&(u[1]=-u[3],u[3]=0)}var w=a._parseDots(e);if(!w)return null;if(k=k.replace(/[\(\)\s,\xb0#]/g,"_"),b.gradient&&k!=b.gradient.id&&(p.defs.removeChild(b.gradient),delete b.gradient),!b.gradient){s=q(j+"Gradient",{id:k}),b.gradient=s,q(s,"radial"==j?{fx:m,fy:n}:{x1:u[0],y1:u[1],x2:u[2],y2:u[3],gradientTransform:b.matrix.invert()}),p.defs.appendChild(s);for(var x=0,y=w.length;x1?H.opacity/100:H.opacity});case"stroke":H=a.getRGB(p),i.setAttribute(o,H.hex),"stroke"==o&&H[b]("opacity")&&q(i,{"stroke-opacity":H.opacity>1?H.opacity/100:H.opacity}),"stroke"==o&&d._.arrows&&("startString"in d._.arrows&&t(d,d._.arrows.startString),"endString"in d._.arrows&&t(d,d._.arrows.endString,1));break;case"gradient":("circle"==d.type||"ellipse"==d.type||"r"!=c(p).charAt())&&r(d,p);break;case"opacity":k.gradient&&!k[b]("stroke-opacity")&&q(i,{"stroke-opacity":p>1?p/100:p});case"fill-opacity":if(k.gradient){I=a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g,l)),I&&(J=I.getElementsByTagName("stop"),q(J[J.length-1],{"stop-opacity":p}));break}default:"font-size"==o&&(p=e(p,10)+"px");var K=o.replace(/(\-.)/g,function(a){return a.substring(1).toUpperCase()});i.style[K]=p,d._.dirty=1,i.setAttribute(o,p)}}y(d,f),i.style.visibility=m},x=1.2,y=function(d,f){if("text"==d.type&&(f[b]("text")||f[b]("font")||f[b]("font-size")||f[b]("x")||f[b]("y"))){var g=d.attrs,h=d.node,i=h.firstChild?e(a._g.doc.defaultView.getComputedStyle(h.firstChild,l).getPropertyValue("font-size"),10):10;if(f[b]("text")){for(g.text=f.text;h.firstChild;)h.removeChild(h.firstChild);for(var j,k=c(f.text).split("\n"),m=[],n=0,o=k.length;n"));var X=U.getBoundingClientRect();s.W=m.w=(X.right-X.left)/V,s.H=m.h=(X.bottom-X.top)/V,s.X=m.x,s.Y=m.y+s.H/2,("x"in i||"y"in i)&&(s.path.v=a.format("m{0},{1}l{2},{1}",f(m.x*u),f(m.y*u),f(m.x*u)+1));for(var Y=["x","y","text","font","font-family","font-weight","font-style","font-size"],Z=0,$=Y.length;Z<$;Z++)if(Y[Z]in i){s._.dirty=1;break}switch(m["text-anchor"]){case"start":s.textpath.style["v-text-align"]="left",s.bbx=s.W/2;break;case"end":s.textpath.style["v-text-align"]="right",s.bbx=-s.W/2;break;default:s.textpath.style["v-text-align"]="center",s.bbx=0}s.textpath.style["v-text-kern"]=!0}},C=function(b,f,g){b.attrs=b.attrs||{};var h=(b.attrs,Math.pow),i="linear",j=".5 .5";if(b.attrs.gradient=f,f=c(f).replace(a._radial_gradient,function(a,b,c){return i="radial",b&&c&&(b=d(b),c=d(c),h(b-.5,2)+h(c-.5,2)>.25&&(c=e.sqrt(.25-h(b-.5,2))*(2*(c>.5)-1)+.5),j=b+n+c),o}),f=f.split(/\s*\-\s*/),"linear"==i){var k=f.shift();if(k=-d(k),isNaN(k))return null}var l=a._parseDots(f);if(!l)return null;if(b=b.shape||b.node,l.length){b.removeChild(g),g.on=!0,g.method="none",g.color=l[0].color,g.color2=l[l.length-1].color;for(var m=[],p=0,q=l.length;p')}}catch(c){F=function(a){return b.createElement("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}},a._engine.initWin(a._g.win),a._engine.create=function(){var b=a._getContainer.apply(0,arguments),c=b.container,d=b.height,e=b.width,f=b.x,g=b.y;if(!c)throw new Error("VML container not found.");var h=new a._Paper,i=h.canvas=a._g.doc.createElement("div"),j=i.style;return f=f||0,g=g||0,e=e||512,d=d||342,h.width=e,h.height=d,e==+e&&(e+="px"),d==+d&&(d+="px"),h.coordsize=1e3*u+n+1e3*u,h.coordorigin="0 0",h.span=a._g.doc.createElement("span"),h.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;",i.appendChild(h.span),j.cssText=a.format("top:0;left:0;display:inline-block;position:absolute;clip:rect(0 {0} {1} 0);",e,d),1==c?(a._g.doc.body.appendChild(i),j.left=f+"px",j.top=g+"px",j.position="absolute"):c.firstChild?c.insertBefore(i,c.firstChild):c.appendChild(i),h.renderfix=function(){},h},a.prototype.clear=function(){a.eve("raphael.clear",this),this.canvas.innerHTML=o,this.span=a._g.doc.createElement("span"),this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;",this.canvas.appendChild(this.span),this.bottom=this.top=null},a.prototype.remove=function(){a.eve("raphael.remove",this),this.canvas.parentNode.removeChild(this.canvas);for(var b in this)this[b]="function"==typeof this[b]?a._removedFactory(b):null;return!0};var G=a.st;for(var H in E)E[b](H)&&!G[b](H)&&(G[H]=function(a){return function(){var b=arguments;return this.forEach(function(c){c[a].apply(c,b)})}}(H))}}),function(a,b){if("function"==typeof define&&define.amd)define("raphael",["raphael.core","raphael.svg","raphael.vml"],function(a){return b(a)});else if("object"==typeof exports){var c=require("raphael.core");require("raphael.svg"),require("raphael.vml"),module.exports=b(c)}}(this,function(a){return a.ninja()}),BI.Svg=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.Svg.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-svg"})},_init:function(){BI.Svg.superclass._init.apply(this,arguments),this.paper=Raphael(this.element[0]),this.element.css("overflow","hidden"),$(this.paper.canvas).width("100%").height("100%").css({left:"0",top:"0"}).appendTo(this.element),this.top=this.paper.top,this.bottom=this.paper.bottom,this.customAttributes=this.paper.customAttributes,this.ca=this.paper.ca,this.raphael=this.paper.raphael},add:function(){return this.paper.add.apply(this.paper,arguments)},path:function(){return this.paper.path.apply(this.paper,arguments)},image:function(){return this.paper.image.apply(this.paper,arguments)},rect:function(){return this.paper.rect.apply(this.paper,arguments)},circle:function(){return this.paper.circle.apply(this.paper,arguments)},ellipse:function(){return this.paper.ellipse.apply(this.paper,arguments)},text:function(){return this.paper.text.apply(this.paper,arguments)},print:function(){return this.paper.print.apply(this.paper,arguments)},setStart:function(){return this.paper.setStart.apply(this.paper,arguments)},setFinish:function(){return this.paper.setFinish.apply(this.paper,arguments)},setSize:function(){return this.paper.setSize.apply(this.paper,arguments)},setViewBox:function(){return this.paper.setViewBox.apply(this.paper,arguments)},getById:function(){return this.paper.getById.apply(this.paper,arguments)},getElementByPoint:function(){return this.paper.getElementByPoint.apply(this.paper,arguments)},getElementsByPoint:function(){return this.paper.getElementsByPoint.apply(this.paper,arguments)},getFont:function(){return this.paper.getFont.apply(this.paper,arguments)},set:function(){return this.paper.set.apply(this.paper,arguments)},remove:function(){return this.paper.remove.apply(this.paper,arguments)},clear:function(){return this.paper.clear.apply(this.paper,arguments)}}),BI.shortcut("bi.svg",BI.Svg),BI.NativeTableScrollbar=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.NativeTableScrollbar.superclass._defaultConfig.apply(this,arguments),{attributes:{tabIndex:0},contentSize:0,defaultPosition:0,position:0,size:0})},render:function(){var a=this;this.options;this.element.width(36);var b=BI.throttle(function(){a.fireEvent(BI.NativeTableScrollbar.EVENT_SCROLL,a.element.scrollTop())},150,{leading:!1});return this.element.scroll(function(){b()}),{type:"bi.default",scrolly:!0,items:[{type:"bi.layout",width:1,ref:function(b){a.inner=b}}]}},mounted:function(){this._populate()},_populate:function(){var a=this.options;if(a.size<1||a.contentSize<=a.size)return void this.setVisible(!1);this.setVisible(!0);try{this.element.scrollTop(a.position)}catch(b){}this.inner.element.height(a.contentSize)},setContentSize:function(a){this.options.contentSize=a},setPosition:function(a){this.options.position=a},setSize:function(a){this.setHeight(a),this.options.size=a},populate:function(){this._populate()}}),BI.NativeTableScrollbar.EVENT_SCROLL="EVENT_SCROLL",BI.shortcut("bi.native_table_scrollbar",BI.NativeTableScrollbar),BI.NativeTableHorizontalScrollbar=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.NativeTableHorizontalScrollbar.superclass._defaultConfig.apply(this,arguments),{attributes:{tabIndex:0},contentSize:0,position:0,size:0})},render:function(){var a=this;this.options;this.element.height(36);var b=BI.throttle(function(){a.fireEvent(BI.NativeTableScrollbar.EVENT_SCROLL,a.element.scrollLeft())},150,{leading:!1});return this.element.scroll(function(){b()}),{type:"bi.default",scrollx:!0,items:[{type:"bi.layout",height:1,ref:function(b){a.inner=b}}]}},setContentSize:function(a){this.options.contentSize=a},setPosition:function(a){this.options.position=a},setSize:function(a){this.setWidth(a),this.options.size=a},_populate:function(){var a=this.options;if(a.size<1||a.contentSize<=a.size)return void this.setVisible(!1);this.setVisible(!0);try{this.element.scrollLeft(a.position)}catch(b){}this.inner.element.width(a.contentSize)},populate:function(){this._populate()}}),BI.NativeTableHorizontalScrollbar.EVENT_SCROLL="EVENT_SCROLL",BI.shortcut("bi.native_table_horizontal_scrollbar",BI.NativeTableHorizontalScrollbar),BI.TableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.TableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-table-cell",textAlign:"left",text:""})},_init:function(){BI.TableCell.superclass._init.apply(this,arguments),BI.createWidget({type:"bi.label",element:this,whiteSpace:"nowrap",textAlign:this.options.textAlign,height:this.options.height,text:this.options.text,value:this.options.value,lgap:5})}}),BI.shortcut("bi.table_cell",BI.TableCell),BI.CollectionTableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.CollectionTableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-collection-table-cell bi-border-right bi-border-bottom",width:0,height:0,_left:0,_top:0,cell:{}})},_init:function(){BI.CollectionTableCell.superclass._init.apply(this,arguments);var a=this.options;this.cell=BI.createWidget(BI.extend({type:"bi.label"},a.cell,{cls:(a.cell.cls||"")+" collection-table-cell-wrapper",width:a.width-(0===a._left?1:0)-1,height:a.height-(0===a._top?1:0)-1})),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.cell,left:0,right:0,top:0,bottom:0}]})},setWidth:function(a){BI.CollectionTableCell.superclass.setWidth.apply(this,arguments);var b=this.options;this.cell.setWidth(b.width-(0===b._left?1:0)-1)},setHeight:function(a){BI.CollectionTableCell.superclass.setHeight.apply(this,arguments);var b=this.options;this.cell.setHeight(b.height-(0===b._top?1:0)-1)}}),BI.shortcut("bi.collection_table_cell",BI.CollectionTableCell),BI.CollectionTable=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.CollectionTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-collection-table",headerRowSize:25,rowSize:25,columnSize:[],isNeedFreeze:!1,freezeCols:[],isNeedMerge:!1,mergeCols:[],mergeRule:BI.emptyFn,header:[],items:[],regionColumnSize:[]})},render:function(){var a=this,b=this.options;this._width=0,this._height=0,this._scrollBarSize=BI.DOM.getScrollWidth(),this.topLeftCollection=BI.createWidget({type:"bi.collection_view",cellSizeAndPositionGetter:function(b){return a.topLeftItems[b]}}),this.topLeftCollection.on(BI.CollectionView.EVENT_SCROLL,function(b){a.bottomLeftCollection.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.topRightCollection=BI.createWidget({type:"bi.collection_view",cellSizeAndPositionGetter:function(b){return a.topRightItems[b]}}),this.topRightCollection.on(BI.CollectionView.EVENT_SCROLL,function(b){a.bottomRightCollection.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.bottomLeftCollection=BI.createWidget({type:"bi.collection_view",cellSizeAndPositionGetter:function(b){return a.bottomLeftItems[b]}}),this.bottomLeftCollection.on(BI.CollectionView.EVENT_SCROLL,function(b){a.bottomRightCollection.setScrollTop(b.scrollTop),a.topLeftCollection.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.bottomRightCollection=BI.createWidget({type:"bi.collection_view",cellSizeAndPositionGetter:function(b){return a.bottomRightItems[b]}}),this.bottomRightCollection.on(BI.CollectionView.EVENT_SCROLL,function(b){a.bottomLeftCollection.setScrollTop(b.scrollTop),a.topRightCollection.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.topLeft=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.topLeftCollection]}),this.topRight=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.topRightCollection]}),this.bottomLeft=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.bottomLeftCollection]}),this.bottomRight=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.bottomRightCollection]}),this.contextLayout=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.topLeft,top:0,left:0},{el:this.topRight,top:0},{el:this.bottomLeft,left:0},{el:this.bottomRight}]}),this.topScrollbar=BI.createWidget({type:"bi.grid_table_scrollbar",width:BI.GridTableScrollbar.SIZE}),this.topScrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(b){a.bottomLeftCollection.setScrollTop(b),a.bottomRightCollection.setScrollTop(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.leftScrollbar=BI.createWidget({type:"bi.grid_table_horizontal_scrollbar",height:BI.GridTableScrollbar.SIZE}),this.leftScrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(b){a.topLeftCollection.setScrollLeft(b),a.bottomLeftCollection.setScrollLeft(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.rightScrollbar=BI.createWidget({type:"bi.grid_table_horizontal_scrollbar",height:BI.GridTableScrollbar.SIZE}),this.rightScrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(b){a.topRightCollection.setScrollLeft(b),a.bottomRightCollection.setScrollLeft(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.scrollBarLayout=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.topScrollbar,right:0,top:0},{el:this.leftScrollbar,left:0},{el:this.rightScrollbar}]}),this._width=b.width-BI.GridTableScrollbar.SIZE,this._height=b.height-BI.GridTableScrollbar.SIZE},mounted:function(){var a=this.options;(a.items.length>0||a.header.length>0)&&(this._digest(),this._populate())},_getFreezeColLength:function(){var a=this.options;return a.isNeedFreeze===!0?BI.clamp(a.freezeCols.length,0,a.columnSize.length):0},_getFreezeHeaderHeight:function(){var a=this.options;return a.header.length*a.headerRowSize>=this._height?0:a.header.length*a.headerRowSize},_getActualItems:function(){var a=this.options;return a.header.length*a.headerRowSize>=this._height?a.header.concat(a.items):a.items},_populateScrollbar:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[];BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g}),this.topScrollbar.setContentSize(this._getActualItems().length*a.rowSize),this.topScrollbar.setSize(this._height-this._getFreezeHeaderHeight()),this.topScrollbar.setPosition(this.bottomRightCollection.getScrollTop()),this.topScrollbar.populate(),this.leftScrollbar.setContentSize(c),this.leftScrollbar.setSize(b),this.leftScrollbar.setPosition(this.bottomLeftCollection.getScrollLeft()),this.leftScrollbar.populate(),this.rightScrollbar.setContentSize(d),this.rightScrollbar.setSize(this._width-b),this.rightScrollbar.setPosition(this.bottomRightCollection.getScrollLeft()),this.rightScrollbar.populate();var g=this.scrollBarLayout.attr("items");g[0].top=this._getFreezeHeaderHeight(),g[1].top=this._height,g[2].top=this._height,g[2].left=b,this.scrollBarLayout.attr("items",g),this.scrollBarLayout.resize()},_populateTable:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[];BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g});var g=b,h=this._getFreezeHeaderHeight(),i=this._width-b,j=this._getFreezeHeaderHeight(),k=b,l=this._height-h,m=this._width-b,n=this._height-j,o=g+this._scrollBarSize,p=h+this._scrollBarSize,q=i+this._scrollBarSize,r=j+this._scrollBarSize,s=k+this._scrollBarSize,t=l+this._scrollBarSize,u=m+this._scrollBarSize,v=n+this._scrollBarSize,w=function(a){a.element.css({overflow:"scroll",overflowX:"scroll",overflowY:"scroll"})};this.topLeft.setWidth(g),this.topLeft.setHeight(h),this.topRight.setWidth(i),this.topRight.setHeight(j),this.bottomLeft.setWidth(k),this.bottomLeft.setHeight(l),this.bottomRight.setWidth(m),this.bottomRight.setHeight(n),this.topLeftCollection.setWidth(o),this.topLeftCollection.setHeight(p),this.topRightCollection.setWidth(q),this.topRightCollection.setHeight(r),this.bottomLeftCollection.setWidth(s),this.bottomLeftCollection.setHeight(t),this.bottomRightCollection.setWidth(u),this.bottomRightCollection.setHeight(v),w(this.topLeftCollection),w(this.topRightCollection),w(this.bottomLeftCollection),w(this.bottomRightCollection);var x=this.contextLayout.attr("items");x[1].left=b,x[2].top=this._getFreezeHeaderHeight(),x[3].left=b,x[3].top=this._getFreezeHeaderHeight(),this.contextLayout.attr("items",x),this.contextLayout.resize();var y=[],z=[],A=[],B=[],C=function(a,b,c){BI.each(a,function(a,d){var e={type:"bi.collection_table_cell", -cell:b[d.row][d.col]};c.push(e)})};C(this.topLeftItems,a.header,y),C(this.topRightItems,a.header,z),C(this.bottomLeftItems,this._getActualItems(),A),C(this.bottomRightItems,this._getActualItems(),B),this.topLeftCollection._populate(y),this.topRightCollection._populate(z),this.bottomLeftCollection._populate(A),this.bottomRightCollection._populate(B)},_digest:function(){var a=this.options,b=this._getFreezeColLength();this._getFreezeHeaderHeight()<=0?(this.topLeftItems=[],this.topRightItems=[],this.bottomLeftItems=this._serialize(this._getActualItems(),0,b,a.rowSize,a.columnSize,a.mergeCols,BI.range(a.header.length)),this.bottomRightItems=this._serialize(this._getActualItems(),b,a.columnSize.length,a.rowSize,a.columnSize,a.mergeCols,BI.range(a.header.length))):(this.topLeftItems=this._serialize(a.header,0,b,a.headerRowSize,a.columnSize,a.mergeCols),this.topRightItems=this._serialize(a.header,b,a.columnSize.length,a.headerRowSize,a.columnSize,!0),this.bottomLeftItems=this._serialize(a.items,0,b,a.rowSize,a.columnSize,a.mergeCols),this.bottomRightItems=this._serialize(a.items,b,a.columnSize.length,a.rowSize,a.columnSize,a.mergeCols))},_serialize:function(a,b,c,d,e,f,g){f=f||[],g=g||[];for(var h=this.options,i=[],j={},k={},l={},m={},n=[],o=b;o-1||g===!0||g.indexOf(a)>-1)if(0===a&&e===b)r(0,b);else if(e===b&&a>0){var i=h.mergeRule(j[a][e],j[a-1][e]);i===!0?(p(a,e),l[a]=k[e]):r(a,e)}else if(0===a&&e>b){var n=h.mergeRule(j[a][e],j[a][e-1]);n===!0?(q(a,e),k[e]=l[a]):r(a,e)}else{var i=h.mergeRule(j[a][e],j[a-1][e]),n=h.mergeRule(j[a][e],j[a][e-1]);if(n&&i)continue;n&&q(a,e),i&&p(a,e),n||i||r(a,e)}else r(a,e)}),BI.map(i,function(a,b){return{x:b.x,y:b.y,row:b.item._row,col:b.item._col,width:b.item._width,height:b.item._height}})},_populate:function(){this._width<=0||this._height<=0||(this._isNeedDigest===!0&&this._digest(),this._isNeedDigest=!1,this._populateTable(),this._populateScrollbar())},getRegionSize:function(){var a=this.options,b=a.regionColumnSize[0]||0;return a.isNeedFreeze===!1||0===a.freezeCols.length?0:(b||BI.each(a.freezeCols,function(c,d){b+=a.columnSize[d]}),b)},setVerticalScroll:function(a){this.bottomLeftCollection.setScrollTop(a),this.bottomRightCollection.setScrollTop(a)},setLeftHorizontalScroll:function(a){this.topLeftCollection.setScrollLeft(a),this.bottomLeftCollection.setScrollLeft(a)},setRightHorizontalScroll:function(a){this.topRightCollection.setScrollLeft(a),this.bottomRightCollection.setScrollLeft(a)},getVerticalScroll:function(){return this.bottomRightCollection.getScrollTop()},getLeftHorizontalScroll:function(){return this.bottomLeftCollection.getScrollLeft()},getRightHorizontalScroll:function(){return this.bottomRightCollection.getScrollLeft()},setWidth:function(a){BI.CollectionTable.superclass.setWidth.apply(this,arguments),this._width=this.options.width-BI.GridTableScrollbar.SIZE},setHeight:function(a){BI.CollectionTable.superclass.setHeight.apply(this,arguments),this._height=this.options.height-BI.GridTableScrollbar.SIZE},setColumnSize:function(a){this._isNeedDigest=!0,this.options.columnSize=a},setRegionColumnSize:function(a){this._isNeedDigest=!0,this.options.regionColumnSize=a},getColumnSize:function(){return this.options.columnSize},getRegionColumnSize:function(){return this.options.regionColumnSize},populate:function(a,b){a&&a!==this.options.items&&(this._isNeedDigest=!0,this.options.items=a,this._restore()),b&&b!==this.options.header&&(this._isNeedDigest=!0,this.options.header=b,this._restore()),this._populate()},_restore:function(){this.topLeftCollection.restore(),this.topRightCollection.restore(),this.bottomLeftCollection.restore(),this.bottomRightCollection.restore()},restore:function(){this._restore()}}),BI.shortcut("bi.collection_table",BI.CollectionTable),BI.QuickCollectionTable=BI.inherit(BI.CollectionTable,{_defaultConfig:function(){return BI.extend(BI.QuickCollectionTable.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-quick-collection-table"})},render:function(){BI.QuickCollectionTable.superclass.render.apply(this,arguments);this.options;this.topLeftCollection.setOverflowX(!1),this.topLeftCollection.setOverflowY(!1),this.topRightCollection.setOverflowX(!1),this.topRightCollection.setOverflowY(!1),this.bottomLeftCollection.setOverflowX(!1),this.bottomLeftCollection.setOverflowY(!1),this.bottomRightCollection.setOverflowX(!1),this.bottomRightCollection.setOverflowY(!1)},mounted:function(){BI.QuickCollectionTable.superclass.mounted.apply(this,arguments);var a=this;this._topLeftWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelLeft,this),BI.bind(this._shouldHandleLeftX,this),BI.bind(this._shouldHandleY,this)),this._topRightWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelRight,this),BI.bind(this._shouldHandleRightX,this),BI.bind(this._shouldHandleY,this)),this._bottomLeftWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelLeft,this),BI.bind(this._shouldHandleLeftX,this),BI.bind(this._shouldHandleY,this)),this._bottomRightWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelRight,this),BI.bind(this._shouldHandleRightX,this),BI.bind(this._shouldHandleY,this)),this.topLeftCollection.element.mousewheel(function(b){a._topLeftWheelHandler.onWheel(b.originalEvent)}),this.topRightCollection.element.mousewheel(function(b){a._topRightWheelHandler.onWheel(b.originalEvent)}),this.bottomLeftCollection.element.mousewheel(function(b){a._bottomLeftWheelHandler.onWheel(b.originalEvent)}),this.bottomRightCollection.element.mousewheel(function(b){a._bottomRightWheelHandler.onWheel(b.originalEvent)})},_shouldHandleLeftX:function(a){return a>0?this.bottomLeftCollection.getScrollLeft()0},_shouldHandleRightX:function(a){return a>0?this.bottomRightCollection.getScrollLeft()0},_shouldHandleY:function(a){return a>0?this.bottomRightCollection.getScrollTop()0},_onWheelLeft:function(a,b){var c=this,d=this.bottomLeftCollection.getScrollTop(),e=this.bottomLeftCollection.getScrollLeft();d+=b,e+=a,this.bottomLeftCollection.setScrollTop(d),this.bottomRightCollection.setScrollTop(d),this.topLeftCollection.setScrollLeft(e),this.bottomLeftCollection.setScrollLeft(e),c._populateScrollbar(),this.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)},_onWheelRight:function(a,b){var c=this,d=this.bottomRightCollection.getScrollTop(),e=this.bottomRightCollection.getScrollLeft();d+=b,e+=a,this.bottomLeftCollection.setScrollTop(d),this.bottomRightCollection.setScrollTop(d),this.topRightCollection.setScrollLeft(e),this.bottomRightCollection.setScrollLeft(e),c._populateScrollbar(),this.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)},_populateTable:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[];BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g});var g=b,h=this._getFreezeHeaderHeight(),i=this._width-b,j=this._getFreezeHeaderHeight(),k=b,l=this._height-h,m=this._width-b,n=this._height-j;this.topLeft.setWidth(g),this.topLeft.setHeight(h),this.topRight.setWidth(i),this.topRight.setHeight(j),this.bottomLeft.setWidth(k),this.bottomLeft.setHeight(l),this.bottomRight.setWidth(m),this.bottomRight.setHeight(n),this.topLeftCollection.setWidth(g),this.topLeftCollection.setHeight(h),this.topRightCollection.setWidth(i),this.topRightCollection.setHeight(j),this.bottomLeftCollection.setWidth(k),this.bottomLeftCollection.setHeight(l),this.bottomRightCollection.setWidth(m),this.bottomRightCollection.setHeight(n);var o=this.contextLayout.attr("items");o[1].left=b,o[2].top=this._getFreezeHeaderHeight(),o[3].left=b,o[3].top=this._getFreezeHeaderHeight(),this.contextLayout.attr("items",o),this.contextLayout.resize();var p=[],q=[],r=[],s=[],t=function(a,b,c){BI.each(a,function(a,d){var e={type:"bi.collection_table_cell",cell:b[d.row][d.col]};c.push(e)})};t(this.topLeftItems,a.header,p),t(this.topRightItems,a.header,q),t(this.bottomLeftItems,this._getActualItems(),r),t(this.bottomRightItems,this._getActualItems(),s),this.topLeftCollection.populate(p),this.topRightCollection.populate(q),this.bottomLeftCollection.populate(r),this.bottomRightCollection.populate(s)}}),BI.shortcut("bi.quick_collection_table",BI.QuickCollectionTable),BI.GridTableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.GridTableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-grid-table-cell bi-border-right bi-border-bottom",width:0,height:0,_rowIndex:0,_columnIndex:0,_left:0,_top:0,cell:{}})},_init:function(){BI.GridTableCell.superclass._init.apply(this,arguments);var a=this.options;this.cell=BI.createWidget(BI.extend({type:"bi.label"},a.cell,{cls:(a.cell.cls||"")+"grid-table-cell-wrapper",width:a.width-(0===a._columnIndex?1:0)-1,height:a.height-(0===a._rowIndex?1:0)-1})),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.cell,left:0,right:0,top:0,bottom:0}]})},setWidth:function(a){BI.GridTableCell.superclass.setWidth.apply(this,arguments);var b=this.options;this.cell.setWidth(b.width-(0===b._columnIndex?1:0)-1)},setHeight:function(a){BI.GridTableCell.superclass.setHeight.apply(this,arguments);var b=this.options;this.cell.setHeight(b.height-(0===b._rowIndex?1:0)-1)}}),BI.shortcut("bi.grid_table_cell",BI.GridTableCell),BI.GridTable=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.GridTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-grid-table",headerRowSize:25,rowSize:25,columnSize:[],isNeedFreeze:!1,freezeCols:[],header:[],items:[],regionColumnSize:[]})},render:function(){var a=this,b=this.options;this._width=0,this._height=0,this._scrollBarSize=BI.DOM.getScrollWidth();var c=function(){return b.rowSize},d=function(a){return b.columnSize[a]},e=function(c){return b.columnSize[c+a._getFreezeColLength()]};this.topLeftGrid=BI.createWidget({type:"bi.grid_view",rowHeightGetter:c,columnWidthGetter:d}),this.topLeftGrid.on(BI.GridView.EVENT_SCROLL,function(b){a.bottomLeftGrid.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.topRightGrid=BI.createWidget({type:"bi.grid_view",rowHeightGetter:c,columnWidthGetter:e}),this.topRightGrid.on(BI.GridView.EVENT_SCROLL,function(b){a.bottomRightGrid.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.bottomLeftGrid=BI.createWidget({type:"bi.grid_view",rowHeightGetter:c,columnWidthGetter:d}),this.bottomLeftGrid.on(BI.GridView.EVENT_SCROLL,function(b){a.bottomRightGrid.setScrollTop(b.scrollTop),a.topLeftGrid.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.bottomRightGrid=BI.createWidget({type:"bi.grid_view",rowHeightGetter:c,columnWidthGetter:e}),this.bottomRightGrid.on(BI.GridView.EVENT_SCROLL,function(b){a.bottomLeftGrid.setScrollTop(b.scrollTop),a.topRightGrid.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.topLeft=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.topLeftGrid]}),this.topRight=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.topRightGrid]}),this.bottomLeft=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.bottomLeftGrid]}),this.bottomRight=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.bottomRightGrid]}),this.contextLayout=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.topLeft,top:0,left:0},{el:this.topRight,top:0},{el:this.bottomLeft,left:0},{el:this.bottomRight}]}),this.topScrollbar=BI.createWidget({type:"bi.grid_table_scrollbar",width:BI.GridTableScrollbar.SIZE}),this.topScrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(b){a.bottomLeftGrid.setScrollTop(b),a.bottomRightGrid.setScrollTop(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.leftScrollbar=BI.createWidget({type:"bi.grid_table_horizontal_scrollbar",height:BI.GridTableScrollbar.SIZE}),this.leftScrollbar.on(BI.GridTableHorizontalScrollbar.EVENT_SCROLL,function(b){a.topLeftGrid.setScrollLeft(b),a.bottomLeftGrid.setScrollLeft(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.rightScrollbar=BI.createWidget({type:"bi.grid_table_horizontal_scrollbar",height:BI.GridTableScrollbar.SIZE}),this.rightScrollbar.on(BI.GridTableHorizontalScrollbar.EVENT_SCROLL,function(b){a.topRightGrid.setScrollLeft(b),a.bottomRightGrid.setScrollLeft(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.scrollBarLayout=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.topScrollbar,right:0,top:0},{el:this.leftScrollbar,left:0},{el:this.rightScrollbar}]}),this._width=b.width-BI.GridTableScrollbar.SIZE,this._height=b.height-BI.GridTableScrollbar.SIZE,this.header=this._getHeader(),this.items=this._getItems()},mounted:function(){var a=this.options;(a.items.length>0||a.header.length>0)&&this._populate()},_getFreezeColLength:function(){var a=this.options;return a.isNeedFreeze===!0?BI.clamp(a.freezeCols.length,0,a.columnSize.length):0},_getFreezeHeaderHeight:function(){var a=this.options;return a.header.length*a.headerRowSize>=this._height?0:a.header.length*a.headerRowSize},_getActualItems:function(){var a=this.options;return a.header.length*a.headerRowSize>=this._height?a.header.concat(a.items):a.items},_populateScrollbar:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[];BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g}),this.topScrollbar.setContentSize(this._getActualItems().length*a.rowSize),this.topScrollbar.setSize(this._height-this._getFreezeHeaderHeight()),this.topScrollbar.setPosition(Math.min(this.bottomLeftGrid.getScrollTop(),this.bottomRightGrid.getScrollTop())),this.topScrollbar.populate(),this.leftScrollbar.setContentSize(c),this.leftScrollbar.setSize(b),this.leftScrollbar.setPosition(this.bottomLeftGrid.getScrollLeft()),this.leftScrollbar.populate(),this.rightScrollbar.setContentSize(d),this.rightScrollbar.setSize(this._width-b),this.rightScrollbar.setPosition(this.bottomRightGrid.getScrollLeft()),this.rightScrollbar.populate();var g=this.scrollBarLayout.attr("items");g[0].top=this._getFreezeHeaderHeight(),g[1].top=this._height,g[2].top=this._height,g[2].left=b,this.scrollBarLayout.attr("items",g),this.scrollBarLayout.resize()},_getHeader:function(){var a=this.options,b=this._getFreezeColLength(),c=[],d=[];return BI.each(a.header,function(a,e){c[a]=[],d[a]=[],BI.each(e,function(e,f){var g={type:"bi.grid_table_cell",cell:f};e0?c/g:0),this.topLeftGrid.setEstimatedRowSize(a.headerRowSize),this.topRightGrid.setEstimatedColumnSize(a.columnSize.length-g>0?d/(a.columnSize.length-g):0),this.topRightGrid.setEstimatedRowSize(a.headerRowSize),this.bottomLeftGrid.setEstimatedColumnSize(g>0?c/g:0),this.bottomLeftGrid.setEstimatedRowSize(a.rowSize),this.bottomRightGrid.setEstimatedColumnSize(a.columnSize.length-g>0?d/(a.columnSize.length-g):0),this.bottomRightGrid.setEstimatedRowSize(a.rowSize),this.topLeftGrid.setColumnCount(g),this.topRightGrid.setColumnCount(a.columnSize.length-g),this.bottomLeftGrid.setColumnCount(g),this.bottomRightGrid.setColumnCount(a.columnSize.length-g);var y=this.contextLayout.attr("items");y[1].left=b,y[2].top=this._getFreezeHeaderHeight(),y[3].left=b,y[3].top=this._getFreezeHeaderHeight(),this.contextLayout.attr("items",y),this.contextLayout.resize(),this.topLeftGrid._populate(this.header[0]),this.topRightGrid._populate(this.header[1]),this.bottomLeftGrid._populate(this.items[0]),this.bottomRightGrid._populate(this.items[1])},_populate:function(){this._width<=0||this._height<=0||(this._populateTable(),this._populateScrollbar())},getRegionSize:function(){var a=this.options,b=a.regionColumnSize[0]||0;return a.isNeedFreeze===!1||0===a.freezeCols.length?0:(b||BI.each(a.freezeCols,function(c,d){b+=a.columnSize[d]}),b)},setVerticalScroll:function(a){this.bottomLeftGrid.setScrollTop(a),this.bottomRightGrid.setScrollTop(a)},setLeftHorizontalScroll:function(a){this.topLeftGrid.setScrollLeft(a),this.bottomLeftGrid.setScrollLeft(a)},setRightHorizontalScroll:function(a){this.topRightGrid.setScrollLeft(a),this.bottomRightGrid.setScrollLeft(a)},getVerticalScroll:function(){return this.bottomRightGrid.getScrollTop()},getLeftHorizontalScroll:function(){return this.bottomLeftGrid.getScrollLeft()},getRightHorizontalScroll:function(){return this.bottomRightGrid.getScrollLeft()},setWidth:function(a){BI.GridTable.superclass.setWidth.apply(this,arguments),this._width=this.options.width-BI.GridTableScrollbar.SIZE},setHeight:function(a){BI.GridTable.superclass.setHeight.apply(this,arguments),this._height=this.options.height-BI.GridTableScrollbar.SIZE},setColumnSize:function(a){this.options.columnSize=a,this._isNeedDigest=!0},setRegionColumnSize:function(a){this.options.regionColumnSize=a,this._isNeedDigest=!0},getColumnSize:function(){return this.options.columnSize},getRegionColumnSize:function(){return this.options.regionColumnSize},populate:function(a,b){a&&this.options.items!==a&&(this.options.items=a,this.items=this._getItems(),this._restore()),b&&this.options.header!==b&&(this.options.header=b,this.header=this._getHeader(),this._restore()),this._populate()},_restore:function(){this.topLeftGrid.restore(),this.topRightGrid.restore(),this.bottomLeftGrid.restore(),this.bottomRightGrid.restore()},restore:function(){this._restore()}}),BI.shortcut("bi.grid_table",BI.GridTable),BI.QuickGridTable=BI.inherit(BI.GridTable,{_defaultConfig:function(){return BI.extend(BI.QuickGridTable.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-quick-grid-table"})},render:function(){BI.QuickGridTable.superclass.render.apply(this,arguments);this.options;this.topLeftGrid.setOverflowX(!1),this.topLeftGrid.setOverflowY(!1),this.topRightGrid.setOverflowX(!1),this.topRightGrid.setOverflowY(!1),this.bottomLeftGrid.setOverflowX(!1),this.bottomLeftGrid.setOverflowY(!1),this.bottomRightGrid.setOverflowX(!1),this.bottomRightGrid.setOverflowY(!1)},mounted:function(){BI.QuickGridTable.superclass.mounted.apply(this,arguments);var a=this;this._topLeftWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelLeft,this),BI.bind(this._shouldHandleLeftX,this),BI.bind(this._shouldHandleY,this)),this._topRightWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelRight,this),BI.bind(this._shouldHandleRightX,this),BI.bind(this._shouldHandleY,this)),this._bottomLeftWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelLeft,this),BI.bind(this._shouldHandleLeftX,this),BI.bind(this._shouldHandleY,this)),this._bottomRightWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelRight,this),BI.bind(this._shouldHandleRightX,this),BI.bind(this._shouldHandleY,this)),this.topLeftGrid.element.mousewheel(function(b){a._topLeftWheelHandler.onWheel(b.originalEvent)}),this.topRightGrid.element.mousewheel(function(b){a._topRightWheelHandler.onWheel(b.originalEvent)}),this.bottomLeftGrid.element.mousewheel(function(b){a._bottomLeftWheelHandler.onWheel(b.originalEvent)}),this.bottomRightGrid.element.mousewheel(function(b){a._bottomRightWheelHandler.onWheel(b.originalEvent)})},_shouldHandleLeftX:function(a){return a>0?this.bottomLeftGrid.getScrollLeft()0},_shouldHandleRightX:function(a){return a>0?this.bottomRightGrid.getScrollLeft()0},_shouldHandleY:function(a){return a>0?this.bottomRightGrid.getScrollTop()0},_onWheelLeft:function(a,b){var c=this,d=this.bottomLeftGrid.getScrollTop(),e=this.bottomLeftGrid.getScrollLeft();d+=b,e+=a,this.bottomLeftGrid.setScrollTop(d),this.bottomRightGrid.setScrollTop(d),this.topLeftGrid.setScrollLeft(e),this.bottomLeftGrid.setScrollLeft(e),c._populateScrollbar(),this.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)},_onWheelRight:function(a,b){var c=this,d=this.bottomRightGrid.getScrollTop(),e=this.bottomRightGrid.getScrollLeft();d+=b,e+=a,this.bottomLeftGrid.setScrollTop(d),this.bottomRightGrid.setScrollTop(d),this.topRightGrid.setScrollLeft(e),this.bottomRightGrid.setScrollLeft(e),c._populateScrollbar(),this.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)},_populateTable:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[],g=this._getFreezeColLength();BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g});var h=b,i=this._getFreezeHeaderHeight(),j=this._width-b,k=this._getFreezeHeaderHeight(),l=b,m=this._height-i,n=this._width-b,o=this._height-k;this.topLeft.setWidth(h),this.topLeft.setHeight(i),this.topRight.setWidth(j),this.topRight.setHeight(k),this.bottomLeft.setWidth(l),this.bottomLeft.setHeight(m),this.bottomRight.setWidth(n),this.bottomRight.setHeight(o),this.topLeftGrid.setWidth(h),this.topLeftGrid.setHeight(i),this.topRightGrid.setWidth(j),this.topRightGrid.setHeight(k),this.bottomLeftGrid.setWidth(l),this.bottomLeftGrid.setHeight(m),this.bottomRightGrid.setWidth(n),this.bottomRightGrid.setHeight(o),this.topLeftGrid.setEstimatedColumnSize(g>0?c/g:0),this.topLeftGrid.setEstimatedRowSize(a.headerRowSize),this.topRightGrid.setEstimatedColumnSize(a.columnSize.length-g>0?d/(a.columnSize.length-g):0),this.topRightGrid.setEstimatedRowSize(a.headerRowSize),this.bottomLeftGrid.setEstimatedColumnSize(g>0?c/g:0),this.bottomLeftGrid.setEstimatedRowSize(a.rowSize),this.bottomRightGrid.setEstimatedColumnSize(a.columnSize.length-g>0?d/(a.columnSize.length-g):0),this.bottomRightGrid.setEstimatedRowSize(a.rowSize),this.topLeftGrid.setColumnCount(g),this.topRightGrid.setColumnCount(a.columnSize.length-g),this.bottomLeftGrid.setColumnCount(g),this.bottomRightGrid.setColumnCount(a.columnSize.length-g);var p=this.contextLayout.attr("items");p[1].left=b,p[2].top=this._getFreezeHeaderHeight(),p[3].left=b,p[3].top=this._getFreezeHeaderHeight(),this.contextLayout.attr("items",p),this.contextLayout.resize();var q=[],r=[],s=[],t=[];BI.each(a.header,function(a,b){q[a]=[],r[a]=[],BI.each(b,function(b,c){var d={type:"bi.grid_table_cell",cell:c};bb&&(this.options.position=b),this._populate(),this.fireEvent(BI.GridTableScrollbar.EVENT_SCROLL,this.options.position)},_onMouseDown:function(a){if(a.target!==this.face.element[0]){var b=this._isHorizontal()?a.offsetX:a.offsetY;b/=this._getScale(),this.options.position=BI.clamp(b-.5*this._getFaceSize()/this._getScale(),0,this.options.contentSize-this.options.size),this._populate(),this.fireEvent(BI.GridTableScrollbar.EVENT_SCROLL,this.options.position)}else this._mouseMoveTracker.captureMouseMoves(a);try{this.element[0].focus()}catch(a){}},_onMouseMove:function(a,b){var c=this._isHorizontal()?a:b;c/=this._getScale(),this.options.position=BI.clamp(this.options.position+c,0,this.options.contentSize-this.options.size),this.isDragging=this._mouseMoveTracker.isDragging(),this._populate(),this.fireEvent(BI.GridTableScrollbar.EVENT_SCROLL,this.options.position)},_onMouseMoveEnd:function(a){this._mouseMoveTracker.releaseMouseMoves(),this.isDragging===!0&&(this.isDragging=!1,this._populate())},_onKeyDown:function(a){var b={BACKSPACE:8,TAB:9,RETURN:13,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46,COMMA:188,PERIOD:190,A:65,Z:90,ZERO:48,NUMPAD_0:96,NUMPAD_9:105},c=a.keyCode;if(c!==b.TAB){var d=40,e=0;if(this._isHorizontal())switch(c){case b.HOME:e=-1,d=this.options.contentSize;break;case b.LEFT:e=-1;break;case b.RIGHT:e=1;break;default:return}if(!this._isHorizontal())switch(c){case b.SPACE:e=a.shiftKey?-1:1;break;case b.HOME:e=-1,d=this.options.contentSize;break;case b.UP:e=-1;break;case b.DOWN:e=1;break;case b.PAGE_UP:e=-1,d=this.options.size;break;case b.PAGE_DOWN:e=1,d=this.options.size;break;default:return}this.options.position=BI.clamp(this.options.position+d*e,0,this.options.contentSize-this.options.size),a.preventDefault(),this._populate(),this.fireEvent(BI.GridTableScrollbar.EVENT_SCROLL,this.options.position)}},_populate:function(){var a=this.options;if(a.size<1||a.contentSize<=a.size)return void this.setVisible(!1);this.setVisible(!0);var b=a.size,c=this._isHorizontal(),d=this.focused||this.isDragging,e=this._getFaceSize(),f=a.isOpaque;this.element[f===!0?"addClass":"removeClass"]("public-scrollbar-main-opaque"),this.element[d===!0?"addClass":"removeClass"]("public-scrollbar-main-active"),this.face.element[d===!0?"addClass":"removeClass"]("public-scrollbar-face-active");var g=a.position*this._getScale()+this._const.FACE_MARGIN,h=this.contextLayout.attr("items");c?(this.setWidth(b),this.face.setWidth(e-this._const.FACE_MARGIN_2),h[0].left=g,h[0].top=0):(this.setHeight(b),this.face.setHeight(e-this._const.FACE_MARGIN_2),h[0].left=0,h[0].top=g),this.contextLayout.attr("items",h),this.contextLayout.resize()},setContentSize:function(a){this.options.contentSize=a},setPosition:function(a){this.options.position=a},setSize:function(a){this.options.size=a},populate:function(){this._populate()}}),BI.GridTableScrollbar.SIZE=10,BI.GridTableScrollbar.EVENT_SCROLL="EVENT_SCROLL",BI.shortcut("bi.grid_table_scrollbar",BI.GridTableScrollbar),BI.GridTableHorizontalScrollbar=BI.inherit(BI.Widget,{_const:{FACE_MARGIN:4,FACE_MARGIN_2:8,FACE_SIZE_MIN:30,KEYBOARD_SCROLL_AMOUNT:40},_defaultConfig:function(){return BI.extend(BI.GridTableHorizontalScrollbar.superclass._defaultConfig.apply(this,arguments),{attributes:{tabIndex:0},contentSize:0,position:0,size:0})},_init:function(){BI.GridTableHorizontalScrollbar.superclass._init.apply(this,arguments);var a=this,b=this.options;this.scrollbar=BI.createWidget({type:"bi.grid_table_scrollbar",orientation:"horizontal",isOpaque:!0,position:b.position,contentSize:b.contentSize,size:b.size}),this.scrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(){a.fireEvent(BI.GridTableHorizontalScrollbar.EVENT_SCROLL,arguments)}),BI.createWidget({type:"bi.absolute",cls:"horizontal-scrollbar",element:this,width:b.size,height:BI.GridTableScrollbar.SIZE,items:[{el:{type:"bi.absolute",scrollable:!1,height:BI.GridTableScrollbar.SIZE,items:[{el:this.scrollbar,left:0,top:0}]},top:0,left:0,right:0}]})},setContentSize:function(a){this.options.contentSize=a,this.scrollbar.setContentSize(a)},setPosition:function(a){this.options.position=a,this.scrollbar.setPosition(a)},setSize:function(a){this.setWidth(a),this.options.size=a,this.scrollbar.setSize(a)},populate:function(){this.scrollbar.populate();var a=this.options;return a.size<1||a.contentSize<=a.size?void this.setVisible(!1):void this.setVisible(!0)}}),BI.GridTableHorizontalScrollbar.EVENT_SCROLL="EVENT_SCROLL",BI.shortcut("bi.grid_table_horizontal_scrollbar",BI.GridTableHorizontalScrollbar),BI.TableHeaderCell=BI.inherit(BI.Widget,{ -_defaultConfig:function(){return BI.extend(BI.TableHeaderCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-table-header-cell",text:""})},_init:function(){BI.TableHeaderCell.superclass._init.apply(this,arguments),BI.createWidget({type:"bi.label",element:this,textAlign:"center",height:this.options.height,text:this.options.text,value:this.options.value})}}),BI.shortcut("bi.table_header_cell",BI.TableHeaderCell),BI.Table=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.Table.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-table",logic:{dynamic:!1},isNeedFreeze:!1,freezeCols:[],isNeedMerge:!1,mergeCols:[],mergeRule:function(a,b){return BI.isEqual(a,b)},columnSize:[],headerRowSize:25,footerRowSize:25,rowSize:25,regionColumnSize:!1,header:[],footer:!1,items:[]})},_calculateWidth:function(a){return a&&"0"!==a?(a=BI.parseFloat(a),a<0&&(a=0),a>1.01?a:100*a+"%"):""},_calculateHeight:function(a){return a?a:""},_isRightFreeze:function(){return BI.isNotEmptyArray(this.options.freezeCols)&&0!==BI.first(this.options.freezeCols)},_createTopLeft:function(){var a=this.options,b=this._isRightFreeze();this.topLeftColGroupTds={},this.topLeftBodyTds={},this.topLeftBodyItems={};var c=this._table(),d=this._createColGroup(this.columnLeft,this.topLeftColGroupTds),e=this.topLeftBody=this._body();if(e.element.append(this._createHeaderCells(this.topLeftItems,this.columnLeft,this.mergeLeft,this.topLeftBodyTds,this.topLeftBodyItems)),BI.createWidget({type:"bi.adaptive",element:c,items:[d,e]}),b){var f=0;BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)||(f+=c)}),BI.isNumeric(f)&&f>1&&(f=BI.parseFloat(f)+a.columnSize.length-a.freezeCols.length)}return this.topLeftContainer=BI.createWidget({type:"bi.adaptive",width:this._calculateWidth(f),items:[c]})},_createTopRight:function(){var a=this.options,b=this._isRightFreeze();this.topRightColGroupTds={},this.topRightBodyTds={},this.topRightBodyItems={};var c=this._table(),d=this._createColGroup(this.columnRight,this.topRightColGroupTds),e=this.topRightBody=this._body();if(e.element.append(this._createHeaderCells(this.topRightItems,this.columnRight,this.mergeRight,this.topRightBodyTds,this.topRightBodyItems,this.columnLeft.length)),BI.createWidget({type:"bi.adaptive",element:c,items:[d,e]}),!b){var f=0;BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)||(f+=c)}),BI.isNumeric(f)&&(f=BI.parseFloat(f)+a.columnSize.length-a.freezeCols.length)}return this.topRightContainer=BI.createWidget({type:"bi.adaptive",width:f||void 0,items:[c]})},_createBottomLeft:function(){var a=this.options,b=this._isRightFreeze();this.bottomLeftColGroupTds={},this.bottomLeftBodyTds={},this.bottomLeftBodyItems={};var c=this._table(),d=this._createColGroup(this.columnLeft,this.bottomLeftColGroupTds),e=this._createBottomLeftBody();if(BI.createWidget({type:"bi.adaptive",element:c,items:[d,e]}),b){var f=0;BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)||(f+=c)}),BI.isNumeric(f)&&f>1&&(f=BI.parseFloat(f)+a.columnSize.length-a.freezeCols.length)}return this.bottomLeftContainer=BI.createWidget({type:"bi.adaptive",width:this._calculateWidth(f),items:[c]})},_createBottomLeftBody:function(){var a=this.bottomLeftBody=this._body();return a.element.append(this._createCells(this.bottomLeftItems,this.columnLeft,this.mergeLeft,this.bottomLeftBodyTds,this.bottomLeftBodyItems)),a},_createBottomRight:function(){var a=this.options,b=this._isRightFreeze();this.bottomRightColGroupTds={},this.bottomRightBodyTds={},this.bottomRightBodyItems={};var c=this._table(),d=this._createColGroup(this.columnRight,this.bottomRightColGroupTds),e=this._createBottomRightBody();if(BI.createWidget({type:"bi.adaptive",element:c,items:[d,e]}),!b){var f=0;BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)||(f+=c)}),BI.isNumeric(f)&&f>1&&(f=BI.parseFloat(f)+a.columnSize.length-a.freezeCols.length)}return this.bottomRightContainer=BI.createWidget({type:"bi.adaptive",width:this._calculateWidth(f),items:[c]})},_createBottomRightBody:function(){var a=this.bottomRightBody=this._body();return a.element.append(this._createCells(this.bottomRightItems,this.columnRight,this.mergeRight,this.bottomRightBodyTds,this.bottomRightBodyItems,this.columnLeft.length)),a},_createFreezeTable:function(){var a=this,b=this.options,c=this._isRightFreeze(),d=this._split(b.header);this.topLeftItems=d.left,this.topRightItems=d.right,d=this._split(b.items),this.bottomLeftItems=d.left,this.bottomRightItems=d.right,this.columnLeft=[],this.columnRight=[],BI.each(b.columnSize,function(d,e){b.freezeCols.contains(d)?a[c?"columnRight":"columnLeft"].push(e):a[c?"columnLeft":"columnRight"].push(e)}),this.mergeLeft=[],this.mergeRight=[],BI.each(b.mergeCols,function(d,e){b.freezeCols.contains(e)?a[c?"mergeRight":"mergeLeft"].push(e):a[c?"mergeLeft":"mergeRight"].push(e)});var e=this._createTopLeft(),f=this._createTopRight(),g=this._createBottomLeft(),h=this._createBottomRight();this.scrollTopLeft=BI.createWidget({type:"bi.adaptive",cls:"scroll-top-left",width:"100%",height:"100%",scrollable:!1,items:[e]}),this.scrollTopRight=BI.createWidget({type:"bi.adaptive",cls:"scroll-top-right",width:"100%",height:"100%",scrollable:!1,items:[f]}),this.scrollBottomLeft=BI.createWidget({type:"bi.adaptive",cls:"scroll-bottom-left",width:"100%",height:"100%",scrollable:c||null,scrollx:!c,items:[g]}),this.scrollBottomRight=BI.createWidget({type:"bi.adaptive",cls:"scroll-bottom-right",width:"100%",height:"100%",scrollable:!c||null,scrollx:c,items:[h]}),this.topLeft=BI.createWidget({type:"bi.adaptive",cls:"top-left",scrollable:!1,items:[this.scrollTopLeft]}),this.topRight=BI.createWidget({type:"bi.adaptive",cls:"top-right",scrollable:!1,items:[this.scrollTopRight]}),this.bottomLeft=BI.createWidget({type:"bi.adaptive",cls:"bottom-left",items:[this.scrollBottomLeft]}),this.bottomRight=BI.createWidget({type:"bi.adaptive",cls:"bottom-right",scrollable:!1,items:[this.scrollBottomRight]});var i=b.header.length*((b.headerRowSize||b.rowSize)+1)+1,j=BI.sum(b.freezeCols,function(a,c){return b.columnSize[c]>1?b.columnSize[c]+1:b.columnSize[c]});this._resize=function(){a.scrollBottomLeft.element.is(":visible")&&(a.scrollBottomLeft.element.css({"overflow-x":"auto"}),a.scrollBottomRight.element.css({"overflow-x":"auto"}),a.setColumnSize(b.columnSize),c?a.scrollBottomLeft.element.css({"overflow-y":"auto"}):a.scrollBottomRight.element.css({"overflow-y":"auto"}),(a.scrollBottomLeft.element.hasHorizonScroll()||a.scrollBottomRight.element.hasHorizonScroll())&&(a.scrollBottomLeft.element.css("overflow-x","scroll"),a.scrollBottomRight.element.css("overflow-x","scroll")),a.scrollBottomRight.element.hasVerticalScroll()?a.scrollTopRight.element.css("overflow-y","scroll"):a.scrollTopRight.element.css("overflow-y","hidden"),a.scrollBottomLeft.element.hasVerticalScroll()?a.scrollTopLeft.element.css("overflow-y","scroll"):a.scrollTopLeft.element.css("overflow-y","hidden"),a.scrollTopLeft.element[0].scrollLeft=a.scrollBottomLeft.element[0].scrollLeft,a.scrollTopRight.element[0].scrollLeft=a.scrollBottomRight.element[0].scrollLeft,a.scrollBottomLeft.element[0].scrollTop=a.scrollBottomRight.element[0].scrollTop)};var k=b.regionColumnSize;0===b.freezeCols.length?k=c?["fill",0]:[0,"fill"]:b.freezeCols.length>=b.columnSize.length&&(k=c?[0,"fill"]:["fill",0]),this.partitions=BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("table",BI.extend({},b.logic,{rows:2,columns:2,columnSize:k||(c?["fill",j]:[j,"fill"]),rowSize:[i,"fill"],items:[[{el:this.topLeft},{el:this.topRight}],[{el:this.bottomLeft},{el:this.bottomRight}]]})))),this._initFreezeScroll(),BI.ResizeDetector.addResizeListener(this,function(){a._resize(),a.fireEvent(BI.Table.EVENT_TABLE_RESIZE)})},mounted:function(){this._resize&&this._resize(),this.fireEvent(BI.Table.EVENT_TABLE_AFTER_INIT)},_initFreezeScroll:function(){function a(a,c,d){a.scroll(function(e){d.scrollTop(a.scrollTop()),c.scrollLeft(a.scrollLeft()),b.fireEvent(BI.Table.EVENT_TABLE_SCROLL)})}var b=this;this.options;a(this.scrollBottomRight.element,this.scrollTopRight.element,this.scrollBottomLeft.element)},resize:function(){this._resize&&this._resize()},_createCells:function(a,b,c,d,e,f,g){var h=this,i=this.options,j={},k={},l={},m={},n={};b=b||i.columnSize,c=c||i.mergeCols,d=d||{},e=e||{},f=f||0,g||(g=i.rowSize);var o=document.createDocumentFragment();return BI.each(a,function(a,p){function q(a,b){var c=(0|j[b].attr("height"))+g+1;j[b].attr("height",c).css("height",c);var f=(0|(j[b].attr("rowspan")||1))+1;j[b].attr("rowspan",f),j[b].__mergeRows.pushDistinct(a),d[a][b]=j[b],e[a][b]=m[b]}function r(a,c){if(b[c]){var f=0|k[a].attr("width");f>1.05&&b[c]?(f=f+b[c]+1,c===b.length-1&&f--):f+=b[c],f=h._calculateWidth(f),k[a].attr("width",f).css("width",f),l[a].element.width(f)}var g=(0|(k[a].attr("colspan")||1))+1;k[a].attr("colspan",g),k[a].__mergeCols.pushDistinct(c),d[a][c]=k[a],e[a][c]=l[a]}function s(a,c){var i=h._calculateWidth(b[c]);i>1.05&&c===b.length-1&&i--;var o=h._calculateHeight(g),q=$("").attr("height",o).attr("width",i).css({width:i,height:o,position:"relative"}).addClass(0===(1&c)?"odd-col":"even-col").addClass(0===a?"first-row":"").addClass(0===c?"first-col":"").addClass(c===p.length-1?"last-col":""),r=BI.createWidget(n[a][c],{type:"bi.table_cell",textAlign:"left",width:BI.isNumeric(i)?i:"",height:BI.isNumeric(o)?o:"",_row:a,_col:c+f});h.addWidget(r.getName(),r),r._mount(),r.element.css("position","relative"),q.append(r.element),t.append(q),j[c]=q,j[c].__mergeRows=[a],m[c]=r,k[a]=q,k[a].__mergeCols=[c],l[a]=r,d[a][c]=q,e[a][c]=r}var t=$("").addClass(0===(1&a)?"odd":"even");BI.each(p,function(b,f){if(n[a]||(n[a]={}),d[a]||(d[a]={}),e[a]||(e[a]={}),n[a][b]=f,i.isNeedMerge&&c.contains(b))if(0===a&&0===b)s(0,0);else if(0===b&&a>0){var g=i.mergeRule(n[a][b],n[a-1][b]);g===!0?(q(a,b),k[a]=j[b],l[a]=m[b]):s(a,b)}else if(0===a&&b>0){var h=i.mergeRule(n[a][b],n[a][b-1]);h===!0?(r(a,b),j[b]=k[a],m[b]=l[a]):s(a,b)}else{var g=i.mergeRule(n[a][b],n[a-1][b]),h=i.mergeRule(n[a][b],n[a][b-1]);if(h&&g)return;h&&r(a,b),g&&q(a,b),h||g||s(a,b)}else s(a,b)}),o.appendChild(t[0])}),o},_createColGroupCells:function(a,b){var c=this,d=this.options;a=a||d.columnSize,b=b||{};var e=document.createDocumentFragment();return BI.each(a,function(a,d){var f=c._calculateWidth(d),g=$("").attr("width",f).css("width",f);b[a]=g,e.appendChild(g[0])}),e},_createHeaderCells:function(a,b,c,d,e,f){var g=this.options;f||(f=0);var h=this._createCells(a,b,BI.range(g.columnSize.length),d,e,f,g.headerRowSize||g.rowSize);return h},_createFooterCells:function(a,b,c,d){var e=(this.options,this._createCells(a,b,[],c,d,0));return e},_createColGroup:function(a,b,c){this.options;return this.colgroup=this._colgroup(),this.colgroup.element.append(this._createColGroupCells(a,b,c)),this.colgroup},_createHeader:function(){var a=this.options;if(a.header!==!1)return this.header=this._header(),this.header.element.append(this._createHeaderCells(a.header,null,null,this.headerTds,this.headerItems)),this.header},_createFooter:function(a,b,c){var d=this.options;if(d.footer!==!1)return this.footer=this._footer(),this.footer.element.append(this._createFooterCells(d.footer,null,this.footerTds,this.footerItems)),this.footer},_createBody:function(){var a=this.options;return this.body=this._body(),this.body.element.append(this._createCells(a.items,null,null,this.bodyTds,this.bodyItems)),this.body},_createNormalTable:function(){var a=this,b=this.options,c=this._table();this.colgroupTds={},this.headerTds={},this.footerTds={},this.bodyTds={},this.headerItems={},this.footerItems={},this.bodyItems={};var d=this._createColGroup(null,this.colgroupTds),e=this._createHeader(),f=this._createFooter(),g=this._createBody();BI.createWidget({type:"bi.adaptive",element:c,items:[d,e,f,g]});var h=BI.sum(this.options.columnSize)||void 0;h=this._calculateWidth(h),BI.isNumeric(h)&&h>1&&(h+=b.columnSize.length),this.tableContainer=BI.createWidget({type:"bi.adaptive",width:this._calculateWidth(h),items:[c]}),this.scrollBottomRight=BI.createWidget({type:"bi.adaptive",width:"100%",height:"100%",cls:"scroll-bottom-right",scrollable:!0,items:[this.tableContainer]}),BI.createWidget({type:"bi.adaptive",cls:"bottom-right",element:this,scrollable:!1,items:[this.scrollBottomRight]}),this._initNormalScroll(),BI.nextTick(function(){a.element.is(":visible")&&a.fireEvent(BI.Table.EVENT_TABLE_AFTER_INIT)})},_initNormalScroll:function(){var a=this;this.scrollBottomRight.element.scroll(function(b){a.fireEvent(BI.Table.EVENT_TABLE_SCROLL)})},_split:function(a){var b=this.options,c=[],d=[],e=this._isRightFreeze();return BI.each(a,function(a,f){c.push([]),d.push([]),BI.each(f,function(f,g){b.freezeCols.contains(f)?(e?d:c)[a].push(g):(e?c:d)[a].push(g)})}),{left:c,right:d}},_table:function(){return BI.createWidget({type:"bi.layout",tagName:"table",cls:"table",attribute:{cellspacing:0,cellpadding:0}})},_header:function(){return BI.createWidget({type:"bi.layout",cls:"header",tagName:"thead"})},_footer:function(){return BI.createWidget({type:"bi.layout",cls:"footer",tagName:"tfoot"})},_body:function(){return BI.createWidget({type:"bi.layout",tagName:"tbody",cls:"body"})},_colgroup:function(){return BI.createWidget({type:"bi.layout",tagName:"colgroup"})},render:function(){this.populate(this.options.items)},setColumnSize:function(a){var b=this,c=this.options,d=this._isRightFreeze();if(c.columnSize=a||[],c.isNeedFreeze){var e=[],f=[];BI.each(c.columnSize,function(a,b){c.freezeCols.contains(a)?d?f.push(b):e.push(b):d?e.push(b):f.push(b)});var g=0,h=1,i=2,j=3,k=function(a){var c,d,k,l;switch(a){case g:c=b.topLeftColGroupTds,d=b.topLeftBodyTds,k=b.topLeftBodyItems,l=e;break;case h:c=b.topRightColGroupTds,d=b.topRightBodyTds,k=b.topRightBodyItems,l=f;break;case i:c=b.bottomLeftColGroupTds,d=b.bottomLeftBodyTds,k=b.bottomLeftBodyItems,l=e;break;case j:c=b.bottomRightColGroupTds,d=b.bottomRightBodyTds,k=b.bottomRightBodyItems,l=f}BI.each(c,function(a,c){var e=0|c.attr("width");if(""!==l[a]&&e!==l[a]){var f=b._calculateWidth(l[a]);c.attr("width",f).css("width",f),BI.each(d,function(c,d){if(d[a])if(d[a].__mergeCols.length>1){var e=0;BI.each(l,function(b,c){d[a].__mergeCols.contains(b)&&(e+=c)}),e=b._calculateWidth(e),e>1&&(e+=d[a].__mergeCols.length-1),BI.isNumeric(e)?a==BI.size(d)-1?d[a].attr("width",e-1).css("width",e-1):d[a].attr("width",e).css("width",e):d[a].attr("width","").css("width","")}else a==BI.size(d)-1?d[a].attr("width",f-1).css("width",f-1):d[a].attr("width",f).css("width",f)}),BI.each(k,function(c,e){if(e[a])if(d[c][a].__mergeCols.length>1){var g=0;BI.each(l,function(b,e){d[c][a].__mergeCols.contains(b)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=d[c][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")})}})};k(g),k(h),k(i),k(j);var l=0,m=0;this.columnLeft=[],this.columnRight=[],BI.each(c.columnSize,function(a,e){c.freezeCols.contains(a)?(l+=e,b[d?"columnRight":"columnLeft"].push(e)):(m+=e,b[d?"columnLeft":"columnRight"].push(e))}),l=this._calculateWidth(l),m=this._calculateWidth(m),BI.isNumeric(l)&&(l=BI.parseFloat(l)+c.freezeCols.length),BI.isNumeric(m)&&(m=BI.parseFloat(m)+c.columnSize.length-c.freezeCols.length),this.topLeftContainer.element.width(d?m:l),this.bottomLeftContainer.element.width(d?m:l),this.topRightContainer.element.width(d?l:m),this.bottomRightContainer.element.width(d?l:m),this.scrollTopLeft.element[0].scrollLeft=this.scrollBottomLeft.element[0].scrollLeft,this.scrollTopRight.element[0].scrollLeft=this.scrollBottomRight.element[0].scrollLeft}else{BI.each(this.colgroupTds,function(a,d){var e=0|d.attr("width");if(""!==c.columnSize[a]&&e!==c.columnSize[a]){var f=b._calculateWidth(c.columnSize[a]);d.attr("width",f).css("width",f),BI.each(b.bodyTds,function(d,e){if(e[a])if(e[a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(b,c){e[a].__mergeCols.contains(b)&&(g+=c)}),g=b._calculateWidth(g),g>1&&(g+=e[a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f):e[a].attr("width","").css("width","")}else a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f)}),BI.each(b.headerTds,function(d,e){if(e[a])if(e[a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(b,c){e[a].__mergeCols.contains(b)&&(g+=c)}),g=b._calculateWidth(g),g>1&&(g+=e[a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f):e[a].attr("width","").css("width","")}else a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f)}),BI.each(b.footerTds,function(d,e){if(e[a])if(e[a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(b,c){e[a].__mergeCols.contains(b)&&(g+=c)}),g=b._calculateWidth(g),g>1&&(g+=e[a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f):e[a].attr("width","").css("width","")}else a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f)}),BI.each(b.bodyItems,function(d,e){if(e[a])if(b.bodyTds[d][a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(c,e){b.bodyTds[d][a].__mergeCols.contains(c)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=b.bodyTds[d][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")}),BI.each(b.headerItems,function(d,e){if(e[a])if(b.headerTds[d][a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(c,e){b.headerTds[d][a].__mergeCols.contains(c)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=b.headerTds[d][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")}),BI.each(b.footerItems,function(d,e){if(e[a])if(b.footerTds[d][a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(c,e){b.footerTds[d][a].__mergeCols.contains(c)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=b.footerTds[d][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")})}});var n=this._calculateWidth(BI.sum(c.columnSize));n>1.05&&(n+=c.columnSize.length),n>1.05&&this.tableContainer.element.width(n)}},getColumnSize:function(){return this.options.columnSize},getCalculateColumnSize:function(){var a=this,b=this.options,c=[];if(b.isNeedFreeze===!0){if(BI.size(this.bottomLeftBodyTds)>0||BI.size(this.bottomRightBodyTds)>0)return BI.any(this.bottomLeftBodyTds,function(a,b){if(!BI.any(b,function(a,b){if(b.__mergeCols.length>1)return!0}))return BI.each(b,function(a,d){var e=d.width()/d.__mergeCols.length;a==BI.size(b)-1&&e++,c.push(e)}),!0})||BI.each(this.bottomLeftBodyTds[0],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.bottomLeftBodyTds[0])-1&&e++,c.push(e)}),BI.any(this.bottomRightBodyTds,function(a,b){if(!BI.any(b,function(a,b){if(b.__mergeCols.length>1)return!0}))return BI.each(b,function(a,d){var e=d.width()/d.__mergeCols.length;a==BI.size(b)-1&&e++,c.push(e)}),!0})||BI.each(this.bottomRightBodyTds[0],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.bottomRightBodyTds[0])-1&&e++,c.push(e)}),c;BI.any(this.topLeftBodyTds,function(a,b){if(!BI.any(b,function(a,b){if(b.__mergeCols.length>1)return!0}))return BI.each(b,function(a,d){var e=d.width()/d.__mergeCols.length;a==BI.size(b)-1&&e++,c.push(e)}),!0})||BI.each(this.topLeftBodyTds[BI.size(this.topLeftBodyTds)-1],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.topLeftBodyTds[BI.size(a.topLeftBodyTds)-1])-1&&e++,c.push(e)}),BI.any(this.topRightBodyTds,function(a,b){if(!BI.any(b,function(a,b){if(b.__mergeCols.length>1)return!0}))return BI.each(b,function(a,d){var e=d.width()/d.__mergeCols.length;a==BI.size(b)-1&&e++,c.push(e)}),!0})||BI.each(this.topRightBodyTds[BI.size(this.topRightBodyTds)-1],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.topRightBodyTds[BI.size(a.topRightBodyTds)-1])-1&&e++,c.push(e)})}else BI.each(this.headerTds[BI.size(this.headerTds)-1],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.headerTds[BI.size(a.headerTds)-1])-1&&e++,c.push(e)});return c},setHeaderColumnSize:function(a){var b=this,c=this.options,d=this._isRightFreeze();if(c.isNeedFreeze){var e=[],f=[];BI.each(a,function(a,b){c.freezeCols.contains(a)?d?f.push(b):e.push(b):d?e.push(b):f.push(b)});var g=0,h=1,i=function(a){var c,d,i,j;switch(a){case g:c=b.topLeftColGroupTds,d=b.topLeftBodyTds,i=b.topLeftBodyItems,j=e;break;case h:c=b.topRightColGroupTds,d=b.topRightBodyTds,i=b.topRightBodyItems,j=f}BI.each(c,function(a,c){var e=0|c.attr("width");if(e!==j[a]){var f=b._calculateWidth(j[a]);c.attr("width",f).css("width",f),BI.each(d,function(c,d){if(d[a])if(d[a].__mergeCols.length>1){var e=0;BI.each(j,function(b,c){d[a].__mergeCols.contains(b)&&(e+=c)}),e=b._calculateWidth(e),e>1&&(e+=d[a].__mergeCols.length-1),BI.isNumeric(e)?a==BI.size(d)-1?d[a].attr("width",e-1).css("width",e-1):d[a].attr("width",e).css("width",e):d[a].attr("width","").css("width","")}else a==BI.size(d)-1?d[a].attr("width",f-1).css("width",f-1):d[a].attr("width",f).css("width",f)}),BI.each(i,function(c,e){if(e[a])if(d[c][a].__mergeCols.length>1){var g=0;BI.each(j,function(b,e){d[c][a].__mergeCols.contains(b)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=d[c][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")})}})};i(g),i(h);var j=0,k=0;BI.each(a,function(a,b){c.freezeCols.contains(a)?j+=b:k+=b}),j=this._calculateWidth(j),k=this._calculateWidth(k),BI.isNumeric(j)&&(j=BI.parseFloat(j)+c.freezeCols.length),BI.isNumeric(k)&&(k=BI.parseFloat(k)+a.length-c.freezeCols.length),this.topLeftContainer.element.width(d?k:j),this.topRightContainer.element.width(d?j:k),this.scrollTopLeft.element[0].scrollLeft=this.scrollBottomLeft.element[0].scrollLeft,this.scrollTopRight.element[0].scrollLeft=this.scrollBottomRight.element[0].scrollLeft}else{BI.each(this.colgroupTds,function(c,d){var e=0|d.attr("width");if(e!==a[c]){var f=b._calculateWidth(a[c]);d.attr("width",f).css("width",f),BI.each(b.headerTds,function(d,e){if(e[c])if(e[c].__mergeCols.length>1){var g=0;BI.each(a,function(a,b){e[c].__mergeCols.contains(a)&&(g+=b)}),g=b._calculateWidth(g),g>1&&(g+=e[c].__mergeCols.length-1),BI.isNumeric(g)?c==BI.size(e)-1?e[c].element.attr("width",g-1).css("width",g-1):e[c].element.attr("width",g).css("width",g):e[c].attr("width","").css("width","")}else c==BI.size(e)-1?e[c].attr("width",f-1).css("width",f-1):e[c].attr("width",f).css("width",f)}),BI.each(b.headerItems,function(d,e){if(e[c])if(b.headerTds[d][c].__mergeCols.length>1){var g=0;BI.each(a,function(a,e){b.headerTds[d][c].__mergeCols.contains(a)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=b.headerTds[d][c].__mergeCols.length-1),BI.isNumeric(g)?c==BI.size(e)-1?e[c].element.attr("width",g-1).css("width",g-1):e[c].element.attr("width",g).css("width",g):e[c].element.attr("width","").css("width","")}else BI.isNumeric(f)?c==BI.size(e)-1?e[c].element.attr("width",f-1).css("width",f-1):e[c].element.attr("width",f).css("width",f):e[c].element.attr("width","").css("width","")})}});var l=this._calculateWidth(BI.sum(a));l>1.05&&(l+=a.length),this.tableContainer.element.width(l)}},setRegionColumnSize:function(a){var b=this.options;b.regionColumnSize=a,0===b.freezeCols.length?b.isNeedFreeze?(this.partitions.attr("columnSize",this._isRightFreeze()?["fill",0]:[0,"fill"]),this.partitions.resize()):this.tableContainer.element.width(a[0]):b.freezeCols.length>0&&b.freezeCols.length=d?d:0;e=d?(b+=this.table.getRegionSize(),b-=this.table.getRightHorizontalScroll()):b-=this.table.getLeftHorizontalScroll(),b},_formatHeader:function(a){var b=this,c=this.options,d=[],e=function(a,d){b.resizer.setVisible(!0);var e=c.headerRowSize+b._getRegionRowSize()[1];b.resizer.setHeight(e),b._setResizerPosition(b._getResizerLeft(a)+d,(c.header.length-1)*c.headerRowSize)},f=function(a,d){b.resizer.setVisible(!1);var e=c.columnSize.slice();e[a]=d,c.columnSize=e,b.table.setColumnSize(e),b._populate(),b.fireEvent(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE)};return BI.each(a,function(g,h){g===a.length-1?(d[g]=[],BI.each(h,function(a,i){if(a===b._getFreezeColLength()-1||a===h.length-1)d[g][a]=i;else if(d[g][a]={type:"bi.resizable_table_cell",cell:i,suitableSize:c.minColumnSize[a],maxSize:c.maxColumnSize[a],resize:BI.bind(e,null,a),stop:BI.bind(f,null,a)},c.isNeedMerge)for(var j=g;j>0&&b._mergeRule(d[j][a],d[j-1][a]);)d[j-1][a]={type:"bi.resizable_table_cell",cell:d[j-1][a],suitableSize:c.minColumnSize[a],maxSize:c.maxColumnSize[a],resize:BI.bind(e,null,a),stop:BI.bind(f,null,a)},j--})):d.push(h)}),d},_populate:function(){var a=(this.options,this._getRegionSize());a>0?(this.regionResizerHandler.setVisible(!0),this._setRegionResizerHandlerPosition(a-3,0)):this.regionResizerHandler.setVisible(!1)},setWidth:function(a){BI.ResizableTable.superclass.setWidth.apply(this,arguments),this.table.setWidth(a)},setHeight:function(a){BI.ResizableTable.superclass.setHeight.apply(this,arguments),this.table.setHeight(a)},setVerticalScroll:function(a){this.table.setVerticalScroll(a)},setLeftHorizontalScroll:function(a){this.table.setLeftHorizontalScroll(a)},setRightHorizontalScroll:function(a){this.table.setRightHorizontalScroll(a)},setColumnSize:function(a){this.options.columnSize=a,this.table.setColumnSize(a)},getColumnSize:function(){return this.table.getColumnSize()},setRegionColumnSize:function(a){this.options.regionColumnSize=a,this.table.setRegionColumnSize(a)},getRegionColumnSize:function(){return this.table.getRegionColumnSize()},getVerticalScroll:function(){return this.table.getVerticalScroll()},getLeftHorizontalScroll:function(){return this.table.getLeftHorizontalScroll()},getRightHorizontalScroll:function(){return this.table.getRightHorizontalScroll()},attr:function(){BI.ResizableTable.superclass.attr.apply(this,arguments),this.table.attr.apply(this.table,arguments)},restore:function(){this.table.restore()},populate:function(a,b){a&&(this.options.items=a),b&&(this.options.header=b,this.options.isNeedResize&&(b=this._formatHeader(b))),this.table.populate(a,b),this._populate()}}),BI.shortcut("bi.resizable_table",BI.ResizableTable),BI.CustomTree=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.CustomTree.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-custom-tree",expander:{el:{},popup:{type:"bi.custom_tree"}},items:[],itemsCreator:BI.emptyFn,el:{type:"bi.button_tree",chooseType:0,layouts:[{type:"bi.vertical"}]}})},_init:function(){BI.CustomTree.superclass._init.apply(this,arguments),this.initTree(this.options.items)},_formatItems:function(a){var b=this,c=this.options;a=BI.Tree.transformToTreeFormat(a);var d=[];return BI.each(a,function(a,e){if(BI.isNotEmptyArray(e.children)||e.isParent===!0){var f=BI.extend({type:"bi.expander",el:{},popup:{type:"bi.custom_tree"}},BI.deepClone(c.expander),{id:e.id,pId:e.pId,value:e.value}),g=BI.stripEL(e);BI.isWidget(g)?f.el=g:(g=BI.clone(g),delete g.children,BI.extend(f.el,g)),f.popup.expander=BI.deepClone(c.expander),f.items=f.popup.items=e.children,f.itemsCreator=f.popup.itemsCreator=function(a){if(BI.isNotNull(a.node))return c.itemsCreator.apply(b,arguments);var d=Array.prototype.slice.call(arguments,0);return d[0].node=e,c.itemsCreator.apply(b,d)},BI.isNull(f.popup.el)&&(f.popup.el=BI.deepClone(c.el)),d.push(f)}else d.push(e)}),d},initTree:function(a){var b=this,c=this.options;this.tree=BI.createWidget(c.el,{element:this,items:this._formatItems(a),itemsCreator:function(a,d){c.itemsCreator.apply(this,[a,function(a){var c=Array.prototype.slice.call(arguments,0);c[0]=b._formatItems(a),d.apply(null,c)}])}}),this.tree.on(BI.Controller.EVENT_CHANGE,function(a,c,d){b.fireEvent(BI.Controller.EVENT_CHANGE,arguments),a===BI.Events.CLICK&&b.fireEvent(BI.CustomTree.EVENT_CHANGE,c,d)})},stroke:function(a){this.populate.apply(this,arguments)},populate:function(a){var b=Array.prototype.slice.call(arguments,0);arguments.length>0&&(b[0]=this._formatItems(a)),this.tree.populate.apply(this.tree,b)},setValue:function(a){this.tree&&this.tree.setValue(a)},getValue:function(){return this.tree?this.tree.getValue():[]},getAllButtons:function(){return this.tree?this.tree.getAllButtons():[]},getAllLeaves:function(){return this.tree?this.tree.getAllLeaves():[]},getNodeById:function(a){return this.tree&&this.tree.getNodeById(a)},getNodeByValue:function(a){return this.tree&&this.tree.getNodeByValue(a)},empty:function(){this.tree.empty()}}),BI.CustomTree.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.custom_tree",BI.CustomTree),function($){var settings={},roots={},caches={},_consts={className:{BUTTON:"button",LEVEL:"level",ICO_LOADING:"ico_loading",SWITCH:"switch"},event:{NODECREATED:"ztree_nodeCreated",CLICK:"ztree_click",EXPAND:"ztree_expand",COLLAPSE:"ztree_collapse",ASYNC_SUCCESS:"ztree_async_success",ASYNC_ERROR:"ztree_async_error",REMOVE:"ztree_remove",SELECTED:"ztree_selected",UNSELECTED:"ztree_unselected"},id:{A:"_a",ICON:"_ico",SPAN:"_span",SWITCH:"_switch",UL:"_ul"},line:{ROOT:"root",ROOTS:"roots",CENTER:"center",BOTTOM:"bottom",NOLINE:"noline",LINE:"line"},folder:{OPEN:"open",CLOSE:"close",DOCU:"docu"},node:{CURSELECTED:"curSelectedNode"}},_setting={treeId:"",treeObj:null,view:{addDiyDom:null,autoCancelSelected:!0,dblClickExpand:!0,expandSpeed:"fast",fontCss:{},nameIsHTML:!1,selectedMulti:!0,showIcon:!0,showLine:!0,showTitle:!0,txtSelectedEnable:!1},data:{key:{children:"children",name:"name",title:"",url:"url"},simpleData:{enable:!1,idKey:"id",pIdKey:"pId",rootPId:null},keep:{parent:!1,leaf:!1}},async:{enable:!1,contentType:"application/x-www-form-urlencoded",type:"post",dataType:"text",url:"",autoParam:[],otherParam:[],dataFilter:null},callback:{beforeAsync:null,beforeClick:null,beforeDblClick:null,beforeRightClick:null,beforeMouseDown:null,beforeMouseUp:null,beforeExpand:null,beforeCollapse:null,beforeRemove:null,onAsyncError:null,onAsyncSuccess:null,onNodeCreated:null,onClick:null,onDblClick:null,onRightClick:null,onMouseDown:null,onMouseUp:null,onExpand:null,onCollapse:null,onRemove:null}},_initRoot=function(a){var b=data.getRoot(a);b||(b={},data.setRoot(a,b)),b[a.data.key.children]=[],b.expandTriggerFlag=!1,b.curSelectedList=[],b.noSelection=!0,b.createdNodes=[],b.zId=0,b._ver=(new Date).getTime()},_initCache=function(a){var b=data.getCache(a);b||(b={},data.setCache(a,b)),b.nodes=[],b.doms=[]},_bindEvent=function(a){var b=a.treeObj,c=consts.event;b.bind(c.NODECREATED,function(b,c,d){tools.apply(a.callback.onNodeCreated,[b,c,d])}),b.bind(c.CLICK,function(b,c,d,e,f){tools.apply(a.callback.onClick,[c,d,e,f])}),b.bind(c.EXPAND,function(b,c,d){tools.apply(a.callback.onExpand,[b,c,d])}),b.bind(c.COLLAPSE,function(b,c,d){tools.apply(a.callback.onCollapse,[b,c,d])}),b.bind(c.ASYNC_SUCCESS,function(b,c,d,e){tools.apply(a.callback.onAsyncSuccess,[b,c,d,e])}),b.bind(c.ASYNC_ERROR,function(b,c,d,e,f,g){tools.apply(a.callback.onAsyncError,[b,c,d,e,f,g])}),b.bind(c.REMOVE,function(b,c,d){tools.apply(a.callback.onRemove,[b,c,d])}),b.bind(c.SELECTED,function(b,c,d,e){tools.apply(a.callback.onSelected,[c,d,e])}),b.bind(c.UNSELECTED,function(b,c,d,e){tools.apply(a.callback.onUnSelected,[c,d,e])})},_unbindEvent=function(a){var b=a.treeObj,c=consts.event;b.unbind(c.NODECREATED).unbind(c.CLICK).unbind(c.EXPAND).unbind(c.COLLAPSE).unbind(c.ASYNC_SUCCESS).unbind(c.ASYNC_ERROR).unbind(c.REMOVE).unbind(c.SELECTED).unbind(c.UNSELECTED)},_eventProxy=function(a){var b=a.target,c=data.getSetting(a.data.treeId),d="",e=null,f="",g="",h=null,i=null,j=null;if(tools.eqs(a.type,"mousedown")?g="mousedown":tools.eqs(a.type,"mouseup")?g="mouseup":tools.eqs(a.type,"contextmenu")?g="contextmenu":tools.eqs(a.type,"click")?tools.eqs(b.tagName,"span")&&null!==b.getAttribute("treeNode"+consts.id.SWITCH)?(d=tools.getNodeMainDom(b).id,f="switchNode"):(j=tools.getMDom(c,b,[{tagName:"a",attrName:"treeNode"+consts.id.A}]),j&&(d=tools.getNodeMainDom(j).id,f="clickNode")):tools.eqs(a.type,"dblclick")&&(g="dblclick",j=tools.getMDom(c,b,[{tagName:"a",attrName:"treeNode"+consts.id.A}]),j&&(d=tools.getNodeMainDom(j).id,f="switchNode")),g.length>0&&0==d.length&&(j=tools.getMDom(c,b,[{tagName:"a",attrName:"treeNode"+consts.id.A}]),j&&(d=tools.getNodeMainDom(j).id)),d.length>0)switch(e=data.getNodeCache(c,d),f){case"switchNode":e.isParent&&(tools.eqs(a.type,"click")||tools.eqs(a.type,"dblclick")&&tools.apply(c.view.dblClickExpand,[c.treeId,e],c.view.dblClickExpand))?h=handler.onSwitchNode:f="";break;case"clickNode":h=handler.onClickNode}switch(g){case"mousedown":i=handler.onZTreeMousedown;break;case"mouseup":i=handler.onZTreeMouseup;break;case"dblclick":i=handler.onZTreeDblclick;break;case"contextmenu":i=handler.onZTreeContextmenu}var k={stop:!1,node:e,nodeEventType:f,nodeEventCallback:h,treeEventType:g,treeEventCallback:i};return k},_initNode=function(a,b,c,d,e,f,g){if(c){var h=data.getRoot(a),i=a.data.key.children;c.level=b,c.tId=a.treeId+"_"+ ++h.zId,c.parentTId=d?d.tId:null,c.open="string"==typeof c.open?tools.eqs(c.open,"true"):!!c.open,c[i]&&c[i].length>0?(c.isParent=!0,c.zAsync=!0):(c.isParent="string"==typeof c.isParent?tools.eqs(c.isParent,"true"):!!c.isParent,c.open=!(!c.isParent||a.async.enable)&&c.open,c.zAsync=!c.isParent),c.isFirstNode=e,c.isLastNode=f,c.getParentNode=function(){return data.getNodeCache(a,c.parentTId)},c.getPreNode=function(){return data.getPreNode(a,c)},c.getNextNode=function(){return data.getNextNode(a,c)},c.isAjaxing=!1,data.fixPIdKeyValue(a,c)}},_init={bind:[_bindEvent],unbind:[_unbindEvent],caches:[_initCache],nodes:[_initNode],proxys:[_eventProxy],roots:[_initRoot],beforeA:[],afterA:[],innerBeforeA:[],innerAfterA:[],zTreeTools:[]},data={addNodeCache:function(a,b){data.getCache(a).nodes[data.getNodeCacheId(b.tId)]=b},getNodeCacheId:function(a){return a.substring(a.lastIndexOf("_")+1)},addAfterA:function(a){_init.afterA.push(a)},addBeforeA:function(a){_init.beforeA.push(a)},addInnerAfterA:function(a){_init.innerAfterA.push(a)},addInnerBeforeA:function(a){_init.innerBeforeA.push(a)},addInitBind:function(a){_init.bind.push(a)},addInitUnBind:function(a){_init.unbind.push(a)},addInitCache:function(a){_init.caches.push(a)},addInitNode:function(a){_init.nodes.push(a)},addInitProxy:function(a,b){b?_init.proxys.splice(0,0,a):_init.proxys.push(a)},addInitRoot:function(a){_init.roots.push(a)},addNodesData:function(a,b,c){var d=a.data.key.children;b[d]||(b[d]=[]),b[d].length>0&&(b[d][b[d].length-1].isLastNode=!1,view.setNodeLineIcos(a,b[d][b[d].length-1])),b.isParent=!0,b[d]=b[d].concat(c)},addSelectedNode:function(a,b){var c=data.getRoot(a);data.isSelectedNode(a,b)||c.curSelectedList.push(b)},addCreatedNode:function(a,b){if(a.callback.onNodeCreated||a.view.addDiyDom){var c=data.getRoot(a);c.createdNodes.push(b)}},addZTreeTools:function(a){_init.zTreeTools.push(a)},exSetting:function(a){$.extend(!0,_setting,a)},fixPIdKeyValue:function(a,b){a.data.simpleData.enable&&(b[a.data.simpleData.pIdKey]=b.parentTId?b.getParentNode()[a.data.simpleData.idKey]:a.data.simpleData.rootPId)},getAfterA:function(a,b,c){for(var d=0,e=_init.afterA.length;d-1&&f.push(b[g]),f=f.concat(data.getNodesByParamFuzzy(a,b[g][e],c,d));return f},getNodesByFilter:function(a,b,c,d,e){if(!b)return d?null:[];for(var f=a.data.key.children,g=d?null:[],h=0,i=b.length;h0)},clone:function(a){if(null===a)return null;var b=tools.isArray(a)?[]:{};for(var c in a)b[c]=a[c]instanceof Date?new Date(a[c].getTime()):"object"==typeof a[c]?arguments.callee(a[c]):a[c];return b},eqs:function(a,b){return a.toLowerCase()===b.toLowerCase()},isArray:function(a){return"[object Array]"===Object.prototype.toString.apply(a)},$:function(a,b,c){return b&&"string"!=typeof b&&(c=b,b=""),"string"==typeof a?$(a,c?c.treeObj.get(0).ownerDocument:null):$("#"+a.tId+b,c?c.treeObj:null)},getMDom:function(a,b,c){if(!b)return null;for(;b&&b.id!==a.treeId;){for(var d=0,e=c.length;b.tagName&&d0},uCanDo:function(a,b){return!0}},view={addNodes:function(a,b,c,d){if(!a.data.keep.leaf||!b||b.isParent)if(tools.isArray(c)||(c=[c]),a.data.simpleData.enable&&(c=data.transformTozTreeFormat(a,c)),b){var e=$$(b,consts.id.SWITCH,a),f=$$(b,consts.id.ICON,a),g=$$(b,consts.id.UL,a);b.open||(view.replaceSwitchClass(b,e,consts.folder.CLOSE),view.replaceIcoClass(b,f,consts.folder.CLOSE),b.open=!1,g.css({display:"none"})),data.addNodesData(a,b,c),view.createNodes(a,b.level+1,c,b),d||view.expandCollapseParentNode(a,b,!0)}else data.addNodesData(a,data.getRoot(a),c),view.createNodes(a,0,c,null)},appendNodes:function(a,b,c,d,e,f){if(!c)return[];for(var g=[],h=a.data.key.children,i=0,j=c.length;i0&&(p=view.appendNodes(a,b+1,k[h],k,e,f&&k.open)),f&&(view.makeDOMNodeMainBefore(g,a,k),view.makeDOMNodeLine(g,a,k),data.getBeforeA(a,k,g),view.makeDOMNodeNameBefore(g,a,k),data.getInnerBeforeA(a,k,g),view.makeDOMNodeIcon(g,a,k),data.getInnerAfterA(a,k,g),view.makeDOMNodeNameAfter(g,a,k),data.getAfterA(a,k,g),k.isParent&&k.open&&view.makeUlHtml(a,k,g,p.join("")),view.makeDOMNodeMainAfter(g,a,k),data.addCreatedNode(a,k))}return g},appendParentULDom:function(a,b){var c=[],d=$$(b,a);!d.get(0)&&b.parentTId&&(view.appendParentULDom(a,b.getParentNode()),d=$$(b,a));var e=$$(b,consts.id.UL,a);e.get(0)&&e.remove();var f=a.data.key.children,g=view.appendNodes(a,b.level+1,b[f],b,!1,!0);view.makeUlHtml(a,b,c,g.join("")),d.append(c.join(""))},asyncNode:function(setting,node,isSilent,callback){var i,l;if(node&&!node.isParent)return tools.apply(callback),!1;if(node&&node.isAjaxing)return!1;if(0==tools.apply(setting.callback.beforeAsync,[setting.treeId,node],!0))return tools.apply(callback),!1;if(node){node.isAjaxing=!0;var icoObj=$$(node,consts.id.ICON,setting);icoObj.attr({style:"","class":consts.className.BUTTON+" "+consts.className.ICO_LOADING})}var tmpParam={};for(i=0,l=setting.async.autoParam.length;node&&i1&&(spKey=pKey[1],pKey=pKey[0]),tmpParam[spKey]=node[pKey]}if(tools.isArray(setting.async.otherParam))for(i=0,l=setting.async.otherParam.length;i=0;d--)if(e=f[d],b===e||!b&&(!c||c!==e)){if($$(e,consts.id.A,a).removeClass(consts.node.CURSELECTED),b){data.removeSelectedNode(a,b),a.treeObj.trigger(consts.event.UNSELECTED,[event,a.treeId,e]);break}f.splice(d,1),a.treeObj.trigger(consts.event.UNSELECTED,[event,a.treeId,e])}},createNodeCallback:function(a){if(a.callback.onNodeCreated||a.view.addDiyDom)for(var b=data.getRoot(a);b.createdNodes.length>0;){var c=b.createdNodes.shift();tools.apply(a.view.addDiyDom,[a.treeId,c]),a.callback.onNodeCreated&&a.treeObj.trigger(consts.event.NODECREATED,[a.treeId,c])}},createNodes:function(a,b,c,d){if(c&&0!=c.length){var e=data.getRoot(a),f=a.data.key.children,g=!d||d.open||!!$$(d[f][0],a).get(0);e.createdNodes=[];var h=view.appendNodes(a,b,c,d,!0,g);if(d){var i=$$(d,consts.id.UL,a);i.get(0)&&i.append(h.join(""))}else a.treeObj.append(h.join(""));view.createNodeCallback(a)}},destroy:function(a){a&&(data.initCache(a),data.initRoot(a),event.unbindTree(a),event.unbindEvent(a),a.treeObj.empty(),delete settings[a.treeId])},expandCollapseNode:function(a,b,c,d,e){var f=data.getRoot(a),g=a.data.key.children;if(!b)return void tools.apply(e,[]);if(f.expandTriggerFlag){var h=e;e=function(){h&&h(),b.open?a.treeObj.trigger(consts.event.EXPAND,[a.treeId,b]):a.treeObj.trigger(consts.event.COLLAPSE,[a.treeId,b])},f.expandTriggerFlag=!1}if(!b.open&&b.isParent&&(!$$(b,consts.id.UL,a).get(0)||b[g]&&b[g].length>0&&!$$(b[g][0],a).get(0))&&(view.appendParentULDom(a,b),view.createNodeCallback(a)),b.open==c)return void tools.apply(e,[]);var i=$$(b,consts.id.UL,a),j=$$(b,consts.id.SWITCH,a),k=$$(b,consts.id.ICON,a);b.isParent?(b.open=!b.open,b.iconOpen&&b.iconClose&&k.attr("style",view.makeNodeIcoStyle(a,b)),b.open?(view.replaceSwitchClass(b,j,consts.folder.OPEN),view.replaceIcoClass(b,k,consts.folder.OPEN),0==d||""==a.view.expandSpeed?(i.show(),tools.apply(e,[])):b[g]&&b[g].length>0?i.slideDown(a.view.expandSpeed,e):(i.show(),tools.apply(e,[]))):(view.replaceSwitchClass(b,j,consts.folder.CLOSE),view.replaceIcoClass(b,k,consts.folder.CLOSE),0!=d&&""!=a.view.expandSpeed&&b[g]&&b[g].length>0?i.slideUp(a.view.expandSpeed,e):(i.hide(),tools.apply(e,[])))):tools.apply(e,[])},expandCollapseParentNode:function(a,b,c,d,e){if(b){if(!b.parentTId)return void view.expandCollapseNode(a,b,c,d,e);view.expandCollapseNode(a,b,c,d),b.parentTId&&view.expandCollapseParentNode(a,b.getParentNode(),c,d,e)}},expandCollapseSonNode:function(a,b,c,d,e){var f=data.getRoot(a),g=a.data.key.children,h=b?b[g]:f[g],i=!b&&d,j=data.getRoot(a).expandTriggerFlag;if(data.getRoot(a).expandTriggerFlag=!1,h)for(var k=0,l=h.length;k=0;c--)if(b===d[c])return!0;return!1},makeDOMNodeIcon:function(a,b,c){var d=data.getNodeName(b,c),e=b.view.nameIsHTML?d:d.replace(/&/g,"&").replace(//g,">");a.push("",e,"")},makeDOMNodeLine:function(a,b,c){a.push("")},makeDOMNodeMainAfter:function(a,b,c){a.push("
  • ")},makeDOMNodeMainBefore:function(a,b,c){a.push("
  • ")},makeDOMNodeNameAfter:function(a,b,c){a.push("")},makeDOMNodeNameBefore:function(a,b,c){var d=data.getNodeTitle(b,c),e=view.makeNodeUrl(b,c),f=view.makeNodeFontCss(b,c),g=[];for(var h in f)g.push(h,":",f[h],";");a.push("0?"href='"+e+"'":""," target='",view.makeNodeTarget(c),"' style='",g.join(""),"'"),tools.apply(b.view.showTitle,[b.treeId,c],b.view.showTitle)&&d&&a.push("title='",d.replace(/'/g,"'").replace(//g,">"),"'"),a.push(">")},makeNodeFontCss:function(a,b){var c=tools.apply(a.view.fontCss,[a.treeId,b],a.view.fontCss);return c&&"function"!=typeof c?c:{}},makeNodeIcoClass:function(a,b){var c=["ico"];return b.isAjaxing||(c[0]=(b.iconSkin?b.iconSkin+"_":"")+c[0],b.isParent?c.push(b.open?consts.folder.OPEN:consts.folder.CLOSE):c.push(consts.folder.DOCU)),consts.className.BUTTON+" "+c.join("_")},makeNodeIcoStyle:function(a,b){var c=[];if(!b.isAjaxing){var d=b.isParent&&b.iconOpen&&b.iconClose?b.open?b.iconOpen:b.iconClose:b.icon;d&&c.push("background:url(",d,") 0 0 no-repeat;"),0!=a.view.showIcon&&tools.apply(a.view.showIcon,[a.treeId,b],!0)||c.push("width:0px;height:0px;")}return c.join("")},makeNodeLineClass:function(a,b){var c=[];return a.view.showLine?0==b.level&&b.isFirstNode&&b.isLastNode?c.push(consts.line.ROOT):0==b.level&&b.isFirstNode?c.push(consts.line.ROOTS):b.isLastNode?c.push(consts.line.BOTTOM):c.push(consts.line.CENTER):c.push(consts.line.NOLINE),b.isParent?c.push(b.open?consts.folder.OPEN:consts.folder.CLOSE):c.push(consts.folder.DOCU),view.makeNodeLineClassEx(b)+c.join("_")},makeNodeLineClassEx:function(a){return consts.className.BUTTON+" "+consts.className.LEVEL+a.level+" "+consts.className.SWITCH+" "},makeNodeTarget:function(a){return a.target||"_blank"},makeNodeUrl:function(a,b){var c=a.data.key.url;return b[c]?b[c]:null},makeUlHtml:function(a,b,c,d){c.push("
      "),c.push(d),c.push("
    ")},makeUlLineClass:function(a,b){return a.view.showLine&&!b.isLastNode?consts.line.LINE:""},removeChildNodes:function(a,b){if(b){var c=a.data.key.children,d=b[c]; -if(d){for(var e=0,f=d.length;e0&&(b[c][0].isFirstNode=!0)},setLastNode:function(a,b){var c=a.data.key.children,d=b[c].length;d>0&&(b[c][d-1].isLastNode=!0)},removeNode:function(a,b){var c=data.getRoot(a),d=a.data.key.children,e=b.parentTId?b.getParentNode():c;if(b.isFirstNode=!1,b.isLastNode=!1,b.getPreNode=function(){return null},b.getNextNode=function(){return null},data.getNodeCache(a,b.tId)){$$(b,a).remove(),data.removeNodeCache(a,b),data.removeSelectedNode(a,b);for(var f=0,g=e[d].length;f0){var l=e[d][k-1];if(h=$$(l,consts.id.UL,a),i=$$(l,consts.id.SWITCH,a),j=$$(l,consts.id.ICON,a),e==c)if(1==e[d].length)view.replaceSwitchClass(l,i,consts.line.ROOT);else{var m=$$(e[d][0],consts.id.SWITCH,a);view.replaceSwitchClass(e[d][0],m,consts.line.ROOTS),view.replaceSwitchClass(l,i,consts.line.BOTTOM)}else view.replaceSwitchClass(l,i,consts.line.BOTTOM);h.removeClass(consts.line.LINE)}}else e.isParent=!1,e.open=!1,h=$$(e,consts.id.UL,a),i=$$(e,consts.id.SWITCH,a),j=$$(e,consts.id.ICON,a),view.replaceSwitchClass(e,i,consts.folder.DOCU),view.replaceIcoClass(e,j,consts.folder.DOCU),h.css("display","none")}},replaceIcoClass:function(a,b,c){if(b&&!a.isAjaxing){var d=b.attr("class");if(void 0!=d){var e=d.split("_");switch(c){case consts.folder.OPEN:case consts.folder.CLOSE:case consts.folder.DOCU:e[e.length-1]=c}b.attr("class",e.join("_"))}}},replaceSwitchClass:function(a,b,c){if(b){var d=b.attr("class");if(void 0!=d){var e=d.split("_");switch(c){case consts.line.ROOT:case consts.line.ROOTS:case consts.line.CENTER:case consts.line.BOTTOM:case consts.line.NOLINE:e[0]=view.makeNodeLineClassEx(a)+c;break;case consts.folder.OPEN:case consts.folder.CLOSE:case consts.folder.DOCU:e[1]=c}b.attr("class",e.join("_")),c!==consts.folder.DOCU?b.removeAttr("disabled"):b.attr("disabled","disabled")}}},selectNode:function(a,b,c){c||view.cancelPreSelectedNode(a,null,b),$$(b,consts.id.A,a).addClass(consts.node.CURSELECTED),data.addSelectedNode(a,b),a.treeObj.trigger(consts.event.SELECTED,[event,a.treeId,b])},setNodeFontCss:function(a,b){var c=$$(b,consts.id.A,a),d=view.makeNodeFontCss(a,b);d&&c.css(d)},setNodeLineIcos:function(a,b){if(b){var c=$$(b,consts.id.SWITCH,a),d=$$(b,consts.id.UL,a),e=$$(b,consts.id.ICON,a),f=view.makeUlLineClass(a,b);0==f.length?d.removeClass(consts.line.LINE):d.addClass(f),c.attr("class",view.makeNodeLineClass(a,b)),b.isParent?c.removeAttr("disabled"):c.attr("disabled","disabled"),e.removeAttr("style"),e.attr("style",view.makeNodeIcoStyle(a,b)),e.attr("class",view.makeNodeIcoClass(a,b))}},setNodeName:function(a,b){var c=data.getNodeTitle(a,b),d=$$(b,consts.id.SPAN,a);if(d.empty(),a.view.nameIsHTML?d.html(data.getNodeName(a,b)):d.text(data.getNodeName(a,b)),tools.apply(a.view.showTitle,[a.treeId,b],a.view.showTitle)){var e=$$(b,consts.id.A,a);e.attr("title",c?c:"")}},setNodeTarget:function(a,b){var c=$$(b,consts.id.A,a);c.attr("target",view.makeNodeTarget(b))},setNodeUrl:function(a,b){var c=$$(b,consts.id.A,a),d=view.makeNodeUrl(a,b);null==d||0==d.length?c.removeAttr("href"):c.attr("href",d)},switchNode:function(a,b){if(b.open||!tools.canAsync(a,b))view.expandCollapseNode(a,b,!b.open);else if(a.async.enable){if(!view.asyncNode(a,b))return void view.expandCollapseNode(a,b,!b.open)}else b&&view.expandCollapseNode(a,b,!b.open)}};$.fn.zTree={consts:_consts,_z:{tools:tools,view:view,event:event,data:data},getZTreeObj:function(a){var b=data.getZTreeTools(a);return b?b:null},destroy:function(a){if(a&&a.length>0)view.destroy(data.getSetting(a));else for(var b in settings)view.destroy(settings[b])},init:function(a,b,c){var d=tools.clone(_setting);$.extend(!0,d,b),d.treeId=a.attr("id"),d.treeObj=a,d.treeObj.empty(),settings[d.treeId]=d,"undefined"==typeof document.body.style.maxHeight&&(d.view.expandSpeed=""),data.initRoot(d);var e=data.getRoot(d),f=d.data.key.children;c=c?tools.clone(tools.isArray(c)?c:[c]):[],d.data.simpleData.enable?e[f]=data.transformTozTreeFormat(d,c):e[f]=c,data.initCache(d),event.unbindTree(d),event.bindTree(d),event.unbindEvent(d),event.bindEvent(d);var g={setting:d,addNodes:function(a,b,c){function e(){view.addNodes(d,a,f,1==c)}if(!b)return null;if(a||(a=null),a&&!a.isParent&&d.data.keep.leaf)return null;var f=tools.clone(tools.isArray(b)?b:[b]);return tools.canAsync(d,a)?view.asyncNode(d,a,c,e):e(),f},cancelSelectedNode:function(a){view.cancelPreSelectedNode(d,a)},destroy:function(){view.destroy(d)},expandAll:function(a){return a=!!a,view.expandCollapseSonNode(d,null,a,!0),a},expandNode:function(a,b,c,e,f){if(!a||!a.isParent)return null;if(b!==!0&&b!==!1&&(b=!a.open),f=!!f,f&&b&&0==tools.apply(d.callback.beforeExpand,[d.treeId,a],!0))return null;if(f&&!b&&0==tools.apply(d.callback.beforeCollapse,[d.treeId,a],!0))return null;if(b&&a.parentTId&&view.expandCollapseParentNode(d,a.getParentNode(),b,!1),b===a.open&&!c)return null;if(data.getRoot(d).expandTriggerFlag=f,!tools.canAsync(d,a)&&c)view.expandCollapseSonNode(d,a,b,!0,function(){if(e!==!1)try{$$(a,d).focus().blur()}catch(b){}});else if(a.open=!b,view.switchNode(this.setting,a),e!==!1)try{$$(a,d).focus().blur()}catch(g){}return b},getNodes:function(){return data.getNodes(d)},getNodeByParam:function(a,b,c){return a?data.getNodeByParam(d,c?c[d.data.key.children]:data.getNodes(d),a,b):null},getNodeByTId:function(a){return data.getNodeCache(d,a)},getNodesByParam:function(a,b,c){return a?data.getNodesByParam(d,c?c[d.data.key.children]:data.getNodes(d),a,b):null},getNodesByParamFuzzy:function(a,b,c){return a?data.getNodesByParamFuzzy(d,c?c[d.data.key.children]:data.getNodes(d),a,b):null},getNodesByFilter:function(a,b,c,e){return b=!!b,a&&"function"==typeof a?data.getNodesByFilter(d,c?c[d.data.key.children]:data.getNodes(d),a,b,e):b?null:[]},getNodeIndex:function(a){if(!a)return null;for(var b=d.data.key.children,c=a.parentTId?a.getParentNode():data.getRoot(d),e=0,f=c[b].length;e0?view.createNodes(d,0,e[f]):d.async.enable&&d.async.url&&""!==d.async.url&&view.asyncNode(d),g}};var zt=$.fn.zTree,$$=tools.$,consts=zt.consts}(jQuery),function(a){var b={event:{CHECK:"ztree_check"},id:{CHECK:"_check"},checkbox:{STYLE:"checkbox",DEFAULT:"chk",DISABLED:"disable",FALSE:"false",TRUE:"true",FULL:"full",PART:"part",FOCUS:"focus"},radio:{STYLE:"radio",TYPE_ALL:"all",TYPE_LEVEL:"level"}},c={check:{enable:!1,autoCheckTrigger:!1,chkStyle:b.checkbox.STYLE,nocheckInherit:!1,chkDisabledInherit:!1,radioType:b.radio.TYPE_LEVEL,chkboxType:{Y:"ps",N:"ps"}},data:{key:{checked:"checked"}},callback:{beforeCheck:null,onCheck:null}},d=function(a){var b=v.getRoot(a);b.radioCheckedList=[]},e=function(a){},f=function(a){var b=a.treeObj,c=t.event;b.bind(c.CHECK,function(b,c,d,e){b.srcEvent=c,s.apply(a.callback.onCheck,[b,d,e])})},g=function(a){var b=a.treeObj,c=t.event;b.unbind(c.CHECK)},h=function(a){var b=a.target,c=v.getSetting(a.data.treeId),d="",e=null,f="",g="",h=null,i=null;if(s.eqs(a.type,"mouseover")?c.check.enable&&s.eqs(b.tagName,"span")&&null!==b.getAttribute("treeNode"+t.id.CHECK)&&(d=s.getNodeMainDom(b).id,f="mouseoverCheck"):s.eqs(a.type,"mouseout")?c.check.enable&&s.eqs(b.tagName,"span")&&null!==b.getAttribute("treeNode"+t.id.CHECK)&&(d=s.getNodeMainDom(b).id,f="mouseoutCheck"):s.eqs(a.type,"click")&&c.check.enable&&s.eqs(b.tagName,"span")&&null!==b.getAttribute("treeNode"+t.id.CHECK)&&(d=s.getNodeMainDom(b).id,f="checkNode"),d.length>0)switch(e=v.getNodeCache(c,d),f){case"checkNode":h=n.onCheckNode;break;case"mouseoverCheck":h=n.onMouseoverCheck;break;case"mouseoutCheck":h=n.onMouseoutCheck}var j={stop:"checkNode"===f,node:e,nodeEventType:f,nodeEventCallback:h,treeEventType:g,treeEventCallback:i};return j},i=function(a,b,c,d,e,f,g){if(c){var h=a.data.key.checked;if("string"==typeof c[h]&&(c[h]=s.eqs(c[h],"true")),c[h]=!!c[h],c.checkedOld=c[h],"string"==typeof c.nocheck&&(c.nocheck=s.eqs(c.nocheck,"true")),c.nocheck=!!c.nocheck||a.check.nocheckInherit&&d&&!!d.nocheck,"string"==typeof c.chkDisabled&&(c.chkDisabled=s.eqs(c.chkDisabled,"true")),c.chkDisabled=!!c.chkDisabled||a.check.chkDisabledInherit&&d&&!!d.chkDisabled,"string"==typeof c.halfCheck&&(c.halfCheck=s.eqs(c.halfCheck,"true")),c.halfCheck=!!c.halfCheck,c.check_Child_State=-1,c.check_Focus=!1,c.getCheckStatus=function(){return v.getCheckStatus(a,c)},a.check.chkStyle==t.radio.STYLE&&a.check.radioType==t.radio.TYPE_ALL&&c[h]){var i=v.getRoot(a);i.radioCheckedList.push(c)}}},j=function(a,b,c){a.data.key.checked;a.check.enable&&(v.makeChkFlag(a,b),c.push(""))},k=function(a,b){b.checkNode=function(a,b,c,d){var e=this.setting.data.key.checked;if(a.chkDisabled!==!0&&(b!==!0&&b!==!1&&(b=!a[e]),d=!!d,(a[e]!==b||c)&&(!d||0!=s.apply(this.setting.callback.beforeCheck,[this.setting.treeId,a],!0))&&s.uCanDo(this.setting)&&this.setting.check.enable&&a.nocheck!==!0)){a[e]=b;var f=w(a,t.id.CHECK,this.setting);(c||this.setting.check.chkStyle===t.radio.STYLE)&&u.checkNodeRelation(this.setting,a),u.setChkClass(this.setting,f,a),u.repairParentChkClassWithSelf(this.setting,a),d&&this.setting.treeObj.trigger(t.event.CHECK,[null,this.setting.treeId,a])}},b.checkAllNodes=function(a){u.repairAllChk(this.setting,!!a)},b.getCheckedNodes=function(a){var b=this.setting.data.key.children;return a=a!==!1,v.getTreeCheckedNodes(this.setting,v.getRoot(this.setting)[b],a)},b.getChangeCheckedNodes=function(){var a=this.setting.data.key.children;return v.getTreeChangeCheckedNodes(this.setting,v.getRoot(this.setting)[a])},b.setChkDisabled=function(a,b,c,d){b=!!b,c=!!c,d=!!d,u.repairSonChkDisabled(this.setting,a,b,d),u.repairParentChkDisabled(this.setting,a.getParentNode(),b,c)};var c=b.updateNode;b.updateNode=function(a,d){if(c&&c.apply(b,arguments),a&&this.setting.check.enable){var e=w(a,this.setting);if(e.get(0)&&s.uCanDo(this.setting)){var f=w(a,t.id.CHECK,this.setting);1!=d&&this.setting.check.chkStyle!==t.radio.STYLE||u.checkNodeRelation(this.setting,a),u.setChkClass(this.setting,f,a),u.repairParentChkClassWithSelf(this.setting,a)}}}},l={getRadioCheckedList:function(a){for(var b=v.getRoot(a).radioCheckedList,c=0,d=b.length;c-1&&b.check_Child_State<2:b.check_Child_State>0};return d},getTreeCheckedNodes:function(a,b,c,d){if(!b)return[];var e=a.data.key.children,f=a.data.key.checked,g=c&&a.check.chkStyle==t.radio.STYLE&&a.check.radioType==t.radio.TYPE_ALL;d=d?d:[];for(var h=0,i=b.length;h0));h++);return d},getTreeChangeCheckedNodes:function(a,b,c){if(!b)return[];var d=a.data.key.children,e=a.data.key.checked;c=c?c:[];for(var f=0,g=b.length;f0?2:0,2==i){e=2;break}0==i&&(e=0)}else if(a.check.chkStyle==t.checkbox.STYLE){if(i=h.nocheck===!0||h.chkDisabled===!0?h.check_Child_State:h.halfCheck===!0?1:h[d]?h.check_Child_State===-1||2===h.check_Child_State?2:1:h.check_Child_State>0?1:0,1===i){e=1;break}if(2===i&&e>-1&&f>0&&i!==e){e=1;break}if(2===e&&i>-1&&i<2){e=1;break}i>-1&&(e=i)}}b.check_Child_State=e}}},m={},n={onCheckNode:function(a,b){if(b.chkDisabled===!0)return!1;var c=v.getSetting(a.data.treeId),d=c.data.key.checked;if(0==s.apply(c.callback.beforeCheck,[c.treeId,b],!0))return!0;b[d]=!b[d],u.checkNodeRelation(c,b);var e=w(b,t.id.CHECK,c);return u.setChkClass(c,e,b),u.repairParentChkClassWithSelf(c,b),c.treeObj.trigger(t.event.CHECK,[a,c.treeId,b]),!0},onMouseoverCheck:function(a,b){if(b.chkDisabled===!0)return!1;var c=v.getSetting(a.data.treeId),d=w(b,t.id.CHECK,c);return b.check_Focus=!0,u.setChkClass(c,d,b),!0},onMouseoutCheck:function(a,b){if(b.chkDisabled===!0)return!1;var c=v.getSetting(a.data.treeId),d=w(b,t.id.CHECK,c);return b.check_Focus=!1,u.setChkClass(c,d,b),!0}},o={},p={checkNodeRelation:function(a,b){var c,d,e,f=a.data.key.children,g=a.data.key.checked,h=t.radio;if(a.check.chkStyle==h.STYLE){var i=v.getRadioCheckedList(a);if(b[g])if(a.check.radioType==h.TYPE_ALL){for(d=i.length-1;d>=0;d--)c=i[d],c[g]&&c!=b&&(c[g]=!1,i.splice(d,1),u.setChkClass(a,w(c,t.id.CHECK,a),c),c.parentTId!=b.parentTId&&u.repairParentChkClassWithSelf(a,c));i.push(b)}else{var j=b.parentTId?b.getParentNode():v.getRoot(a);for(d=0,e=j[f].length;d-1)&&u.setSonNodeCheckBox(a,b,!0),b[g]||b[f]&&0!=b[f].length&&!(a.check.chkboxType.N.indexOf("s")>-1)||u.setSonNodeCheckBox(a,b,!1),b[g]&&a.check.chkboxType.Y.indexOf("p")>-1&&u.setParentNodeCheckBox(a,b,!0),!b[g]&&a.check.chkboxType.N.indexOf("p")>-1&&u.setParentNodeCheckBox(a,b,!1)},makeChkClass:function(a,b){var c=a.data.key.checked,d=t.checkbox,e=t.radio,f="";f=b.chkDisabled===!0?d.DISABLED:b.halfCheck?d.PART:a.check.chkStyle==e.STYLE?b.check_Child_State<1?d.FULL:d.PART:b[c]?2===b.check_Child_State||b.check_Child_State===-1?d.FULL:d.PART:b.check_Child_State<1?d.FULL:d.PART;var g=a.check.chkStyle+"_"+(b[c]?d.TRUE:d.FALSE)+"_"+f;return g=b.check_Focus&&b.chkDisabled!==!0?g+"_"+d.FOCUS:g,t.className.BUTTON+" "+d.DEFAULT+" "+g},repairAllChk:function(a,b){if(a.check.enable&&a.check.chkStyle===t.checkbox.STYLE)for(var c=a.data.key.checked,d=a.data.key.children,e=v.getRoot(a),f=0,g=e[d].length;f0?u.repairParentChkClass(a,b[c][0]):u.repairParentChkClass(a,b)}},repairSonChkDisabled:function(a,b,c,d){if(b){var e=a.data.key.children;if(b.chkDisabled!=c&&(b.chkDisabled=c),u.repairChkClass(a,b),b[e]&&d)for(var f=0,g=b[e].length;f0){h=!1;break}h&&u.setParentNodeCheckBox(a,b.getParentNode(),c,d)}},setSonNodeCheckBox:function(a,b,c,d){if(b){var e=a.data.key.children,f=a.data.key.checked,g=w(b,t.id.CHECK,a);d||(d=b);var h=!1;if(b[e])for(var i=0,j=b[e].length;i0?c?2:0:-1)):b.check_Child_State=-1,u.setChkClass(a,g,b),a.check.autoCheckTrigger&&b!=d&&b.nocheck!==!0&&b.chkDisabled!==!0&&a.treeObj.trigger(t.event.CHECK,[null,a.treeId,b]))}}},q={tools:o,view:p,event:m,data:l};a.extend(!0,a.fn.zTree.consts,b),a.extend(!0,a.fn.zTree._z,q);var r=a.fn.zTree,s=r._z.tools,t=r.consts,u=r._z.view,v=r._z.data,w=(r._z.event,s.$);v.exSetting(c),v.addInitBind(f),v.addInitUnBind(g),v.addInitCache(e),v.addInitNode(i),v.addInitProxy(h,!0),v.addInitRoot(d),v.addBeforeA(j),v.addZTreeTools(k);var x=u.createNodes;u.createNodes=function(a,b,c,d){x&&x.apply(u,arguments),c&&u.repairParentChkClassWithSelf(a,d)};var y=u.removeNode;u.removeNode=function(a,b){var c=b.getParentNode();y&&y.apply(u,arguments),b&&c&&(u.repairChkClass(a,c),u.repairParentChkClass(a,c))};var z=u.appendNodes;u.appendNodes=function(a,b,c,d,e,f){var g="";return z&&(g=z.apply(u,arguments)),d&&v.makeChkFlag(a,d),g}}(jQuery),BI.IconChangeButton=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.IconChangeButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:"bi-icon-change-button",iconClass:"",iconWidth:null,iconHeight:null,stopEvent:!1,stopPropagation:!1,selected:!1,once:!1,forceSelected:!1,forceNotSelected:!1,disableSelected:!1,shadow:!1,isShadowShowingOnSelected:!1,trigger:null,handler:BI.emptyFn})},_init:function(){BI.IconChangeButton.superclass._init.apply(this,arguments);var a=this,b=this.options;this.button=BI.createWidget({type:"bi.icon_button",element:this,cls:b.iconClass,height:b.height,iconWidth:b.iconWidth,iconHeight:b.iconHeight,stopEvent:b.stopEvent,stopPropagation:b.stopPropagation,selected:b.selected,once:b.once,forceSelected:b.forceSelected,forceNotSelected:b.forceNotSelected,disableSelected:b.disableSelected,shadow:b.shadow,isShadowShowingOnSelected:b.isShadowShowingOnSelected,trigger:b.trigger,handler:b.handler}),this.button.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.button.on(BI.IconButton.EVENT_CHANGE,function(){a.fireEvent(BI.IconChangeButton.EVENT_CHANGE,arguments)})},isSelected:function(){return this.button.isSelected()},setSelected:function(a){this.button.setSelected(a)},setIcon:function(a){var b=this.options;b.iconClass!==a&&(this.element.removeClass(b.iconClass).addClass(a),b.iconClass=a)}}),BI.IconChangeButton.EVENT_CHANGE="IconChangeButton.EVENT_CHANGE",BI.shortcut("bi.icon_change_button",BI.IconChangeButton),BI.HalfIconButton=BI.inherit(BI.IconButton,{_defaultConfig:function(){var a=BI.HalfIconButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-half-icon-button check-half-select-icon",height:16,width:16,iconWidth:16,iconHeight:16,selected:!1})},_init:function(){BI.HalfIconButton.superclass._init.apply(this,arguments)},doClick:function(){BI.HalfIconButton.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.HalfIconButton.EVENT_CHANGE)}}),BI.HalfIconButton.EVENT_CHANGE="HalfIconButton.EVENT_CHANGE",BI.shortcut("bi.half_icon_button",BI.HalfIconButton),BI.TriggerIconButton=BI.inherit(BI.IconButton,{_defaultConfig:function(){var a=BI.TriggerIconButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-trigger-icon-button",extraCls:"pull-down-font"})},_init:function(){BI.TriggerIconButton.superclass._init.apply(this,arguments)},doClick:function(){BI.TriggerIconButton.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.TriggerIconButton.EVENT_CHANGE,this)}}),BI.TriggerIconButton.EVENT_CHANGE="TriggerIconButton.EVENT_CHANGE",BI.shortcut("bi.trigger_icon_button",BI.TriggerIconButton),BI.MultiSelectItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MultiSelectItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-multi-select-item",height:25,logic:{dynamic:!1}})},_init:function(){BI.MultiSelectItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.checkbox"}),this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,rgap:b.rgap,text:b.text,keyword:b.keyword,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected())}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(b.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",{type:"bi.center_adapt",items:[this.checkbox],width:36},this.text)}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.MultiSelectItem.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected()),this.isValid()&&this.fireEvent(BI.MultiSelectItem.EVENT_CHANGE,this.getValue(),this)},setSelected:function(a){BI.MultiSelectItem.superclass.setSelected.apply(this,arguments),this.checkbox.setSelected(a)}}),BI.MultiSelectItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multi_select_item",BI.MultiSelectItem),BI.SingleSelectIconTextItem=BI.inherit(BI.Single,{_defaultConfig:function(){return BI.extend(BI.SingleSelectIconTextItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-single-select-icon-text-item bi-list-item-active",iconClass:"",hgap:10,height:25})},_init:function(){BI.SingleSelectIconTextItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.text=BI.createWidget({type:"bi.icon_text_item",element:this,cls:b.iconClass,once:b.once,selected:b.selected,height:b.height,iconHeight:b.iconHeight,iconWidth:b.iconWidth,text:b.text,keyword:b.keyword,value:b.value,py:b.py}),this.text.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)})},isSelected:function(){return this.text.isSelected()},setSelected:function(a){this.text.setSelected(a)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.SingleSelectIconTextItem.superclass.doClick.apply(this,arguments)}}),BI.shortcut("bi.single_select_icon_text_item",BI.SingleSelectIconTextItem),BI.SingleSelectItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.SingleSelectItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-single-select-item bi-list-item-active",hgap:10,height:25,textAlign:"left"})},_init:function(){BI.SingleSelectItem.superclass._init.apply(this,arguments);var a=this.options;this.text=BI.createWidget({type:"bi.label",element:this,textAlign:a.textAlign,whiteSpace:"nowrap",textHeight:a.height,height:a.height,hgap:a.hgap,text:a.text,keyword:a.keyword,value:a.value,py:a.py})},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.SingleSelectItem.superclass.doClick.apply(this,arguments)},setSelected:function(a){BI.SingleSelectItem.superclass.setSelected.apply(this,arguments)}}),BI.shortcut("bi.single_select_item",BI.SingleSelectItem),BI.SingleSelectRadioItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.SingleSelectRadioItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-single-select-radio-item bi-list-item-active",logic:{dynamic:!1},hgap:10,height:25})},_init:function(){BI.SingleSelectRadioItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.radio=BI.createWidget({type:"bi.radio"}),this.radio.on(BI.Controller.EVENT_CHANGE,function(b){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,keyword:b.keyword,value:b.value,py:b.py}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(b.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",{type:"bi.center_adapt",items:[this.radio],width:36},this.text)}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.SingleSelectRadioItem.superclass.doClick.apply(this,arguments),this.radio.setSelected(this.isSelected())},setSelected:function(a){BI.SingleSelectRadioItem.superclass.setSelected.apply(this,arguments),this.radio.setSelected(a)}}),BI.shortcut("bi.single_select_radio_item",BI.SingleSelectRadioItem),BI.ArrowNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.ArrowNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-arrow-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){var a=this,b=this.options;BI.ArrowNode.superclass._init.apply(this,arguments),this.checkbox=BI.createWidget({type:"bi.arrow_tree_group_node_checkbox",iconWidth:13,iconHeight:13}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.ArrowNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isOpened())},setValue:function(a){this.text.setValue(a)},setOpened:function(a){BI.ArrowNode.superclass.setOpened.apply(this,arguments),this.checkbox.setSelected(a)}}),BI.shortcut("bi.arrow_group_node",BI.ArrowNode),BI.FirstPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.FirstPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-first-plus-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.FirstPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.first_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.FirstPlusGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.FirstPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.first_plus_group_node",BI.FirstPlusGroupNode),BI.IconArrowNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.IconArrowNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-icon-arrow-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25,iconHeight:13,iconWidth:13,iconCls:""})},_init:function(){BI.IconArrowNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.tree_group_node_checkbox",width:23,stopPropagation:!0});var c=BI.createWidget({type:"bi.center_adapt",cls:b.iconCls,width:23,items:[{type:"bi.icon",height:b.iconHeight,width:b.iconWidth}]});this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var d=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),e=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},{width:23,el:c},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(d,BI.extend(b.logic,{items:e}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.IconArrowNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.IconArrowNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.icon_arrow_node",BI.IconArrowNode),BI.LastPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.LastPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-last-plus-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"", -open:!1,height:25})},_init:function(){BI.LastPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.last_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.LastPlusGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.LastPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.last_plus_group_node",BI.LastPlusGroupNode),BI.MidPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MidPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-mid-plus-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.MidPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.mid_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.MidPlusGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.MidPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.mid_plus_group_node",BI.MidPlusGroupNode),BI.MultiLayerIconArrowNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MultiLayerIconArrowNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-multilayer-icon-arrow-node bi-list-item",layer:0,id:"",pId:"",open:!1,height:25,iconHeight:13,iconWidth:13,iconCls:""})},_init:function(){BI.MultiLayerIconArrowNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.node=BI.createWidget({type:"bi.icon_arrow_node",iconCls:b.iconCls,id:b.id,pId:b.pId,open:b.open,height:b.height,iconHeight:b.iconHeight,iconWidth:b.iconWidth,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.node.on(BI.Controller.EVENT_CHANGE,function(b){a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",width:13,height:b.height})}),c.push(this.node),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},isOnce:function(){return!0},doRedMark:function(){this.node.doRedMark.apply(this.node,arguments)},unRedMark:function(){this.node.unRedMark.apply(this.node,arguments)},isSelected:function(){return this.node.isSelected()},setSelected:function(a){BI.MultiLayerIconArrowNode.superclass.setSelected.apply(this,arguments),this.node.setSelected(a)},doClick:function(){BI.NodeButton.superclass.doClick.apply(this,arguments),this.node.setSelected(this.isSelected())},setOpened:function(a){BI.MultiLayerIconArrowNode.superclass.setOpened.apply(this,arguments),this.node.setOpened(a)}}),BI.shortcut("bi.multilayer_icon_arrow_node",BI.MultiLayerIconArrowNode),BI.PlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.PlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-plus-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.PlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.tree_node_checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.PlusGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.PlusGroupNode.superclass.setOpened.apply(this,arguments),this.checkbox&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.plus_group_node",BI.PlusGroupNode),BI.TriangleGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.TriangleGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-triangle-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.TriangleGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({iconWidth:13,iconHeight:13,type:"bi.tree_group_node_checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py,keyword:b.keyword}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.TriangleGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isOpened())},setOpened:function(a){BI.TriangleGroupNode.superclass.setOpened.apply(this,arguments),this.checkbox.setSelected(a)},setText:function(a){BI.TriangleGroupNode.superclass.setText.apply(this,arguments),this.text.setText(a)}}),BI.shortcut("bi.triangle_group_node",BI.TriangleGroupNode),BI.FirstTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.FirstTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-first-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",layer:0,height:25})},_init:function(){BI.FirstTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,0===b.layer?"":{width:13,el:{type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height}},{width:25,el:{type:"bi.layout",cls:"mid-line-conn-background",width:25,height:b.height}},{el:this.text});BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.FirstTreeLeafItem.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setSelected:function(a){BI.FirstTreeLeafItem.superclass.setSelected.apply(this,arguments),this.checkbox.setSelected(a)}}),BI.shortcut("bi.first_tree_leaf_item",BI.FirstTreeLeafItem),BI.IconTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.IconTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-icon-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},height:25,iconWidth:16,iconHeight:16,iconCls:""})},_init:function(){BI.IconTreeLeafItem.superclass._init.apply(this,arguments);var a=this.options,b=BI.createWidget({type:"bi.center_adapt",width:23,cls:a.iconCls,items:[{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}]});this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:a.height,height:a.height,hgap:a.hgap,text:a.text,value:a.value,py:a.py});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:23,el:b},{el:this.text});BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(a.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.IconTreeLeafItem.superclass.doClick.apply(this,arguments)},setSelected:function(a){BI.IconTreeLeafItem.superclass.setSelected.apply(this,arguments)}}),BI.shortcut("bi.icon_tree_leaf_item",BI.IconTreeLeafItem),BI.LastTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.LastTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-last-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",layer:0,height:25})},_init:function(){BI.LastTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,0===b.layer?"":{width:13,el:{type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height}},{width:25,el:{type:"bi.layout",cls:"mid-line-conn-background",width:25,height:b.height}},{el:this.text});BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.LastTreeLeafItem.superclass.doClick.apply(this,arguments)},setSelected:function(a){BI.LastTreeLeafItem.superclass.setSelected.apply(this,arguments)}}),BI.shortcut("bi.last_tree_leaf_item",BI.LastTreeLeafItem),BI.MidTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MidTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-mid-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",layer:0,height:25})},_init:function(){BI.MidTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,0===b.layer?"":{width:13,el:{type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height}},{width:25,el:{type:"bi.layout",cls:"mid-line-conn-background",width:25,height:b.height}},{el:this.text});BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.MidTreeLeafItem.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setSelected:function(a){BI.MidTreeLeafItem.superclass.setSelected.apply(this,arguments),this.checkbox.setSelected(a)}}),BI.shortcut("bi.mid_tree_leaf_item",BI.MidTreeLeafItem),BI.MultiLayerIconTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MultiLayerIconTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-multilayer-icon-tree-leaf-item bi-list-item-active",layer:0,height:25,iconCls:"",iconHeight:14,iconWidth:12})},_init:function(){BI.MultiLayerIconTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.item=BI.createWidget({type:"bi.icon_tree_leaf_item",cls:"bi-list-item-none",iconCls:b.iconCls,id:b.id,pId:b.pId,isFront:!0,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py,iconWidth:b.iconWidth,iconHeight:b.iconHeight}),this.item.on(BI.Controller.EVENT_CHANGE,function(b){b!==BI.Events.CLICK&&a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",width:13,height:b.height})}),c.push(this.item),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.item.doRedMark.apply(this.item,arguments)},unRedMark:function(){this.item.unRedMark.apply(this.item,arguments)},doHighLight:function(){this.item.doHighLight.apply(this.item,arguments)},unHighLight:function(){this.item.unHighLight.apply(this.item,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.MultiLayerIconTreeLeafItem.superclass.doClick.apply(this,arguments),this.item.setSelected(this.isSelected())},setSelected:function(a){BI.MultiLayerIconTreeLeafItem.superclass.setSelected.apply(this,arguments),this.item.setSelected(a)},getValue:function(){return this.options.value}}),BI.shortcut("bi.multilayer_icon_tree_leaf_item",BI.MultiLayerIconTreeLeafItem),BI.TreeTextLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.TreeTextLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-tree-text-leaf-item bi-list-item-active",id:"",pId:"",height:25,hgap:0,lgap:0,rgap:0})},_init:function(){BI.TreeTextLeafItem.superclass._init.apply(this,arguments);var a=this.options;this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:a.height,height:a.height,hgap:a.hgap,lgap:a.lgap,rgap:a.hgap,text:a.text,value:a.value,py:a.py}),BI.createWidget({type:"bi.htape",element:this,items:[{el:this.text}]})},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId}}),BI.shortcut("bi.tree_text_leaf_item",BI.TreeTextLeafItem),BI.Calendar=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.Calendar.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:"bi-calendar",logic:{dynamic:!1},min:"1900-01-01",max:"2099-12-31",year:2015,month:7,day:25})},_dateCreator:function(a,b,c){var d=this.options,e={},f=Date.getDate(),g=d.min.match(/\d+/g),h=d.max.match(/\d+/g);a<(0|g[0])&&(a=0|g[0]),a>(0|h[0])&&(a=0|h[0]),f.setFullYear(a,b,c),e.ymd=[f.getFullYear(),f.getMonth(),f.getDate()];var i=Date._MD.slice(0);i[1]=Date.isLeap(e.ymd[0])?29:28,f.setFullYear(e.ymd[0],e.ymd[1],1),e.FDay=f.getDay(),e.PDay=i[0===b?11:b-1]-e.FDay+1,e.NDay=1;var j=[];return BI.each(BI.range(42),function(a){var b,c={},d=e.ymd[0],f=e.ymd[1]+1;a=e.FDay&&a=0?c%12:(12+c%12)%12;return{year:Date.getDate().getFullYear()+d,month:e}}}),BI.shortcut("bi.calendar",BI.Calendar),BI.YearCalendar=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.YearCalendar.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:"bi-year-calendar",behaviors:{},logic:{dynamic:!1},min:"1900-01-01",max:"2099-12-31",year:null})},_yearCreator:function(a){var b=this.options;a=0|a;var c=BI.YearCalendar.getStartYear(a),d=[];return BI.each(BI.range(BI.YearCalendar.INTERVAL),function(a){var e={};Date.checkVoid(c+a,1,1,b.min,b.max)[0]&&(e.disabled=!0),e.text=c+a,d.push(e)}),d},_init:function(){BI.YearCalendar.superclass._init.apply(this,arguments);var a=this,b=this.options;this.currentYear=Date.getDate().getFullYear();var c=this._yearCreator(b.year||this.currentYear),d=c.length,e=BI.makeArray(d,""),f=[0,6,1,7,2,8,3,9,4,10,5,11];BI.each(c,function(a,b){e[a]=c[f[a]]});var g=[];g.push(e.slice(0,2)),g.push(e.slice(2,4)),g.push(e.slice(4,6)),g.push(e.slice(6,8)),g.push(e.slice(8,10)),g.push(e.slice(10,12)),g=BI.map(g,function(a,b){return BI.map(b,function(a,b){return BI.extend(b,{type:"bi.text_item",cls:"bi-list-item-active",textAlign:"center",whiteSpace:"normal",once:!1,forceSelected:!0,height:23,width:38,value:b.text,disabled:b.disabled})})}),this.years=BI.createWidget({type:"bi.button_group",behaviors:b.behaviors,items:BI.createItems(g,{}),layouts:[BI.LogicFactory.createLogic("table",BI.extend({},b.logic,{columns:2,rows:6,columnSize:[.5,.5],rowSize:25})),{type:"bi.center_adapt",vgap:1}]}),this.years.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("vertical",BI.extend({},b.logic,{items:BI.LogicFactory.createLogicItemsByDirection("top",this.years)}))))},isFrontYear:function(){var a=this.options,b=a.year;return b=0|b,!!Date.checkVoid(BI.YearCalendar.getStartYear(b)-1,1,1,a.min,a.max)[0]},isFinalYear:function(){var a=this.options,b=(this._const,a.year);return b=0|b,!!Date.checkVoid(BI.YearCalendar.getEndYear(b)+1,1,1,a.min,a.max)[0]},setValue:function(a){this.years.setValue([a])},getValue:function(){return this.years.getValue()[0]}}),BI.extend(BI.YearCalendar,{INTERVAL:12,getStartYear:function(a){var b=Date.getDate().getFullYear();return a-((a-b+3)%BI.YearCalendar.INTERVAL+12)%BI.YearCalendar.INTERVAL},getEndYear:function(a){return BI.YearCalendar.getStartYear(a)+BI.YearCalendar.INTERVAL},getPageByYear:function(a){var b=Date.getDate().getFullYear();return a=BI.YearCalendar.getStartYear(a),(a-b+3)/BI.YearCalendar.INTERVAL}}),BI.shortcut("bi.year_calendar",BI.YearCalendar),BI.ComplexCanvas=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.ComplexCanvas.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-complex-canvas"})},_init:function(){BI.ComplexCanvas.superclass._init.apply(this,arguments);var a=this.options;this.canvas=BI.createWidget({type:"bi.canvas",element:this,width:a.width,height:a.height})},branch:function(a,b,c,d,e,f){var g=this,h=[].slice.call(arguments);if(h.length<=5)return this.canvas.line.apply(this.canvas,arguments);var i;BI.isOdd(h.length)&&(i=BI.last(h),h=BI.initial(h)),h=[].slice.call(h,2);var j=BI.filter(h,function(a){return a%2===0}),k=BI.filter(h,function(a){return a%2!==0});i||(i={});var l=i.offset||20;if(b>d&&b>f||bd&&b>f)var m=Math.max.apply(this,k)+l;else var m=Math.min.apply(this,k)-l;var n=Math.min.apply(this,j),o=BI.indexOf(j,n),p=Math.max.apply(this,j),q=BI.indexOf(j,p);return this.canvas.line(n,k[o],n,m,p,m,p,k[q],i),BI.each(j,function(a,b){a!==q&&a!==o&&g.canvas.line(b,k[a],b,m,i)}),void this.canvas.line(a,m,a,b,i)}if(a>c&&a>e||ac&&a>e)var r=Math.max.apply(this,j)+l;else var r=Math.min.apply(this,j)-l;var s=Math.min.apply(this,k),t=BI.indexOf(k,s),u=Math.max.apply(this,k),v=BI.indexOf(k,u);return this.canvas.line(j[t],s,r,s,r,u,j[v],u,i),BI.each(k,function(a,b){a!==t&&a!==v&&g.canvas.line(j[a],b,r,b,i)}),void this.canvas.line(r,b,a,b,i)}},stroke:function(a){this.canvas.stroke(a)}}),BI.shortcut("bi.complex_canvas",BI.ComplexCanvas),BI.ArrowTreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.ArrowTreeGroupNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-arrow-tree-group-node",iconWidth:13,iconHeight:13})},_init:function(){BI.ArrowTreeGroupNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.ArrowTreeGroupNodeCheckbox.superclass.setSelected.apply(this,arguments),a?this.element.removeClass("column-next-page-h-font").addClass("column-pre-page-h-font"):this.element.removeClass("column-pre-page-h-font").addClass("column-next-page-h-font")}}),BI.shortcut("bi.arrow_tree_group_node_checkbox",BI.ArrowTreeGroupNodeCheckbox),BI.CheckingMarkNode=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.CheckingMarkNode.superclass._defaultConfig.apply(this,arguments),{extraCls:"check-mark-font",iconWidth:13,iconHeight:13})},_init:function(){BI.CheckingMarkNode.superclass._init.apply(this,arguments),this.setSelected(this.options.selected)},setSelected:function(a){BI.CheckingMarkNode.superclass.setSelected.apply(this,arguments),a===!0?this.element.addClass("check-mark-font"):this.element.removeClass("check-mark-font")}}),BI.shortcut("bi.checking_mark_node",BI.CheckingMarkNode),BI.FirstTreeNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.FirstTreeNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-collapse-icon-type2",iconWidth:25,iconHeight:25})},_init:function(){BI.FirstTreeNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.FirstTreeNodeCheckbox.superclass.setSelected.apply(this,arguments),a===!0?this.element.addClass("tree-expand-icon-type2"):this.element.removeClass("tree-expand-icon-type2")}}),BI.shortcut("bi.first_tree_node_checkbox",BI.FirstTreeNodeCheckbox),BI.LastTreeNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.LastTreeNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-collapse-icon-type4",iconWidth:25,iconHeight:25})},_init:function(){BI.LastTreeNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.LastTreeNodeCheckbox.superclass.setSelected.apply(this,arguments),a===!0?this.element.addClass("tree-expand-icon-type3"):this.element.removeClass("tree-expand-icon-type3")}}),BI.shortcut("bi.last_tree_node_checkbox",BI.LastTreeNodeCheckbox),BI.MidTreeNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.MidTreeNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-collapse-icon-type3",iconWidth:25,iconHeight:25})},_init:function(){BI.MidTreeNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.MidTreeNodeCheckbox.superclass.setSelected.apply(this,arguments),a===!0?this.element.addClass("tree-expand-icon-type3"):this.element.removeClass("tree-expand-icon-type3")}}),BI.shortcut("bi.mid_tree_node_checkbox",BI.MidTreeNodeCheckbox),BI.TreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.TreeGroupNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-node-triangle-collapse-font",iconWidth:13,iconHeight:13})},_init:function(){BI.TreeGroupNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.TreeGroupNodeCheckbox.superclass.setSelected.apply(this,arguments),a?this.element.removeClass("tree-node-triangle-collapse-font").addClass("tree-node-triangle-expand-font"):this.element.removeClass("tree-node-triangle-expand-font").addClass("tree-node-triangle-collapse-font")}}),BI.shortcut("bi.tree_group_node_checkbox",BI.TreeGroupNodeCheckbox),BI.TreeNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.TreeNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-collapse-icon-type1",iconWidth:25,iconHeight:25})},_init:function(){BI.TreeNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.TreeNodeCheckbox.superclass.setSelected.apply(this,arguments),a?this.element.addClass("tree-expand-icon-type1"):this.element.removeClass("tree-expand-icon-type1")}}),BI.shortcut("bi.tree_node_checkbox",BI.TreeNodeCheckbox);try{!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.Clipboard=a()}}(function(){var a;return function b(a,c,d){function e(g,h){if(!c[g]){if(!a[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};a[g][0].call(k.exports,function(b){var c=a[g][1][b];return e(c?c:b)},k,k.exports,b,a,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g0&&void 0!==arguments[0]?arguments[0]:{};this.action=a.action,this.emitter=a.emitter,this.target=a.target,this.text=a.text,this.trigger=a.trigger,this.selectedText=""}},{key:"initSelection",value:function(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function(){var a=this,b="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return a.removeFake()},this.fakeHandler=document.body.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[b?"right":"left"]="-9999px";var c=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=c+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,document.body.appendChild(this.fakeElem),this.selectedText=(0,e["default"])(this.fakeElem),this.copyText()}},{key:"removeFake",value:function(){this.fakeHandler&&(document.body.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function(){this.selectedText=(0,e["default"])(this.target),this.copyText()}},{key:"copyText",value:function(){var a=void 0;try{a=document.execCommand(this.action)}catch(b){a=!1}this.handleResult(a)}},{key:"handleResult",value:function(a){this.emitter.emit(a?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function(){this.removeFake()}},{key:"action",set:function(){var a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=a,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function(){return this._action}},{key:"target",set:function(a){if(void 0!==a){if(!a||"object"!==("undefined"==typeof a?"undefined":f(a))||1!==a.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&a.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(a.hasAttribute("readonly")||a.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=a}},get:function(){return this._target}}]),a}();a.exports=h})},{select:5}],8:[function(b,c,d){!function(e,f){if("function"==typeof a&&a.amd)a(["module","./clipboard-action","tiny-emitter","good-listener"],f);else if("undefined"!=typeof d)f(c,b("./clipboard-action"),b("tiny-emitter"),b("good-listener"));else{var g={exports:{}};f(g,e.clipboardAction,e.tinyEmitter,e.goodListener),e.clipboard=g.exports}}(this,function(a,b,c,d){"use strict";function e(a){return a&&a.__esModule?a:{"default":a}}function f(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function g(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function h(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function i(a,b){var c="data-clipboard-"+a;if(b.hasAttribute(c))return b.getAttribute(c)}var j=e(b),k=e(c),l=e(d),m=function(){function a(a,b){for(var c=0;c0&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof a.action?a.action:this.defaultAction,this.target="function"==typeof a.target?a.target:this.defaultTarget,this.text="function"==typeof a.text?a.text:this.defaultText}},{key:"listenClick",value:function(a){var b=this;this.listener=(0,l["default"])(a,"click",function(a){return b.onClick(a)})}},{key:"onClick",value:function(a){var b=a.delegateTarget||a.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new j["default"]({action:this.action(b),target:this.target(b),text:this.text(b),trigger:b,emitter:this})}},{key:"defaultAction",value:function(a){return i("action",a)}},{key:"defaultTarget",value:function(a){var b=i("target",a);if(b)return document.querySelector(b)}},{key:"defaultText",value:function(a){return i("text",a)}},{key:"destroy",value:function(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function(){var a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["copy","cut"],b="string"==typeof a?[a]:a,c=!!document.queryCommandSupported;return b.forEach(function(a){c=c&&!!document.queryCommandSupported(a)}),c}}]),b}(k["default"]);a.exports=n})},{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8)})}catch(e){!function(a){a.fn.zclip=function(b){if("object"==typeof b&&!b.length){var c=a.extend({path:"ZeroClipboard.swf",copy:null,beforeCopy:null,afterCopy:null,clickAfter:!0,setHandCursor:!0,setCSSEffects:!0},b);return this.each(function(){var b=a(this);if(b.is(":visible")&&("string"==typeof c.copy||a.isFunction(c.copy))){ZeroClipboard.setMoviePath(c.path);var d=new ZeroClipboard.Client;a.isFunction(c.copy)&&b.bind("zClip_copy",c.copy),a.isFunction(c.beforeCopy)&&b.bind("zClip_beforeCopy",c.beforeCopy),a.isFunction(c.afterCopy)&&b.bind("zClip_afterCopy",c.afterCopy),d.setHandCursor(c.setHandCursor),d.setCSSEffects(c.setCSSEffects),d.addEventListener("mouseOver",function(a){b.trigger("mouseenter")}),d.addEventListener("mouseOut",function(a){b.trigger("mouseleave")}),d.addEventListener("mouseDown",function(e){b.trigger("mousedown"),a.isFunction(c.copy)?d.setText(b.triggerHandler("zClip_copy")):d.setText(c.copy),a.isFunction(c.beforeCopy)&&b.trigger("zClip_beforeCopy")}),d.addEventListener("complete",function(d,e){a.isFunction(c.afterCopy)?b.trigger("zClip_afterCopy"):(e.length>500&&(e=e.substr(0,500)+"...\n\n("+(e.length-500)+" characters not shown)"),b.removeClass("hover"),alert("Copied text to clipboard:\n\n "+e)),c.clickAfter&&b.trigger("click")}),d.glue(b[0],b.parent()[0]),a(window).bind("load resize",function(){d.reposition()})}})}if("string"==typeof b)return this.each(function(){var c=a(this);b=b.toLowerCase();var d=c.data("zclipId"),e=a("#"+d+".zclip");"remove"==b?(e.remove(),c.removeClass("active hover")):"hide"==b?(e.hide(),c.removeClass("active hover")):"show"==b&&e.show()})}}(jQuery);var ZeroClipboard={version:"1.0.7",clients:{},moviePath:"ZeroClipboard.swf",nextId:1,$:function(a){return"string"==typeof a&&(a=document.getElementById(a)),a.addClass||(a.hide=function(){this.style.display="none"},a.show=function(){this.style.display=""},a.addClass=function(a){this.removeClass(a),this.className+=" "+a},a.removeClass=function(a){for(var b=this.className.split(/\s+/),c=-1,d=0;d-1&&(b.splice(c,1),this.className=b.join(" ")),this},a.hasClass=function(a){return!!this.className.match(new RegExp("\\s*"+a+"\\s*"))}),a},setMoviePath:function(a){this.moviePath=a},dispatch:function(a,b,c){var d=this.clients[a];d&&d.receiveEvent(b,c)},register:function(a,b){this.clients[a]=b},getDOMObjectPosition:function(a,b){var c={left:0,top:0,width:a.width?a.width:a.offsetWidth,height:a.height?a.height:a.offsetHeight};return a&&a!=b&&(c.left+=a.offsetLeft,c.top+=a.offsetTop),c},Client:function(a){this.handlers={},this.id=ZeroClipboard.nextId++,this.movieId="ZeroClipboardMovie_"+this.id,ZeroClipboard.register(this.id,this),a&&this.glue(a)}};ZeroClipboard.Client.prototype={id:0,ready:!1,movie:null,clipText:"",handCursorEnabled:!0,cssEffects:!0,handlers:null,glue:function(a,b,c){this.domElement=ZeroClipboard.$(a);var d=99;this.domElement.style.zIndex&&(d=parseInt(this.domElement.style.zIndex,10)+1),"string"==typeof b?b=ZeroClipboard.$(b):"undefined"==typeof b&&(b=document.getElementsByTagName("body")[0]);var e=ZeroClipboard.getDOMObjectPosition(this.domElement,b);this.div=document.createElement("div"),this.div.className="zclip",this.div.id="zclip-"+this.movieId,$(this.domElement).data("zclipId","zclip-"+this.movieId);var f=this.div.style;if(f.position="absolute",f.left=""+e.left+"px",f.top=""+e.top+"px",f.width=""+e.width+"px",f.height=""+e.height+"px",f.zIndex=d,"object"==typeof c)for(addedStyle in c)f[addedStyle]=c[addedStyle];b.appendChild(this.div),this.div.innerHTML=this.getHTML(e.width,e.height)},getHTML:function(a,b){var c="",d="id="+this.id+"&width="+a+"&height="+b;if(navigator.userAgent.match(/MSIE/)){var e=location.href.match(/^https/i)?"https://":"http://";c+=''}else c+='';return c},hide:function(){this.div&&(this.div.style.left="-2000px")},show:function(){this.reposition()},destroy:function(){if(this.domElement&&this.div){this.hide(),this.div.innerHTML="";var a=document.getElementsByTagName("body")[0];try{a.removeChild(this.div)}catch(b){}this.domElement=null,this.div=null}},reposition:function(a){if(a&&(this.domElement=ZeroClipboard.$(a),this.domElement||this.hide()),this.domElement&&this.div){var b=ZeroClipboard.getDOMObjectPosition(this.domElement),c=this.div.style;c.left=""+b.left+"px",c.top=""+b.top+"px"}},setText:function(a){this.clipText=a,this.ready&&this.movie.setText(a)},addEventListener:function(a,b){a=a.toString().toLowerCase().replace(/^on/,""),this.handlers[a]||(this.handlers[a]=[]),this.handlers[a].push(b)},setHandCursor:function(a){this.handCursorEnabled=a,this.ready&&this.movie.setHandCursor(a)},setCSSEffects:function(a){this.cssEffects=!!a},receiveEvent:function(a,b){switch(a=a.toString().toLowerCase().replace(/^on/,"")){case"load":if(this.movie=document.getElementById(this.movieId),!this.movie){var c=this;return void setTimeout(function(){c.receiveEvent("load",null)},1)}if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){var c=this;return setTimeout(function(){c.receiveEvent("load",null)},100),void(this.ready=!0)}this.ready=!0;try{this.movie.setText(this.clipText)}catch(d){}try{this.movie.setHandCursor(this.handCursorEnabled)}catch(d){}break;case"mouseover":this.domElement&&this.cssEffects&&(this.domElement.addClass("hover"),this.recoverActive&&this.domElement.addClass("active"));break;case"mouseout":this.domElement&&this.cssEffects&&(this.recoverActive=!1,this.domElement.hasClass("active")&&(this.domElement.removeClass("active"),this.recoverActive=!0),this.domElement.removeClass("hover"));break;case"mousedown":this.domElement&&this.cssEffects&&this.domElement.addClass("active");break;case"mouseup":this.domElement&&this.cssEffects&&(this.domElement.removeClass("active"),this.recoverActive=!1)}if(this.handlers[a])for(var e=0,f=this.handlers[a].length;e=0&&(0|a)<=255},d=BI.createWidgets([{},{},{}],{type:"bi.small_text_editor",cls:"color-picker-editor-input",validationChecker:c,errorText:BI.i18nText("BI-Color_Picker_Error_Text"),allowBlank:!0,value:255,width:32,height:20});BI.each(d,function(b,c){c.on(BI.TextEditor.EVENT_CHANGE,function(){a.R.isValid()&&a.G.isValid()&&a.B.isValid()&&(a.colorShow.element.css("background-color",a.getValue()),a.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE))})}),this.R=d[0],this.G=d[1],this.B=d[2],this.none=BI.createWidget({type:"bi.checkbox",title:BI.i18nText("BI-Basic_Auto")}),this.none.on(BI.Checkbox.EVENT_CHANGE,function(){this.isSelected()?(a.lastColor=a.getValue(),a.setValue("")):a.setValue(a.lastColor||"#000000"),a.R.isValid()&&a.G.isValid()&&a.B.isValid()&&(a.colorShow.element.css("background-color",a.getValue()),a.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE))}),this.transparent=BI.createWidget({type:"bi.checkbox",title:BI.i18nText("BI-Transparent_Color")}),this.transparent.on(BI.Checkbox.EVENT_CHANGE,function(){this.isSelected()?(a.lastColor=a.getValue(),a.setValue("transparent")):a.setValue(a.lastColor||"#000000"),a.R.isValid()&&a.G.isValid()&&a.B.isValid()&&(a.colorShow.element.css("background-color",a.getValue()),a.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE))}),BI.createWidget({type:"bi.htape",element:this,items:[{el:this.colorShow,width:"fill"},{el:b[0],lgap:10,width:16},{el:this.R,width:32},{el:b[1],lgap:10,width:16},{el:this.G,width:32},{el:b[2],lgap:10,width:16},{el:this.B,width:32},{el:{type:"bi.center_adapt",items:[this.none]},width:18},{el:{type:"bi.center_adapt",items:[this.transparent]},width:18}]})},setValue:function(a){if("transparent"===a)return this.transparent.setSelected(!0),this.none.setSelected(!1),this.R.setValue(""),this.G.setValue(""),void this.B.setValue("");a?this.none.setSelected(!1):(a="",this.none.setSelected(!0)),this.transparent.setSelected(!1),this.colorShow.element.css("background-color",a);var b=BI.DOM.rgb2json(BI.DOM.hex2rgb(a));this.R.setValue(BI.isNull(b.r)?"":b.r),this.G.setValue(BI.isNull(b.g)?"":b.g),this.B.setValue(BI.isNull(b.b)?"":b.b)},getValue:function(){return this.transparent.isSelected()?"transparent":BI.DOM.rgb2hex(BI.DOM.json2rgb({r:this.R.getValue(),g:this.G.getValue(),b:this.B.getValue()}))}}),BI.ColorPickerEditor.EVENT_CHANGE="ColorPickerEditor.EVENT_CHANGE",BI.shortcut("bi.color_picker_editor",BI.ColorPickerEditor),BI.Farbtastic=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.Farbtastic.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-farbtastic",width:195,height:195})},_init:function(){BI.Farbtastic.superclass._init.apply(this,arguments)},mounted:function(){var a=this;this.farbtastic=$.farbtastic(this.element,function(b){a.fireEvent(BI.Farbtastic.EVENT_CHANGE,a.getValue(),a)})},setValue:function(a){this.farbtastic.setColor(a)},getValue:function(){return this.farbtastic.color}}),BI.Farbtastic.EVENT_CHANGE="Farbtastic.EVENT_CHANGE",BI.shortcut("bi.farbtastic",BI.Farbtastic),jQuery.fn.farbtastic=function(a){return $.farbtastic(this,a),this},jQuery.farbtastic=function(a,b){var a=$(a).get(0);return a.farbtastic||(a.farbtastic=new jQuery._farbtastic(a,b))},jQuery._farbtastic=function(a,b){var c=this;$(a).html('
    ');var d=$(".farbtastic",a);c.wheel=$(".wheel",a).get(0),c.radius=84,c.square=100,c.width=194,navigator.appVersion.match(/MSIE [0-6]\./)&&$("*",d).each(function(){if("none"!=this.currentStyle.backgroundImage){var a=this.currentStyle.backgroundImage;a=this.currentStyle.backgroundImage.substring(5,a.length-2),$(this).css({backgroundImage:"none",filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+a+"')"})}}),c.linkTo=function(a){return"object"==typeof c.callback&&$(c.callback).unbind("keyup",c.updateValue),c.color=null,"function"==typeof a?c.callback=a:"object"!=typeof a&&"string"!=typeof a||(c.callback=$(a),c.callback.bind("keyup",c.updateValue),c.callback.get(0).value&&c.setColor(c.callback.get(0).value)),this},c.updateValue=function(a){this.value&&this.value!=c.color&&c.setColor(this.value)},c.setColor=function(a){var b=c.unpack(a);return c.color!=a&&b&&(c.color=a,c.rgb=b,c.hsl=c.RGBToHSL(c.rgb),c.updateDisplay()),this},c.setHSL=function(a){return c.hsl=a,c.rgb=c.HSLToRGB(a),c.color=c.pack(c.rgb),c.updateDisplay(),this},c.widgetCoords=function(a){var b,d,e=a.target||a.srcElement,f=c.wheel;if("undefined"!=typeof a.offsetX){for(var g={x:a.offsetX,y:a.offsetY},h=e;h;)h.mouseX=g.x,h.mouseY=g.y,g.x+=h.offsetLeft,g.y+=h.offsetTop,h=h.offsetParent;for(var h=f,i={x:0,y:0};h;){if("undefined"!=typeof h.mouseX){b=h.mouseX-i.x,d=h.mouseY-i.y;break}i.x+=h.offsetLeft,i.y+=h.offsetTop,h=h.offsetParent}for(h=e;h;)h.mouseX=void 0,h.mouseY=void 0,h=h.offsetParent}else{var g=c.absolutePosition(f);b=(a.pageX||0*(a.clientX+$("html").get(0).scrollLeft))-g.x,d=(a.pageY||0*(a.clientY+$("html").get(0).scrollTop))-g.y}return{x:b-c.width/2,y:d-c.width/2}},c.click=function(a){var b=c.widgetCoords(a);return c.circleDrag=2*Math.max(Math.abs(b.x),Math.abs(b.y))>c.square,c.mousemove(a),!1},c.mousemove=function(a){var b=c.widgetCoords(a);if(c.circleDrag){var d=Math.atan2(b.x,-b.y)/6.28;d<0&&(d+=1),c.setHSL([d,c.hsl[1],c.hsl[2]])}else{var e=Math.max(0,Math.min(1,-(b.x/c.square)+.5)),f=Math.max(0,Math.min(1,-(b.y/c.square)+.5));c.setHSL([c.hsl[0],e,f])}return!1},c.updateDisplay=function(){var a=6.28*c.hsl[0];$(".h-marker",d).css({left:Math.round(Math.sin(a)*c.radius+c.width/2)+"px",top:Math.round(-Math.cos(a)*c.radius+c.width/2)+"px"}),$(".sl-marker",d).css({left:Math.round(c.square*(.5-c.hsl[1])+c.width/2)+"px",top:Math.round(c.square*(.5-c.hsl[2])+c.width/2)+"px"}),$(".color",d).css("backgroundColor",c.pack(c.HSLToRGB([c.hsl[0],1,.5]))),"object"==typeof c.callback?($(c.callback).css({backgroundColor:c.color,color:c.hsl[2]>.5?"#000":"#fff"}),$(c.callback).each(function(){this.value&&this.value!=c.color&&(this.value=c.color); +var K=d.matrix||new n,L={_:{transform:G.transform},getBBox:function(){return d.getBBox(1)}};r[z]=[K.a,K.b,K.c,K.d,K.e,K.f],La(L,s[z]),s[z]=L._.transform,t[z]=[(L.matrix.a-K.a)/q,(L.matrix.b-K.b)/q,(L.matrix.c-K.c)/q,(L.matrix.d-K.d)/q,(L.matrix.e-K.e)/q,(L.matrix.f-K.f)/q]}break;case"csv":var M=H(i[z])[I](v),N=H(r[z])[I](v);if("clip-rect"==z)for(r[z]=N,t[z]=[],w=N.length;w--;)t[z][w]=(M[w]-r[z][w])/q;s[z]=M;break;default:for(M=[][D](i[z]),N=[][D](r[z]),t[z]=[],w=d.paper.customAttributes[z].length;w--;)t[z][w]=((M[w]||0)-(N[w]||0))/q}var O=i.easing,P=b.easing_formulas[O];if(!P)if(P=H(O).match(Y),P&&5==P.length){var Q=P;P=function(a){return p(a,+Q[1],+Q[2],+Q[3],+Q[4],q)}}else P=la;if(o=i.start||c.start||+new Date,u={anim:c,percent:e,timestamp:o,start:o+(c.del||0),status:0,initstatus:f||0,stop:!1,ms:q,easing:P,from:r,diff:t,to:s,el:d,callback:i.callback,prev:m,next:l,repeat:h||c.times,origin:d.attr(),totalOrigin:g},fb.push(u),f&&!j&&!k&&(u.stop=!0,u.start=new Date-q*f,1==fb.length))return hb();k&&(u.start=new Date-u.ms*f),1==fb.length&&gb(hb)}a("raphael.anim.start."+d.id,d,c)}}function s(a){for(var b=0;b',qa=ra.firstChild,qa.style.behavior="url(#default#VML)",!qa||"object"!=typeof qa.adj)return b.type=F;ra=null}b.svg=!(b.vml="VML"==b.type),b._Paper=B,b.fn=u=B.prototype=b.prototype,b._id=0,b._oid=0,b.is=function(a,b){return b=L.call(b),"finite"==b?!X[y](+a):"array"==b?a instanceof Array:"null"==b&&null===a||b===typeof a&&null!==a||"object"==b&&a===Object(a)||"array"==b&&Array.isArray&&Array.isArray(a)||V.call(a).slice(8,-1).toLowerCase()==b},b.angle=function(a,c,d,e,f,g){if(null==f){var h=a-d,i=c-e;return h||i?(180+180*M.atan2(-i,-h)/R+360)%360:0}return b.angle(a,c,f,g)-b.angle(d,e,f,g)},b.rad=function(a){return a%360*R/180},b.deg=function(a){return Math.round(180*a/R%360*1e3)/1e3},b.snapTo=function(a,c,d){if(d=b.is(d,"finite")?d:10,b.is(a,U)){for(var e=a.length;e--;)if(P(a[e]-c)<=d)return a[e]}else{a=+a;var f=c%a;if(fa-d)return c-f+a}return c};b.createUUID=function(a,b){return function(){return"xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx".replace(a,b).toUpperCase()}}(/[xy]/g,function(a){var b=16*M.random()|0,c="x"==a?b:3&b|8;return c.toString(16)});b.setWindow=function(c){a("raphael.setWindow",b,z.win,c),z.win=c,z.doc=z.win.document,b._engine.initWin&&b._engine.initWin(z.win)};var sa=function(a){if(b.vml){var c,d=/^\s+|\s+$/g;try{var f=new ActiveXObject("htmlfile");f.write(""),f.close(),c=f.body}catch(g){c=createPopup().document.body}var h=c.createTextRange();sa=e(function(a){try{c.style.color=H(a).replace(d,F);var b=h.queryCommandValue("ForeColor");return b=(255&b)<<16|65280&b|(16711680&b)>>>16,"#"+("000000"+b.toString(16)).slice(-6)}catch(e){return"none"}})}else{var i=z.doc.createElement("i");i.title="Raphaël Colour Picker",i.style.display="none",z.doc.body.appendChild(i),sa=e(function(a){return i.style.color=a,z.doc.defaultView.getComputedStyle(i,F).getPropertyValue("color")})}return sa(a)},ta=function(){return"hsb("+[this.h,this.s,this.b]+")"},ua=function(){return"hsl("+[this.h,this.s,this.l]+")"},va=function(){return this.hex},wa=function(a,c,d){if(null==c&&b.is(a,"object")&&"r"in a&&"g"in a&&"b"in a&&(d=a.b,c=a.g,a=a.r),null==c&&b.is(a,T)){var e=b.getRGB(a);a=e.r,c=e.g,d=e.b}return(a>1||c>1||d>1)&&(a/=255,c/=255,d/=255),[a,c,d]},xa=function(a,c,d,e){a*=255,c*=255,d*=255;var f={r:a,g:c,b:d,hex:b.rgb(a,c,d),toString:va};return b.is(e,"finite")&&(f.opacity=e),f};b.color=function(a){var c;return b.is(a,"object")&&"h"in a&&"s"in a&&"b"in a?(c=b.hsb2rgb(a),a.r=c.r,a.g=c.g,a.b=c.b,a.hex=c.hex):b.is(a,"object")&&"h"in a&&"s"in a&&"l"in a?(c=b.hsl2rgb(a),a.r=c.r,a.g=c.g,a.b=c.b,a.hex=c.hex):(b.is(a,"string")&&(a=b.getRGB(a)),b.is(a,"object")&&"r"in a&&"g"in a&&"b"in a?(c=b.rgb2hsl(a),a.h=c.h,a.s=c.s,a.l=c.l,c=b.rgb2hsb(a),a.v=c.b):(a={hex:"none"},a.r=a.g=a.b=a.h=a.s=a.v=a.l=-1)),a.toString=va,a},b.hsb2rgb=function(a,b,c,d){this.is(a,"object")&&"h"in a&&"s"in a&&"b"in a&&(c=a.b,b=a.s,d=a.o,a=a.h),a*=360;var e,f,g,h,i;return a=a%360/60,i=c*b,h=i*(1-P(a%2-1)),e=f=g=c-i,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a],xa(e,f,g,d)},b.hsl2rgb=function(a,b,c,d){this.is(a,"object")&&"h"in a&&"s"in a&&"l"in a&&(c=a.l,b=a.s,a=a.h),(a>1||b>1||c>1)&&(a/=360,b/=100,c/=100),a*=360;var e,f,g,h,i;return a=a%360/60,i=2*b*(c<.5?c:1-c),h=i*(1-P(a%2-1)),e=f=g=c-i/2,a=~~a,e+=[i,h,0,0,h,i][a],f+=[h,i,i,h,0,0][a],g+=[0,0,h,i,i,h][a],xa(e,f,g,d)},b.rgb2hsb=function(a,b,c){c=wa(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g;return f=N(a,b,c),g=f-O(a,b,c),d=0==g?null:f==a?(b-c)/g:f==b?(c-a)/g+2:(a-b)/g+4,d=(d+360)%6*60/360,e=0==g?0:g/f,{h:d,s:e,b:f,toString:ta}},b.rgb2hsl=function(a,b,c){c=wa(a,b,c),a=c[0],b=c[1],c=c[2];var d,e,f,g,h,i;return g=N(a,b,c),h=O(a,b,c),i=g-h,d=0==i?null:g==a?(b-c)/i:g==b?(c-a)/i+2:(a-b)/i+4,d=(d+360)%6*60/360,f=(g+h)/2,e=0==i?0:f<.5?i/(2*f):i/(2-2*f),{h:d,s:e,l:f,toString:ua}},b._path2string=function(){return this.join(",").replace(fa,"$1")};b._preload=function(a,b){var c=z.doc.createElement("img");c.style.cssText="position:absolute;left:-9999em;top:-9999em",c.onload=function(){b.call(this),this.onload=null,z.doc.body.removeChild(this)},c.onerror=function(){z.doc.body.removeChild(this)},z.doc.body.appendChild(c),c.src=a};b.getRGB=e(function(a){if(!a||(a=H(a)).indexOf("-")+1)return{r:-1,g:-1,b:-1,hex:"none",error:1,toString:f};if("none"==a)return{r:-1,g:-1,b:-1,hex:"none",toString:f};!(ea[y](a.toLowerCase().substring(0,2))||"#"==a.charAt())&&(a=sa(a));var c,d,e,g,h,i,j=a.match(W);return j?(j[2]&&(e=_(j[2].substring(5),16),d=_(j[2].substring(3,5),16),c=_(j[2].substring(1,3),16)),j[3]&&(e=_((h=j[3].charAt(3))+h,16),d=_((h=j[3].charAt(2))+h,16),c=_((h=j[3].charAt(1))+h,16)),j[4]&&(i=j[4][I](da),c=$(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=$(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),e=$(i[2]),"%"==i[2].slice(-1)&&(e*=2.55),"rgba"==j[1].toLowerCase().slice(0,4)&&(g=$(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100)),j[5]?(i=j[5][I](da),c=$(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=$(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),e=$(i[2]),"%"==i[2].slice(-1)&&(e*=2.55),("deg"==i[0].slice(-3)||"°"==i[0].slice(-1))&&(c/=360),"hsba"==j[1].toLowerCase().slice(0,4)&&(g=$(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100),b.hsb2rgb(c,d,e,g)):j[6]?(i=j[6][I](da),c=$(i[0]),"%"==i[0].slice(-1)&&(c*=2.55),d=$(i[1]),"%"==i[1].slice(-1)&&(d*=2.55),e=$(i[2]),"%"==i[2].slice(-1)&&(e*=2.55),("deg"==i[0].slice(-3)||"°"==i[0].slice(-1))&&(c/=360),"hsla"==j[1].toLowerCase().slice(0,4)&&(g=$(i[3])),i[3]&&"%"==i[3].slice(-1)&&(g/=100),b.hsl2rgb(c,d,e,g)):(j={r:c,g:d,b:e,toString:f},j.hex="#"+(16777216|e|d<<8|c<<16).toString(16).slice(1),b.is(g,"finite")&&(j.opacity=g),j)):{r:-1,g:-1,b:-1,hex:"none",error:1,toString:f}},b),b.hsb=e(function(a,c,d){return b.hsb2rgb(a,c,d).hex}),b.hsl=e(function(a,c,d){return b.hsl2rgb(a,c,d).hex}),b.rgb=e(function(a,b,c){function d(a){return a+.5|0}return"#"+(16777216|d(c)|d(b)<<8|d(a)<<16).toString(16).slice(1)}),b.getColor=function(a){var b=this.getColor.start=this.getColor.start||{h:0,s:1,b:a||.75},c=this.hsb2rgb(b.h,b.s,b.b);return b.h+=.075,b.h>1&&(b.h=0,b.s-=.2,b.s<=0&&(this.getColor.start={h:0,s:1,b:b.b})),c.hex},b.getColor.reset=function(){delete this.start},b.parsePathString=function(a){if(!a)return null;var c=ya(a);if(c.arr)return Aa(c.arr);var d={a:7,c:6,h:1,l:2,m:2,r:4,q:4,s:4,t:2,v:1,z:0},e=[];return b.is(a,U)&&b.is(a[0],U)&&(e=Aa(a)),e.length||H(a).replace(ga,function(a,b,c){var f=[],g=b.toLowerCase();if(c.replace(ia,function(a,b){b&&f.push(+b)}),"m"==g&&f.length>2&&(e.push([b][D](f.splice(0,2))),g="l",b="m"==b?"l":"L"),"r"==g)e.push([b][D](f));else for(;f.length>=d[g]&&(e.push([b][D](f.splice(0,d[g]))),d[g]););}),e.toString=b._path2string,c.arr=Aa(e),e},b.parseTransformString=e(function(a){if(!a)return null;var c=[];return b.is(a,U)&&b.is(a[0],U)&&(c=Aa(a)),c.length||H(a).replace(ha,function(a,b,d){var e=[];L.call(b);d.replace(ia,function(a,b){b&&e.push(+b)}),c.push([b][D](e))}),c.toString=b._path2string,c});var ya=function(a){var b=ya.ps=ya.ps||{};return b[a]?b[a].sleep=100:b[a]={sleep:100},setTimeout(function(){for(var c in b)b[y](c)&&c!=a&&(b[c].sleep--,!b[c].sleep&&delete b[c])}),b[a]};b.findDotsAtSegment=function(a,b,c,d,e,f,g,h,i){var j=1-i,k=Q(j,3),l=Q(j,2),m=i*i,n=m*i,o=k*a+3*l*i*c+3*j*i*i*e+n*g,p=k*b+3*l*i*d+3*j*i*i*f+n*h,q=a+2*i*(c-a)+m*(e-2*c+a),r=b+2*i*(d-b)+m*(f-2*d+b),s=c+2*i*(e-c)+m*(g-2*e+c),t=d+2*i*(f-d)+m*(h-2*f+d),u=j*a+i*c,v=j*b+i*d,w=j*e+i*g,x=j*f+i*h,y=90-180*M.atan2(q-s,r-t)/R;return(q>s||r=a.x&&b<=a.x2&&c>=a.y&&c<=a.y2},b.isBBoxIntersect=function(a,c){var d=b.isPointInsideBBox;return d(c,a.x,a.y)||d(c,a.x2,a.y)||d(c,a.x,a.y2)||d(c,a.x2,a.y2)||d(a,c.x,c.y)||d(a,c.x2,c.y)||d(a,c.x,c.y2)||d(a,c.x2,c.y2)||(a.xc.x||c.xa.x)&&(a.yc.y||c.ya.y)},b.pathIntersection=function(a,b){return m(a,b)},b.pathIntersectionNumber=function(a,b){return m(a,b,1)},b.isPointInsidePath=function(a,c,d){var e=b.pathBBox(a);return b.isPointInsideBBox(e,c,d)&&m(a,[["M",c,d],["H",e.x2+10]],1)%2==1},b._removedFactory=function(b){return function(){a("raphael.log",null,"Raphaël: you are calling to method “"+b+"” of removed object",b)}};var za=b.pathBBox=function(a){var b=ya(a);if(b.bbox)return c(b.bbox);if(!a)return{x:0,y:0,width:0,height:0,x2:0,y2:0};a=Ia(a);for(var d,e=0,f=0,g=[],h=[],i=0,j=a.length;i1&&(s=M.sqrt(s),c=s*c,d=s*d);var t=c*c,u=d*d,v=(g==h?-1:1)*M.sqrt(P((t*u-t*r*r-u*q*q)/(t*r*r+u*q*q))),w=v*c*r/d+(a+i)/2,x=v*-d*q/c+(b+j)/2,y=M.asin(((b-x)/d).toFixed(9)),z=M.asin(((j-x)/d).toFixed(9));y=az&&(y-=2*R),!h&&z>y&&(z-=2*R)}var A=z-y;if(P(A)>m){var B=z,C=i,E=j;z=y+m*(h&&z>y?1:-1),i=w+c*M.cos(z),j=x+d*M.sin(z),o=Fa(i,j,c,d,f,0,h,C,E,[z,B,w,x])}A=z-y;var F=M.cos(y),G=M.sin(y),H=M.cos(z),J=M.sin(z),K=M.tan(A/4),L=4/3*c*K,N=4/3*d*K,O=[a,b],Q=[a+L*G,b-N*F],S=[i+L*J,j-N*H],T=[i,j];if(Q[0]=2*O[0]-Q[0],Q[1]=2*O[1]-Q[1],k)return[Q,S,T][D](o);o=[Q,S,T][D](o).join()[I](",");for(var U=[],V=0,W=o.length;V"1e12"&&(m=.5),P(n)>"1e12"&&(n=.5),m>0&&m<1&&(i=Ga(a,b,c,d,e,f,g,h,m),p.push(i.x),o.push(i.y)),n>0&&n<1&&(i=Ga(a,b,c,d,e,f,g,h,n),p.push(i.x),o.push(i.y)),j=f-2*d+b-(h-2*f+d),k=2*(d-b)-2*(f-d),l=b-d,m=(-k+M.sqrt(k*k-4*j*l))/2/j,n=(-k-M.sqrt(k*k-4*j*l))/2/j,P(m)>"1e12"&&(m=.5),P(n)>"1e12"&&(n=.5),m>0&&m<1&&(i=Ga(a,b,c,d,e,f,g,h,m),p.push(i.x),o.push(i.y)),n>0&&n<1&&(i=Ga(a,b,c,d,e,f,g,h,n),p.push(i.x),o.push(i.y)),{min:{x:O[C](0,p),y:O[C](0,o)},max:{x:N[C](0,p),y:N[C](0,o)}}}),Ia=b._path2curve=e(function(a,b){var c=!b&&ya(a);if(!b&&c.curve)return Aa(c.curve);for(var d=Ca(a),e=b&&Ca(b),f={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},g={x:0,y:0,bx:0,by:0,X:0,Y:0,qx:null,qy:null},h=(function(a,b,c){var d,e,f={T:1,Q:1};if(!a)return["C",b.x,b.y,b.x,b.y,b.x,b.y];switch(!(a[0]in f)&&(b.qx=b.qy=null),a[0]){case"M":b.X=a[1],b.Y=a[2];break;case"A":a=["C"][D](Fa[C](0,[b.x,b.y][D](a.slice(1))));break;case"S":"C"==c||"S"==c?(d=2*b.x-b.bx,e=2*b.y-b.by):(d=b.x,e=b.y),a=["C",d,e][D](a.slice(1));break;case"T":"Q"==c||"T"==c?(b.qx=2*b.x-b.qx,b.qy=2*b.y-b.qy):(b.qx=b.x,b.qy=b.y),a=["C"][D](Ea(b.x,b.y,b.qx,b.qy,a[1],a[2]));break;case"Q":b.qx=a[1],b.qy=a[2],a=["C"][D](Ea(b.x,b.y,a[1],a[2],a[3],a[4]));break;case"L":a=["C"][D](Da(b.x,b.y,a[1],a[2]));break;case"H":a=["C"][D](Da(b.x,b.y,a[1],b.y));break;case"V":a=["C"][D](Da(b.x,b.y,b.x,a[1]));break;case"Z":a=["C"][D](Da(b.x,b.y,b.X,b.Y))}return a}),i=function(a,b){if(a[b].length>7){a[b].shift();for(var c=a[b];c.length;)k[b]="A",e&&(l[b]="A"),a.splice(b++,0,["C"][D](c.splice(0,6)));a.splice(b,1),p=N(d.length,e&&e.length||0)}},j=function(a,b,c,f,g){a&&b&&"M"==a[g][0]&&"M"!=b[g][0]&&(b.splice(g,0,["M",f.x,f.y]),c.bx=0,c.by=0,c.x=a[g][1],c.y=a[g][2],p=N(d.length,e&&e.length||0))},k=[],l=[],m="",n="",o=0,p=N(d.length,e&&e.length||0);oe){if(c&&!m.start){if(k=_a(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n),l+=["C"+k.start.x,k.start.y,k.m.x,k.m.y,k.x,k.y],f)return l;m.start=l,l=["M"+k.x,k.y+"C"+k.n.x,k.n.y,k.end.x,k.end.y,i[5],i[6]].join(),n+=j,g=+i[5],h=+i[6];continue}if(!a&&!c)return k=_a(g,h,i[1],i[2],i[3],i[4],i[5],i[6],e-n),{x:k.x,y:k.y,alpha:k.alpha}}n+=j,g=+i[5],h=+i[6]}l+=i.shift()+i}return m.end=l,k=a?n:c?m:b.findDotsAtSegment(g,h,i[0],i[1],i[2],i[3],i[4],i[5],1),k.alpha&&(k={x:k.x,y:k.y,alpha:k.alpha}),k}},bb=ab(1),cb=ab(),db=ab(0,1);b.getTotalLength=bb,b.getPointAtLength=cb,b.getSubpath=function(a,b,c){if(this.getTotalLength(a)-c<1e-6)return db(a,b).end;var d=db(a,c,1);return b?db(d,b).end:d},Xa.getTotalLength=function(){var a=this.getPath();if(a)return this.node.getTotalLength?this.node.getTotalLength():bb(a)},Xa.getPointAtLength=function(a){var b=this.getPath();if(b)return cb(b,a)},Xa.getPath=function(){var a,c=b._getPath[this.type];if("text"!=this.type&&"set"!=this.type)return c&&(a=c(this)),a},Xa.getSubpath=function(a,c){var d=this.getPath();if(d)return b.getSubpath(d,a,c)};var eb=b.easing_formulas={linear:function(a){return a},"<":function(a){return Q(a,1.7)},">":function(a){return Q(a,.48)},"<>":function(a){var b=.48-a/1.04,c=M.sqrt(.1734+b*b),d=c-b,e=Q(P(d),1/3)*(d<0?-1:1),f=-c-b,g=Q(P(f),1/3)*(f<0?-1:1),h=e+g+.5;return 3*(1-h)*h*h+h*h*h},backIn:function(a){var b=1.70158;return a*a*((b+1)*a-b)},backOut:function(a){a-=1;var b=1.70158;return a*a*((b+1)*a+b)+1},elastic:function(a){return a==!!a?a:Q(2,-10*a)*M.sin((a-.075)*(2*R)/.3)+1},bounce:function(a){var b,c=7.5625,d=2.75;return a<1/d?b=c*a*a:a<2/d?(a-=1.5/d,b=c*a*a+.75):a<2.5/d?(a-=2.25/d,b=c*a*a+.9375):(a-=2.625/d,b=c*a*a+.984375),b}};eb.easeIn=eb["ease-in"]=eb["<"],eb.easeOut=eb["ease-out"]=eb[">"],eb.easeInOut=eb["ease-in-out"]=eb["<>"],eb["back-in"]=eb.backIn,eb["back-out"]=eb.backOut;var fb=[],gb=window.requestAnimationFrame||window.webkitRequestAnimationFrame||window.mozRequestAnimationFrame||window.oRequestAnimationFrame||window.msRequestAnimationFrame||function(a){setTimeout(a,16)},hb=function(){for(var c=+new Date,d=0;d1&&!e.next){for(g in m)m[y](g)&&(p[g]=e.totalOrigin[g]);e.el.attr(p),r(e.anim,e.el,e.anim.percents[0],null,e.totalOrigin,e.repeat-1)}e.next&&!e.stop&&r(e.anim,e.el,e.next,null,e.totalOrigin,e.repeat)}}}fb.length&&gb(hb)},ib=function(a){return a>255?255:a<0?0:a};Xa.animateWith=function(a,c,d,e,f,g){var h=this;if(h.removed)return g&&g.call(h),h;var i=d instanceof q?d:b.animation(d,e,f,g);r(i,h,i.percents[0],null,h.attr());for(var j=0,k=fb.length;ji&&(i=k)}i+="%",!a[i].callback&&(a[i].callback=e)}return new q(a,c)}return d&&(h.easing=d),e&&(h.callback=e),new q({100:h},c)},Xa.animate=function(a,c,d,e){var f=this;if(f.removed)return e&&e.call(f),f;var g=a instanceof q?a:b.animation(a,c,d,e);return r(g,f,g.percents[0],null,f.attr()),f},Xa.setTime=function(a,b){return a&&null!=b&&this.status(a,O(b,a.ms)/a.ms),this},Xa.status=function(a,b){var c,d,e=[],f=0;if(null!=b)return r(a,this,-1,O(b,1)),this;for(c=fb.length;f.5)-1;i(m-.5,2)+i(n-.5,2)>.25&&(n=f.sqrt(.25-i(m-.5,2))*e+.5)&&.5!=n&&(n=n.toFixed(5)-1e-5*e)}return l}),e=e.split(/\s*\-\s*/),"linear"==j){var t=e.shift();if(t=-d(t),isNaN(t))return null;var u=[0,0,f.cos(a.rad(t)),f.sin(a.rad(t))],v=1/(g(h(u[2]),h(u[3]))||1);u[2]*=v,u[3]*=v,u[2]<0&&(u[0]=-u[2],u[2]=0),u[3]<0&&(u[1]=-u[3],u[3]=0)}var w=a._parseDots(e);if(!w)return null;if(k=k.replace(/[\(\)\s,\xb0#]/g,"_"),b.gradient&&k!=b.gradient.id&&(p.defs.removeChild(b.gradient),delete b.gradient),!b.gradient){s=q(j+"Gradient",{id:k}),b.gradient=s,q(s,"radial"==j?{fx:m,fy:n}:{x1:u[0],y1:u[1],x2:u[2],y2:u[3],gradientTransform:b.matrix.invert()}),p.defs.appendChild(s);for(var x=0,y=w.length;x1?H.opacity/100:H.opacity});case"stroke":H=a.getRGB(p),i.setAttribute(o,H.hex),"stroke"==o&&H[b]("opacity")&&q(i,{"stroke-opacity":H.opacity>1?H.opacity/100:H.opacity}),"stroke"==o&&d._.arrows&&("startString"in d._.arrows&&t(d,d._.arrows.startString),"endString"in d._.arrows&&t(d,d._.arrows.endString,1));break;case"gradient":("circle"==d.type||"ellipse"==d.type||"r"!=c(p).charAt())&&r(d,p);break;case"opacity":k.gradient&&!k[b]("stroke-opacity")&&q(i,{"stroke-opacity":p>1?p/100:p});case"fill-opacity":if(k.gradient){I=a._g.doc.getElementById(i.getAttribute("fill").replace(/^url\(#|\)$/g,l)),I&&(J=I.getElementsByTagName("stop"),q(J[J.length-1],{"stop-opacity":p}));break}default:"font-size"==o&&(p=e(p,10)+"px");var K=o.replace(/(\-.)/g,function(a){return a.substring(1).toUpperCase()});i.style[K]=p,d._.dirty=1,i.setAttribute(o,p)}}y(d,f),i.style.visibility=m},x=1.2,y=function(d,f){if("text"==d.type&&(f[b]("text")||f[b]("font")||f[b]("font-size")||f[b]("x")||f[b]("y"))){var g=d.attrs,h=d.node,i=h.firstChild?e(a._g.doc.defaultView.getComputedStyle(h.firstChild,l).getPropertyValue("font-size"),10):10;if(f[b]("text")){for(g.text=f.text;h.firstChild;)h.removeChild(h.firstChild);for(var j,k=c(f.text).split("\n"),m=[],n=0,o=k.length;n"));var X=U.getBoundingClientRect();s.W=m.w=(X.right-X.left)/V,s.H=m.h=(X.bottom-X.top)/V,s.X=m.x,s.Y=m.y+s.H/2,("x"in i||"y"in i)&&(s.path.v=a.format("m{0},{1}l{2},{1}",f(m.x*u),f(m.y*u),f(m.x*u)+1));for(var Y=["x","y","text","font","font-family","font-weight","font-style","font-size"],Z=0,$=Y.length;Z<$;Z++)if(Y[Z]in i){s._.dirty=1;break}switch(m["text-anchor"]){case"start":s.textpath.style["v-text-align"]="left",s.bbx=s.W/2;break;case"end":s.textpath.style["v-text-align"]="right",s.bbx=-s.W/2;break;default:s.textpath.style["v-text-align"]="center",s.bbx=0}s.textpath.style["v-text-kern"]=!0}},C=function(b,f,g){b.attrs=b.attrs||{};var h=(b.attrs,Math.pow),i="linear",j=".5 .5";if(b.attrs.gradient=f,f=c(f).replace(a._radial_gradient,function(a,b,c){return i="radial",b&&c&&(b=d(b),c=d(c),h(b-.5,2)+h(c-.5,2)>.25&&(c=e.sqrt(.25-h(b-.5,2))*(2*(c>.5)-1)+.5),j=b+n+c),o}),f=f.split(/\s*\-\s*/),"linear"==i){var k=f.shift();if(k=-d(k),isNaN(k))return null}var l=a._parseDots(f);if(!l)return null;if(b=b.shape||b.node,l.length){b.removeChild(g),g.on=!0,g.method="none",g.color=l[0].color,g.color2=l[l.length-1].color;for(var m=[],p=0,q=l.length;p')}}catch(c){F=function(a){return b.createElement("<"+a+' xmlns="urn:schemas-microsoft.com:vml" class="rvml">')}}},a._engine.initWin(a._g.win),a._engine.create=function(){var b=a._getContainer.apply(0,arguments),c=b.container,d=b.height,e=b.width,f=b.x,g=b.y;if(!c)throw new Error("VML container not found.");var h=new a._Paper,i=h.canvas=a._g.doc.createElement("div"),j=i.style;return f=f||0,g=g||0,e=e||512,d=d||342,h.width=e,h.height=d,e==+e&&(e+="px"),d==+d&&(d+="px"),h.coordsize=1e3*u+n+1e3*u,h.coordorigin="0 0",h.span=a._g.doc.createElement("span"),h.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;",i.appendChild(h.span),j.cssText=a.format("top:0;left:0;display:inline-block;position:absolute;clip:rect(0 {0} {1} 0);",e,d),1==c?(a._g.doc.body.appendChild(i),j.left=f+"px",j.top=g+"px",j.position="absolute"):c.firstChild?c.insertBefore(i,c.firstChild):c.appendChild(i),h.renderfix=function(){},h},a.prototype.clear=function(){a.eve("raphael.clear",this),this.canvas.innerHTML=o,this.span=a._g.doc.createElement("span"),this.span.style.cssText="position:absolute;left:-9999em;top:-9999em;padding:0;margin:0;line-height:1;display:inline;",this.canvas.appendChild(this.span),this.bottom=this.top=null},a.prototype.remove=function(){a.eve("raphael.remove",this),this.canvas.parentNode.removeChild(this.canvas);for(var b in this)this[b]="function"==typeof this[b]?a._removedFactory(b):null;return!0};var G=a.st;for(var H in E)E[b](H)&&!G[b](H)&&(G[H]=function(a){return function(){var b=arguments;return this.forEach(function(c){c[a].apply(c,b)})}}(H))}}),function(a,b){if("function"==typeof define&&define.amd)define("raphael",["raphael.core","raphael.svg","raphael.vml"],function(a){return b(a)});else if("object"==typeof exports){var c=require("raphael.core");require("raphael.svg"),require("raphael.vml"),module.exports=b(c)}}(this,function(a){return a.ninja()}),BI.Svg=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.Svg.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-svg"})},_init:function(){BI.Svg.superclass._init.apply(this,arguments),this.paper=Raphael(this.element[0]),this.element.css("overflow","hidden"),$(this.paper.canvas).width("100%").height("100%").css({left:"0",top:"0"}).appendTo(this.element),this.top=this.paper.top,this.bottom=this.paper.bottom,this.customAttributes=this.paper.customAttributes,this.ca=this.paper.ca,this.raphael=this.paper.raphael},add:function(){return this.paper.add.apply(this.paper,arguments)},path:function(){return this.paper.path.apply(this.paper,arguments)},image:function(){return this.paper.image.apply(this.paper,arguments)},rect:function(){return this.paper.rect.apply(this.paper,arguments)},circle:function(){return this.paper.circle.apply(this.paper,arguments)},ellipse:function(){return this.paper.ellipse.apply(this.paper,arguments)},text:function(){return this.paper.text.apply(this.paper,arguments)},print:function(){return this.paper.print.apply(this.paper,arguments)},setStart:function(){return this.paper.setStart.apply(this.paper,arguments)},setFinish:function(){return this.paper.setFinish.apply(this.paper,arguments)},setSize:function(){return this.paper.setSize.apply(this.paper,arguments)},setViewBox:function(){return this.paper.setViewBox.apply(this.paper,arguments)},getById:function(){return this.paper.getById.apply(this.paper,arguments)},getElementByPoint:function(){return this.paper.getElementByPoint.apply(this.paper,arguments)},getElementsByPoint:function(){return this.paper.getElementsByPoint.apply(this.paper,arguments)},getFont:function(){return this.paper.getFont.apply(this.paper,arguments)},set:function(){return this.paper.set.apply(this.paper,arguments)},remove:function(){return this.paper.remove.apply(this.paper,arguments)},clear:function(){return this.paper.clear.apply(this.paper,arguments)}}),BI.shortcut("bi.svg",BI.Svg),BI.NativeTableScrollbar=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.NativeTableScrollbar.superclass._defaultConfig.apply(this,arguments),{attributes:{tabIndex:0},contentSize:0,defaultPosition:0,position:0,size:0})},render:function(){var a=this;this.options;this.element.width(36);var b=BI.throttle(function(){a.fireEvent(BI.NativeTableScrollbar.EVENT_SCROLL,a.element.scrollTop())},150,{leading:!1});return this.element.scroll(function(){b()}),{type:"bi.default",scrolly:!0,items:[{type:"bi.layout",width:1,ref:function(b){a.inner=b}}]}},mounted:function(){this._populate()},_populate:function(){var a=this.options;if(a.size<1||a.contentSize<=a.size)return void this.setVisible(!1);this.setVisible(!0);try{this.element.scrollTop(a.position)}catch(b){}this.inner.element.height(a.contentSize)},setContentSize:function(a){this.options.contentSize=a},setPosition:function(a){this.options.position=a},setSize:function(a){this.setHeight(a),this.options.size=a},populate:function(){this._populate()}}),BI.NativeTableScrollbar.EVENT_SCROLL="EVENT_SCROLL",BI.shortcut("bi.native_table_scrollbar",BI.NativeTableScrollbar),BI.NativeTableHorizontalScrollbar=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.NativeTableHorizontalScrollbar.superclass._defaultConfig.apply(this,arguments),{attributes:{tabIndex:0},contentSize:0,position:0,size:0})},render:function(){var a=this;this.options;this.element.height(36);var b=BI.throttle(function(){a.fireEvent(BI.NativeTableScrollbar.EVENT_SCROLL,a.element.scrollLeft())},150,{leading:!1});return this.element.scroll(function(){b()}),{type:"bi.default",scrollx:!0,items:[{type:"bi.layout",height:1,ref:function(b){a.inner=b}}]}},setContentSize:function(a){this.options.contentSize=a},setPosition:function(a){this.options.position=a},setSize:function(a){this.setWidth(a),this.options.size=a},_populate:function(){var a=this.options;if(a.size<1||a.contentSize<=a.size)return void this.setVisible(!1);this.setVisible(!0);try{this.element.scrollLeft(a.position)}catch(b){}this.inner.element.width(a.contentSize)},populate:function(){this._populate()}}),BI.NativeTableHorizontalScrollbar.EVENT_SCROLL="EVENT_SCROLL",BI.shortcut("bi.native_table_horizontal_scrollbar",BI.NativeTableHorizontalScrollbar),BI.TableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.TableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-table-cell",textAlign:"left",text:""})},_init:function(){BI.TableCell.superclass._init.apply(this,arguments),BI.createWidget({type:"bi.label",element:this,whiteSpace:"nowrap",textAlign:this.options.textAlign,height:this.options.height,text:this.options.text,value:this.options.value,lgap:5})}}),BI.shortcut("bi.table_cell",BI.TableCell),BI.CollectionTableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.CollectionTableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-collection-table-cell bi-border-right bi-border-bottom",width:0,height:0,_left:0,_top:0,cell:{}})},_init:function(){BI.CollectionTableCell.superclass._init.apply(this,arguments);var a=this.options;this.cell=BI.createWidget(BI.extend({type:"bi.label"},a.cell,{cls:(a.cell.cls||"")+" collection-table-cell-wrapper",width:a.width-(0===a._left?1:0)-1,height:a.height-(0===a._top?1:0)-1})),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.cell,left:0,right:0,top:0,bottom:0}]})},setWidth:function(a){BI.CollectionTableCell.superclass.setWidth.apply(this,arguments);var b=this.options;this.cell.setWidth(b.width-(0===b._left?1:0)-1)},setHeight:function(a){BI.CollectionTableCell.superclass.setHeight.apply(this,arguments);var b=this.options;this.cell.setHeight(b.height-(0===b._top?1:0)-1)}}),BI.shortcut("bi.collection_table_cell",BI.CollectionTableCell),BI.CollectionTable=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.CollectionTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-collection-table",headerRowSize:25,rowSize:25,columnSize:[],isNeedFreeze:!1,freezeCols:[],isNeedMerge:!1,mergeCols:[],mergeRule:BI.emptyFn,header:[],items:[],regionColumnSize:[]})},render:function(){var a=this,b=this.options;this._width=0,this._height=0,this._scrollBarSize=BI.DOM.getScrollWidth(),this.topLeftCollection=BI.createWidget({type:"bi.collection_view",cellSizeAndPositionGetter:function(b){return a.topLeftItems[b]}}),this.topLeftCollection.on(BI.CollectionView.EVENT_SCROLL,function(b){a.bottomLeftCollection.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.topRightCollection=BI.createWidget({type:"bi.collection_view",cellSizeAndPositionGetter:function(b){return a.topRightItems[b]}}),this.topRightCollection.on(BI.CollectionView.EVENT_SCROLL,function(b){a.bottomRightCollection.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.bottomLeftCollection=BI.createWidget({type:"bi.collection_view",cellSizeAndPositionGetter:function(b){return a.bottomLeftItems[b]}}),this.bottomLeftCollection.on(BI.CollectionView.EVENT_SCROLL,function(b){a.bottomRightCollection.setScrollTop(b.scrollTop),a.topLeftCollection.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.bottomRightCollection=BI.createWidget({type:"bi.collection_view",cellSizeAndPositionGetter:function(b){return a.bottomRightItems[b]}}),this.bottomRightCollection.on(BI.CollectionView.EVENT_SCROLL,function(b){a.bottomLeftCollection.setScrollTop(b.scrollTop),a.topRightCollection.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.topLeft=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.topLeftCollection]}),this.topRight=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.topRightCollection]}),this.bottomLeft=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.bottomLeftCollection]}),this.bottomRight=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.bottomRightCollection]}),this.contextLayout=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.topLeft,top:0,left:0},{el:this.topRight,top:0},{el:this.bottomLeft,left:0},{el:this.bottomRight}]}),this.topScrollbar=BI.createWidget({type:"bi.grid_table_scrollbar",width:BI.GridTableScrollbar.SIZE}),this.topScrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(b){a.bottomLeftCollection.setScrollTop(b),a.bottomRightCollection.setScrollTop(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.leftScrollbar=BI.createWidget({type:"bi.grid_table_horizontal_scrollbar",height:BI.GridTableScrollbar.SIZE}),this.leftScrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(b){a.topLeftCollection.setScrollLeft(b),a.bottomLeftCollection.setScrollLeft(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.rightScrollbar=BI.createWidget({type:"bi.grid_table_horizontal_scrollbar",height:BI.GridTableScrollbar.SIZE}),this.rightScrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(b){a.topRightCollection.setScrollLeft(b),a.bottomRightCollection.setScrollLeft(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.scrollBarLayout=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.topScrollbar,right:0,top:0},{el:this.leftScrollbar,left:0},{el:this.rightScrollbar}]}),this._width=b.width-BI.GridTableScrollbar.SIZE,this._height=b.height-BI.GridTableScrollbar.SIZE},mounted:function(){var a=this.options;(a.items.length>0||a.header.length>0)&&(this._digest(),this._populate())},_getFreezeColLength:function(){var a=this.options;return a.isNeedFreeze===!0?BI.clamp(a.freezeCols.length,0,a.columnSize.length):0},_getFreezeHeaderHeight:function(){var a=this.options;return a.header.length*a.headerRowSize>=this._height?0:a.header.length*a.headerRowSize},_getActualItems:function(){var a=this.options;return a.header.length*a.headerRowSize>=this._height?a.header.concat(a.items):a.items},_populateScrollbar:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[];BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g}),this.topScrollbar.setContentSize(this._getActualItems().length*a.rowSize),this.topScrollbar.setSize(this._height-this._getFreezeHeaderHeight()),this.topScrollbar.setPosition(this.bottomRightCollection.getScrollTop()),this.topScrollbar.populate(),this.leftScrollbar.setContentSize(c),this.leftScrollbar.setSize(b),this.leftScrollbar.setPosition(this.bottomLeftCollection.getScrollLeft()),this.leftScrollbar.populate(),this.rightScrollbar.setContentSize(d),this.rightScrollbar.setSize(this._width-b),this.rightScrollbar.setPosition(this.bottomRightCollection.getScrollLeft()),this.rightScrollbar.populate();var g=this.scrollBarLayout.attr("items");g[0].top=this._getFreezeHeaderHeight(),g[1].top=this._height,g[2].top=this._height,g[2].left=b,this.scrollBarLayout.attr("items",g),this.scrollBarLayout.resize()},_populateTable:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[];BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g});var g=b,h=this._getFreezeHeaderHeight(),i=this._width-b,j=this._getFreezeHeaderHeight(),k=b,l=this._height-h,m=this._width-b,n=this._height-j,o=g+this._scrollBarSize,p=h+this._scrollBarSize,q=i+this._scrollBarSize,r=j+this._scrollBarSize,s=k+this._scrollBarSize,t=l+this._scrollBarSize,u=m+this._scrollBarSize,v=n+this._scrollBarSize,w=function(a){a.element.css({overflow:"scroll",overflowX:"scroll",overflowY:"scroll"})};this.topLeft.setWidth(g),this.topLeft.setHeight(h),this.topRight.setWidth(i),this.topRight.setHeight(j),this.bottomLeft.setWidth(k),this.bottomLeft.setHeight(l),this.bottomRight.setWidth(m),this.bottomRight.setHeight(n),this.topLeftCollection.setWidth(o),this.topLeftCollection.setHeight(p),this.topRightCollection.setWidth(q),this.topRightCollection.setHeight(r),this.bottomLeftCollection.setWidth(s),this.bottomLeftCollection.setHeight(t),this.bottomRightCollection.setWidth(u),this.bottomRightCollection.setHeight(v),w(this.topLeftCollection),w(this.topRightCollection),w(this.bottomLeftCollection),w(this.bottomRightCollection);var x=this.contextLayout.attr("items");x[1].left=b,x[2].top=this._getFreezeHeaderHeight(),x[3].left=b,x[3].top=this._getFreezeHeaderHeight(),this.contextLayout.attr("items",x),this.contextLayout.resize();var y=[],z=[],A=[],B=[],C=function(a,b,c){ +BI.each(a,function(a,d){var e={type:"bi.collection_table_cell",cell:b[d.row][d.col]};c.push(e)})};C(this.topLeftItems,a.header,y),C(this.topRightItems,a.header,z),C(this.bottomLeftItems,this._getActualItems(),A),C(this.bottomRightItems,this._getActualItems(),B),this.topLeftCollection._populate(y),this.topRightCollection._populate(z),this.bottomLeftCollection._populate(A),this.bottomRightCollection._populate(B)},_digest:function(){var a=this.options,b=this._getFreezeColLength();this._getFreezeHeaderHeight()<=0?(this.topLeftItems=[],this.topRightItems=[],this.bottomLeftItems=this._serialize(this._getActualItems(),0,b,a.rowSize,a.columnSize,a.mergeCols,BI.range(a.header.length)),this.bottomRightItems=this._serialize(this._getActualItems(),b,a.columnSize.length,a.rowSize,a.columnSize,a.mergeCols,BI.range(a.header.length))):(this.topLeftItems=this._serialize(a.header,0,b,a.headerRowSize,a.columnSize,a.mergeCols),this.topRightItems=this._serialize(a.header,b,a.columnSize.length,a.headerRowSize,a.columnSize,!0),this.bottomLeftItems=this._serialize(a.items,0,b,a.rowSize,a.columnSize,a.mergeCols),this.bottomRightItems=this._serialize(a.items,b,a.columnSize.length,a.rowSize,a.columnSize,a.mergeCols))},_serialize:function(a,b,c,d,e,f,g){f=f||[],g=g||[];for(var h=this.options,i=[],j={},k={},l={},m={},n=[],o=b;o-1||g===!0||g.indexOf(a)>-1)if(0===a&&e===b)r(0,b);else if(e===b&&a>0){var i=h.mergeRule(j[a][e],j[a-1][e]);i===!0?(p(a,e),l[a]=k[e]):r(a,e)}else if(0===a&&e>b){var n=h.mergeRule(j[a][e],j[a][e-1]);n===!0?(q(a,e),k[e]=l[a]):r(a,e)}else{var i=h.mergeRule(j[a][e],j[a-1][e]),n=h.mergeRule(j[a][e],j[a][e-1]);if(n&&i)continue;n&&q(a,e),i&&p(a,e),n||i||r(a,e)}else r(a,e)}),BI.map(i,function(a,b){return{x:b.x,y:b.y,row:b.item._row,col:b.item._col,width:b.item._width,height:b.item._height}})},_populate:function(){this._width<=0||this._height<=0||(this._isNeedDigest===!0&&this._digest(),this._isNeedDigest=!1,this._populateTable(),this._populateScrollbar())},getRegionSize:function(){var a=this.options,b=a.regionColumnSize[0]||0;return a.isNeedFreeze===!1||0===a.freezeCols.length?0:(b||BI.each(a.freezeCols,function(c,d){b+=a.columnSize[d]}),b)},setVerticalScroll:function(a){this.bottomLeftCollection.setScrollTop(a),this.bottomRightCollection.setScrollTop(a)},setLeftHorizontalScroll:function(a){this.topLeftCollection.setScrollLeft(a),this.bottomLeftCollection.setScrollLeft(a)},setRightHorizontalScroll:function(a){this.topRightCollection.setScrollLeft(a),this.bottomRightCollection.setScrollLeft(a)},getVerticalScroll:function(){return this.bottomRightCollection.getScrollTop()},getLeftHorizontalScroll:function(){return this.bottomLeftCollection.getScrollLeft()},getRightHorizontalScroll:function(){return this.bottomRightCollection.getScrollLeft()},setWidth:function(a){BI.CollectionTable.superclass.setWidth.apply(this,arguments),this._width=this.options.width-BI.GridTableScrollbar.SIZE},setHeight:function(a){BI.CollectionTable.superclass.setHeight.apply(this,arguments),this._height=this.options.height-BI.GridTableScrollbar.SIZE},setColumnSize:function(a){this._isNeedDigest=!0,this.options.columnSize=a},setRegionColumnSize:function(a){this._isNeedDigest=!0,this.options.regionColumnSize=a},getColumnSize:function(){return this.options.columnSize},getRegionColumnSize:function(){return this.options.regionColumnSize},populate:function(a,b){a&&a!==this.options.items&&(this._isNeedDigest=!0,this.options.items=a,this._restore()),b&&b!==this.options.header&&(this._isNeedDigest=!0,this.options.header=b,this._restore()),this._populate()},_restore:function(){this.topLeftCollection.restore(),this.topRightCollection.restore(),this.bottomLeftCollection.restore(),this.bottomRightCollection.restore()},restore:function(){this._restore()}}),BI.shortcut("bi.collection_table",BI.CollectionTable),BI.QuickCollectionTable=BI.inherit(BI.CollectionTable,{_defaultConfig:function(){return BI.extend(BI.QuickCollectionTable.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-quick-collection-table"})},render:function(){BI.QuickCollectionTable.superclass.render.apply(this,arguments);this.options;this.topLeftCollection.setOverflowX(!1),this.topLeftCollection.setOverflowY(!1),this.topRightCollection.setOverflowX(!1),this.topRightCollection.setOverflowY(!1),this.bottomLeftCollection.setOverflowX(!1),this.bottomLeftCollection.setOverflowY(!1),this.bottomRightCollection.setOverflowX(!1),this.bottomRightCollection.setOverflowY(!1)},mounted:function(){BI.QuickCollectionTable.superclass.mounted.apply(this,arguments);var a=this;this._topLeftWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelLeft,this),BI.bind(this._shouldHandleLeftX,this),BI.bind(this._shouldHandleY,this)),this._topRightWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelRight,this),BI.bind(this._shouldHandleRightX,this),BI.bind(this._shouldHandleY,this)),this._bottomLeftWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelLeft,this),BI.bind(this._shouldHandleLeftX,this),BI.bind(this._shouldHandleY,this)),this._bottomRightWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelRight,this),BI.bind(this._shouldHandleRightX,this),BI.bind(this._shouldHandleY,this)),this.topLeftCollection.element.mousewheel(function(b){a._topLeftWheelHandler.onWheel(b.originalEvent)}),this.topRightCollection.element.mousewheel(function(b){a._topRightWheelHandler.onWheel(b.originalEvent)}),this.bottomLeftCollection.element.mousewheel(function(b){a._bottomLeftWheelHandler.onWheel(b.originalEvent)}),this.bottomRightCollection.element.mousewheel(function(b){a._bottomRightWheelHandler.onWheel(b.originalEvent)})},_shouldHandleLeftX:function(a){return a>0?this.bottomLeftCollection.getScrollLeft()0},_shouldHandleRightX:function(a){return a>0?this.bottomRightCollection.getScrollLeft()0},_shouldHandleY:function(a){return a>0?this.bottomRightCollection.getScrollTop()0},_onWheelLeft:function(a,b){var c=this,d=this.bottomLeftCollection.getScrollTop(),e=this.bottomLeftCollection.getScrollLeft();d+=b,e+=a,this.bottomLeftCollection.setScrollTop(d),this.bottomRightCollection.setScrollTop(d),this.topLeftCollection.setScrollLeft(e),this.bottomLeftCollection.setScrollLeft(e),c._populateScrollbar(),this.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)},_onWheelRight:function(a,b){var c=this,d=this.bottomRightCollection.getScrollTop(),e=this.bottomRightCollection.getScrollLeft();d+=b,e+=a,this.bottomLeftCollection.setScrollTop(d),this.bottomRightCollection.setScrollTop(d),this.topRightCollection.setScrollLeft(e),this.bottomRightCollection.setScrollLeft(e),c._populateScrollbar(),this.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)},_populateTable:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[];BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g});var g=b,h=this._getFreezeHeaderHeight(),i=this._width-b,j=this._getFreezeHeaderHeight(),k=b,l=this._height-h,m=this._width-b,n=this._height-j;this.topLeft.setWidth(g),this.topLeft.setHeight(h),this.topRight.setWidth(i),this.topRight.setHeight(j),this.bottomLeft.setWidth(k),this.bottomLeft.setHeight(l),this.bottomRight.setWidth(m),this.bottomRight.setHeight(n),this.topLeftCollection.setWidth(g),this.topLeftCollection.setHeight(h),this.topRightCollection.setWidth(i),this.topRightCollection.setHeight(j),this.bottomLeftCollection.setWidth(k),this.bottomLeftCollection.setHeight(l),this.bottomRightCollection.setWidth(m),this.bottomRightCollection.setHeight(n);var o=this.contextLayout.attr("items");o[1].left=b,o[2].top=this._getFreezeHeaderHeight(),o[3].left=b,o[3].top=this._getFreezeHeaderHeight(),this.contextLayout.attr("items",o),this.contextLayout.resize();var p=[],q=[],r=[],s=[],t=function(a,b,c){BI.each(a,function(a,d){var e={type:"bi.collection_table_cell",cell:b[d.row][d.col]};c.push(e)})};t(this.topLeftItems,a.header,p),t(this.topRightItems,a.header,q),t(this.bottomLeftItems,this._getActualItems(),r),t(this.bottomRightItems,this._getActualItems(),s),this.topLeftCollection.populate(p),this.topRightCollection.populate(q),this.bottomLeftCollection.populate(r),this.bottomRightCollection.populate(s)}}),BI.shortcut("bi.quick_collection_table",BI.QuickCollectionTable),BI.GridTableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.GridTableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-grid-table-cell bi-border-right bi-border-bottom",width:0,height:0,_rowIndex:0,_columnIndex:0,_left:0,_top:0,cell:{}})},_init:function(){BI.GridTableCell.superclass._init.apply(this,arguments);var a=this.options;this.cell=BI.createWidget(BI.extend({type:"bi.label"},a.cell,{cls:(a.cell.cls||"")+"grid-table-cell-wrapper",width:a.width-(0===a._columnIndex?1:0)-1,height:a.height-(0===a._rowIndex?1:0)-1})),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.cell,left:0,right:0,top:0,bottom:0}]})},setWidth:function(a){BI.GridTableCell.superclass.setWidth.apply(this,arguments);var b=this.options;this.cell.setWidth(b.width-(0===b._columnIndex?1:0)-1)},setHeight:function(a){BI.GridTableCell.superclass.setHeight.apply(this,arguments);var b=this.options;this.cell.setHeight(b.height-(0===b._rowIndex?1:0)-1)}}),BI.shortcut("bi.grid_table_cell",BI.GridTableCell),BI.GridTable=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.GridTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-grid-table",headerRowSize:25,rowSize:25,columnSize:[],isNeedFreeze:!1,freezeCols:[],header:[],items:[],regionColumnSize:[]})},render:function(){var a=this,b=this.options;this._width=0,this._height=0,this._scrollBarSize=BI.DOM.getScrollWidth();var c=function(){return b.rowSize},d=function(a){return b.columnSize[a]},e=function(c){return b.columnSize[c+a._getFreezeColLength()]};this.topLeftGrid=BI.createWidget({type:"bi.grid_view",rowHeightGetter:c,columnWidthGetter:d}),this.topLeftGrid.on(BI.GridView.EVENT_SCROLL,function(b){a.bottomLeftGrid.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.topRightGrid=BI.createWidget({type:"bi.grid_view",rowHeightGetter:c,columnWidthGetter:e}),this.topRightGrid.on(BI.GridView.EVENT_SCROLL,function(b){a.bottomRightGrid.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.bottomLeftGrid=BI.createWidget({type:"bi.grid_view",rowHeightGetter:c,columnWidthGetter:d}),this.bottomLeftGrid.on(BI.GridView.EVENT_SCROLL,function(b){a.bottomRightGrid.setScrollTop(b.scrollTop),a.topLeftGrid.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.bottomRightGrid=BI.createWidget({type:"bi.grid_view",rowHeightGetter:c,columnWidthGetter:e}),this.bottomRightGrid.on(BI.GridView.EVENT_SCROLL,function(b){a.bottomLeftGrid.setScrollTop(b.scrollTop),a.topRightGrid.setScrollLeft(b.scrollLeft),a._populateScrollbar(),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.topLeft=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.topLeftGrid]}),this.topRight=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.topRightGrid]}),this.bottomLeft=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.bottomLeftGrid]}),this.bottomRight=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.bottomRightGrid]}),this.contextLayout=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.topLeft,top:0,left:0},{el:this.topRight,top:0},{el:this.bottomLeft,left:0},{el:this.bottomRight}]}),this.topScrollbar=BI.createWidget({type:"bi.grid_table_scrollbar",width:BI.GridTableScrollbar.SIZE}),this.topScrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(b){a.bottomLeftGrid.setScrollTop(b),a.bottomRightGrid.setScrollTop(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.leftScrollbar=BI.createWidget({type:"bi.grid_table_horizontal_scrollbar",height:BI.GridTableScrollbar.SIZE}),this.leftScrollbar.on(BI.GridTableHorizontalScrollbar.EVENT_SCROLL,function(b){a.topLeftGrid.setScrollLeft(b),a.bottomLeftGrid.setScrollLeft(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.rightScrollbar=BI.createWidget({type:"bi.grid_table_horizontal_scrollbar",height:BI.GridTableScrollbar.SIZE}),this.rightScrollbar.on(BI.GridTableHorizontalScrollbar.EVENT_SCROLL,function(b){a.topRightGrid.setScrollLeft(b),a.bottomRightGrid.setScrollLeft(b),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.scrollBarLayout=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.topScrollbar,right:0,top:0},{el:this.leftScrollbar,left:0},{el:this.rightScrollbar}]}),this._width=b.width-BI.GridTableScrollbar.SIZE,this._height=b.height-BI.GridTableScrollbar.SIZE,this.header=this._getHeader(),this.items=this._getItems()},mounted:function(){var a=this.options;(a.items.length>0||a.header.length>0)&&this._populate()},_getFreezeColLength:function(){var a=this.options;return a.isNeedFreeze===!0?BI.clamp(a.freezeCols.length,0,a.columnSize.length):0},_getFreezeHeaderHeight:function(){var a=this.options;return a.header.length*a.headerRowSize>=this._height?0:a.header.length*a.headerRowSize},_getActualItems:function(){var a=this.options;return a.header.length*a.headerRowSize>=this._height?a.header.concat(a.items):a.items},_populateScrollbar:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[];BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g}),this.topScrollbar.setContentSize(this._getActualItems().length*a.rowSize),this.topScrollbar.setSize(this._height-this._getFreezeHeaderHeight()),this.topScrollbar.setPosition(Math.min(this.bottomLeftGrid.getScrollTop(),this.bottomRightGrid.getScrollTop())),this.topScrollbar.populate(),this.leftScrollbar.setContentSize(c),this.leftScrollbar.setSize(b),this.leftScrollbar.setPosition(this.bottomLeftGrid.getScrollLeft()),this.leftScrollbar.populate(),this.rightScrollbar.setContentSize(d),this.rightScrollbar.setSize(this._width-b),this.rightScrollbar.setPosition(this.bottomRightGrid.getScrollLeft()),this.rightScrollbar.populate();var g=this.scrollBarLayout.attr("items");g[0].top=this._getFreezeHeaderHeight(),g[1].top=this._height,g[2].top=this._height,g[2].left=b,this.scrollBarLayout.attr("items",g),this.scrollBarLayout.resize()},_getHeader:function(){var a=this.options,b=this._getFreezeColLength(),c=[],d=[];return BI.each(a.header,function(a,e){c[a]=[],d[a]=[],BI.each(e,function(e,f){var g={type:"bi.grid_table_cell",cell:f};e0?c/g:0),this.topLeftGrid.setEstimatedRowSize(a.headerRowSize),this.topRightGrid.setEstimatedColumnSize(a.columnSize.length-g>0?d/(a.columnSize.length-g):0),this.topRightGrid.setEstimatedRowSize(a.headerRowSize),this.bottomLeftGrid.setEstimatedColumnSize(g>0?c/g:0),this.bottomLeftGrid.setEstimatedRowSize(a.rowSize),this.bottomRightGrid.setEstimatedColumnSize(a.columnSize.length-g>0?d/(a.columnSize.length-g):0),this.bottomRightGrid.setEstimatedRowSize(a.rowSize),this.topLeftGrid.setColumnCount(g),this.topRightGrid.setColumnCount(a.columnSize.length-g),this.bottomLeftGrid.setColumnCount(g),this.bottomRightGrid.setColumnCount(a.columnSize.length-g);var y=this.contextLayout.attr("items");y[1].left=b,y[2].top=this._getFreezeHeaderHeight(),y[3].left=b,y[3].top=this._getFreezeHeaderHeight(),this.contextLayout.attr("items",y),this.contextLayout.resize(),this.topLeftGrid._populate(this.header[0]),this.topRightGrid._populate(this.header[1]),this.bottomLeftGrid._populate(this.items[0]),this.bottomRightGrid._populate(this.items[1])},_populate:function(){this._width<=0||this._height<=0||(this._populateTable(),this._populateScrollbar())},getRegionSize:function(){var a=this.options,b=a.regionColumnSize[0]||0;return a.isNeedFreeze===!1||0===a.freezeCols.length?0:(b||BI.each(a.freezeCols,function(c,d){b+=a.columnSize[d]}),b)},setVerticalScroll:function(a){this.bottomLeftGrid.setScrollTop(a),this.bottomRightGrid.setScrollTop(a)},setLeftHorizontalScroll:function(a){this.topLeftGrid.setScrollLeft(a),this.bottomLeftGrid.setScrollLeft(a)},setRightHorizontalScroll:function(a){this.topRightGrid.setScrollLeft(a),this.bottomRightGrid.setScrollLeft(a)},getVerticalScroll:function(){return this.bottomRightGrid.getScrollTop()},getLeftHorizontalScroll:function(){return this.bottomLeftGrid.getScrollLeft()},getRightHorizontalScroll:function(){return this.bottomRightGrid.getScrollLeft()},setWidth:function(a){BI.GridTable.superclass.setWidth.apply(this,arguments),this._width=this.options.width-BI.GridTableScrollbar.SIZE},setHeight:function(a){BI.GridTable.superclass.setHeight.apply(this,arguments),this._height=this.options.height-BI.GridTableScrollbar.SIZE},setColumnSize:function(a){this.options.columnSize=a,this._isNeedDigest=!0},setRegionColumnSize:function(a){this.options.regionColumnSize=a,this._isNeedDigest=!0},getColumnSize:function(){return this.options.columnSize},getRegionColumnSize:function(){return this.options.regionColumnSize},populate:function(a,b){a&&this.options.items!==a&&(this.options.items=a,this.items=this._getItems(),this._restore()),b&&this.options.header!==b&&(this.options.header=b,this.header=this._getHeader(),this._restore()),this._populate()},_restore:function(){this.topLeftGrid.restore(),this.topRightGrid.restore(),this.bottomLeftGrid.restore(),this.bottomRightGrid.restore()},restore:function(){this._restore()}}),BI.shortcut("bi.grid_table",BI.GridTable),BI.QuickGridTable=BI.inherit(BI.GridTable,{_defaultConfig:function(){return BI.extend(BI.QuickGridTable.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-quick-grid-table"})},render:function(){BI.QuickGridTable.superclass.render.apply(this,arguments);this.options;this.topLeftGrid.setOverflowX(!1),this.topLeftGrid.setOverflowY(!1),this.topRightGrid.setOverflowX(!1),this.topRightGrid.setOverflowY(!1),this.bottomLeftGrid.setOverflowX(!1),this.bottomLeftGrid.setOverflowY(!1),this.bottomRightGrid.setOverflowX(!1),this.bottomRightGrid.setOverflowY(!1)},mounted:function(){BI.QuickGridTable.superclass.mounted.apply(this,arguments);var a=this;this._topLeftWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelLeft,this),BI.bind(this._shouldHandleLeftX,this),BI.bind(this._shouldHandleY,this)),this._topRightWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelRight,this),BI.bind(this._shouldHandleRightX,this),BI.bind(this._shouldHandleY,this)),this._bottomLeftWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelLeft,this),BI.bind(this._shouldHandleLeftX,this),BI.bind(this._shouldHandleY,this)),this._bottomRightWheelHandler=new BI.WheelHandler(BI.bind(this._onWheelRight,this),BI.bind(this._shouldHandleRightX,this),BI.bind(this._shouldHandleY,this)),this.topLeftGrid.element.mousewheel(function(b){a._topLeftWheelHandler.onWheel(b.originalEvent)}),this.topRightGrid.element.mousewheel(function(b){a._topRightWheelHandler.onWheel(b.originalEvent)}),this.bottomLeftGrid.element.mousewheel(function(b){a._bottomLeftWheelHandler.onWheel(b.originalEvent)}),this.bottomRightGrid.element.mousewheel(function(b){a._bottomRightWheelHandler.onWheel(b.originalEvent)})},_shouldHandleLeftX:function(a){return a>0?this.bottomLeftGrid.getScrollLeft()0},_shouldHandleRightX:function(a){return a>0?this.bottomRightGrid.getScrollLeft()0},_shouldHandleY:function(a){return a>0?this.bottomRightGrid.getScrollTop()0},_onWheelLeft:function(a,b){var c=this,d=this.bottomLeftGrid.getScrollTop(),e=this.bottomLeftGrid.getScrollLeft();d+=b,e+=a,this.bottomLeftGrid.setScrollTop(d),this.bottomRightGrid.setScrollTop(d),this.topLeftGrid.setScrollLeft(e),this.bottomLeftGrid.setScrollLeft(e),c._populateScrollbar(),this.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)},_onWheelRight:function(a,b){var c=this,d=this.bottomRightGrid.getScrollTop(),e=this.bottomRightGrid.getScrollLeft();d+=b,e+=a,this.bottomLeftGrid.setScrollTop(d),this.bottomRightGrid.setScrollTop(d),this.topRightGrid.setScrollLeft(e),this.bottomRightGrid.setScrollLeft(e),c._populateScrollbar(),this.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)},_populateTable:function(){var a=this.options,b=this.getRegionSize(),c=0,d=0,e=0,f=[],g=this._getFreezeColLength();BI.each(a.columnSize,function(b,g){a.isNeedFreeze===!0&&a.freezeCols.contains(b)?c+=g:d+=g,e+=g,0===b?f[b]=g:f[b]=f[b-1]+g});var h=b,i=this._getFreezeHeaderHeight(),j=this._width-b,k=this._getFreezeHeaderHeight(),l=b,m=this._height-i,n=this._width-b,o=this._height-k;this.topLeft.setWidth(h),this.topLeft.setHeight(i),this.topRight.setWidth(j),this.topRight.setHeight(k),this.bottomLeft.setWidth(l),this.bottomLeft.setHeight(m),this.bottomRight.setWidth(n),this.bottomRight.setHeight(o),this.topLeftGrid.setWidth(h),this.topLeftGrid.setHeight(i),this.topRightGrid.setWidth(j),this.topRightGrid.setHeight(k),this.bottomLeftGrid.setWidth(l),this.bottomLeftGrid.setHeight(m),this.bottomRightGrid.setWidth(n),this.bottomRightGrid.setHeight(o),this.topLeftGrid.setEstimatedColumnSize(g>0?c/g:0),this.topLeftGrid.setEstimatedRowSize(a.headerRowSize),this.topRightGrid.setEstimatedColumnSize(a.columnSize.length-g>0?d/(a.columnSize.length-g):0),this.topRightGrid.setEstimatedRowSize(a.headerRowSize),this.bottomLeftGrid.setEstimatedColumnSize(g>0?c/g:0),this.bottomLeftGrid.setEstimatedRowSize(a.rowSize),this.bottomRightGrid.setEstimatedColumnSize(a.columnSize.length-g>0?d/(a.columnSize.length-g):0),this.bottomRightGrid.setEstimatedRowSize(a.rowSize),this.topLeftGrid.setColumnCount(g),this.topRightGrid.setColumnCount(a.columnSize.length-g),this.bottomLeftGrid.setColumnCount(g),this.bottomRightGrid.setColumnCount(a.columnSize.length-g);var p=this.contextLayout.attr("items");p[1].left=b,p[2].top=this._getFreezeHeaderHeight(),p[3].left=b,p[3].top=this._getFreezeHeaderHeight(),this.contextLayout.attr("items",p),this.contextLayout.resize();var q=[],r=[],s=[],t=[];BI.each(a.header,function(a,b){q[a]=[],r[a]=[],BI.each(b,function(b,c){var d={type:"bi.grid_table_cell",cell:c};bb&&(this.options.position=b),this._populate(),this.fireEvent(BI.GridTableScrollbar.EVENT_SCROLL,this.options.position)},_onMouseDown:function(a){if(a.target!==this.face.element[0]){var b=this._isHorizontal()?a.offsetX:a.offsetY;b/=this._getScale(),this.options.position=BI.clamp(b-.5*this._getFaceSize()/this._getScale(),0,this.options.contentSize-this.options.size),this._populate(),this.fireEvent(BI.GridTableScrollbar.EVENT_SCROLL,this.options.position)}else this._mouseMoveTracker.captureMouseMoves(a);try{this.element[0].focus()}catch(a){}},_onMouseMove:function(a,b){var c=this._isHorizontal()?a:b;c/=this._getScale(),this.options.position=BI.clamp(this.options.position+c,0,this.options.contentSize-this.options.size),this.isDragging=this._mouseMoveTracker.isDragging(),this._populate(),this.fireEvent(BI.GridTableScrollbar.EVENT_SCROLL,this.options.position)},_onMouseMoveEnd:function(a){this._mouseMoveTracker.releaseMouseMoves(),this.isDragging===!0&&(this.isDragging=!1,this._populate())},_onKeyDown:function(a){var b={BACKSPACE:8,TAB:9,RETURN:13,ALT:18,ESC:27,SPACE:32,PAGE_UP:33,PAGE_DOWN:34,END:35,HOME:36,LEFT:37,UP:38,RIGHT:39,DOWN:40,DELETE:46,COMMA:188,PERIOD:190,A:65,Z:90,ZERO:48,NUMPAD_0:96,NUMPAD_9:105},c=a.keyCode;if(c!==b.TAB){var d=40,e=0;if(this._isHorizontal())switch(c){case b.HOME:e=-1,d=this.options.contentSize;break;case b.LEFT:e=-1;break;case b.RIGHT:e=1;break;default:return}if(!this._isHorizontal())switch(c){case b.SPACE:e=a.shiftKey?-1:1;break;case b.HOME:e=-1,d=this.options.contentSize;break;case b.UP:e=-1;break;case b.DOWN:e=1;break;case b.PAGE_UP:e=-1,d=this.options.size;break;case b.PAGE_DOWN:e=1,d=this.options.size;break;default:return}this.options.position=BI.clamp(this.options.position+d*e,0,this.options.contentSize-this.options.size),a.preventDefault(),this._populate(),this.fireEvent(BI.GridTableScrollbar.EVENT_SCROLL,this.options.position)}},_populate:function(){var a=this.options;if(a.size<1||a.contentSize<=a.size)return void this.setVisible(!1);this.setVisible(!0);var b=a.size,c=this._isHorizontal(),d=this.focused||this.isDragging,e=this._getFaceSize(),f=a.isOpaque;this.element[f===!0?"addClass":"removeClass"]("public-scrollbar-main-opaque"),this.element[d===!0?"addClass":"removeClass"]("public-scrollbar-main-active"),this.face.element[d===!0?"addClass":"removeClass"]("public-scrollbar-face-active");var g=a.position*this._getScale()+this._const.FACE_MARGIN,h=this.contextLayout.attr("items");c?(this.setWidth(b),this.face.setWidth(e-this._const.FACE_MARGIN_2),h[0].left=g,h[0].top=0):(this.setHeight(b),this.face.setHeight(e-this._const.FACE_MARGIN_2),h[0].left=0,h[0].top=g),this.contextLayout.attr("items",h),this.contextLayout.resize()},setContentSize:function(a){this.options.contentSize=a},setPosition:function(a){this.options.position=a},setSize:function(a){this.options.size=a},populate:function(){this._populate()}}),BI.GridTableScrollbar.SIZE=10,BI.GridTableScrollbar.EVENT_SCROLL="EVENT_SCROLL",BI.shortcut("bi.grid_table_scrollbar",BI.GridTableScrollbar),BI.GridTableHorizontalScrollbar=BI.inherit(BI.Widget,{_const:{FACE_MARGIN:4,FACE_MARGIN_2:8,FACE_SIZE_MIN:30,KEYBOARD_SCROLL_AMOUNT:40},_defaultConfig:function(){return BI.extend(BI.GridTableHorizontalScrollbar.superclass._defaultConfig.apply(this,arguments),{attributes:{tabIndex:0},contentSize:0,position:0,size:0})},_init:function(){BI.GridTableHorizontalScrollbar.superclass._init.apply(this,arguments);var a=this,b=this.options;this.scrollbar=BI.createWidget({type:"bi.grid_table_scrollbar",orientation:"horizontal",isOpaque:!0,position:b.position,contentSize:b.contentSize,size:b.size}),this.scrollbar.on(BI.GridTableScrollbar.EVENT_SCROLL,function(){a.fireEvent(BI.GridTableHorizontalScrollbar.EVENT_SCROLL,arguments)}),BI.createWidget({type:"bi.absolute",cls:"horizontal-scrollbar",element:this,width:b.size,height:BI.GridTableScrollbar.SIZE,items:[{el:{type:"bi.absolute",scrollable:!1,height:BI.GridTableScrollbar.SIZE,items:[{el:this.scrollbar,left:0,top:0}]},top:0,left:0,right:0}]})},setContentSize:function(a){this.options.contentSize=a,this.scrollbar.setContentSize(a)},setPosition:function(a){this.options.position=a,this.scrollbar.setPosition(a)},setSize:function(a){this.setWidth(a),this.options.size=a,this.scrollbar.setSize(a)},populate:function(){this.scrollbar.populate();var a=this.options;return a.size<1||a.contentSize<=a.size?void this.setVisible(!1):void this.setVisible(!0)}}),BI.GridTableHorizontalScrollbar.EVENT_SCROLL="EVENT_SCROLL",BI.shortcut("bi.grid_table_horizontal_scrollbar",BI.GridTableHorizontalScrollbar), +BI.TableHeaderCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.TableHeaderCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-table-header-cell",text:""})},_init:function(){BI.TableHeaderCell.superclass._init.apply(this,arguments),BI.createWidget({type:"bi.label",element:this,textAlign:"center",height:this.options.height,text:this.options.text,value:this.options.value})}}),BI.shortcut("bi.table_header_cell",BI.TableHeaderCell),BI.Table=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.Table.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-table",logic:{dynamic:!1},isNeedFreeze:!1,freezeCols:[],isNeedMerge:!1,mergeCols:[],mergeRule:function(a,b){return BI.isEqual(a,b)},columnSize:[],headerRowSize:25,footerRowSize:25,rowSize:25,regionColumnSize:!1,header:[],footer:!1,items:[]})},_calculateWidth:function(a){return a&&"0"!==a?(a=BI.parseFloat(a),a<0&&(a=0),a>1.01?a:100*a+"%"):""},_calculateHeight:function(a){return a?a:""},_isRightFreeze:function(){return BI.isNotEmptyArray(this.options.freezeCols)&&0!==BI.first(this.options.freezeCols)},_createTopLeft:function(){var a=this.options,b=this._isRightFreeze();this.topLeftColGroupTds={},this.topLeftBodyTds={},this.topLeftBodyItems={};var c=this._table(),d=this._createColGroup(this.columnLeft,this.topLeftColGroupTds),e=this.topLeftBody=this._body();if(e.element.append(this._createHeaderCells(this.topLeftItems,this.columnLeft,this.mergeLeft,this.topLeftBodyTds,this.topLeftBodyItems)),BI.createWidget({type:"bi.adaptive",element:c,items:[d,e]}),b){var f=0;BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)||(f+=c)}),BI.isNumeric(f)&&f>1&&(f=BI.parseFloat(f)+a.columnSize.length-a.freezeCols.length)}return this.topLeftContainer=BI.createWidget({type:"bi.adaptive",width:this._calculateWidth(f),items:[c]})},_createTopRight:function(){var a=this.options,b=this._isRightFreeze();this.topRightColGroupTds={},this.topRightBodyTds={},this.topRightBodyItems={};var c=this._table(),d=this._createColGroup(this.columnRight,this.topRightColGroupTds),e=this.topRightBody=this._body();if(e.element.append(this._createHeaderCells(this.topRightItems,this.columnRight,this.mergeRight,this.topRightBodyTds,this.topRightBodyItems,this.columnLeft.length)),BI.createWidget({type:"bi.adaptive",element:c,items:[d,e]}),!b){var f=0;BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)||(f+=c)}),BI.isNumeric(f)&&(f=BI.parseFloat(f)+a.columnSize.length-a.freezeCols.length)}return this.topRightContainer=BI.createWidget({type:"bi.adaptive",width:f||void 0,items:[c]})},_createBottomLeft:function(){var a=this.options,b=this._isRightFreeze();this.bottomLeftColGroupTds={},this.bottomLeftBodyTds={},this.bottomLeftBodyItems={};var c=this._table(),d=this._createColGroup(this.columnLeft,this.bottomLeftColGroupTds),e=this._createBottomLeftBody();if(BI.createWidget({type:"bi.adaptive",element:c,items:[d,e]}),b){var f=0;BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)||(f+=c)}),BI.isNumeric(f)&&f>1&&(f=BI.parseFloat(f)+a.columnSize.length-a.freezeCols.length)}return this.bottomLeftContainer=BI.createWidget({type:"bi.adaptive",width:this._calculateWidth(f),items:[c]})},_createBottomLeftBody:function(){var a=this.bottomLeftBody=this._body();return a.element.append(this._createCells(this.bottomLeftItems,this.columnLeft,this.mergeLeft,this.bottomLeftBodyTds,this.bottomLeftBodyItems)),a},_createBottomRight:function(){var a=this.options,b=this._isRightFreeze();this.bottomRightColGroupTds={},this.bottomRightBodyTds={},this.bottomRightBodyItems={};var c=this._table(),d=this._createColGroup(this.columnRight,this.bottomRightColGroupTds),e=this._createBottomRightBody();if(BI.createWidget({type:"bi.adaptive",element:c,items:[d,e]}),!b){var f=0;BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)||(f+=c)}),BI.isNumeric(f)&&f>1&&(f=BI.parseFloat(f)+a.columnSize.length-a.freezeCols.length)}return this.bottomRightContainer=BI.createWidget({type:"bi.adaptive",width:this._calculateWidth(f),items:[c]})},_createBottomRightBody:function(){var a=this.bottomRightBody=this._body();return a.element.append(this._createCells(this.bottomRightItems,this.columnRight,this.mergeRight,this.bottomRightBodyTds,this.bottomRightBodyItems,this.columnLeft.length)),a},_createFreezeTable:function(){var a=this,b=this.options,c=this._isRightFreeze(),d=this._split(b.header);this.topLeftItems=d.left,this.topRightItems=d.right,d=this._split(b.items),this.bottomLeftItems=d.left,this.bottomRightItems=d.right,this.columnLeft=[],this.columnRight=[],BI.each(b.columnSize,function(d,e){b.freezeCols.contains(d)?a[c?"columnRight":"columnLeft"].push(e):a[c?"columnLeft":"columnRight"].push(e)}),this.mergeLeft=[],this.mergeRight=[],BI.each(b.mergeCols,function(d,e){b.freezeCols.contains(e)?a[c?"mergeRight":"mergeLeft"].push(e):a[c?"mergeLeft":"mergeRight"].push(e)});var e=this._createTopLeft(),f=this._createTopRight(),g=this._createBottomLeft(),h=this._createBottomRight();this.scrollTopLeft=BI.createWidget({type:"bi.adaptive",cls:"scroll-top-left",width:"100%",height:"100%",scrollable:!1,items:[e]}),this.scrollTopRight=BI.createWidget({type:"bi.adaptive",cls:"scroll-top-right",width:"100%",height:"100%",scrollable:!1,items:[f]}),this.scrollBottomLeft=BI.createWidget({type:"bi.adaptive",cls:"scroll-bottom-left",width:"100%",height:"100%",scrollable:c||null,scrollx:!c,items:[g]}),this.scrollBottomRight=BI.createWidget({type:"bi.adaptive",cls:"scroll-bottom-right",width:"100%",height:"100%",scrollable:!c||null,scrollx:c,items:[h]}),this.topLeft=BI.createWidget({type:"bi.adaptive",cls:"top-left",scrollable:!1,items:[this.scrollTopLeft]}),this.topRight=BI.createWidget({type:"bi.adaptive",cls:"top-right",scrollable:!1,items:[this.scrollTopRight]}),this.bottomLeft=BI.createWidget({type:"bi.adaptive",cls:"bottom-left",items:[this.scrollBottomLeft]}),this.bottomRight=BI.createWidget({type:"bi.adaptive",cls:"bottom-right",scrollable:!1,items:[this.scrollBottomRight]});var i=b.header.length*((b.headerRowSize||b.rowSize)+1)+1,j=BI.sum(b.freezeCols,function(a,c){return b.columnSize[c]>1?b.columnSize[c]+1:b.columnSize[c]});this._resize=function(){a.scrollBottomLeft.element.is(":visible")&&(a.scrollBottomLeft.element.css({"overflow-x":"auto"}),a.scrollBottomRight.element.css({"overflow-x":"auto"}),a.setColumnSize(b.columnSize),c?a.scrollBottomLeft.element.css({"overflow-y":"auto"}):a.scrollBottomRight.element.css({"overflow-y":"auto"}),(a.scrollBottomLeft.element.hasHorizonScroll()||a.scrollBottomRight.element.hasHorizonScroll())&&(a.scrollBottomLeft.element.css("overflow-x","scroll"),a.scrollBottomRight.element.css("overflow-x","scroll")),a.scrollBottomRight.element.hasVerticalScroll()?a.scrollTopRight.element.css("overflow-y","scroll"):a.scrollTopRight.element.css("overflow-y","hidden"),a.scrollBottomLeft.element.hasVerticalScroll()?a.scrollTopLeft.element.css("overflow-y","scroll"):a.scrollTopLeft.element.css("overflow-y","hidden"),a.scrollTopLeft.element[0].scrollLeft=a.scrollBottomLeft.element[0].scrollLeft,a.scrollTopRight.element[0].scrollLeft=a.scrollBottomRight.element[0].scrollLeft,a.scrollBottomLeft.element[0].scrollTop=a.scrollBottomRight.element[0].scrollTop)};var k=b.regionColumnSize;0===b.freezeCols.length?k=c?["fill",0]:[0,"fill"]:b.freezeCols.length>=b.columnSize.length&&(k=c?[0,"fill"]:["fill",0]),this.partitions=BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("table",BI.extend({},b.logic,{rows:2,columns:2,columnSize:k||(c?["fill",j]:[j,"fill"]),rowSize:[i,"fill"],items:[[{el:this.topLeft},{el:this.topRight}],[{el:this.bottomLeft},{el:this.bottomRight}]]})))),this._initFreezeScroll(),BI.ResizeDetector.addResizeListener(this,function(){a._resize(),a.fireEvent(BI.Table.EVENT_TABLE_RESIZE)})},mounted:function(){this._resize&&this._resize(),this.fireEvent(BI.Table.EVENT_TABLE_AFTER_INIT)},_initFreezeScroll:function(){function a(a,c,d){a.scroll(function(e){d.scrollTop(a.scrollTop()),c.scrollLeft(a.scrollLeft()),b.fireEvent(BI.Table.EVENT_TABLE_SCROLL)})}var b=this;this.options;a(this.scrollBottomRight.element,this.scrollTopRight.element,this.scrollBottomLeft.element)},resize:function(){this._resize&&this._resize()},_createCells:function(a,b,c,d,e,f,g){var h=this,i=this.options,j={},k={},l={},m={},n={};b=b||i.columnSize,c=c||i.mergeCols,d=d||{},e=e||{},f=f||0,g||(g=i.rowSize);var o=document.createDocumentFragment();return BI.each(a,function(a,p){function q(a,b){var c=(0|j[b].attr("height"))+g+1;j[b].attr("height",c).css("height",c);var f=(0|(j[b].attr("rowspan")||1))+1;j[b].attr("rowspan",f),j[b].__mergeRows.pushDistinct(a),d[a][b]=j[b],e[a][b]=m[b]}function r(a,c){if(b[c]){var f=0|k[a].attr("width");f>1.05&&b[c]?(f=f+b[c]+1,c===b.length-1&&f--):f+=b[c],f=h._calculateWidth(f),k[a].attr("width",f).css("width",f),l[a].element.width(f)}var g=(0|(k[a].attr("colspan")||1))+1;k[a].attr("colspan",g),k[a].__mergeCols.pushDistinct(c),d[a][c]=k[a],e[a][c]=l[a]}function s(a,c){var i=h._calculateWidth(b[c]);i>1.05&&c===b.length-1&&i--;var o=h._calculateHeight(g),q=$("").attr("height",o).attr("width",i).css({width:i,height:o,position:"relative"}).addClass(0===(1&c)?"odd-col":"even-col").addClass(0===a?"first-row":"").addClass(0===c?"first-col":"").addClass(c===p.length-1?"last-col":""),r=BI.createWidget(n[a][c],{type:"bi.table_cell",textAlign:"left",width:BI.isNumeric(i)?i:"",height:BI.isNumeric(o)?o:"",_row:a,_col:c+f});h.addWidget(r.getName(),r),r._mount(),r.element.css("position","relative"),q.append(r.element),t.append(q),j[c]=q,j[c].__mergeRows=[a],m[c]=r,k[a]=q,k[a].__mergeCols=[c],l[a]=r,d[a][c]=q,e[a][c]=r}var t=$("").addClass(0===(1&a)?"odd":"even");BI.each(p,function(b,f){if(n[a]||(n[a]={}),d[a]||(d[a]={}),e[a]||(e[a]={}),n[a][b]=f,i.isNeedMerge&&c.contains(b))if(0===a&&0===b)s(0,0);else if(0===b&&a>0){var g=i.mergeRule(n[a][b],n[a-1][b]);g===!0?(q(a,b),k[a]=j[b],l[a]=m[b]):s(a,b)}else if(0===a&&b>0){var h=i.mergeRule(n[a][b],n[a][b-1]);h===!0?(r(a,b),j[b]=k[a],m[b]=l[a]):s(a,b)}else{var g=i.mergeRule(n[a][b],n[a-1][b]),h=i.mergeRule(n[a][b],n[a][b-1]);if(h&&g)return;h&&r(a,b),g&&q(a,b),h||g||s(a,b)}else s(a,b)}),o.appendChild(t[0])}),o},_createColGroupCells:function(a,b){var c=this,d=this.options;a=a||d.columnSize,b=b||{};var e=document.createDocumentFragment();return BI.each(a,function(a,d){var f=c._calculateWidth(d),g=$("").attr("width",f).css("width",f);b[a]=g,e.appendChild(g[0])}),e},_createHeaderCells:function(a,b,c,d,e,f){var g=this.options;f||(f=0);var h=this._createCells(a,b,BI.range(g.columnSize.length),d,e,f,g.headerRowSize||g.rowSize);return h},_createFooterCells:function(a,b,c,d){var e=(this.options,this._createCells(a,b,[],c,d,0));return e},_createColGroup:function(a,b,c){this.options;return this.colgroup=this._colgroup(),this.colgroup.element.append(this._createColGroupCells(a,b,c)),this.colgroup},_createHeader:function(){var a=this.options;if(a.header!==!1)return this.header=this._header(),this.header.element.append(this._createHeaderCells(a.header,null,null,this.headerTds,this.headerItems)),this.header},_createFooter:function(a,b,c){var d=this.options;if(d.footer!==!1)return this.footer=this._footer(),this.footer.element.append(this._createFooterCells(d.footer,null,this.footerTds,this.footerItems)),this.footer},_createBody:function(){var a=this.options;return this.body=this._body(),this.body.element.append(this._createCells(a.items,null,null,this.bodyTds,this.bodyItems)),this.body},_createNormalTable:function(){var a=this,b=this.options,c=this._table();this.colgroupTds={},this.headerTds={},this.footerTds={},this.bodyTds={},this.headerItems={},this.footerItems={},this.bodyItems={};var d=this._createColGroup(null,this.colgroupTds),e=this._createHeader(),f=this._createFooter(),g=this._createBody();BI.createWidget({type:"bi.adaptive",element:c,items:[d,e,f,g]});var h=BI.sum(this.options.columnSize)||void 0;h=this._calculateWidth(h),BI.isNumeric(h)&&h>1&&(h+=b.columnSize.length),this.tableContainer=BI.createWidget({type:"bi.adaptive",width:this._calculateWidth(h),items:[c]}),this.scrollBottomRight=BI.createWidget({type:"bi.adaptive",width:"100%",height:"100%",cls:"scroll-bottom-right",scrollable:!0,items:[this.tableContainer]}),BI.createWidget({type:"bi.adaptive",cls:"bottom-right",element:this,scrollable:!1,items:[this.scrollBottomRight]}),this._initNormalScroll(),BI.nextTick(function(){a.element.is(":visible")&&a.fireEvent(BI.Table.EVENT_TABLE_AFTER_INIT)})},_initNormalScroll:function(){var a=this;this.scrollBottomRight.element.scroll(function(b){a.fireEvent(BI.Table.EVENT_TABLE_SCROLL)})},_split:function(a){var b=this.options,c=[],d=[],e=this._isRightFreeze();return BI.each(a,function(a,f){c.push([]),d.push([]),BI.each(f,function(f,g){b.freezeCols.contains(f)?(e?d:c)[a].push(g):(e?c:d)[a].push(g)})}),{left:c,right:d}},_table:function(){return BI.createWidget({type:"bi.layout",tagName:"table",cls:"table",attribute:{cellspacing:0,cellpadding:0}})},_header:function(){return BI.createWidget({type:"bi.layout",cls:"header",tagName:"thead"})},_footer:function(){return BI.createWidget({type:"bi.layout",cls:"footer",tagName:"tfoot"})},_body:function(){return BI.createWidget({type:"bi.layout",tagName:"tbody",cls:"body"})},_colgroup:function(){return BI.createWidget({type:"bi.layout",tagName:"colgroup"})},render:function(){this.populate(this.options.items)},setColumnSize:function(a){var b=this,c=this.options,d=this._isRightFreeze();if(c.columnSize=a||[],c.isNeedFreeze){var e=[],f=[];BI.each(c.columnSize,function(a,b){c.freezeCols.contains(a)?d?f.push(b):e.push(b):d?e.push(b):f.push(b)});var g=0,h=1,i=2,j=3,k=function(a){var c,d,k,l;switch(a){case g:c=b.topLeftColGroupTds,d=b.topLeftBodyTds,k=b.topLeftBodyItems,l=e;break;case h:c=b.topRightColGroupTds,d=b.topRightBodyTds,k=b.topRightBodyItems,l=f;break;case i:c=b.bottomLeftColGroupTds,d=b.bottomLeftBodyTds,k=b.bottomLeftBodyItems,l=e;break;case j:c=b.bottomRightColGroupTds,d=b.bottomRightBodyTds,k=b.bottomRightBodyItems,l=f}BI.each(c,function(a,c){var e=0|c.attr("width");if(""!==l[a]&&e!==l[a]){var f=b._calculateWidth(l[a]);c.attr("width",f).css("width",f),BI.each(d,function(c,d){if(d[a])if(d[a].__mergeCols.length>1){var e=0;BI.each(l,function(b,c){d[a].__mergeCols.contains(b)&&(e+=c)}),e=b._calculateWidth(e),e>1&&(e+=d[a].__mergeCols.length-1),BI.isNumeric(e)?a==BI.size(d)-1?d[a].attr("width",e-1).css("width",e-1):d[a].attr("width",e).css("width",e):d[a].attr("width","").css("width","")}else a==BI.size(d)-1?d[a].attr("width",f-1).css("width",f-1):d[a].attr("width",f).css("width",f)}),BI.each(k,function(c,e){if(e[a])if(d[c][a].__mergeCols.length>1){var g=0;BI.each(l,function(b,e){d[c][a].__mergeCols.contains(b)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=d[c][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")})}})};k(g),k(h),k(i),k(j);var l=0,m=0;this.columnLeft=[],this.columnRight=[],BI.each(c.columnSize,function(a,e){c.freezeCols.contains(a)?(l+=e,b[d?"columnRight":"columnLeft"].push(e)):(m+=e,b[d?"columnLeft":"columnRight"].push(e))}),l=this._calculateWidth(l),m=this._calculateWidth(m),BI.isNumeric(l)&&(l=BI.parseFloat(l)+c.freezeCols.length),BI.isNumeric(m)&&(m=BI.parseFloat(m)+c.columnSize.length-c.freezeCols.length),this.topLeftContainer.element.width(d?m:l),this.bottomLeftContainer.element.width(d?m:l),this.topRightContainer.element.width(d?l:m),this.bottomRightContainer.element.width(d?l:m),this.scrollTopLeft.element[0].scrollLeft=this.scrollBottomLeft.element[0].scrollLeft,this.scrollTopRight.element[0].scrollLeft=this.scrollBottomRight.element[0].scrollLeft}else{BI.each(this.colgroupTds,function(a,d){var e=0|d.attr("width");if(""!==c.columnSize[a]&&e!==c.columnSize[a]){var f=b._calculateWidth(c.columnSize[a]);d.attr("width",f).css("width",f),BI.each(b.bodyTds,function(d,e){if(e[a])if(e[a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(b,c){e[a].__mergeCols.contains(b)&&(g+=c)}),g=b._calculateWidth(g),g>1&&(g+=e[a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f):e[a].attr("width","").css("width","")}else a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f)}),BI.each(b.headerTds,function(d,e){if(e[a])if(e[a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(b,c){e[a].__mergeCols.contains(b)&&(g+=c)}),g=b._calculateWidth(g),g>1&&(g+=e[a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f):e[a].attr("width","").css("width","")}else a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f)}),BI.each(b.footerTds,function(d,e){if(e[a])if(e[a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(b,c){e[a].__mergeCols.contains(b)&&(g+=c)}),g=b._calculateWidth(g),g>1&&(g+=e[a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f):e[a].attr("width","").css("width","")}else a==BI.size(e)-1?e[a].attr("width",f-1).css("width",f-1):e[a].attr("width",f).css("width",f)}),BI.each(b.bodyItems,function(d,e){if(e[a])if(b.bodyTds[d][a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(c,e){b.bodyTds[d][a].__mergeCols.contains(c)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=b.bodyTds[d][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")}),BI.each(b.headerItems,function(d,e){if(e[a])if(b.headerTds[d][a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(c,e){b.headerTds[d][a].__mergeCols.contains(c)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=b.headerTds[d][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")}),BI.each(b.footerItems,function(d,e){if(e[a])if(b.footerTds[d][a].__mergeCols.length>1){var g=0;BI.each(c.columnSize,function(c,e){b.footerTds[d][a].__mergeCols.contains(c)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=b.footerTds[d][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")})}});var n=this._calculateWidth(BI.sum(c.columnSize));n>1.05&&(n+=c.columnSize.length),n>1.05&&this.tableContainer.element.width(n)}},getColumnSize:function(){return this.options.columnSize},getCalculateColumnSize:function(){var a=this,b=this.options,c=[];if(b.isNeedFreeze===!0){if(BI.size(this.bottomLeftBodyTds)>0||BI.size(this.bottomRightBodyTds)>0)return BI.any(this.bottomLeftBodyTds,function(a,b){if(!BI.any(b,function(a,b){if(b.__mergeCols.length>1)return!0}))return BI.each(b,function(a,d){var e=d.width()/d.__mergeCols.length;a==BI.size(b)-1&&e++,c.push(e)}),!0})||BI.each(this.bottomLeftBodyTds[0],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.bottomLeftBodyTds[0])-1&&e++,c.push(e)}),BI.any(this.bottomRightBodyTds,function(a,b){if(!BI.any(b,function(a,b){if(b.__mergeCols.length>1)return!0}))return BI.each(b,function(a,d){var e=d.width()/d.__mergeCols.length;a==BI.size(b)-1&&e++,c.push(e)}),!0})||BI.each(this.bottomRightBodyTds[0],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.bottomRightBodyTds[0])-1&&e++,c.push(e)}),c;BI.any(this.topLeftBodyTds,function(a,b){if(!BI.any(b,function(a,b){if(b.__mergeCols.length>1)return!0}))return BI.each(b,function(a,d){var e=d.width()/d.__mergeCols.length;a==BI.size(b)-1&&e++,c.push(e)}),!0})||BI.each(this.topLeftBodyTds[BI.size(this.topLeftBodyTds)-1],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.topLeftBodyTds[BI.size(a.topLeftBodyTds)-1])-1&&e++,c.push(e)}),BI.any(this.topRightBodyTds,function(a,b){if(!BI.any(b,function(a,b){if(b.__mergeCols.length>1)return!0}))return BI.each(b,function(a,d){var e=d.width()/d.__mergeCols.length;a==BI.size(b)-1&&e++,c.push(e)}),!0})||BI.each(this.topRightBodyTds[BI.size(this.topRightBodyTds)-1],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.topRightBodyTds[BI.size(a.topRightBodyTds)-1])-1&&e++,c.push(e)})}else BI.each(this.headerTds[BI.size(this.headerTds)-1],function(b,d){var e=d.width()/d.__mergeCols.length;b==BI.size(a.headerTds[BI.size(a.headerTds)-1])-1&&e++,c.push(e)});return c},setHeaderColumnSize:function(a){var b=this,c=this.options,d=this._isRightFreeze();if(c.isNeedFreeze){var e=[],f=[];BI.each(a,function(a,b){c.freezeCols.contains(a)?d?f.push(b):e.push(b):d?e.push(b):f.push(b)});var g=0,h=1,i=function(a){var c,d,i,j;switch(a){case g:c=b.topLeftColGroupTds,d=b.topLeftBodyTds,i=b.topLeftBodyItems,j=e;break;case h:c=b.topRightColGroupTds,d=b.topRightBodyTds,i=b.topRightBodyItems,j=f}BI.each(c,function(a,c){var e=0|c.attr("width");if(e!==j[a]){var f=b._calculateWidth(j[a]);c.attr("width",f).css("width",f),BI.each(d,function(c,d){if(d[a])if(d[a].__mergeCols.length>1){var e=0;BI.each(j,function(b,c){d[a].__mergeCols.contains(b)&&(e+=c)}),e=b._calculateWidth(e),e>1&&(e+=d[a].__mergeCols.length-1),BI.isNumeric(e)?a==BI.size(d)-1?d[a].attr("width",e-1).css("width",e-1):d[a].attr("width",e).css("width",e):d[a].attr("width","").css("width","")}else a==BI.size(d)-1?d[a].attr("width",f-1).css("width",f-1):d[a].attr("width",f).css("width",f)}),BI.each(i,function(c,e){if(e[a])if(d[c][a].__mergeCols.length>1){var g=0;BI.each(j,function(b,e){d[c][a].__mergeCols.contains(b)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=d[c][a].__mergeCols.length-1),BI.isNumeric(g)?a==BI.size(e)-1?e[a].element.attr("width",g-1).css("width",g-1):e[a].element.attr("width",g).css("width",g):e[a].element.attr("width","").css("width","")}else BI.isNumeric(f)?a==BI.size(e)-1?e[a].element.attr("width",f-1).css("width",f-1):e[a].element.attr("width",f).css("width",f):e[a].element.attr("width","").css("width","")})}})};i(g),i(h);var j=0,k=0;BI.each(a,function(a,b){c.freezeCols.contains(a)?j+=b:k+=b}),j=this._calculateWidth(j),k=this._calculateWidth(k),BI.isNumeric(j)&&(j=BI.parseFloat(j)+c.freezeCols.length),BI.isNumeric(k)&&(k=BI.parseFloat(k)+a.length-c.freezeCols.length),this.topLeftContainer.element.width(d?k:j),this.topRightContainer.element.width(d?j:k),this.scrollTopLeft.element[0].scrollLeft=this.scrollBottomLeft.element[0].scrollLeft,this.scrollTopRight.element[0].scrollLeft=this.scrollBottomRight.element[0].scrollLeft}else{BI.each(this.colgroupTds,function(c,d){var e=0|d.attr("width");if(e!==a[c]){var f=b._calculateWidth(a[c]);d.attr("width",f).css("width",f),BI.each(b.headerTds,function(d,e){if(e[c])if(e[c].__mergeCols.length>1){var g=0;BI.each(a,function(a,b){e[c].__mergeCols.contains(a)&&(g+=b)}),g=b._calculateWidth(g),g>1&&(g+=e[c].__mergeCols.length-1),BI.isNumeric(g)?c==BI.size(e)-1?e[c].element.attr("width",g-1).css("width",g-1):e[c].element.attr("width",g).css("width",g):e[c].attr("width","").css("width","")}else c==BI.size(e)-1?e[c].attr("width",f-1).css("width",f-1):e[c].attr("width",f).css("width",f)}),BI.each(b.headerItems,function(d,e){if(e[c])if(b.headerTds[d][c].__mergeCols.length>1){var g=0;BI.each(a,function(a,e){b.headerTds[d][c].__mergeCols.contains(a)&&(g+=e)}),g=b._calculateWidth(g),g>1&&(g+=b.headerTds[d][c].__mergeCols.length-1),BI.isNumeric(g)?c==BI.size(e)-1?e[c].element.attr("width",g-1).css("width",g-1):e[c].element.attr("width",g).css("width",g):e[c].element.attr("width","").css("width","")}else BI.isNumeric(f)?c==BI.size(e)-1?e[c].element.attr("width",f-1).css("width",f-1):e[c].element.attr("width",f).css("width",f):e[c].element.attr("width","").css("width","")})}});var l=this._calculateWidth(BI.sum(a));l>1.05&&(l+=a.length),this.tableContainer.element.width(l)}},setRegionColumnSize:function(a){var b=this.options;b.regionColumnSize=a,0===b.freezeCols.length?b.isNeedFreeze?(this.partitions.attr("columnSize",this._isRightFreeze()?["fill",0]:[0,"fill"]),this.partitions.resize()):this.tableContainer.element.width(a[0]):b.freezeCols.length>0&&b.freezeCols.length=d?d:0;e=d?(b+=this.table.getRegionSize(),b-=this.table.getRightHorizontalScroll()):b-=this.table.getLeftHorizontalScroll(),b},_formatHeader:function(a){var b=this,c=this.options,d=[],e=function(a,d){b.resizer.setVisible(!0);var e=c.headerRowSize+b._getRegionRowSize()[1];b.resizer.setHeight(e),b._setResizerPosition(b._getResizerLeft(a)+d,(c.header.length-1)*c.headerRowSize)},f=function(a,d){b.resizer.setVisible(!1);var e=c.columnSize.slice();e[a]=d,c.columnSize=e,b.table.setColumnSize(e),b._populate(),b.fireEvent(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE)};return BI.each(a,function(g,h){g===a.length-1?(d[g]=[],BI.each(h,function(a,i){if(a===b._getFreezeColLength()-1||a===h.length-1)d[g][a]=i;else if(d[g][a]={type:"bi.resizable_table_cell",cell:i,suitableSize:c.minColumnSize[a],maxSize:c.maxColumnSize[a],resize:BI.bind(e,null,a),stop:BI.bind(f,null,a)},c.isNeedMerge)for(var j=g;j>0&&b._mergeRule(d[j][a],d[j-1][a]);)d[j-1][a]={type:"bi.resizable_table_cell",cell:d[j-1][a],suitableSize:c.minColumnSize[a],maxSize:c.maxColumnSize[a],resize:BI.bind(e,null,a),stop:BI.bind(f,null,a)},j--})):d.push(h)}),d},_populate:function(){var a=(this.options,this._getRegionSize());a>0?(this.regionResizerHandler.setVisible(!0),this._setRegionResizerHandlerPosition(a-3,0)):this.regionResizerHandler.setVisible(!1)},setWidth:function(a){BI.ResizableTable.superclass.setWidth.apply(this,arguments),this.table.setWidth(a)},setHeight:function(a){BI.ResizableTable.superclass.setHeight.apply(this,arguments),this.table.setHeight(a)},setVerticalScroll:function(a){this.table.setVerticalScroll(a)},setLeftHorizontalScroll:function(a){this.table.setLeftHorizontalScroll(a)},setRightHorizontalScroll:function(a){this.table.setRightHorizontalScroll(a)},setColumnSize:function(a){this.options.columnSize=a,this.table.setColumnSize(a)},getColumnSize:function(){return this.table.getColumnSize()},setRegionColumnSize:function(a){this.options.regionColumnSize=a,this.table.setRegionColumnSize(a)},getRegionColumnSize:function(){return this.table.getRegionColumnSize()},getVerticalScroll:function(){return this.table.getVerticalScroll()},getLeftHorizontalScroll:function(){return this.table.getLeftHorizontalScroll()},getRightHorizontalScroll:function(){return this.table.getRightHorizontalScroll()},attr:function(){BI.ResizableTable.superclass.attr.apply(this,arguments),this.table.attr.apply(this.table,arguments)},restore:function(){this.table.restore()},populate:function(a,b){a&&(this.options.items=a),b&&(this.options.header=b,this.options.isNeedResize&&(b=this._formatHeader(b))),this.table.populate(a,b),this._populate()}}),BI.shortcut("bi.resizable_table",BI.ResizableTable),BI.CustomTree=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.CustomTree.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-custom-tree",expander:{el:{},popup:{type:"bi.custom_tree"}},items:[],itemsCreator:BI.emptyFn,el:{type:"bi.button_tree",chooseType:0,layouts:[{type:"bi.vertical"}]}})},_init:function(){BI.CustomTree.superclass._init.apply(this,arguments),this.initTree(this.options.items)},_formatItems:function(a){var b=this,c=this.options;a=BI.Tree.transformToTreeFormat(a);var d=[];return BI.each(a,function(a,e){if(BI.isNotEmptyArray(e.children)||e.isParent===!0){var f=BI.extend({type:"bi.expander",el:{},popup:{type:"bi.custom_tree"}},BI.deepClone(c.expander),{id:e.id,pId:e.pId,value:e.value}),g=BI.stripEL(e);BI.isWidget(g)?f.el=g:(g=BI.clone(g),delete g.children,BI.extend(f.el,g)),f.popup.expander=BI.deepClone(c.expander),f.items=f.popup.items=e.children,f.itemsCreator=f.popup.itemsCreator=function(a){if(BI.isNotNull(a.node))return c.itemsCreator.apply(b,arguments);var d=Array.prototype.slice.call(arguments,0);return d[0].node=e,c.itemsCreator.apply(b,d)},BI.isNull(f.popup.el)&&(f.popup.el=BI.deepClone(c.el)),d.push(f)}else d.push(e)}),d},initTree:function(a){var b=this,c=this.options;this.tree=BI.createWidget(c.el,{element:this,items:this._formatItems(a),itemsCreator:function(a,d){c.itemsCreator.apply(this,[a,function(a){var c=Array.prototype.slice.call(arguments,0);c[0]=b._formatItems(a),d.apply(null,c)}])}}),this.tree.on(BI.Controller.EVENT_CHANGE,function(a,c,d){b.fireEvent(BI.Controller.EVENT_CHANGE,arguments),a===BI.Events.CLICK&&b.fireEvent(BI.CustomTree.EVENT_CHANGE,c,d)})},stroke:function(a){this.populate.apply(this,arguments)},populate:function(a){var b=Array.prototype.slice.call(arguments,0);arguments.length>0&&(b[0]=this._formatItems(a)),this.tree.populate.apply(this.tree,b)},setValue:function(a){this.tree&&this.tree.setValue(a)},getValue:function(){return this.tree?this.tree.getValue():[]},getAllButtons:function(){return this.tree?this.tree.getAllButtons():[]},getAllLeaves:function(){return this.tree?this.tree.getAllLeaves():[]},getNodeById:function(a){return this.tree&&this.tree.getNodeById(a)},getNodeByValue:function(a){return this.tree&&this.tree.getNodeByValue(a)},empty:function(){this.tree.empty()}}),BI.CustomTree.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.custom_tree",BI.CustomTree),function($){var settings={},roots={},caches={},_consts={className:{BUTTON:"button",LEVEL:"level",ICO_LOADING:"ico_loading",SWITCH:"switch"},event:{NODECREATED:"ztree_nodeCreated",CLICK:"ztree_click",EXPAND:"ztree_expand",COLLAPSE:"ztree_collapse",ASYNC_SUCCESS:"ztree_async_success",ASYNC_ERROR:"ztree_async_error",REMOVE:"ztree_remove",SELECTED:"ztree_selected",UNSELECTED:"ztree_unselected"},id:{A:"_a",ICON:"_ico",SPAN:"_span",SWITCH:"_switch",UL:"_ul"},line:{ROOT:"root",ROOTS:"roots",CENTER:"center",BOTTOM:"bottom",NOLINE:"noline",LINE:"line"},folder:{OPEN:"open",CLOSE:"close",DOCU:"docu"},node:{CURSELECTED:"curSelectedNode"}},_setting={treeId:"",treeObj:null,view:{addDiyDom:null,autoCancelSelected:!0,dblClickExpand:!0,expandSpeed:"fast",fontCss:{},nameIsHTML:!1,selectedMulti:!0,showIcon:!0,showLine:!0,showTitle:!0,txtSelectedEnable:!1},data:{key:{children:"children",name:"name",title:"",url:"url"},simpleData:{enable:!1,idKey:"id",pIdKey:"pId",rootPId:null},keep:{parent:!1,leaf:!1}},async:{enable:!1,contentType:"application/x-www-form-urlencoded",type:"post",dataType:"text",url:"",autoParam:[],otherParam:[],dataFilter:null},callback:{beforeAsync:null,beforeClick:null,beforeDblClick:null,beforeRightClick:null,beforeMouseDown:null,beforeMouseUp:null,beforeExpand:null,beforeCollapse:null,beforeRemove:null,onAsyncError:null,onAsyncSuccess:null,onNodeCreated:null,onClick:null,onDblClick:null,onRightClick:null,onMouseDown:null,onMouseUp:null,onExpand:null,onCollapse:null,onRemove:null}},_initRoot=function(a){var b=data.getRoot(a);b||(b={},data.setRoot(a,b)),b[a.data.key.children]=[],b.expandTriggerFlag=!1,b.curSelectedList=[],b.noSelection=!0,b.createdNodes=[],b.zId=0,b._ver=(new Date).getTime()},_initCache=function(a){var b=data.getCache(a);b||(b={},data.setCache(a,b)),b.nodes=[],b.doms=[]},_bindEvent=function(a){var b=a.treeObj,c=consts.event;b.bind(c.NODECREATED,function(b,c,d){tools.apply(a.callback.onNodeCreated,[b,c,d])}),b.bind(c.CLICK,function(b,c,d,e,f){tools.apply(a.callback.onClick,[c,d,e,f])}),b.bind(c.EXPAND,function(b,c,d){tools.apply(a.callback.onExpand,[b,c,d])}),b.bind(c.COLLAPSE,function(b,c,d){tools.apply(a.callback.onCollapse,[b,c,d])}),b.bind(c.ASYNC_SUCCESS,function(b,c,d,e){tools.apply(a.callback.onAsyncSuccess,[b,c,d,e])}),b.bind(c.ASYNC_ERROR,function(b,c,d,e,f,g){tools.apply(a.callback.onAsyncError,[b,c,d,e,f,g])}),b.bind(c.REMOVE,function(b,c,d){tools.apply(a.callback.onRemove,[b,c,d])}),b.bind(c.SELECTED,function(b,c,d,e){tools.apply(a.callback.onSelected,[c,d,e])}),b.bind(c.UNSELECTED,function(b,c,d,e){tools.apply(a.callback.onUnSelected,[c,d,e])})},_unbindEvent=function(a){var b=a.treeObj,c=consts.event;b.unbind(c.NODECREATED).unbind(c.CLICK).unbind(c.EXPAND).unbind(c.COLLAPSE).unbind(c.ASYNC_SUCCESS).unbind(c.ASYNC_ERROR).unbind(c.REMOVE).unbind(c.SELECTED).unbind(c.UNSELECTED)},_eventProxy=function(a){var b=a.target,c=data.getSetting(a.data.treeId),d="",e=null,f="",g="",h=null,i=null,j=null;if(tools.eqs(a.type,"mousedown")?g="mousedown":tools.eqs(a.type,"mouseup")?g="mouseup":tools.eqs(a.type,"contextmenu")?g="contextmenu":tools.eqs(a.type,"click")?tools.eqs(b.tagName,"span")&&null!==b.getAttribute("treeNode"+consts.id.SWITCH)?(d=tools.getNodeMainDom(b).id,f="switchNode"):(j=tools.getMDom(c,b,[{tagName:"a",attrName:"treeNode"+consts.id.A}]),j&&(d=tools.getNodeMainDom(j).id,f="clickNode")):tools.eqs(a.type,"dblclick")&&(g="dblclick",j=tools.getMDom(c,b,[{tagName:"a",attrName:"treeNode"+consts.id.A}]),j&&(d=tools.getNodeMainDom(j).id,f="switchNode")),g.length>0&&0==d.length&&(j=tools.getMDom(c,b,[{tagName:"a",attrName:"treeNode"+consts.id.A}]),j&&(d=tools.getNodeMainDom(j).id)),d.length>0)switch(e=data.getNodeCache(c,d),f){case"switchNode":e.isParent&&(tools.eqs(a.type,"click")||tools.eqs(a.type,"dblclick")&&tools.apply(c.view.dblClickExpand,[c.treeId,e],c.view.dblClickExpand))?h=handler.onSwitchNode:f="";break;case"clickNode":h=handler.onClickNode}switch(g){case"mousedown":i=handler.onZTreeMousedown;break;case"mouseup":i=handler.onZTreeMouseup;break;case"dblclick":i=handler.onZTreeDblclick;break;case"contextmenu":i=handler.onZTreeContextmenu}var k={stop:!1,node:e,nodeEventType:f,nodeEventCallback:h,treeEventType:g,treeEventCallback:i};return k},_initNode=function(a,b,c,d,e,f,g){if(c){var h=data.getRoot(a),i=a.data.key.children;c.level=b,c.tId=a.treeId+"_"+ ++h.zId,c.parentTId=d?d.tId:null,c.open="string"==typeof c.open?tools.eqs(c.open,"true"):!!c.open,c[i]&&c[i].length>0?(c.isParent=!0,c.zAsync=!0):(c.isParent="string"==typeof c.isParent?tools.eqs(c.isParent,"true"):!!c.isParent,c.open=!(!c.isParent||a.async.enable)&&c.open,c.zAsync=!c.isParent),c.isFirstNode=e,c.isLastNode=f,c.getParentNode=function(){return data.getNodeCache(a,c.parentTId)},c.getPreNode=function(){return data.getPreNode(a,c)},c.getNextNode=function(){return data.getNextNode(a,c)},c.isAjaxing=!1,data.fixPIdKeyValue(a,c)}},_init={bind:[_bindEvent],unbind:[_unbindEvent],caches:[_initCache],nodes:[_initNode],proxys:[_eventProxy],roots:[_initRoot],beforeA:[],afterA:[],innerBeforeA:[],innerAfterA:[],zTreeTools:[]},data={addNodeCache:function(a,b){data.getCache(a).nodes[data.getNodeCacheId(b.tId)]=b},getNodeCacheId:function(a){return a.substring(a.lastIndexOf("_")+1)},addAfterA:function(a){_init.afterA.push(a)},addBeforeA:function(a){_init.beforeA.push(a)},addInnerAfterA:function(a){_init.innerAfterA.push(a)},addInnerBeforeA:function(a){_init.innerBeforeA.push(a)},addInitBind:function(a){_init.bind.push(a)},addInitUnBind:function(a){_init.unbind.push(a)},addInitCache:function(a){_init.caches.push(a)},addInitNode:function(a){_init.nodes.push(a)},addInitProxy:function(a,b){b?_init.proxys.splice(0,0,a):_init.proxys.push(a)},addInitRoot:function(a){_init.roots.push(a)},addNodesData:function(a,b,c){var d=a.data.key.children;b[d]||(b[d]=[]),b[d].length>0&&(b[d][b[d].length-1].isLastNode=!1,view.setNodeLineIcos(a,b[d][b[d].length-1])),b.isParent=!0,b[d]=b[d].concat(c)},addSelectedNode:function(a,b){var c=data.getRoot(a);data.isSelectedNode(a,b)||c.curSelectedList.push(b)},addCreatedNode:function(a,b){if(a.callback.onNodeCreated||a.view.addDiyDom){var c=data.getRoot(a);c.createdNodes.push(b)}},addZTreeTools:function(a){_init.zTreeTools.push(a)},exSetting:function(a){$.extend(!0,_setting,a)},fixPIdKeyValue:function(a,b){a.data.simpleData.enable&&(b[a.data.simpleData.pIdKey]=b.parentTId?b.getParentNode()[a.data.simpleData.idKey]:a.data.simpleData.rootPId)},getAfterA:function(a,b,c){for(var d=0,e=_init.afterA.length;d-1&&f.push(b[g]),f=f.concat(data.getNodesByParamFuzzy(a,b[g][e],c,d));return f},getNodesByFilter:function(a,b,c,d,e){if(!b)return d?null:[];for(var f=a.data.key.children,g=d?null:[],h=0,i=b.length;h0)},clone:function(a){if(null===a)return null;var b=tools.isArray(a)?[]:{};for(var c in a)b[c]=a[c]instanceof Date?new Date(a[c].getTime()):"object"==typeof a[c]?arguments.callee(a[c]):a[c];return b},eqs:function(a,b){return a.toLowerCase()===b.toLowerCase()},isArray:function(a){return"[object Array]"===Object.prototype.toString.apply(a)},$:function(a,b,c){return b&&"string"!=typeof b&&(c=b,b=""),"string"==typeof a?$(a,c?c.treeObj.get(0).ownerDocument:null):$("#"+a.tId+b,c?c.treeObj:null)},getMDom:function(a,b,c){if(!b)return null;for(;b&&b.id!==a.treeId;){for(var d=0,e=c.length;b.tagName&&d0},uCanDo:function(a,b){return!0}},view={addNodes:function(a,b,c,d){if(!a.data.keep.leaf||!b||b.isParent)if(tools.isArray(c)||(c=[c]),a.data.simpleData.enable&&(c=data.transformTozTreeFormat(a,c)),b){var e=$$(b,consts.id.SWITCH,a),f=$$(b,consts.id.ICON,a),g=$$(b,consts.id.UL,a);b.open||(view.replaceSwitchClass(b,e,consts.folder.CLOSE),view.replaceIcoClass(b,f,consts.folder.CLOSE),b.open=!1,g.css({display:"none"})),data.addNodesData(a,b,c),view.createNodes(a,b.level+1,c,b),d||view.expandCollapseParentNode(a,b,!0)}else data.addNodesData(a,data.getRoot(a),c),view.createNodes(a,0,c,null)},appendNodes:function(a,b,c,d,e,f){if(!c)return[];for(var g=[],h=a.data.key.children,i=0,j=c.length;i0&&(p=view.appendNodes(a,b+1,k[h],k,e,f&&k.open)),f&&(view.makeDOMNodeMainBefore(g,a,k),view.makeDOMNodeLine(g,a,k),data.getBeforeA(a,k,g),view.makeDOMNodeNameBefore(g,a,k),data.getInnerBeforeA(a,k,g),view.makeDOMNodeIcon(g,a,k),data.getInnerAfterA(a,k,g),view.makeDOMNodeNameAfter(g,a,k),data.getAfterA(a,k,g),k.isParent&&k.open&&view.makeUlHtml(a,k,g,p.join("")),view.makeDOMNodeMainAfter(g,a,k),data.addCreatedNode(a,k))}return g},appendParentULDom:function(a,b){var c=[],d=$$(b,a);!d.get(0)&&b.parentTId&&(view.appendParentULDom(a,b.getParentNode()),d=$$(b,a));var e=$$(b,consts.id.UL,a);e.get(0)&&e.remove();var f=a.data.key.children,g=view.appendNodes(a,b.level+1,b[f],b,!1,!0);view.makeUlHtml(a,b,c,g.join("")),d.append(c.join(""))},asyncNode:function(setting,node,isSilent,callback){var i,l;if(node&&!node.isParent)return tools.apply(callback),!1;if(node&&node.isAjaxing)return!1;if(0==tools.apply(setting.callback.beforeAsync,[setting.treeId,node],!0))return tools.apply(callback),!1;if(node){node.isAjaxing=!0;var icoObj=$$(node,consts.id.ICON,setting);icoObj.attr({style:"","class":consts.className.BUTTON+" "+consts.className.ICO_LOADING})}var tmpParam={};for(i=0,l=setting.async.autoParam.length;node&&i1&&(spKey=pKey[1],pKey=pKey[0]),tmpParam[spKey]=node[pKey]}if(tools.isArray(setting.async.otherParam))for(i=0,l=setting.async.otherParam.length;i=0;d--)if(e=f[d],b===e||!b&&(!c||c!==e)){if($$(e,consts.id.A,a).removeClass(consts.node.CURSELECTED),b){data.removeSelectedNode(a,b),a.treeObj.trigger(consts.event.UNSELECTED,[event,a.treeId,e]);break}f.splice(d,1),a.treeObj.trigger(consts.event.UNSELECTED,[event,a.treeId,e])}},createNodeCallback:function(a){if(a.callback.onNodeCreated||a.view.addDiyDom)for(var b=data.getRoot(a);b.createdNodes.length>0;){var c=b.createdNodes.shift();tools.apply(a.view.addDiyDom,[a.treeId,c]),a.callback.onNodeCreated&&a.treeObj.trigger(consts.event.NODECREATED,[a.treeId,c])}},createNodes:function(a,b,c,d){if(c&&0!=c.length){var e=data.getRoot(a),f=a.data.key.children,g=!d||d.open||!!$$(d[f][0],a).get(0);e.createdNodes=[];var h=view.appendNodes(a,b,c,d,!0,g);if(d){var i=$$(d,consts.id.UL,a);i.get(0)&&i.append(h.join(""))}else a.treeObj.append(h.join(""));view.createNodeCallback(a)}},destroy:function(a){a&&(data.initCache(a),data.initRoot(a),event.unbindTree(a),event.unbindEvent(a),a.treeObj.empty(),delete settings[a.treeId])},expandCollapseNode:function(a,b,c,d,e){var f=data.getRoot(a),g=a.data.key.children;if(!b)return void tools.apply(e,[]);if(f.expandTriggerFlag){var h=e;e=function(){h&&h(),b.open?a.treeObj.trigger(consts.event.EXPAND,[a.treeId,b]):a.treeObj.trigger(consts.event.COLLAPSE,[a.treeId,b])},f.expandTriggerFlag=!1}if(!b.open&&b.isParent&&(!$$(b,consts.id.UL,a).get(0)||b[g]&&b[g].length>0&&!$$(b[g][0],a).get(0))&&(view.appendParentULDom(a,b),view.createNodeCallback(a)),b.open==c)return void tools.apply(e,[]);var i=$$(b,consts.id.UL,a),j=$$(b,consts.id.SWITCH,a),k=$$(b,consts.id.ICON,a);b.isParent?(b.open=!b.open,b.iconOpen&&b.iconClose&&k.attr("style",view.makeNodeIcoStyle(a,b)),b.open?(view.replaceSwitchClass(b,j,consts.folder.OPEN),view.replaceIcoClass(b,k,consts.folder.OPEN),0==d||""==a.view.expandSpeed?(i.show(),tools.apply(e,[])):b[g]&&b[g].length>0?i.slideDown(a.view.expandSpeed,e):(i.show(),tools.apply(e,[]))):(view.replaceSwitchClass(b,j,consts.folder.CLOSE),view.replaceIcoClass(b,k,consts.folder.CLOSE),0!=d&&""!=a.view.expandSpeed&&b[g]&&b[g].length>0?i.slideUp(a.view.expandSpeed,e):(i.hide(),tools.apply(e,[])))):tools.apply(e,[])},expandCollapseParentNode:function(a,b,c,d,e){if(b){if(!b.parentTId)return void view.expandCollapseNode(a,b,c,d,e);view.expandCollapseNode(a,b,c,d),b.parentTId&&view.expandCollapseParentNode(a,b.getParentNode(),c,d,e)}},expandCollapseSonNode:function(a,b,c,d,e){var f=data.getRoot(a),g=a.data.key.children,h=b?b[g]:f[g],i=!b&&d,j=data.getRoot(a).expandTriggerFlag;if(data.getRoot(a).expandTriggerFlag=!1,h)for(var k=0,l=h.length;k=0;c--)if(b===d[c])return!0;return!1},makeDOMNodeIcon:function(a,b,c){var d=data.getNodeName(b,c),e=b.view.nameIsHTML?d:d.replace(/&/g,"&").replace(//g,">");a.push("",e,"")},makeDOMNodeLine:function(a,b,c){a.push("")},makeDOMNodeMainAfter:function(a,b,c){a.push("
  • ")},makeDOMNodeMainBefore:function(a,b,c){a.push("
  • ")},makeDOMNodeNameAfter:function(a,b,c){a.push("")},makeDOMNodeNameBefore:function(a,b,c){var d=data.getNodeTitle(b,c),e=view.makeNodeUrl(b,c),f=view.makeNodeFontCss(b,c),g=[];for(var h in f)g.push(h,":",f[h],";");a.push("0?"href='"+e+"'":""," target='",view.makeNodeTarget(c),"' style='",g.join(""),"'"),tools.apply(b.view.showTitle,[b.treeId,c],b.view.showTitle)&&d&&a.push("title='",d.replace(/'/g,"'").replace(//g,">"),"'"),a.push(">")},makeNodeFontCss:function(a,b){var c=tools.apply(a.view.fontCss,[a.treeId,b],a.view.fontCss);return c&&"function"!=typeof c?c:{}},makeNodeIcoClass:function(a,b){var c=["ico"];return b.isAjaxing||(c[0]=(b.iconSkin?b.iconSkin+"_":"")+c[0],b.isParent?c.push(b.open?consts.folder.OPEN:consts.folder.CLOSE):c.push(consts.folder.DOCU)),consts.className.BUTTON+" "+c.join("_")},makeNodeIcoStyle:function(a,b){var c=[];if(!b.isAjaxing){var d=b.isParent&&b.iconOpen&&b.iconClose?b.open?b.iconOpen:b.iconClose:b.icon;d&&c.push("background:url(",d,") 0 0 no-repeat;"),0!=a.view.showIcon&&tools.apply(a.view.showIcon,[a.treeId,b],!0)||c.push("width:0px;height:0px;")}return c.join("")},makeNodeLineClass:function(a,b){var c=[];return a.view.showLine?0==b.level&&b.isFirstNode&&b.isLastNode?c.push(consts.line.ROOT):0==b.level&&b.isFirstNode?c.push(consts.line.ROOTS):b.isLastNode?c.push(consts.line.BOTTOM):c.push(consts.line.CENTER):c.push(consts.line.NOLINE),b.isParent?c.push(b.open?consts.folder.OPEN:consts.folder.CLOSE):c.push(consts.folder.DOCU),view.makeNodeLineClassEx(b)+c.join("_")},makeNodeLineClassEx:function(a){return consts.className.BUTTON+" "+consts.className.LEVEL+a.level+" "+consts.className.SWITCH+" "},makeNodeTarget:function(a){return a.target||"_blank"},makeNodeUrl:function(a,b){var c=a.data.key.url;return b[c]?b[c]:null},makeUlHtml:function(a,b,c,d){c.push("
      "),c.push(d),c.push("
    ")},makeUlLineClass:function(a,b){return a.view.showLine&&!b.isLastNode?consts.line.LINE:""},removeChildNodes:function(a,b){ +if(b){var c=a.data.key.children,d=b[c];if(d){for(var e=0,f=d.length;e0&&(b[c][0].isFirstNode=!0)},setLastNode:function(a,b){var c=a.data.key.children,d=b[c].length;d>0&&(b[c][d-1].isLastNode=!0)},removeNode:function(a,b){var c=data.getRoot(a),d=a.data.key.children,e=b.parentTId?b.getParentNode():c;if(b.isFirstNode=!1,b.isLastNode=!1,b.getPreNode=function(){return null},b.getNextNode=function(){return null},data.getNodeCache(a,b.tId)){$$(b,a).remove(),data.removeNodeCache(a,b),data.removeSelectedNode(a,b);for(var f=0,g=e[d].length;f0){var l=e[d][k-1];if(h=$$(l,consts.id.UL,a),i=$$(l,consts.id.SWITCH,a),j=$$(l,consts.id.ICON,a),e==c)if(1==e[d].length)view.replaceSwitchClass(l,i,consts.line.ROOT);else{var m=$$(e[d][0],consts.id.SWITCH,a);view.replaceSwitchClass(e[d][0],m,consts.line.ROOTS),view.replaceSwitchClass(l,i,consts.line.BOTTOM)}else view.replaceSwitchClass(l,i,consts.line.BOTTOM);h.removeClass(consts.line.LINE)}}else e.isParent=!1,e.open=!1,h=$$(e,consts.id.UL,a),i=$$(e,consts.id.SWITCH,a),j=$$(e,consts.id.ICON,a),view.replaceSwitchClass(e,i,consts.folder.DOCU),view.replaceIcoClass(e,j,consts.folder.DOCU),h.css("display","none")}},replaceIcoClass:function(a,b,c){if(b&&!a.isAjaxing){var d=b.attr("class");if(void 0!=d){var e=d.split("_");switch(c){case consts.folder.OPEN:case consts.folder.CLOSE:case consts.folder.DOCU:e[e.length-1]=c}b.attr("class",e.join("_"))}}},replaceSwitchClass:function(a,b,c){if(b){var d=b.attr("class");if(void 0!=d){var e=d.split("_");switch(c){case consts.line.ROOT:case consts.line.ROOTS:case consts.line.CENTER:case consts.line.BOTTOM:case consts.line.NOLINE:e[0]=view.makeNodeLineClassEx(a)+c;break;case consts.folder.OPEN:case consts.folder.CLOSE:case consts.folder.DOCU:e[1]=c}b.attr("class",e.join("_")),c!==consts.folder.DOCU?b.removeAttr("disabled"):b.attr("disabled","disabled")}}},selectNode:function(a,b,c){c||view.cancelPreSelectedNode(a,null,b),$$(b,consts.id.A,a).addClass(consts.node.CURSELECTED),data.addSelectedNode(a,b),a.treeObj.trigger(consts.event.SELECTED,[event,a.treeId,b])},setNodeFontCss:function(a,b){var c=$$(b,consts.id.A,a),d=view.makeNodeFontCss(a,b);d&&c.css(d)},setNodeLineIcos:function(a,b){if(b){var c=$$(b,consts.id.SWITCH,a),d=$$(b,consts.id.UL,a),e=$$(b,consts.id.ICON,a),f=view.makeUlLineClass(a,b);0==f.length?d.removeClass(consts.line.LINE):d.addClass(f),c.attr("class",view.makeNodeLineClass(a,b)),b.isParent?c.removeAttr("disabled"):c.attr("disabled","disabled"),e.removeAttr("style"),e.attr("style",view.makeNodeIcoStyle(a,b)),e.attr("class",view.makeNodeIcoClass(a,b))}},setNodeName:function(a,b){var c=data.getNodeTitle(a,b),d=$$(b,consts.id.SPAN,a);if(d.empty(),a.view.nameIsHTML?d.html(data.getNodeName(a,b)):d.text(data.getNodeName(a,b)),tools.apply(a.view.showTitle,[a.treeId,b],a.view.showTitle)){var e=$$(b,consts.id.A,a);e.attr("title",c?c:"")}},setNodeTarget:function(a,b){var c=$$(b,consts.id.A,a);c.attr("target",view.makeNodeTarget(b))},setNodeUrl:function(a,b){var c=$$(b,consts.id.A,a),d=view.makeNodeUrl(a,b);null==d||0==d.length?c.removeAttr("href"):c.attr("href",d)},switchNode:function(a,b){if(b.open||!tools.canAsync(a,b))view.expandCollapseNode(a,b,!b.open);else if(a.async.enable){if(!view.asyncNode(a,b))return void view.expandCollapseNode(a,b,!b.open)}else b&&view.expandCollapseNode(a,b,!b.open)}};$.fn.zTree={consts:_consts,_z:{tools:tools,view:view,event:event,data:data},getZTreeObj:function(a){var b=data.getZTreeTools(a);return b?b:null},destroy:function(a){if(a&&a.length>0)view.destroy(data.getSetting(a));else for(var b in settings)view.destroy(settings[b])},init:function(a,b,c){var d=tools.clone(_setting);$.extend(!0,d,b),d.treeId=a.attr("id"),d.treeObj=a,d.treeObj.empty(),settings[d.treeId]=d,"undefined"==typeof document.body.style.maxHeight&&(d.view.expandSpeed=""),data.initRoot(d);var e=data.getRoot(d),f=d.data.key.children;c=c?tools.clone(tools.isArray(c)?c:[c]):[],d.data.simpleData.enable?e[f]=data.transformTozTreeFormat(d,c):e[f]=c,data.initCache(d),event.unbindTree(d),event.bindTree(d),event.unbindEvent(d),event.bindEvent(d);var g={setting:d,addNodes:function(a,b,c){function e(){view.addNodes(d,a,f,1==c)}if(!b)return null;if(a||(a=null),a&&!a.isParent&&d.data.keep.leaf)return null;var f=tools.clone(tools.isArray(b)?b:[b]);return tools.canAsync(d,a)?view.asyncNode(d,a,c,e):e(),f},cancelSelectedNode:function(a){view.cancelPreSelectedNode(d,a)},destroy:function(){view.destroy(d)},expandAll:function(a){return a=!!a,view.expandCollapseSonNode(d,null,a,!0),a},expandNode:function(a,b,c,e,f){if(!a||!a.isParent)return null;if(b!==!0&&b!==!1&&(b=!a.open),f=!!f,f&&b&&0==tools.apply(d.callback.beforeExpand,[d.treeId,a],!0))return null;if(f&&!b&&0==tools.apply(d.callback.beforeCollapse,[d.treeId,a],!0))return null;if(b&&a.parentTId&&view.expandCollapseParentNode(d,a.getParentNode(),b,!1),b===a.open&&!c)return null;if(data.getRoot(d).expandTriggerFlag=f,!tools.canAsync(d,a)&&c)view.expandCollapseSonNode(d,a,b,!0,function(){if(e!==!1)try{$$(a,d).focus().blur()}catch(b){}});else if(a.open=!b,view.switchNode(this.setting,a),e!==!1)try{$$(a,d).focus().blur()}catch(g){}return b},getNodes:function(){return data.getNodes(d)},getNodeByParam:function(a,b,c){return a?data.getNodeByParam(d,c?c[d.data.key.children]:data.getNodes(d),a,b):null},getNodeByTId:function(a){return data.getNodeCache(d,a)},getNodesByParam:function(a,b,c){return a?data.getNodesByParam(d,c?c[d.data.key.children]:data.getNodes(d),a,b):null},getNodesByParamFuzzy:function(a,b,c){return a?data.getNodesByParamFuzzy(d,c?c[d.data.key.children]:data.getNodes(d),a,b):null},getNodesByFilter:function(a,b,c,e){return b=!!b,a&&"function"==typeof a?data.getNodesByFilter(d,c?c[d.data.key.children]:data.getNodes(d),a,b,e):b?null:[]},getNodeIndex:function(a){if(!a)return null;for(var b=d.data.key.children,c=a.parentTId?a.getParentNode():data.getRoot(d),e=0,f=c[b].length;e0?view.createNodes(d,0,e[f]):d.async.enable&&d.async.url&&""!==d.async.url&&view.asyncNode(d),g}};var zt=$.fn.zTree,$$=tools.$,consts=zt.consts}(jQuery),function(a){var b={event:{CHECK:"ztree_check"},id:{CHECK:"_check"},checkbox:{STYLE:"checkbox",DEFAULT:"chk",DISABLED:"disable",FALSE:"false",TRUE:"true",FULL:"full",PART:"part",FOCUS:"focus"},radio:{STYLE:"radio",TYPE_ALL:"all",TYPE_LEVEL:"level"}},c={check:{enable:!1,autoCheckTrigger:!1,chkStyle:b.checkbox.STYLE,nocheckInherit:!1,chkDisabledInherit:!1,radioType:b.radio.TYPE_LEVEL,chkboxType:{Y:"ps",N:"ps"}},data:{key:{checked:"checked"}},callback:{beforeCheck:null,onCheck:null}},d=function(a){var b=v.getRoot(a);b.radioCheckedList=[]},e=function(a){},f=function(a){var b=a.treeObj,c=t.event;b.bind(c.CHECK,function(b,c,d,e){b.srcEvent=c,s.apply(a.callback.onCheck,[b,d,e])})},g=function(a){var b=a.treeObj,c=t.event;b.unbind(c.CHECK)},h=function(a){var b=a.target,c=v.getSetting(a.data.treeId),d="",e=null,f="",g="",h=null,i=null;if(s.eqs(a.type,"mouseover")?c.check.enable&&s.eqs(b.tagName,"span")&&null!==b.getAttribute("treeNode"+t.id.CHECK)&&(d=s.getNodeMainDom(b).id,f="mouseoverCheck"):s.eqs(a.type,"mouseout")?c.check.enable&&s.eqs(b.tagName,"span")&&null!==b.getAttribute("treeNode"+t.id.CHECK)&&(d=s.getNodeMainDom(b).id,f="mouseoutCheck"):s.eqs(a.type,"click")&&c.check.enable&&s.eqs(b.tagName,"span")&&null!==b.getAttribute("treeNode"+t.id.CHECK)&&(d=s.getNodeMainDom(b).id,f="checkNode"),d.length>0)switch(e=v.getNodeCache(c,d),f){case"checkNode":h=n.onCheckNode;break;case"mouseoverCheck":h=n.onMouseoverCheck;break;case"mouseoutCheck":h=n.onMouseoutCheck}var j={stop:"checkNode"===f,node:e,nodeEventType:f,nodeEventCallback:h,treeEventType:g,treeEventCallback:i};return j},i=function(a,b,c,d,e,f,g){if(c){var h=a.data.key.checked;if("string"==typeof c[h]&&(c[h]=s.eqs(c[h],"true")),c[h]=!!c[h],c.checkedOld=c[h],"string"==typeof c.nocheck&&(c.nocheck=s.eqs(c.nocheck,"true")),c.nocheck=!!c.nocheck||a.check.nocheckInherit&&d&&!!d.nocheck,"string"==typeof c.chkDisabled&&(c.chkDisabled=s.eqs(c.chkDisabled,"true")),c.chkDisabled=!!c.chkDisabled||a.check.chkDisabledInherit&&d&&!!d.chkDisabled,"string"==typeof c.halfCheck&&(c.halfCheck=s.eqs(c.halfCheck,"true")),c.halfCheck=!!c.halfCheck,c.check_Child_State=-1,c.check_Focus=!1,c.getCheckStatus=function(){return v.getCheckStatus(a,c)},a.check.chkStyle==t.radio.STYLE&&a.check.radioType==t.radio.TYPE_ALL&&c[h]){var i=v.getRoot(a);i.radioCheckedList.push(c)}}},j=function(a,b,c){a.data.key.checked;a.check.enable&&(v.makeChkFlag(a,b),c.push(""))},k=function(a,b){b.checkNode=function(a,b,c,d){var e=this.setting.data.key.checked;if(a.chkDisabled!==!0&&(b!==!0&&b!==!1&&(b=!a[e]),d=!!d,(a[e]!==b||c)&&(!d||0!=s.apply(this.setting.callback.beforeCheck,[this.setting.treeId,a],!0))&&s.uCanDo(this.setting)&&this.setting.check.enable&&a.nocheck!==!0)){a[e]=b;var f=w(a,t.id.CHECK,this.setting);(c||this.setting.check.chkStyle===t.radio.STYLE)&&u.checkNodeRelation(this.setting,a),u.setChkClass(this.setting,f,a),u.repairParentChkClassWithSelf(this.setting,a),d&&this.setting.treeObj.trigger(t.event.CHECK,[null,this.setting.treeId,a])}},b.checkAllNodes=function(a){u.repairAllChk(this.setting,!!a)},b.getCheckedNodes=function(a){var b=this.setting.data.key.children;return a=a!==!1,v.getTreeCheckedNodes(this.setting,v.getRoot(this.setting)[b],a)},b.getChangeCheckedNodes=function(){var a=this.setting.data.key.children;return v.getTreeChangeCheckedNodes(this.setting,v.getRoot(this.setting)[a])},b.setChkDisabled=function(a,b,c,d){b=!!b,c=!!c,d=!!d,u.repairSonChkDisabled(this.setting,a,b,d),u.repairParentChkDisabled(this.setting,a.getParentNode(),b,c)};var c=b.updateNode;b.updateNode=function(a,d){if(c&&c.apply(b,arguments),a&&this.setting.check.enable){var e=w(a,this.setting);if(e.get(0)&&s.uCanDo(this.setting)){var f=w(a,t.id.CHECK,this.setting);1!=d&&this.setting.check.chkStyle!==t.radio.STYLE||u.checkNodeRelation(this.setting,a),u.setChkClass(this.setting,f,a),u.repairParentChkClassWithSelf(this.setting,a)}}}},l={getRadioCheckedList:function(a){for(var b=v.getRoot(a).radioCheckedList,c=0,d=b.length;c-1&&b.check_Child_State<2:b.check_Child_State>0};return d},getTreeCheckedNodes:function(a,b,c,d){if(!b)return[];var e=a.data.key.children,f=a.data.key.checked,g=c&&a.check.chkStyle==t.radio.STYLE&&a.check.radioType==t.radio.TYPE_ALL;d=d?d:[];for(var h=0,i=b.length;h0));h++);return d},getTreeChangeCheckedNodes:function(a,b,c){if(!b)return[];var d=a.data.key.children,e=a.data.key.checked;c=c?c:[];for(var f=0,g=b.length;f0?2:0,2==i){e=2;break}0==i&&(e=0)}else if(a.check.chkStyle==t.checkbox.STYLE){if(i=h.nocheck===!0||h.chkDisabled===!0?h.check_Child_State:h.halfCheck===!0?1:h[d]?h.check_Child_State===-1||2===h.check_Child_State?2:1:h.check_Child_State>0?1:0,1===i){e=1;break}if(2===i&&e>-1&&f>0&&i!==e){e=1;break}if(2===e&&i>-1&&i<2){e=1;break}i>-1&&(e=i)}}b.check_Child_State=e}}},m={},n={onCheckNode:function(a,b){if(b.chkDisabled===!0)return!1;var c=v.getSetting(a.data.treeId),d=c.data.key.checked;if(0==s.apply(c.callback.beforeCheck,[c.treeId,b],!0))return!0;b[d]=!b[d],u.checkNodeRelation(c,b);var e=w(b,t.id.CHECK,c);return u.setChkClass(c,e,b),u.repairParentChkClassWithSelf(c,b),c.treeObj.trigger(t.event.CHECK,[a,c.treeId,b]),!0},onMouseoverCheck:function(a,b){if(b.chkDisabled===!0)return!1;var c=v.getSetting(a.data.treeId),d=w(b,t.id.CHECK,c);return b.check_Focus=!0,u.setChkClass(c,d,b),!0},onMouseoutCheck:function(a,b){if(b.chkDisabled===!0)return!1;var c=v.getSetting(a.data.treeId),d=w(b,t.id.CHECK,c);return b.check_Focus=!1,u.setChkClass(c,d,b),!0}},o={},p={checkNodeRelation:function(a,b){var c,d,e,f=a.data.key.children,g=a.data.key.checked,h=t.radio;if(a.check.chkStyle==h.STYLE){var i=v.getRadioCheckedList(a);if(b[g])if(a.check.radioType==h.TYPE_ALL){for(d=i.length-1;d>=0;d--)c=i[d],c[g]&&c!=b&&(c[g]=!1,i.splice(d,1),u.setChkClass(a,w(c,t.id.CHECK,a),c),c.parentTId!=b.parentTId&&u.repairParentChkClassWithSelf(a,c));i.push(b)}else{var j=b.parentTId?b.getParentNode():v.getRoot(a);for(d=0,e=j[f].length;d-1)&&u.setSonNodeCheckBox(a,b,!0),b[g]||b[f]&&0!=b[f].length&&!(a.check.chkboxType.N.indexOf("s")>-1)||u.setSonNodeCheckBox(a,b,!1),b[g]&&a.check.chkboxType.Y.indexOf("p")>-1&&u.setParentNodeCheckBox(a,b,!0),!b[g]&&a.check.chkboxType.N.indexOf("p")>-1&&u.setParentNodeCheckBox(a,b,!1)},makeChkClass:function(a,b){var c=a.data.key.checked,d=t.checkbox,e=t.radio,f="";f=b.chkDisabled===!0?d.DISABLED:b.halfCheck?d.PART:a.check.chkStyle==e.STYLE?b.check_Child_State<1?d.FULL:d.PART:b[c]?2===b.check_Child_State||b.check_Child_State===-1?d.FULL:d.PART:b.check_Child_State<1?d.FULL:d.PART;var g=a.check.chkStyle+"_"+(b[c]?d.TRUE:d.FALSE)+"_"+f;return g=b.check_Focus&&b.chkDisabled!==!0?g+"_"+d.FOCUS:g,t.className.BUTTON+" "+d.DEFAULT+" "+g},repairAllChk:function(a,b){if(a.check.enable&&a.check.chkStyle===t.checkbox.STYLE)for(var c=a.data.key.checked,d=a.data.key.children,e=v.getRoot(a),f=0,g=e[d].length;f0?u.repairParentChkClass(a,b[c][0]):u.repairParentChkClass(a,b)}},repairSonChkDisabled:function(a,b,c,d){if(b){var e=a.data.key.children;if(b.chkDisabled!=c&&(b.chkDisabled=c),u.repairChkClass(a,b),b[e]&&d)for(var f=0,g=b[e].length;f0){h=!1;break}h&&u.setParentNodeCheckBox(a,b.getParentNode(),c,d)}},setSonNodeCheckBox:function(a,b,c,d){if(b){var e=a.data.key.children,f=a.data.key.checked,g=w(b,t.id.CHECK,a);d||(d=b);var h=!1;if(b[e])for(var i=0,j=b[e].length;i0?c?2:0:-1)):b.check_Child_State=-1,u.setChkClass(a,g,b),a.check.autoCheckTrigger&&b!=d&&b.nocheck!==!0&&b.chkDisabled!==!0&&a.treeObj.trigger(t.event.CHECK,[null,a.treeId,b]))}}},q={tools:o,view:p,event:m,data:l};a.extend(!0,a.fn.zTree.consts,b),a.extend(!0,a.fn.zTree._z,q);var r=a.fn.zTree,s=r._z.tools,t=r.consts,u=r._z.view,v=r._z.data,w=(r._z.event,s.$);v.exSetting(c),v.addInitBind(f),v.addInitUnBind(g),v.addInitCache(e),v.addInitNode(i),v.addInitProxy(h,!0),v.addInitRoot(d),v.addBeforeA(j),v.addZTreeTools(k);var x=u.createNodes;u.createNodes=function(a,b,c,d){x&&x.apply(u,arguments),c&&u.repairParentChkClassWithSelf(a,d)};var y=u.removeNode;u.removeNode=function(a,b){var c=b.getParentNode();y&&y.apply(u,arguments),b&&c&&(u.repairChkClass(a,c),u.repairParentChkClass(a,c))};var z=u.appendNodes;u.appendNodes=function(a,b,c,d,e,f){var g="";return z&&(g=z.apply(u,arguments)),d&&v.makeChkFlag(a,d),g}}(jQuery),BI.IconChangeButton=BI.inherit(BI.Single,{_defaultConfig:function(){var a=BI.IconChangeButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:"bi-icon-change-button",iconClass:"",iconWidth:null,iconHeight:null,stopEvent:!1,stopPropagation:!1,selected:!1,once:!1,forceSelected:!1,forceNotSelected:!1,disableSelected:!1,shadow:!1,isShadowShowingOnSelected:!1,trigger:null,handler:BI.emptyFn})},_init:function(){BI.IconChangeButton.superclass._init.apply(this,arguments);var a=this,b=this.options;this.button=BI.createWidget({type:"bi.icon_button",element:this,cls:b.iconClass,height:b.height,iconWidth:b.iconWidth,iconHeight:b.iconHeight,stopEvent:b.stopEvent,stopPropagation:b.stopPropagation,selected:b.selected,once:b.once,forceSelected:b.forceSelected,forceNotSelected:b.forceNotSelected,disableSelected:b.disableSelected,shadow:b.shadow,isShadowShowingOnSelected:b.isShadowShowingOnSelected,trigger:b.trigger,handler:b.handler}),this.button.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.button.on(BI.IconButton.EVENT_CHANGE,function(){a.fireEvent(BI.IconChangeButton.EVENT_CHANGE,arguments)})},isSelected:function(){return this.button.isSelected()},setSelected:function(a){this.button.setSelected(a)},setIcon:function(a){var b=this.options;b.iconClass!==a&&(this.element.removeClass(b.iconClass).addClass(a),b.iconClass=a)}}),BI.IconChangeButton.EVENT_CHANGE="IconChangeButton.EVENT_CHANGE",BI.shortcut("bi.icon_change_button",BI.IconChangeButton),BI.HalfIconButton=BI.inherit(BI.IconButton,{_defaultConfig:function(){var a=BI.HalfIconButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-half-icon-button check-half-select-icon",height:16,width:16,iconWidth:16,iconHeight:16,selected:!1})},_init:function(){BI.HalfIconButton.superclass._init.apply(this,arguments)},doClick:function(){BI.HalfIconButton.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.HalfIconButton.EVENT_CHANGE)}}),BI.HalfIconButton.EVENT_CHANGE="HalfIconButton.EVENT_CHANGE",BI.shortcut("bi.half_icon_button",BI.HalfIconButton),BI.TriggerIconButton=BI.inherit(BI.IconButton,{_defaultConfig:function(){var a=BI.TriggerIconButton.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-trigger-icon-button",extraCls:"pull-down-font"})},_init:function(){BI.TriggerIconButton.superclass._init.apply(this,arguments)},doClick:function(){BI.TriggerIconButton.superclass.doClick.apply(this,arguments),this.isValid()&&this.fireEvent(BI.TriggerIconButton.EVENT_CHANGE,this)}}),BI.TriggerIconButton.EVENT_CHANGE="TriggerIconButton.EVENT_CHANGE",BI.shortcut("bi.trigger_icon_button",BI.TriggerIconButton),BI.MultiSelectItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MultiSelectItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-multi-select-item",height:25,logic:{dynamic:!1}})},_init:function(){BI.MultiSelectItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.checkbox"}),this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,rgap:b.rgap,text:b.text,keyword:b.keyword,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected())}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(b.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",{type:"bi.center_adapt",items:[this.checkbox],width:36},this.text)}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.MultiSelectItem.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected()),this.isValid()&&this.fireEvent(BI.MultiSelectItem.EVENT_CHANGE,this.getValue(),this)},setSelected:function(a){BI.MultiSelectItem.superclass.setSelected.apply(this,arguments),this.checkbox.setSelected(a)}}),BI.MultiSelectItem.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multi_select_item",BI.MultiSelectItem),BI.SingleSelectIconTextItem=BI.inherit(BI.Single,{_defaultConfig:function(){return BI.extend(BI.SingleSelectIconTextItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-single-select-icon-text-item bi-list-item-active",iconClass:"",hgap:10,height:25})},_init:function(){BI.SingleSelectIconTextItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.text=BI.createWidget({type:"bi.icon_text_item",element:this,cls:b.iconClass,once:b.once,selected:b.selected,height:b.height,iconHeight:b.iconHeight,iconWidth:b.iconWidth,text:b.text,keyword:b.keyword,value:b.value,py:b.py}),this.text.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)})},isSelected:function(){return this.text.isSelected()},setSelected:function(a){this.text.setSelected(a)},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.SingleSelectIconTextItem.superclass.doClick.apply(this,arguments)}}),BI.shortcut("bi.single_select_icon_text_item",BI.SingleSelectIconTextItem),BI.SingleSelectItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.SingleSelectItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-single-select-item bi-list-item-active",hgap:10,height:25,textAlign:"left"})},_init:function(){BI.SingleSelectItem.superclass._init.apply(this,arguments);var a=this.options;this.text=BI.createWidget({type:"bi.label",element:this,textAlign:a.textAlign,whiteSpace:"nowrap",textHeight:a.height,height:a.height,hgap:a.hgap,text:a.text,keyword:a.keyword,value:a.value,py:a.py})},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.SingleSelectItem.superclass.doClick.apply(this,arguments)},setSelected:function(a){BI.SingleSelectItem.superclass.setSelected.apply(this,arguments)}}),BI.shortcut("bi.single_select_item",BI.SingleSelectItem),BI.SingleSelectRadioItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.SingleSelectRadioItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-single-select-radio-item bi-list-item-active",logic:{dynamic:!1},hgap:10,height:25})},_init:function(){BI.SingleSelectRadioItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.radio=BI.createWidget({type:"bi.radio"}),this.radio.on(BI.Controller.EVENT_CHANGE,function(b){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.text=BI.createWidget({type:"bi.label",cls:"list-item-text",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,keyword:b.keyword,value:b.value,py:b.py}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("horizontal",BI.extend(b.logic,{items:BI.LogicFactory.createLogicItemsByDirection("left",{type:"bi.center_adapt",items:[this.radio],width:36},this.text)}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.SingleSelectRadioItem.superclass.doClick.apply(this,arguments),this.radio.setSelected(this.isSelected())},setSelected:function(a){BI.SingleSelectRadioItem.superclass.setSelected.apply(this,arguments),this.radio.setSelected(a)}}),BI.shortcut("bi.single_select_radio_item",BI.SingleSelectRadioItem),BI.ArrowNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.ArrowNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-arrow-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){var a=this,b=this.options;BI.ArrowNode.superclass._init.apply(this,arguments),this.checkbox=BI.createWidget({type:"bi.arrow_tree_group_node_checkbox",iconWidth:13,iconHeight:13}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.ArrowNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isOpened())},setValue:function(a){this.text.setValue(a)},setOpened:function(a){BI.ArrowNode.superclass.setOpened.apply(this,arguments),this.checkbox.setSelected(a)}}),BI.shortcut("bi.arrow_group_node",BI.ArrowNode),BI.FirstPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.FirstPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-first-plus-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.FirstPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.first_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.FirstPlusGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.FirstPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.first_plus_group_node",BI.FirstPlusGroupNode),BI.IconArrowNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.IconArrowNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-icon-arrow-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25,iconHeight:13,iconWidth:13,iconCls:""})},_init:function(){BI.IconArrowNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.tree_group_node_checkbox",width:23,stopPropagation:!0});var c=BI.createWidget({type:"bi.center_adapt",cls:b.iconCls,width:23,items:[{type:"bi.icon",height:b.iconHeight,width:b.iconWidth}]});this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var d=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),e=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},{width:23,el:c},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(d,BI.extend(b.logic,{items:e}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.IconArrowNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.IconArrowNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.icon_arrow_node",BI.IconArrowNode),BI.LastPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.LastPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-last-plus-group-node bi-list-item", +logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.LastPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.last_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.LastPlusGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.LastPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.last_plus_group_node",BI.LastPlusGroupNode),BI.MidPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MidPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-mid-plus-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.MidPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.mid_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.MidPlusGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.MidPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.mid_plus_group_node",BI.MidPlusGroupNode),BI.MultiLayerIconArrowNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MultiLayerIconArrowNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-multilayer-icon-arrow-node bi-list-item",layer:0,id:"",pId:"",open:!1,height:25,iconHeight:13,iconWidth:13,iconCls:""})},_init:function(){BI.MultiLayerIconArrowNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.node=BI.createWidget({type:"bi.icon_arrow_node",iconCls:b.iconCls,id:b.id,pId:b.pId,open:b.open,height:b.height,iconHeight:b.iconHeight,iconWidth:b.iconWidth,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.node.on(BI.Controller.EVENT_CHANGE,function(b){a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",width:13,height:b.height})}),c.push(this.node),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},isOnce:function(){return!0},doRedMark:function(){this.node.doRedMark.apply(this.node,arguments)},unRedMark:function(){this.node.unRedMark.apply(this.node,arguments)},isSelected:function(){return this.node.isSelected()},setSelected:function(a){BI.MultiLayerIconArrowNode.superclass.setSelected.apply(this,arguments),this.node.setSelected(a)},doClick:function(){BI.NodeButton.superclass.doClick.apply(this,arguments),this.node.setSelected(this.isSelected())},setOpened:function(a){BI.MultiLayerIconArrowNode.superclass.setOpened.apply(this,arguments),this.node.setOpened(a)}}),BI.shortcut("bi.multilayer_icon_arrow_node",BI.MultiLayerIconArrowNode),BI.PlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.PlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-plus-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.PlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.tree_node_checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.PlusGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setOpened:function(a){BI.PlusGroupNode.superclass.setOpened.apply(this,arguments),this.checkbox&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.plus_group_node",BI.PlusGroupNode),BI.TriangleGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.TriangleGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-triangle-group-node bi-list-item",logic:{dynamic:!1},id:"",pId:"",open:!1,height:25})},_init:function(){BI.TriangleGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({iconWidth:13,iconHeight:13,type:"bi.tree_group_node_checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py,keyword:b.keyword}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.TriangleGroupNode.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isOpened())},setOpened:function(a){BI.TriangleGroupNode.superclass.setOpened.apply(this,arguments),this.checkbox.setSelected(a)},setText:function(a){BI.TriangleGroupNode.superclass.setText.apply(this,arguments),this.text.setText(a)}}),BI.shortcut("bi.triangle_group_node",BI.TriangleGroupNode),BI.FirstTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.FirstTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-first-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",layer:0,height:25})},_init:function(){BI.FirstTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,0===b.layer?"":{width:13,el:{type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height}},{width:25,el:{type:"bi.layout",cls:"mid-line-conn-background",width:25,height:b.height}},{el:this.text});BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.FirstTreeLeafItem.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setSelected:function(a){BI.FirstTreeLeafItem.superclass.setSelected.apply(this,arguments),this.checkbox.setSelected(a)}}),BI.shortcut("bi.first_tree_leaf_item",BI.FirstTreeLeafItem),BI.IconTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.IconTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-icon-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},height:25,iconWidth:16,iconHeight:16,iconCls:""})},_init:function(){BI.IconTreeLeafItem.superclass._init.apply(this,arguments);var a=this.options,b=BI.createWidget({type:"bi.center_adapt",width:23,cls:a.iconCls,items:[{type:"bi.icon",width:a.iconWidth,height:a.iconHeight}]});this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:a.height,height:a.height,hgap:a.hgap,text:a.text,value:a.value,py:a.py});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:23,el:b},{el:this.text});BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(a.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.IconTreeLeafItem.superclass.doClick.apply(this,arguments)},setSelected:function(a){BI.IconTreeLeafItem.superclass.setSelected.apply(this,arguments)}}),BI.shortcut("bi.icon_tree_leaf_item",BI.IconTreeLeafItem),BI.LastTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.LastTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-last-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",layer:0,height:25})},_init:function(){BI.LastTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,0===b.layer?"":{width:13,el:{type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height}},{width:25,el:{type:"bi.layout",cls:"mid-line-conn-background",width:25,height:b.height}},{el:this.text});BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.LastTreeLeafItem.superclass.doClick.apply(this,arguments)},setSelected:function(a){BI.LastTreeLeafItem.superclass.setSelected.apply(this,arguments)}}),BI.shortcut("bi.last_tree_leaf_item",BI.LastTreeLeafItem),BI.MidTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MidTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-mid-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",layer:0,height:25})},_init:function(){BI.MidTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.checkbox"}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,0===b.layer?"":{width:13,el:{type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height}},{width:25,el:{type:"bi.layout",cls:"mid-line-conn-background",width:25,height:b.height}},{el:this.text});BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.MidTreeLeafItem.superclass.doClick.apply(this,arguments),this.checkbox.setSelected(this.isSelected())},setSelected:function(a){BI.MidTreeLeafItem.superclass.setSelected.apply(this,arguments),this.checkbox.setSelected(a)}}),BI.shortcut("bi.mid_tree_leaf_item",BI.MidTreeLeafItem),BI.MultiLayerIconTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MultiLayerIconTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-multilayer-icon-tree-leaf-item bi-list-item-active",layer:0,height:25,iconCls:"",iconHeight:14,iconWidth:12})},_init:function(){BI.MultiLayerIconTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.item=BI.createWidget({type:"bi.icon_tree_leaf_item",cls:"bi-list-item-none",iconCls:b.iconCls,id:b.id,pId:b.pId,isFront:!0,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py,iconWidth:b.iconWidth,iconHeight:b.iconHeight}),this.item.on(BI.Controller.EVENT_CHANGE,function(b){b!==BI.Events.CLICK&&a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",width:13,height:b.height})}),c.push(this.item),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.item.doRedMark.apply(this.item,arguments)},unRedMark:function(){this.item.unRedMark.apply(this.item,arguments)},doHighLight:function(){this.item.doHighLight.apply(this.item,arguments)},unHighLight:function(){this.item.unHighLight.apply(this.item,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.MultiLayerIconTreeLeafItem.superclass.doClick.apply(this,arguments),this.item.setSelected(this.isSelected())},setSelected:function(a){BI.MultiLayerIconTreeLeafItem.superclass.setSelected.apply(this,arguments),this.item.setSelected(a)},getValue:function(){return this.options.value}}),BI.shortcut("bi.multilayer_icon_tree_leaf_item",BI.MultiLayerIconTreeLeafItem),BI.TreeTextLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.TreeTextLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-tree-text-leaf-item bi-list-item-active",id:"",pId:"",height:25,hgap:0,lgap:0,rgap:0})},_init:function(){BI.TreeTextLeafItem.superclass._init.apply(this,arguments);var a=this.options;this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:a.height,height:a.height,hgap:a.hgap,lgap:a.lgap,rgap:a.hgap,text:a.text,value:a.value,py:a.py}),BI.createWidget({type:"bi.htape",element:this,items:[{el:this.text}]})},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId}}),BI.shortcut("bi.tree_text_leaf_item",BI.TreeTextLeafItem),BI.Calendar=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.Calendar.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:"bi-calendar",logic:{dynamic:!1},min:"1900-01-01",max:"2099-12-31",year:2015,month:7,day:25})},_dateCreator:function(a,b,c){var d=this.options,e={},f=Date.getDate(),g=d.min.match(/\d+/g),h=d.max.match(/\d+/g);a<(0|g[0])&&(a=0|g[0]),a>(0|h[0])&&(a=0|h[0]),f.setFullYear(a,b,c),e.ymd=[f.getFullYear(),f.getMonth(),f.getDate()];var i=Date._MD.slice(0);i[1]=Date.isLeap(e.ymd[0])?29:28,f.setFullYear(e.ymd[0],e.ymd[1],1),e.FDay=f.getDay(),e.PDay=i[0===b?11:b-1]-e.FDay+1,e.NDay=1;var j=[];return BI.each(BI.range(42),function(a){var b,c={},d=e.ymd[0],f=e.ymd[1]+1;a=e.FDay&&a=0?c%12:(12+c%12)%12;return{year:Date.getDate().getFullYear()+d,month:e}}}),BI.shortcut("bi.calendar",BI.Calendar),BI.YearCalendar=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.YearCalendar.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:"bi-year-calendar",behaviors:{},logic:{dynamic:!1},min:"1900-01-01",max:"2099-12-31",year:null})},_yearCreator:function(a){var b=this.options;a=0|a;var c=BI.YearCalendar.getStartYear(a),d=[];return BI.each(BI.range(BI.YearCalendar.INTERVAL),function(a){var e={};Date.checkVoid(c+a,1,1,b.min,b.max)[0]&&(e.disabled=!0),e.text=c+a,d.push(e)}),d},_init:function(){BI.YearCalendar.superclass._init.apply(this,arguments);var a=this,b=this.options;this.currentYear=Date.getDate().getFullYear();var c=this._yearCreator(b.year||this.currentYear),d=c.length,e=BI.makeArray(d,""),f=[0,6,1,7,2,8,3,9,4,10,5,11];BI.each(c,function(a,b){e[a]=c[f[a]]});var g=[];g.push(e.slice(0,2)),g.push(e.slice(2,4)),g.push(e.slice(4,6)),g.push(e.slice(6,8)),g.push(e.slice(8,10)),g.push(e.slice(10,12)),g=BI.map(g,function(a,b){return BI.map(b,function(a,b){return BI.extend(b,{type:"bi.text_item",cls:"bi-list-item-active",textAlign:"center",whiteSpace:"normal",once:!1,forceSelected:!0,height:23,width:38,value:b.text,disabled:b.disabled})})}),this.years=BI.createWidget({type:"bi.button_group",behaviors:b.behaviors,items:BI.createItems(g,{}),layouts:[BI.LogicFactory.createLogic("table",BI.extend({},b.logic,{columns:2,rows:6,columnSize:[.5,.5],rowSize:25})),{type:"bi.center_adapt",vgap:1}]}),this.years.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("vertical",BI.extend({},b.logic,{items:BI.LogicFactory.createLogicItemsByDirection("top",this.years)}))))},isFrontYear:function(){var a=this.options,b=a.year;return b=0|b,!!Date.checkVoid(BI.YearCalendar.getStartYear(b)-1,1,1,a.min,a.max)[0]},isFinalYear:function(){var a=this.options,b=(this._const,a.year);return b=0|b,!!Date.checkVoid(BI.YearCalendar.getEndYear(b)+1,1,1,a.min,a.max)[0]},setValue:function(a){this.years.setValue([a])},getValue:function(){return this.years.getValue()[0]}}),BI.extend(BI.YearCalendar,{INTERVAL:12,getStartYear:function(a){var b=Date.getDate().getFullYear();return a-((a-b+3)%BI.YearCalendar.INTERVAL+12)%BI.YearCalendar.INTERVAL},getEndYear:function(a){return BI.YearCalendar.getStartYear(a)+BI.YearCalendar.INTERVAL},getPageByYear:function(a){var b=Date.getDate().getFullYear();return a=BI.YearCalendar.getStartYear(a),(a-b+3)/BI.YearCalendar.INTERVAL}}),BI.shortcut("bi.year_calendar",BI.YearCalendar),BI.ComplexCanvas=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.ComplexCanvas.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-complex-canvas"})},_init:function(){BI.ComplexCanvas.superclass._init.apply(this,arguments);var a=this.options;this.canvas=BI.createWidget({type:"bi.canvas",element:this,width:a.width,height:a.height})},branch:function(a,b,c,d,e,f){var g=this,h=[].slice.call(arguments);if(h.length<=5)return this.canvas.line.apply(this.canvas,arguments);var i;BI.isOdd(h.length)&&(i=BI.last(h),h=BI.initial(h)),h=[].slice.call(h,2);var j=BI.filter(h,function(a){return a%2===0}),k=BI.filter(h,function(a){return a%2!==0});i||(i={});var l=i.offset||20;if(b>d&&b>f||bd&&b>f)var m=Math.max.apply(this,k)+l;else var m=Math.min.apply(this,k)-l;var n=Math.min.apply(this,j),o=BI.indexOf(j,n),p=Math.max.apply(this,j),q=BI.indexOf(j,p);return this.canvas.line(n,k[o],n,m,p,m,p,k[q],i),BI.each(j,function(a,b){a!==q&&a!==o&&g.canvas.line(b,k[a],b,m,i)}),void this.canvas.line(a,m,a,b,i)}if(a>c&&a>e||ac&&a>e)var r=Math.max.apply(this,j)+l;else var r=Math.min.apply(this,j)-l;var s=Math.min.apply(this,k),t=BI.indexOf(k,s),u=Math.max.apply(this,k),v=BI.indexOf(k,u);return this.canvas.line(j[t],s,r,s,r,u,j[v],u,i),BI.each(k,function(a,b){a!==t&&a!==v&&g.canvas.line(j[a],b,r,b,i)}),void this.canvas.line(r,b,a,b,i)}},stroke:function(a){this.canvas.stroke(a)}}),BI.shortcut("bi.complex_canvas",BI.ComplexCanvas),BI.ArrowTreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.ArrowTreeGroupNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-arrow-tree-group-node",iconWidth:13,iconHeight:13})},_init:function(){BI.ArrowTreeGroupNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.ArrowTreeGroupNodeCheckbox.superclass.setSelected.apply(this,arguments),a?this.element.removeClass("column-next-page-h-font").addClass("column-pre-page-h-font"):this.element.removeClass("column-pre-page-h-font").addClass("column-next-page-h-font")}}),BI.shortcut("bi.arrow_tree_group_node_checkbox",BI.ArrowTreeGroupNodeCheckbox),BI.CheckingMarkNode=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.CheckingMarkNode.superclass._defaultConfig.apply(this,arguments),{extraCls:"check-mark-font",iconWidth:13,iconHeight:13})},_init:function(){BI.CheckingMarkNode.superclass._init.apply(this,arguments),this.setSelected(this.options.selected)},setSelected:function(a){BI.CheckingMarkNode.superclass.setSelected.apply(this,arguments),a===!0?this.element.addClass("check-mark-font"):this.element.removeClass("check-mark-font")}}),BI.shortcut("bi.checking_mark_node",BI.CheckingMarkNode),BI.FirstTreeNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.FirstTreeNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-collapse-icon-type2",iconWidth:25,iconHeight:25})},_init:function(){BI.FirstTreeNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.FirstTreeNodeCheckbox.superclass.setSelected.apply(this,arguments),a===!0?this.element.addClass("tree-expand-icon-type2"):this.element.removeClass("tree-expand-icon-type2")}}),BI.shortcut("bi.first_tree_node_checkbox",BI.FirstTreeNodeCheckbox),BI.LastTreeNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.LastTreeNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-collapse-icon-type4",iconWidth:25,iconHeight:25})},_init:function(){BI.LastTreeNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.LastTreeNodeCheckbox.superclass.setSelected.apply(this,arguments),a===!0?this.element.addClass("tree-expand-icon-type3"):this.element.removeClass("tree-expand-icon-type3")}}),BI.shortcut("bi.last_tree_node_checkbox",BI.LastTreeNodeCheckbox),BI.MidTreeNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.MidTreeNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-collapse-icon-type3",iconWidth:25,iconHeight:25})},_init:function(){BI.MidTreeNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.MidTreeNodeCheckbox.superclass.setSelected.apply(this,arguments),a===!0?this.element.addClass("tree-expand-icon-type3"):this.element.removeClass("tree-expand-icon-type3")}}),BI.shortcut("bi.mid_tree_node_checkbox",BI.MidTreeNodeCheckbox),BI.TreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.TreeGroupNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-node-triangle-collapse-font",iconWidth:13,iconHeight:13})},_init:function(){BI.TreeGroupNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.TreeGroupNodeCheckbox.superclass.setSelected.apply(this,arguments),a?this.element.removeClass("tree-node-triangle-collapse-font").addClass("tree-node-triangle-expand-font"):this.element.removeClass("tree-node-triangle-expand-font").addClass("tree-node-triangle-collapse-font")}}),BI.shortcut("bi.tree_group_node_checkbox",BI.TreeGroupNodeCheckbox),BI.TreeNodeCheckbox=BI.inherit(BI.IconButton,{_defaultConfig:function(){return BI.extend(BI.TreeNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{extraCls:"tree-collapse-icon-type1",iconWidth:25,iconHeight:25})},_init:function(){BI.TreeNodeCheckbox.superclass._init.apply(this,arguments)},setSelected:function(a){BI.TreeNodeCheckbox.superclass.setSelected.apply(this,arguments),a?this.element.addClass("tree-expand-icon-type1"):this.element.removeClass("tree-expand-icon-type1")}}),BI.shortcut("bi.tree_node_checkbox",BI.TreeNodeCheckbox);try{!function(a){if("object"==typeof exports&&"undefined"!=typeof module)module.exports=a();else if("function"==typeof define&&define.amd)define([],a);else{var b;b="undefined"!=typeof window?window:"undefined"!=typeof global?global:"undefined"!=typeof self?self:this,b.Clipboard=a()}}(function(){var a;return function b(a,c,d){function e(g,h){if(!c[g]){if(!a[g]){var i="function"==typeof require&&require;if(!h&&i)return i(g,!0);if(f)return f(g,!0);var j=new Error("Cannot find module '"+g+"'");throw j.code="MODULE_NOT_FOUND",j}var k=c[g]={exports:{}};a[g][0].call(k.exports,function(b){var c=a[g][1][b];return e(c?c:b)},k,k.exports,b,a,c,d)}return c[g].exports}for(var f="function"==typeof require&&require,g=0;g0&&void 0!==arguments[0]?arguments[0]:{};this.action=a.action,this.emitter=a.emitter,this.target=a.target,this.text=a.text,this.trigger=a.trigger,this.selectedText=""}},{key:"initSelection",value:function(){this.text?this.selectFake():this.target&&this.selectTarget()}},{key:"selectFake",value:function(){var a=this,b="rtl"==document.documentElement.getAttribute("dir");this.removeFake(),this.fakeHandlerCallback=function(){return a.removeFake()},this.fakeHandler=document.body.addEventListener("click",this.fakeHandlerCallback)||!0,this.fakeElem=document.createElement("textarea"),this.fakeElem.style.fontSize="12pt",this.fakeElem.style.border="0",this.fakeElem.style.padding="0",this.fakeElem.style.margin="0",this.fakeElem.style.position="absolute",this.fakeElem.style[b?"right":"left"]="-9999px";var c=window.pageYOffset||document.documentElement.scrollTop;this.fakeElem.style.top=c+"px",this.fakeElem.setAttribute("readonly",""),this.fakeElem.value=this.text,document.body.appendChild(this.fakeElem),this.selectedText=(0,e["default"])(this.fakeElem),this.copyText()}},{key:"removeFake",value:function(){this.fakeHandler&&(document.body.removeEventListener("click",this.fakeHandlerCallback),this.fakeHandler=null,this.fakeHandlerCallback=null),this.fakeElem&&(document.body.removeChild(this.fakeElem),this.fakeElem=null)}},{key:"selectTarget",value:function(){this.selectedText=(0,e["default"])(this.target),this.copyText()}},{key:"copyText",value:function(){var a=void 0;try{a=document.execCommand(this.action)}catch(b){a=!1}this.handleResult(a)}},{key:"handleResult",value:function(a){this.emitter.emit(a?"success":"error",{action:this.action,text:this.selectedText,trigger:this.trigger,clearSelection:this.clearSelection.bind(this)})}},{key:"clearSelection",value:function(){this.target&&this.target.blur(),window.getSelection().removeAllRanges()}},{key:"destroy",value:function(){this.removeFake()}},{key:"action",set:function(){var a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:"copy";if(this._action=a,"copy"!==this._action&&"cut"!==this._action)throw new Error('Invalid "action" value, use either "copy" or "cut"')},get:function(){return this._action}},{key:"target",set:function(a){if(void 0!==a){if(!a||"object"!==("undefined"==typeof a?"undefined":f(a))||1!==a.nodeType)throw new Error('Invalid "target" value, use a valid Element');if("copy"===this.action&&a.hasAttribute("disabled"))throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute');if("cut"===this.action&&(a.hasAttribute("readonly")||a.hasAttribute("disabled")))throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes');this._target=a}},get:function(){return this._target}}]),a}();a.exports=h})},{select:5}],8:[function(b,c,d){!function(e,f){if("function"==typeof a&&a.amd)a(["module","./clipboard-action","tiny-emitter","good-listener"],f);else if("undefined"!=typeof d)f(c,b("./clipboard-action"),b("tiny-emitter"),b("good-listener"));else{var g={exports:{}};f(g,e.clipboardAction,e.tinyEmitter,e.goodListener),e.clipboard=g.exports}}(this,function(a,b,c,d){"use strict";function e(a){return a&&a.__esModule?a:{"default":a}}function f(a,b){if(!(a instanceof b))throw new TypeError("Cannot call a class as a function")}function g(a,b){if(!a)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return!b||"object"!=typeof b&&"function"!=typeof b?a:b}function h(a,b){if("function"!=typeof b&&null!==b)throw new TypeError("Super expression must either be null or a function, not "+typeof b);a.prototype=Object.create(b&&b.prototype,{constructor:{value:a,enumerable:!1,writable:!0,configurable:!0}}),b&&(Object.setPrototypeOf?Object.setPrototypeOf(a,b):a.__proto__=b)}function i(a,b){var c="data-clipboard-"+a;if(b.hasAttribute(c))return b.getAttribute(c)}var j=e(b),k=e(c),l=e(d),m=function(){function a(a,b){for(var c=0;c0&&void 0!==arguments[0]?arguments[0]:{};this.action="function"==typeof a.action?a.action:this.defaultAction,this.target="function"==typeof a.target?a.target:this.defaultTarget,this.text="function"==typeof a.text?a.text:this.defaultText}},{key:"listenClick",value:function(a){var b=this;this.listener=(0,l["default"])(a,"click",function(a){return b.onClick(a)})}},{key:"onClick",value:function(a){var b=a.delegateTarget||a.currentTarget;this.clipboardAction&&(this.clipboardAction=null),this.clipboardAction=new j["default"]({action:this.action(b),target:this.target(b),text:this.text(b),trigger:b,emitter:this})}},{key:"defaultAction",value:function(a){return i("action",a)}},{key:"defaultTarget",value:function(a){var b=i("target",a);if(b)return document.querySelector(b)}},{key:"defaultText",value:function(a){return i("text",a)}},{key:"destroy",value:function(){this.listener.destroy(),this.clipboardAction&&(this.clipboardAction.destroy(),this.clipboardAction=null)}}],[{key:"isSupported",value:function(){var a=arguments.length>0&&void 0!==arguments[0]?arguments[0]:["copy","cut"],b="string"==typeof a?[a]:a,c=!!document.queryCommandSupported;return b.forEach(function(a){c=c&&!!document.queryCommandSupported(a)}),c}}]),b}(k["default"]);a.exports=n})},{"./clipboard-action":7,"good-listener":4,"tiny-emitter":6}]},{},[8])(8)})}catch(e){!function(a){a.fn.zclip=function(b){if("object"==typeof b&&!b.length){var c=a.extend({path:"ZeroClipboard.swf",copy:null,beforeCopy:null,afterCopy:null,clickAfter:!0,setHandCursor:!0,setCSSEffects:!0},b);return this.each(function(){var b=a(this);if(b.is(":visible")&&("string"==typeof c.copy||a.isFunction(c.copy))){ZeroClipboard.setMoviePath(c.path);var d=new ZeroClipboard.Client;a.isFunction(c.copy)&&b.bind("zClip_copy",c.copy),a.isFunction(c.beforeCopy)&&b.bind("zClip_beforeCopy",c.beforeCopy),a.isFunction(c.afterCopy)&&b.bind("zClip_afterCopy",c.afterCopy),d.setHandCursor(c.setHandCursor),d.setCSSEffects(c.setCSSEffects),d.addEventListener("mouseOver",function(a){b.trigger("mouseenter")}),d.addEventListener("mouseOut",function(a){b.trigger("mouseleave")}),d.addEventListener("mouseDown",function(e){b.trigger("mousedown"),a.isFunction(c.copy)?d.setText(b.triggerHandler("zClip_copy")):d.setText(c.copy),a.isFunction(c.beforeCopy)&&b.trigger("zClip_beforeCopy")}),d.addEventListener("complete",function(d,e){a.isFunction(c.afterCopy)?b.trigger("zClip_afterCopy"):(e.length>500&&(e=e.substr(0,500)+"...\n\n("+(e.length-500)+" characters not shown)"),b.removeClass("hover"),alert("Copied text to clipboard:\n\n "+e)),c.clickAfter&&b.trigger("click")}),d.glue(b[0],b.parent()[0]),a(window).bind("load resize",function(){d.reposition()})}})}if("string"==typeof b)return this.each(function(){var c=a(this);b=b.toLowerCase();var d=c.data("zclipId"),e=a("#"+d+".zclip");"remove"==b?(e.remove(),c.removeClass("active hover")):"hide"==b?(e.hide(),c.removeClass("active hover")):"show"==b&&e.show()})}}(jQuery);var ZeroClipboard={version:"1.0.7",clients:{},moviePath:"ZeroClipboard.swf",nextId:1,$:function(a){return"string"==typeof a&&(a=document.getElementById(a)),a.addClass||(a.hide=function(){this.style.display="none"},a.show=function(){this.style.display=""},a.addClass=function(a){this.removeClass(a),this.className+=" "+a},a.removeClass=function(a){for(var b=this.className.split(/\s+/),c=-1,d=0;d-1&&(b.splice(c,1),this.className=b.join(" ")),this},a.hasClass=function(a){return!!this.className.match(new RegExp("\\s*"+a+"\\s*"))}),a},setMoviePath:function(a){this.moviePath=a},dispatch:function(a,b,c){var d=this.clients[a];d&&d.receiveEvent(b,c)},register:function(a,b){this.clients[a]=b},getDOMObjectPosition:function(a,b){var c={left:0,top:0,width:a.width?a.width:a.offsetWidth,height:a.height?a.height:a.offsetHeight};return a&&a!=b&&(c.left+=a.offsetLeft,c.top+=a.offsetTop),c},Client:function(a){this.handlers={},this.id=ZeroClipboard.nextId++,this.movieId="ZeroClipboardMovie_"+this.id,ZeroClipboard.register(this.id,this),a&&this.glue(a)}};ZeroClipboard.Client.prototype={id:0,ready:!1,movie:null,clipText:"",handCursorEnabled:!0,cssEffects:!0,handlers:null,glue:function(a,b,c){this.domElement=ZeroClipboard.$(a);var d=99;this.domElement.style.zIndex&&(d=parseInt(this.domElement.style.zIndex,10)+1),"string"==typeof b?b=ZeroClipboard.$(b):"undefined"==typeof b&&(b=document.getElementsByTagName("body")[0]);var e=ZeroClipboard.getDOMObjectPosition(this.domElement,b);this.div=document.createElement("div"),this.div.className="zclip",this.div.id="zclip-"+this.movieId,$(this.domElement).data("zclipId","zclip-"+this.movieId);var f=this.div.style;if(f.position="absolute",f.left=""+e.left+"px",f.top=""+e.top+"px",f.width=""+e.width+"px",f.height=""+e.height+"px",f.zIndex=d,"object"==typeof c)for(addedStyle in c)f[addedStyle]=c[addedStyle];b.appendChild(this.div),this.div.innerHTML=this.getHTML(e.width,e.height)},getHTML:function(a,b){var c="",d="id="+this.id+"&width="+a+"&height="+b;if(navigator.userAgent.match(/MSIE/)){var e=location.href.match(/^https/i)?"https://":"http://";c+=''}else c+='';return c},hide:function(){this.div&&(this.div.style.left="-2000px")},show:function(){this.reposition()},destroy:function(){if(this.domElement&&this.div){this.hide(),this.div.innerHTML="";var a=document.getElementsByTagName("body")[0];try{a.removeChild(this.div)}catch(b){}this.domElement=null,this.div=null}},reposition:function(a){if(a&&(this.domElement=ZeroClipboard.$(a),this.domElement||this.hide()),this.domElement&&this.div){var b=ZeroClipboard.getDOMObjectPosition(this.domElement),c=this.div.style;c.left=""+b.left+"px",c.top=""+b.top+"px"}},setText:function(a){this.clipText=a,this.ready&&this.movie.setText(a)},addEventListener:function(a,b){a=a.toString().toLowerCase().replace(/^on/,""),this.handlers[a]||(this.handlers[a]=[]),this.handlers[a].push(b)},setHandCursor:function(a){this.handCursorEnabled=a,this.ready&&this.movie.setHandCursor(a)},setCSSEffects:function(a){this.cssEffects=!!a},receiveEvent:function(a,b){switch(a=a.toString().toLowerCase().replace(/^on/,"")){case"load":if(this.movie=document.getElementById(this.movieId),!this.movie){var c=this;return void setTimeout(function(){c.receiveEvent("load",null)},1)}if(!this.ready&&navigator.userAgent.match(/Firefox/)&&navigator.userAgent.match(/Windows/)){var c=this;return setTimeout(function(){c.receiveEvent("load",null)},100),void(this.ready=!0)}this.ready=!0;try{this.movie.setText(this.clipText)}catch(d){}try{this.movie.setHandCursor(this.handCursorEnabled)}catch(d){}break;case"mouseover":this.domElement&&this.cssEffects&&(this.domElement.addClass("hover"),this.recoverActive&&this.domElement.addClass("active"));break;case"mouseout":this.domElement&&this.cssEffects&&(this.recoverActive=!1,this.domElement.hasClass("active")&&(this.domElement.removeClass("active"),this.recoverActive=!0),this.domElement.removeClass("hover"));break;case"mousedown":this.domElement&&this.cssEffects&&this.domElement.addClass("active");break;case"mouseup":this.domElement&&this.cssEffects&&(this.domElement.removeClass("active"),this.recoverActive=!1)}if(this.handlers[a])for(var e=0,f=this.handlers[a].length;e=0&&(0|a)<=255},d=BI.createWidgets([{},{},{}],{type:"bi.small_text_editor",cls:"color-picker-editor-input",validationChecker:c,errorText:BI.i18nText("BI-Color_Picker_Error_Text"),allowBlank:!0,value:255,width:32,height:20});BI.each(d,function(b,c){c.on(BI.TextEditor.EVENT_CHANGE,function(){a.R.isValid()&&a.G.isValid()&&a.B.isValid()&&(a.colorShow.element.css("background-color",a.getValue()),a.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE))})}),this.R=d[0],this.G=d[1],this.B=d[2],this.none=BI.createWidget({type:"bi.checkbox",title:BI.i18nText("BI-Basic_Auto")}),this.none.on(BI.Checkbox.EVENT_CHANGE,function(){this.isSelected()?(a.lastColor=a.getValue(),a.setValue("")):a.setValue(a.lastColor||"#000000"),a.R.isValid()&&a.G.isValid()&&a.B.isValid()&&(a.colorShow.element.css("background-color",a.getValue()),a.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE))}),this.transparent=BI.createWidget({type:"bi.checkbox",title:BI.i18nText("BI-Transparent_Color")}),this.transparent.on(BI.Checkbox.EVENT_CHANGE,function(){this.isSelected()?(a.lastColor=a.getValue(),a.setValue("transparent")):a.setValue(a.lastColor||"#000000"),a.R.isValid()&&a.G.isValid()&&a.B.isValid()&&(a.colorShow.element.css("background-color",a.getValue()),a.fireEvent(BI.ColorPickerEditor.EVENT_CHANGE))}),BI.createWidget({type:"bi.htape",element:this,items:[{el:this.colorShow,width:"fill"},{el:b[0],lgap:10,width:16},{el:this.R,width:32},{el:b[1],lgap:10,width:16},{el:this.G,width:32},{el:b[2],lgap:10,width:16},{el:this.B,width:32},{el:{type:"bi.center_adapt",items:[this.none]},width:18},{el:{type:"bi.center_adapt",items:[this.transparent]},width:18}]})},setValue:function(a){if("transparent"===a)return this.transparent.setSelected(!0),this.none.setSelected(!1),this.R.setValue(""),this.G.setValue(""),void this.B.setValue("");a?this.none.setSelected(!1):(a="",this.none.setSelected(!0)),this.transparent.setSelected(!1),this.colorShow.element.css("background-color",a);var b=BI.DOM.rgb2json(BI.DOM.hex2rgb(a));this.R.setValue(BI.isNull(b.r)?"":b.r),this.G.setValue(BI.isNull(b.g)?"":b.g),this.B.setValue(BI.isNull(b.b)?"":b.b)},getValue:function(){return this.transparent.isSelected()?"transparent":BI.DOM.rgb2hex(BI.DOM.json2rgb({r:this.R.getValue(),g:this.G.getValue(),b:this.B.getValue()}))}}),BI.ColorPickerEditor.EVENT_CHANGE="ColorPickerEditor.EVENT_CHANGE",BI.shortcut("bi.color_picker_editor",BI.ColorPickerEditor),BI.Farbtastic=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.Farbtastic.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-farbtastic",width:195,height:195})},_init:function(){BI.Farbtastic.superclass._init.apply(this,arguments)},mounted:function(){var a=this;this.farbtastic=$.farbtastic(this.element,function(b){a.fireEvent(BI.Farbtastic.EVENT_CHANGE,a.getValue(),a)})},setValue:function(a){this.farbtastic.setColor(a)},getValue:function(){return this.farbtastic.color}}),BI.Farbtastic.EVENT_CHANGE="Farbtastic.EVENT_CHANGE",BI.shortcut("bi.farbtastic",BI.Farbtastic),jQuery.fn.farbtastic=function(a){return $.farbtastic(this,a),this},jQuery.farbtastic=function(a,b){var a=$(a).get(0);return a.farbtastic||(a.farbtastic=new jQuery._farbtastic(a,b))},jQuery._farbtastic=function(a,b){var c=this;$(a).html('
    ');var d=$(".farbtastic",a);c.wheel=$(".wheel",a).get(0),c.radius=84,c.square=100,c.width=194,navigator.appVersion.match(/MSIE [0-6]\./)&&$("*",d).each(function(){if("none"!=this.currentStyle.backgroundImage){var a=this.currentStyle.backgroundImage;a=this.currentStyle.backgroundImage.substring(5,a.length-2),$(this).css({backgroundImage:"none",filter:"progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='"+a+"')"})}}),c.linkTo=function(a){return"object"==typeof c.callback&&$(c.callback).unbind("keyup",c.updateValue),c.color=null,"function"==typeof a?c.callback=a:"object"!=typeof a&&"string"!=typeof a||(c.callback=$(a),c.callback.bind("keyup",c.updateValue),c.callback.get(0).value&&c.setColor(c.callback.get(0).value)),this},c.updateValue=function(a){this.value&&this.value!=c.color&&c.setColor(this.value)},c.setColor=function(a){var b=c.unpack(a);return c.color!=a&&b&&(c.color=a,c.rgb=b,c.hsl=c.RGBToHSL(c.rgb),c.updateDisplay()),this},c.setHSL=function(a){return c.hsl=a,c.rgb=c.HSLToRGB(a),c.color=c.pack(c.rgb),c.updateDisplay(),this},c.widgetCoords=function(a){var b,d,e=a.target||a.srcElement,f=c.wheel;if("undefined"!=typeof a.offsetX){for(var g={x:a.offsetX,y:a.offsetY},h=e;h;)h.mouseX=g.x,h.mouseY=g.y,g.x+=h.offsetLeft,g.y+=h.offsetTop,h=h.offsetParent;for(var h=f,i={x:0,y:0};h;){if("undefined"!=typeof h.mouseX){b=h.mouseX-i.x,d=h.mouseY-i.y;break}i.x+=h.offsetLeft,i.y+=h.offsetTop,h=h.offsetParent}for(h=e;h;)h.mouseX=void 0,h.mouseY=void 0,h=h.offsetParent}else{var g=c.absolutePosition(f);b=(a.pageX||0*(a.clientX+$("html").get(0).scrollLeft))-g.x,d=(a.pageY||0*(a.clientY+$("html").get(0).scrollTop))-g.y}return{x:b-c.width/2,y:d-c.width/2}},c.click=function(a){var b=c.widgetCoords(a);return c.circleDrag=2*Math.max(Math.abs(b.x),Math.abs(b.y))>c.square,c.mousemove(a),!1},c.mousemove=function(a){var b=c.widgetCoords(a);if(c.circleDrag){var d=Math.atan2(b.x,-b.y)/6.28;d<0&&(d+=1),c.setHSL([d,c.hsl[1],c.hsl[2]])}else{var e=Math.max(0,Math.min(1,-(b.x/c.square)+.5)),f=Math.max(0,Math.min(1,-(b.y/c.square)+.5));c.setHSL([c.hsl[0],e,f])}return!1},c.updateDisplay=function(){var a=6.28*c.hsl[0];$(".h-marker",d).css({left:Math.round(Math.sin(a)*c.radius+c.width/2)+"px",top:Math.round(-Math.cos(a)*c.radius+c.width/2)+"px"}),$(".sl-marker",d).css({left:Math.round(c.square*(.5-c.hsl[1])+c.width/2)+"px",top:Math.round(c.square*(.5-c.hsl[2])+c.width/2)+"px"}),$(".color",d).css("backgroundColor",c.pack(c.HSLToRGB([c.hsl[0],1,.5]))),"object"==typeof c.callback?($(c.callback).css({backgroundColor:c.color,color:c.hsl[2]>.5?"#000":"#fff"}),$(c.callback).each(function(){this.value&&this.value!=c.color&&(this.value=c.color); })):"function"==typeof c.callback&&c.callback.call(c,c.color)},c.absolutePosition=function(a){var b={x:a.offsetLeft,y:a.offsetTop};if(a.offsetParent){var d=c.absolutePosition(a.offsetParent);b.x+=d.x,b.y+=d.y}return b},c.pack=function(a){var b=Math.round(255*a[0]),c=Math.round(255*a[1]),d=Math.round(255*a[2]);return"#"+(b<16?"0":"")+b.toString(16)+(c<16?"0":"")+c.toString(16)+(d<16?"0":"")+d.toString(16)},c.unpack=function(a){return 7==a.length?[parseInt("0x"+a.substring(1,3))/255,parseInt("0x"+a.substring(3,5))/255,parseInt("0x"+a.substring(5,7))/255]:4==a.length?[parseInt("0x"+a.substring(1,2))/15,parseInt("0x"+a.substring(2,3))/15,parseInt("0x"+a.substring(3,4))/15]:void 0},c.HSLToRGB=function(a){var b,c,d=a[0],e=a[1],f=a[2];return c=f<=.5?f*(e+1):f+e-f*e,b=2*f-c,[this.hueToRGB(b,c,d+.33333),this.hueToRGB(b,c,d),this.hueToRGB(b,c,d-.33333)]},c.hueToRGB=function(a,b,c){return c=c<0?c+1:c>1?c-1:c,6*c<1?a+(b-a)*c*6:2*c<1?b:3*c<2?a+(b-a)*(.66666-c)*6:a},c.RGBToHSL=function(a){var b,c,d,e,f,g,h=a[0],i=a[1],j=a[2];return b=Math.min(h,Math.min(i,j)),c=Math.max(h,Math.max(i,j)),d=c-b,g=(b+c)/2,f=0,g>0&&g<1&&(f=d/(g<.5?2*g:2-2*g)),e=0,d>0&&(c==h&&c!=i&&(e+=(i-j)/d),c==i&&c!=j&&(e+=2+(j-h)/d),c==j&&c!=h&&(e+=4+(h-i)/d),e/=6),[e,f,g]},$("*",d).click(c.click),c.setColor("#000000"),b&&c.linkTo(b)},BI.BubbleCombo=BI.inherit(BI.Widget,{_const:{TRIANGLE_LENGTH:6},_defaultConfig:function(){return BI.extend(BI.BubbleCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-bubble-combo",trigger:"click",toggle:!0,direction:"bottom",isDefaultInit:!1,destroyWhenHide:!1,isNeedAdjustHeight:!0,isNeedAdjustWidth:!0,stopPropagation:!1,adjustLength:0,hideChecker:BI.emptyFn,offsetStyle:"left",el:{},popup:{}})},_init:function(){BI.BubbleCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.combo=BI.createWidget({type:"bi.combo",element:this,trigger:b.trigger,toggle:b.toggle,direction:b.direction,isDefaultInit:b.isDefaultInit,destroyWhenHide:b.destroyWhenHide,isNeedAdjustHeight:b.isNeedAdjustHeight,isNeedAdjustWidth:b.isNeedAdjustWidth,adjustLength:this._getAdjustLength(),stopPropagation:b.stopPropagation,adjustXOffset:0,adjustYOffset:0,hideChecker:b.hideChecker,offsetStyle:b.offsetStyle,el:b.el,popup:BI.extend({type:"bi.bubble_popup_view"},b.popup)}),this.combo.on(BI.Combo.EVENT_TRIGGER_CHANGE,function(){a.fireEvent(BI.BubbleCombo.EVENT_TRIGGER_CHANGE,arguments)}),this.combo.on(BI.Combo.EVENT_CHANGE,function(){a.fireEvent(BI.BubbleCombo.EVENT_CHANGE,arguments)}),this.combo.on(BI.Combo.EVENT_EXPAND,function(){a.fireEvent(BI.BubbleCombo.EVENT_EXPAND,arguments)}),this.combo.on(BI.Combo.EVENT_COLLAPSE,function(){a.fireEvent(BI.BubbleCombo.EVENT_COLLAPSE,arguments)}),this.combo.on(BI.Combo.EVENT_AFTER_INIT,function(){a.fireEvent(BI.BubbleCombo.EVENT_AFTER_INIT,arguments)}),this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW,function(){a.fireEvent(BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW,arguments)}),this.combo.on(BI.Combo.EVENT_AFTER_POPUPVIEW,function(){a._showTriangle(),a.fireEvent(BI.BubbleCombo.EVENT_AFTER_POPUPVIEW,arguments)}),this.combo.on(BI.Combo.EVENT_BEFORE_HIDEVIEW,function(){a._hideTriangle(),a.fireEvent(BI.BubbleCombo.EVENT_BEFORE_HIDEVIEW,arguments)}),this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW,function(){a.fireEvent(BI.BubbleCombo.EVENT_AFTER_HIDEVIEW,arguments)})},_getAdjustLength:function(){return this._const.TRIANGLE_LENGTH+this.options.adjustLength},_createTriangle:function(a){var b={},c={},d=this.options.adjustLength,e=this.element.offset(),f=e.left,g=e.left+this.element.outerWidth(),h=e.top,i=e.top+this.element.outerHeight();switch(a){case"left":b={top:h,height:this.element.outerHeight(),left:f-d-this._const.TRIANGLE_LENGTH},c={width:this._const.TRIANGLE_LENGTH};break;case"right":b={top:h,height:this.element.outerHeight(),left:g+d},c={width:this._const.TRIANGLE_LENGTH};break;case"top":b={left:f,width:this.element.outerWidth(),top:h-d-this._const.TRIANGLE_LENGTH},c={height:this._const.TRIANGLE_LENGTH};break;case"bottom":b={left:f,width:this.element.outerWidth(),top:i+d},c={height:this._const.TRIANGLE_LENGTH}}this.triangle&&this.triangle.destroy(),this.triangle=BI.createWidget(c,{type:"bi.center_adapt",cls:"button-combo-triangle-wrapper",items:[{type:"bi.layout",cls:"bubble-combo-triangle-"+a+" bi-high-light-border"}]}),b.el=this.triangle,BI.createWidget({type:"bi.absolute",element:this,items:[b]})},_createLeftTriangle:function(){this._createTriangle("left")},_createRightTriangle:function(){this._createTriangle("right")},_createTopTriangle:function(){this._createTriangle("top")},_createBottomTriangle:function(){this._createTriangle("bottom")},_showTriangle:function(){var a=this.combo.getPopupPosition();switch(a.dir){case"left,top":case"left,bottom":this._createLeftTriangle(),this.combo.getView().showLine("right");break;case"right,top":case"right,bottom":this._createRightTriangle(),this.combo.getView().showLine("left");break;case"top,left":case"top,right":this._createTopTriangle(),this.combo.getView().showLine("bottom");break;case"bottom,left":case"bottom,right":this._createBottomTriangle(),this.combo.getView().showLine("top")}},_hideTriangle:function(){this.triangle&&this.triangle.destroy(),this.triangle=null,this.combo.getView()&&this.combo.getView().hideLine()},hideView:function(){this._hideTriangle(),this.combo&&this.combo.hideView()},showView:function(){this.combo&&this.combo.showView()},isViewVisible:function(){return this.combo.isViewVisible()}}),BI.BubbleCombo.EVENT_TRIGGER_CHANGE="EVENT_TRIGGER_CHANGE",BI.BubbleCombo.EVENT_CHANGE="EVENT_CHANGE",BI.BubbleCombo.EVENT_EXPAND="EVENT_EXPAND",BI.BubbleCombo.EVENT_COLLAPSE="EVENT_COLLAPSE",BI.BubbleCombo.EVENT_AFTER_INIT="EVENT_AFTER_INIT",BI.BubbleCombo.EVENT_BEFORE_POPUPVIEW="EVENT_BEFORE_POPUPVIEW",BI.BubbleCombo.EVENT_AFTER_POPUPVIEW="EVENT_AFTER_POPUPVIEW",BI.BubbleCombo.EVENT_BEFORE_HIDEVIEW="EVENT_BEFORE_HIDEVIEW",BI.BubbleCombo.EVENT_AFTER_HIDEVIEW="EVENT_AFTER_HIDEVIEW",BI.shortcut("bi.bubble_combo",BI.BubbleCombo),BI.BubblePopupView=BI.inherit(BI.PopupView,{_defaultConfig:function(){var a=BI.BubblePopupView.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:a.baseCls+" bi-bubble-popup-view"})},_init:function(){BI.BubblePopupView.superclass._init.apply(this,arguments)},showLine:function(a){var b={},c={};switch(a){case"left":b={top:0,bottom:0,left:-1},c={width:3};break;case"right":b={top:0,bottom:0,right:-1},c={width:3};break;case"top":b={left:0,right:0,top:-1},c={height:3};break;case"bottom":b={left:0,right:0,bottom:-1},c={height:3}}this.line=BI.createWidget(c,{type:"bi.layout",cls:"bubble-popup-line bi-high-light-background"}),b.el=this.line,BI.createWidget({type:"bi.absolute",element:this,items:[b]})},hideLine:function(){this.line&&this.line.destroy()}}),BI.shortcut("bi.bubble_popup_view",BI.BubblePopupView),BI.BubblePopupBarView=BI.inherit(BI.BubblePopupView,{_defaultConfig:function(){return BI.extend(BI.BubblePopupBarView.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-bubble-bar-popup-view",buttons:[{value:BI.i18nText(BI.i18nText("BI-Basic_Sure"))},{value:BI.i18nText("BI-Basic_Cancel"),level:"ignore"}]})},_init:function(){BI.BubblePopupBarView.superclass._init.apply(this,arguments)},_createToolBar:function(){var a=this.options,b=this,c=[];return BI.each(a.buttons.reverse(),function(a,d){BI.isWidget(d)?c.push(d):c.push(BI.extend({type:"bi.button",height:30,handler:function(a){b.fireEvent(BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON,a)}},d))}),BI.createWidget({type:"bi.right_vertical_adapt",height:40,hgap:10,bgap:10,items:c})}}),BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON="EVENT_CLICK_TOOLBAR_BUTTON",BI.shortcut("bi.bubble_bar_popup_view",BI.BubblePopupBarView),BI.EditorIconCheckCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.EditorIconCheckCombo.superclass._defaultConfig.apply(this,arguments),{baseClass:"bi-check-editor-combo",width:100,height:24,chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,allowBlank:!0,watermark:"",errorText:""})},_init:function(){BI.EditorIconCheckCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget({type:"bi.editor_trigger",items:b.items,height:b.height,validationChecker:b.validationChecker,quitChecker:b.quitChecker,allowBlank:b.allowBlank,watermark:b.watermark,errorText:b.errorText}),this.trigger.on(BI.EditorTrigger.EVENT_CHANGE,function(){a.popup.setValue(this.getValue()),a.fireEvent(BI.EditorIconCheckCombo.EVENT_CHANGE)}),this.popup=BI.createWidget({type:"bi.text_value_check_combo_popup",chooseType:b.chooseType,items:b.items}),this.popup.on(BI.TextValueCheckComboPopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.editorIconCheckCombo.hideView(),a.fireEvent(BI.EditorIconCheckCombo.EVENT_CHANGE)}),this.popup.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editorIconCheckCombo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup,maxHeight:300}})},setValue:function(a){this.editorIconCheckCombo.setValue(a)},getValue:function(){return this.trigger.getValue()},populate:function(a){this.options.items=a,this.editorIconCheckCombo.populate(a)}}),BI.EditorIconCheckCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.editor_icon_check_combo",BI.EditorIconCheckCombo),BI.IconCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.IconCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-icon-combo",width:24,height:24,iconClass:"",el:{},popup:{},minWidth:100,maxWidth:"auto",maxHeight:300,direction:"bottom",adjustLength:3,adjustXOffset:0,adjustYOffset:0,offsetStyle:"left",chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE})},_init:function(){BI.IconCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget(b.el,{type:"bi.icon_combo_trigger",iconClass:b.iconClass,title:b.title,items:b.items,width:b.width,height:b.height,iconWidth:b.iconWidth,iconHeight:b.iconHeight}),this.popup=BI.createWidget(b.popup,{type:"bi.icon_combo_popup",chooseType:b.chooseType,items:b.items}),this.popup.on(BI.IconComboPopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.iconCombo.hideView(),a.fireEvent(BI.IconCombo.EVENT_CHANGE)}),this.popup.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.iconCombo=BI.createWidget({type:"bi.combo",element:this,direction:b.direction,trigger:b.trigger,container:b.container,adjustLength:b.adjustLength,adjustXOffset:b.adjustXOffset,adjustYOffset:b.adjustYOffset,offsetStyle:b.offsetStyle,el:this.trigger,popup:{el:this.popup,maxWidth:b.maxWidth,maxHeight:b.maxHeight,minWidth:b.minWidth}})},showView:function(){this.iconCombo.showView()},hideView:function(){this.iconCombo.hideView()},setValue:function(a){this.iconCombo.setValue(a)},getValue:function(){return this.iconCombo.getValue()},populate:function(a){this.options.items=a,this.iconCombo.populate(a)}}),BI.IconCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_combo",BI.IconCombo),BI.IconComboPopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.IconComboPopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi.icon-combo-popup",chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE})},_init:function(){BI.IconComboPopup.superclass._init.apply(this,arguments);var a=this.options,b=this;this.popup=BI.createWidget({type:"bi.button_group",items:BI.createItems(a.items,{type:"bi.single_select_icon_text_item",height:30}),chooseType:a.chooseType,layouts:[{type:"bi.vertical"}]}),this.popup.on(BI.Controller.EVENT_CHANGE,function(a,c,d){b.fireEvent(BI.Controller.EVENT_CHANGE,arguments),a===BI.Events.CLICK&&b.fireEvent(BI.IconComboPopup.EVENT_CHANGE,c,d)}),BI.createWidget({type:"bi.vertical",element:this,items:[this.popup]})},populate:function(a){BI.IconComboPopup.superclass.populate.apply(this,arguments),a=BI.createItems(a,{type:"bi.single_select_icon_text_item",height:30}),this.popup.populate(a)},getValue:function(){return this.popup.getValue()},setValue:function(a){this.popup.setValue(a)}}),BI.IconComboPopup.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_combo_popup",BI.IconComboPopup),BI.IconComboTrigger=BI.inherit(BI.Trigger,{_defaultConfig:function(){return BI.extend(BI.IconComboTrigger.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-icon-combo-trigger",el:{},items:[],iconClass:"",width:25,height:25,isShowDown:!0})},_init:function(){BI.IconComboTrigger.superclass._init.apply(this,arguments);var a=this.options;this.button=BI.createWidget(a.el,{type:"bi.icon_change_button",cls:"icon-combo-trigger-icon "+a.iconClass,disableSelected:!0,width:a.width,height:a.height,iconWidth:a.iconWidth,iconHeight:a.iconHeight}),this.down=BI.createWidget({type:"bi.icon_button",disableSelected:!0,cls:"icon-combo-down-icon trigger-triangle-font",width:12,height:8}),this.down.setVisible(a.isShowDown),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.button,left:0,right:0,top:0,bottom:0},{el:this.down,right:0,bottom:0}]}),BI.isKey(a.value)&&this.setValue(a.value)},populate:function(a){var b=this.options;this.options.items=a||[],this.button.setIcon(b.iconClass),this.button.setSelected(!1),this.down.setSelected(!1)},setValue:function(a){BI.IconComboTrigger.superclass.setValue.apply(this,arguments);var b=this.options,c="";a=BI.isArray(a)?a[0]:a,BI.any(this.options.items,function(b,d){if(a===d.value)return c=d.iconClass,!0})?(this.button.setIcon(c),this.button.setSelected(!0),this.down.setSelected(!0)):(this.button.setIcon(b.iconClass),this.button.setSelected(!1),this.down.setSelected(!1))}}),BI.IconComboTrigger.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_combo_trigger",BI.IconComboTrigger),BI.IconTextValueCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.IconTextValueCombo.superclass._defaultConfig.apply(this,arguments),{baseClass:"bi-icon-text-value-combo",height:30,value:"",el:{}})},_init:function(){BI.IconTextValueCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget(b.el,{type:"bi.select_icon_text_trigger",items:b.items,height:b.height,value:b.value}),this.popup=BI.createWidget({type:"bi.icon_text_value_combo_popup",items:b.items}),this.popup.on(BI.IconTextValueComboPopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.textIconCombo.hideView(),a.fireEvent(BI.IconTextValueCombo.EVENT_CHANGE,arguments)}),this.popup.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.textIconCombo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup,maxHeight:300}}),BI.isKey(b.value)&&this.setValue(b.value)},setValue:function(a){this.textIconCombo.setValue(a)},getValue:function(){return this.textIconCombo.getValue()},populate:function(a){this.options.items=a,this.textIconCombo.populate(a)}}),BI.IconTextValueCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_text_value_combo",BI.IconTextValueCombo),BI.IconTextValueComboPopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.IconTextValueComboPopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-icon-text-icon-popup"})},_init:function(){BI.IconTextValueComboPopup.superclass._init.apply(this,arguments);var a=this.options,b=this;this.popup=BI.createWidget({type:"bi.button_group",items:BI.createItems(a.items,{type:"bi.single_select_icon_text_item",height:30}),chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,layouts:[{type:"bi.vertical"}]}),this.popup.on(BI.Controller.EVENT_CHANGE,function(a,c,d){b.fireEvent(BI.Controller.EVENT_CHANGE,arguments),a===BI.Events.CLICK&&b.fireEvent(BI.IconTextValueComboPopup.EVENT_CHANGE,c,d)}),BI.createWidget({type:"bi.vertical",element:this,items:[this.popup]})},populate:function(a){BI.IconTextValueComboPopup.superclass.populate.apply(this,arguments),a=BI.createItems(a,{type:"bi.single_select_icon_text_item",height:30}),this.popup.populate(a)},getValue:function(){return this.popup.getValue()},setValue:function(a){this.popup.setValue(a)}}),BI.IconTextValueComboPopup.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.icon_text_value_combo_popup",BI.IconTextValueComboPopup),BI.StaticCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.StaticCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-static-combo",height:24,text:"",el:{},items:[],chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE})},_init:function(){BI.StaticCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget(b.el,{type:"bi.text_icon_item",cls:"bi-select-text-trigger bi-border pull-down-font",text:b.text,readonly:!0,textLgap:5,height:b.height-2}),this.popup=BI.createWidget({type:"bi.text_value_combo_popup",textAlign:b.textAlign,chooseType:b.chooseType,items:b.items}),this.popup.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.popup.on(BI.TextValueComboPopup.EVENT_CHANGE,function(){a.combo.hideView(),a.fireEvent(BI.StaticCombo.EVENT_CHANGE,arguments)}),this.combo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup}})},populate:function(a){this.combo.populate(a)},setValue:function(a){this.combo.setValue(a)},getValue:function(){return this.combo.getValue()}}),BI.StaticCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.static_combo",BI.StaticCombo),BI.TextValueCheckCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.TextValueCheckCombo.superclass._defaultConfig.apply(this,arguments),{baseClass:"bi-text-value-check-combo",width:100,height:24,chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,value:""})},_init:function(){BI.TextValueCheckCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget({type:"bi.select_text_trigger",items:b.items,height:b.height}),this.popup=BI.createWidget({type:"bi.text_value_check_combo_popup",chooseType:b.chooseType,items:b.items}),this.popup.on(BI.TextValueCheckComboPopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.textIconCheckCombo.hideView(),a.fireEvent(BI.TextValueCheckCombo.EVENT_CHANGE)}),this.popup.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.textIconCheckCombo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup,maxHeight:300}}),BI.isKey(b.value)&&this.setValue(b.value)},setTitle:function(a){this.trigger.setTitle(a)},setValue:function(a){this.textIconCheckCombo.setValue(a)},setWarningTitle:function(a){this.trigger.setWarningTitle(a)},getValue:function(){return this.textIconCheckCombo.getValue()},populate:function(a){this.options.items=a,this.textIconCheckCombo.populate(a)}}),BI.TextValueCheckCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_value_check_combo",BI.TextValueCheckCombo),BI.SmallTextValueCheckCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SmallTextValueCheckCombo.superclass._defaultConfig.apply(this,arguments),{width:100,height:24,chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,text:""})},_init:function(){BI.SmallTextValueCheckCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget({type:"bi.small_select_text_trigger",items:b.items,height:b.height,text:b.text}),this.popup=BI.createWidget({type:"bi.text_value_check_combo_popup",chooseType:b.chooseType,items:b.items}),this.popup.on(BI.TextValueCheckComboPopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.SmallTextIconCheckCombo.hideView(),a.fireEvent(BI.SmallTextValueCheckCombo.EVENT_CHANGE)}),this.popup.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.SmallTextIconCheckCombo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup,maxHeight:300}})},setValue:function(a){this.SmallTextIconCheckCombo.setValue(a)},getValue:function(){return this.SmallTextIconCheckCombo.getValue()},populate:function(a){this.options.items=a,this.SmallTextIconCheckCombo.populate(a)}}),BI.SmallTextValueCheckCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.small_text_value_check_combo",BI.SmallTextValueCheckCombo),BI.TextValueCheckComboPopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.TextValueCheckComboPopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-text-icon-popup",chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE})},_init:function(){BI.TextValueCheckComboPopup.superclass._init.apply(this,arguments);var a=this.options,b=this;this.popup=BI.createWidget({type:"bi.button_group",items:this._formatItems(a.items),chooseType:a.chooseType,layouts:[{type:"bi.vertical"}]}),this.popup.on(BI.Controller.EVENT_CHANGE,function(a,c,d){b.fireEvent(BI.Controller.EVENT_CHANGE,arguments),a===BI.Events.CLICK&&b.fireEvent(BI.TextValueCheckComboPopup.EVENT_CHANGE,c,d)}),BI.createWidget({type:"bi.vertical",element:this,items:[this.popup]})},_formatItems:function(a){return BI.map(a,function(a,b){return BI.extend({type:"bi.icon_text_item",cls:"item-check-font bi-list-item",height:30},b)})},populate:function(a){BI.TextValueCheckComboPopup.superclass.populate.apply(this,arguments),this.popup.populate(this._formatItems(a))},getValue:function(){return this.popup.getValue()},setValue:function(a){this.popup.setValue(a)}}),BI.TextValueCheckComboPopup.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_value_check_combo_popup",BI.TextValueCheckComboPopup),BI.TextValueCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.TextValueCombo.superclass._defaultConfig.apply(this,arguments),{baseClass:"bi-text-value-combo",height:30,chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,value:"",el:{}})},_init:function(){BI.TextValueCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget(b.el,{type:"bi.select_text_trigger",items:b.items,height:b.height}),this.popup=BI.createWidget({type:"bi.text_value_combo_popup",chooseType:b.chooseType,items:b.items}),this.popup.on(BI.TextValueComboPopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.textIconCombo.hideView(),a.fireEvent(BI.TextValueCombo.EVENT_CHANGE,arguments)}),this.popup.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.textIconCombo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup,maxHeight:300}}),BI.isKey(b.value)&&this.setValue(b.value)},setValue:function(a){this.textIconCombo.setValue(a)},getValue:function(){return this.textIconCombo.getValue()},populate:function(a){this.options.items=a,this.textIconCombo.populate(a)}}),BI.TextValueCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_value_combo",BI.TextValueCombo),BI.SmallTextValueCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SmallTextValueCombo.superclass._defaultConfig.apply(this,arguments),{width:100,height:24,chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,el:{},text:""})},_init:function(){BI.SmallTextValueCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget(b.el,{type:"bi.small_select_text_trigger",items:b.items,height:b.height,text:b.text}),this.popup=BI.createWidget({type:"bi.text_value_combo_popup",chooseType:b.chooseType,items:b.items}),this.popup.on(BI.TextValueComboPopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.SmallTextValueCombo.hideView(),a.fireEvent(BI.SmallTextValueCombo.EVENT_CHANGE)}),this.popup.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.SmallTextValueCombo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup,maxHeight:300}})},setValue:function(a){this.SmallTextValueCombo.setValue(a)},getValue:function(){return this.SmallTextValueCombo.getValue()},populate:function(a){this.options.items=a,this.SmallTextValueCombo.populate(a)}}),BI.SmallTextValueCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.small_text_value_combo",BI.SmallTextValueCombo),BI.TextValueComboPopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.TextValueComboPopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-text-icon-popup",chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE})},_init:function(){BI.TextValueComboPopup.superclass._init.apply(this,arguments);var a=this.options,b=this;this.popup=BI.createWidget({type:"bi.button_group",items:BI.createItems(a.items,{type:"bi.single_select_item",textAlign:a.textAlign,height:30}),chooseType:a.chooseType,layouts:[{type:"bi.vertical"}]}),this.popup.on(BI.Controller.EVENT_CHANGE,function(a,c,d){b.fireEvent(BI.Controller.EVENT_CHANGE,arguments),a===BI.Events.CLICK&&b.fireEvent(BI.TextValueComboPopup.EVENT_CHANGE,c,d)}),BI.createWidget({type:"bi.vertical",element:this,items:[this.popup]})},populate:function(a){BI.TextValueComboPopup.superclass.populate.apply(this,arguments),a=BI.createItems(a,{type:"bi.single_select_item",height:30}),this.popup.populate(a)},getValue:function(){return this.popup.getValue()},setValue:function(a){this.popup.setValue(a)}}),BI.TextValueComboPopup.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_value_combo_popup",BI.TextValueComboPopup),BI.TextValueDownListCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.TextValueDownListCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-text-value-down-list-combo",height:30})},_init:function(){BI.TextValueDownListCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this._createValueMap(),this.trigger=BI.createWidget({type:"bi.down_list_select_text_trigger",height:b.height,items:b.items}),this.combo=BI.createWidget({type:"bi.down_list_combo",element:this,chooseType:BI.Selection.Single,adjustLength:2,height:b.height,el:this.trigger,items:BI.deepClone(b.items)}),this.combo.on(BI.DownListCombo.EVENT_CHANGE,function(){a.setValue(a.combo.getValue()[0].value),a.fireEvent(BI.TextValueDownListCombo.EVENT_CHANGE)}),this.combo.on(BI.DownListCombo.EVENT_SON_VALUE_CHANGE,function(){a.setValue(a.combo.getValue()[0].childValue),a.fireEvent(BI.TextValueDownListCombo.EVENT_CHANGE)})},_createValueMap:function(){var a=this;this.valueMap={},BI.each(BI.flatten(this.options.items),function(b,c){BI.has(c,"el")?BI.each(c.children,function(b,d){a.valueMap[d.value]={value:c.el.value,childValue:d.value}}):a.valueMap[c.value]={value:c.value}})},setValue:function(a){a=this.valueMap[a],this.combo.setValue([a]),this.trigger.setValue(a.childValue||a.value)},getValue:function(){var a=this.combo.getValue()[0];return[a.childValue||a.value]},populate:function(a){this.options.items=BI.flatten(a),this.combo.populate(a),this._createValueMap()}}),BI.TextValueDownListCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.text_value_down_list_combo",BI.TextValueDownListCombo),BI.DownListSelectTextTrigger=BI.inherit(BI.Trigger,{_defaultConfig:function(){return BI.extend(BI.DownListSelectTextTrigger.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-down-list-select-text-trigger",height:24,text:""})},_init:function(){BI.DownListSelectTextTrigger.superclass._init.apply(this,arguments);var a=this.options;this.trigger=BI.createWidget({type:"bi.select_text_trigger",element:this,height:a.height,items:this._formatItemArray(a.items),text:a.text})},_formatItemArray:function(){var a=BI.flatten(BI.deepClone(this.options.items)),b=[];return BI.each(a,function(a,c){BI.has(c,"el")?(BI.each(c.children,function(a,b){b.text=c.el.text+"("+b.text+")"}),b=BI.concat(b,c.children)):b.push(c)}),b},setValue:function(a){this.trigger.setValue(a)},populate:function(a){this.trigger.populate(this._formatItemArray(a))}}),BI.shortcut("bi.down_list_select_text_trigger",BI.DownListSelectTextTrigger),BI.ClearEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.ClearEditor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:"bi-clear-editor",height:24,errorText:"",watermark:"",validationChecker:BI.emptyFn,quitChecker:BI.emptyFn})},_init:function(){BI.ClearEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.editor",height:b.height,watermark:b.watermark,allowBlank:!0,errorText:b.errorText,validationChecker:b.validationChecker,quitChecker:b.quitChecker}),this.clear=BI.createWidget({type:"bi.icon_button",stopEvent:!0,cls:"search-close-h-font"}),this.clear.on(BI.IconButton.EVENT_CHANGE,function(){a.setValue(""),a.fireEvent(BI.Controller.EVENT_CHANGE,BI.Events.STOPEDIT),a.fireEvent(BI.ClearEditor.EVENT_CLEAR)}),BI.createWidget({element:this,type:"bi.htape",items:[{el:this.editor},{el:this.clear,width:25}]}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_FOCUS,function(){a.fireEvent(BI.ClearEditor.EVENT_FOCUS)}),this.editor.on(BI.Editor.EVENT_BLUR,function(){a.fireEvent(BI.ClearEditor.EVENT_BLUR)}),this.editor.on(BI.Editor.EVENT_CLICK,function(){a.fireEvent(BI.ClearEditor.EVENT_CLICK)}),this.editor.on(BI.Editor.EVENT_CHANGE,function(){a._checkClear(),a.fireEvent(BI.ClearEditor.EVENT_CHANGE)}),this.editor.on(BI.Editor.EVENT_KEY_DOWN,function(b){a.fireEvent(BI.ClearEditor.EVENT_KEY_DOWN,b)}),this.editor.on(BI.Editor.EVENT_SPACE,function(){a.fireEvent(BI.ClearEditor.EVENT_SPACE)}),this.editor.on(BI.Editor.EVENT_BACKSPACE,function(){a.fireEvent(BI.ClearEditor.EVENT_BACKSPACE)}),this.editor.on(BI.Editor.EVENT_VALID,function(){a.fireEvent(BI.ClearEditor.EVENT_VALID)}),this.editor.on(BI.Editor.EVENT_ERROR,function(){a.fireEvent(BI.ClearEditor.EVENT_ERROR)}),this.editor.on(BI.Editor.EVENT_ENTER,function(){a.fireEvent(BI.ClearEditor.EVENT_ENTER)}),this.editor.on(BI.Editor.EVENT_RESTRICT,function(){a.fireEvent(BI.ClearEditor.EVENT_RESTRICT)}),this.editor.on(BI.Editor.EVENT_EMPTY,function(){a._checkClear(),a.fireEvent(BI.ClearEditor.EVENT_EMPTY)}),this.editor.on(BI.Editor.EVENT_REMOVE,function(){a.fireEvent(BI.ClearEditor.EVENT_REMOVE)}),this.editor.on(BI.Editor.EVENT_CONFIRM,function(){a.fireEvent(BI.ClearEditor.EVENT_CONFIRM)}),this.editor.on(BI.Editor.EVENT_START,function(){a.fireEvent(BI.ClearEditor.EVENT_START)}),this.editor.on(BI.Editor.EVENT_PAUSE,function(){a.fireEvent(BI.ClearEditor.EVENT_PAUSE)}),this.editor.on(BI.Editor.EVENT_STOP,function(){a.fireEvent(BI.ClearEditor.EVENT_STOP)}),this.clear.invisible()},_checkClear:function(){this.getValue()?this.clear.visible():this.clear.invisible()},focus:function(){this.editor.focus()},blur:function(){this.editor.blur()},getValue:function(){if(this.isValid()){var a=this.editor.getValue().match(/[\S]+/g);return BI.isNull(a)?"":a[a.length-1]}},setValue:function(a){this.editor.setValue(a),BI.isKey(a)&&this.clear.visible()},isValid:function(){return this.editor.isValid()}}),BI.ClearEditor.EVENT_CHANGE="EVENT_CHANGE",BI.ClearEditor.EVENT_FOCUS="EVENT_FOCUS",BI.ClearEditor.EVENT_BLUR="EVENT_BLUR",BI.ClearEditor.EVENT_CLICK="EVENT_CLICK",BI.ClearEditor.EVENT_KEY_DOWN="EVENT_KEY_DOWN",BI.ClearEditor.EVENT_SPACE="EVENT_SPACE",BI.ClearEditor.EVENT_BACKSPACE="EVENT_BACKSPACE",BI.ClearEditor.EVENT_CLEAR="EVENT_CLEAR",BI.ClearEditor.EVENT_START="EVENT_START",BI.ClearEditor.EVENT_PAUSE="EVENT_PAUSE",BI.ClearEditor.EVENT_STOP="EVENT_STOP",BI.ClearEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.ClearEditor.EVENT_VALID="EVENT_VALID",BI.ClearEditor.EVENT_ERROR="EVENT_ERROR",BI.ClearEditor.EVENT_ENTER="EVENT_ENTER",BI.ClearEditor.EVENT_RESTRICT="EVENT_RESTRICT",BI.ClearEditor.EVENT_REMOVE="EVENT_REMOVE",BI.ClearEditor.EVENT_EMPTY="EVENT_EMPTY",BI.shortcut("bi.clear_editor",BI.ClearEditor),BI.ShelterEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.ShelterEditor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-shelter-editor",hgap:4,vgap:2,lgap:0,rgap:0,tgap:0,bgap:0, validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,allowBlank:!0,watermark:"",errorText:"",height:24,textAlign:"left"})},_init:function(){BI.ShelterEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.editor",height:b.height,hgap:b.hgap,vgap:b.vgap,lgap:b.lgap,rgap:b.rgap,tgap:b.tgap,bgap:b.bgap,value:b.value,validationChecker:b.validationChecker,quitChecker:b.quitChecker,allowBlank:b.allowBlank,watermark:b.watermark,errorText:b.errorText}),this.text=BI.createWidget({type:"bi.text_button",cls:"shelter-editor-text",title:b.title,warningTitle:b.warningTitle,tipType:b.tipType,textAlign:b.textAlign,height:b.height,hgap:4}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.text,left:0,right:0,top:0,bottom:0}]}),this.text.on(BI.Controller.EVENT_CHANGE,function(){arguments[2]=a,a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.text.on(BI.TextButton.EVENT_CHANGE,function(){a.fireEvent(BI.ShelterEditor.EVENT_CLICK_LABEL)}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_FOCUS,function(){a.fireEvent(BI.ShelterEditor.EVENT_FOCUS,arguments)}),this.editor.on(BI.Editor.EVENT_BLUR,function(){a.fireEvent(BI.ShelterEditor.EVENT_BLUR,arguments)}),this.editor.on(BI.Editor.EVENT_CLICK,function(){a.fireEvent(BI.ShelterEditor.EVENT_CLICK,arguments)}),this.editor.on(BI.Editor.EVENT_CHANGE,function(){a.fireEvent(BI.ShelterEditor.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_KEY_DOWN,function(b){a.fireEvent(BI.ShelterEditor.EVENT_KEY_DOWN,arguments)}),this.editor.on(BI.Editor.EVENT_VALID,function(){a.fireEvent(BI.ShelterEditor.EVENT_VALID,arguments)}),this.editor.on(BI.Editor.EVENT_CONFIRM,function(){a._showHint(),a._checkText(),a.fireEvent(BI.ShelterEditor.EVENT_CONFIRM,arguments)}),this.editor.on(BI.Editor.EVENT_START,function(){a.fireEvent(BI.ShelterEditor.EVENT_START,arguments)}),this.editor.on(BI.Editor.EVENT_PAUSE,function(){a.fireEvent(BI.ShelterEditor.EVENT_PAUSE,arguments)}),this.editor.on(BI.Editor.EVENT_STOP,function(){a.fireEvent(BI.ShelterEditor.EVENT_STOP,arguments)}),this.editor.on(BI.Editor.EVENT_SPACE,function(){a.fireEvent(BI.ShelterEditor.EVENT_SPACE,arguments)}),this.editor.on(BI.Editor.EVENT_ERROR,function(){a._checkText(),a.fireEvent(BI.ShelterEditor.EVENT_ERROR,arguments)}),this.editor.on(BI.Editor.EVENT_ENTER,function(){a.fireEvent(BI.ShelterEditor.EVENT_ENTER,arguments)}),this.editor.on(BI.Editor.EVENT_RESTRICT,function(){a.fireEvent(BI.ShelterEditor.EVENT_RESTRICT,arguments)}),this.editor.on(BI.Editor.EVENT_EMPTY,function(){a.fireEvent(BI.ShelterEditor.EVENT_EMPTY,arguments)}),BI.createWidget({type:"bi.vertical",scrolly:!1,element:this,items:[this.editor]}),this._showHint(),a._checkText()},_checkText:function(){var a=this.options;""===this.editor.getValue()?(this.text.setValue(a.watermark||""),this.text.element.addClass("bi-water-mark")):(this.text.setValue(this.editor.getValue()),this.text.element.removeClass("bi-water-mark"))},_showInput:function(){this.editor.visible(),this.text.invisible()},_showHint:function(){this.editor.invisible(),this.text.visible()},setTitle:function(a){this.text.setTitle(a)},setWarningTitle:function(a){this.text.setWarningTitle(a)},focus:function(){this._showInput(),this.editor.focus()},blur:function(){this.editor.blur(),this._showHint(),this._checkText()},doRedMark:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},isValid:function(){return this.editor.isValid()},setErrorText:function(a){this.editor.setErrorText(a)},getErrorText:function(){return this.editor.getErrorText()},isEditing:function(){return this.editor.isEditing()},getLastValidValue:function(){return this.editor.getLastValidValue()},setTextStyle:function(a){this.text.setStyle(a)},setValue:function(a){this.editor.setValue(a),this._checkText()},getValue:function(){return this.editor.getValue()},getState:function(){return this.text.getValue()},setState:function(a){this._showHint(),this.text.setValue(a)}}),BI.ShelterEditor.EVENT_CHANGE="EVENT_CHANGE",BI.ShelterEditor.EVENT_FOCUS="EVENT_FOCUS",BI.ShelterEditor.EVENT_BLUR="EVENT_BLUR",BI.ShelterEditor.EVENT_CLICK="EVENT_CLICK",BI.ShelterEditor.EVENT_KEY_DOWN="EVENT_KEY_DOWN",BI.ShelterEditor.EVENT_CLICK_LABEL="EVENT_CLICK_LABEL",BI.ShelterEditor.EVENT_START="EVENT_START",BI.ShelterEditor.EVENT_PAUSE="EVENT_PAUSE",BI.ShelterEditor.EVENT_STOP="EVENT_STOP",BI.ShelterEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.ShelterEditor.EVENT_VALID="EVENT_VALID",BI.ShelterEditor.EVENT_ERROR="EVENT_ERROR",BI.ShelterEditor.EVENT_ENTER="EVENT_ENTER",BI.ShelterEditor.EVENT_RESTRICT="EVENT_RESTRICT",BI.ShelterEditor.EVENT_SPACE="EVENT_SPACE",BI.ShelterEditor.EVENT_EMPTY="EVENT_EMPTY",BI.shortcut("bi.shelter_editor",BI.ShelterEditor),BI.SignInitialEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.SignInitialEditor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-sign-initial-editor",hgap:4,vgap:2,lgap:0,rgap:0,tgap:0,bgap:0,validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,allowBlank:!0,watermark:"",errorText:"",value:"",text:"",height:24})},_init:function(){BI.SignInitialEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.editor",height:b.height,hgap:b.hgap,vgap:b.vgap,lgap:b.lgap,rgap:b.rgap,tgap:b.tgap,bgap:b.bgap,value:b.value,validationChecker:b.validationChecker,quitChecker:b.quitChecker,allowBlank:b.allowBlank,watermark:b.watermark,errorText:b.errorText}),this.text=BI.createWidget({type:"bi.text_button",cls:"sign-editor-text",title:b.title,warningTitle:b.warningTitle,tipType:b.tipType,textAlign:"left",height:b.height,hgap:4,handler:function(){a._showInput(),a.editor.focus(),a.editor.selectAll()}}),this.text.on(BI.TextButton.EVENT_CHANGE,function(){BI.nextTick(function(){a.fireEvent(BI.SignInitialEditor.EVENT_CLICK_LABEL)})}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.text,left:0,right:0,top:0,bottom:0}]}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_FOCUS,function(){a.fireEvent(BI.SignInitialEditor.EVENT_FOCUS,arguments)}),this.editor.on(BI.Editor.EVENT_BLUR,function(){a.fireEvent(BI.SignInitialEditor.EVENT_BLUR,arguments)}),this.editor.on(BI.Editor.EVENT_CLICK,function(){a.fireEvent(BI.SignInitialEditor.EVENT_CLICK,arguments)}),this.editor.on(BI.Editor.EVENT_CHANGE,function(){a.fireEvent(BI.SignInitialEditor.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_KEY_DOWN,function(b){a.fireEvent(BI.SignInitialEditor.EVENT_KEY_DOWN,arguments)}),this.editor.on(BI.Editor.EVENT_VALID,function(){a.fireEvent(BI.SignInitialEditor.EVENT_VALID,arguments)}),this.editor.on(BI.Editor.EVENT_CONFIRM,function(){a._showHint(),a._checkText(),a.fireEvent(BI.SignInitialEditor.EVENT_CONFIRM,arguments)}),this.editor.on(BI.Editor.EVENT_START,function(){a.fireEvent(BI.SignInitialEditor.EVENT_START,arguments)}),this.editor.on(BI.Editor.EVENT_PAUSE,function(){a.fireEvent(BI.SignInitialEditor.EVENT_PAUSE,arguments)}),this.editor.on(BI.Editor.EVENT_STOP,function(){a.fireEvent(BI.SignInitialEditor.EVENT_STOP,arguments)}),this.editor.on(BI.Editor.EVENT_SPACE,function(){a.fireEvent(BI.SignInitialEditor.EVENT_SPACE,arguments)}),this.editor.on(BI.Editor.EVENT_ERROR,function(){a._checkText(),a.fireEvent(BI.SignInitialEditor.EVENT_ERROR,arguments)}),this.editor.on(BI.Editor.EVENT_ENTER,function(){a.fireEvent(BI.SignInitialEditor.EVENT_ENTER,arguments)}),this.editor.on(BI.Editor.EVENT_RESTRICT,function(){a.fireEvent(BI.SignInitialEditor.EVENT_RESTRICT,arguments)}),this.editor.on(BI.Editor.EVENT_EMPTY,function(){a.fireEvent(BI.SignInitialEditor.EVENT_EMPTY,arguments)}),BI.createWidget({type:"bi.vertical",scrolly:!1,element:this,items:[this.editor]}),this._showHint(),a._checkText()},_checkText:function(){var a=this.options;BI.nextTick(BI.bind(function(){if(""===this.editor.getValue())this.text.setValue(a.watermark||""),this.text.element.addClass("bi-water-mark");else{var b=this.editor.getValue();b=BI.isEmpty(b)||b==a.text?a.text:b+"("+a.text+")",this.text.setValue(b),this.text.element.removeClass("bi-water-mark")}},this))},_showInput:function(){this.editor.visible(),this.text.invisible()},_showHint:function(){this.editor.invisible(),this.text.visible()},setTitle:function(a){this.text.setTitle(a)},setWarningTitle:function(a){this.text.setWarningTitle(a)},focus:function(){this._showInput(),this.editor.focus()},blur:function(){this.editor.blur(),this._showHint(),this._checkText()},doRedMark:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},isValid:function(){return this.editor.isValid()},setErrorText:function(a){this.editor.setErrorText(a)},getErrorText:function(){return this.editor.getErrorText()},isEditing:function(){return this.editor.isEditing()},getLastValidValue:function(){return this.editor.getLastValidValue()},setValue:function(a){var b=this.options;this.editor.setValue(a.value),b.text=a.text||b.text,this._checkText()},getValue:function(){return{value:this.editor.getValue(),text:this.options.text}},getState:function(){return this.text.getValue()},setState:function(a){var b=this.options;this._showHint(),a=BI.isEmpty(a)||a==b.text?b.text:a+"("+b.text+")",this.text.setValue(a)}}),BI.SignInitialEditor.EVENT_CHANGE="EVENT_CHANGE",BI.SignInitialEditor.EVENT_FOCUS="EVENT_FOCUS",BI.SignInitialEditor.EVENT_BLUR="EVENT_BLUR",BI.SignInitialEditor.EVENT_CLICK="EVENT_CLICK",BI.SignInitialEditor.EVENT_KEY_DOWN="EVENT_KEY_DOWN",BI.SignInitialEditor.EVENT_CLICK_LABEL="EVENT_CLICK_LABEL",BI.SignInitialEditor.EVENT_START="EVENT_START",BI.SignInitialEditor.EVENT_PAUSE="EVENT_PAUSE",BI.SignInitialEditor.EVENT_STOP="EVENT_STOP",BI.SignInitialEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.SignInitialEditor.EVENT_VALID="EVENT_VALID",BI.SignInitialEditor.EVENT_ERROR="EVENT_ERROR",BI.SignInitialEditor.EVENT_ENTER="EVENT_ENTER",BI.SignInitialEditor.EVENT_RESTRICT="EVENT_RESTRICT",BI.SignInitialEditor.EVENT_SPACE="EVENT_SPACE",BI.SignInitialEditor.EVENT_EMPTY="EVENT_EMPTY",BI.shortcut("bi.sign_initial_editor",BI.SignInitialEditor),BI.SignEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.SignEditor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-sign-editor",hgap:4,vgap:2,lgap:0,rgap:0,tgap:0,bgap:0,validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,allowBlank:!0,watermark:"",errorText:"",height:24})},_init:function(){BI.SignEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.editor",height:b.height,hgap:b.hgap,vgap:b.vgap,lgap:b.lgap,rgap:b.rgap,tgap:b.tgap,bgap:b.bgap,value:b.value,validationChecker:b.validationChecker,quitChecker:b.quitChecker,allowBlank:b.allowBlank,watermark:b.watermark,errorText:b.errorText}),this.text=BI.createWidget({type:"bi.text_button",cls:"sign-editor-text",title:b.title,warningTitle:b.warningTitle,tipType:b.tipType,textAlign:"left",height:b.height,hgap:4,handler:function(){a._showInput(),a.editor.focus(),a.editor.selectAll()}}),this.text.on(BI.TextButton.EVENT_CHANGE,function(){BI.nextTick(function(){a.fireEvent(BI.SignEditor.EVENT_CLICK_LABEL)})}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.text,left:0,right:0,top:0,bottom:0}]}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_FOCUS,function(){a.fireEvent(BI.SignEditor.EVENT_FOCUS,arguments)}),this.editor.on(BI.Editor.EVENT_BLUR,function(){a.fireEvent(BI.SignEditor.EVENT_BLUR,arguments)}),this.editor.on(BI.Editor.EVENT_CLICK,function(){a.fireEvent(BI.SignEditor.EVENT_CLICK,arguments)}),this.editor.on(BI.Editor.EVENT_CHANGE,function(){a.fireEvent(BI.SignEditor.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_KEY_DOWN,function(b){a.fireEvent(BI.SignEditor.EVENT_KEY_DOWN,arguments)}),this.editor.on(BI.Editor.EVENT_VALID,function(){a.fireEvent(BI.SignEditor.EVENT_VALID,arguments)}),this.editor.on(BI.Editor.EVENT_CONFIRM,function(){a._showHint(),a._checkText(),a.fireEvent(BI.SignEditor.EVENT_CONFIRM,arguments)}),this.editor.on(BI.Editor.EVENT_START,function(){a.fireEvent(BI.SignEditor.EVENT_START,arguments)}),this.editor.on(BI.Editor.EVENT_PAUSE,function(){a.fireEvent(BI.SignEditor.EVENT_PAUSE,arguments)}),this.editor.on(BI.Editor.EVENT_STOP,function(){a.fireEvent(BI.SignEditor.EVENT_STOP,arguments)}),this.editor.on(BI.Editor.EVENT_SPACE,function(){a.fireEvent(BI.SignEditor.EVENT_SPACE,arguments)}),this.editor.on(BI.Editor.EVENT_ERROR,function(){a._checkText(),a.fireEvent(BI.SignEditor.EVENT_ERROR,arguments)}),this.editor.on(BI.Editor.EVENT_ENTER,function(){a.fireEvent(BI.SignEditor.EVENT_ENTER,arguments)}),this.editor.on(BI.Editor.EVENT_RESTRICT,function(){a.fireEvent(BI.SignEditor.EVENT_RESTRICT,arguments)}),this.editor.on(BI.Editor.EVENT_EMPTY,function(){a.fireEvent(BI.SignEditor.EVENT_EMPTY,arguments)}),BI.createWidget({type:"bi.vertical",scrolly:!1,element:this,items:[this.editor]}),this._showHint(),a._checkText()},_checkText:function(){var a=this.options;BI.nextTick(BI.bind(function(){""===this.editor.getValue()?(this.text.setValue(a.watermark||""),this.text.element.addClass("bi-water-mark")):(this.text.setValue(this.editor.getValue()),this.text.element.removeClass("bi-water-mark"))},this))},_showInput:function(){this.editor.visible(),this.text.invisible()},_showHint:function(){this.editor.invisible(),this.text.visible()},setTitle:function(a){this.text.setTitle(a)},setWarningTitle:function(a){this.text.setWarningTitle(a)},focus:function(){this._showInput(),this.editor.focus()},blur:function(){this.editor.blur(),this._showHint(),this._checkText()},doRedMark:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},isValid:function(){return this.editor.isValid()},setErrorText:function(a){this.editor.setErrorText(a)},getErrorText:function(){return this.editor.getErrorText()},isEditing:function(){return this.editor.isEditing()},getLastValidValue:function(){return this.editor.getLastValidValue()},setValue:function(a){this.editor.setValue(a),this._checkText()},getValue:function(){return this.editor.getValue()},getState:function(){return this.text.getValue()},setState:function(a){this._showHint(),this.text.setValue(a)}}),BI.SignEditor.EVENT_CHANGE="EVENT_CHANGE",BI.SignEditor.EVENT_FOCUS="EVENT_FOCUS",BI.SignEditor.EVENT_BLUR="EVENT_BLUR",BI.SignEditor.EVENT_CLICK="EVENT_CLICK",BI.SignEditor.EVENT_KEY_DOWN="EVENT_KEY_DOWN",BI.SignEditor.EVENT_CLICK_LABEL="EVENT_CLICK_LABEL",BI.SignEditor.EVENT_START="EVENT_START",BI.SignEditor.EVENT_PAUSE="EVENT_PAUSE",BI.SignEditor.EVENT_STOP="EVENT_STOP",BI.SignEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.SignEditor.EVENT_VALID="EVENT_VALID",BI.SignEditor.EVENT_ERROR="EVENT_ERROR",BI.SignEditor.EVENT_ENTER="EVENT_ENTER",BI.SignEditor.EVENT_RESTRICT="EVENT_RESTRICT",BI.SignEditor.EVENT_SPACE="EVENT_SPACE",BI.SignEditor.EVENT_EMPTY="EVENT_EMPTY",BI.shortcut("bi.sign_editor",BI.SignEditor),BI.StateEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.StateEditor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-state-editor",hgap:4,vgap:2,lgap:0,rgap:0,tgap:0,bgap:0,validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,allowBlank:!0,watermark:"",errorText:"",height:24})},_init:function(){BI.StateEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.editor",height:b.height,hgap:b.hgap,vgap:b.vgap,lgap:b.lgap,rgap:b.rgap,tgap:b.tgap,bgap:b.bgap,value:b.value,validationChecker:b.validationChecker,quitChecker:b.quitChecker,allowBlank:b.allowBlank,watermark:b.watermark,errorText:b.errorText}),this.text=BI.createWidget({type:"bi.text_button",cls:"state-editor-infinite-text bi-disabled",textAlign:"left",height:b.height,text:BI.i18nText("BI-Basic_Unrestricted"),hgap:4,handler:function(){a._showInput(),a.editor.focus(),a.editor.setValue("")}}),this.text.on(BI.TextButton.EVENT_CHANGE,function(){BI.nextTick(function(){a.fireEvent(BI.StateEditor.EVENT_CLICK_LABEL)})}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.text,left:0,right:0,top:0,bottom:0}]}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_FOCUS,function(){a.fireEvent(BI.StateEditor.EVENT_FOCUS,arguments)}),this.editor.on(BI.Editor.EVENT_BLUR,function(){a.fireEvent(BI.StateEditor.EVENT_BLUR,arguments)}),this.editor.on(BI.Editor.EVENT_CLICK,function(){a.fireEvent(BI.StateEditor.EVENT_CLICK,arguments)}),this.editor.on(BI.Editor.EVENT_CHANGE,function(){a.fireEvent(BI.StateEditor.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_KEY_DOWN,function(b){a.fireEvent(BI.StateEditor.EVENT_KEY_DOWN,arguments)}),this.editor.on(BI.Editor.EVENT_VALID,function(){a.fireEvent(BI.StateEditor.EVENT_VALID,arguments)}),this.editor.on(BI.Editor.EVENT_CONFIRM,function(){a._showHint(),a.fireEvent(BI.StateEditor.EVENT_CONFIRM,arguments)}),this.editor.on(BI.Editor.EVENT_START,function(){a.fireEvent(BI.StateEditor.EVENT_START,arguments)}),this.editor.on(BI.Editor.EVENT_PAUSE,function(){a.fireEvent(BI.StateEditor.EVENT_PAUSE,arguments)}),this.editor.on(BI.Editor.EVENT_STOP,function(){a.fireEvent(BI.StateEditor.EVENT_STOP,arguments)}),this.editor.on(BI.Editor.EVENT_SPACE,function(){a.fireEvent(BI.StateEditor.EVENT_SPACE,arguments)}),this.editor.on(BI.Editor.EVENT_ERROR,function(){a.fireEvent(BI.StateEditor.EVENT_ERROR,arguments)}),this.editor.on(BI.Editor.EVENT_ENTER,function(){a.fireEvent(BI.StateEditor.EVENT_ENTER,arguments)}),this.editor.on(BI.Editor.EVENT_RESTRICT,function(){a.fireEvent(BI.StateEditor.EVENT_RESTRICT,arguments)}),this.editor.on(BI.Editor.EVENT_EMPTY,function(){a.fireEvent(BI.StateEditor.EVENT_EMPTY,arguments)}),BI.createWidget({type:"bi.vertical",scrolly:!1,element:this,items:[this.editor]}),this._showHint()},doRedMark:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},focus:function(){this.options.disabled===!1&&(this._showInput(),this.editor.focus())},blur:function(){this.editor.blur(),this._showHint()},_showInput:function(){this.editor.visible(),this.text.invisible()},_showHint:function(){this.editor.invisible(),this.text.visible()},isValid:function(){return this.editor.isValid()},setErrorText:function(a){this.editor.setErrorText(a)},getErrorText:function(){return this.editor.getErrorText()},isEditing:function(){return this.editor.isEditing()},getLastValidValue:function(){return this.editor.getLastValidValue()},setValue:function(a){this.editor.setValue(a)},getValue:function(){return this.editor.getValue()},getState:function(){return this.editor.getValue().match(/[^\s]+/g)},setState:function(a){return BI.StateEditor.superclass.setValue.apply(this,arguments),BI.isNumber(a)?void(a===BI.Selection.All?(this.text.setText(BI.i18nText("BI-Select_All")),this.text.setTitle(""),this.text.element.removeClass("state-editor-infinite-text")):a===BI.Selection.Multi?(this.text.setText(BI.i18nText("BI-Select_Part")),this.text.setTitle(""),this.text.element.removeClass("state-editor-infinite-text")):(this.text.setText(BI.i18nText("BI-Basic_Unrestricted")),this.text.setTitle(""),this.text.element.addClass("state-editor-infinite-text"))):BI.isString(a)?(this.text.setText(a),this.text.setTitle(a),void this.text.element.removeClass("state-editor-infinite-text")):void(BI.isArray(a)&&(BI.isEmpty(a)?(this.text.setText(BI.i18nText("BI-Basic_Unrestricted")),this.text.element.addClass("state-editor-infinite-text")):1===a.length?(this.text.setText(a[0]),this.text.setTitle(a[0]),this.text.element.removeClass("state-editor-infinite-text")):(this.text.setText(BI.i18nText("BI-Select_Part")),this.text.setTitle(""),this.text.element.removeClass("state-editor-infinite-text"))))}}),BI.StateEditor.EVENT_CHANGE="EVENT_CHANGE",BI.StateEditor.EVENT_FOCUS="EVENT_FOCUS",BI.StateEditor.EVENT_BLUR="EVENT_BLUR",BI.StateEditor.EVENT_CLICK="EVENT_CLICK",BI.StateEditor.EVENT_KEY_DOWN="EVENT_KEY_DOWN",BI.StateEditor.EVENT_CLICK_LABEL="EVENT_CLICK_LABEL",BI.StateEditor.EVENT_START="EVENT_START",BI.StateEditor.EVENT_PAUSE="EVENT_PAUSE",BI.StateEditor.EVENT_STOP="EVENT_STOP",BI.StateEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.StateEditor.EVENT_VALID="EVENT_VALID",BI.StateEditor.EVENT_ERROR="EVENT_ERROR",BI.StateEditor.EVENT_ENTER="EVENT_ENTER",BI.StateEditor.EVENT_RESTRICT="EVENT_RESTRICT",BI.StateEditor.EVENT_SPACE="EVENT_SPACE",BI.StateEditor.EVENT_EMPTY="EVENT_EMPTY",BI.shortcut("bi.state_editor",BI.StateEditor),BI.SimpleStateEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.SimpleStateEditor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-simple-state-editor",hgap:4,vgap:2,lgap:0,rgap:0,tgap:0,bgap:0,validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,mouseOut:!1,allowBlank:!0,watermark:"",errorText:"",height:24})},_init:function(){BI.SimpleStateEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.editor",height:b.height,hgap:b.hgap,vgap:b.vgap,lgap:b.lgap,rgap:b.rgap,tgap:b.tgap,bgap:b.bgap,value:b.value,validationChecker:b.validationChecker,quitChecker:b.quitChecker,allowBlank:b.allowBlank,watermark:b.watermark,errorText:b.errorText}),this.text=BI.createWidget({type:"bi.text_button",cls:"state-editor-infinite-text bi-disabled",textAlign:"left",height:b.height,text:BI.i18nText("BI-Basic_Unrestricted"),hgap:4,handler:function(){a._showInput(),a.editor.focus(),a.editor.setValue("")}}),this.text.on(BI.TextButton.EVENT_CHANGE,function(){BI.nextTick(function(){a.fireEvent(BI.SimpleStateEditor.EVENT_CLICK_LABEL)})}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.text,left:0,right:0,top:0,bottom:0}]}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_FOCUS,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_FOCUS,arguments)}),this.editor.on(BI.Editor.EVENT_BLUR,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_BLUR,arguments)}),this.editor.on(BI.Editor.EVENT_CLICK,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_CLICK,arguments)}),this.editor.on(BI.Editor.EVENT_CHANGE,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_KEY_DOWN,function(b){a.fireEvent(BI.SimpleStateEditor.EVENT_KEY_DOWN,arguments)}),this.editor.on(BI.Editor.EVENT_VALID,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_VALID,arguments)}),this.editor.on(BI.Editor.EVENT_CONFIRM,function(){a._showHint(),a.fireEvent(BI.SimpleStateEditor.EVENT_CONFIRM,arguments)}),this.editor.on(BI.Editor.EVENT_START,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_START,arguments)}),this.editor.on(BI.Editor.EVENT_PAUSE,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_PAUSE,arguments)}),this.editor.on(BI.Editor.EVENT_STOP,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_STOP,arguments)}),this.editor.on(BI.Editor.EVENT_SPACE,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_SPACE,arguments)}),this.editor.on(BI.Editor.EVENT_ERROR,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_ERROR,arguments)}),this.editor.on(BI.Editor.EVENT_ENTER,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_ENTER,arguments)}),this.editor.on(BI.Editor.EVENT_RESTRICT,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_RESTRICT,arguments)}),this.editor.on(BI.Editor.EVENT_EMPTY,function(){a.fireEvent(BI.SimpleStateEditor.EVENT_EMPTY,arguments)}),BI.createWidget({type:"bi.vertical",scrolly:!1,element:this,items:[this.editor]}),this._showHint()},doRedMark:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},focus:function(){this._showInput(),this.editor.focus()},blur:function(){this.editor.blur(),this._showHint()},_showInput:function(){this.editor.visible(),this.text.invisible()},_showHint:function(){this.editor.invisible(),this.text.visible()},isValid:function(){return this.editor.isValid()},setErrorText:function(a){this.editor.setErrorText(a)},getErrorText:function(){return this.editor.getErrorText()},isEditing:function(){return this.editor.isEditing()},getLastValidValue:function(){return this.editor.getLastValidValue()},setValue:function(a){this.editor.setValue(a)},getValue:function(){return this.editor.getValue()},getState:function(){return this.editor.getValue().match(/[^\s]+/g)},setState:function(a){return BI.SimpleStateEditor.superclass.setValue.apply(this,arguments),BI.isNumber(a)?void(a===BI.Selection.All?(this.text.setText(BI.i18nText("BI-Already_Selected")),this.text.element.removeClass("state-editor-infinite-text")):a===BI.Selection.Multi?(this.text.setText(BI.i18nText("BI-Already_Selected")),this.text.element.removeClass("state-editor-infinite-text")):(this.text.setText(BI.i18nText("BI-Basic_Unrestricted")),this.text.element.addClass("state-editor-infinite-text"))):void(BI.isArray(a)&&1!==a.length?BI.isEmpty(a)?(this.text.setText(BI.i18nText("BI-Basic_Unrestricted")),this.text.element.addClass("state-editor-infinite-text")):(this.text.setText(BI.i18nText("BI-Already_Selected")),this.text.element.removeClass("state-editor-infinite-text")):(this.text.setText(a),this.text.setTitle(a),this.text.element.removeClass("state-editor-infinite-text")))}}),BI.SimpleStateEditor.EVENT_CHANGE="EVENT_CHANGE",BI.SimpleStateEditor.EVENT_FOCUS="EVENT_FOCUS",BI.SimpleStateEditor.EVENT_BLUR="EVENT_BLUR",BI.SimpleStateEditor.EVENT_CLICK="EVENT_CLICK",BI.SimpleStateEditor.EVENT_KEY_DOWN="EVENT_KEY_DOWN",BI.SimpleStateEditor.EVENT_CLICK_LABEL="EVENT_CLICK_LABEL",BI.SimpleStateEditor.EVENT_START="EVENT_START",BI.SimpleStateEditor.EVENT_PAUSE="EVENT_PAUSE",BI.SimpleStateEditor.EVENT_STOP="EVENT_STOP",BI.SimpleStateEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.SimpleStateEditor.EVENT_VALID="EVENT_VALID",BI.SimpleStateEditor.EVENT_ERROR="EVENT_ERROR",BI.SimpleStateEditor.EVENT_ENTER="EVENT_ENTER",BI.SimpleStateEditor.EVENT_RESTRICT="EVENT_RESTRICT",BI.SimpleStateEditor.EVENT_SPACE="EVENT_SPACE",BI.SimpleStateEditor.EVENT_EMPTY="EVENT_EMPTY",BI.shortcut("bi.simple_state_editor",BI.SimpleStateEditor),BI.BarPopoverSection=BI.inherit(BI.PopoverSection,{_defaultConfig:function(){return BI.extend(BI.BarPopoverSection.superclass._defaultConfig.apply(this,arguments),{btns:[BI.i18nText(BI.i18nText("BI-Basic_Sure")),BI.i18nText(BI.i18nText("BI-Basic_Cancel"))]})},_init:function(){BI.BarPopoverSection.superclass._init.apply(this,arguments)},rebuildSouth:function(a){var b=this,c=this.options;this.sure=BI.createWidget({type:"bi.button",text:this.options.btns[0],warningTitle:c.warningTitle,height:30,value:0,handler:function(a){b.end(),b.close(a)}}),this.cancel=BI.createWidget({type:"bi.button",text:this.options.btns[1],height:30,value:1,level:"ignore",handler:function(a){b.close(a)}}),BI.createWidget({type:"bi.right_vertical_adapt",element:a,lgap:10,items:[this.cancel,this.sure]})},setConfirmButtonEnable:function(a){this.sure.setEnable(!!a)}}),BI.MultiPopupView=BI.inherit(BI.PopupView,{_defaultConfig:function(){var a=BI.MultiPopupView.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-multi-list-view",buttons:[BI.i18nText("BI-Basic_Sure")]})},_init:function(){BI.MultiPopupView.superclass._init.apply(this,arguments)},_createToolBar:function(){var a=this.options,b=this;if(0!==a.buttons.length){var c=[];return BI.each(a.buttons,function(a,b){c.push({text:b,value:a})}),this.buttongroup=BI.createWidget({type:"bi.button_group",cls:"list-view-toolbar bi-high-light bi-border-top",height:30,items:BI.createItems(c,{type:"bi.text_button",once:!1,shadow:!0,isShadowShowingOnSelected:!0}),layouts:[{type:"bi.center",hgap:0,vgap:0}]}),this.buttongroup.on(BI.ButtonGroup.EVENT_CHANGE,function(a,c){b.fireEvent(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON,a,c)}),this.buttongroup}}}),BI.MultiPopupView.EVENT_CHANGE="EVENT_CHANGE",BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON="EVENT_CLICK_TOOLBAR_BUTTON",BI.shortcut("bi.multi_popup_view",BI.MultiPopupView),BI.PopupPanel=BI.inherit(BI.MultiPopupView,{_defaultConfig:function(){var a=BI.PopupPanel.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-popup-panel",title:""})},_init:function(){BI.PopupPanel.superclass._init.apply(this,arguments)},_createTool:function(){var a=this,b=this.options,c=BI.createWidget({type:"bi.icon_button",cls:"close-h-font",width:25,height:25});return c.on(BI.IconButton.EVENT_CHANGE,function(){a.setVisible(!1),a.fireEvent(BI.PopupPanel.EVENT_CLOSE)}),BI.createWidget({type:"bi.htape",cls:"popup-panel-title bi-background bi-border",height:25,items:[{el:{type:"bi.label",textAlign:"left",text:b.title,height:25,lgap:10}},{el:c,width:25}]})}}),BI.PopupPanel.EVENT_CHANGE="EVENT_CHANGE",BI.PopupPanel.EVENT_CLOSE="EVENT_CLOSE",BI.PopupPanel.EVENT_CLICK_TOOLBAR_BUTTON="EVENT_CLICK_TOOLBAR_BUTTON",BI.shortcut("bi.popup_panel",BI.PopupPanel),BI.ListPane=BI.inherit(BI.Pane,{_defaultConfig:function(){var a=BI.ListPane.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-list-pane",logic:{dynamic:!0},lgap:0,rgap:0,tgap:0,bgap:0,vgap:0,hgap:0,items:[],itemsCreator:BI.emptyFn,hasNext:BI.emptyFn,onLoaded:BI.emptyFn,el:{type:"bi.button_group"}})},_init:function(){BI.ListPane.superclass._init.apply(this,arguments);var a=this,b=this.options;this.button_group=BI.createWidget(b.el,{type:"bi.button_group",chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,behaviors:{},items:b.items,itemsCreator:function(c,d){1===c.times&&(a.empty(),BI.nextTick(function(){a.loading()})),b.itemsCreator(c,function(){d.apply(a,arguments),1===c.times&&BI.nextTick(function(){a.loaded()})})},hasNext:b.hasNext,layouts:[{type:"bi.vertical"}]}),this.button_group.on(BI.Controller.EVENT_CHANGE,function(b,c,d){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments),b===BI.Events.CLICK&&a.fireEvent(BI.ListPane.EVENT_CHANGE,c,d)}),this.check(),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Top),BI.extend({scrolly:!0,lgap:b.lgap,rgap:b.rgap,tgap:b.tgap,bgap:b.bgap,vgap:b.vgap,hgap:b.hgap},b.logic,{items:BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Top,this.button_group) }))))},hasPrev:function(){return this.button_group.hasPrev&&this.button_group.hasPrev()},hasNext:function(){return this.button_group.hasNext&&this.button_group.hasNext()},prependItems:function(a){this.options.items=a.concat(this.options.items),this.button_group.prependItems.apply(this.button_group,arguments),this.check()},addItems:function(a){this.options.items=this.options.items.concat(a),this.button_group.addItems.apply(this.button_group,arguments),this.check()},removeItemAt:function(a){a=a||[],BI.removeAt(this.options.items,a),this.button_group.removeItemAt.apply(this.button_group,arguments),this.check()},populate:function(a){var b=this;this.options;return 0===arguments.length&&BI.isFunction(this.button_group.attr("itemsCreator"))?void this.button_group.attr("itemsCreator").apply(this,[{times:1},function(){if(0===arguments.length)throw new Error("参数不能为空");b.populate.apply(b,arguments)}]):(BI.ListPane.superclass.populate.apply(this,arguments),void this.button_group.populate.apply(this.button_group,arguments))},empty:function(){this.button_group.empty()},setNotSelectedValue:function(){this.button_group.setNotSelectedValue.apply(this.button_group,arguments)},getNotSelectedValue:function(){return this.button_group.getNotSelectedValue()},setValue:function(){this.button_group.setValue.apply(this.button_group,arguments)},getValue:function(){return this.button_group.getValue.apply(this.button_group,arguments)},getAllButtons:function(){return this.button_group.getAllButtons()},getAllLeaves:function(){return this.button_group.getAllLeaves()},getSelectedButtons:function(){return this.button_group.getSelectedButtons()},getNotSelectedButtons:function(){return this.button_group.getNotSelectedButtons()},getIndexByValue:function(a){return this.button_group.getIndexByValue(a)},getNodeById:function(a){return this.button_group.getNodeById(a)},getNodeByValue:function(a){return this.button_group.getNodeByValue(a)}}),BI.ListPane.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.list_pane",BI.ListPane),BI.Panel=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.Panel.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-panel bi-border",title:"",titleButtons:[],el:{},logic:{dynamic:!1}})},_init:function(){BI.Panel.superclass._init.apply(this,arguments);var a=this.options;BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic("vertical",BI.extend(a.logic,{items:BI.LogicFactory.createLogicItemsByDirection("top",this._createTitle(),this.options.el)}))))},_createTitle:function(){var a=this,b=this.options;return this.text=BI.createWidget({type:"bi.label",cls:"panel-title-text",text:b.title,height:30}),this.button_group=BI.createWidget({type:"bi.button_group",items:b.titleButtons,layouts:[{type:"bi.center_adapt",lgap:10}]}),this.button_group.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.button_group.on(BI.ButtonGroup.EVENT_CHANGE,function(b,c){a.fireEvent(BI.Panel.EVENT_CHANGE,b,c)}),{el:{type:"bi.left_right_vertical_adapt",cls:"panel-title bi-tips bi-border-bottom bi-background",height:30,items:{left:[this.text],right:[this.button_group]},lhgap:10,rhgap:10},height:30}},setTitle:function(a){this.text.setValue(a)}}),BI.Panel.EVENT_CHANGE="Panel.EVENT_CHANGE",BI.shortcut("bi.panel",BI.Panel),BI.SelectList=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SelectList.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-select-list",direction:BI.Direction.Top,logic:{dynamic:!0},items:[],itemsCreator:BI.emptyFn,hasNext:BI.emptyFn,onLoaded:BI.emptyFn,toolbar:{type:"bi.multi_select_bar"},el:{type:"bi.list_pane"}})},_init:function(){BI.SelectList.superclass._init.apply(this,arguments);var a=this,b=this.options;this.toolbar=BI.createWidget(b.toolbar),this.allSelected=!1,this.toolbar.on(BI.Controller.EVENT_CHANGE,function(b,c,d){a.allSelected=this.isSelected(),b===BI.Events.CLICK&&(a.setAllSelected(a.allSelected),a.fireEvent(BI.SelectList.EVENT_CHANGE,c,d)),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.list=BI.createWidget(b.el,{type:"bi.list_pane",items:b.items,itemsCreator:function(c,d){1===c.times&&a.toolbar.setVisible(!1),b.itemsCreator(c,function(b){d.apply(a,arguments),1===c.times&&(a.toolbar.setVisible(b&&b.length>0),a.toolbar.setEnable(b&&b.length>0)),a._checkAllSelected()})},onLoaded:b.onLoaded,hasNext:b.hasNext}),this.list.on(BI.Controller.EVENT_CHANGE,function(b,c,d){b===BI.Events.CLICK&&(a._checkAllSelected(),a.fireEvent(BI.SelectList.EVENT_CHANGE,c,d)),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(b.direction),BI.extend({scrolly:!0},b.logic,{items:BI.LogicFactory.createLogicItemsByDirection(b.direction,this.toolbar,this.list)})))),b.items.length<=0&&(this.toolbar.setVisible(!1),this.toolbar.setEnable(!1))},_checkAllSelected:function(){var a=this.list.getValue().length,b=this.getAllLeaves().length-a,c=this.list.hasNext(),d=this.toolbar.isSelected(),e=a>0&&(b>0||!d&&c);e=e||b>0&&c&&d,this.toolbar.setHalfSelected(e),!e&&this.toolbar.setSelected(a>0&&b<=0&&(!c||d))},setAllSelected:function(a){BI.each(this.getAllButtons(),function(b,c){(c.setSelected||c.setAllSelected).apply(c,[a])}),this.allSelected=!!a,this.toolbar.setSelected(a),this.toolbar.setHalfSelected(!1)},setToolBarVisible:function(a){this.toolbar.setVisible(a)},isAllSelected:function(){return this.allSelected},hasPrev:function(){return this.list.hasPrev()},hasNext:function(){return this.list.hasNext()},prependItems:function(a){this.list.prependItems.apply(this.list,arguments)},addItems:function(a){this.list.addItems.apply(this.list,arguments)},setValue:function(a){var b=a.type===BI.ButtonGroup.CHOOSE_TYPE_ALL;this.setAllSelected(b),this.list[b?"setNotSelectedValue":"setValue"](a.value),this._checkAllSelected()},getValue:function(){return this.isAllSelected()===!1?{type:BI.ButtonGroup.CHOOSE_TYPE_MULTI,value:this.list.getValue(),assist:this.list.getNotSelectedValue()}:{type:BI.ButtonGroup.CHOOSE_TYPE_ALL,value:this.list.getNotSelectedValue(),assist:this.list.getValue()}},empty:function(){this.list.empty()},populate:function(a){this.toolbar.setVisible(!BI.isEmptyArray(a)),this.toolbar.setEnable(!BI.isEmptyArray(a)),this.list.populate.apply(this.list,arguments),this._checkAllSelected()},_setEnable:function(a){BI.SelectList.superclass._setEnable.apply(this,arguments),this.toolbar.setEnable(a)},resetHeight:function(a){var b=(this.toolbar.element.outerHeight()||25)*(this.toolbar.isVisible()?1:0);this.list.resetHeight?this.list.resetHeight(a-b):this.list.element.css({"max-height":a-b+"px"})},setNotSelectedValue:function(){this.list.setNotSelectedValue.apply(this.list,arguments),this._checkAllSelected()},getNotSelectedValue:function(){return this.list.getNotSelectedValue()},getAllButtons:function(){return this.list.getAllButtons()},getAllLeaves:function(){return this.list.getAllLeaves()},getSelectedButtons:function(){return this.list.getSelectedButtons()},getNotSelectedButtons:function(){return this.list.getNotSelectedButtons()},getIndexByValue:function(a){return this.list.getIndexByValue(a)},getNodeById:function(a){return this.list.getNodeById(a)},getNodeByValue:function(a){return this.list.getNodeByValue(a)}}),BI.SelectList.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.select_list",BI.SelectList),BI.LazyLoader=BI.inherit(BI.Widget,{_const:{PAGE:100},_defaultConfig:function(){return BI.extend(BI.LazyLoader.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-lazy-loader",el:{}})},_init:function(){var a=this,b=this.options;BI.LazyLoader.superclass._init.apply(this,arguments);var c=b.items.length;this.loader=BI.createWidget({type:"bi.loader",element:this,el:b.el,itemsCreator:function(b,c){c(a._getNextItems(b))},hasNext:function(a){return a.count=1)},setValue:function(a){this.pager.setValue(a)},setVPage:function(a){this.pager.setValue(a)},setCount:function(a){this.rowCount.setText(a),this.rowCount.setTitle(a)},getCurrentPage:function(){return this.pager.getCurrentPage()},hasPrev:function(){return this.pager.hasPrev()},hasNext:function(){return this.pager.hasNext()},setPagerVisible:function(a){this.editor.setVisible(a),this.allPages.setVisible(a),this.pager.setVisible(a)},populate:function(){this.pager.populate()}}),BI.AllCountPager.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.all_count_pager",BI.AllCountPager),BI.DirectionPager=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.DirectionPager.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-direction-pager",height:30,horizontal:{pages:!1,curr:1,hasPrev:BI.emptyFn,hasNext:BI.emptyFn,firstPage:1,lastPage:BI.emptyFn},vertical:{pages:!1,curr:1,hasPrev:BI.emptyFn,hasNext:BI.emptyFn,firstPage:1,lastPage:BI.emptyFn}})},_init:function(){BI.DirectionPager.superclass._init.apply(this,arguments);var a=this.options;a.vertical,a.horizontal;this._createVPager(),this._createHPager(),this.layout=BI.createWidget({type:"bi.absolute",scrollable:!1,element:this,items:[{el:this.vpager,top:5,right:74},{el:this.vlabel,top:5,right:111},{el:this.hpager,top:5,right:-9},{el:this.hlabel,top:5,right:28}]})},_createVPager:function(){var a=this,b=this.options,c=b.vertical;this.vlabel=BI.createWidget({type:"bi.label",width:24,height:20,value:c.curr,title:c.curr,invisible:!0}),this.vpager=BI.createWidget({type:"bi.pager",width:76,layouts:[{type:"bi.horizontal",scrollx:!1,rgap:24,vgap:1}],invisible:!0,dynamicShow:!1,pages:c.pages,curr:c.curr,groups:0,first:!1,last:!1,prev:{type:"bi.icon_button",value:"prev",title:BI.i18nText("BI-Up_Page"),warningTitle:BI.i18nText("BI-Current_Is_First_Page"),height:20,iconWidth:16,iconHeight:16,cls:"direction-pager-prev column-pre-page-h-font"},next:{type:"bi.icon_button",value:"next",title:BI.i18nText("BI-Down_Page"),warningTitle:BI.i18nText("BI-Current_Is_Last_Page"),height:20,iconWidth:16,iconHeight:16,cls:"direction-pager-next column-next-page-h-font"},hasPrev:c.hasPrev,hasNext:c.hasNext,firstPage:c.firstPage,lastPage:c.lastPage}),this.vpager.on(BI.Pager.EVENT_CHANGE,function(){a.fireEvent(BI.DirectionPager.EVENT_CHANGE)}),this.vpager.on(BI.Pager.EVENT_AFTER_POPULATE,function(){a.vlabel.setValue(this.getCurrentPage()),a.vlabel.setTitle(this.getCurrentPage())})},_createHPager:function(){var a=this,b=this.options,c=b.horizontal;this.hlabel=BI.createWidget({type:"bi.label",width:24,height:20,value:c.curr,title:c.curr,invisible:!0}),this.hpager=BI.createWidget({type:"bi.pager",width:76,layouts:[{type:"bi.horizontal",scrollx:!1,rgap:24,vgap:1}],invisible:!0,dynamicShow:!1,pages:c.pages,curr:c.curr,groups:0,first:!1,last:!1,prev:{type:"bi.icon_button",value:"prev",title:BI.i18nText("BI-Left_Page"),warningTitle:BI.i18nText("BI-Current_Is_First_Page"),height:20,iconWidth:16,iconHeight:16,cls:"direction-pager-prev row-pre-page-h-font"},next:{type:"bi.icon_button",value:"next",title:BI.i18nText("BI-Right_Page"),warningTitle:BI.i18nText("BI-Current_Is_Last_Page"),height:20,iconWidth:16,iconHeight:16,cls:"direction-pager-next row-next-page-h-font"},hasPrev:c.hasPrev,hasNext:c.hasNext,firstPage:c.firstPage,lastPage:c.lastPage}),this.hpager.on(BI.Pager.EVENT_CHANGE,function(){a.fireEvent(BI.DirectionPager.EVENT_CHANGE)}),this.hpager.on(BI.Pager.EVENT_AFTER_POPULATE,function(){a.hlabel.setValue(this.getCurrentPage()),a.hlabel.setTitle(this.getCurrentPage())})},getVPage:function(){return this.vpager.getCurrentPage()},getHPage:function(){return this.hpager.getCurrentPage()},setVPage:function(a){this.vpager.setValue(a),this.vlabel.setValue(a),this.vlabel.setTitle(a)},setHPage:function(a){this.hpager.setValue(a),this.hlabel.setValue(a),this.hlabel.setTitle(a)},hasVNext:function(){return this.vpager.hasNext()},hasHNext:function(){return this.hpager.hasNext()},hasVPrev:function(){return this.vpager.hasPrev()},hasHPrev:function(){return this.hpager.hasPrev()},setHPagerVisible:function(a){this.hpager.setVisible(a),this.hlabel.setVisible(a)},setVPagerVisible:function(a){this.vpager.setVisible(a),this.vlabel.setVisible(a)},populate:function(){this.vpager.populate(),this.hpager.populate();var a=!1,b=!1;this.hasHNext()||this.hasHPrev()?(this.setHPagerVisible(!0),b=!0):this.setHPagerVisible(!1),this.hasVNext()||this.hasVPrev()?(this.setVPagerVisible(!0),a=!0):this.setVPagerVisible(!1),this.setVisible(b||a);var c=[74,111,-9,28],d=this.layout.attr("items");a===!0&&b===!0?(d[0].right=c[0],d[1].right=c[1],d[2].right=c[2],d[3].right=c[3]):a===!0?(d[0].right=c[2],d[1].right=c[3]):b===!0&&(d[2].right=c[2],d[3].right=c[3]),this.layout.attr("items",d),this.layout.resize()},clear:function(){this.vpager.attr("curr",1),this.hpager.attr("curr",1)}}),BI.DirectionPager.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.direction_pager",BI.DirectionPager),BI.DetailPager=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.DetailPager.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-detail-pager",behaviors:{},layouts:[{type:"bi.horizontal",hgap:10,vgap:0}],dynamicShow:!0,dynamicShowFirstLast:!1,dynamicShowPrevNext:!1,pages:!1,curr:function(){return 1},groups:0,jump:BI.emptyFn,first:!1,last:!1,prev:"上一页",next:"下一页",firstPage:1,lastPage:function(){return 1},hasPrev:BI.emptyFn,hasNext:BI.emptyFn})},_init:function(){BI.DetailPager.superclass._init.apply(this,arguments);var a=this;this.currPage=BI.result(this.options,"curr"),this._lock=!1,this._debouce=BI.debounce(function(){a._lock=!1},300),this._populate()},_populate:function(){var a=this,b=this.options,c=[],d={};this.empty();var e=BI.result(b,"pages"),f=BI.result(this,"currPage"),g=BI.result(b,"groups"),h=BI.result(b,"first"),i=BI.result(b,"last"),j=BI.result(b,"prev"),k=BI.result(b,"next");e===!1?(g=0,h=!1,i=!1):g>e&&(g=e),d.index=Math.ceil((f+(g>1&&g!==e?1:0))/(0===g?1:g)),(!b.dynamicShow&&!b.dynamicShowPrevNext||f>1)&&j!==!1&&(BI.isKey(j)?c.push({text:j,value:"prev",disabled:e===!1?b.hasPrev(f)===!1:!(f>1&&j!==!1)}):c.push(BI.extend({disabled:e===!1?b.hasPrev(f)===!1:!(f>1&&j!==!1)},j))),(!b.dynamicShow&&!b.dynamicShowFirstLast||d.index>1&&0!==g)&&h&&(c.push({text:h,value:"first",disabled:!(d.index>1&&0!==g)}),d.index>1&&0!==g&&c.push({type:"bi.label",cls:"page-ellipsis",text:"…"})),d.poor=Math.floor((g-1)/2),d.start=d.index>1?f-d.poor:1,d.end=d.index>1?function(){var a=f+(g-d.poor-1);return a>e?e:a}():g,d.end-d.start1&&0!==g&&e>g&&d.endg&&d.endg&&d.endg&&d.end1},hasNext:function(a){a||(a=1);var b=this.options,c=this.options.pages;return c===!1?b.hasNext(a):ac?c:(d=BI.result(b,"firstPage"),ab.pages?b.pages:a,this.currPage=a;this._populate()},getValue:function(){var a=this.button_group.getValue()[0];switch(a){case"prev":return-1;case"next":return 1;case"first":return BI.MIN;case"last":return BI.MAX;default:return a}},attr:function(a,b){BI.DetailPager.superclass.attr.apply(this,arguments),"curr"===a&&(this.currPage=BI.result(this.options,"curr"))},populate:function(){this._populate()}}),BI.DetailPager.EVENT_CHANGE="EVENT_CHANGE",BI.DetailPager.EVENT_AFTER_POPULATE="EVENT_AFTER_POPULATE",BI.shortcut("bi.detail_pager",BI.DetailPager),BI.RichEditorAction=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.RichEditorAction.superclass._defaultConfig.apply(this,arguments),{width:20,height:20,command:""})},_init:function(){BI.RichEditorAction.superclass._init.apply(this,arguments);var a=this,b=this.options;b.editor.on(BI.NicEditor.EVENT_SELECTED,function(b){a.setEnable(!0),a.checkNodes(b.target),a.key(b)}),b.editor.on(BI.NicEditor.EVENT_BLUR,function(){a.setEnable(!1)}),b.editor.on(BI.NicEditor.EVENT_KEYDOWN,BI.bind(this.keydown,this))},checkNodes:function(a){if(!a)return!1;var b=a;do if(this.options.tags&&this.options.tags.contains(b.nodeName))return this.activate(),!0;while(b=b.parentNode&&b.className&&b.className.indexOf("bi-nic-editor")>=-1);for(b=a;3==b.nodeType;)b=b.parentNode;if(this.options.css)for(var c in this.options.css)if($(b).css(c)==this.options.css[c])return this.activate(),!0;return this.deactivate(),!1},start:function(){},key:function(){},keydown:function(){},hideIf:function(a){},activate:function(){},deactivate:function(){},doCommand:function(a){this.options.command&&this.options.editor.nicCommand(this.options.command,a)}}),BI.RichEditorParamAction=BI.inherit(BI.RichEditorAction,{_defaultConfig:function(){return BI.extend(BI.RichEditorParamAction.superclass._defaultConfig.apply(this,arguments),{})},_init:function(){BI.RichEditorParamAction.superclass._init.apply(this,arguments)},_isParam:function(a){return"param"===a.attr("data-type")},_createBlankNode:function(){return $("").html(" ")},_addBlank:function(a){var b=this.options,c=b.editor.selectedInstance,d=a.next();if(0===d.length||this._isParam(d)){var e=this._createBlankNode(),f=this._createBlankNode();a.before(e),a.after(f),c.setFocus(f[0])}else c.setFocus(d[0])},_get$Sel:function(){var a=this.options,b=a.editor.selectedInstance,c=$(b.selElm());return 3===c[0].nodeType&&this._isParam(c.parent())&&(c=c.parent()),c},addParam:function(a){var b=this.options,c=this._get$Sel(),d=$("").attr({"data-type":"param","data-value":a}).css({color:"white",backgroundColor:"#009de3",padding:"0 5px"}).text(a).keydown(function(a){return a.keyCode!==BI.KeyCode.BACKSPACE&&a.keyCode!==BI.KeyCode.DELETE||d.destroy(),a.stopEvent(),!1}),e=b.editor.instance.getElm().element;e.find(c).length<=0?e.append(d):c.after(d),this._addBlank(d)},keydown:function(a){var b=(this.options,this._get$Sel());return 229===a.keyCode&&this._isParam(b)?(this._addBlank(b),a.stopEvent(),!1):(BI.Key[a.keyCode]||a.keyCode===BI.KeyCode.TAB||a.keyCode===BI.KeyCode.ENTER||a.keyCode===BI.KeyCode.SPACE)&&this._isParam(b)?(a.stopEvent(),!1):a.keyCode!==BI.KeyCode.BACKSPACE&&a.keyCode!==BI.KeyCode.DELETE||!this._isParam(b)?void 0:(b.destroy(),a.preventDefault(),!1)},key:function(a){}}),BI.RichEditorTextToolbar=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.RichEditorTextToolbar.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-rich-editor-text-toolbar bi-background",buttons:[{type:"bi.rich_editor_size_chooser"},{type:"bi.rich_editor_bold_button"},{type:"bi.rich_editor_italic_button"},{type:"bi.rich_editor_underline_button"},{type:"bi.rich_editor_color_chooser"},{type:"bi.rich_editor_background_color_chooser"},{type:"bi.rich_editor_align_left_button"},{type:"bi.rich_editor_align_center_button"},{type:"bi.rich_editor_align_right_button"},{type:"bi.rich_editor_param_button"}],height:28})},_init:function(){BI.RichEditorTextToolbar.superclass._init.apply(this,arguments);var a=this.options,b=BI.createWidgets(BI.map(a.buttons,function(b,c){return BI.extend(c,{editor:a.editor})}));this.element.mousedown(function(a){BI.each(b,function(b,c){c.hideIf(a)})}),BI.createWidget({type:"bi.left",element:this,items:b,hgap:3,vgap:3})},mounted:function(){var a=this;BI.isIE9Below()&&(this.element.mousedown(function(){a._noSelect(a.element[0])}),this._noSelect(this.element[0]))},_noSelect:function(a){a.setAttribute&&"input"!=a.nodeName.toLowerCase()&&"textarea"!=a.nodeName.toLowerCase()&&a.setAttribute("unselectable","on");for(var b=0;b0)c=this._getRegionCl right:0,bottom:0},{el:c,top:0,left:0}]});BI.createWidget({type:"bi.htape",element:this,items:[d,{el:this.changeIcon,width:30}],ref:function(b){a.comboWrapper=b}})},_checkDynamicValue:function(a){var b=null;switch(BI.isNotNull(a)&&(b=a.type),b){case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY:this.changeIcon.setVisible(!0),this.comboWrapper.attr("items")[1].width=30,this.comboWrapper.resize();break;default:this.comboWrapper.attr("items")[1].width=0,this.comboWrapper.resize(),this.changeIcon.setVisible(!1)}},setValue:function(a){this.storeValue=a,this.popup.setValue(a),this.trigger.setValue(a),this._checkDynamicValue(a)},getValue:function(){return this.storeValue},getKey:function(){return this.trigger.getKey()},hidePopupView:function(){this.combo.hideView()}}),BI.shortcut("bi.multidate_combo",BI.MultiDateCombo),BI.MultiDateCombo.EVENT_CONFIRM="EVENT_CONFIRM",BI.MultiDateCombo.EVENT_FOCUS="EVENT_FOCUS",BI.MultiDateCombo.EVENT_CHANGE="EVENT_CHANGE",BI.MultiDateCombo.EVENT_VALID="EVENT_VALID",BI.MultiDateCombo.EVENT_ERROR="EVENT_ERROR",BI.MultiDateCombo.EVENT_BEFORE_POPUPVIEW="BI.MultiDateCombo.EVENT_BEFORE_POPUPVIEW",BI.extend(BI.MultiDateCombo,{MULTI_DATE_YMD_CARD:1,MULTI_DATE_YEAR_CARD:2,MULTI_DATE_QUARTER_CARD:3,MULTI_DATE_MONTH_CARD:4,MULTI_DATE_WEEK_CARD:5,MULTI_DATE_DAY_CARD:6}),BI.extend(BI.MultiDateCombo,{DATE_TYPE:{MULTI_DATE_YEAR_PREV:1,MULTI_DATE_YEAR_AFTER:2,MULTI_DATE_YEAR_BEGIN:3,MULTI_DATE_YEAR_END:4,MULTI_DATE_MONTH_PREV:5,MULTI_DATE_MONTH_AFTER:6,MULTI_DATE_MONTH_BEGIN:7,MULTI_DATE_MONTH_END:8,MULTI_DATE_QUARTER_PREV:9,MULTI_DATE_QUARTER_AFTER:10,MULTI_DATE_QUARTER_BEGIN:11,MULTI_DATE_QUARTER_END:12,MULTI_DATE_WEEK_PREV:13,MULTI_DATE_WEEK_AFTER:14,MULTI_DATE_DAY_PREV:15,MULTI_DATE_DAY_AFTER:16,MULTI_DATE_DAY_TODAY:17,MULTI_DATE_PARAM:18,MULTI_DATE_CALENDAR:19,YEAR_QUARTER:20,YEAR_MONTH:21,YEAR_WEEK:22,YEAR_DAY:23,MONTH_WEEK:24,MONTH_DAY:25,YEAR:26,SAME_PERIOD:27,LAST_SAME_PERIOD:28}}),BI.DayCard=BI.inherit(BI.MultiDateCard,{_defaultConfig:function(){return $.extend(BI.DayCard.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multidate-daycard"})},_init:function(){BI.DayCard.superclass._init.apply(this,arguments)},dateConfig:function(){return[{isEditorExist:!0,selected:!0,text:BI.i18nText("BI-Multi_Date_Day_Prev"),value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV},{isEditorExist:!0,text:BI.i18nText("BI-Multi_Date_Day_Next"),value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER},{isEditorExist:!1,value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY,text:BI.i18nText("BI-Multi_Date_Today")}]},defaultSelectedItem:function(){return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV}}),BI.DayCard.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.daycard",BI.DayCard),BI.MonthCard=BI.inherit(BI.MultiDateCard,{_defaultConfig:function(){return $.extend(BI.MonthCard.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multidate-monthcard"})},_init:function(){BI.MonthCard.superclass._init.apply(this,arguments)},dateConfig:function(){return[{selected:!0,isEditorExist:!0,value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_PREV,text:BI.i18nText("BI-Multi_Date_Month_Prev")},{isEditorExist:!0,value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER,text:BI.i18nText("BI-Multi_Date_Month_Next")},{value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN,isEditorExist:!1,text:BI.i18nText("BI-Multi_Date_Month_Begin")},{value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END,isEditorExist:!1,text:BI.i18nText("BI-Multi_Date_Month_End")}]},defaultSelectedItem:function(){return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_PREV}}),BI.MonthCard.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.monthcard",BI.MonthCard),BI.MultiDatePopup=BI.inherit(BI.Widget,{constants:{tabHeight:30,tabWidth:42,titleHeight:27,itemHeight:30,triggerHeight:24,buttonWidth:90,buttonHeight:25,cardHeight:229,cardWidth:270,popupHeight:259,popupWidth:270,comboAdjustHeight:1,ymdWidth:58,lgap:2,border:1},_defaultConfig:function(){return BI.extend(BI.MultiDatePopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multidate-popup",width:268,height:260})},_init:function(){BI.MultiDatePopup.superclass._init.apply(this,arguments);var a=this;this.options;this.storeValue="",this.textButton=BI.createWidget({type:"bi.text_button",forceCenter:!0,cls:"bi-multidate-popup-label bi-border-left bi-border-right bi-border-top",shadow:!0,text:BI.i18nText("BI-Multi_Date_Today")}),this.textButton.on(BI.TextButton.EVENT_CHANGE,function(){a.fireEvent(BI.MultiDatePopup.BUTTON_lABEL_EVENT_CHANGE)}),this.clearButton=BI.createWidget({type:"bi.text_button",forceCenter:!0,cls:"bi-multidate-popup-button bi-border-top",shadow:!0,text:BI.i18nText("BI-Basic_Clear")}),this.clearButton.on(BI.TextButton.EVENT_CHANGE,function(){a.fireEvent(BI.MultiDatePopup.BUTTON_CLEAR_EVENT_CHANGE)}),this.okButton=BI.createWidget({type:"bi.text_button",forceCenter:!0,cls:"bi-multidate-popup-button bi-border-top",shadow:!0,text:BI.i18nText("BI-Basic_OK")}),this.okButton.on(BI.TextButton.EVENT_CHANGE,function(){a.fireEvent(BI.MultiDatePopup.BUTTON_OK_EVENT_CHANGE)}),this.dateTab=BI.createWidget({type:"bi.tab",tab:{cls:"bi-multidate-popup-tab bi-border-bottom",height:this.constants.tabHeight,items:BI.createItems([{text:BI.i18nText("BI-Multi_Date_YMD"),value:BI.MultiDateCombo.MULTI_DATE_YMD_CARD,width:this.constants.ymdWidth},{text:BI.i18nText("BI-Multi_Date_Year"),value:BI.MultiDateCombo.MULTI_DATE_YEAR_CARD},{text:BI.i18nText("BI-Multi_Date_Quarter"),value:BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD},{text:BI.i18nText("BI-Multi_Date_Month"),value:BI.MultiDateCombo.MULTI_DATE_MONTH_CARD},{text:BI.i18nText("BI-Multi_Date_Week"),value:BI.MultiDateCombo.MULTI_DATE_WEEK_CARD},{text:BI.i18nText("BI-Multi_Date_Day"),value:BI.MultiDateCombo.MULTI_DATE_DAY_CARD}],{width:this.constants.tabWidth,textAlign:"center",height:this.constants.itemHeight,cls:"bi-multidate-popup-item bi-list-item-active"}),layouts:[{type:"bi.left"}]},cardCreator:function(b){switch(b){case BI.MultiDateCombo.MULTI_DATE_YMD_CARD:return a.ymd=BI.createWidget({type:"bi.date_calendar_popup",min:a.options.min,max:a.options.max}),a.ymd.on(BI.DateCalendarPopup.EVENT_CHANGE,function(){a.fireEvent(BI.MultiDatePopup.CALENDAR_EVENT_CHANGE)}),a.ymd;case BI.MultiDateCombo.MULTI_DATE_YEAR_CARD:return a.year=BI.createWidget({type:"bi.yearcard"}),a.year.on(BI.MultiDateCard.EVENT_CHANGE,function(b){a._setInnerValue(a.year,b)}),a.year;case BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD:return a.quarter=BI.createWidget({type:"bi.quartercard"}),a.quarter.on(BI.MultiDateCard.EVENT_CHANGE,function(b){a._setInnerValue(a.quarter,b)}),a.quarter;case BI.MultiDateCombo.MULTI_DATE_MONTH_CARD:return a.month=BI.createWidget({type:"bi.monthcard"}),a.month.on(BI.MultiDateCard.EVENT_CHANGE,function(b){a._setInnerValue(a.month,b)}),a.month;case BI.MultiDateCombo.MULTI_DATE_WEEK_CARD:return a.week=BI.createWidget({type:"bi.weekcard"}),a.week.on(BI.MultiDateCard.EVENT_CHANGE,function(b){a._setInnerValue(a.week,b)}),a.week;case BI.MultiDateCombo.MULTI_DATE_DAY_CARD:return a.day=BI.createWidget({type:"bi.daycard"}),a.day.on(BI.MultiDateCard.EVENT_CHANGE,function(b){a._setInnerValue(a.day,b)}),a.day}}}),this.dateTab.setSelect(BI.MultiDateCombo.MULTI_DATE_YMD_CARD),this.cur=BI.MultiDateCombo.MULTI_DATE_YMD_CARD,this.dateTab.on(BI.Tab.EVENT_CHANGE,function(){var b=a.dateTab.getSelect();switch(b){case BI.MultiDateCombo.MULTI_DATE_YMD_CARD:var c=this.getTab(a.cur).getCalculationValue();a.ymd.setValue({year:c.getFullYear(),month:c.getMonth(),day:c.getDate()}),a._setInnerValue(a.ymd);break;case BI.MultiDateCombo.MULTI_DATE_YEAR_CARD:a.year.setValue(a.storeValue),a._setInnerValue(a.year);break;case BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD:a.quarter.setValue(a.storeValue),a._setInnerValue(a.quarter);break;case BI.MultiDateCombo.MULTI_DATE_MONTH_CARD:a.month.setValue(a.storeValue),a._setInnerValue(a.month);break;case BI.MultiDateCombo.MULTI_DATE_WEEK_CARD:a.week.setValue(a.storeValue),a._setInnerValue(a.week);break;case BI.MultiDateCombo.MULTI_DATE_DAY_CARD:a.day.setValue(a.storeValue),a._setInnerValue(a.day)}a.cur=b}),this.dateButton=BI.createWidget({type:"bi.grid",items:[[this.clearButton,this.textButton,this.okButton]]}),BI.createWidget({element:this,type:"bi.vtape",items:[{el:this.dateTab},{el:this.dateButton,height:30}]})},_setInnerValue:function(a){if(this.dateTab.getSelect()===BI.MultiDateCombo.MULTI_DATE_YMD_CARD)this.textButton.setValue(BI.i18nText("BI-Multi_Date_Today")),this.textButton.setEnable(!0);else{var b=a.getCalculationValue();b=b.print("%Y-%x-%e"),this.textButton.setValue(b),this.textButton.setEnable(!1)}},_checkValueValid:function(a){return BI.isNull(a)||BI.isEmptyObject(a)||BI.isEmptyString(a)},setValue:function(a){this.storeValue=a;var b,c,d,e=this;switch(BI.isNotNull(a)&&(c=a.type||BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_CALENDAR,d=a.value,BI.isNull(d)&&(d=a)),c){case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END:this.dateTab.setSelect(BI.MultiDateCombo.MULTI_DATE_YEAR_CARD),this.year.setValue({type:c,value:d}),this.cur=BI.MultiDateCombo.MULTI_DATE_YEAR_CARD,e._setInnerValue(this.year);break;case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END:this.dateTab.setSelect(BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD),this.cur=BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD,this.quarter.setValue({type:c,value:d}),e._setInnerValue(this.quarter);break;case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END:this.dateTab.setSelect(BI.MultiDateCombo.MULTI_DATE_MONTH_CARD),this.cur=BI.MultiDateCombo.MULTI_DATE_MONTH_CARD,this.month.setValue({type:c,value:d}),e._setInnerValue(this.month);break;case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER:this.dateTab.setSelect(BI.MultiDateCombo.MULTI_DATE_WEEK_CARD),this.cur=BI.MultiDateCombo.MULTI_DATE_WEEK_CARD,this.week.setValue({type:c,value:d}),e._setInnerValue(this.week);break;case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER:case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY:this.dateTab.setSelect(BI.MultiDateCombo.MULTI_DATE_DAY_CARD),this.cur=BI.MultiDateCombo.MULTI_DATE_DAY_CARD,this.day.setValue({type:c,value:d}),e._setInnerValue(this.day);break;default:if(this._checkValueValid(d)){var b=Date.getDate();this.dateTab.setSelect(BI.MultiDateCombo.MULTI_DATE_YMD_CARD),this.ymd.setValue({year:b.getFullYear(),month:b.getMonth(),day:b.getDate()}),this.textButton.setValue(BI.i18nText("BI-Multi_Date_Today"))}else this.dateTab.setSelect(BI.MultiDateCombo.MULTI_DATE_YMD_CARD),this.ymd.setValue(d),this.textButton.setValue(BI.i18nText("BI-Multi_Date_Today"));this.textButton.setEnable(!0)}},getValue:function(){var a=this.dateTab.getSelect();switch(a){case BI.MultiDateCombo.MULTI_DATE_YMD_CARD:return this.ymd.getValue();case BI.MultiDateCombo.MULTI_DATE_YEAR_CARD:return this.year.getValue();case BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD:return this.quarter.getValue();case BI.MultiDateCombo.MULTI_DATE_MONTH_CARD:return this.month.getValue();case BI.MultiDateCombo.MULTI_DATE_WEEK_CARD:return this.week.getValue();case BI.MultiDateCombo.MULTI_DATE_DAY_CARD:return this.day.getValue()}}}),BI.MultiDatePopup.BUTTON_OK_EVENT_CHANGE="BUTTON_OK_EVENT_CHANGE",BI.MultiDatePopup.BUTTON_lABEL_EVENT_CHANGE="BUTTON_lABEL_EVENT_CHANGE",BI.MultiDatePopup.BUTTON_CLEAR_EVENT_CHANGE="BUTTON_CLEAR_EVENT_CHANGE",BI.MultiDatePopup.CALENDAR_EVENT_CHANGE="CALENDAR_EVENT_CHANGE",BI.shortcut("bi.multidate_popup",BI.MultiDatePopup),BI.QuarterCard=BI.inherit(BI.MultiDateCard,{_defaultConfig:function(){return $.extend(BI.QuarterCard.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multidate-quartercard"})},_init:function(){BI.QuarterCard.superclass._init.apply(this,arguments)},dateConfig:function(){return[{selected:!0,value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_PREV,isEditorExist:!0,text:BI.i18nText("BI-Multi_Date_Quarter_Prev")},{value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER,isEditorExist:!0,text:BI.i18nText("BI-Multi_Date_Quarter_Next")},{value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN,isEditorExist:!1,text:BI.i18nText("BI-Multi_Date_Quarter_Begin")},{value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END,isEditorExist:!1,text:BI.i18nText("BI-Multi_Date_Quarter_End")}]},defaultSelectedItem:function(){return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_PREV}}),BI.QuarterCard.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.quartercard",BI.QuarterCard),BI.MultiDateSegment=BI.inherit(BI.Single,{constants:{itemHeight:24,maxGap:15,minGap:10,textWidth:60,defaultEditorValue:"1"},_defaultConfig:function(){return $.extend(BI.MultiDateSegment.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multidate-segment",text:"",height:30,isEditorExist:!0,selected:!1,defaultEditorValue:"1"})},_init:function(){BI.MultiDateSegment.superclass._init.apply(this,arguments);var a=this,b=this.options;this.radio=BI.createWidget({type:"bi.radio",selected:b.selected}),this.radio.on(BI.Controller.EVENT_CHANGE,function(b){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.textEditor=BI.createWidget({type:"bi.text_editor",value:this.constants.defaultEditorValue,title:function(){return a.textEditor.getValue()},tipType:"success",cls:"bi-multidate-editor",width:this.constants.textWidth,height:this.constants.itemHeight}),this.textEditor.on(BI.Controller.EVENT_CHANGE,function(b){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",cls:"bi-multidate-normal-label",text:b.text,height:this.constants.itemHeight}),this._createSegment()},_createSegment:function(){return this.options.isEditorExist===!0?BI.createWidget({element:this,type:"bi.left",items:[{el:{type:"bi.center_adapt",items:[this.radio],height:this.constants.itemHeight},lgap:0},{el:{type:"bi.center_adapt",items:[this.textEditor],widgetName:"textEditor"},lgap:this.constants.maxGap},{el:this.text,lgap:this.constants.minGap}]}):BI.createWidget({element:this,type:"bi.left",items:[{el:{type:"bi.center_adapt",items:[this.radio],height:this.constants.itemHeight},lgap:0},{el:this.text,lgap:this.constants.maxGap}]})},setSelected:function(a){BI.isNotNull(this.radio)&&(this.radio.setSelected(a),this.textEditor.setEnable(a))},isSelected:function(){return this.radio.isSelected()},getValue:function(){return this.options.value},getInputValue:function(){return 0|this.textEditor.getValue()},setInputValue:function(a){this.textEditor.setValue(a)},isEditorExist:function(){return this.options.isEditorExist}}),BI.MultiDateSegment.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multidate_segment",BI.MultiDateSegment),BI.WeekCard=BI.inherit(BI.MultiDateCard,{_defaultConfig:function(){return $.extend(BI.WeekCard.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multidate-weekcard"})},_init:function(){BI.WeekCard.superclass._init.apply(this,arguments)},dateConfig:function(){return[{selected:!0,isEditorExist:!0,text:BI.i18nText("BI-Multi_Date_Week_Prev"),value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_PREV},{isEditorExist:!0,text:BI.i18nText("BI-Multi_Date_Week_Next"),value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER}]},defaultSelectedItem:function(){return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_PREV}}),BI.WeekCard.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.weekcard",BI.WeekCard),BI.YearCard=BI.inherit(BI.MultiDateCard,{_defaultConfig:function(){return $.extend(BI.YearCard.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multidate-yearcard"})},_init:function(){BI.YearCard.superclass._init.apply(this,arguments)},dateConfig:function(){return[{selected:!0,isEditorExist:!0,text:BI.i18nText("BI-Multi_Date_Year_Prev"),value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV},{isEditorExist:!0,text:BI.i18nText("BI-Multi_Date_Year_Next"),value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER},{isEditorExist:!1,value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN,text:BI.i18nText("BI-Multi_Date_Year_Begin")},{isEditorExist:!1,value:BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END,text:BI.i18nText("BI-Multi_Date_Year_End")}]},defaultSelectedItem:function(){return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV}}),BI.YearCard.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.yearcard",BI.YearCard),BI.MultiLayerSelectTreeCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSelectTreeCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multilayer_select_tree-combo",isDefaultInit:!1,height:30,text:"",items:[]})},_init:function(){BI.MultiLayerSelectTreeCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget({type:"bi.single_tree_trigger",text:b.text,height:b.height,items:b.items}),this.popup=BI.createWidget({type:"bi.multilayer_select_tree_popup",isDefaultInit:b.isDefaultInit,items:b.items}),this.combo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup}}),this.combo.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.popup.on(BI.MultiLayerSelectTreePopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.combo.hideView(),a.fireEvent(BI.MultiLayerSelectTreeCombo.EVENT_CHANGE)})},setValue:function(a){a=BI.isArray(a)?a:[a],this.trigger.setValue(a),this.popup.setValue(a)},getValue:function(){return this.popup.getValue()},populate:function(a){this.combo.populate(a)}}),BI.MultiLayerSelectTreeCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multilayer_select_tree_combo",BI.MultiLayerSelectTreeCombo),BI.MultiLayerSelectLevelTree=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSelectLevelTree.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multilayer-select-level-tree",isDefaultInit:!1,items:[],itemsCreator:BI.emptyFn})},_init:function(){BI.MultiLayerSelectLevelTree.superclass._init.apply(this,arguments),this.initTree(this.options.items)},_formatItems:function(a,b){var c=this;return BI.each(a,function(d,e){var f={};if(e.layer=b,BI.isKey(e.id)||(e.id=BI.UUID()),e.isParent===!0||BI.isNotEmptyArray(e.children)){switch(d){case 0:f.type="bi.multilayer_select_tree_first_plus_group_node";break;case a.length-1:f.type="bi.multilayer_select_tree_last_plus_group_node";break;default:f.type="bi.multilayer_select_tree_mid_plus_group_node"}BI.defaults(e,f),c._formatItems(e.children,b+1)}else{switch(d){case a.length-1:f.type="bi.multilayer_single_tree_last_tree_leaf_item";break;default:f.type="bi.multilayer_single_tree_mid_tree_leaf_item"}BI.defaults(e,f)}}),a},_assertId:function(a){BI.each(a,function(a,b){b.id=b.id||BI.UUID()})},initTree:function(a){var b=this,c=this.options;this.empty(),this._assertId(a),this.tree=BI.createWidget({type:"bi.custom_tree",element:this,expander:{type:"bi.select_tree_expander",isDefaultInit:c.isDefaultInit,el:{},popup:{type:"bi.custom_tree"}},items:this._formatItems(BI.Tree.transformToTreeFormat(a),0),itemsCreator:c.itemsCreator,el:{type:"bi.button_tree",chooseType:BI.Selection.Single,layouts:[{type:"bi.vertical"}]}}),this.tree.on(BI.Controller.EVENT_CHANGE,function(a){b.fireEvent(BI.Controller.EVENT_CHANGE,arguments),a===BI.Events.CLICK&&b.fireEvent(BI.MultiLayerSelectLevelTree.EVENT_CHANGE,arguments)})},populate:function(a){this.tree.populate(this._formatItems(BI.Tree.transformToTreeFormat(a),0))},setValue:function(a){this.tree.setValue(a)},getValue:function(){return this.tree.getValue()},getAllLeaves:function(){return this.tree.getAllLeaves()},getNodeById:function(a){return this.tree.getNodeById(a)},getNodeByValue:function(a){return this.tree.getNodeByValue(a)}}),BI.MultiLayerSelectLevelTree.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multilayer_select_level_tree",BI.MultiLayerSelectLevelTree),BI.MultiLayerSelectTreePopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSelectTreePopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multilayer-select-tree-popup",tipText:BI.i18nText("BI-No_Selected_Item"),isDefaultInit:!1,itemsCreator:BI.emptyFn,items:[]})},_init:function(){BI.MultiLayerSelectTreePopup.superclass._init.apply(this,arguments);var a=this,b=this.options;this.tree=BI.createWidget({type:"bi.multilayer_select_level_tree",isDefaultInit:b.isDefaultInit,items:b.items,itemsCreator:b.itemsCreator}),BI.createWidget({type:"bi.vertical",scrolly:!1,scrollable:!0,element:this,items:[this.tree]}),this.tree.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.tree.on(BI.MultiLayerSelectLevelTree.EVENT_CHANGE,function(){a.fireEvent(BI.MultiLayerSelectTreePopup.EVENT_CHANGE)}),this.check()},getValue:function(){return this.tree.getValue()},setValue:function(a){a=BI.isArray(a)?a:[a],this.tree.setValue(a)},populate:function(a){BI.MultiLayerSelectTreePopup.superclass.populate.apply(this,arguments),this.tree.populate(a)}}),BI.MultiLayerSelectTreePopup.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multilayer_select_tree_popup",BI.MultiLayerSelectTreePopup),BI.MultiLayerSelectTreeFirstPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-multilayer-select-tree-first-plus-group-node bi-list-item-active",layer:0,id:"",pId:"",readonly:!0,open:!1,height:25})},_init:function(){BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.node=BI.createWidget({type:"bi.select_tree_first_plus_group_node",cls:"bi-list-item-none",stopPropagation:!0,logic:{dynamic:!0},id:b.id,pId:b.pId,open:b.open,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.node.on(BI.Controller.EVENT_CHANGE,function(b){a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.node),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},isOnce:function(){return!0},doRedMark:function(){this.node.doRedMark.apply(this.node,arguments)},unRedMark:function(){this.node.unRedMark.apply(this.node,arguments)},isSelected:function(){return this.node.isSelected()},setSelected:function(a){BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass.setSelected.apply(this,arguments),this.node.setSelected(a)},doClick:function(){BI.NodeButton.superclass.doClick.apply(this,arguments),this.node.setSelected(this.isSelected())},setOpened:function(a){BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass.setOpened.apply(this,arguments),this.node.setOpened(a)}}),BI.shortcut("bi.multilayer_select_tree_first_plus_group_node",BI.MultiLayerSelectTreeFirstPlusGroupNode),BI.MultiLayerSelectTreeLastPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-multilayer-select-tree-last-plus-group-node bi-list-item-active",layer:0,id:"",pId:"",readonly:!0,open:!1,height:25})},_init:function(){BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.node=BI.createWidget({type:"bi.select_tree_last_plus_group_node",cls:"bi-list-item-none",stopPropagation:!0,logic:{dynamic:!0},id:b.id,pId:b.pId,open:b.open,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.node.on(BI.Controller.EVENT_CHANGE,function(b){a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.node),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.node.doRedMark.apply(this.node,arguments)},unRedMark:function(){this.node.unRedMark.apply(this.node,arguments)},isSelected:function(){return this.node.isSelected()},setSelected:function(a){BI.MultiLayerSelectTreeLastPlusGroupNode.superclass.setSelected.apply(this,arguments),this.node.setSelected(a)},doClick:function(){BI.MultiLayerSelectTreeLastPlusGroupNode.superclass.doClick.apply(this,arguments),this.node.setSelected(this.isSelected())},setOpened:function(a){BI.MultiLayerSelectTreeLastPlusGroupNode.superclass.setOpened.apply(this,arguments),this.node.setOpened(a)}}),BI.shortcut("bi.multilayer_select_tree_last_plus_group_node",BI.MultiLayerSelectTreeLastPlusGroupNode),BI.MultiLayerSelectTreeMidPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-multilayer-select-tree-mid-plus-group-node bi-list-item-active",layer:0,id:"",pId:"",readonly:!0,open:!1,height:25})},_init:function(){BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.node=BI.createWidget({type:"bi.select_tree_mid_plus_group_node",cls:"bi-list-item-none",stopPropagation:!0,logic:{dynamic:!0},id:b.id,pId:b.pId,open:b.open,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.node.on(BI.Controller.EVENT_CHANGE,function(b){a.setSelected(a.isSelected()),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.node),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.node.doRedMark.apply(this.node,arguments)},unRedMark:function(){this.node.unRedMark.apply(this.node,arguments)},isSelected:function(){return this.node.isSelected()},setSelected:function(a){BI.MultiLayerSelectTreeMidPlusGroupNode.superclass.setSelected.apply(this,arguments),this.node.setSelected(a)},doClick:function(){BI.MultiLayerSelectTreeMidPlusGroupNode.superclass.doClick.apply(this,arguments),this.node.setSelected(this.isSelected())},setOpened:function(a){BI.MultiLayerSelectTreeMidPlusGroupNode.superclass.setOpened.apply(this,arguments),this.node.setOpened(a)}}),BI.shortcut("bi.multilayer_select_tree_mid_plus_group_node",BI.MultiLayerSelectTreeMidPlusGroupNode),BI.MultiLayerSingleTreeCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSingleTreeCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multilayer-singletree-combo",isDefaultInit:!1,height:30,text:"",itemsCreator:BI.emptyFn,items:[]})},_init:function(){BI.MultiLayerSingleTreeCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget({type:"bi.single_tree_trigger",text:b.text,height:b.height,items:b.items}),this.popup=BI.createWidget({type:"bi.multilayer_single_tree_popup",isDefaultInit:b.isDefaultInit,items:b.items}),this.combo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup}}),this.combo.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.popup.on(BI.MultiLayerSingleTreePopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.combo.hideView(),a.fireEvent(BI.MultiLayerSingleTreeCombo.EVENT_CHANGE)})},setValue:function(a){a=BI.isArray(a)?a:[a],this.trigger.setValue(a),this.popup.setValue(a)},getValue:function(){return this.popup.getValue()},populate:function(a){this.combo.populate(a)}}),BI.MultiLayerSingleTreeCombo.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multilayer_single_tree_combo",BI.MultiLayerSingleTreeCombo),BI.MultiLayerSingleLevelTree=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSingleLevelTree.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multilayer-single-level-tree",isDefaultInit:!1,items:[],itemsCreator:BI.emptyFn})},_init:function(){BI.MultiLayerSingleLevelTree.superclass._init.apply(this,arguments),this.initTree(this.options.items)},_formatItems:function(a,b){var c=this;return BI.each(a,function(d,e){var f={};if(e.layer=b,BI.isKey(e.id)||(e.id=BI.UUID()),e.isParent===!0||BI.isNotEmptyArray(e.children)){switch(d){case 0:f.type="bi.multilayer_single_tree_first_plus_group_node";break;case a.length-1:f.type="bi.multilayer_single_tree_last_plus_group_node";break;default:f.type="bi.multilayer_single_tree_mid_plus_group_node"}BI.defaults(e,f),c._formatItems(e.children,b+1)}else{switch(d){case a.length-1:f.type="bi.multilayer_single_tree_last_tree_leaf_item";break;default:f.type="bi.multilayer_single_tree_mid_tree_leaf_item"}BI.defaults(e,f)}}),a},_assertId:function(a){BI.each(a,function(a,b){b.id=b.id||BI.UUID()})},initTree:function(a){var b=this,c=this.options;this.empty(),this._assertId(a),this.tree=BI.createWidget({type:"bi.custom_tree",element:this,expander:{isDefaultInit:c.isDefaultInit,el:{},popup:{type:"bi.custom_tree"}},items:this._formatItems(BI.Tree.transformToTreeFormat(a),0),itemsCreator:function(a,b){c.itemsCreator(a,function(a){b(BI.Tree.transformToTreeFormat(a),0)})},el:{type:"bi.button_tree",chooseType:BI.Selection.Single,layouts:[{type:"bi.vertical"}]}}),this.tree.on(BI.Controller.EVENT_CHANGE,function(a,c){b.fireEvent(BI.Controller.EVENT_CHANGE,arguments),a===BI.Events.CLICK&&b.fireEvent(BI.MultiLayerSingleLevelTree.EVENT_CHANGE,c)})},populate:function(a){this.tree.populate(this._formatItems(BI.Tree.transformToTreeFormat(a),0))},setValue:function(a){this.tree.setValue(a)},getValue:function(){return this.tree.getValue()},getAllLeaves:function(){return this.tree.getAllLeaves()},getNodeById:function(a){return this.tree.getNodeById(a)},getNodeByValue:function(a){return this.tree.getNodeByValue(a)}}),BI.MultiLayerSingleLevelTree.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multilayer_single_level_tree",BI.MultiLayerSingleLevelTree),BI.MultiLayerSingleTreePopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSingleTreePopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multilayer-singletree-popup",tipText:BI.i18nText("BI-No_Selected_Item"),isDefaultInit:!1,itemsCreator:BI.emptyFn,items:[]})},_init:function(){BI.MultiLayerSingleTreePopup.superclass._init.apply(this,arguments);var a=this,b=this.options;this.tree=BI.createWidget({type:"bi.multilayer_single_level_tree",isDefaultInit:b.isDefaultInit,items:b.items,itemsCreator:b.itemsCreator}),BI.createWidget({type:"bi.vertical",scrolly:!1,scrollable:!0,element:this,items:[this.tree]}),this.tree.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments); }),this.tree.on(BI.MultiLayerSingleLevelTree.EVENT_CHANGE,function(){a.fireEvent(BI.MultiLayerSingleTreePopup.EVENT_CHANGE)}),this.check()},getValue:function(){return this.tree.getValue()},setValue:function(a){a=BI.isArray(a)?a:[a],this.tree.setValue(a)},populate:function(a){BI.MultiLayerSingleTreePopup.superclass.populate.apply(this,arguments),this.tree.populate(a)}}),BI.MultiLayerSingleTreePopup.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multilayer_single_tree_popup",BI.MultiLayerSingleTreePopup),BI.MultiLayerSingleTreeFirstPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-multilayer-single-tree-first-plus-group-node bi-list-item",layer:0,id:"",pId:"",open:!1,height:25})},_init:function(){BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.node=BI.createWidget({type:"bi.first_plus_group_node",cls:"bi-list-item-none",logic:{dynamic:!0},id:b.id,pId:b.pId,open:b.open,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.node.on(BI.Controller.EVENT_CHANGE,function(b){b!==BI.Events.CLICK&&a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.node),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.node.doRedMark.apply(this.node,arguments)},unRedMark:function(){this.node.unRedMark.apply(this.node,arguments)},doClick:function(){BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass.doClick.apply(this,arguments),this.node.setSelected(this.isSelected())},setOpened:function(a){BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.node)&&this.node.setOpened(a)}}),BI.shortcut("bi.multilayer_single_tree_first_plus_group_node",BI.MultiLayerSingleTreeFirstPlusGroupNode),BI.MultiLayerSingleTreeLastPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-multilayer-single-tree-last-plus-group-node bi-list-item",layer:0,id:"",pId:"",open:!1,height:25})},_init:function(){BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.node=BI.createWidget({type:"bi.last_plus_group_node",cls:"bi-list-item-none",logic:{dynamic:!0},id:b.id,pId:b.pId,open:b.open,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.node.on(BI.Controller.EVENT_CHANGE,function(b){b!==BI.Events.CLICK&&a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.node),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.node.doRedMark.apply(this.node,arguments)},unRedMark:function(){this.node.unRedMark.apply(this.node,arguments)},doClick:function(){BI.MultiLayerSingleTreeLastPlusGroupNode.superclass.doClick.apply(this,arguments),this.node.setSelected(this.isSelected())},setOpened:function(a){BI.MultiLayerSingleTreeLastPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.node)&&this.node.setOpened(a)}}),BI.shortcut("bi.multilayer_single_tree_last_plus_group_node",BI.MultiLayerSingleTreeLastPlusGroupNode),BI.MultiLayerSingleTreeMidPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-multilayer-single-tree-mid-plus-group-node bi-list-item",layer:0,id:"",pId:"",open:!1,height:25})},_init:function(){BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.node=BI.createWidget({type:"bi.mid_plus_group_node",cls:"bi-list-item-none",logic:{dynamic:!0},id:b.id,pId:b.pId,open:b.open,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.node.on(BI.Controller.EVENT_CHANGE,function(b){b!==BI.Events.CLICK&&a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.node),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.node.doRedMark.apply(this.node,arguments)},unRedMark:function(){this.node.unRedMark.apply(this.node,arguments)},doClick:function(){BI.MultiLayerSingleTreeMidPlusGroupNode.superclass.doClick.apply(this,arguments),this.node.setSelected(this.isSelected())},setOpened:function(a){BI.MultiLayerSingleTreeMidPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.node)&&this.node.setOpened(a)}}),BI.shortcut("bi.multilayer_single_tree_mid_plus_group_node",BI.MultiLayerSingleTreeMidPlusGroupNode),BI.MultiLayerSingleTreeFirstTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-multilayer-single-tree-first-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},layer:0,id:"",pId:"",height:25})},_init:function(){BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.item=BI.createWidget({type:"bi.first_tree_leaf_item",cls:"bi-list-item-none",logic:{dynamic:!0},id:b.id,pId:b.pId,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.item.on(BI.Controller.EVENT_CHANGE,function(b){b!==BI.Events.CLICK&&a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.item),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.item.doRedMark.apply(this.item,arguments)},unRedMark:function(){this.item.unRedMark.apply(this.item,arguments)},doHighLight:function(){this.item.doHighLight.apply(this.item,arguments)},unHighLight:function(){this.item.unHighLight.apply(this.item,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass.doClick.apply(this,arguments),this.item.setSelected(this.isSelected())},setSelected:function(a){BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass.setSelected.apply(this,arguments),this.item.setSelected(a)}}),BI.shortcut("bi.multilayer_single_tree_first_tree_leaf_item",BI.MultiLayerSingleTreeFirstTreeLeafItem),BI.MultiLayerSingleTreeLastTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-multilayer-single-tree-last-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},layer:0,id:"",pId:"",height:25})},_init:function(){BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.item=BI.createWidget({type:"bi.last_tree_leaf_item",cls:"bi-list-item-none",logic:{dynamic:!0},id:b.id,pId:b.pId,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.item.on(BI.Controller.EVENT_CHANGE,function(b){b!==BI.Events.CLICK&&a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.item),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.item.doRedMark.apply(this.item,arguments)},unRedMark:function(){this.item.unRedMark.apply(this.item,arguments)},doHighLight:function(){this.item.doHighLight.apply(this.item,arguments)},unHighLight:function(){this.item.unHighLight.apply(this.item,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.MultiLayerSingleTreeLastTreeLeafItem.superclass.doClick.apply(this,arguments),this.item.setSelected(this.isSelected())},setSelected:function(a){BI.MultiLayerSingleTreeLastTreeLeafItem.superclass.setSelected.apply(this,arguments),this.item.setSelected(a)}}),BI.shortcut("bi.multilayer_single_tree_last_tree_leaf_item",BI.MultiLayerSingleTreeLastTreeLeafItem),BI.MultiLayerSingleTreeMidTreeLeafItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-multilayer-single-tree-mid-tree-leaf-item bi-list-item-active",logic:{dynamic:!1},layer:0,id:"",pId:"",height:25})},_init:function(){BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._init.apply(this,arguments);var a=this,b=this.options;this.item=BI.createWidget({type:"bi.mid_tree_leaf_item",cls:"bi-list-item-none",logic:{dynamic:!0},id:b.id,pId:b.pId,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.item.on(BI.Controller.EVENT_CHANGE,function(b){b!==BI.Events.CLICK&&a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)});var c=[];BI.count(0,b.layer,function(){c.push({type:"bi.layout",cls:"base-line-conn-background",width:13,height:b.height})}),c.push(this.item),BI.createWidget({type:"bi.td",element:this,columnSize:BI.makeArray(b.layer,13),items:[c]})},doRedMark:function(){this.item.doRedMark.apply(this.item,arguments)},unRedMark:function(){this.item.unRedMark.apply(this.item,arguments)},doHighLight:function(){this.item.doHighLight.apply(this.item,arguments)},unHighLight:function(){this.item.unHighLight.apply(this.item,arguments)},getId:function(){return this.options.id},getPId:function(){return this.options.pId},doClick:function(){BI.MultiLayerSingleTreeMidTreeLeafItem.superclass.doClick.apply(this,arguments),this.item.setSelected(this.isSelected())},setSelected:function(a){BI.MultiLayerSingleTreeMidTreeLeafItem.superclass.setSelected.apply(this,arguments),this.item.setSelected(a)}}),BI.shortcut("bi.multilayer_single_tree_mid_tree_leaf_item",BI.MultiLayerSingleTreeMidTreeLeafItem),BI.MultiSelectCheckPane=BI.inherit(BI.Widget,{constants:{height:25,lgap:10,tgap:5},_defaultConfig:function(){return BI.extend(BI.MultiSelectCheckPane.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-check-pane bi-background",items:[],itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,onClickContinueSelect:BI.emptyFn})},_init:function(){BI.MultiSelectCheckPane.superclass._init.apply(this,arguments);var a=this,b=this.options;this.storeValue={},this.display=BI.createWidget({type:"bi.display_selected_list",items:b.items,itemsCreator:function(c,d){return c=BI.extend(c||{},{selectedValues:a.storeValue.value}),a.storeValue.type===BI.Selection.Multi?void d({items:BI.map(a.storeValue.value,function(a,c){var d=b.valueFormatter(c)||c;return{text:d,value:c,title:d}})}):void b.itemsCreator(c,d)}}),this.continueSelect=BI.createWidget({type:"bi.text_button",text:BI.i18nText("BI-Continue_Select"),cls:"multi-select-check-selected bi-high-light"}),this.continueSelect.on(BI.TextButton.EVENT_CHANGE,function(){b.onClickContinueSelect()}),BI.createWidget({type:"bi.vtape",element:this,items:[{height:this.constants.height,el:{type:"bi.left",cls:"multi-select-continue-select",items:[{el:{type:"bi.label",text:BI.i18nText("BI-Selected_Data")},lgap:this.constants.lgap,tgap:this.constants.tgap},{el:this.continueSelect,lgap:this.constants.lgap,tgap:this.constants.tgap}]}},{height:"fill",el:this.display}]})},setValue:function(a){this.storeValue=a||{}},empty:function(){this.display.empty()},populate:function(){this.display.populate.apply(this.display,arguments)}}),BI.shortcut("bi.multi_select_check_pane",BI.MultiSelectCheckPane),BI.DisplaySelectedList=BI.inherit(BI.Pane,{constants:{height:25,lgap:10},_defaultConfig:function(){return BI.extend(BI.DisplaySelectedList.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-display-list",itemsCreator:BI.emptyFn,items:[]})},_init:function(){BI.DisplaySelectedList.superclass._init.apply(this,arguments);var a=this,b=this.options;this.hasNext=!1,this.button_group=BI.createWidget({type:"bi.list_pane",element:this,el:{type:"bi.loader",isDefaultInit:!1,logic:{dynamic:!0,scrolly:!0},items:this._createItems(b.items),chooseType:BI.ButtonGroup.CHOOSE_TYPE_MULTI,layouts:[{type:"bi.vertical",lgap:10}]},itemsCreator:function(c,d){b.itemsCreator(c,function(b){a.hasNext=!!b.hasNext,d(a._createItems(b.items))})},hasNext:function(){return a.hasNext}})},_createItems:function(a){return BI.createItems(a,{type:"bi.icon_text_item",cls:"cursor-default check-font display-list-item bi-tips",once:!0,invalid:!0,selected:!0,height:this.constants.height,logic:{dynamic:!0}})},empty:function(){this.button_group.empty()},populate:function(a){0===arguments.length?this.button_group.populate():this.button_group.populate(this._createItems(a))}}),BI.shortcut("bi.display_selected_list",BI.DisplaySelectedList),BI.MultiSelectInsertCombo=BI.inherit(BI.Single,{_defaultConfig:function(){return BI.extend(BI.MultiSelectInsertCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-insert-combo",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,height:28})},_init:function(){BI.MultiSelectInsertCombo.superclass._init.apply(this,arguments);var a=this,b=this.options,c=function(){BI.isKey(a._startValue)&&a.storeValue.value[a.storeValue.type===BI.Selection.All?"remove":"pushDistinct"](a._startValue),a.trigger.getSearcher().setState(a.storeValue),a.trigger.getCounter().setButtonChecked(a.storeValue)};this.storeValue={},this.requesting=!1,this.trigger=BI.createWidget({type:"bi.multi_select_trigger",height:b.height,masker:{offset:{left:1,top:1,right:2,bottom:33}},valueFormatter:b.valueFormatter,itemsCreator:function(c,d){b.itemsCreator(c,function(b){1===c.times&&BI.isNotNull(c.keywords)&&a.trigger.setValue(BI.deepClone(a.getValue())),d.apply(a,arguments)})}}),this.trigger.on(BI.MultiSelectTrigger.EVENT_START,function(){a._setStartValue(""),this.getSearcher().setValue(a.storeValue)}),this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP,function(){a._setStartValue("")}),this.trigger.on(BI.MultiSelectTrigger.EVENT_PAUSE,function(){var b=this.getSearcher().getKeyword();a._join({type:BI.Selection.Multi,value:[b]},function(){a.storeValue.type===BI.Selection.Multi&&a.storeValue.value.pushDistinct(b),a.combo.setValue(a.storeValue),a._setStartValue(b),c(),a.populate(),a._setStartValue("")})}),this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING,function(b){var d=BI.last(b);b=BI.initial(b||[]),b.length>0&&a._joinKeywords(b,function(){BI.isEndWithBlank(d)?(a.combo.setValue(a.storeValue),c(),a.combo.populate(),a._setStartValue("")):(a.combo.setValue(a.storeValue),c())})}),this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE,function(b,d){d instanceof BI.MultiSelectBar?a._joinAll(this.getValue(),function(){c()}):a._join(this.getValue(),function(){c()})}),this.trigger.on(BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW,function(){this.getCounter().setValue(a.storeValue)}),this.trigger.on(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK,function(){a.combo.isViewVisible()||a.combo.showView()}),this.combo=BI.createWidget({type:"bi.combo",toggle:!1,el:this.trigger,adjustLength:1,popup:{type:"bi.multi_select_popup_view",ref:function(){a.popup=this,a.trigger.setAdapter(this)},listeners:[{eventName:BI.MultiSelectPopupView.EVENT_CHANGE,action:function(){a.storeValue=this.getValue(),a._adjust(function(){c()})}},{eventName:BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM,action:function(){a._defaultState()}},{eventName:BI.MultiSelectPopupView.EVENT_CLICK_CLEAR,action:function(){a.setValue(),a._defaultState()}}],itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,onLoaded:function(){BI.nextTick(function(){a.combo.adjustWidth(),a.combo.adjustHeight(),a.trigger.getCounter().adjustView(),a.trigger.getSearcher().adjustView()})}},hideChecker:function(a){return 0===d.element.find(a.target).length}}),this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW,function(){this.setValue(a.storeValue),BI.nextTick(function(){a.populate()})}),this.wants2Quit=!1,this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW,function(){a.trigger.stopEditing(),a.requesting===!0?a.wants2Quit=!0:a.fireEvent(BI.MultiSelectInsertCombo.EVENT_CONFIRM)});var d=BI.createWidget({type:"bi.trigger_icon_button",width:b.height,height:b.height,cls:"multi-select-trigger-icon-button bi-border-left"});d.on(BI.TriggerIconButton.EVENT_CHANGE,function(){a.trigger.getCounter().hideView(),a.combo.isViewVisible()?a.combo.hideView():a.combo.showView()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.combo,left:0,right:0,top:0,bottom:0},{el:d,right:0,top:0,bottom:0}]})},_defaultState:function(){this.trigger.stopEditing(),this.combo.hideView()},_assertValue:function(a){a||(a={}),a.type||(a.type=BI.Selection.Multi),a.value||(a.value=[])},_makeMap:function(a){return BI.makeObject(a||[])},_joinKeywords:function(a,b){function c(c){var e=d._makeMap(c);BI.each(a,function(a,b){BI.isNotNull(e[b])&&d.storeValue.value[d.storeValue.type===BI.Selection.Multi?"pushDistinct":"remove"](b)}),d._adjust(b)}var d=this,e=this.options;this._assertValue(this.storeValue),this.requesting=!0,e.itemsCreator({type:BI.MultiSelectInsertCombo.REQ_GET_ALL_DATA,keywords:a},function(a){var b=BI.pluck(a.items,"value");c(b)})},_joinAll:function(a,b){var c=this,d=this.options;this._assertValue(a),this.requesting=!0,d.itemsCreator({type:BI.MultiSelectInsertCombo.REQ_GET_ALL_DATA,keywords:[this.trigger.getKey()]},function(d){var e=BI.pluck(d.items,"value");if(c.storeValue.type===a.type){var f=!1,g=c._makeMap(c.storeValue.value);return BI.each(e,function(a,b){BI.isNotNull(g[b])&&(f=!0,delete g[b])}),f&&(c.storeValue.value=BI.values(g)),void c._adjust(b)}var h=c._makeMap(c.storeValue.value),i=c._makeMap(a.value),j=[];BI.each(e,function(a,b){BI.isNotNull(h[e[a]])&&delete h[e[a]],BI.isNull(i[e[a]])&&j.push(b)}),c.storeValue.value=j.concat(BI.values(h)),c._adjust(b)})},_adjust:function(a){function b(){c.wants2Quit===!0&&(c.fireEvent(BI.MultiSelectInsertCombo.EVENT_CONFIRM),c.wants2Quit=!1),c.requesting=!1}var c=this;this.options;b(),a()},_join:function(a,b){var c=this;this.options;if(this._assertValue(a),this._assertValue(this.storeValue),this.storeValue.type===a.type){var d=this._makeMap(this.storeValue.value);BI.each(a.value,function(a,b){d[b]||(c.storeValue.value.push(b),d[b]=b)});var e=!1;return BI.each(a.assist,function(a,b){BI.isNotNull(d[b])&&(e=!0,delete d[b])}),e&&(this.storeValue.value=BI.values(d)),void c._adjust(b)}this._joinAll(a,b)},_setStartValue:function(a){this._startValue=a,this.popup.setStartValue(a)},setValue:function(a){this.storeValue=a||{},this._assertValue(this.storeValue),this.combo.setValue(this.storeValue)},getValue:function(){return BI.deepClone(this.storeValue)},populate:function(){this.combo.populate.apply(this.combo,arguments)}}),BI.extend(BI.MultiSelectInsertCombo,{REQ_GET_DATA_LENGTH:0,REQ_GET_ALL_DATA:-1}),BI.MultiSelectInsertCombo.EVENT_CONFIRM="EVENT_CONFIRM",BI.shortcut("bi.multi_select_insert_combo",BI.MultiSelectInsertCombo),BI.MultiSelectCombo=BI.inherit(BI.Single,{_defaultConfig:function(){return BI.extend(BI.MultiSelectCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-combo",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,height:28})},_init:function(){BI.MultiSelectCombo.superclass._init.apply(this,arguments);var a=this,b=this.options,c=function(){BI.isKey(a._startValue)&&a.storeValue.value[a.storeValue.type===BI.Selection.All?"remove":"pushDistinct"](a._startValue),a.trigger.getSearcher().setState(a.storeValue),a.trigger.getCounter().setButtonChecked(a.storeValue)};this.storeValue={},this.requesting=!1,this.trigger=BI.createWidget({type:"bi.multi_select_trigger",height:b.height,masker:{offset:{left:1,top:1,right:2,bottom:33}},valueFormatter:b.valueFormatter,itemsCreator:function(c,d){b.itemsCreator(c,function(b){1===c.times&&BI.isNotNull(c.keywords)&&a.trigger.setValue(BI.deepClone(a.getValue())),d.apply(a,arguments)})}}),this.trigger.on(BI.MultiSelectTrigger.EVENT_START,function(){a._setStartValue(""),this.getSearcher().setValue(a.storeValue)}),this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP,function(){a._setStartValue("")}),this.trigger.on(BI.MultiSelectTrigger.EVENT_PAUSE,function(){if(this.getSearcher().hasMatched()){var b=this.getSearcher().getKeyword();a._join({type:BI.Selection.Multi,value:[b]},function(){a.combo.setValue(a.storeValue),a._setStartValue(b),c(),a.populate(),a._setStartValue("")})}}),this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING,function(b){var d=BI.last(b);b=BI.initial(b||[]),b.length>0&&a._joinKeywords(b,function(){BI.isEndWithBlank(d)?(a.combo.setValue(a.storeValue),c(),a.combo.populate(),a._setStartValue("")):(a.combo.setValue(a.storeValue),c())})}),this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE,function(b,d){d instanceof BI.MultiSelectBar?a._joinAll(this.getValue(),function(){c()}):a._join(this.getValue(),function(){c()})}),this.trigger.on(BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW,function(){this.getCounter().setValue(a.storeValue)}),this.trigger.on(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK,function(){a.combo.isViewVisible()||a.combo.showView()}),this.combo=BI.createWidget({type:"bi.combo",toggle:!1,el:this.trigger,adjustLength:1,popup:{type:"bi.multi_select_popup_view",ref:function(){a.popup=this,a.trigger.setAdapter(this)},listeners:[{eventName:BI.MultiSelectPopupView.EVENT_CHANGE,action:function(){a.storeValue=this.getValue(),a._adjust(function(){c()})}},{eventName:BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM,action:function(){a._defaultState()}},{eventName:BI.MultiSelectPopupView.EVENT_CLICK_CLEAR,action:function(){a.setValue(),a._defaultState()}}],itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,onLoaded:function(){BI.nextTick(function(){a.combo.adjustWidth(),a.combo.adjustHeight(),a.trigger.getCounter().adjustView(),a.trigger.getSearcher().adjustView()})}},hideChecker:function(a){return 0===d.element.find(a.target).length}}),this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW,function(){this.setValue(a.storeValue),BI.nextTick(function(){a.populate()})}),this.wants2Quit=!1,this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW,function(){a.trigger.stopEditing(),a.requesting===!0?a.wants2Quit=!0:a.fireEvent(BI.MultiSelectCombo.EVENT_CONFIRM)});var d=BI.createWidget({type:"bi.trigger_icon_button",width:b.height,height:b.height,cls:"multi-select-trigger-icon-button bi-border-left"});d.on(BI.TriggerIconButton.EVENT_CHANGE,function(){a.trigger.getCounter().hideView(),a.combo.isViewVisible()?a.combo.hideView():a.combo.showView()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.combo,left:0,right:0,top:0,bottom:0},{el:d,right:0,top:0,bottom:0}]})},_defaultState:function(){this.trigger.stopEditing(),this.combo.hideView()},_assertValue:function(a){a||(a={}),a.type||(a.type=BI.Selection.Multi),a.value||(a.value=[])},_makeMap:function(a){return BI.makeObject(a||[])},_joinKeywords:function(a,b){function c(c){var e=d._makeMap(c);BI.each(a,function(a,b){BI.isNotNull(e[b])&&d.storeValue.value[d.storeValue.type===BI.Selection.Multi?"pushDistinct":"remove"](b)}),d._adjust(b)}var d=this,e=this.options;this._assertValue(this.storeValue),this.requesting=!0,e.itemsCreator({type:BI.MultiSelectCombo.REQ_GET_ALL_DATA,keywords:a},function(a){var b=BI.pluck(a.items,"value");c(b)})},_joinAll:function(a,b){var c=this,d=this.options;this._assertValue(a),this.requesting=!0,d.itemsCreator({type:BI.MultiSelectCombo.REQ_GET_ALL_DATA,keywords:[this.trigger.getKey()]},function(d){var e=BI.pluck(d.items,"value");if(c.storeValue.type===a.type){var f=!1,g=c._makeMap(c.storeValue.value);return BI.each(e,function(a,b){BI.isNotNull(g[b])&&(f=!0,delete g[b])}),f&&(c.storeValue.value=BI.values(g)),void c._adjust(b)}var h=c._makeMap(c.storeValue.value),i=c._makeMap(a.value),j=[];BI.each(e,function(a,b){BI.isNotNull(h[e[a]])&&delete h[e[a]],BI.isNull(i[e[a]])&&j.push(b)}),c.storeValue.value=j.concat(BI.values(h)),c._adjust(b)})},_adjust:function(a){function b(){c.storeValue.type===BI.Selection.All&&c.storeValue.value.length>=c._count?c.storeValue={type:BI.Selection.Multi,value:[]}:c.storeValue.type===BI.Selection.Multi&&c.storeValue.value.length>=c._count&&(c.storeValue={type:BI.Selection.All,value:[]}),c.wants2Quit===!0&&(c.fireEvent(BI.MultiSelectCombo.EVENT_CONFIRM),c.wants2Quit=!1),c.requesting=!1}var c=this,d=this.options;this._count?(b(),a()):d.itemsCreator({type:BI.MultiSelectCombo.REQ_GET_DATA_LENGTH},function(d){c._count=d.count,b(),a()})},_join:function(a,b){var c=this;this.options;if(this._assertValue(a),this._assertValue(this.storeValue),this.storeValue.type===a.type){var d=this._makeMap(this.storeValue.value);BI.each(a.value,function(a,b){d[b]||(c.storeValue.value.push(b),d[b]=b)});var e=!1;return BI.each(a.assist,function(a,b){BI.isNotNull(d[b])&&(e=!0,delete d[b])}),e&&(this.storeValue.value=BI.values(d)),void c._adjust(b)}this._joinAll(a,b)},_setStartValue:function(a){this._startValue=a,this.popup.setStartValue(a)},setValue:function(a){this.storeValue=a||{},this._assertValue(this.storeValue),this.combo.setValue(this.storeValue)},getValue:function(){return BI.deepClone(this.storeValue)},populate:function(){this._count=null,this.combo.populate.apply(this.combo,arguments)}}),BI.extend(BI.MultiSelectCombo,{REQ_GET_DATA_LENGTH:0,REQ_GET_ALL_DATA:-1}),BI.MultiSelectCombo.EVENT_CONFIRM="EVENT_CONFIRM",BI.shortcut("bi.multi_select_combo",BI.MultiSelectCombo),BI.MultiSelectLoader=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectLoader.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-loader",logic:{dynamic:!0},el:{height:400},valueFormatter:BI.emptyFn,itemsCreator:BI.emptyFn,onLoaded:BI.emptyFn})},_init:function(){BI.MultiSelectLoader.superclass._init.apply(this,arguments);var a=this,b=this.options,c=!1;this.button_group=BI.createWidget({type:"bi.select_list",element:this,logic:b.logic,el:BI.extend({onLoaded:b.onLoaded,el:{type:"bi.loader",isDefaultInit:!1,logic:{dynamic:!0,scrolly:!0},el:{chooseType:BI.ButtonGroup.CHOOSE_TYPE_MULTI,behaviors:{redmark:function(){return!0}},layouts:[{type:"bi.vertical"}]}}},b.el),itemsCreator:function(d,e){var f=a._startValue;a.storeValue&&(d=BI.extend(d||{},{selectedValues:BI.isKey(f)&&a.storeValue.type===BI.Selection.Multi?a.storeValue.value.concat(f):a.storeValue.value})),b.itemsCreator(d,function(g){c=g.hasNext;var h=[];if(1===d.times&&a.storeValue){var i=BI.map(a.storeValue.value,function(c,d){var e=b.valueFormatter(d)||d;return{text:e,value:d,title:e,selected:a.storeValue.type===BI.Selection.Multi}});if(BI.isKey(a._startValue)&&!a.storeValue.value.contains(a._startValue)){var j=b.valueFormatter(f)||f;i.unshift({text:j,value:f,title:j,selected:!0})}h=a._createItems(i)}e(h.concat(a._createItems(g.items)),g.keyword||""),1===d.times&&a.storeValue&&(BI.isKey(f)&&a.storeValue.value[a.storeValue.type===BI.Selection.All?"remove":"pushDistinct"](f),a.setValue(a.storeValue)),1===d.times&&a._scrollToTop()})},hasNext:function(){return c}}),this.button_group.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.button_group.on(BI.SelectList.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectLoader.EVENT_CHANGE,arguments)})},_createItems:function(a){return BI.createItems(a,{type:"bi.multi_select_item",logic:this.options.logic,height:25,selected:this.isAllSelected()})},_scrollToTop:function(){var a=this;BI.delay(function(){a.button_group.element.scrollTop(0)},30)},isAllSelected:function(){return this.button_group.isAllSelected()},_assertValue:function(a){a||(a={}),a.type||(a.type=BI.Selection.Multi),a.value||(a.value=[])},setStartValue:function(a){this._startValue=a},setValue:function(a){this.storeValue=a||{},this._assertValue(this.storeValue),this.button_group.setValue(this.storeValue)},getValue:function(){return this.button_group.getValue()},getAllButtons:function(){return this.button_group.getAllButtons()},empty:function(){this.button_group.empty()},populate:function(a){this.button_group.populate.apply(this.button_group,arguments)},resetHeight:function(a){this.button_group.resetHeight(a)},resetWidth:function(a){this.button_group.resetWidth(a)}}),BI.MultiSelectLoader.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multi_select_loader",BI.MultiSelectLoader),BI.MultiSelectPopupView=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectPopupView.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-popup-view",maxWidth:"auto",minWidth:135,maxHeight:400,valueFormatter:BI.emptyFn,itemsCreator:BI.emptyFn,onLoaded:BI.emptyFn})},_init:function(){BI.MultiSelectPopupView.superclass._init.apply(this,arguments);var a=this,b=this.options;this.loader=BI.createWidget({type:"bi.multi_select_loader",itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,onLoaded:b.onLoaded}),this.popupView=BI.createWidget({type:"bi.multi_popup_view",stopPropagation:!1,maxWidth:b.maxWidth,minWidth:b.minWidth,maxHeight:b.maxHeight,element:this,buttons:[BI.i18nText("BI-Basic_Clears"),BI.i18nText("BI-Basic_Sure")],el:this.loader}),this.popupView.on(BI.MultiPopupView.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectPopupView.EVENT_CHANGE)}),this.popupView.on(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON,function(b){switch(b){case 0:a.fireEvent(BI.MultiSelectPopupView.EVENT_CLICK_CLEAR);break;case 1:a.fireEvent(BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM)}})},isAllSelected:function(){return this.loader.isAllSelected()},setStartValue:function(a){this.loader.setStartValue(a)},setValue:function(a){this.popupView.setValue(a)},getValue:function(){return this.popupView.getValue()},populate:function(a){this.popupView.populate.apply(this.popupView,arguments)},resetHeight:function(a){this.popupView.resetHeight(a)},resetWidth:function(a){this.popupView.resetWidth(a)}}),BI.MultiSelectPopupView.EVENT_CHANGE="EVENT_CHANGE",BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM="EVENT_CLICK_CONFIRM",BI.MultiSelectPopupView.EVENT_CLICK_CLEAR="EVENT_CLICK_CLEAR",BI.shortcut("bi.multi_select_popup_view",BI.MultiSelectPopupView),BI.MultiSelectTrigger=BI.inherit(BI.Trigger,{constants:{height:14,rgap:4,lgap:4},_defaultConfig:function(){return BI.extend(BI.MultiSelectTrigger.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-trigger bi-border",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,searcher:{},switcher:{},adapter:null,masker:{}})},_init:function(){BI.MultiSelectTrigger.superclass._init.apply(this,arguments);var a=this,b=this.options;b.height&&this.setHeight(b.height-2),this.searcher=BI.createWidget(b.searcher,{type:"bi.multi_select_searcher",height:b.height,itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,popup:{},adapter:b.adapter,masker:b.masker}),this.searcher.on(BI.MultiSelectSearcher.EVENT_START,function(){a.fireEvent(BI.MultiSelectTrigger.EVENT_START)}),this.searcher.on(BI.MultiSelectSearcher.EVENT_PAUSE,function(){a.fireEvent(BI.MultiSelectTrigger.EVENT_PAUSE)}),this.searcher.on(BI.MultiSelectSearcher.EVENT_SEARCHING,function(){a.fireEvent(BI.MultiSelectTrigger.EVENT_SEARCHING,arguments)}),this.searcher.on(BI.MultiSelectSearcher.EVENT_STOP,function(){a.fireEvent(BI.MultiSelectTrigger.EVENT_STOP)}),this.searcher.on(BI.MultiSelectSearcher.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectTrigger.EVENT_CHANGE,arguments)}),this.numberCounter=BI.createWidget(b.switcher,{type:"bi.multi_select_check_selected_switcher",valueFormatter:b.valueFormatter,itemsCreator:b.itemsCreator,adapter:b.adapter,masker:b.masker}),this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE,function(){a.fireEvent(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK); }),this.numberCounter.on(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW,function(){a.fireEvent(BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW)});var c=BI.createWidget({type:"bi.right_vertical_adapt",hgap:4,items:[{el:this.numberCounter}]}),d=BI.createWidget({type:"bi.htape",element:this,items:[{el:this.searcher,width:"fill"},{el:c,width:0},{el:BI.createWidget(),width:30}]});this.numberCounter.on(BI.Events.VIEW,function(b){BI.nextTick(function(){d.attr("items")[1].width=b===!0?a.numberCounter.element.outerWidth()+8:0,d.resize()})}),this.element.click(function(b){a.element.__isMouseInBounds__(b)&&!a.numberCounter.element.__isMouseInBounds__(b)&&a.numberCounter.hideView()})},getCounter:function(){return this.numberCounter},getSearcher:function(){return this.searcher},stopEditing:function(){this.searcher.stopSearch(),this.numberCounter.hideView()},setAdapter:function(a){this.searcher.setAdapter(a),this.numberCounter.setAdapter(a)},setValue:function(a){this.searcher.setValue(a),this.numberCounter.setValue(a)},getKey:function(){return this.searcher.getKey()},getValue:function(){return this.searcher.getValue()}}),BI.MultiSelectTrigger.EVENT_TRIGGER_CLICK="EVENT_TRIGGER_CLICK",BI.MultiSelectTrigger.EVENT_COUNTER_CLICK="EVENT_COUNTER_CLICK",BI.MultiSelectTrigger.EVENT_CHANGE="EVENT_CHANGE",BI.MultiSelectTrigger.EVENT_START="EVENT_START",BI.MultiSelectTrigger.EVENT_STOP="EVENT_STOP",BI.MultiSelectTrigger.EVENT_PAUSE="EVENT_PAUSE",BI.MultiSelectTrigger.EVENT_SEARCHING="EVENT_SEARCHING",BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW="EVENT_BEFORE_COUNTER_POPUPVIEW",BI.shortcut("bi.multi_select_trigger",BI.MultiSelectTrigger),BI.MultiSelectSearchLoader=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectSearchLoader.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-search-loader",itemsCreator:BI.emptyFn,keywordGetter:BI.emptyFn,valueFormatter:BI.emptyFn})},_init:function(){BI.MultiSelectSearchLoader.superclass._init.apply(this,arguments);var a=this,b=this.options,c=!1;this.button_group=BI.createWidget({type:"bi.select_list",element:this,logic:{dynamic:!1},el:{tipText:BI.i18nText("BI-No_Select"),el:{type:"bi.loader",isDefaultInit:!1,logic:{dynamic:!0,scrolly:!0},el:{chooseType:BI.ButtonGroup.CHOOSE_TYPE_MULTI,behaviors:{redmark:function(){return!0}},layouts:[{type:"bi.vertical"}]}}},itemsCreator:function(d,e){a.storeValue&&(d=BI.extend(d||{},{selectedValues:a.storeValue.value})),b.itemsCreator(d,function(f){var g=f.keyword=b.keywordGetter();c=f.hasNext;var h=[];if(1===d.times&&a.storeValue){var i=a._filterValues(a.storeValue);h=a._createItems(i)}e(h.concat(a._createItems(f.items)),g),1===d.times&&a.storeValue&&a.setValue(a.storeValue)})},hasNext:function(){return c}}),this.button_group.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.button_group.on(BI.SelectList.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectSearchLoader.EVENT_CHANGE,arguments)})},_createItems:function(a){return BI.createItems(a,{type:"bi.multi_select_item",logic:{dynamic:!1},height:25,selected:this.isAllSelected()})},isAllSelected:function(){return this.button_group.isAllSelected()},_filterValues:function(a){var b=this.options,c=b.keywordGetter(),d=BI.deepClone(a.value)||[],e=BI.map(d,function(a,c){return{text:b.valueFormatter(c)||c,value:c}});if(BI.isKey(c)){var f=BI.Func.getSearchResult(e,c);d=f.matched.concat(f.finded)}return BI.map(d,function(b,c){return{text:c.text,title:c.text,value:c.value,selected:a.type===BI.Selection.All}})},setValue:function(a){this.storeValue=BI.deepClone(a),this.button_group.setValue(a)},getValue:function(){return this.button_group.getValue()},getAllButtons:function(){return this.button_group.getAllButtons()},empty:function(){this.button_group.empty()},populate:function(a){this.button_group.populate.apply(this.button_group,arguments)},resetHeight:function(a){this.button_group.resetHeight(a)},resetWidth:function(a){this.button_group.resetWidth(a)}}),BI.MultiSelectSearchLoader.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multi_select_search_loader",BI.MultiSelectSearchLoader),BI.MultiSelectSearchPane=BI.inherit(BI.Widget,{constants:{height:25,lgap:10,tgap:5},_defaultConfig:function(){return BI.extend(BI.MultiSelectSearchPane.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-search-pane bi-card",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,keywordGetter:BI.emptyFn})},_init:function(){BI.MultiSelectSearchPane.superclass._init.apply(this,arguments);var a=this,b=this.options;this.tooltipClick=BI.createWidget({type:"bi.label",invisible:!0,text:BI.i18nText("BI-Click_Blank_To_Select"),cls:"multi-select-toolbar",height:this.constants.height}),this.loader=BI.createWidget({type:"bi.multi_select_search_loader",keywordGetter:b.keywordGetter,valueFormatter:b.valueFormatter,itemsCreator:function(c,d){b.itemsCreator.apply(a,[c,function(c){d(c),a.setKeyword(b.keywordGetter())}])}}),this.loader.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.resizer=BI.createWidget({type:"bi.vtape",element:this,items:[{el:this.tooltipClick,height:0},{el:this.loader}]}),this.tooltipClick.setVisible(!1)},setKeyword:function(a){var b,c=this.loader.getAllButtons().length>0&&(b=this.loader.getAllButtons()[0])&&a===b.getValue();c!==this.tooltipClick.isVisible()&&(this.tooltipClick.setVisible(c),this.resizer.attr("items")[0].height=c?this.constants.height:0,this.resizer.resize())},isAllSelected:function(){return this.loader.isAllSelected()},hasMatched:function(){return this.tooltipClick.isVisible()},setValue:function(a){this.loader.setValue(a)},getValue:function(){return this.loader.getValue()},empty:function(){this.loader.empty()},populate:function(a){this.loader.populate.apply(this.loader,arguments)}}),BI.MultiSelectSearchPane.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multi_select_search_pane",BI.MultiSelectSearchPane),BI.MultiSelectCheckSelectedButton=BI.inherit(BI.Single,{_const:{checkSelected:BI.i18nText("BI-Check_Selected")},_defaultConfig:function(){return BI.extend(BI.MultiSelectCheckSelectedButton.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-check-selected-button bi-high-light",itemsCreator:BI.emptyFn})},_init:function(){BI.MultiSelectCheckSelectedButton.superclass._init.apply(this,arguments);var a=this;this.numberCounter=BI.createWidget({type:"bi.text_button",element:this,hgap:4,text:"0",textAlign:"center",textHeight:15}),this.numberCounter.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.numberCounter.on(BI.TextButton.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectCheckSelectedButton.EVENT_CHANGE,arguments)}),this.numberCounter.element.hover(function(){a.numberCounter.setTag(a.numberCounter.getText()),a.numberCounter.setText(a._const.checkSelected)},function(){a.numberCounter.setText(a.numberCounter.getTag())}),this.setVisible(!1)},setValue:function(a){var b=this,c=this.options;return a||(a={}),a.type||(a.type=BI.Selection.Multi),a.value||(a.value=[]),a.type===BI.Selection.All?void c.itemsCreator({type:BI.MultiSelectCombo.REQ_GET_DATA_LENGTH},function(c){var d=c.count-a.value.length;BI.nextTick(function(){b.numberCounter.setText(d),b.setVisible(d>0)})}):void BI.nextTick(function(){b.numberCounter.setText(a.value.length),b.setVisible(a.value.length>0)})},getValue:function(){}}),BI.MultiSelectCheckSelectedButton.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multi_select_check_selected_button",BI.MultiSelectCheckSelectedButton),BI.MultiSelectEditor=BI.inherit(BI.Widget,{_const:{checkSelected:BI.i18nText("BI-Check_Selected")},_defaultConfig:function(){return BI.extend(BI.MultiSelectEditor.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-editor",el:{}})},_init:function(){BI.MultiSelectEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget(b.el,{type:"bi.state_editor",element:this,height:b.height,watermark:BI.i18nText("BI-Basic_Search"),allowBlank:!0}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.StateEditor.EVENT_PAUSE,function(){a.fireEvent(BI.MultiSelectEditor.EVENT_PAUSE)}),this.editor.on(BI.StateEditor.EVENT_CLICK_LABEL,function(){})},focus:function(){this.editor.focus()},blur:function(){this.editor.blur()},setState:function(a){this.editor.setState(a)},setValue:function(a){this.editor.setValue(a)},getValue:function(){var a=this.editor.getState();return BI.isArray(a)&&a.length>0?a[a.length-1]:""},getKeywords:function(){var a=this.editor.getLastValidValue(),b=a.match(/[\S]+/g);return BI.isEndWithBlank(a)?b.concat([" "]):b},populate:function(a){}}),BI.MultiSelectEditor.EVENT_PAUSE="MultiSelectEditor.EVENT_PAUSE",BI.shortcut("bi.multi_select_editor",BI.MultiSelectEditor),BI.MultiSelectSearcher=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectSearcher.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-searcher",itemsCreator:BI.emptyFn,el:{},popup:{},valueFormatter:BI.emptyFn,adapter:null,masker:{}})},_init:function(){BI.MultiSelectSearcher.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget(b.el,{type:"bi.multi_select_editor",height:b.height}),this.searcher=BI.createWidget({type:"bi.searcher",element:this,height:b.height,isAutoSearch:!1,isAutoSync:!1,onSearch:function(a,b){b()},el:this.editor,popup:BI.extend({type:"bi.multi_select_search_pane",valueFormatter:b.valueFormatter,keywordGetter:function(){return a.editor.getValue()},itemsCreator:function(c,d){c.keyword=a.editor.getValue(),this.setKeyword(c.keyword),b.itemsCreator(c,d)}},b.popup),adapter:b.adapter,masker:b.masker}),this.searcher.on(BI.Searcher.EVENT_START,function(){a.fireEvent(BI.MultiSelectSearcher.EVENT_START)}),this.searcher.on(BI.Searcher.EVENT_PAUSE,function(){this.hasMatched(),a.fireEvent(BI.MultiSelectSearcher.EVENT_PAUSE)}),this.searcher.on(BI.Searcher.EVENT_STOP,function(){a.fireEvent(BI.MultiSelectSearcher.EVENT_STOP)}),this.searcher.on(BI.Searcher.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectSearcher.EVENT_CHANGE,arguments)}),this.searcher.on(BI.Searcher.EVENT_SEARCHING,function(){var b=this.getKeywords();a.fireEvent(BI.MultiSelectSearcher.EVENT_SEARCHING,b)})},adjustView:function(){this.searcher.adjustView()},isSearching:function(){return this.searcher.isSearching()},stopSearch:function(){this.searcher.stopSearch()},getKeyword:function(){return this.editor.getValue()},hasMatched:function(){return this.searcher.hasMatched()},hasChecked:function(){return this.searcher.getView()&&this.searcher.getView().hasChecked()},setAdapter:function(a){this.searcher.setAdapter(a)},setState:function(a){var b=this.options;if(a||(a={}),a.value||(a.value=[]),a.type===BI.Selection.All)if(0===a.value.length)this.editor.setState(BI.Selection.All);else if(BI.size(a.assist)<=20){var c="";BI.each(a.assist,function(a,d){c+=0===a?""+(b.valueFormatter(d+"")||d):","+(b.valueFormatter(d+"")||d)}),this.editor.setState(c)}else this.editor.setState(BI.Selection.Multi);else if(0===a.value.length)this.editor.setState(BI.Selection.None);else if(BI.size(a.value)<=20){var c="";BI.each(a.value,function(a,d){c+=0===a?""+(b.valueFormatter(d+"")||d):","+(b.valueFormatter(d+"")||d)}),this.editor.setState(c)}else this.editor.setState(BI.Selection.Multi)},setValue:function(a){this.setState(a),this.searcher.setValue(a)},getKey:function(){return this.editor.getValue()},getValue:function(){return this.searcher.getValue()},populate:function(a){this.searcher.populate.apply(this.searcher,arguments)}}),BI.MultiSelectSearcher.EVENT_BEFORE_POPUPVIEW="EVENT_BEFORE_POPUPVIEW",BI.MultiSelectSearcher.EVENT_CHANGE="EVENT_CHANGE",BI.MultiSelectSearcher.EVENT_START="EVENT_START",BI.MultiSelectSearcher.EVENT_STOP="EVENT_STOP",BI.MultiSelectSearcher.EVENT_PAUSE="EVENT_PAUSE",BI.MultiSelectSearcher.EVENT_SEARCHING="EVENT_SEARCHING",BI.shortcut("bi.multi_select_searcher",BI.MultiSelectSearcher),BI.MultiSelectCheckSelectedSwitcher=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectCheckSelectedSwitcher.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-check-selected-switcher",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,el:{},popup:{},adapter:null,masker:{}})},_init:function(){BI.MultiSelectCheckSelectedSwitcher.superclass._init.apply(this,arguments);var a=this,b=this.options;this.button=BI.createWidget(b.el,{type:"bi.multi_select_check_selected_button",itemsCreator:b.itemsCreator}),this.button.on(BI.Events.VIEW,function(){a.fireEvent(BI.Events.VIEW,arguments)}),this.switcher=BI.createWidget({type:"bi.switcher",toggle:!1,element:this,el:this.button,popup:BI.extend({type:"bi.multi_select_check_pane",valueFormatter:b.valueFormatter,itemsCreator:b.itemsCreator,onClickContinueSelect:function(){a.switcher.hideView()}},b.popup),adapter:b.adapter,masker:b.masker}),this.switcher.on(BI.Switcher.EVENT_TRIGGER_CHANGE,function(){a.fireEvent(BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE)}),this.switcher.on(BI.Switcher.EVENT_BEFORE_POPUPVIEW,function(){a.fireEvent(BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW)}),this.switcher.on(BI.Switcher.EVENT_AFTER_POPUPVIEW,function(){var a=this;BI.nextTick(function(){a.populate()})}),this.switcher.element.click(function(a){a.stopPropagation()})},adjustView:function(){this.switcher.adjustView()},hideView:function(){this.switcher.empty(),this.switcher.hideView()},setAdapter:function(a){this.switcher.setAdapter(a)},setValue:function(a){this.switcher.setValue(a)},setButtonChecked:function(a){this.button.setValue(a)},getValue:function(){},populate:function(a){this.switcher.populate.apply(this.switcher,arguments)}}),BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE="MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE",BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW="MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW",BI.shortcut("bi.multi_select_check_selected_switcher",BI.MultiSelectCheckSelectedSwitcher),BI.MultiSelectInsertList=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectInsertList.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-insert-list",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn})},_init:function(){BI.MultiSelectInsertList.superclass._init.apply(this,arguments);var a=this,b=this.options;this.storeValue={};var c=function(){BI.isKey(a._startValue)&&a.storeValue.value[a.storeValue.type===BI.Selection.All?"remove":"pushDistinct"](a._startValue)};this.adapter=BI.createWidget({type:"bi.multi_select_loader",cls:"popup-multi-select-list bi-border-left bi-border-right bi-border-bottom",itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,logic:{dynamic:!1},el:{}}),this.adapter.on(BI.MultiSelectLoader.EVENT_CHANGE,function(){a.storeValue=this.getValue(),c(),a.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE)}),this.searcherPane=BI.createWidget({type:"bi.multi_select_search_pane",cls:"bi-border-left bi-border-right bi-border-bottom",valueFormatter:b.valueFormatter,keywordGetter:function(){return a.trigger.getKeyword()},itemsCreator:function(c,d){c.keyword=a.trigger.getKeyword(),this.setKeyword(c.keyword),b.itemsCreator(c,d)}}),this.searcherPane.setVisible(!1),this.trigger=BI.createWidget({type:"bi.searcher",isAutoSearch:!1,isAutoSync:!1,onSearch:function(a,b){b()},adapter:this.adapter,popup:this.searcherPane,height:200,masker:!1,listeners:[{eventName:BI.Searcher.EVENT_START,action:function(){a._showSearcherPane(),a._setStartValue(""),this.setValue(BI.deepClone(a.storeValue))}},{eventName:BI.Searcher.EVENT_STOP,action:function(){a._showAdapter(),a._setStartValue(""),a.adapter.setValue(a.storeValue),a.adapter.populate()}},{eventName:BI.Searcher.EVENT_PAUSE,action:function(){var b=this.getKeyword();this.hasMatched()?a._join({type:BI.Selection.Multi,value:[b]},function(){a.storeValue.type===BI.Selection.Multi&&a.storeValue.value.pushDistinct(b),a._showAdapter(),a.adapter.setValue(a.storeValue),a._setStartValue(b),c(),a.adapter.populate(),a._setStartValue(""),a.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE)}):(a.storeValue.type===BI.Selection.Multi&&a.storeValue.value.pushDistinct(b),a._showAdapter(),a.adapter.setValue(a.storeValue),a.adapter.populate(),a.storeValue.type===BI.Selection.Multi&&a.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE))}},{eventName:BI.Searcher.EVENT_SEARCHING,action:function(){var b=this.getKeyword(),d=BI.last(b);b=BI.initial(b||[]),b.length>0&&a._joinKeywords(b,function(){BI.isEndWithBlank(d)?(a.adapter.setValue(a.storeValue),c(),a.adapter.populate(),a._setStartValue("")):(a.adapter.setValue(a.storeValue),c())})}},{eventName:BI.Searcher.EVENT_CHANGE,action:function(b,d){d instanceof BI.MultiSelectBar?a._joinAll(this.getValue(),function(){c(),a.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE)}):a._join(this.getValue(),function(){c(),a.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE)})}}]}),BI.createWidget({type:"bi.vtape",element:this,items:[{el:this.trigger,height:24},{el:this.adapter,height:"fill"}]}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.searcherPane,top:30,bottom:0,left:0,right:0}]})},_showAdapter:function(){this.adapter.setVisible(!0),this.searcherPane.setVisible(!1)},_showSearcherPane:function(){this.searcherPane.setVisible(!0),this.adapter.setVisible(!1)},_defaultState:function(){this.trigger.stopEditing()},_assertValue:function(a){a||(a={}),a.type||(a.type=BI.Selection.Multi),a.value||(a.value=[])},_makeMap:function(a){return BI.makeObject(a||[])},_joinKeywords:function(a,b){function c(c){var e=d._makeMap(c);BI.each(a,function(a,b){BI.isNotNull(e[b])&&d.storeValue.value[d.storeValue.type===BI.Selection.Multi?"pushDistinct":"remove"](b)}),b()}var d=this,e=this.options;this._assertValue(this.storeValue),this._allData?c(this._allData):e.itemsCreator({type:BI.MultiSelectInsertList.REQ_GET_ALL_DATA},function(a){d._allData=BI.pluck(a.items,"value"),c(d._allData)})},_joinAll:function(a,b){var c=this,d=this.options;this._assertValue(a),d.itemsCreator({type:BI.MultiSelectInsertList.REQ_GET_ALL_DATA,keyword:c.trigger.getKeyword()},function(d){var e=BI.pluck(d.items,"value");if(c.storeValue.type===a.type){var f=!1,g=c._makeMap(c.storeValue.value);return BI.each(e,function(a,b){BI.isNotNull(g[b])&&(f=!0,delete g[b])}),f&&(c.storeValue.value=BI.values(g)),void b()}var h=c._makeMap(c.storeValue.value),i=c._makeMap(a.value),j=[];BI.each(e,function(a,b){BI.isNotNull(h[e[a]])&&delete h[e[a]],BI.isNull(i[e[a]])&&j.push(b)}),c.storeValue.value=j.concat(BI.values(h)),b()})},_join:function(a,b){var c=this;this.options;if(this._assertValue(a),this._assertValue(this.storeValue),this.storeValue.type===a.type){var d=this._makeMap(this.storeValue.value);BI.each(a.value,function(a,b){d[b]||(c.storeValue.value.push(b),d[b]=b)});var e=!1;return BI.each(a.assist,function(a,b){BI.isNotNull(d[b])&&(e=!0,delete d[b])}),e&&(this.storeValue.value=BI.values(d)),void b()}this._joinAll(a,b)},_setStartValue:function(a){this._startValue=a,this.adapter.setStartValue(a)},isAllSelected:function(){return this.adapter.isAllSelected()},resize:function(){},setValue:function(a){this.storeValue=a||{},this._assertValue(this.storeValue),this.adapter.setValue(this.storeValue),this.trigger.setValue(this.storeValue)},getValue:function(){return BI.deepClone(this.storeValue)},populate:function(){this._count=null,this._allData=null,this.adapter.populate.apply(this.adapter,arguments),this.trigger.populate.apply(this.trigger,arguments)}}),BI.extend(BI.MultiSelectInsertList,{REQ_GET_DATA_LENGTH:0,REQ_GET_ALL_DATA:-1}),BI.MultiSelectInsertList.EVENT_CHANGE="BI.MultiSelectInsertList.EVENT_CHANGE",BI.shortcut("bi.multi_select_insert_list",BI.MultiSelectInsertList),BI.MultiSelectList=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectList.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-list",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn})},_init:function(){BI.MultiSelectList.superclass._init.apply(this,arguments);var a=this,b=this.options;this.storeValue={};var c=function(){BI.isKey(a._startValue)&&a.storeValue.value[a.storeValue.type===BI.Selection.All?"remove":"pushDistinct"](a._startValue)};this.adapter=BI.createWidget({type:"bi.multi_select_loader",cls:"popup-multi-select-list bi-border-left bi-border-right bi-border-bottom",itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,logic:{dynamic:!1},el:{}}),this.adapter.on(BI.MultiSelectLoader.EVENT_CHANGE,function(){a.storeValue=this.getValue(),a._adjust(function(){c(),a.fireEvent(BI.MultiSelectList.EVENT_CHANGE)})}),this.searcherPane=BI.createWidget({type:"bi.multi_select_search_pane",cls:"bi-border-left bi-border-right bi-border-bottom",valueFormatter:b.valueFormatter,keywordGetter:function(){return a.trigger.getKeyword()},itemsCreator:function(c,d){c.keyword=a.trigger.getKeyword(),this.setKeyword(c.keyword),b.itemsCreator(c,d)}}),this.searcherPane.setVisible(!1),this.trigger=BI.createWidget({type:"bi.searcher",isAutoSearch:!1,isAutoSync:!1,onSearch:function(a,b){b()},adapter:this.adapter,popup:this.searcherPane,height:200,masker:!1,listeners:[{eventName:BI.Searcher.EVENT_START,action:function(){a._showSearcherPane(),a._setStartValue(""),this.setValue(BI.deepClone(a.storeValue))}},{eventName:BI.Searcher.EVENT_STOP,action:function(){a._showAdapter(),a._setStartValue(""),a.adapter.setValue(a.storeValue),a.adapter.populate()}},{eventName:BI.Searcher.EVENT_PAUSE,action:function(){var b=this.getKeyword();this.hasMatched()&&a._join({type:BI.Selection.Multi,value:[b]},function(){a._showAdapter(),a.adapter.setValue(a.storeValue),a._setStartValue(b),c(),a.adapter.populate(),a._setStartValue(""),a.fireEvent(BI.MultiSelectList.EVENT_CHANGE)})}},{eventName:BI.Searcher.EVENT_SEARCHING,action:function(){var b=this.getKeyword(),d=BI.last(b);b=BI.initial(b||[]),b.length>0&&a._joinKeywords(b,function(){BI.isEndWithBlank(d)?(a.adapter.setValue(a.storeValue),c(),a.adapter.populate(),a._setStartValue("")):(a.adapter.setValue(a.storeValue),c())})}},{eventName:BI.Searcher.EVENT_CHANGE,action:function(b,d){d instanceof BI.MultiSelectBar?a._joinAll(this.getValue(),function(){c(),a.fireEvent(BI.MultiSelectList.EVENT_CHANGE)}):a._join(this.getValue(),function(){c(),a.fireEvent(BI.MultiSelectList.EVENT_CHANGE)})}}]}),BI.createWidget({type:"bi.vtape",element:this,items:[{el:this.trigger,height:24},{el:this.adapter,height:"fill"}]}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.searcherPane,top:30,bottom:0,left:0,right:0}]})},_showAdapter:function(){this.adapter.setVisible(!0),this.searcherPane.setVisible(!1)},_showSearcherPane:function(){this.searcherPane.setVisible(!0),this.adapter.setVisible(!1)},_defaultState:function(){this.trigger.stopEditing()},_assertValue:function(a){a||(a={}),a.type||(a.type=BI.Selection.Multi),a.value||(a.value=[])},_makeMap:function(a){return BI.makeObject(a||[])},_joinKeywords:function(a,b){function c(c){var e=d._makeMap(c);BI.each(a,function(a,b){BI.isNotNull(e[b])&&d.storeValue.value[d.storeValue.type===BI.Selection.Multi?"pushDistinct":"remove"](b)}),d._adjust(b)}var d=this,e=this.options;this._assertValue(this.storeValue),this._allData?c(this._allData):e.itemsCreator({type:BI.MultiSelectList.REQ_GET_ALL_DATA},function(a){d._allData=BI.pluck(a.items,"value"),c(d._allData)})},_joinAll:function(a,b){var c=this,d=this.options;this._assertValue(a),d.itemsCreator({type:BI.MultiSelectList.REQ_GET_ALL_DATA,keyword:c.trigger.getKeyword()},function(d){var e=BI.pluck(d.items,"value");if(c.storeValue.type===a.type){var f=!1,g=c._makeMap(c.storeValue.value);return BI.each(e,function(a,b){BI.isNotNull(g[b])&&(f=!0,delete g[b])}),f&&(c.storeValue.value=BI.values(g)),void c._adjust(b)}var h=c._makeMap(c.storeValue.value),i=c._makeMap(a.value),j=[];BI.each(e,function(a,b){BI.isNotNull(h[e[a]])&&delete h[e[a]],BI.isNull(i[e[a]])&&j.push(b)}),c.storeValue.value=j.concat(BI.values(h)),c._adjust(b)})},_adjust:function(a){function b(){c.storeValue.type===BI.Selection.All&&c.storeValue.value.length>=c._count?c.storeValue={type:BI.Selection.Multi,value:[]}:c.storeValue.type===BI.Selection.Multi&&c.storeValue.value.length>=c._count&&(c.storeValue={type:BI.Selection.All,value:[]})}var c=this,d=this.options;this._count?(b(),a()):d.itemsCreator({type:BI.MultiSelectList.REQ_GET_DATA_LENGTH},function(d){c._count=d.count,b(),a()})},_join:function(a,b){var c=this;this.options;if(this._assertValue(a),this._assertValue(this.storeValue),this.storeValue.type===a.type){var d=this._makeMap(this.storeValue.value);BI.each(a.value,function(a,b){d[b]||(c.storeValue.value.push(b),d[b]=b)});var e=!1;return BI.each(a.assist,function(a,b){BI.isNotNull(d[b])&&(e=!0,delete d[b])}),e&&(this.storeValue.value=BI.values(d)),void c._adjust(b)}this._joinAll(a,b)},_setStartValue:function(a){this._startValue=a,this.adapter.setStartValue(a)},isAllSelected:function(){return this.adapter.isAllSelected()},resize:function(){},setValue:function(a){this.storeValue=a||{},this._assertValue(this.storeValue),this.adapter.setValue(this.storeValue),this.trigger.setValue(this.storeValue)},getValue:function(){return BI.deepClone(this.storeValue)},populate:function(){this._count=null,this._allData=null,this.adapter.populate.apply(this.adapter,arguments),this.trigger.populate.apply(this.trigger,arguments)}}),BI.extend(BI.MultiSelectList,{REQ_GET_DATA_LENGTH:0,REQ_GET_ALL_DATA:-1}),BI.MultiSelectList.EVENT_CHANGE="BI.MultiSelectList.EVENT_CHANGE",BI.shortcut("bi.multi_select_list",BI.MultiSelectList),BI.MultiSelectTree=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectTree.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-tree",itemsCreator:BI.emptyFn})},_init:function(){BI.MultiSelectTree.superclass._init.apply(this,arguments);var a=this,b=this.options;this.storeValue={value:{}},this.adapter=BI.createWidget({type:"bi.multi_select_tree_popup",itemsCreator:b.itemsCreator}),this.adapter.on(BI.MultiSelectTreePopup.EVENT_CHANGE,function(){a.searcher.isSearching()?a.storeValue={value:a.searcherPane.getValue()}:a.storeValue={value:a.adapter.getValue()},a.setSelectedValue(a.storeValue.value),a.fireEvent(BI.MultiSelectTree.EVENT_CHANGE)}),this.searcherPane=BI.createWidget({type:"bi.multi_tree_search_pane",cls:"bi-border-left bi-border-right bi-border-bottom",keywordGetter:function(){return a.searcher.getKeyword()},itemsCreator:function(c,d){c.keyword=a.searcher.getKeyword(),b.itemsCreator(c,d)}}),this.searcherPane.setVisible(!1),this.searcher=BI.createWidget({type:"bi.searcher",isAutoSearch:!1,isAutoSync:!1,onSearch:function(b,c){c({keyword:a.searcher.getKeyword()})},adapter:this.adapter,popup:this.searcherPane,masker:!1,listeners:[{eventName:BI.Searcher.EVENT_START,action:function(){a._showSearcherPane()}},{eventName:BI.Searcher.EVENT_STOP,action:function(){a._showAdapter(),BI.nextTick(function(){a.adapter.populate()})}},{eventName:BI.Searcher.EVENT_CHANGE,action:function(){a.searcher.isSearching()?a.storeValue={value:a.searcherPane.getValue()}:a.storeValue={value:a.adapter.getValue()},a.setSelectedValue(a.storeValue.value),a.fireEvent(BI.MultiSelectTree.EVENT_CHANGE)}},{eventName:BI.Searcher.EVENT_PAUSE,action:function(){a._showAdapter()}}]}),BI.createWidget({type:"bi.vtape",element:this,items:[{el:this.searcher,height:24},{el:this.adapter,height:"fill"}]}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.searcherPane,top:30,bottom:0,left:0,right:0}]})},_showAdapter:function(){this.adapter.setVisible(!0),this.searcherPane.setVisible(!1)},_showSearcherPane:function(){this.searcherPane.setVisible(!0),this.adapter.setVisible(!1)},resize:function(){},setSelectedValue:function(a){this.storeValue.value=a||{},this.adapter.setSelectedValue(a),this.searcherPane.setSelectedValue(a),this.searcher.setValue({value:a||{}})},setValue:function(a){this.adapter.setValue(a)},stopSearch:function(){this.searcher.stopSearch()},updateValue:function(a){this.adapter.updateValue(a)},getValue:function(){return this.storeValue.value},populate:function(){this.searcher.populate.apply(this.searcher,arguments),this.adapter.populate.apply(this.adapter,arguments)}}),BI.MultiSelectTree.EVENT_CHANGE="BI.MultiSelectTree.EVENT_CHANGE",BI.shortcut("bi.multi_select_tree",BI.MultiSelectTree),BI.MultiSelectTreePopup=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiSelectTreePopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-select-tree-popup bi-border-left bi-border-right bi-border-bottom",itemsCreator:BI.emptyFn})},_init:function(){BI.MultiSelectTreePopup.superclass._init.apply(this,arguments);var a=this,b=this.options;this.popup=BI.createWidget({type:"bi.async_tree",element:this,itemsCreator:b.itemsCreator}),this.popup.on(BI.TreeView.EVENT_AFTERINIT,function(){a.fireEvent(BI.MultiSelectTreePopup.EVENT_AFTER_INIT)}),this.popup.on(BI.TreeView.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectTreePopup.EVENT_CHANGE)})},hasChecked:function(){return this.popup.hasChecked()},getValue:function(){return this.popup.getValue()},setValue:function(a){a||(a={}),this.popup.setValue(a)},setSelectedValue:function(a){a||(a={}),this.popup.setSelectedValue(a)},updateValue:function(a){this.popup.updateValue(a),this.popup.refresh()},populate:function(a){this.popup.stroke(a)}}),BI.MultiSelectTreePopup.EVENT_AFTER_INIT="BI.MultiSelectTreePopup.EVENT_AFTER_INIT",BI.MultiSelectTreePopup.EVENT_CHANGE="BI.MultiSelectTreePopup.EVENT_CHANGE",BI.shortcut("bi.multi_select_tree_popup",BI.MultiSelectTreePopup),BI.MultiTreeCheckPane=BI.inherit(BI.Pane,{constants:{height:25,lgap:10,tgap:5},_defaultConfig:function(){return BI.extend(BI.MultiTreeCheckPane.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-check-pane bi-background",onClickContinueSelect:BI.emptyFn})},_init:function(){BI.MultiTreeCheckPane.superclass._init.apply(this,arguments);var a=this,b=this.options;this.selectedValues={};var c=BI.createWidget({type:"bi.text_button",text:BI.i18nText("BI-Continue_Select"),cls:"multi-tree-check-selected"});c.on(BI.TextButton.EVENT_CHANGE,function(){b.onClickContinueSelect(),BI.nextTick(function(){a.empty()})});var d=BI.createWidget({type:"bi.left",cls:"multi-tree-continue-select",items:[{el:{type:"bi.label",text:BI.i18nText("BI-Selected_Data")},lgap:this.constants.lgap,tgap:this.constants.tgap},{el:c,lgap:this.constants.lgap,tgap:this.constants.tgap}]});this.display=BI.createWidget({type:"bi.display_tree",cls:"bi-multi-tree-display",itemsCreator:function(a,c){a.type=BI.TreeView.REQ_TYPE_GET_SELECTED_DATA,b.itemsCreator(a,c)}}),this.display.on(BI.Events.AFTERINIT,function(){a.fireEvent(BI.Events.AFTERINIT)}),this.display.on(BI.TreeView.EVENT_INIT,function(){d.setVisible(!1)}),this.display.on(BI.TreeView.EVENT_AFTERINIT,function(){d.setVisible(!0)}),BI.createWidget({type:"bi.vtape",element:this,items:[{height:this.constants.height,el:d},{height:"fill",el:this.display}]})},empty:function(){this.display.empty()},populate:function(a){this.display.stroke(a)},setValue:function(a){a||(a={}),this.display.setSelectedValue(a.value)},getValue:function(){}}),BI.MultiTreeCheckPane.EVENT_CONTINUE_CLICK="EVENT_CONTINUE_CLICK",BI.shortcut("bi.multi_tree_check_pane",BI.MultiTreeCheckPane),BI.MultiTreeCombo=BI.inherit(BI.Single,{constants:{offset:{top:1,left:1,right:2,bottom:33}},_defaultConfig:function(){return BI.extend(BI.MultiTreeCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-combo",itemsCreator:BI.emptyFn,height:25})},_init:function(){function a(){h()?b.storeValue={value:b.trigger.getValue()}:i()&&(b.storeValue={value:b.combo.getValue()}),b.trigger.setValue(b.storeValue)}BI.MultiTreeCombo.superclass._init.apply(this,arguments);var b=this,c=this.options,d=!1,e=!1;this.trigger=BI.createWidget({ -type:"bi.multi_select_trigger",height:c.height,masker:{offset:this.constants.offset},searcher:{type:"bi.multi_tree_searcher",itemsCreator:c.itemsCreator},switcher:{el:{type:"bi.multi_tree_check_selected_button"},popup:{type:"bi.multi_tree_check_pane",itemsCreator:c.itemsCreator}}}),this.combo=BI.createWidget({type:"bi.combo",toggle:!1,el:this.trigger,adjustLength:1,popup:{type:"bi.multi_tree_popup_view",ref:function(){b.popup=this,b.trigger.setAdapter(this)},listeners:[{eventName:BI.MultiTreePopup.EVENT_AFTERINIT,action:function(){b.trigger.getCounter().adjustView(),d=!0,e===!0&&a()}},{eventName:BI.MultiTreePopup.EVENT_CHANGE,action:function(){f=!0;var a={type:BI.Selection.Multi,value:this.hasChecked()?this.getValue():{}};b.trigger.getSearcher().setState(a),b.trigger.getCounter().setButtonChecked(a)}},{eventName:BI.MultiTreePopup.EVENT_CLICK_CONFIRM,action:function(){b.combo.hideView()}},{eventName:BI.MultiTreePopup.EVENT_CLICK_CLEAR,action:function(){g=!0,b.setValue(),b._defaultState()}}],itemsCreator:c.itemsCreator,onLoaded:function(){BI.nextTick(function(){b.trigger.getCounter().adjustView(),b.trigger.getSearcher().adjustView()})}},hideChecker:function(a){return 0===j.element.find(a.target).length}}),this.storeValue={value:{}};var f=!1,g=!1,h=function(){return b.trigger.getSearcher().isSearching()},i=function(){return b.combo.isViewVisible()};this.trigger.on(BI.MultiSelectTrigger.EVENT_START,function(){b.storeValue={value:b.combo.getValue()},this.setValue(b.storeValue)}),this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP,function(){b.storeValue={value:this.getValue()},b.combo.setValue(b.storeValue),BI.nextTick(function(){i()&&b.combo.populate()})}),this.trigger.on(BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW,function(){e===!1&&(e=!0),d===!0&&(e=null,a())}),this.trigger.on(BI.MultiSelectTrigger.EVENT_TRIGGER_CLICK,function(){b.combo.toggle()}),this.trigger.on(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK,function(){b.combo.isViewVisible()||b.combo.showView()}),this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE,function(){var a=this.getSearcher().hasChecked(),b={type:BI.Selection.Multi,value:a?{1:1}:{}};this.getSearcher().setState(a?BI.Selection.Multi:BI.Selection.None),this.getCounter().setButtonChecked(b)}),this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW,function(){h()||(f===!0&&(b.storeValue={value:b.combo.getValue()},f=!1),b.combo.setValue(b.storeValue),b.populate())}),this.combo.on(BI.Combo.EVENT_BEFORE_HIDEVIEW,function(){h()?(b.trigger.stopEditing(),b.fireEvent(BI.MultiTreeCombo.EVENT_CONFIRM)):i()&&(b.trigger.stopEditing(),b.storeValue={value:b.combo.getValue()},g===!0&&(b.storeValue={value:{}}),b.fireEvent(BI.MultiTreeCombo.EVENT_CONFIRM)),g=!1,f=!1});var j=BI.createWidget({type:"bi.trigger_icon_button",width:c.height,height:c.height,cls:"multi-select-trigger-icon-button bi-border-left"});j.on(BI.TriggerIconButton.EVENT_CHANGE,function(){b.trigger.getCounter().hideView(),b.combo.isViewVisible()?b.combo.hideView():b.combo.showView()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.combo,left:0,right:0,top:0,bottom:0},{el:j,right:0,top:0,bottom:0}]})},_defaultState:function(){this.trigger.stopEditing(),this.combo.hideView()},setValue:function(a){this.storeValue.value=a||{},this.combo.setValue({value:a||{}})},getValue:function(){return this.storeValue.value},populate:function(){this.combo.populate.apply(this.combo,arguments)}}),BI.MultiTreeCombo.EVENT_CONFIRM="MultiTreeCombo.EVENT_CONFIRM",BI.shortcut("bi.multi_tree_combo",BI.MultiTreeCombo),BI.MultiTreePopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.MultiTreePopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-popup",maxWidth:"auto",minWidth:100,maxHeight:400,onLoaded:BI.emptyFn})},_init:function(){BI.MultiTreePopup.superclass._init.apply(this,arguments);var a=this,b=this.options;this.selectedValues={},this.tree=BI.createWidget({type:"bi.async_tree",height:400,cls:"popup-view-tree",itemsCreator:b.itemsCreator,onLoaded:b.onLoaded}),this.popupView=BI.createWidget({type:"bi.multi_popup_view",element:this,stopPropagation:!1,maxWidth:b.maxWidth,minWidth:b.minWidth,maxHeight:b.maxHeight,buttons:[BI.i18nText("BI-Basic_Clears"),BI.i18nText("BI-Basic_Sure")],el:this.tree}),this.popupView.on(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON,function(b){switch(b){case 0:a.fireEvent(BI.MultiTreePopup.EVENT_CLICK_CLEAR);break;case 1:a.fireEvent(BI.MultiTreePopup.EVENT_CLICK_CONFIRM)}}),this.tree.on(BI.TreeView.EVENT_CHANGE,function(){a.fireEvent(BI.MultiTreePopup.EVENT_CHANGE)}),this.tree.on(BI.TreeView.EVENT_AFTERINIT,function(){a.fireEvent(BI.MultiTreePopup.EVENT_AFTERINIT)})},getValue:function(){return this.tree.getValue()},setValue:function(a){a||(a={}),this.tree.setSelectedValue(a.value)},populate:function(a){this.tree.stroke(a)},hasChecked:function(){return this.tree.hasChecked()},resetHeight:function(a){this.popupView.resetHeight(a)},resetWidth:function(a){this.popupView.resetWidth(a)}}),BI.MultiTreePopup.EVENT_CHANGE="EVENT_CHANGE",BI.MultiTreePopup.EVENT_CLICK_CONFIRM="EVENT_CLICK_CONFIRM",BI.MultiTreePopup.EVENT_CLICK_CLEAR="EVENT_CLICK_CLEAR",BI.MultiTreePopup.EVENT_AFTERINIT="EVENT_AFTERINIT",BI.shortcut("bi.multi_tree_popup_view",BI.MultiTreePopup),BI.MultiTreeSearchPane=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.MultiTreeSearchPane.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-search-pane bi-card",itemsCreator:BI.emptyFn,keywordGetter:BI.emptyFn})},_init:function(){BI.MultiTreeSearchPane.superclass._init.apply(this,arguments);var a=this,b=this.options;this.partTree=BI.createWidget({type:"bi.part_tree",element:this,tipText:BI.i18nText("BI-No_Select"),itemsCreator:function(a,c){a.keyword=b.keywordGetter(),b.itemsCreator(a,c)}}),this.partTree.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.partTree.on(BI.TreeView.EVENT_CHANGE,function(){a.fireEvent(BI.MultiTreeSearchPane.EVENT_CHANGE)})},hasChecked:function(){return this.partTree.hasChecked()},setValue:function(a){this.setSelectedValue(a.value)},setSelectedValue:function(a){a||(a={}),this.partTree.setSelectedValue(a)},getValue:function(){return this.partTree.getValue()},empty:function(){this.partTree.empty()},populate:function(a){this.partTree.stroke.apply(this.partTree,arguments)}}),BI.MultiTreeSearchPane.EVENT_CHANGE="EVENT_CHANGE",BI.MultiTreeSearchPane.EVENT_CLICK_CONFIRM="EVENT_CLICK_CONFIRM",BI.MultiTreeSearchPane.EVENT_CLICK_CLEAR="EVENT_CLICK_CLEAR",BI.shortcut("bi.multi_tree_search_pane",BI.MultiTreeSearchPane),BI.MultiTreeCheckSelectedButton=BI.inherit(BI.Single,{_const:{checkSelected:BI.i18nText("BI-Check_Selected")},_defaultConfig:function(){return BI.extend(BI.MultiTreeCheckSelectedButton.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-check-selected-button",itemsCreator:BI.emptyFn})},_init:function(){BI.MultiTreeCheckSelectedButton.superclass._init.apply(this,arguments);var a=this;this.indicator=BI.createWidget({type:"bi.icon_button",cls:"check-font trigger-check-selected",width:15,height:15,stopPropagation:!0}),this.checkSelected=BI.createWidget({type:"bi.text_button",cls:"trigger-check-selected",invisible:!0,hgap:4,text:this._const.checkSelected,textAlign:"center",textHeight:15}),this.checkSelected.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.checkSelected.on(BI.TextButton.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectCheckSelectedButton.EVENT_CHANGE,arguments)}),BI.createWidget({type:"bi.horizontal",element:this,items:[this.indicator,this.checkSelected]}),this.element.hover(function(){a.indicator.setVisible(!1),a.checkSelected.setVisible(!0)},function(){a.indicator.setVisible(!0),a.checkSelected.setVisible(!1)}),this.setVisible(!1)},setValue:function(a){a||(a={}),this.setVisible(BI.size(a.value)>0)}}),BI.MultiTreeCheckSelectedButton.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multi_tree_check_selected_button",BI.MultiTreeCheckSelectedButton),BI.MultiTreeSearcher=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiTreeSearcher.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-searcher",itemsCreator:BI.emptyFn,popup:{},adapter:null,masker:{}})},_init:function(){BI.MultiTreeSearcher.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.multi_select_editor",height:b.height,el:{type:"bi.simple_state_editor",height:b.height}}),this.searcher=BI.createWidget({type:"bi.searcher",element:this,isAutoSearch:!1,isAutoSync:!1,onSearch:function(b,c){c({keyword:a.editor.getValue()})},el:this.editor,popup:BI.extend({type:"bi.multi_tree_search_pane",keywordGetter:function(){return a.editor.getValue()},itemsCreator:function(c,d){c.keyword=a.editor.getValue(),b.itemsCreator(c,d)}},b.popup),adapter:b.adapter,masker:b.masker}),this.searcher.on(BI.Searcher.EVENT_START,function(){a.fireEvent(BI.MultiTreeSearcher.EVENT_START)}),this.searcher.on(BI.Searcher.EVENT_PAUSE,function(){this.hasMatched(),a.fireEvent(BI.MultiTreeSearcher.EVENT_PAUSE)}),this.searcher.on(BI.Searcher.EVENT_STOP,function(){a.fireEvent(BI.MultiTreeSearcher.EVENT_STOP)}),this.searcher.on(BI.Searcher.EVENT_CHANGE,function(){a.fireEvent(BI.MultiTreeSearcher.EVENT_CHANGE,arguments)})},adjustView:function(){this.searcher.adjustView()},setAdapter:function(a){this.searcher.setAdapter(a)},isSearching:function(){return this.searcher.isSearching()},stopSearch:function(){this.searcher.stopSearch()},getKeyword:function(){return this.editor.getValue()},hasMatched:function(){return this.searcher.hasMatched()},hasChecked:function(){return this.searcher.getView()&&this.searcher.getView().hasChecked()},setState:function(a){function b(a){var c="",d=0,e=BI.size(a);return BI.each(a,function(a,f){d++;var g=b(f);c+=a+(""===g?"":":"+g)+(d===e?"":",")}),c}if(a||(a={}),a.value||(a.value={}),BI.isNumber(a))this.editor.setState(a);else if(0===BI.size(a.value))this.editor.setState(BI.Selection.None);else{var c="";BI.each(a.value,function(a,d){var e=b(d);c+=a+(""===e?"":":"+e)+"; "}),this.editor.setState(c)}},setValue:function(a){this.setState(a),this.searcher.setValue(a)},getKey:function(){return this.editor.getValue()},getValue:function(){return this.searcher.getValue()},populate:function(a){this.searcher.populate.apply(this.searcher,arguments)}}),BI.MultiTreeSearcher.EVENT_BEFORE_POPUPVIEW="EVENT_BEFORE_POPUPVIEW",BI.MultiTreeSearcher.EVENT_CHANGE="EVENT_CHANGE",BI.MultiTreeSearcher.EVENT_START="EVENT_START",BI.MultiTreeSearcher.EVENT_STOP="EVENT_STOP",BI.MultiTreeSearcher.EVENT_PAUSE="EVENT_PAUSE",BI.shortcut("bi.multi_tree_searcher",BI.MultiTreeSearcher),BI.NumberEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.NumberEditor.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-number-editor bi-border",validationChecker:function(){return!0},valueFormatter:function(a){return a},value:0,allowBlank:!1,errorText:"",step:1})},_init:function(){BI.NumberEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.sign_editor",height:b.height,allowBlank:b.allowBlank,value:b.valueFormatter(b.value),validationChecker:b.validationChecker,errorText:b.errorText}),this.editor.on(BI.TextEditor.EVENT_CHANGE,function(){b.value=this.getValue(),a.fireEvent(BI.NumberEditor.EVENT_CHANGE)}),this.editor.on(BI.TextEditor.EVENT_CONFIRM,function(){a.fireEvent(BI.NumberEditor.EVENT_CONFIRM)}),this.topBtn=BI.createWidget({type:"bi.icon_button",trigger:"lclick,",cls:"column-pre-page-h-font top-button bi-border-left bi-border-bottom"}),this.topBtn.on(BI.IconButton.EVENT_CHANGE,function(){a._finetuning(b.step),a.fireEvent(BI.NumberEditor.EVENT_CHANGE),a.fireEvent(BI.NumberEditor.EVENT_CONFIRM)}),this.bottomBtn=BI.createWidget({type:"bi.icon_button",trigger:"lclick,",cls:"column-next-page-h-font bottom-button bi-border-left bi-border-top"}),this.bottomBtn.on(BI.IconButton.EVENT_CHANGE,function(){a._finetuning(-b.step),a.fireEvent(BI.NumberEditor.EVENT_CHANGE),a.fireEvent(BI.NumberEditor.EVENT_CONFIRM)}),BI.createWidget({type:"bi.htape",element:this,items:[this.editor,{el:{type:"bi.grid",columns:1,rows:2,items:[{column:0,row:0,el:this.topBtn},{column:0,row:1,el:this.bottomBtn}]},width:23}]})},_finetuning:function(a){var b=BI.parseFloat(this.getValue());this.setValue(b.add(a))},setUpEnable:function(a){this.topBtn.setEnable(!!a)},setDownEnable:function(a){this.bottomBtn.setEnable(!!a)},getValue:function(){return this.options.value},setValue:function(a){var b=this.options;b.value=a,this.editor.setValue(b.valueFormatter(a))}}),BI.NumberEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.NumberEditor.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.number_editor",BI.NumberEditor),BI.NumberInterval=BI.inherit(BI.Single,{constants:{typeError:"typeBubble",numberError:"numberBubble",signalError:"signalBubble",editorWidth:114,columns:5,width:30,rows:1,numberErrorCls:"number-error",border:1,less:0,less_equal:1,numTip:""},_defaultConfig:function(){var a=BI.NumberInterval.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-number-interval",height:25,validation:"valid"})},_init:function(){var a=this,b=this.constants,c=this.options;BI.NumberInterval.superclass._init.apply(this,arguments),this.smallEditor=BI.createWidget({type:"bi.editor",height:c.height-2,watermark:BI.i18nText("BI-Basic_Unrestricted"),allowBlank:!0,value:c.min,level:"warning",tipType:"warning",quitChecker:function(){return!1},validationChecker:function(c){return!!BI.isNumeric(c)||(a.smallEditorBubbleType=b.typeError,!1)},cls:"number-interval-small-editor bi-border-top bi-border-bottom bi-border-left"}),this.smallTip=BI.createWidget({type:"bi.label",text:c.numTip,height:c.height-2,invisible:!0}),BI.createWidget({type:"bi.absolute",element:this.smallEditor.element,items:[{el:this.smallTip,top:0,right:5}]}),this.bigEditor=BI.createWidget({type:"bi.editor",height:c.height-2,watermark:BI.i18nText("BI-Basic_Unrestricted"),allowBlank:!0,value:c.max,level:"warning",tipType:"warning",quitChecker:function(){return!1},validationChecker:function(c){return!!BI.isNumeric(c)||(a.bigEditorBubbleType=b.typeError,!1)},cls:"number-interval-big-editor bi-border-top bi-border-bottom bi-border-right"}),this.bigTip=BI.createWidget({type:"bi.label",text:c.numTip,height:c.height-2,invisible:!0}),BI.createWidget({type:"bi.absolute",element:this.bigEditor.element,items:[{el:this.bigTip,top:0,right:5}]}),this.smallCombo=BI.createWidget({type:"bi.icon_combo",cls:"number-interval-small-combo bi-border",height:c.height-2,items:[{text:"("+BI.i18nText("BI-Less_Than")+")",iconClass:"less-font",value:0},{text:"("+BI.i18nText("BI-Less_And_Equal")+")",value:1,iconClass:"less-equal-font"}]}),c.closemin===!0?this.smallCombo.setValue(1):this.smallCombo.setValue(0),this.bigCombo=BI.createWidget({type:"bi.icon_combo",cls:"number-interval-big-combo bi-border",height:c.height-2,items:[{text:"("+BI.i18nText("BI-Less_Than")+")",iconClass:"less-font",value:0},{text:"("+BI.i18nText("BI-Less_And_Equal")+")",value:1,iconClass:"less-equal-font"}]}),c.closemax===!0?this.bigCombo.setValue(1):this.bigCombo.setValue(0),this.label=BI.createWidget({type:"bi.label",text:BI.i18nText("BI-Basic_Value"),textHeight:c.height-2*b.border,width:b.width-2*b.border,height:c.height-2*b.border,level:"warning",tipType:"warning"}),this.left=BI.createWidget({type:"bi.htape",items:[{el:a.smallEditor},{el:a.smallCombo,width:b.width-2*b.border}]}),this.right=BI.createWidget({type:"bi.htape",items:[{el:a.bigCombo,width:b.width-2*b.border},{el:a.bigEditor}]}),BI.createWidget({element:a,type:"bi.center",hgap:15,height:c.height,items:[{type:"bi.absolute",items:[{el:a.left,left:-15,right:0,top:0,bottom:0}]},{type:"bi.absolute",items:[{el:a.right,left:0,right:-15,top:0,bottom:0}]}]}),BI.createWidget({element:a,type:"bi.horizontal_auto",items:[a.label]}),a._setValidEvent(a.bigEditor,b.bigEditor),a._setValidEvent(a.smallEditor,b.smallEditor),a._setErrorEvent(a.bigEditor,b.bigEditor),a._setErrorEvent(a.smallEditor,b.smallEditor),a._setBlurEvent(a.bigEditor),a._setBlurEvent(a.smallEditor),a._setFocusEvent(a.bigEditor),a._setFocusEvent(a.smallEditor),a._setComboValueChangedEvent(a.bigCombo),a._setComboValueChangedEvent(a.smallCombo),a._setEditorValueChangedEvent(a.bigEditor),a._setEditorValueChangedEvent(a.smallEditor)},_checkValidation:function(){var a=this,b=this.constants,c=this.options;if(a._setTitle(""),BI.Bubbles.hide(b.typeError),BI.Bubbles.hide(b.numberError),BI.Bubbles.hide(b.signalError),a.smallEditor.isValid()&&a.bigEditor.isValid()){if(BI.isEmptyString(a.smallEditor.getValue())||BI.isEmptyString(a.bigEditor.getValue()))return a.element.removeClass("number-error"),c.validation="valid","";var d=parseFloat(a.smallEditor.getValue()),e=parseFloat(a.bigEditor.getValue()),f=a.bigCombo.getValue(),g=a.smallCombo.getValue();return f[0]===b.less_equal&&g[0]===b.less_equal?d>e?(a.element.addClass("number-error"),c.validation="invalid",b.numberError):(a.element.removeClass("number-error"),c.validation="valid",""):d>e?(a.element.addClass("number-error"),c.validation="invalid",b.numberError):d===e?(a.element.addClass("number-error"),c.validation="invalid",b.signalError):(a.element.removeClass("number-error"),c.validation="valid","")}return a.element.removeClass("number-error"),c.validation="invalid",b.typeError},_setTitle:function(a){var b=this;b.bigEditor.setTitle(a),b.smallEditor.setTitle(a),b.label.setTitle(a)},_setFocusEvent:function(a){var b=this,c=this.constants;a.on(BI.Editor.EVENT_FOCUS,function(){switch(b._setTitle(""),b._checkValidation()){case c.typeError:BI.Bubbles.show(c.typeError,BI.i18nText("BI-Numerical_Interval_Input_Data"),b,{offsetStyle:"center"});break;case c.numberError:BI.Bubbles.show(c.numberError,BI.i18nText("BI-Numerical_Interval_Number_Value"),b,{offsetStyle:"center"});break;case c.signalError:BI.Bubbles.show(c.signalError,BI.i18nText("BI-Numerical_Interval_Signal_Value"),b,{offsetStyle:"center"});break;default:return}})},_setBlurEvent:function(a){var b=this.constants,c=this;a.on(BI.Editor.EVENT_BLUR,function(){switch(BI.Bubbles.hide(b.typeError),BI.Bubbles.hide(b.numberError),BI.Bubbles.hide(b.signalError),c._checkValidation()){case b.typeError:c._setTitle(BI.i18nText("BI-Numerical_Interval_Input_Data"));break;case b.numberError:c._setTitle(BI.i18nText("BI-Numerical_Interval_Number_Value"));break;case b.signalError:c._setTitle(BI.i18nText("BI-Numerical_Interval_Signal_Value"));break;default:c._setTitle("")}})},_setErrorEvent:function(a){var b=this.constants,c=this;a.on(BI.Editor.EVENT_ERROR,function(){c._checkValidation(),BI.Bubbles.show(b.typeError,BI.i18nText("BI-Numerical_Interval_Input_Data"),c,{offsetStyle:"center"}),c.fireEvent(BI.NumberInterval.EVENT_ERROR)})},_setValidEvent:function(a){var b=this,c=this.constants;a.on(BI.Editor.EVENT_VALID,function(){switch(b._checkValidation()){case c.numberError:BI.Bubbles.show(c.numberError,BI.i18nText("BI-Numerical_Interval_Number_Value"),b,{offsetStyle:"center"}),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;case c.signalError:BI.Bubbles.show(c.signalError,BI.i18nText("BI-Numerical_Interval_Signal_Value"),b,{offsetStyle:"center"}),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;default:b.fireEvent(BI.NumberInterval.EVENT_VALID)}})},_setEditorValueChangedEvent:function(a){var b=this,c=this.constants;a.on(BI.Editor.EVENT_CHANGE,function(){switch(b._checkValidation()){case c.typeError:BI.Bubbles.show(c.typeError,BI.i18nText("BI-Numerical_Interval_Input_Data"),b,{offsetStyle:"center"});break;case c.numberError:BI.Bubbles.show(c.numberError,BI.i18nText("BI-Numerical_Interval_Number_Value"),b,{offsetStyle:"center"});break;case c.signalError:BI.Bubbles.show(c.signalError,BI.i18nText("BI-Numerical_Interval_Signal_Value"),b,{offsetStyle:"center"})}b.fireEvent(BI.NumberInterval.EVENT_CHANGE)})},_setComboValueChangedEvent:function(a){var b=this,c=this.constants;a.on(BI.IconCombo.EVENT_CHANGE,function(){switch(b._checkValidation()){case c.typeError:b._setTitle(BI.i18nText("BI-Numerical_Interval_Input_Data")),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;case c.numberError:b._setTitle(BI.i18nText("BI-Numerical_Interval_Number_Value")),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;case c.signalError:b._setTitle(BI.i18nText("BI-Numerical_Interval_Signal_Value")),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;default:b.fireEvent(BI.NumberInterval.EVENT_CHANGE),b.fireEvent(BI.NumberInterval.EVENT_VALID)}})},isStateValid:function(){return"valid"===this.options.validation},setMinEnable:function(a){this.smallEditor.setEnable(a)},setCloseMinEnable:function(a){this.smallCombo.setEnable(a)},setMaxEnable:function(a){this.bigEditor.setEnable(a)},setCloseMaxEnable:function(a){this.bigCombo.setEnable(a)},showNumTip:function(){this.smallTip.setVisible(!0),this.bigTip.setVisible(!0)},hideNumTip:function(){this.smallTip.setVisible(!1),this.bigTip.setVisible(!1)},setNumTip:function(a){this.smallTip.setText(a),this.bigTip.setText(a)},getNumTip:function(){return this.smallTip.getText()},setValue:function(a){a=a||{};var b,c=this;(BI.isNumeric(a.min)||BI.isEmptyString(a.min))&&c.smallEditor.setValue(a.min),BI.isNotNull(a.min)||c.smallEditor.setValue(""),(BI.isNumeric(a.max)||BI.isEmptyString(a.max))&&c.bigEditor.setValue(a.max),BI.isNotNull(a.max)||c.bigEditor.setValue(""),BI.isNull(a.closemin)||(b=a.closemin===!0?1:0,c.smallCombo.setValue(b)),BI.isNull(a.closemax)||(b=a.closemax===!0?1:0,c.bigCombo.setValue(b))},getValue:function(){var a=this,b={},c=a.smallCombo.getValue(),d=a.bigCombo.getValue();return b.min=a.smallEditor.getValue(),b.max=a.bigEditor.getValue(),0===c[0]?b.closemin=!1:b.closemin=!0,0===d[0]?b.closemax=!1:b.closemax=!0,b}}),BI.NumberInterval.EVENT_CHANGE="EVENT_CHANGE",BI.NumberInterval.EVENT_VALID="EVENT_VALID",BI.NumberInterval.EVENT_ERROR="EVENT_ERROR",BI.shortcut("bi.number_interval",BI.NumberInterval),BI.PageTableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.PageTableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-page-table-cell",text:"",title:""})},_init:function(){BI.PageTableCell.superclass._init.apply(this,arguments);BI.createWidget({type:"bi.label",element:this,textAlign:"left",whiteSpace:"nowrap",height:this.options.height,text:this.options.text,title:this.options.title,value:this.options.value,lgap:5,rgap:5});BI.isNotNull(this.options.styles)&&BI.isObject(this.options.styles)&&this.element.css(this.options.styles)}}),BI.shortcut("bi.page_table_cell",BI.PageTableCell),BI.PageTable=BI.inherit(BI.Widget,{_const:{scrollWidth:18,minScrollWidth:100},_defaultConfig:function(){return BI.extend(BI.PageTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-page-table",el:{type:"bi.sequence_table"},pager:{horizontal:{pages:!1,curr:1,hasPrev:BI.emptyFn,hasNext:BI.emptyFn,firstPage:1,lastPage:BI.emptyFn},vertical:{pages:!1,curr:1,hasPrev:BI.emptyFn,hasNext:BI.emptyFn,firstPage:1,lastPage:BI.emptyFn}},itemsCreator:BI.emptyFn,isNeedFreeze:!1,freezeCols:[],isNeedMerge:!1,mergeCols:[],mergeRule:BI.emptyFn,columnSize:[],minColumnSize:[],maxColumnSize:[],headerRowSize:25,rowSize:25,regionColumnSize:[],headerCellStyleGetter:BI.emptyFn,summaryCellStyleGetter:BI.emptyFn,sequenceCellStyleGetter:BI.emptyFn,header:[],items:[],crossHeader:[],crossItems:[]})},_init:function(){BI.PageTable.superclass._init.apply(this,arguments);var a=this,b=this.options;this.hCurr=1,this.vCurr=1,this.table=BI.createWidget(b.el,{type:"bi.sequence_table",width:b.width,height:b.height&&b.height-30,isNeedResize:!0,isResizeAdapt:!1,isNeedFreeze:b.isNeedFreeze,freezeCols:b.freezeCols,isNeedMerge:b.isNeedMerge,mergeCols:b.mergeCols,mergeRule:b.mergeRule,columnSize:b.columnSize,minColumnSize:b.minColumnSize,maxColumnSize:b.maxColumnSize,headerRowSize:b.headerRowSize,rowSize:b.rowSize,regionColumnSize:b.regionColumnSize,headerCellStyleGetter:b.headerCellStyleGetter,summaryCellStyleGetter:b.summaryCellStyleGetter,sequenceCellStyleGetter:b.sequenceCellStyleGetter,header:b.header,items:b.items,crossHeader:b.crossHeader,crossItems:b.crossItems}),this.table.on(BI.Table.EVENT_TABLE_SCROLL,function(){a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.table.on(BI.Table.EVENT_TABLE_AFTER_REGION_RESIZE,function(){b.regionColumnSize=this.getRegionColumnSize(),b.columnSize=this.getColumnSize(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_REGION_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE,function(){b.regionColumnSize=this.getRegionColumnSize(),b.columnSize=this.getColumnSize(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE,arguments)}),this.pager=BI.createWidget(b.pager,{type:"bi.direction_pager",height:30}),this.pager.on(BI.Pager.EVENT_CHANGE,function(){var c=this.getVPage&&this.getVPage();BI.isNull(c)&&(c=this.getCurrentPage());var d=this.getHPage&&this.getHPage();b.itemsCreator({vpage:c,hpage:d},function(b,e,f,g){a.table.setVPage?a.table.setVPage(c):a.table.setValue(c),a.table.setHPage&&a.table.setHPage(d),a.populate.apply(a,arguments)})}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.table,left:0,top:0},{el:this.pager,left:0,right:0,bottom:0}]})},setHPage:function(a){this.hCurr=a,this.pager.setHPage&&this.pager.setHPage(a),this.table.setHPage&&this.table.setHPage(a)},setVPage:function(a){this.vCurr=a,this.pager.setVPage&&this.pager.setVPage(a),this.table.setVPage&&this.table.setVPage(a)},getHPage:function(){var a=this.pager.getHPage&&this.pager.getHPage();return BI.isNotNull(a)?a:(a=this.pager.getCurrentPage&&this.pager.getCurrentPage(),BI.isNotNull(a)?a:this.hpage)},getVPage:function(){var a=this.pager.getVPage&&this.pager.getVPage();return BI.isNotNull(a)?a:(a=this.pager.getCurrentPage&&this.pager.getCurrentPage(),BI.isNotNull(a)?a:this.vpage)},setWidth:function(a){BI.PageTable.superclass.setWidth.apply(this,arguments),this.table.setWidth(a)},setHeight:function(a){BI.PageTable.superclass.setHeight.apply(this,arguments);var b=!1;this.pager.alwaysShowPager?b=!0:this.pager.hasHNext&&this.pager.hasHNext()?b=!0:this.pager.hasHPrev&&this.pager.hasHPrev()?b=!0:this.pager.hasVNext&&this.pager.hasVNext()?b=!0:this.pager.hasVPrev&&this.pager.hasVPrev()?b=!0:this.pager.hasNext&&this.pager.hasNext()?b=!0:this.pager.hasPrev&&this.pager.hasPrev()&&(b=!0),this.table.setHeight(a-(b?30:0))},setColumnSize:function(a){this.options.columnSize=a,this.table.setColumnSize(a)},getColumnSize:function(){return this.table.getColumnSize()},setRegionColumnSize:function(a){this.options.columnSize=a,this.table.setRegionColumnSize(a)},getRegionColumnSize:function(){return this.table.getRegionColumnSize()},getVerticalScroll:function(){return this.table.getVerticalScroll()},setLeftHorizontalScroll:function(a){this.table.setLeftHorizontalScroll(a)},setRightHorizontalScroll:function(a){this.table.setRightHorizontalScroll(a)},setVerticalScroll:function(a){this.table.setVerticalScroll(a)},restore:function(){this.table.restore()},attr:function(){BI.PageTable.superclass.attr.apply(this,arguments),this.table.attr.apply(this.table,arguments)},populate:function(){this.pager.populate(),this.table.populate.apply(this.table,arguments)},destroy:function(){this.table.destroy(),this.pager&&this.pager.destroy(),BI.PageTable.superclass.destroy.apply(this,arguments)}}),BI.shortcut("bi.page_table",BI.PageTable),BI.PathChooser=BI.inherit(BI.Widget,{_const:{lineColor:"#d4dadd",selectLineColor:"#3f8ce8"},_defaultConfig:function(){return BI.extend(BI.PathChooser.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-path-chooser",items:[]})},_init:function(){BI.PathChooser.superclass._init.apply(this,arguments),this.populate(this.options.items)},_createRegions:function(a){var b=this;this.regions=BI.createWidgets(BI.map(a,function(a,c){return{type:"bi.path_region",title:b.texts[c]||c}})),this.regionMap={},BI.each(a,function(a,c){b.regionMap[c]=a}),this.container=BI.createWidget({type:"bi.horizontal",verticalAlign:"top",scrollx:!1,scrolly:!1,hgap:10,items:this.regions}),BI.createWidget({type:"bi.vertical_adapt",element:this,scrollable:!0,hgap:10,items:[this.container]})},getRegionIndexById:function(a){var b=this.cache[a],c=b.get("region");return this.regionMap[c]},_drawPath:function(a,b,c){var d=this,e=[];e=BI.contains(this.start,a)?this.start:[a],BI.each(e,function(a,b){BI.each(d.radios[b],function(a,b){b.setSelected(!1)}),BI.each(d.lines[b],function(a,b){b.attr("stroke",d._const.lineColor)}),BI.each(d.regionIndexes[b],function(a,b){d.regions[b].reset()})}),BI.each(this.routes[a][c],function(a,e){var f=d.getRegionIndexById(e);d.regions[f].setSelect(b+c,e)});for(var f=BI.last(this.routes[a][c]);f&&this.routes[f]&&1===this.routes[f].length;)BI.each(this.routes[f][0],function(a,b){var c=d.getRegionIndexById(b);d.regions[c].setSelect(0,b)}),this.lines[f][0].attr("stroke",d._const.selectLineColor).toFront(),f=BI.last(this.routes[f][0]);this.lines[a][c].attr("stroke",d._const.selectLineColor).toFront(),this.radios[a]&&this.radios[a][c]&&this.radios[a][c].setSelected(!0)},_drawRadio:function(a,b,c,d,e){var f=this,g=BI.createWidget({type:"bi.radio",cls:"path-chooser-radio",selected:b+c===0,start:a,index:c});g.on(BI.Radio.EVENT_CHANGE,function(){f._drawPath(a,b,c),f.fireEvent(BI.PathChooser.EVENT_CHANGE,a,c)}),this.radios[a]||(this.radios[a]=[]),this.radios[a].push(g),BI.createWidget({type:"bi.absolute",element:this.container,items:[{el:g,left:d-6.5,top:e-6.5}]})},_drawLine:function(a,b){var c=this;this.lines[a]||(this.lines[a]=[]),this.pathes[a]||(this.pathes[a]=[]);var d=this.getRegionIndexById(a),e=this.regions[d].getIndexByValue(a);BI.each(b,function(f,g){c.pathes[a][f]=[];var h=f+e,i="",j=47.5+29*h,k=50+100*d,l=k,m=j,n=j,o=c.getRegionIndexById(BI.last(g)),p=c.regions[o].getIndexByValue(BI.last(g)),q=50+100*o;if(BI.contains(c.start,a)?(l=k-50,i+="M"+(k-50)+","+j,c.pathes[a][f].push({x:k-50,y:j})):0===h?(l=k+50,i+="M"+k+","+j,c.pathes[a][f].push({x:k,y:j})):(l=k+50,i+="M"+k+",47.5L"+(k+50)+",47.5L"+(k+50)+","+j,c.pathes[a][f].push({x:k,y:47.5}),c.pathes[a][f].push({x:k+50,y:47.5}),c.pathes[a][f].push({x:k+50,y:j})),h>0){var r=29*p+47.5;i+="L"+(q-50)+","+n+"L"+(q-50)+","+r+"L"+q+","+r,c.pathes[a][f].push({x:q-50,y:n}),c.pathes[a][f].push({x:q-50,y:r}),c.pathes[a][f].push({x:q,y:r})}else i+="L"+q+","+n,c.pathes[a][f].push({x:q,y:n});var s=c.svg.path(i).attr({stroke:0===h?c._const.selectLineColor:c._const.lineColor,"stroke-dasharray":"-"});c.lines[a].push(s),b.length>1&&c.lines[a][0].toFront(),BI.contains(c.start,a)&&c.lines[c.regions[0].getValueByIndex(0)][0].toFront(),(b.length>1||BI.contains(c.start,a))&&c._drawRadio(a,e,f,l,m)})},_drawLines:function(a){var b=this;this.lines={},this.pathes={},this.radios={},this.regionIndexes={},BI.each(a,function(a,c){b.regionIndexes[a]||(b.regionIndexes[a]=[]),BI.each(c,function(c,d){BI.each(d,function(c,d){var e=b.getRegionIndexById(d);BI.contains(b.regionIndexes[a],e)||b.regionIndexes[a].push(e)})})}),BI.each(a,function(a,c){b._drawLine(a,c)})},_pushNodes:function(a){for(var b=this,c=[],d=0;d0||BI.contains(b.start,e))&&g.addItem(e,b.texts[e])}for(var d=BI.first(c);d0&&(h=c[b-1]);var i=a.cache[h.value||""],j=a.cache[g.value]||new BI.Node(g.value);j.set(g),a.cache[g.value]=j,a.texts[g.value]=g.text,a.texts[g.region]=g.regionText,i=BI.isNull(i)?d.getRoot():i, +type:"bi.multi_select_trigger",height:c.height,masker:{offset:this.constants.offset},searcher:{type:"bi.multi_tree_searcher",itemsCreator:c.itemsCreator},switcher:{el:{type:"bi.multi_tree_check_selected_button"},popup:{type:"bi.multi_tree_check_pane",itemsCreator:c.itemsCreator}}}),this.combo=BI.createWidget({type:"bi.combo",toggle:!1,el:this.trigger,adjustLength:1,popup:{type:"bi.multi_tree_popup_view",ref:function(){b.popup=this,b.trigger.setAdapter(this)},listeners:[{eventName:BI.MultiTreePopup.EVENT_AFTERINIT,action:function(){b.trigger.getCounter().adjustView(),d=!0,e===!0&&a()}},{eventName:BI.MultiTreePopup.EVENT_CHANGE,action:function(){f=!0;var a={type:BI.Selection.Multi,value:this.hasChecked()?this.getValue():{}};b.trigger.getSearcher().setState(a),b.trigger.getCounter().setButtonChecked(a)}},{eventName:BI.MultiTreePopup.EVENT_CLICK_CONFIRM,action:function(){b.combo.hideView()}},{eventName:BI.MultiTreePopup.EVENT_CLICK_CLEAR,action:function(){g=!0,b.setValue(),b._defaultState()}}],itemsCreator:c.itemsCreator,onLoaded:function(){BI.nextTick(function(){b.trigger.getCounter().adjustView(),b.trigger.getSearcher().adjustView()})}},hideChecker:function(a){return 0===j.element.find(a.target).length}}),this.storeValue={value:{}};var f=!1,g=!1,h=function(){return b.trigger.getSearcher().isSearching()},i=function(){return b.combo.isViewVisible()};this.trigger.on(BI.MultiSelectTrigger.EVENT_START,function(){b.storeValue={value:b.combo.getValue()},this.setValue(b.storeValue)}),this.trigger.on(BI.MultiSelectTrigger.EVENT_STOP,function(){b.storeValue={value:this.getValue()},b.combo.setValue(b.storeValue),BI.nextTick(function(){i()&&b.combo.populate()})}),this.trigger.on(BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW,function(){e===!1&&(e=!0),d===!0&&(e=null,a())}),this.trigger.on(BI.MultiSelectTrigger.EVENT_TRIGGER_CLICK,function(){b.combo.toggle()}),this.trigger.on(BI.MultiSelectTrigger.EVENT_COUNTER_CLICK,function(){b.combo.isViewVisible()||b.combo.showView()}),this.trigger.on(BI.MultiSelectTrigger.EVENT_CHANGE,function(){var a=this.getSearcher().hasChecked(),b={type:BI.Selection.Multi,value:a?{1:1}:{}};this.getSearcher().setState(a?BI.Selection.Multi:BI.Selection.None),this.getCounter().setButtonChecked(b)}),this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW,function(){h()||(f===!0&&(b.storeValue={value:b.combo.getValue()},f=!1),b.combo.setValue(b.storeValue),b.populate())}),this.combo.on(BI.Combo.EVENT_BEFORE_HIDEVIEW,function(){h()?(b.trigger.stopEditing(),b.fireEvent(BI.MultiTreeCombo.EVENT_CONFIRM)):i()&&(b.trigger.stopEditing(),b.storeValue={value:b.combo.getValue()},g===!0&&(b.storeValue={value:{}}),b.fireEvent(BI.MultiTreeCombo.EVENT_CONFIRM)),g=!1,f=!1});var j=BI.createWidget({type:"bi.trigger_icon_button",width:c.height,height:c.height,cls:"multi-select-trigger-icon-button bi-border-left"});j.on(BI.TriggerIconButton.EVENT_CHANGE,function(){b.trigger.getCounter().hideView(),b.combo.isViewVisible()?b.combo.hideView():b.combo.showView()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.combo,left:0,right:0,top:0,bottom:0},{el:j,right:0,top:0,bottom:0}]})},_defaultState:function(){this.trigger.stopEditing(),this.combo.hideView()},setValue:function(a){this.storeValue.value=a||{},this.combo.setValue({value:a||{}})},getValue:function(){return this.storeValue.value},populate:function(){this.combo.populate.apply(this.combo,arguments)}}),BI.MultiTreeCombo.EVENT_CONFIRM="MultiTreeCombo.EVENT_CONFIRM",BI.shortcut("bi.multi_tree_combo",BI.MultiTreeCombo),BI.MultiTreePopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.MultiTreePopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-popup",maxWidth:"auto",minWidth:100,maxHeight:400,onLoaded:BI.emptyFn})},_init:function(){BI.MultiTreePopup.superclass._init.apply(this,arguments);var a=this,b=this.options;this.selectedValues={},this.tree=BI.createWidget({type:"bi.async_tree",height:400,cls:"popup-view-tree",itemsCreator:b.itemsCreator,onLoaded:b.onLoaded}),this.popupView=BI.createWidget({type:"bi.multi_popup_view",element:this,stopPropagation:!1,maxWidth:b.maxWidth,minWidth:b.minWidth,maxHeight:b.maxHeight,buttons:[BI.i18nText("BI-Basic_Clears"),BI.i18nText("BI-Basic_Sure")],el:this.tree}),this.popupView.on(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON,function(b){switch(b){case 0:a.fireEvent(BI.MultiTreePopup.EVENT_CLICK_CLEAR);break;case 1:a.fireEvent(BI.MultiTreePopup.EVENT_CLICK_CONFIRM)}}),this.tree.on(BI.TreeView.EVENT_CHANGE,function(){a.fireEvent(BI.MultiTreePopup.EVENT_CHANGE)}),this.tree.on(BI.TreeView.EVENT_AFTERINIT,function(){a.fireEvent(BI.MultiTreePopup.EVENT_AFTERINIT)})},getValue:function(){return this.tree.getValue()},setValue:function(a){a||(a={}),this.tree.setSelectedValue(a.value)},populate:function(a){this.tree.stroke(a)},hasChecked:function(){return this.tree.hasChecked()},resetHeight:function(a){this.popupView.resetHeight(a)},resetWidth:function(a){this.popupView.resetWidth(a)}}),BI.MultiTreePopup.EVENT_CHANGE="EVENT_CHANGE",BI.MultiTreePopup.EVENT_CLICK_CONFIRM="EVENT_CLICK_CONFIRM",BI.MultiTreePopup.EVENT_CLICK_CLEAR="EVENT_CLICK_CLEAR",BI.MultiTreePopup.EVENT_AFTERINIT="EVENT_AFTERINIT",BI.shortcut("bi.multi_tree_popup_view",BI.MultiTreePopup),BI.MultiTreeSearchPane=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.MultiTreeSearchPane.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-search-pane bi-card",itemsCreator:BI.emptyFn,keywordGetter:BI.emptyFn})},_init:function(){BI.MultiTreeSearchPane.superclass._init.apply(this,arguments);var a=this,b=this.options;this.partTree=BI.createWidget({type:"bi.part_tree",element:this,tipText:BI.i18nText("BI-No_Select"),itemsCreator:function(a,c){a.keyword=b.keywordGetter(),b.itemsCreator(a,c)}}),this.partTree.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.partTree.on(BI.TreeView.EVENT_CHANGE,function(){a.fireEvent(BI.MultiTreeSearchPane.EVENT_CHANGE)})},hasChecked:function(){return this.partTree.hasChecked()},setValue:function(a){this.setSelectedValue(a.value)},setSelectedValue:function(a){a||(a={}),this.partTree.setSelectedValue(a)},getValue:function(){return this.partTree.getValue()},empty:function(){this.partTree.empty()},populate:function(a){this.partTree.stroke.apply(this.partTree,arguments)}}),BI.MultiTreeSearchPane.EVENT_CHANGE="EVENT_CHANGE",BI.MultiTreeSearchPane.EVENT_CLICK_CONFIRM="EVENT_CLICK_CONFIRM",BI.MultiTreeSearchPane.EVENT_CLICK_CLEAR="EVENT_CLICK_CLEAR",BI.shortcut("bi.multi_tree_search_pane",BI.MultiTreeSearchPane),BI.MultiTreeCheckSelectedButton=BI.inherit(BI.Single,{_const:{checkSelected:BI.i18nText("BI-Check_Selected")},_defaultConfig:function(){return BI.extend(BI.MultiTreeCheckSelectedButton.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-check-selected-button",itemsCreator:BI.emptyFn})},_init:function(){BI.MultiTreeCheckSelectedButton.superclass._init.apply(this,arguments);var a=this;this.indicator=BI.createWidget({type:"bi.icon_button",cls:"check-font trigger-check-selected",width:15,height:15,stopPropagation:!0}),this.checkSelected=BI.createWidget({type:"bi.text_button",cls:"trigger-check-selected",invisible:!0,hgap:4,text:this._const.checkSelected,textAlign:"center",textHeight:15}),this.checkSelected.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.checkSelected.on(BI.TextButton.EVENT_CHANGE,function(){a.fireEvent(BI.MultiSelectCheckSelectedButton.EVENT_CHANGE,arguments)}),BI.createWidget({type:"bi.horizontal",element:this,items:[this.indicator,this.checkSelected]}),this.element.hover(function(){a.indicator.setVisible(!1),a.checkSelected.setVisible(!0)},function(){a.indicator.setVisible(!0),a.checkSelected.setVisible(!1)}),this.setVisible(!1)},setValue:function(a){a||(a={}),this.setVisible(BI.size(a.value)>0)}}),BI.MultiTreeCheckSelectedButton.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.multi_tree_check_selected_button",BI.MultiTreeCheckSelectedButton),BI.MultiTreeSearcher=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.MultiTreeSearcher.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-multi-tree-searcher",itemsCreator:BI.emptyFn,popup:{},adapter:null,masker:{}})},_init:function(){BI.MultiTreeSearcher.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.multi_select_editor",height:b.height,el:{type:"bi.simple_state_editor",height:b.height}}),this.searcher=BI.createWidget({type:"bi.searcher",element:this,isAutoSearch:!1,isAutoSync:!1,onSearch:function(b,c){c({keyword:a.editor.getValue()})},el:this.editor,popup:BI.extend({type:"bi.multi_tree_search_pane",keywordGetter:function(){return a.editor.getValue()},itemsCreator:function(c,d){c.keyword=a.editor.getValue(),b.itemsCreator(c,d)}},b.popup),adapter:b.adapter,masker:b.masker}),this.searcher.on(BI.Searcher.EVENT_START,function(){a.fireEvent(BI.MultiTreeSearcher.EVENT_START)}),this.searcher.on(BI.Searcher.EVENT_PAUSE,function(){this.hasMatched(),a.fireEvent(BI.MultiTreeSearcher.EVENT_PAUSE)}),this.searcher.on(BI.Searcher.EVENT_STOP,function(){a.fireEvent(BI.MultiTreeSearcher.EVENT_STOP)}),this.searcher.on(BI.Searcher.EVENT_CHANGE,function(){a.fireEvent(BI.MultiTreeSearcher.EVENT_CHANGE,arguments)})},adjustView:function(){this.searcher.adjustView()},setAdapter:function(a){this.searcher.setAdapter(a)},isSearching:function(){return this.searcher.isSearching()},stopSearch:function(){this.searcher.stopSearch()},getKeyword:function(){return this.editor.getValue()},hasMatched:function(){return this.searcher.hasMatched()},hasChecked:function(){return this.searcher.getView()&&this.searcher.getView().hasChecked()},setState:function(a){function b(a){var c="",d=0,e=BI.size(a);return BI.each(a,function(a,f){d++;var g=b(f);c+=a+(""===g?"":":"+g)+(d===e?"":",")}),c}if(a||(a={}),a.value||(a.value={}),BI.isNumber(a))this.editor.setState(a);else if(0===BI.size(a.value))this.editor.setState(BI.Selection.None);else{var c="";BI.each(a.value,function(a,d){var e=b(d);c+=a+(""===e?"":":"+e)+"; "}),this.editor.setState(c)}},setValue:function(a){this.setState(a),this.searcher.setValue(a)},getKey:function(){return this.editor.getValue()},getValue:function(){return this.searcher.getValue()},populate:function(a){this.searcher.populate.apply(this.searcher,arguments)}}),BI.MultiTreeSearcher.EVENT_BEFORE_POPUPVIEW="EVENT_BEFORE_POPUPVIEW",BI.MultiTreeSearcher.EVENT_CHANGE="EVENT_CHANGE",BI.MultiTreeSearcher.EVENT_START="EVENT_START",BI.MultiTreeSearcher.EVENT_STOP="EVENT_STOP",BI.MultiTreeSearcher.EVENT_PAUSE="EVENT_PAUSE",BI.shortcut("bi.multi_tree_searcher",BI.MultiTreeSearcher),BI.NumberEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.NumberEditor.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-number-editor bi-border",validationChecker:function(){return!0},valueFormatter:function(a){return a},value:0,allowBlank:!1,errorText:"",step:1})},_init:function(){BI.NumberEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.sign_editor",height:b.height,allowBlank:b.allowBlank,value:b.valueFormatter(b.value),validationChecker:b.validationChecker,errorText:b.errorText}),this.editor.on(BI.TextEditor.EVENT_CHANGE,function(){b.value=this.getValue(),a.fireEvent(BI.NumberEditor.EVENT_CHANGE)}),this.editor.on(BI.TextEditor.EVENT_CONFIRM,function(){a.fireEvent(BI.NumberEditor.EVENT_CONFIRM)}),this.topBtn=BI.createWidget({type:"bi.icon_button",trigger:"lclick,",cls:"column-pre-page-h-font top-button bi-border-left bi-border-bottom"}),this.topBtn.on(BI.IconButton.EVENT_CHANGE,function(){a._finetuning(b.step),a.fireEvent(BI.NumberEditor.EVENT_CHANGE),a.fireEvent(BI.NumberEditor.EVENT_CONFIRM)}),this.bottomBtn=BI.createWidget({type:"bi.icon_button",trigger:"lclick,",cls:"column-next-page-h-font bottom-button bi-border-left bi-border-top"}),this.bottomBtn.on(BI.IconButton.EVENT_CHANGE,function(){a._finetuning(-b.step),a.fireEvent(BI.NumberEditor.EVENT_CHANGE),a.fireEvent(BI.NumberEditor.EVENT_CONFIRM)}),BI.createWidget({type:"bi.htape",element:this,items:[this.editor,{el:{type:"bi.grid",columns:1,rows:2,items:[{column:0,row:0,el:this.topBtn},{column:0,row:1,el:this.bottomBtn}]},width:23}]})},_finetuning:function(a){var b=BI.parseFloat(this.getValue());this.setValue(b.add(a))},setUpEnable:function(a){this.topBtn.setEnable(!!a)},setDownEnable:function(a){this.bottomBtn.setEnable(!!a)},getValue:function(){return this.options.value},setValue:function(a){var b=this.options;b.value=a,this.editor.setValue(b.valueFormatter(a))}}),BI.NumberEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.NumberEditor.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.number_editor",BI.NumberEditor),BI.NumberInterval=BI.inherit(BI.Single,{constants:{typeError:"typeBubble",numberError:"numberBubble",signalError:"signalBubble",editorWidth:114,columns:5,width:30,rows:1,numberErrorCls:"number-error",border:1,less:0,less_equal:1,numTip:""},_defaultConfig:function(){var a=BI.NumberInterval.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{extraCls:"bi-number-interval",height:25,validation:"valid"})},_init:function(){var a=this,b=this.constants,c=this.options;BI.NumberInterval.superclass._init.apply(this,arguments),this.smallEditor=BI.createWidget({type:"bi.editor",height:c.height-2,watermark:BI.i18nText("BI-Basic_Unrestricted"),allowBlank:!0,value:c.min,level:"warning",tipType:"warning",quitChecker:function(){return!1},validationChecker:function(c){return!!BI.isNumeric(c)||(a.smallEditorBubbleType=b.typeError,!1)},cls:"number-interval-small-editor bi-border-top bi-border-bottom bi-border-left"}),this.smallTip=BI.createWidget({type:"bi.label",text:c.numTip,height:c.height-2,invisible:!0}),BI.createWidget({type:"bi.absolute",element:this.smallEditor.element,items:[{el:this.smallTip,top:0,right:5}]}),this.bigEditor=BI.createWidget({type:"bi.editor",height:c.height-2,watermark:BI.i18nText("BI-Basic_Unrestricted"),allowBlank:!0,value:c.max,level:"warning",tipType:"warning",quitChecker:function(){return!1},validationChecker:function(c){return!!BI.isNumeric(c)||(a.bigEditorBubbleType=b.typeError,!1)},cls:"number-interval-big-editor bi-border-top bi-border-bottom bi-border-right"}),this.bigTip=BI.createWidget({type:"bi.label",text:c.numTip,height:c.height-2,invisible:!0}),BI.createWidget({type:"bi.absolute",element:this.bigEditor.element,items:[{el:this.bigTip,top:0,right:5}]}),this.smallCombo=BI.createWidget({type:"bi.icon_combo",cls:"number-interval-small-combo bi-border",height:c.height-2,items:[{text:"("+BI.i18nText("BI-Less_Than")+")",iconClass:"less-font",value:0},{text:"("+BI.i18nText("BI-Less_And_Equal")+")",value:1,iconClass:"less-equal-font"}]}),c.closemin===!0?this.smallCombo.setValue(1):this.smallCombo.setValue(0),this.bigCombo=BI.createWidget({type:"bi.icon_combo",cls:"number-interval-big-combo bi-border",height:c.height-2,items:[{text:"("+BI.i18nText("BI-Less_Than")+")",iconClass:"less-font",value:0},{text:"("+BI.i18nText("BI-Less_And_Equal")+")",value:1,iconClass:"less-equal-font"}]}),c.closemax===!0?this.bigCombo.setValue(1):this.bigCombo.setValue(0),this.label=BI.createWidget({type:"bi.label",text:BI.i18nText("BI-Basic_Value"),textHeight:c.height-2*b.border,width:b.width-2*b.border,height:c.height-2*b.border,level:"warning",tipType:"warning"}),this.left=BI.createWidget({type:"bi.htape",items:[{el:a.smallEditor},{el:a.smallCombo,width:b.width-2*b.border}]}),this.right=BI.createWidget({type:"bi.htape",items:[{el:a.bigCombo,width:b.width-2*b.border},{el:a.bigEditor}]}),BI.createWidget({element:a,type:"bi.center",hgap:15,height:c.height,items:[{type:"bi.absolute",items:[{el:a.left,left:-15,right:0,top:0,bottom:0}]},{type:"bi.absolute",items:[{el:a.right,left:0,right:-15,top:0,bottom:0}]}]}),BI.createWidget({element:a,type:"bi.horizontal_auto",items:[a.label]}),a._setValidEvent(a.bigEditor,b.bigEditor),a._setValidEvent(a.smallEditor,b.smallEditor),a._setErrorEvent(a.bigEditor,b.bigEditor),a._setErrorEvent(a.smallEditor,b.smallEditor),a._setBlurEvent(a.bigEditor),a._setBlurEvent(a.smallEditor),a._setFocusEvent(a.bigEditor),a._setFocusEvent(a.smallEditor),a._setComboValueChangedEvent(a.bigCombo),a._setComboValueChangedEvent(a.smallCombo),a._setEditorValueChangedEvent(a.bigEditor),a._setEditorValueChangedEvent(a.smallEditor)},_checkValidation:function(){var a=this,b=this.constants,c=this.options;if(a._setTitle(""),BI.Bubbles.hide(b.typeError),BI.Bubbles.hide(b.numberError),BI.Bubbles.hide(b.signalError),!a.smallEditor.isValid()||!a.bigEditor.isValid())return a.element.removeClass("number-error"),c.validation="invalid",b.typeError;if(BI.isEmptyString(a.smallEditor.getValue())||BI.isEmptyString(a.bigEditor.getValue()))return a.element.removeClass("number-error"),c.validation="valid","";var d=parseFloat(a.smallEditor.getValue()),e=parseFloat(a.bigEditor.getValue()),f=a.bigCombo.getValue(),g=a.smallCombo.getValue();return f[0]===b.less_equal&&g[0]===b.less_equal?d>e?(a.element.addClass("number-error"),c.validation="invalid",b.numberError):(a.element.removeClass("number-error"),c.validation="valid",""):d>e?(a.element.addClass("number-error"),c.validation="invalid",b.numberError):d===e?(a.element.addClass("number-error"),c.validation="invalid",b.signalError):(a.element.removeClass("number-error"),c.validation="valid","")},_setTitle:function(a){var b=this;b.bigEditor.setTitle(a),b.smallEditor.setTitle(a),b.label.setTitle(a)},_setFocusEvent:function(a){var b=this,c=this.constants;a.on(BI.Editor.EVENT_FOCUS,function(){switch(b._setTitle(""),b._checkValidation()){case c.typeError:BI.Bubbles.show(c.typeError,BI.i18nText("BI-Numerical_Interval_Input_Data"),b,{offsetStyle:"center"});break;case c.numberError:BI.Bubbles.show(c.numberError,BI.i18nText("BI-Numerical_Interval_Number_Value"),b,{offsetStyle:"center"});break;case c.signalError:BI.Bubbles.show(c.signalError,BI.i18nText("BI-Numerical_Interval_Signal_Value"),b,{offsetStyle:"center"});break;default:return}})},_setBlurEvent:function(a){var b=this.constants,c=this;a.on(BI.Editor.EVENT_BLUR,function(){switch(BI.Bubbles.hide(b.typeError),BI.Bubbles.hide(b.numberError),BI.Bubbles.hide(b.signalError),c._checkValidation()){case b.typeError:c._setTitle(BI.i18nText("BI-Numerical_Interval_Input_Data"));break;case b.numberError:c._setTitle(BI.i18nText("BI-Numerical_Interval_Number_Value"));break;case b.signalError:c._setTitle(BI.i18nText("BI-Numerical_Interval_Signal_Value"));break;default:c._setTitle("")}})},_setErrorEvent:function(a){var b=this.constants,c=this;a.on(BI.Editor.EVENT_ERROR,function(){c._checkValidation(),BI.Bubbles.show(b.typeError,BI.i18nText("BI-Numerical_Interval_Input_Data"),c,{offsetStyle:"center"}),c.fireEvent(BI.NumberInterval.EVENT_ERROR)})},_setValidEvent:function(a){var b=this,c=this.constants;a.on(BI.Editor.EVENT_VALID,function(){switch(b._checkValidation()){case c.numberError:BI.Bubbles.show(c.numberError,BI.i18nText("BI-Numerical_Interval_Number_Value"),b,{offsetStyle:"center"}),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;case c.signalError:BI.Bubbles.show(c.signalError,BI.i18nText("BI-Numerical_Interval_Signal_Value"),b,{offsetStyle:"center"}),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;default:b.fireEvent(BI.NumberInterval.EVENT_VALID)}})},_setEditorValueChangedEvent:function(a){var b=this,c=this.constants;a.on(BI.Editor.EVENT_CHANGE,function(){switch(b._checkValidation()){case c.typeError:BI.Bubbles.show(c.typeError,BI.i18nText("BI-Numerical_Interval_Input_Data"),b,{offsetStyle:"center"});break;case c.numberError:BI.Bubbles.show(c.numberError,BI.i18nText("BI-Numerical_Interval_Number_Value"),b,{offsetStyle:"center"});break;case c.signalError:BI.Bubbles.show(c.signalError,BI.i18nText("BI-Numerical_Interval_Signal_Value"),b,{offsetStyle:"center"})}b.fireEvent(BI.NumberInterval.EVENT_CHANGE)})},_setComboValueChangedEvent:function(a){var b=this,c=this.constants;a.on(BI.IconCombo.EVENT_CHANGE,function(){switch(b._checkValidation()){case c.typeError:b._setTitle(BI.i18nText("BI-Numerical_Interval_Input_Data")),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;case c.numberError:b._setTitle(BI.i18nText("BI-Numerical_Interval_Number_Value")),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;case c.signalError:b._setTitle(BI.i18nText("BI-Numerical_Interval_Signal_Value")),b.fireEvent(BI.NumberInterval.EVENT_ERROR);break;default:b.fireEvent(BI.NumberInterval.EVENT_CHANGE),b.fireEvent(BI.NumberInterval.EVENT_VALID)}})},isStateValid:function(){return"valid"===this.options.validation},setMinEnable:function(a){this.smallEditor.setEnable(a)},setCloseMinEnable:function(a){this.smallCombo.setEnable(a)},setMaxEnable:function(a){this.bigEditor.setEnable(a)},setCloseMaxEnable:function(a){this.bigCombo.setEnable(a)},showNumTip:function(){this.smallTip.setVisible(!0),this.bigTip.setVisible(!0)},hideNumTip:function(){this.smallTip.setVisible(!1),this.bigTip.setVisible(!1)},setNumTip:function(a){this.smallTip.setText(a),this.bigTip.setText(a)},getNumTip:function(){return this.smallTip.getText()},setValue:function(a){a=a||{};var b,c=this;(BI.isNumeric(a.min)||BI.isEmptyString(a.min))&&c.smallEditor.setValue(a.min),BI.isNotNull(a.min)||c.smallEditor.setValue(""),(BI.isNumeric(a.max)||BI.isEmptyString(a.max))&&c.bigEditor.setValue(a.max),BI.isNotNull(a.max)||c.bigEditor.setValue(""),BI.isNull(a.closemin)||(b=a.closemin===!0?1:0,c.smallCombo.setValue(b)),BI.isNull(a.closemax)||(b=a.closemax===!0?1:0,c.bigCombo.setValue(b))},getValue:function(){var a=this,b={},c=a.smallCombo.getValue(),d=a.bigCombo.getValue();return b.min=a.smallEditor.getValue(),b.max=a.bigEditor.getValue(),0===c[0]?b.closemin=!1:b.closemin=!0,0===d[0]?b.closemax=!1:b.closemax=!0,b}}),BI.NumberInterval.EVENT_CHANGE="EVENT_CHANGE",BI.NumberInterval.EVENT_VALID="EVENT_VALID",BI.NumberInterval.EVENT_ERROR="EVENT_ERROR",BI.shortcut("bi.number_interval",BI.NumberInterval),BI.PageTableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.PageTableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-page-table-cell",text:"",title:""})},_init:function(){BI.PageTableCell.superclass._init.apply(this,arguments);BI.createWidget({type:"bi.label",element:this,textAlign:"left",whiteSpace:"nowrap",height:this.options.height,text:this.options.text,title:this.options.title,value:this.options.value,lgap:5,rgap:5});BI.isNotNull(this.options.styles)&&BI.isObject(this.options.styles)&&this.element.css(this.options.styles)}}),BI.shortcut("bi.page_table_cell",BI.PageTableCell),BI.PageTable=BI.inherit(BI.Widget,{_const:{scrollWidth:18,minScrollWidth:100},_defaultConfig:function(){return BI.extend(BI.PageTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-page-table",el:{type:"bi.sequence_table"},pager:{horizontal:{pages:!1,curr:1,hasPrev:BI.emptyFn,hasNext:BI.emptyFn,firstPage:1,lastPage:BI.emptyFn},vertical:{pages:!1,curr:1,hasPrev:BI.emptyFn,hasNext:BI.emptyFn,firstPage:1,lastPage:BI.emptyFn}},itemsCreator:BI.emptyFn,isNeedFreeze:!1,freezeCols:[],isNeedMerge:!1,mergeCols:[],mergeRule:BI.emptyFn,columnSize:[],minColumnSize:[],maxColumnSize:[],headerRowSize:25,rowSize:25,regionColumnSize:[],headerCellStyleGetter:BI.emptyFn,summaryCellStyleGetter:BI.emptyFn,sequenceCellStyleGetter:BI.emptyFn,header:[],items:[],crossHeader:[],crossItems:[]})},_init:function(){BI.PageTable.superclass._init.apply(this,arguments);var a=this,b=this.options;this.hCurr=1,this.vCurr=1,this.table=BI.createWidget(b.el,{type:"bi.sequence_table",width:b.width,height:b.height&&b.height-30,isNeedResize:!0,isResizeAdapt:!1,isNeedFreeze:b.isNeedFreeze,freezeCols:b.freezeCols,isNeedMerge:b.isNeedMerge,mergeCols:b.mergeCols,mergeRule:b.mergeRule,columnSize:b.columnSize,minColumnSize:b.minColumnSize,maxColumnSize:b.maxColumnSize,headerRowSize:b.headerRowSize,rowSize:b.rowSize,regionColumnSize:b.regionColumnSize,headerCellStyleGetter:b.headerCellStyleGetter,summaryCellStyleGetter:b.summaryCellStyleGetter,sequenceCellStyleGetter:b.sequenceCellStyleGetter,header:b.header,items:b.items,crossHeader:b.crossHeader,crossItems:b.crossItems}),this.table.on(BI.Table.EVENT_TABLE_SCROLL,function(){a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.table.on(BI.Table.EVENT_TABLE_AFTER_REGION_RESIZE,function(){b.regionColumnSize=this.getRegionColumnSize(),b.columnSize=this.getColumnSize(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_REGION_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE,function(){b.regionColumnSize=this.getRegionColumnSize(),b.columnSize=this.getColumnSize(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE,arguments)}),this.pager=BI.createWidget(b.pager,{type:"bi.direction_pager",height:30}),this.pager.on(BI.Pager.EVENT_CHANGE,function(){var c=this.getVPage&&this.getVPage();BI.isNull(c)&&(c=this.getCurrentPage());var d=this.getHPage&&this.getHPage();b.itemsCreator({vpage:c,hpage:d},function(b,e,f,g){a.table.setVPage?a.table.setVPage(c):a.table.setValue(c),a.table.setHPage&&a.table.setHPage(d),a.populate.apply(a,arguments)})}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.table,left:0,top:0},{el:this.pager,left:0,right:0,bottom:0}]})},setHPage:function(a){this.hCurr=a,this.pager.setHPage&&this.pager.setHPage(a),this.table.setHPage&&this.table.setHPage(a)},setVPage:function(a){this.vCurr=a,this.pager.setVPage&&this.pager.setVPage(a),this.table.setVPage&&this.table.setVPage(a)},getHPage:function(){var a=this.pager.getHPage&&this.pager.getHPage();return BI.isNotNull(a)?a:(a=this.pager.getCurrentPage&&this.pager.getCurrentPage(),BI.isNotNull(a)?a:this.hpage)},getVPage:function(){var a=this.pager.getVPage&&this.pager.getVPage();return BI.isNotNull(a)?a:(a=this.pager.getCurrentPage&&this.pager.getCurrentPage(),BI.isNotNull(a)?a:this.vpage)},setWidth:function(a){BI.PageTable.superclass.setWidth.apply(this,arguments),this.table.setWidth(a)},setHeight:function(a){BI.PageTable.superclass.setHeight.apply(this,arguments);var b=!1;this.pager.alwaysShowPager?b=!0:this.pager.hasHNext&&this.pager.hasHNext()?b=!0:this.pager.hasHPrev&&this.pager.hasHPrev()?b=!0:this.pager.hasVNext&&this.pager.hasVNext()?b=!0:this.pager.hasVPrev&&this.pager.hasVPrev()?b=!0:this.pager.hasNext&&this.pager.hasNext()?b=!0:this.pager.hasPrev&&this.pager.hasPrev()&&(b=!0),this.table.setHeight(a-(b?30:0))},setColumnSize:function(a){this.options.columnSize=a,this.table.setColumnSize(a)},getColumnSize:function(){return this.table.getColumnSize()},setRegionColumnSize:function(a){this.options.columnSize=a,this.table.setRegionColumnSize(a)},getRegionColumnSize:function(){return this.table.getRegionColumnSize()},getVerticalScroll:function(){return this.table.getVerticalScroll()},setLeftHorizontalScroll:function(a){this.table.setLeftHorizontalScroll(a)},setRightHorizontalScroll:function(a){this.table.setRightHorizontalScroll(a)},setVerticalScroll:function(a){this.table.setVerticalScroll(a)},restore:function(){this.table.restore()},attr:function(){BI.PageTable.superclass.attr.apply(this,arguments),this.table.attr.apply(this.table,arguments)},populate:function(){this.pager.populate(),this.table.populate.apply(this.table,arguments)},destroy:function(){this.table.destroy(),this.pager&&this.pager.destroy(),BI.PageTable.superclass.destroy.apply(this,arguments)}}),BI.shortcut("bi.page_table",BI.PageTable),BI.PathChooser=BI.inherit(BI.Widget,{_const:{lineColor:"#d4dadd",selectLineColor:"#3f8ce8"},_defaultConfig:function(){return BI.extend(BI.PathChooser.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-path-chooser",items:[]})},_init:function(){BI.PathChooser.superclass._init.apply(this,arguments),this.populate(this.options.items)},_createRegions:function(a){var b=this;this.regions=BI.createWidgets(BI.map(a,function(a,c){return{type:"bi.path_region",title:b.texts[c]||c}})),this.regionMap={},BI.each(a,function(a,c){b.regionMap[c]=a}),this.container=BI.createWidget({type:"bi.horizontal",verticalAlign:"top",scrollx:!1,scrolly:!1,hgap:10,items:this.regions}),BI.createWidget({type:"bi.vertical_adapt",element:this,scrollable:!0,hgap:10,items:[this.container]})},getRegionIndexById:function(a){var b=this.cache[a],c=b.get("region");return this.regionMap[c]},_drawPath:function(a,b,c){var d=this,e=[];e=BI.contains(this.start,a)?this.start:[a],BI.each(e,function(a,b){BI.each(d.radios[b],function(a,b){b.setSelected(!1)}),BI.each(d.lines[b],function(a,b){b.attr("stroke",d._const.lineColor)}),BI.each(d.regionIndexes[b],function(a,b){d.regions[b].reset()})}),BI.each(this.routes[a][c],function(a,e){var f=d.getRegionIndexById(e);d.regions[f].setSelect(b+c,e)});for(var f=BI.last(this.routes[a][c]);f&&this.routes[f]&&1===this.routes[f].length;)BI.each(this.routes[f][0],function(a,b){var c=d.getRegionIndexById(b);d.regions[c].setSelect(0,b)}),this.lines[f][0].attr("stroke",d._const.selectLineColor).toFront(),f=BI.last(this.routes[f][0]);this.lines[a][c].attr("stroke",d._const.selectLineColor).toFront(),this.radios[a]&&this.radios[a][c]&&this.radios[a][c].setSelected(!0)},_drawRadio:function(a,b,c,d,e){var f=this,g=BI.createWidget({type:"bi.radio",cls:"path-chooser-radio",selected:b+c===0,start:a,index:c});g.on(BI.Radio.EVENT_CHANGE,function(){f._drawPath(a,b,c),f.fireEvent(BI.PathChooser.EVENT_CHANGE,a,c)}),this.radios[a]||(this.radios[a]=[]),this.radios[a].push(g),BI.createWidget({type:"bi.absolute",element:this.container,items:[{el:g,left:d-6.5,top:e-6.5}]})},_drawLine:function(a,b){var c=this;this.lines[a]||(this.lines[a]=[]),this.pathes[a]||(this.pathes[a]=[]);var d=this.getRegionIndexById(a),e=this.regions[d].getIndexByValue(a);BI.each(b,function(f,g){c.pathes[a][f]=[];var h=f+e,i="",j=47.5+29*h,k=50+100*d,l=k,m=j,n=j,o=c.getRegionIndexById(BI.last(g)),p=c.regions[o].getIndexByValue(BI.last(g)),q=50+100*o;if(BI.contains(c.start,a)?(l=k-50,i+="M"+(k-50)+","+j,c.pathes[a][f].push({x:k-50,y:j})):0===h?(l=k+50,i+="M"+k+","+j,c.pathes[a][f].push({x:k,y:j})):(l=k+50,i+="M"+k+",47.5L"+(k+50)+",47.5L"+(k+50)+","+j,c.pathes[a][f].push({x:k,y:47.5}),c.pathes[a][f].push({x:k+50,y:47.5}),c.pathes[a][f].push({x:k+50,y:j})),h>0){var r=29*p+47.5;i+="L"+(q-50)+","+n+"L"+(q-50)+","+r+"L"+q+","+r,c.pathes[a][f].push({x:q-50,y:n}),c.pathes[a][f].push({x:q-50,y:r}),c.pathes[a][f].push({x:q,y:r})}else i+="L"+q+","+n,c.pathes[a][f].push({x:q,y:n});var s=c.svg.path(i).attr({stroke:0===h?c._const.selectLineColor:c._const.lineColor,"stroke-dasharray":"-"});c.lines[a].push(s),b.length>1&&c.lines[a][0].toFront(),BI.contains(c.start,a)&&c.lines[c.regions[0].getValueByIndex(0)][0].toFront(),(b.length>1||BI.contains(c.start,a))&&c._drawRadio(a,e,f,l,m)})},_drawLines:function(a){var b=this;this.lines={},this.pathes={},this.radios={},this.regionIndexes={},BI.each(a,function(a,c){b.regionIndexes[a]||(b.regionIndexes[a]=[]),BI.each(c,function(c,d){BI.each(d,function(c,d){var e=b.getRegionIndexById(d);BI.contains(b.regionIndexes[a],e)||b.regionIndexes[a].push(e)})})}),BI.each(a,function(a,c){b._drawLine(a,c)})},_pushNodes:function(a){for(var b=this,c=[],d=0;d0||BI.contains(b.start,e))&&g.addItem(e,b.texts[e])}for(var d=BI.first(c);d0&&(h=c[b-1]);var i=a.cache[h.value||""],j=a.cache[g.value]||new BI.Node(g.value);j.set(g),a.cache[g.value]=j,a.texts[g.value]=g.text,a.texts[g.region]=g.regionText,i=BI.isNull(i)?d.getRoot():i, i.getChildIndex(g.value)===-1&&d.addNode(i,j)})}),d.traverse(function(a){BI.each(a.getChildren(),function(b,d){if(BI.contains(c,d.get("region"))){var e=BI.indexOf(c,a.get("region")),f=BI.indexOf(c,d.get("region"));if(e>f){for(var g=c[f],h=f;h0&&(e.push(c),d.push(e),e=[]),e.push(c)}),e.length>0&&d.push(e),BI.each(d,function(a,b){var d=b[0],e=BI.findIndex(c.routes[d],function(a,c){if(BI.isEqual(b,c))return!0});if(e>=0){var f=c.getRegionIndexById(d),g=c.regions[f].getIndexByValue(d);c._drawPath(d,g,e)}})},getValue:function(){var a=[];return BI.each(this.regions,function(b,c){var d=c.getValue();BI.isKey(d)&&a.push(d)}),a}}),BI.PathChooser.EVENT_CHANGE="PathChooser.EVENT_CHANGE",BI.shortcut("bi.path_chooser",BI.PathChooser),BI.PathRegion=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.PathRegion.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-path-region bi-background",width:80,title:""})},_init:function(){BI.PathRegion.superclass._init.apply(this,arguments);var a=this.options;this.zIndex=100;var b=BI.createWidget({type:"bi.label",text:a.title,title:a.title,height:30});b.element.css("zIndex",this.zIndex--),this.items=[],this.vertical=BI.createWidget({type:"bi.vertical",element:this,bgap:5,hgap:10,items:[b]})},hasItem:function(a){return BI.any(this.items,function(b,c){return a===c.getValue()})},addItem:function(a,b){if(BI.isKey(a))var c=BI.createWidget({type:"bi.label",cls:"path-region-label bi-card bi-border bi-list-item-select",text:b,value:a,title:b||a,height:24});else var c=BI.createWidget({type:"bi.layout",height:24});c.element.css("zIndex",this.zIndex--),this.items.push(c),this.vertical.addItem(c),1===this.items.length&&this.setSelect(0,a)},reset:function(){BI.each(this.items,function(a,b){b.element.removeClass("active")})},setSelect:function(a,b){if(this.reset(),!(this.items.length<=0))return 1===this.items.length?void this.items[0].element.addClass("active"):void(this.items[a].attr("value")===b&&this.items[a].element.addClass("active"))},setValue:function(a){this.setSelect(this.getIndexByValue(a),a)},getValueByIndex:function(a){return this.items[a].attr("value")},getIndexByValue:function(a){return BI.findIndex(this.items,function(b,c){return c.attr("value")===a})},getValue:function(){var a;return BI.any(this.items,function(b,c){if(c.element.hasClass("active"))return a=c.getValue(),!0}),a}}),BI.PathRegion.EVENT_CHANGE="PathRegion.EVENT_CHANGE",BI.shortcut("bi.path_region",BI.PathRegion),BI.PreviewTableCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.PreviewTableCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-preview-table-cell",text:""})},_init:function(){BI.PreviewTableCell.superclass._init.apply(this,arguments);this.options;BI.createWidget({type:"bi.label",element:this,textAlign:"left",whiteSpace:"normal",height:this.options.height,text:this.options.text,value:this.options.value})}}),BI.shortcut("bi.preview_table_cell",BI.PreviewTableCell),BI.PreviewTableHeaderCell=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.PreviewTableHeaderCell.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-preview-table-header-cell",text:""})},_init:function(){BI.PreviewTableHeaderCell.superclass._init.apply(this,arguments);this.options;BI.createWidget({type:"bi.label",element:this,textAlign:"left",whiteSpace:"normal",height:this.options.height,text:this.options.text,value:this.options.value})}}),BI.shortcut("bi.preview_table_header_cell",BI.PreviewTableHeaderCell),BI.PreviewTable=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.PreviewTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-preview-table",isNeedFreeze:!1,freezeCols:[],rowSize:null,columnSize:[],headerRowSize:30,header:[],items:[]})},_init:function(){BI.PreviewTable.superclass._init.apply(this,arguments);var a=this,b=this.options;this.table=BI.createWidget({type:"bi.table_view",element:this,isNeedResize:!1,isResizeAdapt:!1,isNeedFreeze:b.isNeedFreeze,freezeCols:b.freezeCols,rowSize:b.rowSize,columnSize:b.columnSize,headerRowSize:b.headerRowSize,header:BI.map(b.header,function(a,b){return BI.map(b,function(a,b){return BI.extend({type:"bi.preview_table_header_cell"},b)})}),items:BI.map(b.items,function(a,b){return BI.map(b,function(a,b){return BI.extend({type:"bi.preview_table_cell"},b)})})}),this.table.on(BI.Table.EVENT_TABLE_AFTER_INIT,function(){a._adjustColumns(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_INIT,arguments)}),this.table.on(BI.Table.EVENT_TABLE_RESIZE,function(){a._adjustColumns()})},_hasAdaptCol:function(a){return BI.any(a,function(a,b){return""===b})},_isPercentage:function(a){return a[0]<=1},_adjustColumns:function(){var a=this.options;if(a.isNeedFreeze===!0){if(this._isPercentage(a.columnSize)){if(this._hasAdaptCol(a.columnSize)){var b=[],c=0;BI.each(a.columnSize,function(a,d){""===d?b.push(a):c+=d}),c=1-c;var d=c/b.length;BI.each(b,function(b,c){a.columnSize[c]=d})}var e=0!==BI.first(a.freezeCols),f=[],g=[];BI.each(a.columnSize,function(b,c){a.freezeCols.contains(b)?f.push(c):g.push(c)});var h=BI.sum(f),i=BI.sum(g);BI.each(f,function(a,b){f[a]=b/h}),BI.each(g,function(a,b){g[a]=b/i}),this.table.setRegionColumnSize(e?["fill",h]:[h,"fill"]),this.table.setColumnSize(e?g.concat(f):f.concat(g))}}else(this._hasAdaptCol(a.columnSize)||this._isPercentage(a.columnSize))&&this.table.setRegionColumnSize(["100%"])},setColumnSize:function(a){return this.table.setColumnSize(a)},getColumnSize:function(){return this.table.getColumnSize()},getCalculateColumnSize:function(){return this.table.getCalculateColumnSize()},setHeaderColumnSize:function(a){return this.table.setHeaderColumnSize(a)},setRegionColumnSize:function(a){return this.table.setRegionColumnSize(a)},getRegionColumnSize:function(){return this.table.getRegionColumnSize()},getCalculateRegionColumnSize:function(){return this.table.getCalculateRegionColumnSize()},getCalculateRegionRowSize:function(){return this.table.getCalculateRegionRowSize()},getClientRegionColumnSize:function(){return this.table.getClientRegionColumnSize()},getScrollRegionColumnSize:function(){return this.table.getScrollRegionColumnSize()},getScrollRegionRowSize:function(){return this.table.getScrollRegionRowSize()},hasVerticalScroll:function(){return this.table.hasVerticalScroll()},setVerticalScroll:function(a){return this.table.setVerticalScroll(a)},setLeftHorizontalScroll:function(a){return this.table.setLeftHorizontalScroll(a)},setRightHorizontalScroll:function(a){return this.table.setRightHorizontalScroll(a)},getVerticalScroll:function(){return this.table.getVerticalScroll()},getLeftHorizontalScroll:function(){return this.table.getLeftHorizontalScroll()},getRightHorizontalScroll:function(){return this.table.getRightHorizontalScroll()},getColumns:function(){return this.table.getColumns()},populate:function(a,b){this.table.populate(a,b)}}),BI.PreviewTable.EVENT_CHANGE="PreviewTable.EVENT_CHANGE",BI.shortcut("bi.preview_table",BI.PreviewTable),BI.QuarterCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.QuarterCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-quarter-combo",behaviors:{},height:25})},_init:function(){BI.QuarterCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.storeValue="",this.trigger=BI.createWidget({type:"bi.quarter_trigger"}),this.trigger.on(BI.QuarterTrigger.EVENT_FOCUS,function(){a.storeValue=this.getKey()}),this.trigger.on(BI.QuarterTrigger.EVENT_START,function(){a.combo.isViewVisible()&&a.combo.hideView()}),this.trigger.on(BI.QuarterTrigger.EVENT_STOP,function(){a.combo.isViewVisible()||a.combo.showView()}),this.trigger.on(BI.QuarterTrigger.EVENT_CONFIRM,function(){a.combo.isViewVisible()||(this.getKey()&&this.getKey()!==a.storeValue?a.setValue(this.getKey()):this.getKey()||a.setValue(),a.fireEvent(BI.QuarterCombo.EVENT_CONFIRM))}),this.popup=BI.createWidget({type:"bi.quarter_popup",behaviors:b.behaviors}),this.popup.on(BI.QuarterPopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.combo.hideView(),a.fireEvent(BI.QuarterCombo.EVENT_CONFIRM)}),this.combo=BI.createWidget({type:"bi.combo",element:this,isNeedAdjustHeight:!1,isNeedAdjustWidth:!1,el:this.trigger,popup:{minWidth:85,el:this.popup}}),this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW,function(){a.fireEvent(BI.QuarterCombo.EVENT_BEFORE_POPUPVIEW)})},setValue:function(a){this.trigger.setValue(a),this.popup.setValue(a)},getValue:function(){return this.popup.getValue()||""}}),BI.QuarterCombo.EVENT_CONFIRM="EVENT_CONFIRM",BI.QuarterCombo.EVENT_BEFORE_POPUPVIEW="EVENT_BEFORE_POPUPVIEW",BI.shortcut("bi.quarter_combo",BI.QuarterCombo),BI.QuarterPopup=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.QuarterPopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-quarter-popup",behaviors:{}})},_init:function(){BI.QuarterPopup.superclass._init.apply(this,arguments);var a=this,b=this.options,c=[{text:Date._QN[1],value:1},{text:Date._QN[2],value:2},{text:Date._QN[3],value:3},{text:Date._QN[4],value:4}];c=BI.map(c,function(a,b){return BI.extend(b,{type:"bi.text_item",cls:"bi-list-item-active",textAlign:"left",whiteSpace:"nowrap",once:!1,forceSelected:!0,height:25})}),this.quarter=BI.createWidget({type:"bi.button_group",element:this,behaviors:b.behaviors,items:BI.createItems(c,{}),layouts:[{type:"bi.vertical"}]}),this.quarter.on(BI.Controller.EVENT_CHANGE,function(b){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments),b===BI.Events.CLICK&&a.fireEvent(BI.MonthPopup.EVENT_CHANGE)})},getValue:function(){return this.quarter.getValue()[0]},setValue:function(a){this.quarter.setValue([a])}}),BI.QuarterPopup.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.quarter_popup",BI.QuarterPopup),BI.QuarterTrigger=BI.inherit(BI.Trigger,{_const:{hgap:4,vgap:2,textWidth:40,errorText:BI.i18nText("BI-Quarter_Trigger_Error_Text")},_defaultConfig:function(){return BI.extend(BI.QuarterTrigger.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-quarter-trigger bi-border",height:24})},_init:function(){BI.QuarterTrigger.superclass._init.apply(this,arguments);var a=this,b=this.options,c=this._const;this.editor=BI.createWidget({type:"bi.sign_editor",height:b.height,validationChecker:function(a){return""===a||BI.isPositiveInteger(a)&&a>=1&&a<=4},quitChecker:function(a){return!1},hgap:c.hgap,vgap:c.vgap,allowBlank:!0,errorText:c.errorText}),this.editor.on(BI.SignEditor.EVENT_FOCUS,function(){a.fireEvent(BI.QuarterTrigger.EVENT_FOCUS)}),this.editor.on(BI.SignEditor.EVENT_CHANGE,function(){a.fireEvent(BI.QuarterTrigger.EVENT_CHANGE)}),this.editor.on(BI.SignEditor.EVENT_CONFIRM,function(){var b=a.editor.getValue();BI.isNotNull(b)&&(a.editor.setValue(b),a.editor.setTitle(b)),a.fireEvent(BI.QuarterTrigger.EVENT_CONFIRM)}),this.editor.on(BI.SignEditor.EVENT_SPACE,function(){a.editor.isValid()&&a.editor.blur()}),this.editor.on(BI.SignEditor.EVENT_START,function(){a.fireEvent(BI.QuarterTrigger.EVENT_START)}),this.editor.on(BI.SignEditor.EVENT_STOP,function(){a.fireEvent(BI.QuarterTrigger.EVENT_STOP)}),BI.createWidget({element:this,type:"bi.htape",items:[{el:this.editor},{el:{type:"bi.text_button",baseCls:"bi-trigger-quarter-text",text:BI.i18nText("BI-Multi_Date_Quarter"),width:c.textWidth},width:c.textWidth},{el:{type:"bi.trigger_icon_button",width:b.height},width:b.height}]})},setValue:function(a){a=a||"",this.editor.setState(a),this.editor.setValue(a),this.editor.setTitle(a)},getKey:function(){return this.editor.getValue()}}),BI.QuarterTrigger.EVENT_FOCUS="EVENT_FOCUS",BI.QuarterTrigger.EVENT_CHANGE="EVENT_CHANGE",BI.QuarterTrigger.EVENT_START="EVENT_START",BI.QuarterTrigger.EVENT_STOP="EVENT_STOP",BI.QuarterTrigger.EVENT_CONFIRM="EVENT_CONFIRM",BI.shortcut("bi.quarter_trigger",BI.QuarterTrigger),BI.RelationViewItem=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.RelationViewItem.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-relation-view-item bi-list-item-active",height:25,hoverIn:BI.emptyFn,hoverOut:BI.emptyFn})},_init:function(){BI.RelationViewItem.superclass._init.apply(this,arguments);var a=this.options;this.element.hover(a.hoverIn,a.hoverOut);var b=[];a.isPrimary&&b.push({type:"bi.icon",width:16,height:16,title:BI.i18nText("BI-Primary_Key")}),b.push({type:"bi.label",text:a.text,value:a.value,height:a.height,textAlign:"left",width:a.isPrimary?70:90,lgap:a.isPrimary?0:10}),BI.createWidget({type:"bi.vertical_adapt",element:this,items:b,cls:"primary-key-font",lgap:5})},enableHover:function(a){BI.RelationViewRegion.superclass.enableHover.apply(this,[{container:"body"}])},setSelected:function(a){this.element[a?"addClass":"removeClass"]("active")}}),BI.shortcut("bi.relation_view_item",BI.RelationViewItem),BI.RelationView=BI.inherit(BI.Widget,{_const:{lineColor:"#c4c6c6",selectLineColor:"#009de3"},_defaultConfig:function(){return BI.extend(BI.RelationView.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-relation-view",items:[]})},_init:function(){BI.RelationView.superclass._init.apply(this,arguments),this.populate(this.options.items)},_calculateWidths:function(){var a=[];return BI.each(this.views,function(b,c){BI.each(c,function(b,c){a[b]||(a[b]=BI.MIN),a[b]=Math.max(a[b],c.getWidth())})}),a},_calculateHeights:function(){var a=BI.makeArray(BI.size(this.views),BI.MIN);return BI.each(this.views,function(b,c){BI.each(c,function(c,d){a[b]=Math.max(a[b],d.getHeight())})}),a},_hoverIn:function(a){var b=this,c=this._const;BI.each(this.relations,function(d,e){BI.each(e,function(e,f){f[0].primary.value!==a&&f[0].foreign.value!==a||(b.lines[d][e].attr("stroke",c.selectLineColor).toFront(),b.storeViews[d].setValue(f[0].primary.value),b.storeViews[e].setValue(f[0].foreign.value))})})},_hoverOut:function(a){var b=this,c=this._const;BI.each(this.relations,function(d,e){BI.each(e,function(e,f){f[0].primary.value!==a&&f[0].foreign.value!==a||(b.lines[d][e].attr("stroke",c.lineColor),b.storeViews[d].setValue([]),b.storeViews[e].setValue([]))})})},previewRelationTables:function(a,b){return b?(BI.each(this.storeViews,function(b,c){a.contains(b)?c.setPreviewSelected(!0):c.toggleRegion(!1)}),void BI.each(this.lines,function(b,c){BI.each(c,function(c,d){a.contains(b)&&a.contains(c)||d.hide()})})):(BI.each(this.storeViews,function(a,b){b.toggleRegion(!0),b.setPreviewSelected(!1)}),void BI.each(this.lines,function(a,b){BI.each(b,function(a,b){b.show()})}))},populate:function(a){var b=this,c=this.options,d=this._const;c.items=a||[],this.empty(),this.svg=BI.createWidget({type:"bi.svg"});var e=this.regions={},f=this.relations={};BI.each(a,function(a,b){var c=b.primary.region,d=b.foreign&&b.foreign.region;c&&!f[c]&&(f[c]={}),c&&d&&!f[c][d]&&(f[c][d]=[]),c&&!e[c]&&(e[c]=[]),d&&!e[d]&&(e[d]=[]),c&&!BI.deepContains(e[c],b.primary)&&e[c].push(b.primary),d&&!BI.deepContains(e[d],b.foreign)&&e[d].push(b.foreign),c&&d&&f[c][d].push(b)});for(var g=[],h=BI.clone(e),i={};!BI.isEmpty(h);){var j=BI.clone(h);BI.each(c.items,function(a,b){i[b.primary.region]||delete j[b.foreign&&b.foreign.region]}),g.push(BI.keys(j)),BI.extend(i,j),BI.each(j,function(a,b){delete h[a]})}var k=this.views={},l=this.storeViews={},m=this.indexes={},n=[];BI.each(g,function(a,c){k[a]||(k[a]={});var d=[];BI.each(c,function(c,f){var g=e[f];k[a][c]=l[f]=BI.createWidget({type:"bi.relation_view_region_container",value:f,header:g[0].regionTitle,text:g.length>0?g[0].regionText:"",handler:g.length>0?g[0].regionHandler:BI.emptyFn,items:g,belongPackage:!(g.length>0)||g[0].belongPackage}),BI.isNotNull(g[0])&&BI.isNotNull(g[0].keyword)&&k[a][c].doRedMark(g[0].keyword),k[a][c].on(BI.RelationViewRegionContainer.EVENT_HOVER_IN,function(a){b._hoverIn(a)}),k[a][c].on(BI.RelationViewRegionContainer.EVENT_HOVER_OUT,function(a){b._hoverOut(a)}),k[a][c].on(BI.RelationViewRegionContainer.EVENT_PREVIEW,function(a){b.fireEvent(BI.RelationView.EVENT_PREVIEW,f,a)}),m[f]={i:a,j:c},d.push(k[a][c])}),n.push({type:"bi.horizontal",items:d})});var o=this._calculateHeights(),p=this._calculateWidths(),q=[0],r=[0];BI.each(o,function(a,b){0!==a&&(r[a]=r[a-1]+o[a-1])}),BI.each(p,function(a,b){0!==a&&(q[a]=q[a-1]+p[a-1])});var s=this.lines={};BI.each(f,function(a,c){BI.each(c,function(c,e){var f=m[a],g=m[c],h=0,i=1,j=2,n=3,t=j,u=h,v=function(a,b,c,d){var e,f=q[b]+(p[b]-k[a][b].getWidth())/2,g=r[a]+(o[a]-k[a][b].getHeight())/2,l="";switch(c){case h:e=d?k[a][b].getTopRightPosition():k[a][b].getTopLeftPosition(),f+=e.x,g+=e.y,l="M"+f+","+g+"L"+f+","+(g-10),g-=10;break;case i:e=k[a][b].getRightPosition(),f+=e.x,g+=e.y,l="M"+f+","+g+"L"+(f+10)+","+g,f+=10;break;case j:e=k[a][b].getBottomPosition(),f+=e.x,g+=e.y,l="M"+f+","+g+"L"+f+","+(g+10),g+=10;break;case n:e=k[a][b].getLeftPosition(),f+=e.x,g+=e.y,l="M"+f+","+g+"L"+(f-10)+","+g,f-=10}return{x:f,y:g,path:l}},w="",x=v(f.i,f.j,t),y=v(g.i,g.j,u,!0);w+=x.path+y.path,s[a]||(s[a]={}),w+="M"+x.x+","+x.y+"L"+y.x+","+y.y;var z=s[a][c]=b.svg.path(w).attr({stroke:d.lineColor,"stroke-width":"2"}).hover(function(){z.attr("stroke",d.selectLineColor).toFront(),l[a].setValue(e[0].primary.value),l[c].setValue(e[0].foreign.value)},function(){z.attr("stroke",d.lineColor),l[a].setValue([]),l[c].setValue([])})})});var t=BI.createWidget();BI.createWidget({type:"bi.vertical",element:t,items:n}),BI.createWidget({type:"bi.absolute",element:t,items:[{el:this.svg,left:0,right:0,top:0,bottom:0}]}),BI.createWidget({type:"bi.center_adapt",scrollable:!0,element:this,items:[t]})}}),BI.RelationView.EVENT_CHANGE="RelationView.EVENT_CHANGE",BI.RelationView.EVENT_PREVIEW="EVENT_PREVIEW",BI.shortcut("bi.relation_view",BI.RelationView),BI.RelationViewRegionContainer=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.RelationViewRegionContainer.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-relation-view-region-container",width:150})},_init:function(){BI.RelationViewRegionContainer.superclass._init.apply(this,arguments);var a=this,b=this.options;this.region=BI.createWidget({type:"bi.relation_view_region",value:b.value,header:b.header,text:b.text,handler:b.handler,items:b.items,belongPackage:b.belongPackage}),this.region.on(BI.RelationViewRegion.EVENT_PREVIEW,function(b){a.fireEvent(BI.RelationViewRegionContainer.EVENT_PREVIEW,b)}),this.region.on(BI.RelationViewRegion.EVENT_HOVER_IN,function(b){a.fireEvent(BI.RelationViewRegionContainer.EVENT_HOVER_IN,b)}),this.region.on(BI.RelationViewRegion.EVENT_HOVER_OUT,function(b){a.fireEvent(BI.RelationViewRegionContainer.EVENT_HOVER_OUT,b)}),BI.createWidget({type:"bi.vertical",element:this,items:[this.region],width:this.region.getWidth(),height:this.region.getHeight()})},doRedMark:function(){this.region.doRedMark.apply(this.region,arguments)},unRedMark:function(){this.region.unRedMark.apply(this.region,arguments)},getWidth:function(){return this.region.getWidth()},getHeight:function(){return this.region.getHeight()},getTopLeftPosition:function(){return this.region.getTopLeftPosition()},getTopRightPosition:function(){return this.region.getTopRightPosition()},getBottomPosition:function(){return this.region.getBottomPosition()},getLeftPosition:function(){return this.region.getLeftPosition()},getRightPosition:function(){return this.region.getRightPosition()},setValue:function(a){this.region.setValue(a)},toggleRegion:function(a){a===!0?this.region.element.fadeIn():this.region.element.fadeOut()},setPreviewSelected:function(a){this.region.setPreviewSelected(a)}}),BI.RelationViewRegionContainer.EVENT_HOVER_IN="RelationViewRegion.EVENT_HOVER_IN",BI.RelationViewRegionContainer.EVENT_HOVER_OUT="RelationViewRegion.EVENT_HOVER_OUT",BI.RelationViewRegionContainer.EVENT_PREVIEW="RelationViewRegion.EVENT_PREVIEW",BI.shortcut("bi.relation_view_region_container",BI.RelationViewRegionContainer),BI.RelationViewRegion=BI.inherit(BI.BasicButton,{_defaultConfig:function(){return BI.extend(BI.RelationViewRegion.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-relation-view-region cursor-pointer",width:150,text:"",value:"",header:"",items:[],belongPackage:!0})},_init:function(){BI.RelationViewRegion.superclass._init.apply(this,arguments);var a=this,b=this.options;this.preview=BI.createWidget({type:"bi.icon_button",cls:"relation-table-preview-font",width:25,height:25,stopPropagation:!0}),this.preview.on(BI.IconButton.EVENT_CHANGE,function(){a.fireEvent(BI.RelationViewRegion.EVENT_PREVIEW,this.isSelected())}),this.title=BI.createWidget({type:"bi.label",height:25,width:70,text:b.text,value:b.value,textAlign:"left"}),BI.isKey(b.header)&&this.title.setTitle(b.header,{container:"body"}),this.button_group=BI.createWidget({type:"bi.button_group",items:this._createItems(b.items),layouts:[{type:"bi.vertical"}]}),BI.createWidget({type:"bi.vertical",element:this,items:[{type:"bi.vertical",cls:"relation-view-region-container bi-card bi-border "+(b.belongPackage?"":"other-package"),items:[{type:"bi.vertical_adapt",cls:"relation-view-region-title bi-border-bottom",items:[this.preview,this.title]},this.button_group]}],hgap:25,vgap:20})},_createItems:function(a){var b=this;return BI.map(a,function(a,c){return BI.extend(c,{type:"bi.relation_view_item",hoverIn:function(){b.setValue(c.value),b.fireEvent(BI.RelationViewRegion.EVENT_HOVER_IN,c.value)},hoverOut:function(){b.setValue([]),b.fireEvent(BI.RelationViewRegion.EVENT_HOVER_OUT,c.value)}})})},doRedMark:function(){this.title.doRedMark.apply(this.title,arguments)},unRedMark:function(){this.title.unRedMark.apply(this.title,arguments)},getWidth:function(){return this.options.width},getHeight:function(){return 25*this.button_group.getAllButtons().length+25+40+3},getTopLeftPosition:function(){return{x:35,y:20}},getTopRightPosition:function(){return{x:this.getWidth()-25-10,y:20}},getBottomPosition:function(){return{x:35,y:this.getHeight()-20}},getLeftPosition:function(){return{x:25,y:30}},getRightPosition:function(){return{x:this.getWidth()-25,y:30}},setValue:function(a){this.button_group.setValue(a)},setPreviewSelected:function(a){this.preview.setSelected(a)}}),BI.RelationViewRegion.EVENT_HOVER_IN="RelationViewRegion.EVENT_HOVER_IN",BI.RelationViewRegion.EVENT_HOVER_OUT="RelationViewRegion.EVENT_HOVER_OUT",BI.RelationViewRegion.EVENT_PREVIEW="RelationViewRegion.EVENT_PREVIEW",BI.shortcut("bi.relation_view_region",BI.RelationViewRegion),BI.ResponisveTable=BI.inherit(BI.Widget,{_const:{perColumnSize:100},_defaultConfig:function(){return BI.extend(BI.ResponisveTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-responsive-table",isNeedFreeze:!1,freezeCols:[],isNeedMerge:!1,mergeCols:[],mergeRule:function(a,b){return BI.isEqual(a,b)},columnSize:[],headerRowSize:25,footerRowSize:25,rowSize:25,regionColumnSize:!1,header:[],footer:!1,items:[],crossHeader:[],crossItems:[]})},_init:function(){BI.ResponisveTable.superclass._init.apply(this,arguments);var a=this,b=this.options;this.table=BI.createWidget({type:"bi.table_view",element:this,isNeedFreeze:b.isNeedFreeze,freezeCols:b.freezeCols,isNeedMerge:b.isNeedMerge,mergeCols:b.mergeCols,mergeRule:b.mergeRule,columnSize:b.columnSize,headerRowSize:b.headerRowSize,footerRowSize:b.footerRowSize,rowSize:b.rowSize,regionColumnSize:b.regionColumnSize,header:b.header,footer:b.footer,items:b.items,crossHeader:b.crossHeader,crossItems:b.crossItems}),this.table.on(BI.Table.EVENT_TABLE_AFTER_INIT,function(){a._initRegionSize(),a.table.resize(),a._resizeHeader(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_INIT,arguments)}),this.table.on(BI.Table.EVENT_TABLE_RESIZE,function(){a._resizeRegion(),a._resizeHeader(),a.fireEvent(BI.Table.EVENT_TABLE_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_SCROLL,function(){a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.table.on(BI.Table.EVENT_TABLE_BEFORE_REGION_RESIZE,function(){a.fireEvent(BI.Table.EVENT_TABLE_BEFORE_REGION_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_REGION_RESIZE,function(){b.isNeedResize===!0&&a._isAdaptiveColumn()&&a._resizeHeader(),a.fireEvent(BI.Table.EVENT_TABLE_REGION_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_AFTER_REGION_RESIZE,function(){a._resizeHeader(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_REGION_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_BEFORE_COLUMN_RESIZE,function(){a._resizeBody(),a.fireEvent(BI.Table.EVENT_TABLE_BEFORE_COLUMN_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_COLUMN_RESIZE,function(){a.fireEvent(BI.Table.EVENT_TABLE_COLUMN_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE,function(){a._resizeRegion(),a._resizeHeader(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE,arguments)})},_initRegionSize:function(){var a=this.options;if(a.isNeedFreeze===!0){var b=this.table.getRegionColumnSize(),c=this.table.element.width();if(!b[0]||"fill"===b[0]||b[0]>c||b[1]>c){var d=a.freezeCols;if(0===d.length)this.table.setRegionColumnSize([0,"fill"]);else if(d.length>0&&d.lengtha.columnSize.length/2&&(e=2*c/3),this.table.setRegionColumnSize([e,"fill"])}else this.table.setRegionColumnSize(["fill",0])}}},_getBlockSize:function(){var a=this.options,b=this.table.getCalculateColumnSize();if(a.isNeedFreeze===!0){var c=[],d=[];BI.each(b,function(b,e){a.freezeCols.contains(b)?c.push(e):d.push(e)});var e=BI.sum(c)+c.length,f=BI.sum(d)+d.length;return{sumLeft:e,sumRight:f,left:c,right:d}}return{size:b,sum:BI.sum(b)+b.length}},_isAdaptiveColumn:function(a){return!(BI.last(a||this.table.getColumnSize())>1.05)},_resizeHeader:function(){var a=this,b=this.options;if(b.isNeedFreeze===!0)if(this._isAdaptiveColumn()){var c=this.table.getCalculateColumnSize();this.table.setHeaderColumnSize(c)}else{var d=this.table.getClientRegionColumnSize(),e=this._getBlockSize(),f=e.sumLeft,g=e.sumRight,h=e.left,i=e.right;h[h.length-1]+=d[0]-f,i[i.length-1]+=d[1]-g;var j=BI.clone(h),k=BI.clone(i);j[j.length-1]="",k[k.length-1]="",this.table.setColumnSize(j.concat(k)),e=a._getBlockSize(),h[h.length-1]0&&a.freezeCols.length=d+e)&&this.table.setRegionColumnSize([d,"fill"]),this._resizeRegion()}},_resizeRegion:function(){var a=this.options,b=this.table.getCalculateRegionColumnSize();if(a.isNeedFreeze===!0&&a.freezeCols.length>0&&a.freezeCols.lengtha.columnSize.length/2&&(e=2*c/3),this.table.setRegionColumnSize([e,"fill"])}}},resize:function(){this.table.resize(),this._resizeRegion(),this._resizeHeader()},setColumnSize:function(a){this.table.setColumnSize(a),this._adjustRegion(),this._resizeHeader()},getColumnSize:function(){return this.table.getColumnSize()},getCalculateColumnSize:function(){return this.table.getCalculateColumnSize()},setHeaderColumnSize:function(a){this.table.setHeaderColumnSize(a),this._adjustRegion(),this._resizeHeader()},setRegionColumnSize:function(a){this.table.setRegionColumnSize(a),this._resizeHeader()},getRegionColumnSize:function(){return this.table.getRegionColumnSize()},getCalculateRegionColumnSize:function(){return this.table.getCalculateRegionColumnSize()},getCalculateRegionRowSize:function(){return this.table.getCalculateRegionRowSize()},getClientRegionColumnSize:function(){return this.table.getClientRegionColumnSize()},getScrollRegionColumnSize:function(){return this.table.getScrollRegionColumnSize()},getScrollRegionRowSize:function(){return this.table.getScrollRegionRowSize()},hasVerticalScroll:function(){return this.table.hasVerticalScroll()},setVerticalScroll:function(a){this.table.setVerticalScroll(a)},setLeftHorizontalScroll:function(a){this.table.setLeftHorizontalScroll(a)},setRightHorizontalScroll:function(a){this.table.setRightHorizontalScroll(a)},getVerticalScroll:function(){return this.table.getVerticalScroll()},getLeftHorizontalScroll:function(){return this.table.getLeftHorizontalScroll()},getRightHorizontalScroll:function(){return this.table.getRightHorizontalScroll()},getColumns:function(){return this.table.getColumns()},attr:function(){BI.ResponisveTable.superclass.attr.apply(this,arguments),this.table.attr.apply(this.table,arguments)},populate:function(a){var b=this,c=this.options;this.table.populate.apply(this.table,arguments),c.isNeedFreeze===!0&&BI.nextTick(function(){b._initRegionSize(),b.table.resize(),b._resizeHeader()})}}),BI.shortcut("bi.responsive_table",BI.ResponisveTable),BI.SelectTreeFirstPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.SelectTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-select-tree-first-plus-group-node bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",readonly:!0,open:!1,height:25})},_init:function(){BI.SelectTreeFirstPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.first_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},isOnce:function(){return!0},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments); },doClick:function(){BI.NodeButton.superclass.doClick.apply(this,arguments)},setOpened:function(a){BI.SelectTreeFirstPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.select_tree_first_plus_group_node",BI.SelectTreeFirstPlusGroupNode),BI.SelectTreeLastPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.SelectTreeLastPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-select-tree-last-plus-group-node bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",readonly:!0,open:!1,height:25})},_init:function(){BI.SelectTreeLastPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.last_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},isOnce:function(){return!0},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.NodeButton.superclass.doClick.apply(this,arguments)},setOpened:function(a){BI.SelectTreeLastPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.select_tree_last_plus_group_node",BI.SelectTreeLastPlusGroupNode),BI.SelectTreeMidPlusGroupNode=BI.inherit(BI.NodeButton,{_defaultConfig:function(){var a=BI.SelectTreeMidPlusGroupNode.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-select-tree-mid-plus-group-node bi-list-item-active",logic:{dynamic:!1},id:"",pId:"",readonly:!0,open:!1,height:25})},_init:function(){BI.SelectTreeMidPlusGroupNode.superclass._init.apply(this,arguments);var a=this,b=this.options;this.checkbox=BI.createWidget({type:"bi.mid_tree_node_checkbox",stopPropagation:!0}),this.text=BI.createWidget({type:"bi.label",textAlign:"left",whiteSpace:"nowrap",textHeight:b.height,height:b.height,hgap:b.hgap,text:b.text,value:b.value,py:b.py}),this.checkbox.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&(this.isSelected()?a.triggerExpand():a.triggerCollapse())});var c=BI.LogicFactory.createLogicTypeByDirection(BI.Direction.Left),d=BI.LogicFactory.createLogicItemsByDirection(BI.Direction.Left,{width:25,el:this.checkbox},this.text);BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(c,BI.extend(b.logic,{items:d}))))},isOnce:function(){return!0},doRedMark:function(){this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doClick:function(){BI.NodeButton.superclass.doClick.apply(this,arguments)},setOpened:function(a){BI.SelectTreeMidPlusGroupNode.superclass.setOpened.apply(this,arguments),BI.isNotNull(this.checkbox)&&this.checkbox.setSelected(a)}}),BI.shortcut("bi.select_tree_mid_plus_group_node",BI.SelectTreeMidPlusGroupNode),BI.SelectTreeCombo=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SelectTreeCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-select-tree-combo",height:30,text:"",items:[]})},_init:function(){BI.SelectTreeCombo.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget({type:"bi.single_tree_trigger",text:b.text,height:b.height,items:b.items}),this.popup=BI.createWidget({type:"bi.select_level_tree",items:b.items}),this.combo=BI.createWidget({type:"bi.combo",element:this,adjustLength:2,el:this.trigger,popup:{el:this.popup}}),this.combo.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.popup.on(BI.SingleTreePopup.EVENT_CHANGE,function(){a.setValue(a.popup.getValue()),a.combo.hideView()})},setValue:function(a){a=BI.isArray(a)?a:[a],this.trigger.setValue(a),this.popup.setValue(a)},getValue:function(){return this.popup.getValue()},populate:function(a){this.combo.populate(a)}}),BI.shortcut("bi.select_tree_combo",BI.SelectTreeCombo),BI.SelectTreeExpander=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SelectTreeExpander.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-select-tree-expander",trigger:"click",toggle:!0,direction:"bottom",isDefaultInit:!0,el:{},popup:{}})},_init:function(){BI.SelectTreeExpander.superclass._init.apply(this,arguments);var a=this,b=this.options;this.trigger=BI.createWidget(BI.extend({stopPropagation:!0},b.el)),this.trigger.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&this.isSelected()&&a.expander.setValue([]),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.expander=BI.createWidget({type:"bi.expander",element:this,trigger:b.trigger,toggle:b.toggle,direction:b.direction,isDefaultInit:b.isDefaultInit,el:this.trigger,popup:b.popup}),this.expander.on(BI.Controller.EVENT_CHANGE,function(b){b===BI.Events.CLICK&&a.trigger.setSelected(!1),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)})},setValue:function(a){BI.contains(a,this.trigger.getValue())?(this.trigger.setSelected(!0),this.expander.setValue([])):(this.trigger.setSelected(!1),this.expander.setValue(a))},getValue:function(){return this.trigger.isSelected()?[this.trigger.getValue()]:this.expander.getValue()},populate:function(a){this.expander.populate(a)}}),BI.shortcut("bi.select_tree_expander",BI.SelectTreeExpander),BI.SelectTreePopup=BI.inherit(BI.Pane,{_defaultConfig:function(){return BI.extend(BI.SelectTreePopup.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-select-level-tree",tipText:BI.i18nText("BI-No_Selected_Item"),items:[]})},_formatItems:function(a,b){var c=this;return BI.each(a,function(d,e){var f={layer:b};if(e.id=e.id||BI.UUID(),e.isParent===!0||BI.isNotEmptyArray(e.children)){switch(d){case 0:f.type="bi.select_tree_first_plus_group_node";break;case a.length-1:f.type="bi.select_tree_last_plus_group_node";break;default:f.type="bi.select_tree_mid_plus_group_node"}BI.defaults(e,f),c._formatItems(e.children)}else{switch(d){case a.length-1:f.type="bi.last_tree_leaf_item";break;default:f.type="bi.mid_tree_leaf_item"}BI.defaults(e,f)}}),a},_init:function(){BI.SelectTreePopup.superclass._init.apply(this,arguments);var a=this,b=this.options;this.tree=BI.createWidget({type:"bi.level_tree",expander:{type:"bi.select_tree_expander",isDefaultInit:!0},items:this._formatItems(BI.Tree.transformToTreeFormat(b.items)),chooseType:BI.Selection.Single}),BI.createWidget({type:"bi.vertical",element:this,items:[this.tree]}),this.tree.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.tree.on(BI.LevelTree.EVENT_CHANGE,function(){a.fireEvent(BI.SelectTreePopup.EVENT_CHANGE)}),this.check()},getValue:function(){return this.tree.getValue()},setValue:function(a){a=BI.isArray(a)?a:[a],this.tree.setValue(a)},populate:function(a){BI.SelectTreePopup.superclass.populate.apply(this,arguments),this.tree.populate(a)}}),BI.SelectTreePopup.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.select_level_tree",BI.SelectTreePopup),BI.SequenceTableDynamicNumber=BI.inherit(BI.SequenceTableTreeNumber,{_defaultConfig:function(){return BI.extend(BI.SequenceTableDynamicNumber.superclass._defaultConfig.apply(this,arguments),{extraCls:"bi-sequence-table-dynamic-number"})},_init:function(){BI.SequenceTableDynamicNumber.superclass._init.apply(this,arguments)},_formatNumber:function(a){function b(a){var c=0;return BI.isNotEmptyArray(a.children)?(BI.each(a.children,function(a,d){c+=b(d)}),a.children.length>1&&BI.isNotEmptyArray(a.values)&&c++):c++,c}var c=this.options,d=[],e=this._getStart(a),f=0,g=0;return BI.each(a,function(a,h){BI.isArray(h.children)&&(BI.each(h.children,function(a,h){var i=b(h);d.push({text:e++,start:f,top:g,cnt:i,index:a,height:i*c.rowSize}),f+=i,g+=i*c.rowSize}),BI.isNotEmptyArray(h.values)&&(d.push({text:BI.i18nText("BI-Summary_Values"),start:f++,top:g,cnt:1,isSummary:!0,height:c.rowSize}),g+=c.rowSize))}),d}}),BI.shortcut("bi.sequence_table_dynamic_number",BI.SequenceTableDynamicNumber),BI.SequenceTableListNumber=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SequenceTableListNumber.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-sequence-table-list-number",isNeedFreeze:!1,scrollTop:0,startSequence:1,headerRowSize:25,rowSize:25,sequenceHeaderCreator:null,header:[],items:[],crossHeader:[],crossItems:[],pageSize:20})},_init:function(){BI.SequenceTableListNumber.superclass._init.apply(this,arguments);var a=this.options;this.start=a.startSequence,this.renderedCells=[],this.renderedKeys=[],this.container=BI.createWidget({type:"bi.absolute",width:60,scrollable:!1}),this.scrollContainer=BI.createWidget({type:"bi.vertical",scrollable:!1,scrolly:!1,items:[this.container]}),this.headerContainer=BI.createWidget({type:"bi.absolute",cls:"bi-border",width:58,scrollable:!1}),this.layout=BI.createWidget({type:"bi.vtape",element:this,items:[{el:this.headerContainer,height:a.headerRowSize*a.header.length-2},{el:{type:"bi.layout"},height:2},{el:this.scrollContainer}]}),this._populate()},_layout:function(){var a=this.options,b=a.headerRowSize*a.header.length-2,c=this.layout.attr("items");a.isNeedFreeze===!1?(c[0].height=0,c[1].height=0):a.isNeedFreeze===!0&&(c[0].height=b,c[1].height=2),this.layout.attr("items",c),this.layout.resize(),this.container.setHeight(a.items.length*a.rowSize);try{this.scrollContainer.element.scrollTop(a.scrollTop)}catch(d){}},_createHeader:function(){var a=this.options;BI.createWidget({type:"bi.absolute",element:this.headerContainer,items:[{el:a.sequenceHeaderCreator||{type:"bi.table_style_cell",cls:"sequence-table-title-cell",styleGetter:a.headerCellStyleGetter,text:BI.i18nText("BI-Number_Index")},left:0,top:0,right:0,bottom:0}]})},_calculateChildrenToRender:function(){for(var a=this,b=this.options,c=BI.clamp(b.scrollTop,0,b.rowSize*b.items.length-(b.height-b.header.length*b.headerRowSize)+BI.DOM.getScrollWidth()),d=Math.floor(c/b.rowSize),e=d+Math.floor((b.height-b.header.length*b.headerRowSize)/b.rowSize),f=[],g=[],h=d,i=0;h<=e&&h-1)b.rowSize!==this.renderedCells[j]._height&&(this.renderedCells[j]._height=b.rowSize,this.renderedCells[j].el.setHeight(b.rowSize)),this.renderedCells[j].top!==k&&(this.renderedCells[j].top=k,this.renderedCells[j].el.element.css("top",k+"px")),f.push(this.renderedCells[j]);else{var l=BI.createWidget(BI.extend({type:"bi.table_style_cell",cls:"sequence-table-number-cell bi-border-left bi-border-right bi-border-bottom",width:60,height:b.rowSize,text:this.start+h,styleGetter:function(c){return function(){return b.sequenceCellStyleGetter(a.start+h-1)}}(i)}));f.push({el:l,left:0,top:k,_height:b.rowSize})}g.push(this.start+h)}var m={},n={},o=[];BI.each(g,function(b,c){BI.deepContains(a.renderedKeys,c)?m[b]=c:n[b]=c}),BI.each(this.renderedKeys,function(a,b){BI.deepContains(m,b)||BI.deepContains(n,b)||o.push(a)}),BI.each(o,function(b,c){a.renderedCells[c].el.destroy()});var p=[];BI.each(n,function(a){p.push(f[a])}),BI.createWidget({type:"bi.absolute",element:this.container,items:p}),this.renderedCells=f,this.renderedKeys=g},_populate:function(){this.headerContainer.empty(),this._createHeader(),this._layout(),this._calculateChildrenToRender()},setVerticalScroll:function(a){if(this.options.scrollTop!==a){this.options.scrollTop=a;try{this.scrollContainer.element.scrollTop(a)}catch(b){}}},getVerticalScroll:function(){return this.options.scrollTop},setVPage:function(a){a=a<1?1:a;var b=this.options;this.start=(a-1)*b.pageSize+1},_restore:function(){this.options;BI.each(this.renderedCells,function(a,b){b.el.destroy()}),this.renderedCells=[],this.renderedKeys=[]},restore:function(){this._restore()},populate:function(a,b){var c=this.options;a&&a!==this.options.items&&(c.items=a,this._restore()),b&&b!==this.options.header&&(c.header=b),this._populate()}}),BI.shortcut("bi.sequence_table_list_number",BI.SequenceTableListNumber),BI.SequenceTable=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SequenceTable.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-sequence-table",el:{type:"bi.adaptive_table"},sequence:{},isNeedResize:!0,isResizeAdapt:!1,isNeedFreeze:!1,freezeCols:[],isNeedMerge:!1,mergeCols:[],mergeRule:BI.emptyFn,columnSize:[],minColumnSize:[],maxColumnSize:[],headerRowSize:25,rowSize:25,regionColumnSize:[],headerCellStyleGetter:BI.emptyFn,summaryCellStyleGetter:BI.emptyFn,sequenceCellStyleGetter:BI.emptyFn,header:[],items:[],crossHeader:[],crossItems:[],showSequence:!1,startSequence:1})},_init:function(){BI.SequenceTable.superclass._init.apply(this,arguments);var a=this,b=this.options;this.sequence=BI.createWidget(b.sequence,{type:"bi.sequence_table_list_number",invisible:b.showSequence===!1,startSequence:b.startSequence,isNeedFreeze:b.isNeedFreeze,header:b.header,items:b.items,crossHeader:b.crossHeader,crossItems:b.crossItems,headerRowSize:b.headerRowSize,rowSize:b.rowSize,width:60,height:b.height&&b.height-BI.GridTableScrollbar.SIZE,headerCellStyleGetter:b.headerCellStyleGetter,summaryCellStyleGetter:b.summaryCellStyleGetter,sequenceCellStyleGetter:b.sequenceCellStyleGetter}),this.table=BI.createWidget(b.el,{type:"bi.adaptive_table",width:b.showSequence===!0?b.width-60:b.width,height:b.height,isNeedResize:b.isNeedResize,isResizeAdapt:b.isResizeAdapt,isNeedFreeze:b.isNeedFreeze,freezeCols:b.freezeCols,isNeedMerge:b.isNeedMerge,mergeCols:b.mergeCols,mergeRule:b.mergeRule,columnSize:b.columnSize,minColumnSize:b.minColumnSize,maxColumnSize:b.maxColumnSize,headerRowSize:b.headerRowSize,rowSize:b.rowSize,regionColumnSize:b.regionColumnSize,headerCellStyleGetter:b.headerCellStyleGetter,summaryCellStyleGetter:b.summaryCellStyleGetter,sequenceCellStyleGetter:b.sequenceCellStyleGetter,header:b.header,items:b.items,crossHeader:b.crossHeader,crossItems:b.crossItems}),this.table.on(BI.Table.EVENT_TABLE_SCROLL,function(b){a.sequence.getVerticalScroll()!==this.getVerticalScroll()&&(a.sequence.setVerticalScroll(this.getVerticalScroll()),a.sequence.populate()),a.fireEvent(BI.Table.EVENT_TABLE_SCROLL,arguments)}),this.table.on(BI.Table.EVENT_TABLE_AFTER_REGION_RESIZE,function(){b.regionColumnSize=this.getRegionColumnSize(),b.columnSize=this.getColumnSize(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_REGION_RESIZE,arguments)}),this.table.on(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE,function(){b.regionColumnSize=this.getRegionColumnSize(),b.columnSize=this.getColumnSize(),a.fireEvent(BI.Table.EVENT_TABLE_AFTER_COLUMN_RESIZE,arguments)}),this.htape=BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.sequence,left:0,top:0},{el:this.table,top:0,left:b.showSequence===!0?60:0}]}),this._populate()},_populate:function(){var a=this.options;a.showSequence===!0?(this.sequence.setVisible(!0),this.table.element.css("left","60px"),this.table.setWidth(a.width-60)):(this.sequence.setVisible(!1),this.table.element.css("left","0px"),this.table.setWidth(a.width))},setWidth:function(a){BI.PageTable.superclass.setWidth.apply(this,arguments),this.table.setWidth(this.options.showSequence?a-60:a)},setHeight:function(a){BI.PageTable.superclass.setHeight.apply(this,arguments),this.table.setHeight(a),this.sequence.setHeight(a-BI.GridTableScrollbar.SIZE)},setColumnSize:function(a){this.options.columnSize=a,this.table.setColumnSize(a)},getColumnSize:function(){return this.table.getColumnSize()},setRegionColumnSize:function(a){this.options.columnSize=a,this.table.setRegionColumnSize(a)},getRegionColumnSize:function(){return this.table.getRegionColumnSize()},hasLeftHorizontalScroll:function(){return this.table.hasLeftHorizontalScroll()},hasRightHorizontalScroll:function(){return this.table.hasRightHorizontalScroll()},setLeftHorizontalScroll:function(a){this.table.setLeftHorizontalScroll(a)},setRightHorizontalScroll:function(a){this.table.setRightHorizontalScroll(a)},setVerticalScroll:function(a){this.table.setVerticalScroll(a),this.sequence.setVerticalScroll(a)},getVerticalScroll:function(){return this.table.getVerticalScroll()},setVPage:function(a){this.sequence.setVPage&&this.sequence.setVPage(a)},setHPage:function(a){this.sequence.setHPage&&this.sequence.setHPage(a)},attr:function(){BI.SequenceTable.superclass.attr.apply(this,arguments),this.table.attr.apply(this.table,arguments),this.sequence.attr.apply(this.sequence,arguments)},restore:function(){this.table.restore(),this.sequence.restore()},populate:function(a,b,c,d){var e=this.options;a&&(e.items=a),b&&(e.header=b),c&&(e.crossItems=c),d&&(e.crossHeader=d),this._populate(),this.table.populate.apply(this.table,arguments),this.sequence.populate.apply(this.sequence,arguments),this.sequence.setVerticalScroll(this.table.getVerticalScroll())},destroy:function(){this.table.destroy(),BI.SequenceTable.superclass.destroy.apply(this,arguments)}}),BI.shortcut("bi.sequence_table",BI.SequenceTable),BI.SingleSelectSearchLoader=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-search-loader",itemsCreator:BI.emptyFn,keywordGetter:BI.emptyFn,valueFormatter:BI.emptyFn})},_init:function(){BI.SingleSelectSearchLoader.superclass._init.apply(this,arguments);var a=this,b=this.options,c=!1;this.button_group=BI.createWidget({type:"bi.single_select_list",element:this,logic:{dynamic:!1},el:{tipText:BI.i18nText("BI-No_Select"),el:{type:"bi.loader",isDefaultInit:!1,logic:{dynamic:!0,scrolly:!0},el:{chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,behaviors:{redmark:function(){return!0}},layouts:[{type:"bi.vertical"}]}}},itemsCreator:function(d,e){a.storeValue&&(d=BI.extend(d||{},{selectedValues:[a.storeValue]})),b.itemsCreator(d,function(f){var g=f.keyword=b.keywordGetter();c=f.hasNext;var h=[];if(1===d.times&&a.storeValue){var i=BI.map([a.storeValue],function(a,c){var d=b.valueFormatter(c)||c;return{text:d,value:c,title:d,selected:!1}});h=a._createItems(i)}e(h.concat(a._createItems(f.items)),g),1===d.times&&a.storeValue&&a.setValue(a.storeValue)})},hasNext:function(){return c}}),this.button_group.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.button_group.on(BI.SingleSelectList.EVENT_CHANGE,function(){a.fireEvent(BI.SingleSelectSearchLoader.EVENT_CHANGE,arguments)})},_createItems:function(a){return BI.createItems(a,{type:"bi.single_select_radio_item",logic:{dynamic:!1},height:25,selected:!1})},_filterValues:function(a){var b=this.options,c=b.keywordGetter(),d=BI.deepClone(a.value)||[],e=BI.map(d,function(a,c){return{text:b.valueFormatter(c)||c,value:c}});if(BI.isKey(c)){var f=BI.Func.getSearchResult(e,c);d=f.matched.concat(f.finded)}return BI.map(d,function(a,b){return{text:b.text,title:b.text,value:b.value,selected:!1}})},setValue:function(a){this.storeValue=a,this.button_group.setValue(a)},getValue:function(){return this.button_group.getValue()},getAllButtons:function(){return this.button_group.getAllButtons()},empty:function(){this.button_group.empty()},populate:function(a){this.button_group.populate.apply(this.button_group,arguments)},resetHeight:function(a){this.button_group.resetHeight(a)},resetWidth:function(a){this.button_group.resetWidth(a)}}),BI.SingleSelectSearchLoader.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.single_select_search_loader",BI.SingleSelectSearchLoader),BI.SingleSelectSearchPane=BI.inherit(BI.Widget,{constants:{height:25,lgap:10,tgap:5},_defaultConfig:function(){return BI.extend(BI.SingleSelectSearchPane.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-search-pane bi-card",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,keywordGetter:BI.emptyFn})},_init:function(){BI.SingleSelectSearchPane.superclass._init.apply(this,arguments);var a=this,b=this.options;this.tooltipClick=BI.createWidget({type:"bi.label",invisible:!0,text:BI.i18nText("BI-Click_Blank_To_Select"),cls:"single-select-toolbar",height:this.constants.height}),this.loader=BI.createWidget({type:"bi.single_select_search_loader",keywordGetter:b.keywordGetter,valueFormatter:b.valueFormatter,itemsCreator:function(c,d){b.itemsCreator.apply(a,[c,function(c){d(c),a.setKeyword(b.keywordGetter())}])}}),this.loader.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.resizer=BI.createWidget({type:"bi.vtape",element:this,items:[{el:this.tooltipClick,height:0},{el:this.loader}]}),this.tooltipClick.setVisible(!1)},setKeyword:function(a){var b,c=this.loader.getAllButtons().length>0&&(b=this.loader.getAllButtons()[0])&&a===b.getValue();c!==this.tooltipClick.isVisible()&&(this.tooltipClick.setVisible(c),this.resizer.attr("items")[0].height=c?this.constants.height:0,this.resizer.resize())},hasMatched:function(){return this.tooltipClick.isVisible()},setValue:function(a){this.loader.setValue(a)},getValue:function(){return this.loader.getValue()},empty:function(){this.loader.empty()},populate:function(a){this.loader.populate.apply(this.loader,arguments)}}),BI.SingleSelectSearchPane.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.single_select_search_pane",BI.SingleSelectSearchPane),BI.SingleSelectCombo=BI.inherit(BI.Single,{_defaultConfig:function(){return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-combo",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,height:28})},_init:function(){BI.SingleSelectCombo.superclass._init.apply(this,arguments);var a=this,b=this.options,c=function(){BI.isKey(a._startValue)&&(a.storeValue=a._startValue),a.trigger.getSearcher().setState(a.storeValue)};this.storeValue="",this.requesting=!1,this.trigger=BI.createWidget({type:"bi.single_select_trigger",height:b.height,masker:{offset:{left:1,top:1,right:2,bottom:33}},valueFormatter:b.valueFormatter,itemsCreator:function(c,d){b.itemsCreator(c,function(b){1===c.times&&BI.isNotNull(c.keywords)&&a.trigger.setValue(a.getValue()),d.apply(a,arguments)})}}),this.trigger.on(BI.SingleSelectTrigger.EVENT_START,function(){a._setStartValue(""),this.getSearcher().setValue(a.storeValue)}),this.trigger.on(BI.SingleSelectTrigger.EVENT_STOP,function(){a._setStartValue("")}),this.trigger.on(BI.SingleSelectTrigger.EVENT_PAUSE,function(){if(this.getSearcher().hasMatched()){var b=this.getSearcher().getKeyword();a._join({type:BI.Selection.Multi,value:[b]},function(){a.combo.setValue(a.storeValue),a._setStartValue(b),c(),a.populate(),a._setStartValue("")})}}),this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING,function(b){var d=BI.last(b);b=BI.initial(b||[]),b.length>0&&a._joinKeywords(b,function(){BI.isEndWithBlank(d)?(a.combo.setValue(a.storeValue),c(),a.combo.populate(),a._setStartValue("")):(a.combo.setValue(a.storeValue),c())})}),this.trigger.on(BI.SingleSelectTrigger.EVENT_CHANGE,function(b,d){a.storeValue=this.getValue(),c()}),this.trigger.on(BI.SingleSelectTrigger.EVENT_COUNTER_CLICK,function(){a.combo.isViewVisible()||a.combo.showView()}),this.combo=BI.createWidget({type:"bi.combo",toggle:!1,el:this.trigger,adjustLength:1,popup:{type:"bi.single_select_popup_view",ref:function(){a.popup=this,a.trigger.setAdapter(this)},listeners:[{eventName:BI.SingleSelectPopupView.EVENT_CHANGE,action:function(){a.storeValue=this.getValue(),a._adjust(function(){c()})}},{eventName:BI.SingleSelectPopupView.EVENT_CLICK_CONFIRM,action:function(){a._defaultState()}},{eventName:BI.SingleSelectPopupView.EVENT_CLICK_CLEAR,action:function(){a.setValue(),a._defaultState()}}],itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,onLoaded:function(){BI.nextTick(function(){a.combo.adjustWidth(),a.combo.adjustHeight(),a.trigger.getSearcher().adjustView()})}},hideChecker:function(a){return 0===d.element.find(a.target).length}}),this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW,function(){this.setValue(a.storeValue),BI.nextTick(function(){a.populate()})}),this.wants2Quit=!1,this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW,function(){a.trigger.stopEditing(),a.requesting===!0?a.wants2Quit=!0:a.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM)});var d=BI.createWidget({type:"bi.trigger_icon_button",width:b.height,height:b.height,cls:"single-select-trigger-icon-button bi-border-left"});d.on(BI.TriggerIconButton.EVENT_CHANGE,function(){a.combo.isViewVisible()?a.combo.hideView():a.combo.showView()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.combo,left:0,right:0,top:0,bottom:0},{el:d,right:0,top:0,bottom:0}]})},_defaultState:function(){this.trigger.stopEditing(),this.combo.hideView()},_assertValue:function(a){a||(a="")},_makeMap:function(a){return BI.makeObject(a||[])},_joinKeywords:function(a,b){function c(c){var e=d._makeMap(c);BI.each(a,function(a,b){BI.isNotNull(e[b])&&d.storeValue.value.remove(b)}),d._adjust(b)}var d=this,e=this.options;this._assertValue(this.storeValue),this.requesting=!0,e.itemsCreator({type:BI.SingleSelectCombo.REQ_GET_ALL_DATA,keywords:a},function(a){var b=BI.pluck(a.items,"value");c(b)})},_joinAll:function(a,b){var c=this,d=this.options;this._assertValue(a),this.requesting=!0,d.itemsCreator({type:BI.SingleSelectCombo.REQ_GET_ALL_DATA,keywords:[this.trigger.getKey()]},function(d){var e=BI.pluck(d.items,"value");if(c.storeValue.type===a.type){var f=!1,g=c._makeMap(c.storeValue.value);return BI.each(e,function(a,b){BI.isNotNull(g[b])&&(f=!0,delete g[b])}),f&&(c.storeValue.value=BI.values(g)),void c._adjust(b)}var h=c._makeMap(c.storeValue.value),i=c._makeMap(a.value),j=[];BI.each(e,function(a,b){BI.isNotNull(h[e[a]])&&delete h[e[a]],BI.isNull(i[e[a]])&&j.push(b)}),c.storeValue.value=j.concat(BI.values(h)),c._adjust(b)})},_adjust:function(a){function b(){c.wants2Quit===!0&&(c.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM),c.wants2Quit=!1),c.requesting=!1}var c=this,d=this.options;this._count?(b(),a()):d.itemsCreator({type:BI.SingleSelectCombo.REQ_GET_DATA_LENGTH},function(d){c._count=d.count,b(),a()})},_join:function(a,b){var c=this;this.options;if(this._assertValue(a),this._assertValue(this.storeValue),this.storeValue.type===a.type){var d=this._makeMap(this.storeValue.value);BI.each(a.value,function(a,b){d[b]||(c.storeValue.value.push(b),d[b]=b)});var e=!1;return BI.each(a.assist,function(a,b){BI.isNotNull(d[b])&&(e=!0,delete d[b])}),e&&(this.storeValue.value=BI.values(d)),void c._adjust(b)}this._joinAll(a,b)},_setStartValue:function(a){this._startValue=a,this.popup.setStartValue(a)},setValue:function(a){this.storeValue=a||"",this._assertValue(this.storeValue),this.combo.setValue(this.storeValue)},getValue:function(){return this.storeValue},populate:function(){this._count=null,this.combo.populate.apply(this.combo,arguments)}}),BI.extend(BI.SingleSelectCombo,{REQ_GET_DATA_LENGTH:0,REQ_GET_ALL_DATA:-1}),BI.SingleSelectCombo.EVENT_CONFIRM="EVENT_CONFIRM",BI.shortcut("bi.single_select_combo",BI.SingleSelectCombo),BI.SingleSelectList=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SingleSelectList.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-select-list",direction:BI.Direction.Top,logic:{dynamic:!0},items:[],itemsCreator:BI.emptyFn,hasNext:BI.emptyFn,onLoaded:BI.emptyFn,el:{type:"bi.list_pane"}})},_init:function(){BI.SingleSelectList.superclass._init.apply(this,arguments);var a=this,b=this.options;this.list=BI.createWidget(b.el,{type:"bi.list_pane",items:b.items,itemsCreator:function(c,d){b.itemsCreator(c,function(b){d.apply(a,arguments)})},onLoaded:b.onLoaded,hasNext:b.hasNext}),this.list.on(BI.Controller.EVENT_CHANGE,function(b,c,d){b===BI.Events.CLICK&&a.fireEvent(BI.SingleSelectList.EVENT_CHANGE,c,d),a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),BI.createWidget(BI.extend({element:this},BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(b.direction),BI.extend({scrolly:!0},b.logic,{items:BI.LogicFactory.createLogicItemsByDirection(b.direction,this.list)}))))},hasPrev:function(){return this.list.hasPrev()},hasNext:function(){return this.list.hasNext()},prependItems:function(a){this.list.prependItems.apply(this.list,arguments)},addItems:function(a){this.list.addItems.apply(this.list,arguments)},setValue:function(a){this.list.setValue([a])},getValue:function(){return this.list.getValue()[0]},empty:function(){this.list.empty()},populate:function(a){this.list.populate.apply(this.list,arguments)},resetHeight:function(a){this.list.resetHeight?this.list.resetHeight(a):this.list.element.css({"max-height":a+"px"})},setNotSelectedValue:function(){this.list.setNotSelectedValue.apply(this.list,arguments)},getNotSelectedValue:function(){return this.list.getNotSelectedValue()},getAllButtons:function(){return this.list.getAllButtons()},getAllLeaves:function(){return this.list.getAllLeaves()},getSelectedButtons:function(){return this.list.getSelectedButtons()},getNotSelectedButtons:function(){return this.list.getNotSelectedButtons()},getIndexByValue:function(a){return this.list.getIndexByValue(a)},getNodeById:function(a){return this.list.getNodeById(a)},getNodeByValue:function(a){return this.list.getNodeByValue(a)}}),BI.SingleSelectList.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.single_select_list",BI.SingleSelectList),BI.SingleSelectLoader=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SingleSelectLoader.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-loader",logic:{dynamic:!0},el:{height:400},valueFormatter:BI.emptyFn,itemsCreator:BI.emptyFn,onLoaded:BI.emptyFn})},_init:function(){BI.SingleSelectLoader.superclass._init.apply(this,arguments);var a=this,b=this.options,c=!1;this.button_group=BI.createWidget({type:"bi.single_select_list",element:this,logic:b.logic,el:BI.extend({onLoaded:b.onLoaded,el:{type:"bi.loader",isDefaultInit:!1,logic:{dynamic:!0,scrolly:!0},el:{chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,behaviors:{redmark:function(){return!0}},layouts:[{type:"bi.vertical"}]}}},b.el),itemsCreator:function(d,e){var f=a._startValue;a.storeValue&&(d=BI.extend(d||{},{selectedValues:[a.storeValue]})),b.itemsCreator(d,function(g){c=g.hasNext;var h=[];if(1===d.times&&a.storeValue){var i=BI.map([a.storeValue],function(a,c){var d=b.valueFormatter(c)||c;return{text:d,value:c,title:d,selected:!1}});h=a._createItems(i)}e(h.concat(a._createItems(g.items)),g.keyword||""),1===d.times&&a.storeValue&&(BI.isKey(f)&&(a.storeValue=f),a.setValue(a.storeValue)),1===d.times&&a._scrollToTop()})},hasNext:function(){return c}}),this.button_group.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.button_group.on(BI.SingleSelectList.EVENT_CHANGE,function(){a.fireEvent(BI.SingleSelectLoader.EVENT_CHANGE,arguments)})},_createItems:function(a){return BI.createItems(a,{type:"bi.single_select_radio_item",logic:this.options.logic,height:25,selected:!1})},_scrollToTop:function(){var a=this;BI.delay(function(){a.button_group.element.scrollTop(0)},30)},_assertValue:function(a){a||(a="")},setStartValue:function(a){this._startValue=a},setValue:function(a){this.storeValue=a||"",this._assertValue(this.storeValue),this.button_group.setValue(this.storeValue)},getValue:function(){return this.button_group.getValue()},getAllButtons:function(){return this.button_group.getAllButtons()},empty:function(){this.button_group.empty()},populate:function(a){this.button_group.populate.apply(this.button_group,arguments)},resetHeight:function(a){this.button_group.resetHeight(a)},resetWidth:function(a){this.button_group.resetWidth(a)}}),BI.SingleSelectLoader.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.single_select_loader",BI.SingleSelectLoader), BI.SingleSelectPopupView=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SingleSelectPopupView.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-popup-view",maxWidth:"auto",minWidth:135,maxHeight:400,valueFormatter:BI.emptyFn,itemsCreator:BI.emptyFn,onLoaded:BI.emptyFn})},_init:function(){BI.SingleSelectPopupView.superclass._init.apply(this,arguments);var a=this,b=this.options;this.loader=BI.createWidget({type:"bi.single_select_loader",itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,onLoaded:b.onLoaded}),this.popupView=BI.createWidget({type:"bi.multi_popup_view",stopPropagation:!1,maxWidth:b.maxWidth,minWidth:b.minWidth,maxHeight:b.maxHeight,element:this,buttons:[BI.i18nText("BI-Basic_Clears"),BI.i18nText("BI-Basic_Sure")],el:this.loader}),this.popupView.on(BI.MultiPopupView.EVENT_CHANGE,function(){a.fireEvent(BI.SingleSelectPopupView.EVENT_CHANGE)}),this.popupView.on(BI.MultiPopupView.EVENT_CLICK_TOOLBAR_BUTTON,function(b){switch(b){case 0:a.fireEvent(BI.SingleSelectPopupView.EVENT_CLICK_CLEAR);break;case 1:a.fireEvent(BI.SingleSelectPopupView.EVENT_CLICK_CONFIRM)}})},setStartValue:function(a){this.loader.setStartValue(a)},setValue:function(a){this.popupView.setValue(a)},getValue:function(){return this.popupView.getValue()},populate:function(a){this.popupView.populate.apply(this.popupView,arguments)},resetHeight:function(a){this.popupView.resetHeight(a)},resetWidth:function(a){this.popupView.resetWidth(a)}}),BI.SingleSelectPopupView.EVENT_CHANGE="EVENT_CHANGE",BI.SingleSelectPopupView.EVENT_CLICK_CONFIRM="EVENT_CLICK_CONFIRM",BI.SingleSelectPopupView.EVENT_CLICK_CLEAR="EVENT_CLICK_CLEAR",BI.shortcut("bi.single_select_popup_view",BI.SingleSelectPopupView),BI.SingleSelectTrigger=BI.inherit(BI.Trigger,{constants:{height:14,rgap:4,lgap:4},_defaultConfig:function(){return BI.extend(BI.SingleSelectTrigger.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-trigger bi-border",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,searcher:{},switcher:{},adapter:null,masker:{}})},_init:function(){BI.SingleSelectTrigger.superclass._init.apply(this,arguments);var a=this,b=this.options;b.height&&this.setHeight(b.height-2),this.searcher=BI.createWidget(b.searcher,{type:"bi.single_select_searcher",height:b.height,itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,popup:{},adapter:b.adapter,masker:b.masker}),this.searcher.on(BI.SingleSelectSearcher.EVENT_START,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_START)}),this.searcher.on(BI.SingleSelectSearcher.EVENT_PAUSE,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_PAUSE)}),this.searcher.on(BI.SingleSelectSearcher.EVENT_SEARCHING,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_SEARCHING,arguments)}),this.searcher.on(BI.SingleSelectSearcher.EVENT_STOP,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_STOP)}),this.searcher.on(BI.SingleSelectSearcher.EVENT_CHANGE,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_CHANGE,arguments)});BI.createWidget({type:"bi.htape",element:this,items:[{el:this.searcher,width:"fill"},{el:BI.createWidget(),width:30}]})},getSearcher:function(){return this.searcher},stopEditing:function(){this.searcher.stopSearch()},setAdapter:function(a){this.searcher.setAdapter(a)},setValue:function(a){this.searcher.setValue(a)},getKey:function(){return this.searcher.getKey()},getValue:function(){return this.searcher.getValue()}}),BI.SingleSelectTrigger.EVENT_TRIGGER_CLICK="EVENT_TRIGGER_CLICK",BI.SingleSelectTrigger.EVENT_COUNTER_CLICK="EVENT_COUNTER_CLICK",BI.SingleSelectTrigger.EVENT_CHANGE="EVENT_CHANGE",BI.SingleSelectTrigger.EVENT_START="EVENT_START",BI.SingleSelectTrigger.EVENT_STOP="EVENT_STOP",BI.SingleSelectTrigger.EVENT_PAUSE="EVENT_PAUSE",BI.SingleSelectTrigger.EVENT_SEARCHING="EVENT_SEARCHING",BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW="EVENT_BEFORE_COUNTER_POPUPVIEW",BI.shortcut("bi.single_select_trigger",BI.SingleSelectTrigger),BI.SingleSelectEditor=BI.inherit(BI.Widget,{_const:{checkSelected:BI.i18nText("BI-Check_Selected")},_defaultConfig:function(){return BI.extend(BI.SingleSelectEditor.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-editor",el:{}})},_init:function(){BI.SingleSelectEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget(b.el,{type:"bi.state_editor",element:this,height:b.height,watermark:BI.i18nText("BI-Basic_Search"),allowBlank:!0}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.StateEditor.EVENT_PAUSE,function(){a.fireEvent(BI.SingleSelectEditor.EVENT_PAUSE)}),this.editor.on(BI.StateEditor.EVENT_CLICK_LABEL,function(){})},focus:function(){this.editor.focus()},blur:function(){this.editor.blur()},setState:function(a){this.editor.setState(a)},setValue:function(a){this.editor.setValue(a)},getValue:function(){var a=this.editor.getState();return BI.isArray(a)&&a.length>0?a[a.length-1]:""},getKeywords:function(){var a=this.editor.getLastValidValue(),b=a.match(/[\S]+/g);return BI.isEndWithBlank(a)?b.concat([" "]):b},populate:function(a){}}),BI.SingleSelectEditor.EVENT_PAUSE="SingleSelectEditor.EVENT_PAUSE",BI.shortcut("bi.single_select_editor",BI.SingleSelectEditor),BI.SingleSelectSearcher=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-searcher",itemsCreator:BI.emptyFn,el:{},popup:{},valueFormatter:BI.emptyFn,adapter:null,masker:{}})},_init:function(){BI.SingleSelectSearcher.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget(b.el,{type:"bi.single_select_editor",height:b.height}),this.searcher=BI.createWidget({type:"bi.searcher",element:this,height:b.height,isAutoSearch:!1,isAutoSync:!1,onSearch:function(a,b){b()},el:this.editor,popup:BI.extend({type:"bi.single_select_search_pane",valueFormatter:b.valueFormatter,keywordGetter:function(){return a.editor.getValue()},itemsCreator:function(c,d){c.keyword=a.editor.getValue(),this.setKeyword(c.keyword),b.itemsCreator(c,d)}},b.popup),adapter:b.adapter,masker:b.masker}),this.searcher.on(BI.Searcher.EVENT_START,function(){a.fireEvent(BI.SingleSelectSearcher.EVENT_START)}),this.searcher.on(BI.Searcher.EVENT_PAUSE,function(){this.hasMatched(),a.fireEvent(BI.SingleSelectSearcher.EVENT_PAUSE)}),this.searcher.on(BI.Searcher.EVENT_STOP,function(){a.fireEvent(BI.SingleSelectSearcher.EVENT_STOP)}),this.searcher.on(BI.Searcher.EVENT_CHANGE,function(){a.fireEvent(BI.SingleSelectSearcher.EVENT_CHANGE,arguments)}),this.searcher.on(BI.Searcher.EVENT_SEARCHING,function(){var b=this.getKeywords();a.fireEvent(BI.SingleSelectSearcher.EVENT_SEARCHING,b)})},adjustView:function(){this.searcher.adjustView()},isSearching:function(){return this.searcher.isSearching()},stopSearch:function(){this.searcher.stopSearch()},getKeyword:function(){return this.editor.getValue()},hasMatched:function(){return this.searcher.hasMatched()},hasChecked:function(){return this.searcher.getView()&&this.searcher.getView().hasChecked()},setAdapter:function(a){this.searcher.setAdapter(a)},setState:function(a){var b=this.options;a||(a=""),""===a?this.editor.setState(BI.Selection.None):this.editor.setState(b.valueFormatter(a+"")||a+"")},setValue:function(a){this.setState(a),this.searcher.setValue(a)},getKey:function(){return this.editor.getValue()},getValue:function(){return this.searcher.getValue()},populate:function(a){this.searcher.populate.apply(this.searcher,arguments)}}),BI.SingleSelectSearcher.EVENT_BEFORE_POPUPVIEW="EVENT_BEFORE_POPUPVIEW",BI.SingleSelectSearcher.EVENT_CHANGE="EVENT_CHANGE",BI.SingleSelectSearcher.EVENT_START="EVENT_START",BI.SingleSelectSearcher.EVENT_STOP="EVENT_STOP",BI.SingleSelectSearcher.EVENT_PAUSE="EVENT_PAUSE",BI.SingleSelectSearcher.EVENT_SEARCHING="EVENT_SEARCHING",BI.shortcut("bi.single_select_searcher",BI.SingleSelectSearcher),BI.SingleSelectSearchLoader=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-search-loader",itemsCreator:BI.emptyFn,keywordGetter:BI.emptyFn,valueFormatter:BI.emptyFn})},_init:function(){BI.SingleSelectSearchLoader.superclass._init.apply(this,arguments);var a=this,b=this.options,c=!1;this.button_group=BI.createWidget({type:"bi.single_select_list",element:this,logic:{dynamic:!1},el:{tipText:BI.i18nText("BI-No_Select"),el:{type:"bi.loader",isDefaultInit:!1,logic:{dynamic:!0,scrolly:!0},el:{chooseType:BI.ButtonGroup.CHOOSE_TYPE_SINGLE,behaviors:{redmark:function(){return!0}},layouts:[{type:"bi.vertical"}]}}},itemsCreator:function(d,e){a.storeValue&&(d=BI.extend(d||{},{selectedValues:[a.storeValue]})),b.itemsCreator(d,function(f){var g=f.keyword=b.keywordGetter();c=f.hasNext;var h=[];if(1===d.times&&a.storeValue){var i=BI.map([a.storeValue],function(a,c){var d=b.valueFormatter(c)||c;return{text:d,value:c,title:d,selected:!1}});h=a._createItems(i)}if(g){for(var j=!1,k=0;k0&&(b=this.loader.getAllButtons()[0])&&a===b.getValue();c!==this.tooltipClick.isVisible()&&(this.tooltipClick.setVisible(c),this.resizer.attr("items")[0].height=c?this.constants.height:0,this.resizer.resize())},hasMatched:function(){return this.tooltipClick.isVisible()},setValue:function(a){this.loader.setValue(a)},getValue:function(){return this.loader.getValue()},empty:function(){this.loader.empty()},populate:function(a){this.loader.populate.apply(this.loader,arguments)}}),BI.SingleSelectSearchPane.EVENT_CHANGE="EVENT_CHANGE",BI.shortcut("bi.single_select_search_add_pane",BI.SingleSelectSearchPane),BI.SingleSelectCombo=BI.inherit(BI.Single,{_defaultConfig:function(){return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-combo",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,height:28})},_init:function(){BI.SingleSelectCombo.superclass._init.apply(this,arguments);var a=this,b=this.options,c=function(){BI.isKey(a._startValue)&&(a.storeValue=a._startValue),a.trigger.getSearcher().setState(a.storeValue)};this.storeValue="",this.requesting=!1,this.trigger=BI.createWidget({type:"bi.single_select_add_trigger",height:b.height,masker:{offset:{left:1,top:1,right:2,bottom:33}},valueFormatter:b.valueFormatter,itemsCreator:function(c,d){b.itemsCreator(c,function(b){1===c.times&&BI.isNotNull(c.keywords)&&a.trigger.setValue(a.getValue()),d.apply(a,arguments)})}}),this.trigger.on(BI.SingleSelectTrigger.EVENT_START,function(){a._setStartValue(""),this.getSearcher().setValue(a.storeValue)}),this.trigger.on(BI.SingleSelectTrigger.EVENT_STOP,function(){a._setStartValue("")}),this.trigger.on(BI.SingleSelectTrigger.EVENT_PAUSE,function(){if(this.getSearcher().hasMatched()){var b=this.getSearcher().getKeyword();a._join({type:BI.Selection.Multi,value:[b]},function(){a.combo.setValue(a.storeValue),a._setStartValue(b),c(),a.populate(),a._setStartValue("")})}}),this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING,function(b){var d=BI.last(b);b=BI.initial(b||[]),b.length>0&&a._joinKeywords(b,function(){BI.isEndWithBlank(d)?(a.combo.setValue(a.storeValue),c(),a.combo.populate(),a._setStartValue("")):(a.combo.setValue(a.storeValue),c())})}),this.trigger.on(BI.SingleSelectTrigger.EVENT_CHANGE,function(b,d){a.storeValue=this.getValue(),c()}),this.trigger.on(BI.SingleSelectTrigger.EVENT_COUNTER_CLICK,function(){a.combo.isViewVisible()||a.combo.showView()}),this.combo=BI.createWidget({type:"bi.combo",toggle:!1,el:this.trigger,adjustLength:1,popup:{type:"bi.single_select_popup_view",ref:function(){a.popup=this,a.trigger.setAdapter(this)},listeners:[{eventName:BI.SingleSelectPopupView.EVENT_CHANGE,action:function(){a.storeValue=this.getValue(),a._adjust(function(){c()})}},{eventName:BI.SingleSelectPopupView.EVENT_CLICK_CONFIRM,action:function(){a._defaultState()}},{eventName:BI.SingleSelectPopupView.EVENT_CLICK_CLEAR,action:function(){a.setValue(),a._defaultState()}}],itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,onLoaded:function(){BI.nextTick(function(){a.combo.adjustWidth(),a.combo.adjustHeight(),a.trigger.getSearcher().adjustView()})}},hideChecker:function(a){return 0===d.element.find(a.target).length}}),this.combo.on(BI.Combo.EVENT_BEFORE_POPUPVIEW,function(){this.setValue(a.storeValue),BI.nextTick(function(){a.populate()})}),this.wants2Quit=!1,this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW,function(){a.trigger.stopEditing(),a.requesting===!0?a.wants2Quit=!0:a.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM)});var d=BI.createWidget({type:"bi.trigger_icon_button",width:b.height,height:b.height,cls:"single-select-trigger-icon-button bi-border-left"});d.on(BI.TriggerIconButton.EVENT_CHANGE,function(){a.combo.isViewVisible()?a.combo.hideView():a.combo.showView()}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.combo,left:0,right:0,top:0,bottom:0},{el:d,right:0,top:0,bottom:0}]})},_defaultState:function(){this.trigger.stopEditing(),this.combo.hideView()},_assertValue:function(a){a||(a="")},_makeMap:function(a){return BI.makeObject(a||[])},_joinKeywords:function(a,b){function c(c){var e=d._makeMap(c);BI.each(a,function(a,b){BI.isNotNull(e[b])&&d.storeValue.value.remove(b)}),d._adjust(b)}var d=this,e=this.options;this._assertValue(this.storeValue),this.requesting=!0,e.itemsCreator({type:BI.SingleSelectCombo.REQ_GET_ALL_DATA,keywords:a},function(a){var b=BI.pluck(a.items,"value");c(b)})},_joinAll:function(a,b){var c=this,d=this.options;this._assertValue(a),this.requesting=!0,d.itemsCreator({type:BI.SingleSelectCombo.REQ_GET_ALL_DATA,keywords:[this.trigger.getKey()]},function(d){var e=BI.pluck(d.items,"value");if(c.storeValue.type===a.type){var f=!1,g=c._makeMap(c.storeValue.value);return BI.each(e,function(a,b){BI.isNotNull(g[b])&&(f=!0,delete g[b])}),f&&(c.storeValue.value=BI.values(g)),void c._adjust(b)}var h=c._makeMap(c.storeValue.value),i=c._makeMap(a.value),j=[];BI.each(e,function(a,b){BI.isNotNull(h[e[a]])&&delete h[e[a]],BI.isNull(i[e[a]])&&j.push(b)}),c.storeValue.value=j.concat(BI.values(h)),c._adjust(b)})},_adjust:function(a){function b(){c.wants2Quit===!0&&(c.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM),c.wants2Quit=!1),c.requesting=!1}var c=this,d=this.options;this._count?(b(),a()):d.itemsCreator({type:BI.SingleSelectCombo.REQ_GET_DATA_LENGTH},function(d){c._count=d.count,b(),a()})},_join:function(a,b){var c=this;this.options;if(this._assertValue(a),this._assertValue(this.storeValue),this.storeValue.type===a.type){var d=this._makeMap(this.storeValue.value);BI.each(a.value,function(a,b){d[b]||(c.storeValue.value.push(b),d[b]=b)});var e=!1;return BI.each(a.assist,function(a,b){BI.isNotNull(d[b])&&(e=!0,delete d[b])}),e&&(this.storeValue.value=BI.values(d)),void c._adjust(b)}this._joinAll(a,b)},_setStartValue:function(a){this._startValue=a,this.popup.setStartValue(a)},setValue:function(a){this.storeValue=a||"",this._assertValue(this.storeValue),this.combo.setValue(this.storeValue)},getValue:function(){return this.storeValue},populate:function(){this._count=null,this.combo.populate.apply(this.combo,arguments)}}),BI.extend(BI.SingleSelectCombo,{REQ_GET_DATA_LENGTH:0,REQ_GET_ALL_DATA:-1}),BI.SingleSelectCombo.EVENT_CONFIRM="EVENT_CONFIRM",BI.shortcut("bi.single_select_add_combo",BI.SingleSelectCombo),BI.SingleSelectTrigger=BI.inherit(BI.Trigger,{constants:{height:14,rgap:4,lgap:4},_defaultConfig:function(){return BI.extend(BI.SingleSelectTrigger.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-trigger bi-border",itemsCreator:BI.emptyFn,valueFormatter:BI.emptyFn,searcher:{},switcher:{},adapter:null,masker:{}})},_init:function(){BI.SingleSelectTrigger.superclass._init.apply(this,arguments);var a=this,b=this.options;b.height&&this.setHeight(b.height-2),this.searcher=BI.createWidget(b.searcher,{type:"bi.single_select_add_searcher",height:b.height,itemsCreator:b.itemsCreator,valueFormatter:b.valueFormatter,popup:{},adapter:b.adapter,masker:b.masker}),this.searcher.on(BI.SingleSelectSearcher.EVENT_START,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_START)}),this.searcher.on(BI.SingleSelectSearcher.EVENT_PAUSE,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_PAUSE)}),this.searcher.on(BI.SingleSelectSearcher.EVENT_SEARCHING,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_SEARCHING,arguments)}),this.searcher.on(BI.SingleSelectSearcher.EVENT_STOP,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_STOP)}),this.searcher.on(BI.SingleSelectSearcher.EVENT_CHANGE,function(){a.fireEvent(BI.SingleSelectTrigger.EVENT_CHANGE,arguments)});BI.createWidget({type:"bi.htape",element:this,items:[{el:this.searcher,width:"fill"},{el:BI.createWidget(),width:30}]})},getSearcher:function(){return this.searcher},stopEditing:function(){this.searcher.stopSearch()},setAdapter:function(a){this.searcher.setAdapter(a)},setValue:function(a){this.searcher.setValue(a)},getKey:function(){return this.searcher.getKey()},getValue:function(){return this.searcher.getValue()}}),BI.SingleSelectTrigger.EVENT_TRIGGER_CLICK="EVENT_TRIGGER_CLICK",BI.SingleSelectTrigger.EVENT_COUNTER_CLICK="EVENT_COUNTER_CLICK",BI.SingleSelectTrigger.EVENT_CHANGE="EVENT_CHANGE",BI.SingleSelectTrigger.EVENT_START="EVENT_START",BI.SingleSelectTrigger.EVENT_STOP="EVENT_STOP",BI.SingleSelectTrigger.EVENT_PAUSE="EVENT_PAUSE",BI.SingleSelectTrigger.EVENT_SEARCHING="EVENT_SEARCHING",BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW="EVENT_BEFORE_COUNTER_POPUPVIEW",BI.shortcut("bi.single_select_add_trigger",BI.SingleSelectTrigger),BI.SingleSelectSearcher=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-select-searcher",itemsCreator:BI.emptyFn,el:{},popup:{},valueFormatter:BI.emptyFn,adapter:null,masker:{}})},_init:function(){BI.SingleSelectSearcher.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget(b.el,{type:"bi.single_select_editor",height:b.height}),this.searcher=BI.createWidget({type:"bi.searcher",element:this,height:b.height,isAutoSearch:!1,isAutoSync:!1,onSearch:function(a,b){b()},el:this.editor,popup:BI.extend({type:"bi.single_select_search_add_pane",valueFormatter:b.valueFormatter,keywordGetter:function(){return a.editor.getValue()},itemsCreator:function(c,d){c.keyword=a.editor.getValue(),this.setKeyword(c.keyword),b.itemsCreator(c,d)}},b.popup),adapter:b.adapter,masker:b.masker}),this.searcher.on(BI.Searcher.EVENT_START,function(){a.fireEvent(BI.SingleSelectSearcher.EVENT_START)}),this.searcher.on(BI.Searcher.EVENT_PAUSE,function(){this.hasMatched(),a.fireEvent(BI.SingleSelectSearcher.EVENT_PAUSE)}),this.searcher.on(BI.Searcher.EVENT_STOP,function(){a.fireEvent(BI.SingleSelectSearcher.EVENT_STOP)}),this.searcher.on(BI.Searcher.EVENT_CHANGE,function(){a.fireEvent(BI.SingleSelectSearcher.EVENT_CHANGE,arguments)}),this.searcher.on(BI.Searcher.EVENT_SEARCHING,function(){var b=this.getKeywords();a.fireEvent(BI.SingleSelectSearcher.EVENT_SEARCHING,b)})},adjustView:function(){this.searcher.adjustView()},isSearching:function(){return this.searcher.isSearching()},stopSearch:function(){this.searcher.stopSearch()},getKeyword:function(){return this.editor.getValue()},hasMatched:function(){return this.searcher.hasMatched()},hasChecked:function(){return this.searcher.getView()&&this.searcher.getView().hasChecked()},setAdapter:function(a){this.searcher.setAdapter(a)},setState:function(a){var b=this.options;a||(a=""),""===a?this.editor.setState(BI.Selection.None):this.editor.setState(b.valueFormatter(a+"")||a+"")},setValue:function(a){this.setState(a),this.searcher.setValue(a)},getKey:function(){return this.editor.getValue()},getValue:function(){return this.searcher.getValue()},populate:function(a){this.searcher.populate.apply(this.searcher,arguments)}}),BI.SingleSelectSearcher.EVENT_BEFORE_POPUPVIEW="EVENT_BEFORE_POPUPVIEW",BI.SingleSelectSearcher.EVENT_CHANGE="EVENT_CHANGE",BI.SingleSelectSearcher.EVENT_START="EVENT_START",BI.SingleSelectSearcher.EVENT_STOP="EVENT_STOP",BI.SingleSelectSearcher.EVENT_PAUSE="EVENT_PAUSE",BI.SingleSelectSearcher.EVENT_SEARCHING="EVENT_SEARCHING",BI.shortcut("bi.single_select_add_searcher",BI.SingleSelectSearcher),BI.SignTextEditor=BI.inherit(BI.Widget,{_defaultConfig:function(){var a=BI.SignTextEditor.superclass._defaultConfig.apply(this,arguments);return BI.extend(a,{baseCls:(a.baseCls||"")+" bi-sign-initial-editor",hgap:4,vgap:2,lgap:0,rgap:0,tgap:0,bgap:0,validationChecker:BI.emptyFn,quitChecker:BI.emptyFn,allowBlank:!0,watermark:"",errorText:"",text:"",height:24})},_init:function(){BI.SignTextEditor.superclass._init.apply(this,arguments);var a=this,b=this.options;this.editor=BI.createWidget({type:"bi.editor",height:b.height,hgap:b.hgap,vgap:b.vgap,lgap:b.lgap,rgap:b.rgap,tgap:b.tgap,bgap:b.bgap,value:b.value,validationChecker:b.validationChecker,quitChecker:b.quitChecker,allowBlank:b.allowBlank,watermark:b.watermark,errorText:b.errorText}),this.text=BI.createWidget({type:"bi.text_button",cls:"sign-editor-text",title:b.title,warningTitle:b.warningTitle,tipType:b.tipType,textAlign:"left",height:b.height,hgap:4,handler:function(){a._showInput(),a.editor.focus(),a.editor.selectAll()}}),this.text.on(BI.TextButton.EVENT_CHANGE,function(){BI.nextTick(function(){a.fireEvent(BI.SignTextEditor.EVENT_CLICK_LABEL)})}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.text,left:0,right:0,top:0,bottom:0}]}),this.editor.on(BI.Controller.EVENT_CHANGE,function(){a.fireEvent(BI.Controller.EVENT_CHANGE,arguments)}),this.editor.on(BI.Editor.EVENT_CONFIRM,function(){a._showHint(),a._checkText(),a.fireEvent(BI.SignTextEditor.EVENT_CONFIRM,arguments)}),this.editor.on(BI.Editor.EVENT_ERROR,function(){a._checkText()}),BI.createWidget({type:"bi.vertical",scrolly:!1,element:this,items:[this.editor]}),this._showHint(),a._checkText()},_checkText:function(){var a=this.options;BI.nextTick(BI.bind(function(){if(""===this.editor.getValue())this.text.setValue(a.watermark||""),this.text.element.addClass("bi-water-mark");else{var b=this.editor.getValue();b=BI.isEmpty(b)||b==a.text?a.text:b+a.text,this.text.setValue(b),this.text.element.removeClass("bi-water-mark")}},this))},_showInput:function(){this.editor.visible(),this.text.invisible()},_showHint:function(){this.editor.invisible(),this.text.visible()},setTitle:function(a){this.text.setTitle(a)},setWarningTitle:function(a){this.text.setWarningTitle(a)},focus:function(){this._showInput(),this.editor.focus()},blur:function(){this.editor.blur(),this._showHint(),this._checkText()},doRedMark:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doRedMark.apply(this.text,arguments)},unRedMark:function(){this.text.unRedMark.apply(this.text,arguments)},doHighLight:function(){""===this.editor.getValue()&&BI.isKey(this.options.watermark)||this.text.doHighLight.apply(this.text,arguments)},unHighLight:function(){this.text.unHighLight.apply(this.text,arguments)},isValid:function(){return this.editor.isValid()},setErrorText:function(a){this.editor.setErrorText(a)},getErrorText:function(){return this.editor.getErrorText()},isEditing:function(){return this.editor.isEditing()},getLastValidValue:function(){return this.editor.getLastValidValue()},setValue:function(a){this.editor.setValue(a),this._checkText()},getValue:function(){return this.editor.getValue()},getState:function(){return this.text.getValue()},setState:function(a){var b=this.options;this._showHint(),a=BI.isEmpty(a)||a==b.text?b.text:a+b.text,this.text.setValue(a)}}),BI.SignTextEditor.EVENT_CONFIRM="EVENT_CONFIRM",BI.SignTextEditor.EVENT_CLICK_LABEL="EVENT_CLICK_LABEL",BI.shortcut("bi.sign_text_editor",BI.SignTextEditor),BI.SliderIconButton=BI.inherit(BI.Widget,{_defaultConfig:function(){return BI.extend(BI.SliderIconButton.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-slider-button"})},_init:function(){BI.extend(BI.SliderIconButton.superclass._init.apply(this,arguments)),this.slider=BI.createWidget({type:"bi.icon_button",cls:"slider-icon slider-button",iconWidth:14,iconHeight:14,height:14,width:14}),BI.createWidget({type:"bi.absolute",element:this,items:[{el:this.slider,top:7,left:-7}],width:0,height:14})}}),BI.shortcut("bi.single_slider_button",BI.SliderIconButton),BI.SingleSlider=BI.inherit(BI.Widget,{_constant:{EDITOR_WIDTH:90,EDITOR_HEIGHT:30,SLIDER_WIDTH_HALF:15,SLIDER_WIDTH:30,SLIDER_HEIGHT:30,TRACK_HEIGHT:24},_defaultConfig:function(){return BI.extend(BI.SingleSlider.superclass._defaultConfig.apply(this,arguments),{baseCls:"bi-single-slider bi-slider-track",digit:!1,unit:""})},_init:function(){BI.SingleSlider.superclass._init.apply(this,arguments);var a=this,b=this.options,c=this._constant;this.enable=!1,this.value="",this.grayTrack=BI.createWidget({type:"bi.layout",cls:"gray-track",height:6}),this.blueTrack=BI.createWidget({type:"bi.layout",cls:"blue-track bi-high-light-background",height:6}),this.track=this._createTrackWrapper(),this.slider=BI.createWidget({type:"bi.single_slider_button"}),this._draggable(this.slider);var d=BI.createWidget({type:"bi.vertical",items:[{type:"bi.absolute",items:[this.slider]}],hgap:c.SLIDER_WIDTH_HALF,height:c.SLIDER_HEIGHT});d.element.click(function(d){if(a.enable){var e=d.clientX-a.element.offset().left-c.SLIDER_WIDTH_HALF,f=a.track.element[0].scrollWidth,g=0;e<0&&(g=0),e>0&&ef-c.SLIDER_WIDTH&&(g=100);var h=BI.parseFloat(g.toFixed(1));a._setAllPosition(h);var i=a._getValueByPercent(h);i=b.digit===!1?i:i.toFixed(b.digit),a.label.setValue(i),a.value=i,a.fireEvent(BI.SingleSlider.EVENT_CHANGE)}}),this.label=BI.createWidget({type:"bi.sign_text_editor",cls:"slider-editor-button",errorText:"",text:b.unit,width:c.EDITOR_WIDTH-2,allowBlank:!1,validationChecker:function(b){return a._checkValidation(b)}}),this.label.element.hover(function(){a.label.element.removeClass("bi-border").addClass("bi-border")},function(){a.label.element.removeClass("bi-border")}),this.label.on(BI.SignEditor.EVENT_CONFIRM,function(){var b=BI.parseFloat(this.getValue()),c=a._getPercentByValue(b),d=BI.parseFloat(c.toFixed(1));a._setAllPosition(d),this.setValue(b),a.value=b,a.fireEvent(BI.SingleSlider.EVENT_CHANGE)}),this._setVisible(!1),BI.createWidget({type:"bi.absolute",element:this,items:[{el:{type:"bi.vertical",items:[{type:"bi.absolute",items:[{el:this.track,width:"100%",height:c.TRACK_HEIGHT}]}],hgap:7,height:c.TRACK_HEIGHT},top:23,left:0,width:"100%"},{el:d,top:20,left:0,width:"100%"},{el:{type:"bi.vertical",items:[{type:"bi.absolute",items:[this.label]}],rgap:c.EDITOR_WIDTH,height:c.EDITOR_HEIGHT},top:0,left:0,width:"100%"}]})},_draggable:function(a){function b(a){return BI.clamp(a,0,c._getGrayTrackLength())}var c=this,d=this.options,e=!1,f=0,g=0,h=0,i=new BI.MouseMoveTracker(function(j){if(i.isDragging()){e=!0,g+=j,f=b(h+g),a.element.addClass("dragging");var k=100*f/c._getGrayTrackLength(),l=BI.parseFloat(k.toFixed(1));c._setBlueTrack(l),c._setLabelPosition(l),c._setSliderPosition(l);var m=c._getValueByPercent(l);m=d.digit===!1?m:m.toFixed(d.digit),c.label.setValue(m),c.value=m,c.fireEvent(BI.SingleSlider.EVENT_CHANGE)}},function(){if(e===!0){f=b(f);var d=100*f/c._getGrayTrackLength(),j=BI.parseFloat(d.toFixed(1));c._setSliderPosition(j),f=0,g=0,h=f,e=!1}a.element.removeClass("dragging"),i.releaseMouseMoves(),c.fireEvent(BI.SingleSlider.EVENT_CHANGE)},document);a.element.on("mousedown",function(c){a.isEnabled()&&(h=this.offsetLeft,b(h),i.captureMouseMoves(c))})},_createTrackWrapper:function(){return BI.createWidget({type:"bi.absolute",items:[{el:{type:"bi.vertical",items:[{type:"bi.absolute",items:[{el:this.grayTrack,top:0,left:0,width:"100%"},{el:this.blueTrack,top:0,left:0,width:"0%"}]}],hgap:8,height:8},top:8,left:0,width:"100%"}]})},_checkValidation:function(a){var b=this.options,c=!1;if(BI.isNumeric(a)&&!(BI.isNull(a)||athis.max))if(b.digit===!1)c=!0;else{var d=(a+"").split(".")[1]||"";c=d.length===b.digit}return c},_setBlueTrack:function(a){this.blueTrack.element.css({width:a+"%"})},_setLabelPosition:function(a){this.label.element.css({left:a+"%"})},_setSliderPosition:function(a){this.slider.element.css({left:a+"%"})},_setAllPosition:function(a){this._setSliderPosition(a),this._setLabelPosition(a),this._setBlueTrack(a)},_setVisible:function(a){this.slider.setVisible(a),this.label.setVisible(a)},_getGrayTrackLength:function(){return this.grayTrack.element[0].scrollWidth},_getValueByPercent:function(a){var b=BI.parseInt(10*a);return(this.max-this.min)*b/1e3+this.min},_getPercentByValue:function(a){return 100*(a-this.min)/(this.max-this.min)},getValue:function(){return this.value},setValue:function(a){var b=this.options;a=BI.parseFloat(a),a=b.digit===!1?a:a.toFixed(b.digit),isNaN(a)||(this._checkValidation(a)&&(this.value=a),a>this.max&&(this.value=this.max),ab&&(this.min=b,this.max=c)},reset:function(){this._setVisible(!1),this.enable=!1,this.value="",this.min=0,this.max=0,this._setBlueTrack(0)},populate:function(){isNaN(this.min)||isNaN(this.max)||(this._setVisible(!0), diff --git a/dist/case.js b/dist/case.js index 5e0d04b95..ccc64a8ff 100644 --- a/dist/case.js +++ b/dist/case.js @@ -18,16 +18,16 @@ BI.IconChangeButton = BI.inherit(BI.Single, { stopEvent: false, stopPropagation: false, selected: false, - once: false, //点击一次选中有效,再点无效 - forceSelected: false, //点击即选中, 选中了就不会被取消 - forceNotSelected: false, //无论怎么点击都不会被选中 - disableSelected: false, //使能选中 + once: false, // 点击一次选中有效,再点无效 + forceSelected: false, // 点击即选中, 选中了就不会被取消 + forceNotSelected: false, // 无论怎么点击都不会被选中 + disableSelected: false, // 使能选中 shadow: false, - isShadowShowingOnSelected: false, //选中状态下是否显示阴影 + isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 trigger: null, handler: BI.emptyFn - }) + }); }, _init: function () { @@ -86,8 +86,8 @@ BI.shortcut("bi.icon_change_button", BI.IconChangeButton);/** * @type {*|void|Object} */ BI.HalfIconButton = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.HalfIconButton.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.HalfIconButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-half-icon-button check-half-select-icon", height: 16, @@ -95,16 +95,16 @@ BI.HalfIconButton = BI.inherit(BI.IconButton, { iconWidth: 16, iconHeight: 16, selected: false - }) + }); }, - _init : function() { + _init: function () { BI.HalfIconButton.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.HalfIconButton.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.HalfIconButton.EVENT_CHANGE); } } @@ -153,7 +153,7 @@ BI.MultiSelectItem = BI.inherit(BI.BasicButton, { logic: { dynamic: false } - }) + }); }, _init: function () { BI.MultiSelectItem.superclass._init.apply(this, arguments); @@ -227,7 +227,7 @@ BI.SingleSelectIconTextItem = BI.inherit(BI.Single, { iconClass: "", hgap: 10, height: 25 - }) + }); }, _init: function () { BI.SingleSelectIconTextItem.superclass._init.apply(this, arguments); @@ -284,7 +284,7 @@ BI.SingleSelectItem = BI.inherit(BI.BasicButton, { hgap: 10, height: 25, textAlign: "left" - }) + }); }, _init: function () { BI.SingleSelectItem.superclass._init.apply(this, arguments); @@ -335,7 +335,7 @@ BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, { }, hgap: 10, height: 25 - }) + }); }, _init: function () { BI.SingleSelectRadioItem.superclass._init.apply(this, arguments); @@ -488,7 +488,7 @@ BI.FirstPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.FirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -573,7 +573,7 @@ BI.IconArrowNode = BI.inherit(BI.NodeButton, { iconHeight: 13, iconWidth: 13, iconCls: "" - }) + }); }, _init: function () { BI.IconArrowNode.superclass._init.apply(this, arguments); @@ -669,7 +669,7 @@ BI.LastPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.LastPlusGroupNode.superclass._init.apply(this, arguments); @@ -749,7 +749,7 @@ BI.MidPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MidPlusGroupNode.superclass._init.apply(this, arguments); @@ -816,7 +816,7 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro var conf = BI.MultiLayerIconArrowNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-icon-arrow-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, @@ -824,7 +824,7 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro iconHeight: 13, iconWidth: 13, iconCls: "" - }) + }); }, _init: function () { BI.MultiLayerIconArrowNode.superclass._init.apply(this, arguments); @@ -832,9 +832,9 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro this.node = BI.createWidget({ type: "bi.icon_arrow_node", iconCls: o.iconCls, - //logic: { + // logic: { // dynamic: true - //}, + // }, id: o.id, pId: o.pId, open: o.open, @@ -857,7 +857,7 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro type: "bi.layout", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -865,7 +865,7 @@ BI.shortcut("bi.mid_plus_group_node", BI.MidPlusGroupNode);BI.MultiLayerIconArro element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, isOnce: function () { @@ -918,7 +918,7 @@ BI.PlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.PlusGroupNode.superclass._init.apply(this, arguments); @@ -994,7 +994,7 @@ BI.TriangleGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.TriangleGroupNode.superclass._init.apply(this, arguments); @@ -1052,7 +1052,7 @@ BI.TriangleGroupNode = BI.inherit(BI.NodeButton, { this.checkbox.setSelected(v); }, - setText: function(text){ + setText: function (text) { BI.TriangleGroupNode.superclass.setText.apply(this, arguments); this.text.setText(text); } @@ -1074,7 +1074,7 @@ BI.FirstTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.FirstTreeLeafItem.superclass._init.apply(this, arguments); @@ -1172,7 +1172,7 @@ BI.shortcut("bi.first_tree_leaf_item", BI.FirstTreeLeafItem);BI.IconTreeLeafItem iconWidth: 16, iconHeight: 16, iconCls: "" - }) + }); }, _init: function () { @@ -1264,7 +1264,7 @@ BI.LastTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.LastTreeLeafItem.superclass._init.apply(this, arguments); @@ -1367,7 +1367,7 @@ BI.MidTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.MidTreeLeafItem.superclass._init.apply(this, arguments); @@ -1467,7 +1467,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { iconCls: "", iconHeight: 14, iconWidth: 12 - }) + }); }, _init: function () { BI.MultiLayerIconTreeLeafItem.superclass._init.apply(this, arguments); @@ -1488,7 +1488,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { iconHeight: o.iconHeight }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -1500,7 +1500,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { type: "bi.layout", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -1545,7 +1545,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { this.item.setSelected(v); }, - getValue: function(){ + getValue: function () { return this.options.value; } }); @@ -1557,7 +1557,7 @@ BI.shortcut("bi.multilayer_icon_tree_leaf_item", BI.MultiLayerIconTreeLeafItem); * @extends BI.BasicButton */ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend(BI.TreeTextLeafItem.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-tree-text-leaf-item bi-list-item-active", id: "", @@ -1566,9 +1566,9 @@ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { hgap: 0, lgap: 0, rgap: 0 - }) + }); }, - _init : function() { + _init: function () { BI.TreeTextLeafItem.superclass._init.apply(this, arguments); var self = this, o = this.options; this.text = BI.createWidget({ @@ -1590,30 +1590,30 @@ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { items: [{ el: this.text }] - }) + }); }, - doRedMark: function(){ + doRedMark: function () { this.text.doRedMark.apply(this.text, arguments); }, - unRedMark: function(){ + unRedMark: function () { this.text.unRedMark.apply(this.text, arguments); }, - doHighLight: function(){ + doHighLight: function () { this.text.doHighLight.apply(this.text, arguments); }, - unHighLight: function(){ + unHighLight: function () { this.text.unHighLight.apply(this.text, arguments); }, - getId: function(){ + getId: function () { return this.options.id; }, - getPId: function(){ + getPId: function () { return this.options.pId; } }); @@ -1631,12 +1631,12 @@ BI.Calendar = BI.inherit(BI.Widget, { logic: { dynamic: false }, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 year: 2015, - month: 7, //7表示八月 + month: 7, // 7表示八月 day: 25 - }) + }); }, _dateCreator: function (Y, M, D) { @@ -1682,7 +1682,7 @@ BI.Calendar = BI.inherit(BI.Widget, { } td.text = DD; items.push(td); - }) + }); return items; }, @@ -1694,13 +1694,13 @@ BI.Calendar = BI.inherit(BI.Widget, { type: "bi.label", height: 25, text: value - } - }) + }; + }); var title = BI.createWidget({ type: "bi.button_group", height: 25, items: items - }) + }); var days = this._dateCreator(o.year, o.month, o.day); items = []; items.push(days.slice(0, 7)); @@ -1722,7 +1722,7 @@ BI.Calendar = BI.inherit(BI.Widget, { height: 25, value: o.year + "-" + o.month + "-" + td.text, disabled: td.lastMonth || td.nextMonth || td.disabled - //selected: td.currentDay + // selected: td.currentDay }); }); }); @@ -1739,7 +1739,7 @@ BI.Calendar = BI.inherit(BI.Widget, { }); this.days.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); BI.createWidget(BI.extend({ element: this @@ -1776,7 +1776,7 @@ BI.Calendar = BI.inherit(BI.Widget, { year: date[0] | 0, month: date[1] | 0, day: date[2] | 0 - } + }; } }); @@ -1788,22 +1788,22 @@ BI.extend(BI.Calendar, { page += json.month - month; return page; }, - getDateJSONByPage: function(v){ + getDateJSONByPage: function (v) { var months = Date.getDate().getMonth(); var page = v; - //对当前page做偏移,使到当前年初 + // 对当前page做偏移,使到当前年初 page = page + months; var year = BI.parseInt(page / 12); - if(page < 0 && page % 12 !== 0){ + if(page < 0 && page % 12 !== 0) { year--; } var month = page >= 0 ? (page % 12) : ((12 + page % 12) % 12); return { year: Date.getDate().getFullYear() + year, month: month - } + }; } }); @@ -1822,10 +1822,10 @@ BI.YearCalendar = BI.inherit(BI.Widget, { logic: { dynamic: false }, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 year: null - }) + }); }, _yearCreator: function (Y) { @@ -1850,7 +1850,7 @@ BI.YearCalendar = BI.inherit(BI.Widget, { this.currentYear = Date.getDate().getFullYear(); var years = this._yearCreator(o.year || this.currentYear); - //纵向排列年 + // 纵向排列年 var len = years.length, tyears = BI.makeArray(len, ""); var map = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; BI.each(years, function (i, y) { @@ -1928,11 +1928,11 @@ BI.YearCalendar = BI.inherit(BI.Widget, { return this.years.getValue()[0]; } }); -//类方法 +// 类方法 BI.extend(BI.YearCalendar, { INTERVAL: 12, - //获取显示的第一年 + // 获取显示的第一年 getStartYear: function (year) { var cur = Date.getDate().getFullYear(); return year - ((year - cur + 3) % BI.YearCalendar.INTERVAL + 12) % BI.YearCalendar.INTERVAL; @@ -1960,7 +1960,7 @@ BI.ComplexCanvas = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.ComplexCanvas.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-complex-canvas" - }) + }); }, @@ -1975,7 +1975,7 @@ BI.ComplexCanvas = BI.inherit(BI.Widget, { }); }, - //绘制树枝节点 + // 绘制树枝节点 branch: function (x0, y0, x1, y1, x2, y2) { var self = this, args = [].slice.call(arguments); if (args.length <= 5) { @@ -2044,18 +2044,18 @@ BI.shortcut("bi.complex_canvas", BI.ComplexCanvas);/** * Created by roy on 15/10/16. * 上箭头与下箭头切换的树节点 */ -BI.ArrowTreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{ - _defaultConfig:function(){ - return BI.extend(BI.ArrowTreeGroupNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{ - extraCls:"bi-arrow-tree-group-node", +BI.ArrowTreeGroupNodeCheckbox = BI.inherit(BI.IconButton, { + _defaultConfig: function () { + return BI.extend(BI.ArrowTreeGroupNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { + extraCls: "bi-arrow-tree-group-node", iconWidth: 13, iconHeight: 13 }); }, - _init:function(){ - BI.ArrowTreeGroupNodeCheckbox.superclass._init.apply(this,arguments); + _init: function () { + BI.ArrowTreeGroupNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.ArrowTreeGroupNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.removeClass("column-next-page-h-font").addClass("column-pre-page-h-font"); @@ -2064,27 +2064,27 @@ BI.ArrowTreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{ } } }); -BI.shortcut("bi.arrow_tree_group_node_checkbox",BI.ArrowTreeGroupNodeCheckbox);/** +BI.shortcut("bi.arrow_tree_group_node_checkbox", BI.ArrowTreeGroupNodeCheckbox);/** * 十字型的树节点 * @class BI.CheckingMarkNode * @extends BI.IconButton */ BI.CheckingMarkNode = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.CheckingMarkNode.superclass._defaultConfig.apply(this, arguments), { extraCls: "check-mark-font", iconWidth: 13, iconHeight: 13 }); }, - _init:function() { + _init: function () { BI.CheckingMarkNode.superclass._init.apply(this, arguments); this.setSelected(this.options.selected); }, - setSelected: function(v){ + setSelected: function (v) { BI.CheckingMarkNode.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("check-mark-font"); } else { this.element.removeClass("check-mark-font"); @@ -2097,20 +2097,20 @@ BI.shortcut("bi.checking_mark_node", BI.CheckingMarkNode);/** * @extends BI.IconButton */ BI.FirstTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.FirstTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type2", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.FirstTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.FirstTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type2"); } else { this.element.removeClass("tree-expand-icon-type2"); @@ -2123,20 +2123,20 @@ BI.shortcut("bi.first_tree_node_checkbox", BI.FirstTreeNodeCheckbox);/** * @extends BI.IconButton */ BI.LastTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.LastTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type4", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.LastTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.LastTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type3"); } else { this.element.removeClass("tree-expand-icon-type3"); @@ -2149,20 +2149,20 @@ BI.shortcut("bi.last_tree_node_checkbox", BI.LastTreeNodeCheckbox);/** * @extends BI.IconButton */ BI.MidTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.MidTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type3", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.MidTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.MidTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type3"); } else { this.element.removeClass("tree-expand-icon-type3"); @@ -2176,18 +2176,18 @@ BI.shortcut("bi.mid_tree_node_checkbox", BI.MidTreeNodeCheckbox);/** * @extends BI.IconButton */ BI.TreeGroupNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.TreeGroupNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-node-triangle-collapse-font", iconWidth: 13, iconHeight: 13 }); }, - _init:function() { + _init: function () { BI.TreeGroupNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.TreeGroupNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.removeClass("tree-node-triangle-collapse-font").addClass("tree-node-triangle-expand-font"); @@ -2202,18 +2202,18 @@ BI.shortcut("bi.tree_group_node_checkbox", BI.TreeGroupNodeCheckbox);/** * @extends BI.IconButton */ BI.TreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.TreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type1", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.TreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.TreeNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.addClass("tree-expand-icon-type1"); @@ -2222,55 +2222,55 @@ BI.TreeNodeCheckbox = BI.inherit(BI.IconButton, { } } }); -BI.shortcut("bi.tree_node_checkbox", BI.TreeNodeCheckbox);/*! +BI.shortcut("bi.tree_node_checkbox", BI.TreeNodeCheckbox);/* ! * clipboard.js v1.6.1 * https://zenorocha.github.io/clipboard.js * * Licensed MIT © Zeno Rocha */ -try {//IE8下会抛错 +try {// IE8下会抛错 (function (f) { if (typeof exports === "object" && typeof module !== "undefined") { - module.exports = f() + module.exports = f(); } else if (typeof define === "function" && define.amd) { - define([], f) + define([], f); } else { var g; if (typeof window !== "undefined") { - g = window + g = window; } else if (typeof global !== "undefined") { - g = global + g = global; } else if (typeof self !== "undefined") { - g = self + g = self; } else { - g = this + g = this; } - g.Clipboard = f() + g.Clipboard = f(); } })(function () { var define, module, exports; - return (function e(t, n, r) { - function s(o, u) { + return (function e (t, n, r) { + function s (o, u) { if (!n[o]) { if (!t[o]) { - var a = typeof require == "function" && require; + 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 + 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 s(n ? n : e); + }, l, l.exports, e, t, n, r); } - return n[o].exports + return n[o].exports; } - var i = typeof require == "function" && require; + var i = typeof require === "function" && require; for (var o = 0; o < r.length; o++)s(r[o]); - return s + return s; })({ 1: [function (require, module, exports) { var DOCUMENT_NODE_TYPE = 9; @@ -2278,7 +2278,7 @@ try {//IE8下会抛错 /** * A polyfill for Element.matches() */ - if (typeof Element !== 'undefined' && !Element.prototype.matches) { + if (typeof Element !== "undefined" && !Element.prototype.matches) { var proto = Element.prototype; proto.matches = proto.matchesSelector || @@ -2295,7 +2295,7 @@ try {//IE8下会抛错 * @param {String} selector * @return {Function} */ - function closest(element, selector) { + function closest (element, selector) { while (element && element.nodeType !== DOCUMENT_NODE_TYPE) { if (element.matches(selector)) return element; element = element.parentNode; @@ -2305,7 +2305,7 @@ try {//IE8下会抛错 module.exports = closest; }, {}], 2: [function (require, module, exports) { - var closest = require('./closest'); + var closest = require("./closest"); /** * Delegates event to a selector. @@ -2317,7 +2317,7 @@ try {//IE8下会抛错 * @param {Boolean} useCapture * @return {Object} */ - function delegate(element, selector, type, callback, useCapture) { + function delegate (element, selector, type, callback, useCapture) { var listenerFn = listener.apply(this, arguments); element.addEventListener(type, listenerFn, useCapture); @@ -2326,7 +2326,7 @@ try {//IE8下会抛错 destroy: function () { element.removeEventListener(type, listenerFn, useCapture); } - } + }; } /** @@ -2338,14 +2338,14 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Function} */ - function listener(element, selector, type, callback) { + function listener (element, selector, type, callback) { return function (e) { e.delegateTarget = closest(e.target, selector); if (e.delegateTarget) { callback.call(element, e); } - } + }; } module.exports = delegate; @@ -2373,8 +2373,8 @@ try {//IE8下会抛错 var type = Object.prototype.toString.call(value); return value !== undefined - && (type === '[object NodeList]' || type === '[object HTMLCollection]') - && ('length' in value) + && (type === "[object NodeList]" || type === "[object HTMLCollection]") + && ("length" in value) && (value.length === 0 || exports.node(value[0])); }; @@ -2385,7 +2385,7 @@ try {//IE8下会抛错 * @return {Boolean} */ exports.string = function (value) { - return typeof value === 'string' + return typeof value === "string" || value instanceof String; }; @@ -2398,12 +2398,12 @@ try {//IE8下会抛错 exports.fn = function (value) { var type = Object.prototype.toString.call(value); - return type === '[object Function]'; + return type === "[object Function]"; }; }, {}], 4: [function (require, module, exports) { - var is = require('./is'); - var delegate = require('delegate'); + var is = require("./is"); + var delegate = require("delegate"); /** * Validates all params and calls the right @@ -2414,31 +2414,29 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listen(target, type, callback) { + function listen (target, type, callback) { if (!target && !type && !callback) { - throw new Error('Missing required arguments'); + throw new Error("Missing required arguments"); } if (!is.string(type)) { - throw new TypeError('Second argument must be a String'); + throw new TypeError("Second argument must be a String"); } if (!is.fn(callback)) { - throw new TypeError('Third argument must be a Function'); + throw new TypeError("Third argument must be a Function"); } if (is.node(target)) { return listenNode(target, type, callback); - } - else if (is.nodeList(target)) { + } else if (is.nodeList(target)) { return listenNodeList(target, type, callback); - } - else if (is.string(target)) { + } else if (is.string(target)) { return listenSelector(target, type, callback); } - else { - throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList'); - } + + throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList"); + } /** @@ -2450,14 +2448,14 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenNode(node, type, callback) { + function listenNode (node, type, callback) { node.addEventListener(type, callback); return { destroy: function () { node.removeEventListener(type, callback); } - } + }; } /** @@ -2469,7 +2467,7 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenNodeList(nodeList, type, callback) { + function listenNodeList (nodeList, type, callback) { Array.prototype.forEach.call(nodeList, function (node) { node.addEventListener(type, callback); }); @@ -2480,7 +2478,7 @@ try {//IE8下会抛错 node.removeEventListener(type, callback); }); } - } + }; } /** @@ -2492,39 +2490,37 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenSelector(selector, type, callback) { + function listenSelector (selector, type, callback) { return delegate(document.body, selector, type, callback); } module.exports = listen; - }, {"./is": 3, "delegate": 2}], 5: [function (require, module, exports) { - function select(element) { + }, {"./is": 3, delegate: 2}], 5: [function (require, module, exports) { + function select (element) { var selectedText; - if (element.nodeName === 'SELECT') { + if (element.nodeName === "SELECT") { element.focus(); selectedText = element.value; - } - else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') { - var isReadOnly = element.hasAttribute('readonly'); + } else if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") { + var isReadOnly = element.hasAttribute("readonly"); if (!isReadOnly) { - element.setAttribute('readonly', ''); + element.setAttribute("readonly", ""); } element.select(); element.setSelectionRange(0, element.value.length); if (!isReadOnly) { - element.removeAttribute('readonly'); + element.removeAttribute("readonly"); } selectedText = element.value; - } - else { - if (element.hasAttribute('contenteditable')) { + } else { + if (element.hasAttribute("contenteditable")) { element.focus(); } @@ -2544,7 +2540,7 @@ try {//IE8下会抛错 module.exports = select; }, {}], 6: [function (require, module, exports) { - function E() { + function E () { // Keep this empty so it's easier to inherit from // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) } @@ -2564,12 +2560,12 @@ try {//IE8下会抛错 once: function (name, callback, ctx) { var self = this; - function listener() { + function listener () { self.off(name, listener); callback.apply(ctx, arguments); - }; + } - listener._ = callback + listener._ = callback; return this.on(name, listener, ctx); }, @@ -2593,8 +2589,7 @@ try {//IE8下会抛错 if (evts && callback) { for (var i = 0, len = evts.length; i < len; i++) { - if (evts[i].fn !== callback && evts[i].fn._ !== callback) - liveEvents.push(evts[i]); + if (evts[i].fn !== callback && evts[i].fn._ !== callback) {liveEvents.push(evts[i]);} } } @@ -2615,9 +2610,9 @@ try {//IE8下会抛错 }, {}], 7: [function (require, module, exports) { (function (global, factory) { if (typeof define === "function" && define.amd) { - define(['module', 'select'], factory); + define(["module", "select"], factory); } else if (typeof exports !== "undefined") { - factory(module, require('select')); + factory(module, require("select")); } else { var mod = { exports: {} @@ -2626,13 +2621,13 @@ try {//IE8下会抛错 global.clipboardAction = mod.exports; } })(this, function (module, _select) { - 'use strict'; + "use strict"; var _select2 = _interopRequireDefault(_select); - function _interopRequireDefault(obj) { + function _interopRequireDefault (obj) { return obj && obj.__esModule ? obj : { - "default": obj + default: obj }; } @@ -2642,14 +2637,14 @@ try {//IE8下会抛错 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - function _classCallCheck(instance, Constructor) { + function _classCallCheck (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { - function defineProperties(target, props) { + function defineProperties (target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; @@ -2670,7 +2665,7 @@ try {//IE8下会抛错 /** * @param {Object} options */ - function ClipboardAction(options) { + function ClipboardAction (options) { _classCallCheck(this, ClipboardAction); this.resolveOptions(options); @@ -2684,8 +2679,8 @@ try {//IE8下会抛错 _createClass(ClipboardAction, [{ - key: 'resolveOptions', - value: function resolveOptions() { + key: "resolveOptions", + value: function resolveOptions () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.action = options.action; @@ -2694,11 +2689,11 @@ try {//IE8下会抛错 this.text = options.text; this.trigger = options.trigger; - this.selectedText = ''; + this.selectedText = ""; } }, { - key: 'initSelection', - value: function initSelection() { + key: "initSelection", + value: function initSelection () { if (this.text) { this.selectFake(); } else if (this.target) { @@ -2706,34 +2701,34 @@ try {//IE8下会抛错 } } }, { - key: 'selectFake', - value: function selectFake() { + key: "selectFake", + value: function selectFake () { var _this = this; - var isRTL = document.documentElement.getAttribute('dir') == 'rtl'; + var isRTL = document.documentElement.getAttribute("dir") == "rtl"; this.removeFake(); this.fakeHandlerCallback = function () { return _this.removeFake(); }; - this.fakeHandler = document.body.addEventListener('click', this.fakeHandlerCallback) || true; + this.fakeHandler = document.body.addEventListener("click", this.fakeHandlerCallback) || true; - this.fakeElem = document.createElement('textarea'); + this.fakeElem = document.createElement("textarea"); // Prevent zooming on iOS - this.fakeElem.style.fontSize = '12pt'; + this.fakeElem.style.fontSize = "12pt"; // Reset box model - this.fakeElem.style.border = '0'; - this.fakeElem.style.padding = '0'; - this.fakeElem.style.margin = '0'; + this.fakeElem.style.border = "0"; + this.fakeElem.style.padding = "0"; + this.fakeElem.style.margin = "0"; // Move element out of screen horizontally - this.fakeElem.style.position = 'absolute'; - this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px'; + this.fakeElem.style.position = "absolute"; + this.fakeElem.style[isRTL ? "right" : "left"] = "-9999px"; // Move element to the same position vertically var yPosition = window.pageYOffset || document.documentElement.scrollTop; - this.fakeElem.style.top = yPosition + 'px'; + this.fakeElem.style.top = yPosition + "px"; - this.fakeElem.setAttribute('readonly', ''); + this.fakeElem.setAttribute("readonly", ""); this.fakeElem.value = this.text; document.body.appendChild(this.fakeElem); @@ -2742,10 +2737,10 @@ try {//IE8下会抛错 this.copyText(); } }, { - key: 'removeFake', - value: function removeFake() { + key: "removeFake", + value: function removeFake () { if (this.fakeHandler) { - document.body.removeEventListener('click', this.fakeHandlerCallback); + document.body.removeEventListener("click", this.fakeHandlerCallback); this.fakeHandler = null; this.fakeHandlerCallback = null; } @@ -2756,14 +2751,14 @@ try {//IE8下会抛错 } } }, { - key: 'selectTarget', - value: function selectTarget() { + key: "selectTarget", + value: function selectTarget () { this.selectedText = (0, _select2["default"])(this.target); this.copyText(); } }, { - key: 'copyText', - value: function copyText() { + key: "copyText", + value: function copyText () { var succeeded = void 0; try { @@ -2775,9 +2770,9 @@ try {//IE8下会抛错 this.handleResult(succeeded); } }, { - key: 'handleResult', - value: function handleResult(succeeded) { - this.emitter.emit(succeeded ? 'success' : 'error', { + key: "handleResult", + value: function handleResult (succeeded) { + this.emitter.emit(succeeded ? "success" : "error", { action: this.action, text: this.selectedText, trigger: this.trigger, @@ -2785,8 +2780,8 @@ try {//IE8下会抛错 }); } }, { - key: 'clearSelection', - value: function clearSelection() { + key: "clearSelection", + value: function clearSelection () { if (this.target) { this.target.blur(); } @@ -2794,44 +2789,44 @@ try {//IE8下会抛错 window.getSelection().removeAllRanges(); } }, { - key: 'destroy', - value: function destroy() { + key: "destroy", + value: function destroy () { this.removeFake(); } }, { - key: 'action', - set: function set() { - var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'copy'; + key: "action", + set: function set () { + var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "copy"; this._action = action; - if (this._action !== 'copy' && this._action !== 'cut') { - throw new Error('Invalid "action" value, use either "copy" or "cut"'); + if (this._action !== "copy" && this._action !== "cut") { + throw new Error("Invalid \"action\" value, use either \"copy\" or \"cut\""); } }, - get: function get() { + get: function get () { return this._action; } }, { - key: 'target', - set: function set(target) { + key: "target", + set: function set (target) { if (target !== undefined) { - if (target && (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target.nodeType === 1) { - if (this.action === 'copy' && target.hasAttribute('disabled')) { - throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute'); + if (target && (typeof target === "undefined" ? "undefined" : _typeof(target)) === "object" && target.nodeType === 1) { + if (this.action === "copy" && target.hasAttribute("disabled")) { + throw new Error("Invalid \"target\" attribute. Please use \"readonly\" instead of \"disabled\" attribute"); } - if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) { - throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes'); + if (this.action === "cut" && (target.hasAttribute("readonly") || target.hasAttribute("disabled"))) { + throw new Error("Invalid \"target\" attribute. You can't cut text from elements with \"readonly\" or \"disabled\" attributes"); } this._target = target; } else { - throw new Error('Invalid "target" value, use a valid Element'); + throw new Error("Invalid \"target\" value, use a valid Element"); } } }, - get: function get() { + get: function get () { return this._target; } }]); @@ -2842,12 +2837,12 @@ try {//IE8下会抛错 module.exports = ClipboardAction; }); - }, {"select": 5}], 8: [function (require, module, exports) { + }, {select: 5}], 8: [function (require, module, exports) { (function (global, factory) { if (typeof define === "function" && define.amd) { - define(['module', './clipboard-action', 'tiny-emitter', 'good-listener'], factory); + define(["module", "./clipboard-action", "tiny-emitter", "good-listener"], factory); } else if (typeof exports !== "undefined") { - factory(module, require('./clipboard-action'), require('tiny-emitter'), require('good-listener')); + factory(module, require("./clipboard-action"), require("tiny-emitter"), require("good-listener")); } else { var mod = { exports: {} @@ -2856,7 +2851,7 @@ try {//IE8下会抛错 global.clipboard = mod.exports; } })(this, function (module, _clipboardAction, _tinyEmitter, _goodListener) { - 'use strict'; + "use strict"; var _clipboardAction2 = _interopRequireDefault(_clipboardAction); @@ -2864,20 +2859,20 @@ try {//IE8下会抛错 var _goodListener2 = _interopRequireDefault(_goodListener); - function _interopRequireDefault(obj) { + function _interopRequireDefault (obj) { return obj && obj.__esModule ? obj : { - "default": obj + default: obj }; } - function _classCallCheck(instance, Constructor) { + function _classCallCheck (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { - function defineProperties(target, props) { + function defineProperties (target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; @@ -2894,7 +2889,7 @@ try {//IE8下会抛错 }; }(); - function _possibleConstructorReturn(self, call) { + function _possibleConstructorReturn (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } @@ -2902,7 +2897,7 @@ try {//IE8下会抛错 return call && (typeof call === "object" || typeof call === "function") ? call : self; } - function _inherits(subClass, superClass) { + function _inherits (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } @@ -2925,7 +2920,7 @@ try {//IE8下会抛错 * @param {String|HTMLElement|HTMLCollection|NodeList} trigger * @param {Object} options */ - function Clipboard(trigger, options) { + function Clipboard (trigger, options) { _classCallCheck(this, Clipboard); var _this = _possibleConstructorReturn(this, (Clipboard.__proto__ || Object.getPrototypeOf(Clipboard)).call(this)); @@ -2943,26 +2938,26 @@ try {//IE8下会抛错 _createClass(Clipboard, [{ - key: 'resolveOptions', - value: function resolveOptions() { + key: "resolveOptions", + value: function resolveOptions () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - this.action = typeof options.action === 'function' ? options.action : this.defaultAction; - this.target = typeof options.target === 'function' ? options.target : this.defaultTarget; - this.text = typeof options.text === 'function' ? options.text : this.defaultText; + this.action = typeof options.action === "function" ? options.action : this.defaultAction; + this.target = typeof options.target === "function" ? options.target : this.defaultTarget; + this.text = typeof options.text === "function" ? options.text : this.defaultText; } }, { - key: 'listenClick', - value: function listenClick(trigger) { + key: "listenClick", + value: function listenClick (trigger) { var _this2 = this; - this.listener = (0, _goodListener2["default"])(trigger, 'click', function (e) { + this.listener = (0, _goodListener2["default"])(trigger, "click", function (e) { return _this2.onClick(e); }); } }, { - key: 'onClick', - value: function onClick(e) { + key: "onClick", + value: function onClick (e) { var trigger = e.delegateTarget || e.currentTarget; if (this.clipboardAction) { @@ -2978,27 +2973,27 @@ try {//IE8下会抛错 }); } }, { - key: 'defaultAction', - value: function defaultAction(trigger) { - return getAttributeValue('action', trigger); + key: "defaultAction", + value: function defaultAction (trigger) { + return getAttributeValue("action", trigger); } }, { - key: 'defaultTarget', - value: function defaultTarget(trigger) { - var selector = getAttributeValue('target', trigger); + key: "defaultTarget", + value: function defaultTarget (trigger) { + var selector = getAttributeValue("target", trigger); if (selector) { return document.querySelector(selector); } } }, { - key: 'defaultText', - value: function defaultText(trigger) { - return getAttributeValue('text', trigger); + key: "defaultText", + value: function defaultText (trigger) { + return getAttributeValue("text", trigger); } }, { - key: 'destroy', - value: function destroy() { + key: "destroy", + value: function destroy () { this.listener.destroy(); if (this.clipboardAction) { @@ -3007,11 +3002,11 @@ try {//IE8下会抛错 } } }], [{ - key: 'isSupported', - value: function isSupported() { - var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut']; + key: "isSupported", + value: function isSupported () { + var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ["copy", "cut"]; - var actions = typeof action === 'string' ? [action] : action; + var actions = typeof action === "string" ? [action] : action; var support = !!document.queryCommandSupported; actions.forEach(function (action) { @@ -3030,8 +3025,8 @@ try {//IE8下会抛错 * @param {String} suffix * @param {Element} element */ - function getAttributeValue(suffix, element) { - var attribute = 'data-clipboard-' + suffix; + function getAttributeValue (suffix, element) { + var attribute = "data-clipboard-" + suffix; if (!element.hasAttribute(attribute)) { return; @@ -3044,7 +3039,7 @@ try {//IE8下会抛错 }); }, {"./clipboard-action": 7, "good-listener": 4, "tiny-emitter": 6}] - }, {}, [8])(8) + }, {}, [8])(8); }); } catch (e) { /* @@ -3063,11 +3058,11 @@ try {//IE8下会抛错 $.fn.zclip = function (params) { - if (typeof params == "object" && !params.length) { + if (typeof params === "object" && !params.length) { var settings = $.extend({ - path: 'ZeroClipboard.swf', + path: "ZeroClipboard.swf", copy: null, beforeCopy: null, afterCopy: null, @@ -3082,62 +3077,62 @@ try {//IE8下会抛错 var o = $(this); - if (o.is(':visible') && (typeof settings.copy == 'string' || $.isFunction(settings.copy))) { + if (o.is(":visible") && (typeof settings.copy === "string" || $.isFunction(settings.copy))) { ZeroClipboard.setMoviePath(settings.path); var clip = new ZeroClipboard.Client(); if ($.isFunction(settings.copy)) { - o.bind('zClip_copy', settings.copy); + o.bind("zClip_copy", settings.copy); } if ($.isFunction(settings.beforeCopy)) { - o.bind('zClip_beforeCopy', settings.beforeCopy); + o.bind("zClip_beforeCopy", settings.beforeCopy); } if ($.isFunction(settings.afterCopy)) { - o.bind('zClip_afterCopy', settings.afterCopy); + o.bind("zClip_afterCopy", settings.afterCopy); } clip.setHandCursor(settings.setHandCursor); clip.setCSSEffects(settings.setCSSEffects); - clip.addEventListener('mouseOver', function (client) { - o.trigger('mouseenter'); + clip.addEventListener("mouseOver", function (client) { + o.trigger("mouseenter"); }); - clip.addEventListener('mouseOut', function (client) { - o.trigger('mouseleave'); + clip.addEventListener("mouseOut", function (client) { + o.trigger("mouseleave"); }); - clip.addEventListener('mouseDown', function (client) { + clip.addEventListener("mouseDown", function (client) { - o.trigger('mousedown'); + o.trigger("mousedown"); if (!$.isFunction(settings.copy)) { clip.setText(settings.copy); } else { - clip.setText(o.triggerHandler('zClip_copy')); + clip.setText(o.triggerHandler("zClip_copy")); } if ($.isFunction(settings.beforeCopy)) { - o.trigger('zClip_beforeCopy'); + o.trigger("zClip_beforeCopy"); } }); - clip.addEventListener('complete', function (client, text) { + clip.addEventListener("complete", function (client, text) { if ($.isFunction(settings.afterCopy)) { - o.trigger('zClip_afterCopy'); + o.trigger("zClip_afterCopy"); } else { if (text.length > 500) { text = text.substr(0, 500) + "...\n\n(" + (text.length - 500) + " characters not shown)"; } - o.removeClass('hover'); + o.removeClass("hover"); alert("Copied text to clipboard:\n\n " + text); } if (settings.clickAfter) { - o.trigger('click'); + o.trigger("click"); } }); @@ -3145,7 +3140,7 @@ try {//IE8下会抛错 clip.glue(o[0], o.parent()[0]); - $(window).bind('load resize', function () { + $(window).bind("load resize", function () { clip.reposition(); }); @@ -3154,25 +3149,25 @@ try {//IE8下会抛错 }); - } else if (typeof params == "string") { + } else if (typeof params === "string") { return this.each(function () { var o = $(this); params = params.toLowerCase(); - var zclipId = o.data('zclipId'); - var clipElm = $('#' + zclipId + '.zclip'); + var zclipId = o.data("zclipId"); + var clipElm = $("#" + zclipId + ".zclip"); if (params == "remove") { clipElm.remove(); - o.removeClass('active hover'); + o.removeClass("active hover"); } else if (params == "hide") { clipElm.hide(); - o.removeClass('active hover'); + o.removeClass("active hover"); } else if (params == "show") { @@ -3184,38 +3179,38 @@ try {//IE8下会抛错 } - } + }; })(jQuery); -// ZeroClipboard -// Simple Set Clipboard System -// Author: Joseph Huckaby + // ZeroClipboard + // Simple Set Clipboard System + // Author: Joseph Huckaby var ZeroClipboard = { version: "1.0.7", clients: {}, // registered upload clients on page, indexed by id - moviePath: 'ZeroClipboard.swf', + moviePath: "ZeroClipboard.swf", // URL to movie nextId: 1, // ID of next movie $: function (thingy) { // simple DOM lookup utility function - if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); + if (typeof(thingy) === "string") thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function () { - this.style.display = 'none'; + this.style.display = "none"; }; thingy.show = function () { - this.style.display = ''; + this.style.display = ""; }; thingy.addClass = function (name) { this.removeClass(name); - this.className += ' ' + name; + this.className += " " + name; }; thingy.removeClass = function (name) { var classes = this.className.split(/\s+/); @@ -3228,7 +3223,7 @@ try {//IE8下会抛错 } if (idx > -1) { classes.splice(idx, 1); - this.className = classes.join(' '); + this.className = classes.join(" "); } return this; }; @@ -3280,7 +3275,7 @@ try {//IE8下会抛错 // unique ID this.id = ZeroClipboard.nextId++; - this.movieId = 'ZeroClipboardMovie_' + this.id; + this.movieId = "ZeroClipboardMovie_" + this.id; // register client with singleton to receive flash events ZeroClipboard.register(this.id, this); @@ -3298,7 +3293,7 @@ try {//IE8下会抛错 // whether movie is ready to receive events or not movie: null, // reference to movie object - clipText: '', + clipText: "", // text to copy to clipboard handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor @@ -3317,29 +3312,29 @@ try {//IE8下会抛错 zIndex = parseInt(this.domElement.style.zIndex, 10) + 1; } - if (typeof(appendElem) == 'string') { + if (typeof(appendElem) === "string") { appendElem = ZeroClipboard.$(appendElem); - } else if (typeof(appendElem) == 'undefined') { - appendElem = document.getElementsByTagName('body')[0]; + } else if (typeof(appendElem) === "undefined") { + appendElem = document.getElementsByTagName("body")[0]; } // find X/Y position of domElement var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem); // create floating DIV above element - this.div = document.createElement('div'); + this.div = document.createElement("div"); this.div.className = "zclip"; this.div.id = "zclip-" + this.movieId; - $(this.domElement).data('zclipId', 'zclip-' + this.movieId); + $(this.domElement).data("zclipId", "zclip-" + this.movieId); var style = this.div.style; - style.position = 'absolute'; - style.left = '' + box.left + 'px'; - style.top = '' + box.top + 'px'; - style.width = '' + box.width + 'px'; - style.height = '' + box.height + 'px'; + style.position = "absolute"; + style.left = "" + box.left + "px"; + style.top = "" + box.top + "px"; + style.width = "" + box.width + "px"; + style.height = "" + box.height + "px"; style.zIndex = zIndex; - if (typeof(stylesToAdd) == 'object') { + if (typeof(stylesToAdd) === "object") { for (addedStyle in stylesToAdd) { style[addedStyle] = stylesToAdd[addedStyle]; } @@ -3353,16 +3348,16 @@ try {//IE8下会抛错 getHTML: function (width, height) { // return HTML for movie - var html = ''; - var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; + var html = ""; + var flashvars = "id=" + this.id + "&width=" + width + "&height=" + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag - var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; - html += ''; + var protocol = location.href.match(/^https/i) ? "https://" : "http://"; + html += ""; } else { // all other browsers get an EMBED tag - html += ''; + html += ""; } return html; }, @@ -3370,7 +3365,7 @@ try {//IE8下会抛错 hide: function () { // temporarily hide floater offscreen if (this.div) { - this.div.style.left = '-2000px'; + this.div.style.left = "-2000px"; } }, @@ -3383,13 +3378,13 @@ try {//IE8下会抛错 // destroy control and floater if (this.domElement && this.div) { this.hide(); - this.div.innerHTML = ''; + this.div.innerHTML = ""; - var body = document.getElementsByTagName('body')[0]; + var body = document.getElementsByTagName("body")[0]; try { body.removeChild(this.div); } catch (e) { - ; + } this.domElement = null; @@ -3408,8 +3403,8 @@ try {//IE8下会抛错 if (this.domElement && this.div) { var box = ZeroClipboard.getDOMObjectPosition(this.domElement); var style = this.div.style; - style.left = '' + box.left + 'px'; - style.top = '' + box.top + 'px'; + style.left = "" + box.left + "px"; + style.top = "" + box.top + "px"; } }, @@ -3424,7 +3419,7 @@ try {//IE8下会抛错 addEventListener: function (eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel - eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + eventName = eventName.toString().toLowerCase().replace(/^on/, ""); if (!this.handlers[eventName]) { this.handlers[eventName] = []; } @@ -3446,18 +3441,18 @@ try {//IE8下会抛错 receiveEvent: function (eventName, args) { // receive event from flash - eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + eventName = eventName.toString().toLowerCase().replace(/^on/, ""); // special behavior for certain events switch (eventName) { - case 'load': + case "load": // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout(function () { - self.receiveEvent('load', null); + self.receiveEvent("load", null); }, 1); return; } @@ -3466,7 +3461,7 @@ try {//IE8下会抛错 if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout(function () { - self.receiveEvent('load', null); + self.receiveEvent("load", null); }, 100); this.ready = true; return; @@ -3483,11 +3478,11 @@ try {//IE8下会抛错 } break; - case 'mouseover': + case "mouseover": if (this.domElement && this.cssEffects) { - this.domElement.addClass('hover'); + this.domElement.addClass("hover"); if (this.recoverActive) { - this.domElement.addClass('active'); + this.domElement.addClass("active"); } @@ -3496,27 +3491,27 @@ try {//IE8下会抛错 break; - case 'mouseout': + case "mouseout": if (this.domElement && this.cssEffects) { this.recoverActive = false; - if (this.domElement.hasClass('active')) { - this.domElement.removeClass('active'); + if (this.domElement.hasClass("active")) { + this.domElement.removeClass("active"); this.recoverActive = true; } - this.domElement.removeClass('hover'); + this.domElement.removeClass("hover"); } break; - case 'mousedown': + case "mousedown": if (this.domElement && this.cssEffects) { - this.domElement.addClass('active'); + this.domElement.addClass("active"); } break; - case 'mouseup': + case "mouseup": if (this.domElement && this.cssEffects) { - this.domElement.removeClass('active'); + this.domElement.removeClass("active"); this.recoverActive = false; } break; @@ -3525,13 +3520,13 @@ try {//IE8下会抛错 for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; - if (typeof(func) == 'function') { + if (typeof(func) === "function") { // actual function reference func(this, args); - } else if ((typeof(func) == 'object') && (func.length == 2)) { + } else if ((typeof(func) === "object") && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][func[1]](this, args); - } else if (typeof(func) == 'string') { + } else if (typeof(func) === "string") { // name of function window[func](this, args); } @@ -3552,7 +3547,7 @@ BI.ClipBoard = BI.inherit(BI.BasicButton, { extraCls: "bi-clipboard", copy: BI.emptyFn, afterCopy: BI.emptyFn - }) + }); }, _init: function () { @@ -3567,7 +3562,7 @@ BI.ClipBoard = BI.inherit(BI.BasicButton, { return BI.isFunction(o.copy) ? o.copy() : o.copy; } }); - this.clipboard.on("success", o.afterCopy) + this.clipboard.on("success", o.afterCopy); } else { this.element.zclip({ path: BI.resourceURL + "/ZeroClipboard.swf", @@ -3597,7 +3592,7 @@ BI.CustomColorChooser = BI.inherit(BI.Widget, { baseCls: "bi-custom-color-chooser", width: 227, height: 245 - }) + }); }, _init: function () { @@ -3638,7 +3633,7 @@ BI.CustomColorChooser = BI.inherit(BI.Widget, { }], height: 215 }] - }) + }); }, setValue: function (color) { @@ -3664,7 +3659,7 @@ BI.ColorChooser = BI.inherit(BI.Widget, { return BI.extend(BI.ColorChooser.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-color-chooser", el: {} - }) + }); }, _init: function () { @@ -3716,7 +3711,7 @@ BI.ColorChooser = BI.inherit(BI.Widget, { this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { self.fireEvent(BI.ColorChooser.EVENT_CHANGE, arguments); - }) + }); }, isViewVisible: function () { @@ -3754,7 +3749,7 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { baseCls: "bi-color-chooser-popup", width: 200, height: 145 - }) + }); }, _init: function () { @@ -3902,7 +3897,7 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { el: this.more, height: 20 }] - }) + }); }, setStoreColors: function (colors) { @@ -3910,13 +3905,13 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { var items = BI.map(colors, function (i, color) { return { value: color - } + }; }); BI.count(colors.length, 8, function (i) { items.push({ value: "", disabled: true - }) + }); }); this.storeColors.populate([items]); } @@ -3948,7 +3943,7 @@ BI.ColorChooserTrigger = BI.inherit(BI.Trigger, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-color-chooser-trigger", height: 30 - }) + }); }, _init: function () { @@ -3991,7 +3986,7 @@ BI.ColorChooserTrigger = BI.inherit(BI.Trigger, { if (color === "") { this.colorContainer.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-background"); } else if (color === "transparent") { - this.colorContainer.element.css("background-color", "").removeClass("auto-color-background").addClass("trans-color-background") + this.colorContainer.element.css("background-color", "").removeClass("auto-color-background").addClass("trans-color-background"); } else { this.colorContainer.element.css({"background-color": color}).removeClass("auto-color-background").removeClass("trans-color-background"); } @@ -4011,7 +4006,7 @@ BI.ColorPickerButton = BI.inherit(BI.BasicButton, { var conf = BI.ColorPickerButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-color-picker-button bi-background bi-border-top bi-border-left" - }) + }); }, _init: function () { @@ -4050,10 +4045,10 @@ BI.ColorPickerButton = BI.inherit(BI.BasicButton, { setSelected: function (b) { BI.ColorPickerButton.superclass.setSelected.apply(this, arguments); - if (!!b) { + if (b) { this._createMask(); } - BI.Maskers[!!b ? "show" : "hide"](this.getName()); + BI.Maskers[b ? "show" : "hide"](this.getName()); } }); BI.ColorPickerButton.EVENT_CHANGE = "ColorPickerButton.EVENT_CHANGE"; @@ -4070,7 +4065,7 @@ BI.ColorPicker = BI.inherit(BI.Widget, { return BI.extend(BI.ColorPicker.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-color-picker", items: null - }) + }); }, _items: [ @@ -4224,11 +4219,11 @@ BI.ColorPicker = BI.inherit(BI.Widget, { }); this.colors.on(BI.ButtonGroup.EVENT_CHANGE, function () { self.fireEvent(BI.ColorPicker.EVENT_CHANGE, arguments); - }) + }); }, - populate: function(items){ - var args =[].slice.call(arguments); + populate: function (items) { + var args = [].slice.call(arguments); args[0] = BI.createItems(items, { type: "bi.color_picker_button", once: false @@ -4259,7 +4254,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { baseCls: "bi-color-picker-editor", // width: 200, height: 20 - }) + }); }, _init: function () { @@ -4341,7 +4336,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { element: this, items: [{ el: this.colorShow, - width: 'fill' + width: "fill" }, { el: RGB[0], lgap: 10, @@ -4376,7 +4371,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { }, width: 18 }] - }) + }); }, setValue: function (color) { @@ -4410,7 +4405,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { r: this.R.getValue(), g: this.G.getValue(), b: this.B.getValue() - })) + })); } }); BI.ColorPickerEditor.EVENT_CHANGE = "ColorPickerEditor.EVENT_CHANGE"; @@ -4428,7 +4423,7 @@ BI.Farbtastic = BI.inherit(BI.Widget, { baseCls: "bi-farbtastic", width: 195, height: 195 - }) + }); }, _init: function () { @@ -4471,159 +4466,157 @@ BI.shortcut("bi.farbtastic", BI.Farbtastic);/** */ jQuery.fn.farbtastic = function (callback) { - $.farbtastic(this, callback); - return this; + $.farbtastic(this, callback); + return this; }; jQuery.farbtastic = function (container, callback) { - var container = $(container).get(0); - return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback)); -} + var container = $(container).get(0); + return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback)); +}; jQuery._farbtastic = function (container, callback) { - // Store farbtastic object - var fb = this; - - // Insert markup - $(container).html('
    '); - var e = $('.farbtastic', container); - fb.wheel = $('.wheel', container).get(0); - // Dimensions - fb.radius = 84; - fb.square = 100; - fb.width = 194; - - // Fix background PNGs in IE6 - if (navigator.appVersion.match(/MSIE [0-6]\./)) { - $('*', e).each(function () { - if (this.currentStyle.backgroundImage != 'none') { - var image = this.currentStyle.backgroundImage; - image = this.currentStyle.backgroundImage.substring(5, image.length - 2); - $(this).css({ - 'backgroundImage': 'none', - 'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" - }); - } - }); - } + // Store farbtastic object + var fb = this; + + // Insert markup + $(container).html("
    "); + var e = $(".farbtastic", container); + fb.wheel = $(".wheel", container).get(0); + // Dimensions + fb.radius = 84; + fb.square = 100; + fb.width = 194; + + // Fix background PNGs in IE6 + if (navigator.appVersion.match(/MSIE [0-6]\./)) { + $("*", e).each(function () { + if (this.currentStyle.backgroundImage != "none") { + var image = this.currentStyle.backgroundImage; + image = this.currentStyle.backgroundImage.substring(5, image.length - 2); + $(this).css({ + backgroundImage: "none", + filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" + }); + } + }); + } - /** + /** * Link to the given element(s) or callback. */ - fb.linkTo = function (callback) { + fb.linkTo = function (callback) { // Unbind previous nodes - if (typeof fb.callback == 'object') { - $(fb.callback).unbind('keyup', fb.updateValue); - } + if (typeof fb.callback === "object") { + $(fb.callback).unbind("keyup", fb.updateValue); + } - // Reset color - fb.color = null; + // Reset color + fb.color = null; - // Bind callback or elements - if (typeof callback == 'function') { - fb.callback = callback; - } - else if (typeof callback == 'object' || typeof callback == 'string') { - fb.callback = $(callback); - fb.callback.bind('keyup', fb.updateValue); - if (fb.callback.get(0).value) { - fb.setColor(fb.callback.get(0).value); - } - } - return this; - } - fb.updateValue = function (event) { - if (this.value && this.value != fb.color) { - fb.setColor(this.value); - } - } + // Bind callback or elements + if (typeof callback === "function") { + fb.callback = callback; + } else if (typeof callback === "object" || typeof callback === "string") { + fb.callback = $(callback); + fb.callback.bind("keyup", fb.updateValue); + if (fb.callback.get(0).value) { + fb.setColor(fb.callback.get(0).value); + } + } + return this; + }; + fb.updateValue = function (event) { + if (this.value && this.value != fb.color) { + fb.setColor(this.value); + } + }; - /** + /** * Change color with HTML syntax #123456 */ - fb.setColor = function (color) { - var unpack = fb.unpack(color); - if (fb.color != color && unpack) { - fb.color = color; - fb.rgb = unpack; - fb.hsl = fb.RGBToHSL(fb.rgb); - fb.updateDisplay(); - } - return this; - } + fb.setColor = function (color) { + var unpack = fb.unpack(color); + if (fb.color != color && unpack) { + fb.color = color; + fb.rgb = unpack; + fb.hsl = fb.RGBToHSL(fb.rgb); + fb.updateDisplay(); + } + return this; + }; - /** + /** * Change color with HSL triplet [0..1, 0..1, 0..1] */ - fb.setHSL = function (hsl) { - fb.hsl = hsl; - fb.rgb = fb.HSLToRGB(hsl); - fb.color = fb.pack(fb.rgb); - fb.updateDisplay(); - return this; - } + fb.setHSL = function (hsl) { + fb.hsl = hsl; + fb.rgb = fb.HSLToRGB(hsl); + fb.color = fb.pack(fb.rgb); + fb.updateDisplay(); + return this; + }; - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// - /** + /** * Retrieve the coordinates of the given event relative to the center * of the widget. */ - fb.widgetCoords = function (event) { - var x, y; - var el = event.target || event.srcElement; - var reference = fb.wheel; - - if (typeof event.offsetX != 'undefined') { - // Use offset coordinates and find common offsetParent - var pos = { x: event.offsetX, y: event.offsetY }; - - // Send the coordinates upwards through the offsetParent chain. - var e = el; - while (e) { - e.mouseX = pos.x; - e.mouseY = pos.y; - pos.x += e.offsetLeft; - pos.y += e.offsetTop; - e = e.offsetParent; - } - - // Look for the coordinates starting from the wheel widget. - var e = reference; - var offset = { x: 0, y: 0 } - while (e) { - if (typeof e.mouseX != 'undefined') { - x = e.mouseX - offset.x; - y = e.mouseY - offset.y; - break; - } - offset.x += e.offsetLeft; - offset.y += e.offsetTop; - e = e.offsetParent; - } - - // Reset stored coordinates - e = el; - while (e) { - e.mouseX = undefined; - e.mouseY = undefined; - e = e.offsetParent; - } - } - else { - // Use absolute coordinates - var pos = fb.absolutePosition(reference); - x = (event.pageX || 0*(event.clientX + $('html').get(0).scrollLeft)) - pos.x; - y = (event.pageY || 0*(event.clientY + $('html').get(0).scrollTop)) - pos.y; - } - // Subtract distance to middle - return { x: x - fb.width / 2, y: y - fb.width / 2 }; - } + fb.widgetCoords = function (event) { + var x, y; + var el = event.target || event.srcElement; + var reference = fb.wheel; + + if (typeof event.offsetX !== "undefined") { + // Use offset coordinates and find common offsetParent + var pos = { x: event.offsetX, y: event.offsetY }; + + // Send the coordinates upwards through the offsetParent chain. + var e = el; + while (e) { + e.mouseX = pos.x; + e.mouseY = pos.y; + pos.x += e.offsetLeft; + pos.y += e.offsetTop; + e = e.offsetParent; + } + + // Look for the coordinates starting from the wheel widget. + var e = reference; + var offset = { x: 0, y: 0 }; + while (e) { + if (typeof e.mouseX !== "undefined") { + x = e.mouseX - offset.x; + y = e.mouseY - offset.y; + break; + } + offset.x += e.offsetLeft; + offset.y += e.offsetTop; + e = e.offsetParent; + } - /** + // Reset stored coordinates + e = el; + while (e) { + e.mouseX = undefined; + e.mouseY = undefined; + e = e.offsetParent; + } + } else { + // Use absolute coordinates + var pos = fb.absolutePosition(reference); + x = (event.pageX || 0 * (event.clientX + $("html").get(0).scrollLeft)) - pos.x; + y = (event.pageY || 0 * (event.clientY + $("html").get(0).scrollTop)) - pos.y; + } + // Subtract distance to middle + return { x: x - fb.width / 2, y: y - fb.width / 2 }; + }; + + /** * Mousedown handler */ - fb.click = function (event) { + fb.click = function (event) { // Capture mouse // if (!document.dragging) { // $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup); @@ -4631,171 +4624,168 @@ jQuery._farbtastic = function (container, callback) { // } // Check which area is being dragged - var pos = fb.widgetCoords(event); - fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; + var pos = fb.widgetCoords(event); + fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; - // Process - fb.mousemove(event); - return false; - } + // Process + fb.mousemove(event); + return false; + }; - /** + /** * Mousemove handler */ - fb.mousemove = function (event) { + fb.mousemove = function (event) { // Get coordinates relative to color picker center - var pos = fb.widgetCoords(event); + var pos = fb.widgetCoords(event); - // Set new HSL parameters - if (fb.circleDrag) { - var hue = Math.atan2(pos.x, -pos.y) / 6.28; - if (hue < 0) hue += 1; - fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); - } - else { - var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); - var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); - fb.setHSL([fb.hsl[0], sat, lum]); - } - return false; - } + // Set new HSL parameters + if (fb.circleDrag) { + var hue = Math.atan2(pos.x, -pos.y) / 6.28; + if (hue < 0) hue += 1; + fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); + } else { + var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); + var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); + fb.setHSL([fb.hsl[0], sat, lum]); + } + return false; + }; - /** + /** * Mouseup handler */ - // fb.mouseup = function () { - // // Uncapture mouse - // $(document).unbind('mousemove', fb.mousemove); - // $(document).unbind('mouseup', fb.mouseup); - // document.dragging = false; - // } - - /** + // fb.mouseup = function () { + // // Uncapture mouse + // $(document).unbind('mousemove', fb.mousemove); + // $(document).unbind('mouseup', fb.mouseup); + // document.dragging = false; + // } + + /** * Update the markers and styles */ - fb.updateDisplay = function () { + fb.updateDisplay = function () { // Markers - var angle = fb.hsl[0] * 6.28; - $('.h-marker', e).css({ - left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px', - top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px' - }); + var angle = fb.hsl[0] * 6.28; + $(".h-marker", e).css({ + left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + "px", + top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + "px" + }); - $('.sl-marker', e).css({ - left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px', - top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px' - }); + $(".sl-marker", e).css({ + left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + "px", + top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + "px" + }); - // Saturation/Luminance gradient - $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); + // Saturation/Luminance gradient + $(".color", e).css("backgroundColor", fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); - // Linked elements or callback - if (typeof fb.callback == 'object') { - // Set background/foreground color - $(fb.callback).css({ - backgroundColor: fb.color, - color: fb.hsl[2] > 0.5 ? '#000' : '#fff' - }); + // Linked elements or callback + if (typeof fb.callback === "object") { + // Set background/foreground color + $(fb.callback).css({ + backgroundColor: fb.color, + color: fb.hsl[2] > 0.5 ? "#000" : "#fff" + }); - // Change linked value - $(fb.callback).each(function() { - if (this.value && this.value != fb.color) { - this.value = fb.color; + // Change linked value + $(fb.callback).each(function () { + if (this.value && this.value != fb.color) { + this.value = fb.color; + } + }); + } else if (typeof fb.callback === "function") { + fb.callback.call(fb, fb.color); } - }); - } - else if (typeof fb.callback == 'function') { - fb.callback.call(fb, fb.color); - } - } + }; - /** + /** * Get absolute position of element */ - fb.absolutePosition = function (el) { - var r = { x: el.offsetLeft, y: el.offsetTop }; - // Resolve relative to offsetParent - if (el.offsetParent) { - var tmp = fb.absolutePosition(el.offsetParent); - r.x += tmp.x; - r.y += tmp.y; - } - return r; - }; - - /* Various color utility functions */ - fb.pack = function (rgb) { - var r = Math.round(rgb[0] * 255); - var g = Math.round(rgb[1] * 255); - var b = Math.round(rgb[2] * 255); - return '#' + (r < 16 ? '0' : '') + r.toString(16) + - (g < 16 ? '0' : '') + g.toString(16) + - (b < 16 ? '0' : '') + b.toString(16); - } - - fb.unpack = function (color) { - if (color.length == 7) { - return [parseInt('0x' + color.substring(1, 3)) / 255, - parseInt('0x' + color.substring(3, 5)) / 255, - parseInt('0x' + color.substring(5, 7)) / 255]; - } - else if (color.length == 4) { - return [parseInt('0x' + color.substring(1, 2)) / 15, - parseInt('0x' + color.substring(2, 3)) / 15, - parseInt('0x' + color.substring(3, 4)) / 15]; - } - } - - fb.HSLToRGB = function (hsl) { - var m1, m2, r, g, b; - var h = hsl[0], s = hsl[1], l = hsl[2]; - m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s; - m1 = l * 2 - m2; - return [this.hueToRGB(m1, m2, h+0.33333), - this.hueToRGB(m1, m2, h), - this.hueToRGB(m1, m2, h-0.33333)]; - } - - fb.hueToRGB = function (m1, m2, h) { - h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); - if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; - if (h * 2 < 1) return m2; - if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; - return m1; - } - - fb.RGBToHSL = function (rgb) { - var min, max, delta, h, s, l; - var r = rgb[0], g = rgb[1], b = rgb[2]; - min = Math.min(r, Math.min(g, b)); - max = Math.max(r, Math.max(g, b)); - delta = max - min; - l = (min + max) / 2; - s = 0; - if (l > 0 && l < 1) { - s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); - } - h = 0; - if (delta > 0) { - if (max == r && max != g) h += (g - b) / delta; - if (max == g && max != b) h += (2 + (b - r) / delta); - if (max == b && max != r) h += (4 + (r - g) / delta); - h /= 6; - } - return [h, s, l]; - } + fb.absolutePosition = function (el) { + var r = { x: el.offsetLeft, y: el.offsetTop }; + // Resolve relative to offsetParent + if (el.offsetParent) { + var tmp = fb.absolutePosition(el.offsetParent); + r.x += tmp.x; + r.y += tmp.y; + } + return r; + }; + + /* Various color utility functions */ + fb.pack = function (rgb) { + var r = Math.round(rgb[0] * 255); + var g = Math.round(rgb[1] * 255); + var b = Math.round(rgb[2] * 255); + return "#" + (r < 16 ? "0" : "") + r.toString(16) + + (g < 16 ? "0" : "") + g.toString(16) + + (b < 16 ? "0" : "") + b.toString(16); + }; + + fb.unpack = function (color) { + if (color.length == 7) { + return [parseInt("0x" + color.substring(1, 3)) / 255, + parseInt("0x" + color.substring(3, 5)) / 255, + parseInt("0x" + color.substring(5, 7)) / 255]; + } else if (color.length == 4) { + return [parseInt("0x" + color.substring(1, 2)) / 15, + parseInt("0x" + color.substring(2, 3)) / 15, + parseInt("0x" + color.substring(3, 4)) / 15]; + } + }; + + fb.HSLToRGB = function (hsl) { + var m1, m2, r, g, b; + var h = hsl[0], s = hsl[1], l = hsl[2]; + m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; + m1 = l * 2 - m2; + return [this.hueToRGB(m1, m2, h + 0.33333), + this.hueToRGB(m1, m2, h), + this.hueToRGB(m1, m2, h - 0.33333)]; + }; + + fb.hueToRGB = function (m1, m2, h) { + h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); + if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; + if (h * 2 < 1) return m2; + if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; + return m1; + }; + + fb.RGBToHSL = function (rgb) { + var min, max, delta, h, s, l; + var r = rgb[0], g = rgb[1], b = rgb[2]; + min = Math.min(r, Math.min(g, b)); + max = Math.max(r, Math.max(g, b)); + delta = max - min; + l = (min + max) / 2; + s = 0; + if (l > 0 && l < 1) { + s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); + } + h = 0; + if (delta > 0) { + if (max == r && max != g) h += (g - b) / delta; + if (max == g && max != b) h += (2 + (b - r) / delta); + if (max == b && max != r) h += (4 + (r - g) / delta); + h /= 6; + } + return [h, s, l]; + }; - // Install mousedown handler (the others are set on the document on-demand) - $('*', e).click(fb.click); + // Install mousedown handler (the others are set on the document on-demand) + $("*", e).click(fb.click); // Init color - fb.setColor('#000000'); + fb.setColor("#000000"); - // Set linked elements/callback - if (callback) { - fb.linkTo(callback); - } -}/** + // Set linked elements/callback + if (callback) { + fb.linkTo(callback); + } +};/** * Created by GUY on 2017/2/8. * * @class BI.BubbleCombo @@ -4810,20 +4800,20 @@ BI.BubbleCombo = BI.inherit(BI.Widget, { baseCls: "bi-bubble-combo", trigger: "click", toggle: true, - direction: "bottom", //top||bottom||left||right||top,left||top,right||bottom,left||bottom,right + direction: "bottom", // top||bottom||left||right||top,left||top,right||bottom,left||bottom,right isDefaultInit: false, destroyWhenHide: false, - isNeedAdjustHeight: true,//是否需要高度调整 + isNeedAdjustHeight: true, // 是否需要高度调整 isNeedAdjustWidth: true, stopPropagation: false, - adjustLength: 0,//调整的距离 + adjustLength: 0, // 调整的距离 // adjustXOffset: 0, // adjustYOffset: 10, hideChecker: BI.emptyFn, - offsetStyle: "left", //left,right,center + offsetStyle: "left", // left,right,center el: {}, popup: {} - }) + }); }, _init: function () { BI.BubbleCombo.superclass._init.apply(this, arguments); @@ -4940,7 +4930,7 @@ BI.BubbleCombo = BI.inherit(BI.Widget, { type: "bi.absolute", element: this, items: [pos] - }) + }); }, _createLeftTriangle: function () { @@ -5027,7 +5017,7 @@ BI.BubblePopupView = BI.inherit(BI.PopupView, { var config = BI.BubblePopupView.superclass._defaultConfig.apply(this, arguments); return BI.extend(config, { baseCls: config.baseCls + " bi-bubble-popup-view" - }) + }); }, _init: function () { BI.BubblePopupView.superclass._init.apply(this, arguments); @@ -5080,7 +5070,7 @@ BI.BubblePopupView = BI.inherit(BI.PopupView, { type: "bi.absolute", element: this, items: [pos] - }) + }); }, hideLine: function () { @@ -5101,7 +5091,7 @@ BI.BubblePopupBarView = BI.inherit(BI.BubblePopupView, { return BI.extend(BI.BubblePopupBarView.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-bubble-bar-popup-view", buttons: [{value: BI.i18nText(BI.i18nText("BI-Basic_Sure"))}, {value: BI.i18nText("BI-Basic_Cancel"), level: "ignore"}] - }) + }); }, _init: function () { BI.BubblePopupBarView.superclass._init.apply(this, arguments); @@ -5111,20 +5101,20 @@ BI.BubblePopupBarView = BI.inherit(BI.BubblePopupView, { var items = []; BI.each(o.buttons.reverse(), function (i, buttonOpt) { - if(BI.isWidget(buttonOpt)){ + if(BI.isWidget(buttonOpt)) { items.push(buttonOpt); }else{ items.push(BI.extend({ - type: 'bi.button', + type: "bi.button", height: 30, handler: function (v) { self.fireEvent(BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON, v); } - }, buttonOpt)) + }, buttonOpt)); } }); return BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", height: 40, hgap: 10, bgap: 10, @@ -5148,7 +5138,7 @@ BI.EditorIconCheckCombo = BI.inherit(BI.Widget, { allowBlank: true, watermark: "", errorText: "" - }) + }); }, _init: function () { @@ -5223,15 +5213,15 @@ BI.IconCombo = BI.inherit(BI.Widget, { el: {}, popup: {}, minWidth: 100, - maxWidth: 'auto', + maxWidth: "auto", maxHeight: 300, direction: "bottom", - adjustLength: 3,//调整的距离 + adjustLength: 3, // 调整的距离 adjustXOffset: 0, adjustYOffset: 0, offsetStyle: "left", chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE - }) + }); }, _init: function () { @@ -5437,11 +5427,11 @@ BI.IconComboTrigger = BI.inherit(BI.Trigger, { var iconClass = ""; v = BI.isArray(v) ? v[0] : v; if (BI.any(this.options.items, function (i, item) { - if (v === item.value) { - iconClass = item.iconClass; - return true; - } - })) { + if (v === item.value) { + iconClass = item.iconClass; + return true; + } + })) { this.button.setIcon(iconClass); this.button.setSelected(true); this.down.setSelected(true); @@ -5590,7 +5580,7 @@ BI.StaticCombo = BI.inherit(BI.Widget, { el: {}, items: [], chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE - }) + }); }, _init: function () { @@ -5728,7 +5718,7 @@ BI.SmallTextValueCheckCombo = BI.inherit(BI.Widget, { height: 24, chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, text: "" - }) + }); }, _init: function () { @@ -5919,7 +5909,7 @@ BI.SmallTextValueCombo = BI.inherit(BI.Widget, { chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, el: {}, text: "" - }) + }); }, _init: function () { @@ -6036,7 +6026,7 @@ BI.TextValueDownListCombo = BI.inherit(BI.Widget, { return BI.extend(BI.TextValueDownListCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-text-value-down-list-combo", height: 30 - }) + }); }, _init: function () { @@ -6078,7 +6068,7 @@ BI.TextValueDownListCombo = BI.inherit(BI.Widget, { BI.each(BI.flatten(this.options.items), function (idx, item) { if (BI.has(item, "el")) { BI.each(item.children, function (id, it) { - self.valueMap[it.value] = {value: item.el.value, childValue: it.value} + self.valueMap[it.value] = {value: item.el.value, childValue: it.value}; }); } else { self.valueMap[item.value] = {value: item.value}; @@ -6133,12 +6123,12 @@ BI.DownListSelectTextTrigger = BI.inherit(BI.Trigger, { }); }, - _formatItemArray: function(){ + _formatItemArray: function () { var sourceArray = BI.flatten(BI.deepClone(this.options.items)); var targetArray = []; - BI.each(sourceArray, function(idx, item){ - if(BI.has(item, "el")){ - BI.each(item.children, function(id, it){ + BI.each(sourceArray, function (idx, item) { + if(BI.has(item, "el")) { + BI.each(item.children, function (id, it) { it.text = item.el.text + "(" + it.text + ")"; }); targetArray = BI.concat(targetArray, item.children); @@ -6230,34 +6220,34 @@ BI.ClearEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.ClearEditor.EVENT_KEY_DOWN, v); }); this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.ClearEditor.EVENT_SPACE) + self.fireEvent(BI.ClearEditor.EVENT_SPACE); }); this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.ClearEditor.EVENT_BACKSPACE) + self.fireEvent(BI.ClearEditor.EVENT_BACKSPACE); }); this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.ClearEditor.EVENT_VALID) + self.fireEvent(BI.ClearEditor.EVENT_VALID); }); this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.ClearEditor.EVENT_ERROR) + self.fireEvent(BI.ClearEditor.EVENT_ERROR); }); this.editor.on(BI.Editor.EVENT_ENTER, function () { self.fireEvent(BI.ClearEditor.EVENT_ENTER); }); this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.ClearEditor.EVENT_RESTRICT) + self.fireEvent(BI.ClearEditor.EVENT_RESTRICT); }); this.editor.on(BI.Editor.EVENT_EMPTY, function () { self._checkClear(); - self.fireEvent(BI.ClearEditor.EVENT_EMPTY) + self.fireEvent(BI.ClearEditor.EVENT_EMPTY); }); this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.ClearEditor.EVENT_REMOVE) + self.fireEvent(BI.ClearEditor.EVENT_REMOVE); }); this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.ClearEditor.EVENT_CONFIRM) + self.fireEvent(BI.ClearEditor.EVENT_CONFIRM); }); this.editor.on(BI.Editor.EVENT_START, function () { self.fireEvent(BI.ClearEditor.EVENT_START); @@ -6349,7 +6339,7 @@ BI.ShelterEditor = BI.inherit(BI.Widget, { errorText: "", height: 24, textAlign: "left" - }) + }); }, _init: function () { @@ -6605,7 +6595,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { value: "", text: "", height: 24 - }) + }); }, _init: function () { @@ -6644,7 +6634,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignInitialEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignInitialEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ @@ -6817,7 +6807,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { return { value: this.editor.getValue(), text: this.options.text - } + }; }, getState: function () { @@ -6872,7 +6862,7 @@ BI.SignEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -6911,7 +6901,7 @@ BI.SignEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ @@ -7130,7 +7120,7 @@ BI.StateEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -7404,7 +7394,7 @@ BI.SimpleStateEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -7644,7 +7634,7 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { _defaultConfig: function () { return BI.extend(BI.BarPopoverSection.superclass._defaultConfig.apply(this, arguments), { btns: [BI.i18nText(BI.i18nText("BI-Basic_Sure")), BI.i18nText(BI.i18nText("BI-Basic_Cancel"))] - }) + }); }, _init: function () { @@ -7654,7 +7644,7 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { rebuildSouth: function (south) { var self = this, o = this.options; this.sure = BI.createWidget({ - type: 'bi.button', + type: "bi.button", text: this.options.btns[0], warningTitle: o.warningTitle, height: 30, @@ -7665,24 +7655,24 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { } }); this.cancel = BI.createWidget({ - type: 'bi.button', + type: "bi.button", text: this.options.btns[1], height: 30, value: 1, - level: 'ignore', + level: "ignore", handler: function (v) { self.close(v); } }); BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", element: south, lgap: 10, items: [this.cancel, this.sure] }); }, - setConfirmButtonEnable: function(v){ + setConfirmButtonEnable: function (v) { this.sure.setEnable(!!v); } });/** @@ -7698,7 +7688,7 @@ BI.MultiPopupView = BI.inherit(BI.PopupView, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-multi-list-view", buttons: [BI.i18nText("BI-Basic_Sure")] - }) + }); }, _init: function () { @@ -7711,12 +7701,12 @@ BI.MultiPopupView = BI.inherit(BI.PopupView, { return; } - var text = []; //构造[{text:content},……] + var text = []; // 构造[{text:content},……] BI.each(o.buttons, function (idx, item) { text.push({ text: item, value: idx - }) + }); }); this.buttongroup = BI.createWidget({ @@ -7761,7 +7751,7 @@ BI.PopupPanel = BI.inherit(BI.MultiPopupView, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-popup-panel", title: "" - }) + }); }, _init: function () { @@ -7833,7 +7823,7 @@ BI.ListPane = BI.inherit(BI.Pane, { el: { type: "bi.button_group" } - }) + }); }, _init: function () { BI.ListPane.superclass._init.apply(this, arguments); @@ -7848,7 +7838,7 @@ BI.ListPane = BI.inherit(BI.Pane, { if (op.times === 1) { self.empty(); BI.nextTick(function () { - self.loading() + self.loading(); }); } o.itemsCreator(op, function () { @@ -7916,7 +7906,7 @@ BI.ListPane = BI.inherit(BI.Pane, { populate: function (items) { var self = this, o = this.options; - if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {//接管loader的populate方法 + if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 this.button_group.attr("itemsCreator").apply(this, [{times: 1}, function () { if (arguments.length === 0) { throw new Error("参数不能为空"); @@ -7983,32 +7973,32 @@ BI.shortcut("bi.list_pane", BI.ListPane);/** * @class BI.Panel * @extends BI.Widget */ -BI.Panel = BI.inherit(BI.Widget,{ - _defaultConfig : function(){ - return BI.extend(BI.Panel.superclass._defaultConfig.apply(this,arguments),{ +BI.Panel = BI.inherit(BI.Widget, { + _defaultConfig: function () { + return BI.extend(BI.Panel.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-panel bi-border", - title:"", - titleButtons:[], - el:{}, - logic:{ + title: "", + titleButtons: [], + el: {}, + logic: { dynamic: false } }); }, - _init:function(){ - BI.Panel.superclass._init.apply(this,arguments); + _init: function () { + BI.Panel.superclass._init.apply(this, arguments); var o = this.options; BI.createWidget(BI.extend({ element: this }, BI.LogicFactory.createLogic("vertical", BI.extend(o.logic, { items: BI.LogicFactory.createLogicItemsByDirection("top", this._createTitle() - ,this.options.el) + , this.options.el) })))); }, - _createTitle:function(){ + _createTitle: function () { var self = this, o = this.options; this.text = BI.createWidget({ type: "bi.label", @@ -8018,19 +8008,19 @@ BI.Panel = BI.inherit(BI.Widget,{ }); this.button_group = BI.createWidget({ - type:"bi.button_group", + type: "bi.button_group", items: o.titleButtons, layouts: [{ type: "bi.center_adapt", - lgap:10 + lgap: 10 }] }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function(){ + this.button_group.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.ButtonGroup.EVENT_CHANGE, function(value, obj){ + this.button_group.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { self.fireEvent(BI.Panel.EVENT_CHANGE, value, obj); }); @@ -8050,13 +8040,13 @@ BI.Panel = BI.inherit(BI.Widget,{ }; }, - setTitle: function(title){ + setTitle: function (title) { this.text.setValue(title); } }); BI.Panel.EVENT_CHANGE = "Panel.EVENT_CHANGE"; -BI.shortcut("bi.panel",BI.Panel);/** +BI.shortcut("bi.panel", BI.Panel);/** * 选择列表 * * Created by GUY on 2015/11/1. @@ -8068,7 +8058,7 @@ BI.SelectList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SelectList.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-select-list", - direction: BI.Direction.Top,//toolbar的位置 + direction: BI.Direction.Top, // toolbar的位置 logic: { dynamic: true }, @@ -8082,13 +8072,13 @@ BI.SelectList = BI.inherit(BI.Widget, { el: { type: "bi.list_pane" } - }) + }); }, _init: function () { BI.SelectList.superclass._init.apply(this, arguments); var self = this, o = this.options; - //全选 + // 全选 this.toolbar = BI.createWidget(o.toolbar); this.allSelected = false; this.toolbar.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { @@ -8199,13 +8189,13 @@ BI.SelectList = BI.inherit(BI.Widget, { value: this.list.getValue(), assist: this.list.getNotSelectedValue() }; - } else { - return { - type: BI.ButtonGroup.CHOOSE_TYPE_ALL, - value: this.list.getNotSelectedValue(), - assist: this.list.getValue() - }; } + return { + type: BI.ButtonGroup.CHOOSE_TYPE_ALL, + value: this.list.getNotSelectedValue(), + assist: this.list.getValue() + }; + }, empty: function () { @@ -8227,7 +8217,7 @@ BI.SelectList = BI.inherit(BI.Widget, { resetHeight: function (h) { var toolHeight = ( this.toolbar.element.outerHeight() || 25) * ( this.toolbar.isVisible() ? 1 : 0); this.list.resetHeight ? this.list.resetHeight(h - toolHeight) : - this.list.element.css({"max-height": h - toolHeight + "px"}) + this.list.element.css({"max-height": h - toolHeight + "px"}); }, setNotSelectedValue: function () { @@ -8279,7 +8269,7 @@ BI.LazyLoader = BI.inherit(BI.Widget, { return BI.extend(BI.LazyLoader.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-lazy-loader", el: {} - }) + }); }, _init: function () { @@ -8289,7 +8279,7 @@ BI.LazyLoader = BI.inherit(BI.Widget, { this.loader = BI.createWidget({ type: "bi.loader", element: this, - //下面是button_group的属性 + // 下面是button_group的属性 el: o.el, itemsCreator: function (options, populate) { @@ -8301,8 +8291,8 @@ BI.LazyLoader = BI.inherit(BI.Widget, { }); this.loader.on(BI.Loader.EVENT_CHANGE, function (obj) { - self.fireEvent(BI.LazyLoader.EVENT_CHANGE, obj) - }) + self.fireEvent(BI.LazyLoader.EVENT_CHANGE, obj); + }); }, _getNextItems: function (options) { var self = this, o = this.options; @@ -8381,9 +8371,9 @@ BI.ListLoader = BI.inherit(BI.Widget, { return BI.extend(BI.ListLoader.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-list-loader", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -8392,11 +8382,11 @@ BI.ListLoader = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, next: {}, hasNext: BI.emptyFn - }) + }); }, _nextLoad: function () { @@ -8440,7 +8430,7 @@ BI.ListLoader = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self._nextLoad(); } - }) + }); } BI.createWidget({ @@ -8465,7 +8455,7 @@ BI.ListLoader = BI.inherit(BI.Widget, { return !!o.hasNext.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, addItems: function (items) { @@ -8575,9 +8565,9 @@ BI.SortList = BI.inherit(BI.Widget, { return BI.extend(BI.SortList.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-sort-list", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -8586,14 +8576,14 @@ BI.SortList = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, next: {}, hasNext: BI.emptyFn - //containment: this.element, - //connectWith: ".bi-sort-list", - }) + // containment: this.element, + // connectWith: ".bi-sort-list", + }); }, _init: function () { @@ -8640,7 +8630,7 @@ BI.SortList = BI.inherit(BI.Widget, { "margin-right": $currentItem.css("margin-right"), "margin-top": $currentItem.css("margin-top"), "margin-bottom": $currentItem.css("margin-bottom"), - "margin": $currentItem.css("margin") + margin: $currentItem.css("margin") }); return holder.element; }, @@ -8749,10 +8739,10 @@ BI.AllCountPager = BI.inherit(BI.Widget, { return BI.extend(BI.AllCountPager.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-all-count-pager", height: 30, - pages: 1, //必选项 - curr: 1, //初始化当前页, pages为数字时可用, - count: 1 //总行数 - }) + pages: 1, // 必选项 + curr: 1, // 初始化当前页, pages为数字时可用, + count: 1 // 总行数 + }); }, _init: function () { BI.AllCountPager.superclass._init.apply(this, arguments); @@ -8858,7 +8848,7 @@ BI.AllCountPager = BI.inherit(BI.Widget, { element: this, columnSize: ["", 35, 40, 36], items: [count, this.editor, this.allPages, this.pager] - }) + }); }, alwaysShowPager: true, @@ -8920,8 +8910,8 @@ BI.DirectionPager = BI.inherit(BI.Widget, { baseCls: "bi-direction-pager", height: 30, horizontal: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -8929,15 +8919,15 @@ BI.DirectionPager = BI.inherit(BI.Widget, { lastPage: BI.emptyFn }, vertical: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, firstPage: 1, lastPage: BI.emptyFn } - }) + }); }, _init: function () { BI.DirectionPager.superclass._init.apply(this, arguments); @@ -9205,35 +9195,35 @@ BI.DetailPager = BI.inherit(BI.Widget, { vgap: 0 }], - dynamicShow: true, //是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 - //dynamicShow为false时以下两个有用 - dynamicShowFirstLast: false,//是否动态显示首页、尾页 - dynamicShowPrevNext: false,//是否动态显示上一页、下一页 - pages: false, //总页数 + dynamicShow: true, // 是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 + // dynamicShow为false时以下两个有用 + dynamicShowFirstLast: false, // 是否动态显示首页、尾页 + dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 + pages: false, // 总页数 curr: function () { return 1; - }, //初始化当前页 - groups: 0, //连续显示分页数 - jump: BI.emptyFn, //分页的回调函数 + }, // 初始化当前页 + groups: 0, // 连续显示分页数 + jump: BI.emptyFn, // 分页的回调函数 - first: false, //是否显示首页 - last: false, //是否显示尾页 + first: false, // 是否显示首页 + last: false, // 是否显示尾页 prev: "上一页", next: "下一页", firstPage: 1, - lastPage: function () { //在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: function () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, - hasPrev: BI.emptyFn, //pages不可用时有效 - hasNext: BI.emptyFn //pages不可用时有效 - }) + hasPrev: BI.emptyFn, // pages不可用时有效 + hasNext: BI.emptyFn // pages不可用时有效 + }); }, _init: function () { BI.DetailPager.superclass._init.apply(this, arguments); var self = this; this.currPage = BI.result(this.options, "curr"); - //翻页太灵敏 + // 翻页太灵敏 this._lock = false; this._debouce = BI.debounce(function () { self._lock = false; @@ -9260,17 +9250,17 @@ BI.DetailPager = BI.inherit(BI.Widget, { groups > pages && (groups = pages); } - //计算当前组 + // 计算当前组 dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); - //当前页非首页,则输出上一页 + // 当前页非首页,则输出上一页 if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) { if (BI.isKey(prev)) { view.push({ text: prev, value: "prev", disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) - }) + }); } else { view.push(BI.extend({ disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) @@ -9278,7 +9268,7 @@ BI.DetailPager = BI.inherit(BI.Widget, { } } - //当前组非首组,则输出首页 + // 当前组非首组,则输出首页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { view.push({ text: first, @@ -9294,14 +9284,14 @@ BI.DetailPager = BI.inherit(BI.Widget, { } } - //输出当前页组 + // 输出当前页组 dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; dict.end = dict.index > 1 ? (function () { var max = curr + (groups - dict.poor - 1); return max > pages ? pages : max; }()) : groups; - if (dict.end - dict.start < groups - 1) { //最后一组状态 + if (dict.end - dict.start < groups - 1) { // 最后一组状态 dict.start = dict.end - groups + 1; } var s = dict.start, e = dict.end; @@ -9315,16 +9305,16 @@ BI.DetailPager = BI.inherit(BI.Widget, { text: s, value: s, selected: true - }) + }); } else { view.push({ text: s, value: s - }) + }); } } - //总页数大于连续分页数,且当前组最大页小于总页,输出尾页 + // 总页数大于连续分页数,且当前组最大页小于总页,输出尾页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0) { view.push({ @@ -9337,27 +9327,27 @@ BI.DetailPager = BI.inherit(BI.Widget, { text: last, value: "last", disabled: !(pages > groups && dict.end < pages && groups !== 0) - }) + }); } - //当前页不为尾页时,输出下一页 + // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { if (BI.isKey(next)) { if (pages === false) { - return {text: next, value: "next", disabled: o.hasNext(curr) === false} + return {text: next, value: "next", disabled: o.hasNext(curr) === false}; } return (dict.flow && curr === pages) ? - {text: next, value: "next", disabled: true} + {text: next, value: "next", disabled: true} : - {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; - } else { - return BI.extend({ - disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) - }, next); + {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; } + return BI.extend({ + disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) + }, next); + }())); } @@ -9633,7 +9623,7 @@ BI.RichEditorParamAction = BI.inherit(BI.RichEditorAction, { keydown: function (e) { var o = this.options; var sel = this._get$Sel(); - if (e.keyCode === 229) {//中文输入法 + if (e.keyCode === 229) {// 中文输入法 if (this._isParam(sel)) { this._addBlank(sel); e.stopEvent(); @@ -9750,7 +9740,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** type: "bi.layout", height: 1 }, this.instance = this.addInstance()] - }) + }); }, addInstance: function () { @@ -9783,7 +9773,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** // return false; } } while (t = t.parentNode); - this.fireEvent('blur', t); + this.fireEvent("blur", t); this.lastSelectedInstance = this.selectedInstance; this.selectedInstance = null; // return false; @@ -9804,7 +9794,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** BI.NicEditor.EVENT_SELECTED = "selected"; BI.NicEditor.EVENT_BLUR = "blur"; BI.NicEditor.EVENT_KEYDOWN = "keydown"; - BI.shortcut('bi.nic_editor', BI.NicEditor); + BI.shortcut("bi.nic_editor", BI.NicEditor); var prefix = "niceditor-"; @@ -9825,7 +9815,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** outline: "none" }).html(o.value); - this.element.css("maxHeight", (o.maxHeight) ? o.maxHeight + 'px' : null); + this.element.css("maxHeight", (o.maxHeight) ? o.maxHeight + "px" : null); this.e = BI.createWidget({ type: "bi.layout", @@ -9851,12 +9841,12 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** // this.setContent("
    "); } this.instanceDoc = document.defaultView; - this.elm.element.on('mousedown', BI.bind(this.selected, this)); - this.elm.element.on('keydown', BI.bind(this.keyDown, this)); - this.elm.element.on('focus', BI.bind(this.selected, this)); - this.elm.element.on('blur', BI.bind(this.blur, this)); - this.elm.element.on('keyup', BI.bind(this.selected, this)); - this.ne.fireEvent('add'); + this.elm.element.on("mousedown", BI.bind(this.selected, this)); + this.elm.element.on("keydown", BI.bind(this.keyDown, this)); + this.elm.element.on("focus", BI.bind(this.selected, this)); + this.elm.element.on("blur", BI.bind(this.blur, this)); + this.elm.element.on("keyup", BI.bind(this.selected, this)); + this.ne.fireEvent("add"); }, disable: function () { @@ -9902,9 +9892,9 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** } } return contain; - } else { - return (this.getSel().type == "Control") ? r.item(0) : r.parentElement(); } + return (this.getSel().type == "Control") ? r.item(0) : r.parentElement(); + }, saveRng: function () { @@ -9926,7 +9916,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** } rng = document.selection.createRange(); - rng.moveStart('character', -el.innerText.length); + rng.moveStart("character", -el.innerText.length); var text = rng.text; for (var i = 0; i < el.innerText.length; i++) { if (el.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) { @@ -9950,7 +9940,7 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** }, keyDown: function (e, t) { - this.ne.fireEvent('keydown', e); + this.ne.fireEvent("keydown", e); }, selected: function (e) { @@ -9962,25 +9952,25 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** var selInstance = this.ne.selectedInstance; if (selInstance != this) { if (selInstance) { - this.ne.fireEvent('blur', e); + this.ne.fireEvent("blur", e); } this.ne.selectedInstance = this; - this.ne.fireEvent('focus', e); + this.ne.fireEvent("focus", e); } - this.ne.fireEvent('selected', e); + this.ne.fireEvent("selected", e); this.isFocused = true; - this.elm.element.addClass(prefix + 'selected'); + this.elm.element.addClass(prefix + "selected"); } // return false; }, blur: function () { this.isFocused = false; - this.elm.element.removeClass(prefix + 'selected'); + this.elm.element.removeClass(prefix + "selected"); }, saveContent: function () { - this.ne.fireEvent('save'); + this.ne.fireEvent("save"); this.e.element.value(this.getContent()); }, @@ -9990,13 +9980,13 @@ BI.shortcut("bi.rich_editor_text_toolbar", BI.RichEditorTextToolbar);/** getContent: function () { this.content = this.getElm().element.html(); - this.ne.fireEvent('get'); + this.ne.fireEvent("get"); return this.content; }, setContent: function (e) { this.content = e; - this.ne.fireEvent('set'); + this.ne.fireEvent("set"); this.elm.element.html(this.content); }, @@ -10045,7 +10035,7 @@ BI.RichEditorBackgroundChooserTrigger = BI.inherit(BI.Widget, { top: 7, left: 2 }] - }) + }); }, setValue: function (color) { @@ -10056,7 +10046,7 @@ BI.RichEditorBackgroundChooserTrigger = BI.inherit(BI.Widget, { return this.font.element.css("color"); } }); -BI.shortcut('bi.rich_editor_background_color_chooser_trigger', BI.RichEditorBackgroundChooserTrigger);/** +BI.shortcut("bi.rich_editor_background_color_chooser_trigger", BI.RichEditorBackgroundChooserTrigger);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorAlignCenterButton @@ -10093,7 +10083,7 @@ BI.RichEditorAlignCenterButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_center_button", BI.RichEditorAlignCenterButton)/** +BI.shortcut("bi.rich_editor_align_center_button", BI.RichEditorAlignCenterButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorAlignLeftButton @@ -10130,7 +10120,7 @@ BI.RichEditorAlignLeftButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_left_button", BI.RichEditorAlignLeftButton)/** +BI.shortcut("bi.rich_editor_align_left_button", BI.RichEditorAlignLeftButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorAlignRightButton @@ -10167,7 +10157,7 @@ BI.RichEditorAlignRightButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_right_button", BI.RichEditorAlignRightButton)/** +BI.shortcut("bi.rich_editor_align_right_button", BI.RichEditorAlignRightButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorBoldButton @@ -10207,7 +10197,7 @@ BI.RichEditorBoldButton = BI.inherit(BI.RichEditorAction, { this.bold.setSelected(false); } }); -BI.shortcut("bi.rich_editor_bold_button", BI.RichEditorBoldButton)/** +BI.shortcut("bi.rich_editor_bold_button", BI.RichEditorBoldButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorItalicButton @@ -10247,7 +10237,7 @@ BI.RichEditorItalicButton = BI.inherit(BI.RichEditorAction, { this.italic.setSelected(false); } }); -BI.shortcut("bi.rich_editor_italic_button", BI.RichEditorItalicButton)/** +BI.shortcut("bi.rich_editor_italic_button", BI.RichEditorItalicButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorParamButton @@ -10274,7 +10264,7 @@ BI.RichEditorParamButton = BI.inherit(BI.RichEditorParamAction, { width: 30 }); this.param.on(BI.Button.EVENT_CHANGE, function () { - self.addParam("参数") + self.addParam("参数"); }); }, activate: function () { @@ -10283,7 +10273,7 @@ BI.RichEditorParamButton = BI.inherit(BI.RichEditorParamAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_param_button", BI.RichEditorParamButton)/** +BI.shortcut("bi.rich_editor_param_button", BI.RichEditorParamButton);/** * * Created by GUY on 2015/11/26. * @class BI.RichEditorItalicButton @@ -10323,7 +10313,7 @@ BI.RichEditorUnderlineButton = BI.inherit(BI.RichEditorAction, { this.underline.setSelected(false); } }); -BI.shortcut("bi.rich_editor_underline_button", BI.RichEditorUnderlineButton)/** +BI.shortcut("bi.rich_editor_underline_button", BI.RichEditorUnderlineButton);/** * 颜色选择trigger * * Created by GUY on 2015/11/26. @@ -10363,7 +10353,7 @@ BI.RichEditorColorChooserTrigger = BI.inherit(BI.Widget, { top: 7, left: 2 }] - }) + }); }, setValue: function (color) { @@ -10374,7 +10364,7 @@ BI.RichEditorColorChooserTrigger = BI.inherit(BI.Widget, { return this.font.element.css("color"); } }); -BI.shortcut('bi.rich_editor_color_chooser_trigger', BI.RichEditorColorChooserTrigger);/** +BI.shortcut("bi.rich_editor_color_chooser_trigger", BI.RichEditorColorChooserTrigger);/** * 颜色选择 * * Created by GUY on 2015/11/26. @@ -10468,7 +10458,7 @@ BI.RichEditorColorChooser = BI.inherit(BI.RichEditorAction, { this.colorchooser.setValue(""); } }); -BI.shortcut('bi.rich_editor_color_chooser', BI.RichEditorColorChooser);/** +BI.shortcut("bi.rich_editor_color_chooser", BI.RichEditorColorChooser);/** * 字体大小选择 * * Created by GUY on 2015/11/26. @@ -10609,7 +10599,7 @@ BI.RichEditor = BI.inherit(BI.Widget, { } }); BI.RichEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.rich_editor', BI.RichEditor);/** +BI.shortcut("bi.rich_editor", BI.RichEditor);/** * 分段控件使用的button * * Created by GUY on 2015/9/7. @@ -10621,19 +10611,19 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { _defaultConfig: function () { var conf = BI.SegmentButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { - baseCls: (conf.baseCls || "") + ' bi-segment-button bi-list-item-active', + baseCls: (conf.baseCls || "") + " bi-segment-button bi-list-item-active", shadow: true, readonly: true, hgap: 5 - }) + }); }, _init: function () { BI.SegmentButton.superclass._init.apply(this, arguments); var opts = this.options, self = this; - //if (BI.isNumber(opts.height) && BI.isNull(opts.lineHeight)) { + // if (BI.isNumber(opts.height) && BI.isNull(opts.lineHeight)) { // this.element.css({lineHeight : (opts.height - 2) + 'px'}); - //} + // } this.text = BI.createWidget({ type: "bi.label", element: this, @@ -10642,7 +10632,7 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { text: opts.text, value: opts.value, hgap: opts.hgap - }) + }); }, setSelected: function () { @@ -10658,7 +10648,7 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { BI.SegmentButton.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.segment_button', BI.SegmentButton);/** +BI.shortcut("bi.segment_button", BI.SegmentButton);/** * 单选按钮组 * * Created by GUY on 2015/9/7. @@ -10689,13 +10679,13 @@ BI.Segment = BI.inherit(BI.Widget, { type: "bi.center" } ] - }) + }); this.buttonGroup.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments) + self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); this.buttonGroup.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { - self.fireEvent(BI.Segment.EVENT_CHANGE, value, obj) - }) + self.fireEvent(BI.Segment.EVENT_CHANGE, value, obj); + }); }, setValue: function (v) { @@ -10711,7 +10701,7 @@ BI.Segment = BI.inherit(BI.Widget, { } }); BI.Segment.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.segment', BI.Segment);/** +BI.shortcut("bi.segment", BI.Segment);/** * 自适应宽度的表格 * * Created by GUY on 2016/2/3. @@ -10731,11 +10721,11 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, isNeedResize: true, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -10748,9 +10738,9 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { regionColumnSize: [], header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -10785,7 +10775,7 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -10852,7 +10842,7 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { freezeCols: freezeCols, columnSize: columnSize, regionColumnSize: regionColumnSize - } + }; }, _populate: function () { @@ -10938,7 +10928,7 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { BI.AdaptiveTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.adaptive_table', BI.AdaptiveTable);/** +BI.shortcut("bi.adaptive_table", BI.AdaptiveTable);/** * * 层级树状结构的表格 * @@ -10954,13 +10944,13 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { el: { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -10973,7 +10963,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { regionColumnSize: [], - //行表头 + // 行表头 rowHeaderCreator: null, headerCellStyleGetter: BI.emptyFn, @@ -10984,14 +10974,14 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { footer: false, items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -11013,16 +11003,16 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { var deep = this._getHDeep(); if (deep <= 0) { newHeader.unshift(o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }); + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }); } else { newHeader[0] = o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }; + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }; } result.push(newHeader); } @@ -11033,7 +11023,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { var self = this, o = this.options; var result = []; - function track(node, layer) { + function track (node, layer) { node.type || (node.type = "bi.layer_tree_table_cell"); node.layer = layer; var next = [node]; @@ -11060,7 +11050,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { return o.summaryCellStyleGetter(true); } }].concat(node.values); - result.push(next) + result.push(next); } }); return BI.DynamicSummaryTreeTable.formatSummaryItems(result, header, o.crossItems, 1); @@ -11128,7 +11118,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { minColumnSize: this._formatColumns(minColumnSize, deep), maxColumnSize: this._formatColumns(maxColumnSize, deep), freezeCols: this._formatFreezeCols() - } + }; }, _init: function () { @@ -11288,13 +11278,13 @@ BI.DynamicSummaryTreeTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -11315,14 +11305,14 @@ BI.DynamicSummaryTreeTable = BI.inherit(BI.Widget, { footer: false, items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -11500,7 +11490,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { formatHorizontalItems: function (nodes, deep, isCross, styleGetter) { var result = []; - function track(store, node) { + function track (store, node) { var next; if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { @@ -11524,7 +11514,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { text: BI.i18nText("BI-Summary_Values"), type: "bi.table_style_cell", styleGetter: function () { - return styleGetter(store === -1) + return styleGetter(store === -1); } }; for (var i = next.length; i < deep; i++) { @@ -11571,7 +11561,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { BI.each(nodes, function (i, node) { track(-1, node); }); - //填充空位 + // 填充空位 BI.each(result, function (i, line) { var last = BI.last(line); for (var j = line.length; j < deep; j++) { @@ -11582,11 +11572,11 @@ BI.extend(BI.DynamicSummaryTreeTable, { }, formatSummaryItems: function (items, header, crossItems, deep) { - //求纵向需要去除的列 + // 求纵向需要去除的列 var cols = []; var leaf = 0; - function track(node) { + function track (node) { if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { track(child); @@ -11622,7 +11612,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { BI.each(items, function (i, node) { var nNode = node.slice(); BI.removeAt(nNode, cols); - nItems.push(nNode);; + nItems.push(nNode); }); header = nHeader; items = nItems; @@ -11642,7 +11632,7 @@ BI.LayerTreeTableCell = BI.inherit(BI.Widget, { baseCls: "bi-layer-tree-table-cell", layer: 0, text: "" - }) + }); }, _init: function () { @@ -11658,7 +11648,7 @@ BI.LayerTreeTableCell = BI.inherit(BI.Widget, { value: o.value, lgap: 5 + 30 * o.layer, rgap: 5 - }) + }); } }); @@ -11678,13 +11668,13 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, - isNeedResize: false,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: false, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -11706,14 +11696,14 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { header: [], items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -11735,16 +11725,16 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { var deep = this._getHDeep(); if (deep <= 0) { newHeader.unshift(o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }); + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }); } else { newHeader[0] = o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }; + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }; } result.push(newHeader); } @@ -11755,7 +11745,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { var self = this, o = this.options; var result = []; - function track(node, layer) { + function track (node, layer) { node.type || (node.type = "bi.layer_tree_table_cell"); node.layer = layer; var next = [node]; @@ -11780,7 +11770,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { return o.summaryCellStyleGetter(true); } }].concat(node.values); - result.push(next) + result.push(next); } }); return result; @@ -11828,7 +11818,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { minColumnSize: this._formatColumns(o.minColumnSize, deep), maxColumnSize: this._formatColumns(o.maxColumnSize, deep), freezeCols: this._formatFreezeCols() - } + }; }, _init: function () { @@ -12024,7 +12014,7 @@ BI.TableStyleCell = BI.inherit(BI.Single, { this._digestStyle(); } }); -BI.shortcut('bi.table_style_cell', BI.TableStyleCell);/** +BI.shortcut("bi.table_style_cell", BI.TableStyleCell);/** * * 树状结构的表格 * @@ -12039,12 +12029,12 @@ BI.TableTree = BI.inherit(BI.Widget, { el: { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -12063,14 +12053,14 @@ BI.TableTree = BI.inherit(BI.Widget, { header: [], items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -12132,7 +12122,7 @@ BI.TableTree = BI.inherit(BI.Widget, { return { header: header, items: items - } + }; }, setWidth: function (width) { @@ -12241,7 +12231,7 @@ BI.extend(BI.TableTree, { var self = this; var result = []; - function track(store, node) { + function track (store, node) { var next; if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { @@ -12260,12 +12250,12 @@ BI.extend(BI.TableTree, { } else { next = []; } - if (/**(store == -1 || node.children.length > 1) &&**/ BI.isNotEmptyArray(node.values)) { + if (/** (store == -1 || node.children.length > 1) &&**/ BI.isNotEmptyArray(node.values)) { var summary = { text: BI.i18nText("BI-Summary_Values"), type: "bi.table_style_cell", styleGetter: function () { - return styleGetter(store === -1) + return styleGetter(store === -1); } }; for (var i = next.length; i < deep; i++) { @@ -12313,7 +12303,7 @@ BI.extend(BI.TableTree, { BI.each(nodes, function (i, node) { track(-1, node); }); - //填充空位 + // 填充空位 BI.each(result, function (i, line) { var last = BI.last(line); for (var j = line.length; j < deep; j++) { @@ -12329,7 +12319,7 @@ BI.extend(BI.TableTree, { }, maxDeep: function (nodes) { - function track(deep, node) { + function track (deep, node) { var d = deep; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { @@ -12361,14 +12351,14 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { return BI.extend(BI.MultiSelectBar.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-multi-select-bar", height: 25, - text: BI.i18nText('BI-Select_All'), + text: BI.i18nText("BI-Select_All"), isAllCheckedBySelectedValue: BI.emptyFn, - //手动控制选中 + // 手动控制选中 disableSelected: true, isHalfCheckedBySelectedValue: function (selectedValues) { return selectedValues.length > 0; } - }) + }); }, _init: function () { BI.MultiSelectBar.superclass._init.apply(this, arguments); @@ -12427,7 +12417,7 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { this.half.invisible(); }, - //自己手动控制选中 + // 自己手动控制选中 beforeClick: function () { var isHalf = this.isHalfSelected(), isSelected = this.isSelected(); if (isHalf === true) { @@ -12483,10 +12473,10 @@ BI.BranchRelation = BI.inherit(BI.Widget, { baseCls: "bi-branch-relation-tree", items: [], - centerOffset: 0,//重心偏移量 + centerOffset: 0, // 重心偏移量 direction: BI.Direction.Bottom, align: BI.VerticalAlign.Top - }) + }); }, _init: function () { @@ -12494,11 +12484,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { this.populate(this.options.items); }, - //树分层 + // 树分层 _stratification: function () { var levels = []; this.tree.recursion(function (node, route) { - //node.isRoot = route.length <= 1; + // node.isRoot = route.length <= 1; node.leaf = node.isLeaf(); if (!levels[route.length - 1]) { levels[route.length - 1] = []; @@ -12508,11 +12498,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return levels; }, - //计算所有节点的叶子结点个数 + // 计算所有节点的叶子结点个数 _calculateLeaves: function () { var count = 0; - function track(node) { + function track (node) { var c = 0; if (node.isLeaf()) { return 1; @@ -12528,7 +12518,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return count; }, - //树平移 + // 树平移 _translate: function (levels) { var adjust = []; var maxLevel = levels.length; @@ -12539,16 +12529,16 @@ BI.BranchRelation = BI.inherit(BI.Widget, { BI.each(nodes, function (j, node) { if (node.isLeaf() && i < maxLevel - 1) { var newNode = new BI.Node(BI.UUID()); - //newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; + // newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; newNode.isNew = true; - //把node向下一层移 + // 把node向下一层移 var tar = 0; if (j > 0) { var c = nodes[j - 1].getLastChild(); tar = levels[i + 1].indexOf(c) + 1; } levels[i + 1].splice(tar, 0, node); - //新增一个临时树节点 + // 新增一个临时树节点 var index = node.parent.getChildIndex(node.id); node.parent.removeChildByIndex(index); node.parent.addChild(newNode, index); @@ -12558,12 +12548,12 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } else { adjust[i].push(node); } - }) + }); }); return adjust; }, - //树补白 + // 树补白 _fill: function (levels) { var adjust = []; var maxLevel = levels.length; @@ -12578,23 +12568,23 @@ BI.BranchRelation = BI.inherit(BI.Widget, { newNode.width = node.width; newNode.height = node.height; newNode.isNew = true; - //把node向下一层移 + // 把node向下一层移 var tar = 0; if (j > 0) { var c = nodes[j - 1].getLastChild(); tar = levels[i + 1].indexOf(c) + 1; } levels[i + 1].splice(tar, 0, newNode); - //新增一个临时树节点 + // 新增一个临时树节点 node.addChild(newNode); } adjust[i].push(node); - }) + }); }); return adjust; }, - //树调整 + // 树调整 _adjust: function (adjust) { while (true) { var isAllNeedAjust = false; @@ -12618,7 +12608,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { node.addChild(c); }); var newNode = new BI.Node(BI.UUID()); - //newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; + // newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; newNode.isNew = true; var index = node.parent.getChildIndex(node.id); node.parent.removeChildByIndex(index); @@ -12627,11 +12617,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { isAllNeedAjust = true; } } - }) + }); }); if (isAllNeedAjust === false) { break; - } else {//树重构 + } else {// 树重构 adjust = this._stratification(); } } @@ -12642,7 +12632,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var o = this.options; var width = 0; - function track1(node) { + function track1 (node) { var w = 0; if (node.isLeaf()) { return node.width; @@ -12653,7 +12643,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return w; } - function track2(node) { + function track2 (node) { var w = 0; if (node.isLeaf()) { return node.height; @@ -12682,7 +12672,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var o = this.options; var height = 0; - function track1(node) { + function track1 (node) { var h = 0; BI.each(node.getChildren(), function (i, child) { h = Math.max(h, track1(child)); @@ -12690,7 +12680,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return h + (node.height || 0); } - function track2(node) { + function track2 (node) { var h = 0; BI.each(node.getChildren(), function (i, child) { h = Math.max(h, track2(child)); @@ -12712,23 +12702,23 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var height = this._calculateHeight(); var levelCount = levels.length; var allLeavesCount = this._calculateLeaves(); - //计算坐标 + // 计算坐标 var xy = {}; var levelHeight = height / levelCount; BI.each(levels, function (i, nodes) { - //计算权重 + // 计算权重 var weights = []; BI.each(nodes, function (j, node) { weights[j] = (node.get("leaves") || 1) / allLeavesCount; }); BI.each(nodes, function (j, node) { - //求前j个元素的权重 + // 求前j个元素的权重 var weight = BI.sum(weights.slice(0, j)); - //求坐标 + // 求坐标 var x = weight * width + weights[j] * width / 2; var y = i * levelHeight + levelHeight / 2; xy[node.id] = {x: x, y: y}; - }) + }); }); return xy; }, @@ -12757,7 +12747,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Bottom: @@ -12778,7 +12768,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Left: @@ -12799,7 +12789,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Right: @@ -12820,7 +12810,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; } @@ -12832,14 +12822,14 @@ BI.BranchRelation = BI.inherit(BI.Widget, { levels = levels.reverse(); } var xy = this._calculateXY(levels); - //画图 + // 画图 this._stroke(levels, xy); }, _isNeedAdjust: function () { var o = this.options; return o.direction === BI.Direction.Top && o.align === BI.VerticalAlign.Bottom || o.direction === BI.Direction.Bottom && o.align === BI.VerticalAlign.Top - || o.direction === BI.Direction.Left && o.align === BI.HorizontalAlign.Right || o.direction === BI.Direction.Right && o.align === BI.HorizontalAlign.Left + || o.direction === BI.Direction.Left && o.align === BI.HorizontalAlign.Right || o.direction === BI.Direction.Right && o.align === BI.HorizontalAlign.Left; }, setValue: function (value) { @@ -12873,9 +12863,9 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } } return r; - } else { - return [sNodes]; } + return [sNodes]; + }, populate: function (items) { @@ -12890,13 +12880,13 @@ BI.BranchRelation = BI.inherit(BI.Widget, { type: "bi.svg" }); - //树分层 + // 树分层 var levels = this._stratification(); if (this._isNeedAdjust()) { - //树平移 + // 树平移 var adjust = this._translate(levels); - //树调整 + // 树调整 adjust = this._adjust(adjust); this._createBranches(adjust); @@ -12935,7 +12925,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { }] }, items: items - }] + }]; } else { items = [{ type: "bi.branch_tree", @@ -12950,7 +12940,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { }] }, items: items - }] + }]; } BI.createWidget({ type: "bi.adaptive", @@ -12982,7 +12972,7 @@ BI.HandStandBranchExpander = BI.inherit(BI.Widget, { }, el: {type: "bi.label"}, popup: {} - }) + }); }, _init: function () { @@ -13040,7 +13030,7 @@ BI.BranchExpander = BI.inherit(BI.Widget, { }, el: {}, popup: {} - }) + }); }, _init: function () { @@ -13097,7 +13087,7 @@ BI.HandStandBranchTree = BI.inherit(BI.Widget, { expander: {}, el: {}, items: [] - }) + }); }, _init: function () { BI.HandStandBranchTree.superclass._init.apply(this, arguments); @@ -13121,10 +13111,10 @@ BI.HandStandBranchTree = BI.inherit(BI.Widget, { }, o.el), items: this.options.items }); - this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function(){ + this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function () { self.fireEvent(BI.HandStandBranchTree.EVENT_CHANGE, arguments); }); - this.branchTree.on(BI.Controller.EVENT_CHANGE, function(){ + this.branchTree.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); }, @@ -13151,7 +13141,7 @@ BI.BranchTree = BI.inherit(BI.Widget, { expander: {}, el: {}, items: [] - }) + }); }, _init: function () { BI.BranchTree.superclass._init.apply(this, arguments); @@ -13175,10 +13165,10 @@ BI.BranchTree = BI.inherit(BI.Widget, { }, o.el), items: this.options.items }); - this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function(){ + this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function () { self.fireEvent(BI.BranchTree.EVENT_CHANGE, arguments); }); - this.branchTree.on(BI.Controller.EVENT_CHANGE, function(){ + this.branchTree.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); }, @@ -13202,13 +13192,13 @@ BI.DisplayTree = BI.inherit(BI.TreeView, { _defaultConfig: function () { return BI.extend(BI.DisplayTree.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-display-tree" - }) + }); }, _init: function () { BI.DisplayTree.superclass._init.apply(this, arguments); }, - //配置属性 + // 配置属性 _configSetting: function () { var setting = { view: { @@ -13231,7 +13221,7 @@ BI.DisplayTree = BI.inherit(BI.TreeView, { } }; - function beforeCollapse(treeId, treeNode) { + function beforeCollapse (treeId, treeNode) { return false; } @@ -13277,7 +13267,7 @@ BI.LevelTree = BI.inherit(BI.Widget, { }, expander: {}, items: [] - }) + }); }, _init: function () { @@ -13329,7 +13319,7 @@ BI.LevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -13359,10 +13349,10 @@ BI.LevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.LevelTree.EVENT_CHANGE, arguments); } - }) + }); }, - //生成树方法 + // 生成树方法 stroke: function (nodes) { this.tree.stroke.apply(this.tree, arguments); }, @@ -13407,7 +13397,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { baseCls: "bi-simple-tree", itemsCreator: BI.emptyFn, items: null - }) + }); }, _init: function () { BI.SimpleTreeView.superclass._init.apply(this, arguments); @@ -13488,7 +13478,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { } else { track(node); } - }) + }); }; track(val); return result; @@ -13507,7 +13497,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { if (node.isLeaf()) { result.push(node.value); } - }) + }); } }); return result; @@ -13563,7 +13553,7 @@ BI.EditorTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -13619,7 +13609,7 @@ BI.IconTrigger = BI.inherit(BI.Trigger, { }); } }); -BI.shortcut('bi.icon_trigger', BI.IconTrigger);/** +BI.shortcut("bi.icon_trigger", BI.IconTrigger);/** * 文字trigger * * Created by GUY on 2015/9/15. @@ -13657,7 +13647,7 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", ref: function (_ref) { self.wrapper = _ref; }, @@ -13672,12 +13662,12 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { }, width: o.triggerWidth || o.height }, - { - el: this.text - }, { - el: this.trigerButton, - width: o.triggerWidth || o.height - } + { + el: this.text + }, { + el: this.trigerButton, + width: o.triggerWidth || o.height + } ] }); }, @@ -13691,13 +13681,13 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { var o = this.options; this.icon.setIcon(iconCls); var iconItem = this.wrapper.attr("items")[0]; - if(BI.isNull(iconCls) || BI.isEmptyString(iconCls)){ - if(iconItem.width !== 0){ + if(BI.isNull(iconCls) || BI.isEmptyString(iconCls)) { + if(iconItem.width !== 0) { iconItem.width = 0; this.wrapper.resize(); } }else{ - if(iconItem.width !== (o.triggerWidth || o.height)){ + if(iconItem.width !== (o.triggerWidth || o.height)) { iconItem.width = (o.triggerWidth || o.height); this.wrapper.resize(); } @@ -13802,7 +13792,7 @@ BI.TextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.text @@ -13965,7 +13955,7 @@ BI.SmallTextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.text diff --git a/dist/chart.js b/dist/chart.js index b095fe2bb..c3bdf2bfe 100644 --- a/dist/chart.js +++ b/dist/chart.js @@ -8,7 +8,7 @@ BI.Chart = BI.inherit(BI.Pane, { _defaultConfig: function () { return BI.extend(BI.Chart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-chart" - }) + }); }, _init: function () { @@ -35,7 +35,7 @@ BI.Chart = BI.inherit(BI.Pane, { }, magnify: function () { - this.vanCharts.refreshRestore() + this.vanCharts.refreshRestore(); }, populate: function (items, options) { @@ -52,7 +52,7 @@ BI.Chart = BI.inherit(BI.Pane, { } }); BI.Chart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.chart', BI.Chart);/** +BI.shortcut("bi.chart", BI.Chart);/** * 图表控件 * @class BI.CombineChart * @extends BI.Widget @@ -68,14 +68,14 @@ BI.CombineChart = BI.inherit(BI.Widget, { types: [[], []], popupItemsGetter: BI.emptyFn, formatConfig: BI.emptyFn - }) + }); }, _init: function () { BI.CombineChart.superclass._init.apply(this, arguments); var self = this, o = this.options; - //图可配置属性 + // 图可配置属性 this.CombineChart = BI.createWidget({ type: "bi.chart", element: this.element @@ -98,7 +98,7 @@ BI.CombineChart = BI.inherit(BI.Widget, { if (BI.isArray(axisItems)) { result = BI.concat(result, axisItems); } else { - result.push(BI.extend(axisItems, {"yAxis": yAxisIndex})); + result.push(BI.extend(axisItems, {yAxis: yAxisIndex})); } }); if (BI.isNotEmptyArray(combineItems)) { @@ -147,7 +147,7 @@ BI.CombineChart = BI.inherit(BI.Widget, { }, hgap: 10 }, item) - } + }; }) }) }, @@ -172,7 +172,7 @@ BI.CombineChart = BI.inherit(BI.Widget, { this.combo.showView(); this._debounce2Destroy(); - function destroyCombo() { + function destroyCombo () { if (self._doDestroy) { this.destroy(); } @@ -207,7 +207,7 @@ BI.CombineChart = BI.inherit(BI.Widget, { }); BI.CombineChart.EVENT_CHANGE = "EVENT_CHANGE"; BI.CombineChart.EVENT_ITEM_CLICK = "EVENT_ITEM_CLICK"; -BI.shortcut('bi.combine_chart', BI.CombineChart);BI.ChartCombineFormatItemFactory = { +BI.shortcut("bi.combine_chart", BI.CombineChart);BI.ChartCombineFormatItemFactory = { combineItems: function (types, items) { var calItems = BI.values(items); return BI.map(calItems, function (idx, item) { @@ -221,55 +221,55 @@ BI.shortcut('bi.combine_chart', BI.CombineChart);BI.ChartCombineFormatItemFactor case BICst.WIDGET.BAR: case BICst.WIDGET.ACCUMULATE_BAR: case BICst.WIDGET.COMPARE_BAR: - item = BI.extend({"type": "bar"}, items); + item = BI.extend({type: "bar"}, items); break; case BICst.WIDGET.BUBBLE: - item = BI.extend({"type": "bubble"}, items); + item = BI.extend({type: "bubble"}, items); break; case BICst.WIDGET.FORCE_BUBBLE: - item = BI.extend({"type": "forceBubble"}, items); + item = BI.extend({type: "forceBubble"}, items); break; case BICst.WIDGET.SCATTER: - item = BI.extend({"type": "scatter"}, items); + item = BI.extend({type: "scatter"}, items); break; case BICst.WIDGET.AXIS: case BICst.WIDGET.ACCUMULATE_AXIS: case BICst.WIDGET.PERCENT_ACCUMULATE_AXIS: case BICst.WIDGET.COMPARE_AXIS: case BICst.WIDGET.FALL_AXIS: - item = BI.extend({"type": "column"}, items); + item = BI.extend({type: "column"}, items); break; case BICst.WIDGET.LINE: - item = BI.extend({"type": "line"}, items); + item = BI.extend({type: "line"}, items); break; case BICst.WIDGET.AREA: case BICst.WIDGET.ACCUMULATE_AREA: case BICst.WIDGET.COMPARE_AREA: case BICst.WIDGET.RANGE_AREA: case BICst.WIDGET.PERCENT_ACCUMULATE_AREA: - item = BI.extend({"type": "area"}, items); + item = BI.extend({type: "area"}, items); break; case BICst.WIDGET.DONUT: - item = BI.extend({"type": "pie"}, items); + item = BI.extend({type: "pie"}, items); break; case BICst.WIDGET.RADAR: case BICst.WIDGET.ACCUMULATE_RADAR: - item = BI.extend({"type": "radar"}, items); + item = BI.extend({type: "radar"}, items); break; case BICst.WIDGET.PIE: - item = BI.extend({"type": "pie"}, items); + item = BI.extend({type: "pie"}, items); break; case BICst.WIDGET.DASHBOARD: - item = BI.extend({"type": "gauge"}, items); + item = BI.extend({type: "gauge"}, items); break; case BICst.WIDGET.MAP: - item = BI.extend({"type": "areaMap"}, items); + item = BI.extend({type: "areaMap"}, items); break; case BICst.WIDGET.GIS_MAP: - item = BI.extend({"type": "pointMap"}, items); + item = BI.extend({type: "pointMap"}, items); break; default: - item = BI.extend({"type": "column"}, items); + item = BI.extend({type: "column"}, items); break; } return item; @@ -277,177 +277,177 @@ BI.shortcut('bi.combine_chart', BI.CombineChart);BI.ChartCombineFormatItemFactor combineConfig: function () { return { - "title": "", - "chartType": "column", - "plotOptions": { - "rotatable": false, - "startAngle": 0, - "borderRadius": 0, - "endAngle": 360, - "innerRadius": "0.0%", - "layout": "horizontal", - "hinge": "rgb(101,107,109)", - "dataLabels": { - "autoAdjust": true, - "style": {"fontFamily": "inherit", "color": "inherit", "fontSize": "12px"}, - "formatter": { - "identifier": "${VALUE}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat, - "XFormat": this._contentFormat2Decimal, - "YFormat": this._contentFormat2Decimal, - "sizeFormat": this._contentFormat2Decimal + title: "", + chartType: "column", + plotOptions: { + rotatable: false, + startAngle: 0, + borderRadius: 0, + endAngle: 360, + innerRadius: "0.0%", + layout: "horizontal", + hinge: "rgb(101,107,109)", + dataLabels: { + autoAdjust: true, + style: {fontFamily: "inherit", color: "inherit", fontSize: "12px"}, + formatter: { + identifier: "${VALUE}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat, + XFormat: this._contentFormat2Decimal, + YFormat: this._contentFormat2Decimal, + sizeFormat: this._contentFormat2Decimal }, - "align": "outside", - "enabled": false + align: "outside", + enabled: false }, - "percentageLabel": { - "formatter": { - "identifier": "${PERCENT}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat + percentageLabel: { + formatter: { + identifier: "${PERCENT}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat }, - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" }, - "align": "bottom", - "enabled": true + align: "bottom", + enabled: true }, - "valueLabel": { - "formatter": { - "identifier": "${SERIES}${VALUE}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat + valueLabel: { + formatter: { + identifier: "${SERIES}${VALUE}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat }, - "backgroundColor": "rgb(255,255,0)", - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + backgroundColor: "rgb(255,255,0)", + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" }, - "align": "inside", - "enabled": true + align: "inside", + enabled: true }, - "hingeBackgroundColor": "rgb(220,242,249)", - "seriesLabel": { - "formatter": { - "identifier": "${CATEGORY}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat + hingeBackgroundColor: "rgb(220,242,249)", + seriesLabel: { + formatter: { + identifier: "${CATEGORY}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat }, - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" }, - "align": "bottom", - "enabled": true + align: "bottom", + enabled: true }, - "paneBackgroundColor": "rgb(252,252,252)", - "needle": "rgb(229,113,90)", - "large": false, - "connectNulls": false, - "shadow": true, - "curve": false, - "sizeBy": "area", - "tooltip": { - "formatter": { - "identifier": "${SERIES}${X}${Y}${SIZE}{CATEGORY}${SERIES}${VALUE}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat, - "XFormat": this._contentFormat2Decimal, - "sizeFormat": this._contentFormat2Decimal, - "YFormat": this._contentFormat2Decimal + paneBackgroundColor: "rgb(252,252,252)", + needle: "rgb(229,113,90)", + large: false, + connectNulls: false, + shadow: true, + curve: false, + sizeBy: "area", + tooltip: { + formatter: { + identifier: "${SERIES}${X}${Y}${SIZE}{CATEGORY}${SERIES}${VALUE}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat, + XFormat: this._contentFormat2Decimal, + sizeFormat: this._contentFormat2Decimal, + YFormat: this._contentFormat2Decimal }, - "shared": false, - "padding": 5, - "backgroundColor": "rgba(0,0,0,0.4980392156862745)", - "borderColor": "rgb(0,0,0)", - "shadow": false, - "borderRadius": 2, - "borderWidth": 0, - "follow": false, - "enabled": true, - "animation": true, - "style": { - "fontFamily": "Microsoft YaHei, Hiragino Sans GB W3", - "color": "#c4c6c6", - "fontSize": "12px", - "fontWeight": "" + shared: false, + padding: 5, + backgroundColor: "rgba(0,0,0,0.4980392156862745)", + borderColor: "rgb(0,0,0)", + shadow: false, + borderRadius: 2, + borderWidth: 0, + follow: false, + enabled: true, + animation: true, + style: { + fontFamily: "Microsoft YaHei, Hiragino Sans GB W3", + color: "#c4c6c6", + fontSize: "12px", + fontWeight: "" } }, - "maxSize": 80, - "fillColorOpacity": 0.5, - "step": false, - "force": false, - "minSize": 15, - "displayNegative": true, - "categoryGap": "16.0%", - "borderColor": "rgb(255,255,255)", - "borderWidth": 1, - "gap": "22.0%", - "animation": true, - "lineWidth": 2, - "bubble": { - "large": false, - "connectNulls": false, - "shadow": true, - "curve": false, - "sizeBy": "area", - "maxSize": 80, - "minSize": 15, - "lineWidth": 0, - "animation": true, - "fillColorOpacity": 0.699999988079071, - "marker": { - "symbol": "circle", - "radius": 28.39695010101295, - "enabled": true + maxSize: 80, + fillColorOpacity: 0.5, + step: false, + force: false, + minSize: 15, + displayNegative: true, + categoryGap: "16.0%", + borderColor: "rgb(255,255,255)", + borderWidth: 1, + gap: "22.0%", + animation: true, + lineWidth: 2, + bubble: { + large: false, + connectNulls: false, + shadow: true, + curve: false, + sizeBy: "area", + maxSize: 80, + minSize: 15, + lineWidth: 0, + animation: true, + fillColorOpacity: 0.699999988079071, + marker: { + symbol: "circle", + radius: 28.39695010101295, + enabled: true } } }, - "dTools": { - "enabled": false, - "style": { - "fontFamily": "Microsoft YaHei, Hiragino Sans GB W3", - "color": "#1a1a1a", - "fontSize": "12px" + dTools: { + enabled: false, + style: { + fontFamily: "Microsoft YaHei, Hiragino Sans GB W3", + color: "#1a1a1a", + fontSize: "12px" }, - "backgroundColor": 'white' + backgroundColor: "white" }, - "dataSheet": { - "enabled": false, - "borderColor": "rgb(0,0,0)", - "borderWidth": 1, - "formatter": this._contentFormat2Decimal, - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + dataSheet: { + enabled: false, + borderColor: "rgb(0,0,0)", + borderWidth: 1, + formatter: this._contentFormat2Decimal, + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" } }, - "borderColor": "rgb(238,238,238)", - "shadow": false, - "legend": { - "borderColor": "rgb(204,204,204)", - "borderRadius": 0, - "shadow": false, - "borderWidth": 0, - "visible": true, - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + borderColor: "rgb(238,238,238)", + shadow: false, + legend: { + borderColor: "rgb(204,204,204)", + borderRadius: 0, + shadow: false, + borderWidth: 0, + visible: true, + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" }, - "position": "right", - "enabled": false + position: "right", + enabled: false }, - "rangeLegend": { - "range": { - "min": 0, - "color": [ + rangeLegend: { + range: { + min: 0, + color: [ [ 0, "rgb(182,226,255)" @@ -461,41 +461,41 @@ BI.shortcut('bi.combine_chart', BI.CombineChart);BI.ChartCombineFormatItemFactor "rgb(36,167,255)" ] ], - "max": 266393 + max: 266393 }, - "enabled": false + enabled: false }, - "zoom": {"zoomType": "xy", "zoomTool": {"visible": false, "resize": true, "from": "", "to": ""}}, - "plotBorderColor": "rgba(255,255,255,0)", - "tools": { - "hidden": false, - "toImage": {"enabled": false}, - "sort": {"enabled": false}, - "fullScreen": {"enabled": false}, - "refresh": { - "enabled": false + zoom: {zoomType: "xy", zoomTool: {visible: false, resize: true, from: "", to: ""}}, + plotBorderColor: "rgba(255,255,255,0)", + tools: { + hidden: false, + toImage: {enabled: false}, + sort: {enabled: false}, + fullScreen: {enabled: false}, + refresh: { + enabled: false } }, - "plotBorderWidth": 0, - "style": "normal", - "colors": ["rgb(99,178,238)", "rgb(118,218,145)"], - "borderRadius": 0, - "borderWidth": 0, - "plotShadow": false, - "plotBorderRadius": 0 + plotBorderWidth: 0, + style: "normal", + colors: ["rgb(99,178,238)", "rgb(118,218,145)"], + borderRadius: 0, + borderWidth: 0, + plotShadow: false, + plotBorderRadius: 0 }; }, _contentFormat: function () { - return BI.contentFormat(arguments[0], '') + return BI.contentFormat(arguments[0], ""); }, _contentFormat2Decimal: function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + return BI.contentFormat(arguments[0], "#.##;-#.##"); }, _contentFormatPercentage: function () { - return BI.contentFormat(arguments[0], '#.##%;-#.##%') + return BI.contentFormat(arguments[0], "#.##%;-#.##%"); } };/** * 图表控件 @@ -540,9 +540,9 @@ BI.AbstractChart = BI.inherit(BI.Widget, { LINE_WIDTH: 1, NUM_SEPARATORS: false, FONT_STYLE: { - "fontFamily": "inherit", - "color": "inherit", - "fontSize": "12px" + fontFamily: "inherit", + color: "inherit", + fontSize: "12px" } }, @@ -550,7 +550,7 @@ BI.AbstractChart = BI.inherit(BI.Widget, { return BI.extend(BI.AbstractChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-abstract-chart", popupItemsGetter: BI.emptyFn - }) + }); }, _init: function () { @@ -600,12 +600,12 @@ BI.AbstractChart = BI.inherit(BI.Widget, { da.x = BI.contentFormat(BI.parseFloat(da.x.div(magnify).toFixed(4)), "#.####;-#.####"); } }); - }) + }); }, formatXYDataWithMagnify: function (number, magnify) { if (BI.isNull(number)) { - return null + return null; } if (!BI.isNumber(number)) { number = BI.parseFloat(number); @@ -672,46 +672,46 @@ BI.AbstractChart = BI.inherit(BI.Widget, { }, formatTickInXYaxis: function (type, number_level, separators, isCompareBar) { - var formatter = '#.##'; + var formatter = "#.##"; switch (type) { case this.constants.NORMAL: - formatter = '#.##'; + formatter = "#.##"; if (separators) { - formatter = '#,###.##' + formatter = "#,###.##"; } break; case this.constants.ZERO2POINT: - formatter = '#0'; + formatter = "#0"; if (separators) { - formatter = '#,###'; + formatter = "#,###"; } break; case this.constants.ONE2POINT: - formatter = '#0.0'; + formatter = "#0.0"; if (separators) { - formatter = '#,###.0'; + formatter = "#,###.0"; } break; case this.constants.TWO2POINT: - formatter = '#0.00'; + formatter = "#0.00"; if (separators) { - formatter = '#,###.00'; + formatter = "#,###.00"; } break; } if (number_level === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT) { - formatter += '%'; + formatter += "%"; } formatter += ";-" + formatter; if(isCompareBar) { return function () { arguments[0] = arguments[0] > 0 ? arguments[0] : (-1) * arguments[0]; return BI.contentFormat(arguments[0], formatter); - } + }; } return function () { - return BI.contentFormat(arguments[0], formatter) - } + return BI.contentFormat(arguments[0], formatter); + }; }, formatDataLabel: function (state, items, config, style) { @@ -719,8 +719,8 @@ BI.AbstractChart = BI.inherit(BI.Widget, { if (state === true) { BI.each(items, function (idx, item) { item.dataLabels = { - "align": "outside", - "autoAdjust": true, + align: "outside", + autoAdjust: true, style: style, enabled: true, formatter: { @@ -737,13 +737,13 @@ BI.AbstractChart = BI.inherit(BI.Widget, { if (state === true) { BI.each(items, function (idx, item) { item.dataLabels = { - "align": "outside", - "autoAdjust": true, + align: "outside", + autoAdjust: true, style: style, enabled: true, formatter: { identifier: "${VALUE}", - valueFormat: format, + valueFormat: format } }; if(isPercentChart) { @@ -764,7 +764,7 @@ BI.AbstractChart = BI.inherit(BI.Widget, { BI.each(config.yAxis, function (idx, axis) { axis.labelStyle = fontStyle; axis.title.style = fontStyle; - }) + }); }, _formatItems: function (items) { @@ -793,7 +793,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AccumulateAreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-accumulate-area-chart" - }) + }); }, _init: function () { @@ -820,7 +820,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AccumulateAreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -887,20 +887,20 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle(v) { + function formatChartStyle (v) { switch (v) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -910,7 +910,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatChartLineStyle(v) { + function formatChartLineStyle (v) { switch (v) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.curve = false; @@ -928,7 +928,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon(cordon) { + function formatCordon (cordon) { BI.each(cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -937,9 +937,9 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -962,14 +962,14 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } }, @@ -1059,7 +1059,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { } }); BI.AccumulateAreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.accumulate_area_chart', BI.AccumulateAreaChart);/** +BI.shortcut("bi.accumulate_area_chart", BI.AccumulateAreaChart);/** * 图表控件 * @class BI.AccumulateAxisChart * @extends BI.Widget @@ -1069,7 +1069,7 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AccumulateAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-accumulate-axis-chart" - }) + }); }, _init: function () { @@ -1094,7 +1094,7 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AccumulateAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -1154,20 +1154,20 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { enableTick: self.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "column"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -1176,9 +1176,9 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -1201,17 +1201,17 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -1221,7 +1221,7 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { } } - function getTitleText(numberLevelType, position, show, title) { + function getTitleText (numberLevelType, position, show, title) { var unit = ""; switch (numberLevelType) { @@ -1239,13 +1239,13 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } unit = unit === "" ? unit : "(" + unit + ")"; @@ -1338,7 +1338,7 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { } }); BI.AccumulateAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.accumulate_axis_chart', BI.AccumulateAxisChart);/** +BI.shortcut("bi.accumulate_axis_chart", BI.AccumulateAxisChart);/** * 图表控件 * @class BI.AccumulateBarChart * @extends BI.Widget @@ -1348,7 +1348,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AccumulateBarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-accumulate-bar-chart" - }) + }); }, _init: function () { @@ -1361,7 +1361,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { }, labelStyle: this.constants.FONT_STYLE, formatter: function () { - return this > 0 ? this : (-1) * this + return this > 0 ? this : (-1) * this; }, gridLineWidth: 0 }]; @@ -1385,7 +1385,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AccumulateBarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -1407,7 +1407,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, lineWidth: this.config.lineWidth, enableTick: this.config.enableTick, - maxWidth: '40%' + maxWidth: "40%" }); self.formatNumberLevelInXaxis(items, this.config.leftYAxisNumberLevel); @@ -1422,17 +1422,17 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { enableMinorTick: this.config.enableMinorTick }); config.chartType = "bar"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.xAxis[0].formatter, this.config.chartFont); config.plotOptions.tooltip.formatter.valueFormat = config.xAxis[0].formatter; - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -1442,7 +1442,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.leftYAxisNumberLevel); @@ -1451,9 +1451,9 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -1476,17 +1476,17 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -1503,13 +1503,13 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -1524,7 +1524,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { var tmp = t.x; t.x = t.y; t.y = tmp; - }) + }); }); }); return items; @@ -1583,7 +1583,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { } }); BI.AccumulateBarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.accumulate_bar_chart', BI.AccumulateBarChart);/** +BI.shortcut("bi.accumulate_bar_chart", BI.AccumulateBarChart);/** * 图表控件 * @class BI.AccumulateRadarChart * @extends BI.Widget @@ -1593,7 +1593,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AccumulateRadarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-accumulate-radar-chart" - }) + }); }, _init: function () { @@ -1606,7 +1606,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { }, labelStyle: this.constants.FONT_STYLE, formatter: function () { - return this > 0 ? this : (-1) * this + return this > 0 ? this : (-1) * this; }, gridLineWidth: 0, position: "bottom" @@ -1630,7 +1630,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AccumulateRadarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -1666,17 +1666,17 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { config.plotOptions.columnType = true; delete config.xAxis; delete config.yAxis; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.radiusAxis[0].formatter, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 config.radiusAxis[0].labelStyle = config.radiusAxis[0].title.style = this.config.chartFont; config.angleAxis[0].labelStyle = config.angleAxis[0].title.style = this.config.chartFont; config.legend.style = this.config.chartFont; return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -1686,7 +1686,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { } } - function formatChartRadarStyle() { + function formatChartRadarStyle () { switch (self.config.chartRadarType) { case BICst.CHART_SHAPE.POLYGON: config.plotOptions.shape = "polygon"; @@ -1697,19 +1697,19 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { } } - function formatNumberLevelInYaxis(type, position, formatter) { + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = formatter; } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -1726,13 +1726,13 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -1776,7 +1776,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { } }); BI.AccumulateRadarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.accumulate_radar_chart', BI.AccumulateRadarChart);/** +BI.shortcut("bi.accumulate_radar_chart", BI.AccumulateRadarChart);/** * 图表控件 * @class BI.AreaChart * @extends BI.Widget @@ -1786,7 +1786,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-area-chart" - }) + }); }, _init: function () { @@ -1812,7 +1812,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -1877,20 +1877,20 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -1900,7 +1900,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -1909,9 +1909,9 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -1934,17 +1934,17 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartLineStyle() { + function formatChartLineStyle () { switch (self.config.chartLineType) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.curve = false; @@ -1962,7 +1962,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { } } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -1979,13 +1979,13 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -2077,7 +2077,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { } }); BI.AreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.area_chart', BI.AreaChart);/** +BI.shortcut("bi.area_chart", BI.AreaChart);/** * 图表控件 柱状 * @class BI.AxisChart * @extends BI.Widget @@ -2090,7 +2090,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-axis-chart" - }) + }); }, _init: function () { @@ -2116,7 +2116,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -2181,7 +2181,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); var lineItem = []; @@ -2194,15 +2194,15 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { } }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [BI.concat(otherItem, lineItem), config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -2212,7 +2212,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -2221,9 +2221,9 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -2243,17 +2243,17 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -2270,13 +2270,13 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -2352,7 +2352,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { } }); BI.AxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.axis_chart', BI.AxisChart);/** +BI.shortcut("bi.axis_chart", BI.AxisChart);/** * 图表控件 * @class BI.BarChart * @extends BI.Widget @@ -2362,7 +2362,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.BarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-bar-chart" - }) + }); }, _init: function () { @@ -2375,7 +2375,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { }, labelStyle: this.constants.FONT_STYLE, formatter: function () { - return this > 0 ? this : (-1) * this + return this > 0 ? this : (-1) * this; }, gridLineWidth: 0 }]; @@ -2402,7 +2402,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.BarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -2414,7 +2414,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { this.formatChartLegend(config, this.config.chartLegend); config.plotOptions.dataLabels.enabled = this.config.showDataLabel; - //分类轴 + // 分类轴 config.yAxis = this.yAxis; config.yAxis[0].title.text = this.config.showXAxisTitle === true ? this.config.xAxisTitle : ""; config.yAxis[0].title.rotation = this.constants.ROTATION; @@ -2423,10 +2423,10 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableTick: this.config.enableTick, lineWidth: this.config.lineWidth, - maxWidth: '40%' + maxWidth: "40%" }); - //值轴 + // 值轴 self.formatNumberLevelInXaxis(items, this.config.leftYAxisNumberLevel); config.xAxis[0].title.text = getXAxisTitle(this.config.leftYAxisNumberLevel, this.constants.X_AXIS); config.xAxis[0].title.align = "center"; @@ -2444,12 +2444,12 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { config.plotOptions.tooltip.formatter.valueFormat = config.xAxis[0].formatter; - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -2459,7 +2459,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.leftYAxisNumberLevel); @@ -2468,9 +2468,9 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -2490,17 +2490,17 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXAxisTitle(numberLevelType, position) { + function getXAxisTitle (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -2517,10 +2517,10 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } unit = unit === "" ? unit : "(" + unit + ")"; @@ -2535,7 +2535,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { var tmp = t.x; t.x = t.y; t.y = tmp; - }) + }); }); }); return items; @@ -2592,7 +2592,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { } }); BI.BarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.bar_chart', BI.BarChart);/** +BI.shortcut("bi.bar_chart", BI.BarChart);/** * 图表控件 * @class BI.BubbleChart * @extends BI.Widget @@ -2602,7 +2602,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.BubbleChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-bubble-chart" - }) + }); }, _init: function () { @@ -2637,7 +2637,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.BubbleChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -2660,7 +2660,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { config.yAxis[0].gridLineWidth = this.config.showGridLine === true ? 1 : 0; config.yAxis[0].lineWidth = 1; config.yAxis[0].title.rotation = this.constants.ROTATION; - config.yAxis[0].maxWidth = '40%'; + config.yAxis[0].maxWidth = "40%"; config.xAxis[0].formatter = self.formatTickInXYaxis(this.config.xAxisStyle, this.config.xAxisNumberLevel, this.config.rightNumSeparators); self.formatNumberLevelInXaxis(items, this.config.xAxisNumberLevel); @@ -2668,41 +2668,42 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { config.xAxis[0].title.text = this.config.showXAxisTitle === true ? this.config.xAxisTitle + config.xAxis[0].title.text : config.xAxis[0].title.text; config.xAxis[0].title.align = "center"; config.xAxis[0].gridLineWidth = this.config.showGridLine === true ? 1 : 0; - config.xAxis[0].maxHeith = '40%'; + config.xAxis[0].maxHeith = "40%"; config.chartType = "bubble"; if (BI.isNotEmptyArray(this.config.tooltip)) { config.plotOptions.bubble.tooltip = { useHtml: true, style: { - color: 'RGB(184, 184, 184)' + color: "RGB(184, 184, 184)" }, formatter: function () { - var y = self.formatTickInXYaxis(self.config.leftYAxisStyle, self.config.leftYAxisNumberLevel, self.config.numSeparators)(this.y); - var x = self.formatTickInXYaxis(self.config.xAxisStyle, self.config.xAxisNumberLevel, self.config.rightNumSeparators)(this.x); - return this.seriesName + '
    (X)' + self.config.tooltip[0] + ':' + x + '
    (Y)' + self.config.tooltip[1] - + ':' + y + '
    (' + BI.i18nText("BI-Size") + ')' + self.config.tooltip[2] + ':' + this.size + '
    '} + var y = self.formatTickInXYaxis(self.config.leftYAxisStyle, self.config.leftYAxisNumberLevel, self.config.numSeparators)(this.y); + var x = self.formatTickInXYaxis(self.config.xAxisStyle, self.config.xAxisNumberLevel, self.config.rightNumSeparators)(this.x); + return this.seriesName + "
    (X)" + self.config.tooltip[0] + ":" + x + "
    (Y)" + self.config.tooltip[1] + + ":" + y + "
    (" + BI.i18nText("BI-Size") + ")" + self.config.tooltip[2] + ":" + this.size + "
    "; + } }; } - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 if (config.plotOptions.dataLabels.enabled === true) { BI.each(items, function (idx, item) { item.dataLabels = { - "style" : self.config.chartFont, - "align": "outside", - "autoAdjust": true, + style: self.config.chartFont, + align: "outside", + autoAdjust: true, enabled: true, formatter: { identifier: "${X}${Y}${SIZE}", - "XFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + XFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); }, - "YFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + YFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); }, - "sizeFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + sizeFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); } } }; @@ -2711,14 +2712,14 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { }); } - //全局样式图表文字 + // 全局样式图表文字 config.yAxis[0].title.style = config.yAxis[0].labelStyle = this.config.chartFont; config.xAxis[0].title.style = config.xAxis[0].labelStyle = this.config.chartFont; config.legend.style = this.config.chartFont; return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -2728,7 +2729,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -2737,9 +2738,9 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -2762,31 +2763,31 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatNumberLevelInYaxis(type, position) { + function formatNumberLevelInYaxis (type, position) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); if (type === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT) { - //config.plotOptions.tooltip.formatter.valueFormat = "function(){return window.FR ? FR.contentFormat(arguments[0], '#0%') : arguments[0]}"; + // config.plotOptions.tooltip.formatter.valueFormat = "function(){return window.FR ? FR.contentFormat(arguments[0], '#0%') : arguments[0]}"; } } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -2803,13 +2804,13 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -2820,9 +2821,9 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { BI.each(item, function (id, it) { BI.each(it.data, function (i, da) { var data = da.size; - da.size = BI.contentFormat(data, '#.##;-#.##') - }) - }) + da.size = BI.contentFormat(data, "#.##;-#.##"); + }); + }); }); return items; }, @@ -2873,7 +2874,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { } }); BI.BubbleChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.bubble_chart', BI.BubbleChart); +BI.shortcut("bi.bubble_chart", BI.BubbleChart); /** * 图表控件 * @class BI.CompareAreaChart @@ -2884,7 +2885,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.CompareAreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-compare-area-chart" - }) + }); }, _init: function () { @@ -2910,7 +2911,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.CompareAreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -2979,20 +2980,20 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function _calculateValueNiceDomain(minValue, maxValue) { + function _calculateValueNiceDomain (minValue, maxValue) { minValue = Math.min(0, minValue); @@ -3001,7 +3002,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { return _linearNiceDomain(minValue, maxValue, tickInterval); } - function _linearTickInterval(minValue, maxValue, m) { + function _linearTickInterval (minValue, maxValue, m) { m = m || 5; var span = maxValue - minValue; @@ -3013,7 +3014,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { return step; } - function _linearNiceDomain(minValue, maxValue, tickInterval) { + function _linearNiceDomain (minValue, maxValue, tickInterval) { minValue = VanUtils.accMul(Math.floor(minValue / tickInterval), tickInterval); @@ -3022,7 +3023,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { return [minValue, maxValue]; } - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -3032,7 +3033,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -3041,9 +3042,9 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -3066,17 +3067,17 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartLineStyle() { + function formatChartLineStyle () { switch (self.config.chartLineType) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.area = { @@ -3100,7 +3101,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatNumberLevelInYaxis(type, position, formatter) { + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { var max = null; @@ -3122,7 +3123,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -3139,13 +3140,13 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -3246,7 +3247,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { } }); BI.CompareAreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.compare_area_chart', BI.CompareAreaChart);/** +BI.shortcut("bi.compare_area_chart", BI.CompareAreaChart);/** * 图表控件 * @class BI.CompareAxisChart * @extends BI.Widget @@ -3256,7 +3257,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.CompareAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-compare-axis-chart" - }) + }); }, _init: function () { @@ -3291,11 +3292,11 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.CompareAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, - _formatConfig: function(config, items){ + _formatConfig: function (config, items) { var self = this, o = this.options; config.colors = this.config.chartColor; config.style = formatChartStyle(); @@ -3306,15 +3307,15 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { config.dataSheet.enabled = this.config.showDataTable; config.xAxis[0].showLabel = !config.dataSheet.enabled; config.zoom.zoomTool.enabled = this.config.showZoom; - if(this.config.showZoom === true){ + if(this.config.showZoom === true) { delete config.dataSheet; delete config.zoom.zoomType; } config.yAxis = this.yAxis; - BI.each(config.yAxis, function(idx, axis){ - var unit = ''; - switch (axis.axisIndex){ + BI.each(config.yAxis, function (idx, axis) { + var unit = ""; + switch (axis.axisIndex) { case self.constants.LEFT_AXIS: unit = getXYAxisUnit(self.config.leftYAxisNumberLevel, self.constants.LEFT_AXIS); axis.title.rotation = self.constants.ROTATION; @@ -3360,7 +3361,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); BI.extend(config.xAxis[1], { @@ -3369,15 +3370,15 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { enableMinorTick: this.config.enableMinorTick }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle(){ + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -3387,23 +3388,23 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon(){ - BI.each(self.config.cordon, function(idx, cor){ - if(idx === 0 && self.xAxis.length > 0){ + function formatCordon () { + BI.each(self.config.cordon, function (idx, cor) { + if(idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.leftYAxisNumberLevel); - self.xAxis[0].plotLines = BI.map(cor, function(i, t){ + self.xAxis[0].plotLines = BI.map(cor, function (i, t) { return BI.extend(t, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); } - if(idx > 0 && self.yAxis.length >= idx){ + if(idx > 0 && self.yAxis.length >= idx) { var magnify = 1; switch (idx - 1) { case self.constants.LEFT_AXIS: @@ -3416,22 +3417,22 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { magnify = self.calcMagnify(self.config.rightYAxisSecondNumberLevel); break; } - self.yAxis[idx - 1].plotLines = BI.map(cor, function(i, t){ + self.yAxis[idx - 1].plotLines = BI.map(cor, function (i, t) { return BI.extend(t, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartLineStyle(){ + function formatChartLineStyle () { switch (self.config.chartLineType) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.curve = false; @@ -3449,29 +3450,29 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { } } - function formatNumberLevelInYaxis(type, position, formatter){ + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { var max = null; BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); - if((BI.isNull(max) || BI.parseFloat(da.y) > BI.parseFloat(max))){ + if((BI.isNull(max) || BI.parseFloat(da.y) > BI.parseFloat(max))) { max = da.y; } } }); - if(position === item.yAxis){ + if(position === item.yAxis) { item.tooltip = BI.deepClone(config.plotOptions.tooltip); item.tooltip.formatter.valueFormat = formatter; } - if(BI.isNotNull(max)){ + if(BI.isNotNull(max)) { self.maxes.push(max); } }); } - function getXYAxisUnit(numberLevelType, position){ + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -3487,19 +3488,19 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { unit = BI.i18nText("BI-Yi"); break; } - if(position === self.constants.X_AXIS){ - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + if(position === self.constants.X_AXIS) { + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } - if(position === self.constants.LEFT_AXIS){ - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + if(position === self.constants.LEFT_AXIS) { + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } - if(position === self.constants.RIGHT_AXIS){ - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + if(position === self.constants.RIGHT_AXIS) { + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } - function _calculateValueNiceDomain(minValue, maxValue){ + function _calculateValueNiceDomain (minValue, maxValue) { minValue = Math.min(0, minValue); @@ -3508,7 +3509,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { return _linearNiceDomain(minValue, maxValue, tickInterval); } - function _linearTickInterval(minValue, maxValue, m){ + function _linearTickInterval (minValue, maxValue, m) { m = m || 5; var span = maxValue - minValue; @@ -3520,7 +3521,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { return step; } - function _linearNiceDomain(minValue, maxValue, tickInterval){ + function _linearNiceDomain (minValue, maxValue, tickInterval) { minValue = VanUtils.accMul(Math.floor(minValue / tickInterval), tickInterval); @@ -3530,12 +3531,12 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { } }, - _formatItems: function(items){ + _formatItems: function (items) { var self = this; this.maxes = []; - BI.each(items, function(idx, item){ - BI.each(item, function(id, it){ - if(idx > 0){ + BI.each(items, function (idx, item) { + BI.each(item, function (id, it) { + if(idx > 0) { BI.extend(it, {reversed: true, xAxis: 1}); }else{ BI.extend(it, {reversed: false, xAxis: 0}); @@ -3562,7 +3563,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { leftYAxisReversed: options.leftYAxisReversed || false, rightYAxisReversed: options.rightYAxisReversed || false, leftYAxisNumberLevel: options.leftYAxisNumberLevel || c.NORMAL, - rightYAxisNumberLevel: options.rightYAxisNumberLevel || c.NORMAL, + rightYAxisNumberLevel: options.rightYAxisNumberLevel || c.NORMAL, xAxisUnit: options.xAxisUnit || "", leftYAxisUnit: options.leftYAxisUnit || "", rightYAxisUnit: options.rightYAxisUnit || "", @@ -3587,16 +3588,16 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { this.yAxis = []; var types = []; - BI.each(items, function(idx, axisItems){ + BI.each(items, function (idx, axisItems) { var type = []; - BI.each(axisItems, function(id, item){ + BI.each(axisItems, function (id, item) { type.push(BICst.WIDGET.AXIS); }); types.push(type); }); - BI.each(types, function(idx, type){ - if(BI.isEmptyArray(type)){ + BI.each(types, function (idx, type) { + if(BI.isEmptyArray(type)) { return; } var newYAxis = { @@ -3621,12 +3622,12 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { this.combineChart.resize(); }, - magnify: function(){ + magnify: function () { this.combineChart.magnify(); } }); BI.CompareAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.compare_axis_chart', BI.CompareAxisChart);/** +BI.shortcut("bi.compare_axis_chart", BI.CompareAxisChart);/** * 图表控件 * @class BI.CompareBarChart * @extends BI.Widget @@ -3636,7 +3637,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.CompareBarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-compare-bar-chart" - }) + }); }, _init: function () { @@ -3673,7 +3674,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.CompareBarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -3695,7 +3696,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { lineWidth: this.config.lineWidth, enableTick: this.config.enableTick, labelRotation: this.config.textDirection, - maxWidth: '40%' + maxWidth: "40%" }); self.formatNumberLevelInXaxis(items, this.config.leftYAxisNumberLevel); @@ -3711,17 +3712,17 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { }); config.chartType = "bar"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.xAxis[0].formatter, this.config.chartFont); config.plotOptions.tooltip.formatter.valueFormat = config.xAxis[0].formatter; - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -3731,7 +3732,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.leftYAxisNumberLevel); @@ -3740,9 +3741,9 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -3765,17 +3766,17 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -3792,13 +3793,13 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -3818,7 +3819,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { } }); it.stack = i; - }) + }); }); BI.each(items, function (idx, item) { result = BI.concat(result, item); @@ -3878,7 +3879,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { } }); BI.CompareBarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.compare_bar_chart', BI.CompareBarChart);/** +BI.shortcut("bi.compare_bar_chart", BI.CompareBarChart);/** * 图表控件 * @class BI.DashboardChart * @extends BI.Widget @@ -3889,18 +3890,18 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.DashboardChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-dashboard-chart" - }) + }); }, _init: function () { BI.DashboardChart.superclass._init.apply(this, arguments); var self = this, o = this.options; this.gaugeAxis = [{ - "minorTickColor": "rgb(226,226,226)", - "tickColor": "rgb(186,186,186)", + minorTickColor: "rgb(226,226,226)", + tickColor: "rgb(186,186,186)", labelStyle: this.constants.FONT_STYLE, - "step": 0, - "showLabel": true + step: 0, + showLabel: true }]; this.combineChart = BI.createWidget({ type: "bi.combine_chart", @@ -3912,7 +3913,7 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.DashboardChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -3928,13 +3929,13 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { if (isDashboard && !isMultiPointers) { config.plotOptions.seriesLabel.enabled = false; if(BI.isNull(items[0].data[0].z)) { - config.plotOptions.tooltip.formatter.identifier = "${SERIES}${X}${Y}${SIZE}${VALUE}" + config.plotOptions.tooltip.formatter.identifier = "${SERIES}${X}${Y}${SIZE}${VALUE}"; } } config.gaugeAxis[0].labelStyle = this.config.chartFont; return [items, config]; - function formatChartDashboardStyle() { + function formatChartDashboardStyle () { var bands = getBandsStyles(self.config.bandsStyles, self.config.autoCustomStyle); var percentageLabel = BI.extend(config.plotOptions.percentageLabel, { enabled: self.config.showPercentage === BICst.PERCENTAGE.SHOW @@ -3946,29 +3947,29 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { formatter: function () { var value = this.value; if (self.config.dashboardNumberLevel === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT && self.config.numSeparators) { - value = BI.contentFormat(this.value, "#,##0%;-#,##0%") + value = BI.contentFormat(this.value, "#,##0%;-#,##0%"); } else if (self.config.dashboardNumberLevel === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT && !self.config.numSeparators) { value = BI.contentFormat(this.value, "#0.00%"); } else if (!(self.config.dashboardNumberLevel === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT) && self.config.numSeparators) { - value = BI.contentFormat(this.value, "#,###.##;-#,###.##") + value = BI.contentFormat(this.value, "#,###.##;-#,###.##"); } else { value = BI.contentFormat(this.value, "#.##;-#.##"); } - var label = '
    ' + this.seriesName + '
    ' + '
    ' + value + - getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS) + '
    '; + var label = "
    " + this.seriesName + "
    " + "
    " + value + + getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS) + "
    "; if (isDashboard && items[0].data.length > 1) { if (isMultiPointers) { - return '
    ' + this.seriesName + ':' + value + - getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS) + '
    '; + return "
    " + this.seriesName + ":" + value + + getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS) + "
    "; } - return label + return label; } else if (isDashboard && BI.isNull(items[0].data[0].z)) { - return label + return label; } - return '
    ' + this.category + '
    ' + label; + return "
    " + this.category + "
    " + label; }, style: self.config.chartFont, useHtml: true @@ -4012,9 +4013,9 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { config.gaugeAxis[0].formatter = function () { var scaleValue = this; if (self.config.numSeparators) { - scaleValue = BI.contentFormat(scaleValue, '#,##0%;-#,##0%') + scaleValue = BI.contentFormat(scaleValue, "#,##0%;-#,##0%"); } else { - scaleValue = BI.contentFormat(scaleValue, '#0.00%') + scaleValue = BI.contentFormat(scaleValue, "#0.00%"); } return scaleValue + getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS); }; @@ -4022,14 +4023,14 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { config.gaugeAxis[0].formatter = function () { var value = this; if (self.config.numSeparators) { - value = BI.contentFormat(value, "#,###;-#,###") + value = BI.contentFormat(value, "#,###;-#,###"); } return value + getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS); }; } } - function setPlotOptions(style, bands, slotValueLAbel, percentageLabel, thermometerLayout, layout) { + function setPlotOptions (style, bands, slotValueLAbel, percentageLabel, thermometerLayout, layout) { config.style = style; config.plotOptions.bands = bands; config.plotOptions.valueLabel = slotValueLAbel; @@ -4038,44 +4039,44 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { config.plotOptions.layout = layout; } - function changeMaxMinScale() { + function changeMaxMinScale () { self.gaugeAxis[0].min = BI.parseFloat(self.config.minScale) || null; self.gaugeAxis[0].max = BI.parseFloat(self.config.maxScale) || null; } - function formatNumberLevelInYaxis(type, position) { + function formatNumberLevelInYaxis (type, position) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = function () { - return BI.contentFormat(this, '#.##;-#.##') + getXYAxisUnit(type, position) + return BI.contentFormat(this, "#.##;-#.##") + getXYAxisUnit(type, position); }; if (self.config.numSeparators) { config.plotOptions.tooltip.formatter.valueFormat = function () { - return BI.contentFormat(arguments[0], '#,###.##;-#,###.##') + return BI.contentFormat(arguments[0], "#,###.##;-#,###.##"); }; } if (type === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT) { config.plotOptions.tooltip.formatter.valueFormat = function () { - return BI.contentFormat(arguments[0], '#0.00%') + return BI.contentFormat(arguments[0], "#0.00%"); }; if (self.config.numSeparators) { config.plotOptions.tooltip.formatter.valueFormat = function () { - return BI.contentFormat(arguments[0], '#,##0%;-#,##0%') + return BI.contentFormat(arguments[0], "#,##0%;-#,##0%"); }; } } } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -4092,18 +4093,18 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.DASHBOARD_AXIS) { - self.config.dashboardUnit !== "" && (unit = unit + self.config.dashboardUnit) + self.config.dashboardUnit !== "" && (unit = unit + self.config.dashboardUnit); } return unit; } - function getBandsStyles(styles, change) { + function getBandsStyles (styles, change) { var min = 0, bands = [], color = null, max = null, conditionMax = null; BI.each(items, function (idx, item) { var data = item.data[0]; if ((BI.isNull(max) || data.y > max)) { - max = data.y + max = data.y; } }); @@ -4113,52 +4114,52 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { break; case BICst.SCALE_SETTING.CUSTOM: if (styles.length === 0) { - return bands - } else { - var maxScale = _calculateValueNiceDomain(0, max)[1]; + return bands; + } + var maxScale = _calculateValueNiceDomain(0, max)[1]; - BI.each(styles, function (idx, style) { - if(BI.parseFloat(style.range.min) > BI.parseFloat(style.range.max)) { - return bands.push({ - color: color, - from: conditionMax, - to: maxScale - }); - } - bands.push({ - color: style.color, - from: style.range.min, - to: style.range.max + BI.each(styles, function (idx, style) { + if(BI.parseFloat(style.range.min) > BI.parseFloat(style.range.max)) { + return bands.push({ + color: color, + from: conditionMax, + to: maxScale }); - color = style.color; - conditionMax = style.range.max - }); - min = BI.parseInt(styles[0].range.min); + } bands.push({ - color: "#808080", - from: 0, - to: min + color: style.color, + from: style.range.min, + to: style.range.max }); + color = style.color; + conditionMax = style.range.max; + }); + min = BI.parseInt(styles[0].range.min); + bands.push({ + color: "#808080", + from: 0, + to: min + }); - bands.push({ - color: color, - from: conditionMax, - to: maxScale - }); + bands.push({ + color: color, + from: conditionMax, + to: maxScale + }); - return bands; - } + return bands; + } } - function _calculateValueNiceDomain(minValue, maxValue) { + function _calculateValueNiceDomain (minValue, maxValue) { minValue = Math.min(0, minValue); var tickInterval = _linearTickInterval(minValue, maxValue); return _linearNiceDomain(minValue, maxValue, tickInterval); } - function _linearTickInterval(minValue, maxValue, m) { + function _linearTickInterval (minValue, maxValue, m) { m = m || 5; var span = maxValue - minValue; var step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)); @@ -4168,7 +4169,7 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { return step; } - function _linearNiceDomain(minValue, maxValue, tickInterval) { + function _linearNiceDomain (minValue, maxValue, tickInterval) { minValue = VanUtils.accMul(Math.floor(minValue / tickInterval), tickInterval); maxValue = VanUtils.accMul(Math.ceil(maxValue / tickInterval), tickInterval); @@ -4183,14 +4184,14 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { var c = this.constants; if (this.config.chartDashboardType === c.NORMAL || this.config.chartDashboardType === c.HALF_DASHBOARD) { var result = []; - if (this.config.numberOfPointer === c.ONE_POINTER && items[0].length === 1) {//单个系列 + if (this.config.numberOfPointer === c.ONE_POINTER && items[0].length === 1) {// 单个系列 BI.each(items[0][0].data, function (idx, da) { result.push({ data: [BI.extend({}, da, { x: items[0][0].name })], name: da.x - }) + }); }); return [result]; } else if(this.config.numberOfPointer === c.ONE_POINTER && items[0].length > 1) { @@ -4200,17 +4201,17 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { x: item.name })], name: BI.UUID() - }) + }); }); - return [result] + return [result]; } - if (this.config.numberOfPointer === c.MULTI_POINTER && items[0].length > 1) {//多个系列 + if (this.config.numberOfPointer === c.MULTI_POINTER && items[0].length > 1) {// 多个系列 BI.each(items, function (idx, item) { BI.each(item, function (id, it) { var data = it.data[0]; data.x = it.name; result.push(data); - }) + }); }); return [[{ data: result, @@ -4228,8 +4229,8 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { y: da.y })], name: da.x - }) - }) + }); + }); }); return [others]; } @@ -4275,7 +4276,7 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { } }); BI.DashboardChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.dashboard_chart', BI.DashboardChart);/** +BI.shortcut("bi.dashboard_chart", BI.DashboardChart);/** * 图表控件 * @class BI.DonutChart * @extends BI.Widget @@ -4285,7 +4286,7 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.DonutChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-donut-chart" - }) + }); }, _init: function () { @@ -4301,11 +4302,11 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.DonutChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, - _formatConfig: function(config, items){ + _formatConfig: function (config, items) { var self = this; delete config.zoom; config.colors = this.config.chartColor; @@ -4326,13 +4327,13 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { da.y = self.formatXYDataWithMagnify(da.y, 1); - }) + }); }); config.legend.style = this.config.chartFont; return [items, config]; - function formatChartStyle(){ + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -4357,9 +4358,9 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { this.options.items = items; var types = []; - BI.each(items, function(idx, axisItems){ + BI.each(items, function (idx, axisItems) { var type = []; - BI.each(axisItems, function(id, item){ + BI.each(axisItems, function (id, item) { type.push(BICst.WIDGET.DONUT); }); types.push(type); @@ -4372,12 +4373,12 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { this.combineChart.resize(); }, - magnify: function(){ + magnify: function () { this.combineChart.magnify(); } }); BI.DonutChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.donut_chart', BI.DonutChart);/** +BI.shortcut("bi.donut_chart", BI.DonutChart);/** * 图表控件 * @class BI.FallAxisChart * @extends BI.Widget @@ -4387,7 +4388,7 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.FallAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-fall-axis-chart" - }) + }); }, _init: function () { @@ -4422,11 +4423,11 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.FallAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, - _formatConfig: function(config, items){ + _formatConfig: function (config, items) { var self = this, o = this.options; var yTitle = getXYAxisUnit(this.config.leftYAxisNumberLevel, this.constants.LEFT_AXIS); config.colors = this.config.chartColor; @@ -4435,11 +4436,11 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { config.legend.enabled = false; config.plotOptions.dataLabels.enabled = this.config.showDataLabel; config.dataSheet.enabled = this.config.showDataTable; - if(config.dataSheet.enabled === true){ + if(config.dataSheet.enabled === true) { config.xAxis[0].showLabel = false; } config.zoom.zoomTool.enabled = this.config.showZoom; - if(this.config.showZoom === true){ + if(this.config.showZoom === true) { delete config.dataSheet; delete config.zoom.zoomType; } @@ -4465,20 +4466,20 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { enableMinorTick: this.config.enableMinorTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); - //为了给数据标签加个%,还要遍历所有的系列,唉 - if(config.plotOptions.dataLabels.enabled === true){ - BI.each(items, function(idx, item){ - if(idx === 0){ + // 为了给数据标签加个%,还要遍历所有的系列,唉 + if(config.plotOptions.dataLabels.enabled === true) { + BI.each(items, function (idx, item) { + if(idx === 0) { item.dataLabels = {}; return; } item.dataLabels = { - "style": self.config.chartFont, - "align": "outside", - "autoAdjust": true, + style: self.config.chartFont, + align: "outside", + autoAdjust: true, enabled: true, formatter: { identifier: "${VALUE}", @@ -4488,12 +4489,12 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { }); } - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle(){ + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -4503,23 +4504,23 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon(){ - BI.each(self.config.cordon, function(idx, cor){ - if(idx === 0 && self.xAxis.length > 0){ + function formatCordon () { + BI.each(self.config.cordon, function (idx, cor) { + if(idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); - self.xAxis[0].plotLines = BI.map(cor, function(i, t){ + self.xAxis[0].plotLines = BI.map(cor, function (i, t) { return BI.extend(t, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); } - if(idx > 0 && self.yAxis.length >= idx){ + if(idx > 0 && self.yAxis.length >= idx) { var magnify = 1; switch (idx - 1) { case self.constants.LEFT_AXIS: @@ -4532,34 +4533,34 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { magnify = self.calcMagnify(self.config.rightYAxisSecondNumberLevel); break; } - self.yAxis[idx - 1].plotLines = BI.map(cor, function(i, t){ + self.yAxis[idx - 1].plotLines = BI.map(cor, function (i, t) { return BI.extend(t, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatNumberLevelInYaxis(type, position, formatter){ + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = formatter; } - function getXYAxisUnit(numberLevelType, position){ + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -4575,33 +4576,33 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { unit = BI.i18nText("BI-Yi"); break; } - if(position === self.constants.X_AXIS){ - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + if(position === self.constants.X_AXIS) { + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } - if(position === self.constants.LEFT_AXIS){ - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + if(position === self.constants.LEFT_AXIS) { + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } - if(position === self.constants.RIGHT_AXIS){ - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + if(position === self.constants.RIGHT_AXIS) { + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } }, - _formatItems: function(items){ + _formatItems: function (items) { var o = this.options; - if(BI.isEmptyArray(items)){ + if(BI.isEmptyArray(items)) { return []; } items = items[0]; var tables = [], sum = 0; var colors = this.config.chartColor || []; - if(BI.isEmptyArray(colors)){ + if(BI.isEmptyArray(colors)) { colors = ["rgb(152, 118, 170)", "rgb(0, 157, 227)"]; } - BI.each(items, function(idx, item){ - BI.each(item.data, function(i, t){ - if(t.y < 0){ + BI.each(items, function (idx, item) { + BI.each(item.data, function (i, t) { + if(t.y < 0) { tables.push([t.x, t.y, sum + t.y, t]); }else{ tables.push([t.x, t.y, sum, t]); @@ -4610,14 +4611,14 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { }); }); - return [BI.map(BI.makeArray(2, null), function(idx, item){ + return [BI.map(BI.makeArray(2, null), function (idx, item) { return { - "data": BI.map(tables, function(id, cell){ + data: BI.map(tables, function (id, cell) { var axis = BI.extend({}, cell[3], { x: cell[0], y: Math.abs(cell[2 - idx]) }); - if(idx === 1){ + if(idx === 1) { axis.color = cell[2 - idx] < 0 ? colors[1] : colors[0]; }else{ axis.color = "rgba(0,0,0,0)"; @@ -4627,7 +4628,7 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { axis.mouseOverColor = "rgba(0,0,0,0)"; axis.tooltip = { enable: false - } + }; } return axis; }), @@ -4666,9 +4667,9 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { }; this.options.items = items; var types = []; - BI.each(items, function(idx, axisItems){ + BI.each(items, function (idx, axisItems) { var type = []; - BI.each(axisItems, function(id, item){ + BI.each(axisItems, function (id, item) { type.push(BICst.WIDGET.AXIS); }); types.push(type); @@ -4681,12 +4682,12 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { this.combineChart.resize(); }, - magnify: function(){ + magnify: function () { this.combineChart.magnify(); } }); BI.FallAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.fall_axis_chart', BI.FallAxisChart);/** +BI.shortcut("bi.fall_axis_chart", BI.FallAxisChart);/** * 图表控件 * @class BI.ForceBubbleChart * @extends BI.Widget @@ -4696,7 +4697,7 @@ BI.ForceBubbleChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.ForceBubbleChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-force-bubble-chart" - }) + }); }, _init: function () { @@ -4712,13 +4713,13 @@ BI.ForceBubbleChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.ForceBubbleChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, _formatConfig: function (config, items) { var self = this, o = this.options; - config.chartType = 'forceBubble'; + config.chartType = "forceBubble"; config.colors = this.config.chartColor; this.formatChartLegend(config, this.config.chartLegend); @@ -4734,7 +4735,7 @@ BI.ForceBubbleChart = BI.inherit(BI.AbstractChart, { BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { da.y = self.formatXYDataWithMagnify(da.y, 1); - }) + }); }); config.legend.style = this.config.chartFont; return [items, config]; @@ -4772,7 +4773,7 @@ BI.ForceBubbleChart = BI.inherit(BI.AbstractChart, { } }); BI.ForceBubbleChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.force_bubble_chart', BI.ForceBubbleChart);/** +BI.shortcut("bi.force_bubble_chart", BI.ForceBubbleChart);/** * 图表控件 * @class BI.GISMapChart * @extends BI.Widget @@ -4782,7 +4783,7 @@ BI.GISMapChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.GISMapChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-gis-map-chart" - }) + }); }, _init: function () { @@ -4798,7 +4799,7 @@ BI.GISMapChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.GISMapChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -4810,29 +4811,29 @@ BI.GISMapChart = BI.inherit(BI.AbstractChart, { config.plotOptions.dataLabels.useHtml = true; config.plotOptions.dataLabels.style = this.config.chartFont; config.plotOptions.dataLabels.formatter = function () { - var name = (BI.isArray(this.name) ? '' : this.name + ',') + BI.contentFormat(this.value, '#.##;-#.##') ; + var name = (BI.isArray(this.name) ? "" : this.name + ",") + BI.contentFormat(this.value, "#.##;-#.##"); var style = "padding: 5px; background-color: rgba(0,0,0,0.4980392156862745);border-color: rgb(0,0,0); border-radius:2px; border-width:0px;"; - var a = '
    ' + name + '
    '; + var a = "
    " + name + "
    "; return a; }; config.plotOptions.tooltip.shared = true; config.plotOptions.tooltip.formatter = function () { - var tip = BI.isArray(this.name) ? '' : this.name; + var tip = BI.isArray(this.name) ? "" : this.name; BI.each(this.points, function (idx, point) { - tip += ('
    ' + point.seriesName + ':' + BI.contentFormat((point.size || point.y), '#.##;-#.##') + '
    '); + tip += ("
    " + point.seriesName + ":" + BI.contentFormat((point.size || point.y), "#.##;-#.##") + "
    "); }); return tip; }; config.geo = { - "tileLayer": "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}", - "attribution": "
    © 2016 AutoNavi" + tileLayer: "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}", + attribution: "© 2016 AutoNavi" }; if (this.config.showBackgroundLayer === true && BI.isNotNull(this.config.backgroundLayerInfo)) { config.geo = {}; if (this.config.backgroundLayerInfo.type === BICst.WMS_SERVER) { config.geo.tileLayer = false; config.geo.wmsUrl = this.config.backgroundLayerInfo.url; - config.geo.wmsLayer = this.config.backgroundLayerInfo.wmsLayer + config.geo.wmsLayer = this.config.backgroundLayerInfo.wmsLayer; } else { config.geo.tileLayer = this.config.backgroundLayerInfo.url; } @@ -4931,7 +4932,7 @@ BI.GISMapChart = BI.inherit(BI.AbstractChart, { } }); BI.GISMapChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.gis_map_chart', BI.GISMapChart);/** +BI.shortcut("bi.gis_map_chart", BI.GISMapChart);/** * 图表控件 * @class BI.LineChart * @extends BI.Widget @@ -4941,7 +4942,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.LineChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-line-chart" - }) + }); }, _init: function () { @@ -4967,7 +4968,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.LineChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -5033,20 +5034,20 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: self.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "line"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -5056,7 +5057,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -5065,9 +5066,9 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -5090,17 +5091,17 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartLineStyle() { + function formatChartLineStyle () { switch (self.config.chartLineType) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.curve = false; @@ -5118,7 +5119,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { } } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -5135,13 +5136,13 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -5227,7 +5228,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { } }); BI.LineChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.line_chart', BI.LineChart);/** +BI.shortcut("bi.line_chart", BI.LineChart);/** * 图表控件 * @class BI.MapChart * @extends BI.Widget @@ -5237,7 +5238,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.MapChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-map-chart" - }) + }); }, _init: function () { @@ -5253,7 +5254,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.MapChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -5275,7 +5276,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { var tip = this.name; var point = this.points[0]; var index = BI.isNull(point.size) ? 0 : 1; - tip += ('
    ' + point.seriesName + ':' + BI.contentFormat(point.size || point.y, formatterArray[index]) + '
    '); + tip += ("
    " + point.seriesName + ":" + BI.contentFormat(point.size || point.y, formatterArray[index]) + "
    "); return tip; }; config.plotOptions.dataLabels.formatter.valueFormat = function () { @@ -5293,7 +5294,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { if (this.config.backgroundLayerInfo.type === BICst.WMS_SERVER) { config.geo.tileLayer = false; config.geo.wmsUrl = this.config.backgroundLayerInfo.url; - config.geo.wmsLayer = this.config.backgroundLayerInfo.wmsLayer + config.geo.wmsLayer = this.config.backgroundLayerInfo.wmsLayer; } else { config.geo.tileLayer = this.config.backgroundLayerInfo.url; } @@ -5318,12 +5319,12 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { items.push({ type: "areaMap", data: [] - }) + }); } return [items, config]; - function formatRangeLegend() { + function formatRangeLegend () { config.rangeLegend.enabled = true; switch (self.config.chartLegend) { case BICst.CHART_LEGENDS.BOTTOM: @@ -5346,36 +5347,36 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { var settings = items[0].settings; var legendFormat = formatToolTipAndDataLabel(settings.format || c.NORMAL, settings.num_level || c.NORMAL, settings.unit || "", settings.numSeparators || c.NUM_SEPARATORS); - to = BI.contentFormat(to, legendFormat) + to = BI.contentFormat(to, legendFormat); } - return to + return to; }; } - function formatToolTipAndDataLabel(format, numberLevel, unit, numSeparators) { - var formatter = '#.##'; + function formatToolTipAndDataLabel (format, numberLevel, unit, numSeparators) { + var formatter = "#.##"; switch (format) { case self.constants.NORMAL: - formatter = '#.##'; - if (numSeparators) formatter = '#,###.##'; + formatter = "#.##"; + if (numSeparators) formatter = "#,###.##"; break; case self.constants.ZERO2POINT: - formatter = '#0'; - if (numSeparators) formatter = '#,###'; + formatter = "#0"; + if (numSeparators) formatter = "#,###"; break; case self.constants.ONE2POINT: - formatter = '#0.0'; - if (numSeparators) formatter = '#,###.0'; + formatter = "#0.0"; + if (numSeparators) formatter = "#,###.0"; break; case self.constants.TWO2POINT: - formatter = '#0.00'; - if (numSeparators) formatter = '#,###.00'; + formatter = "#0.00"; + if (numSeparators) formatter = "#,###.00"; break; } switch (numberLevel) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: - formatter += ''; + formatter += ""; break; case BICst.TARGET_STYLE.NUM_LEVEL.TEN_THOUSAND: formatter += BI.i18nText("BI-Wan"); @@ -5387,23 +5388,23 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { formatter += BI.i18nText("BI-Yi"); break; case BICst.TARGET_STYLE.NUM_LEVEL.PERCENT: - formatter += '%'; + formatter += "%"; break; } return formatter + unit; } - function getRangeStyle(styles, change, defaultColor) { + function getRangeStyle (styles, change, defaultColor) { var range = [], color = null, defaultStyle = {}; var conditionMax = null, conditionMin = null, min = null; BI.each(items, function (idx, item) { BI.each(item.data, function (id, it) { if (BI.isNull(min) || BI.parseFloat(min) > BI.parseFloat(it.y)) { - min = it.y + min = it.y; } - }) + }); }); switch (change) { @@ -5425,11 +5426,11 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { range.push({ color: style.color || "rgba(255,255,255,0)", from: style.range.min, - to: to, + to: to }); } color = style.color; - conditionMax = style.range.max + conditionMax = style.range.max; }); conditionMin = BI.parseFloat(styles[0].range.min); @@ -5449,21 +5450,21 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { }); } return range; - } else { - defaultStyle.color = defaultColor; - return defaultStyle; } + defaultStyle.color = defaultColor; + return defaultStyle; + } } - function _calculateValueNiceDomain(minValue, maxValue) { + function _calculateValueNiceDomain (minValue, maxValue) { minValue = Math.min(0, minValue); var tickInterval = _linearTickInterval(minValue, maxValue); return _linearNiceDomain(minValue, maxValue, tickInterval); } - function _linearTickInterval(minValue, maxValue, m) { + function _linearTickInterval (minValue, maxValue, m) { m = m || 5; var span = maxValue - minValue; var step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)); @@ -5474,7 +5475,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { return step; } - function _linearNiceDomain(minValue, maxValue, tickInterval) { + function _linearNiceDomain (minValue, maxValue, tickInterval) { minValue = VanUtils.accMul(Math.floor(minValue / tickInterval), tickInterval); maxValue = VanUtils.accMul(Math.ceil(maxValue / tickInterval), tickInterval); @@ -5542,7 +5543,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { self._formatDrillItems(da.drilldown); } }); - }) + }); }); return items; }, @@ -5587,7 +5588,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { }); BI.MapChart.EVENT_CHANGE = "EVENT_CHANGE"; BI.MapChart.EVENT_CLICK_DTOOL = "EVENT_CLICK_DTOOL"; -BI.shortcut('bi.map_chart', BI.MapChart);/** +BI.shortcut("bi.map_chart", BI.MapChart);/** * 图表控件 * @class BI.MultiAxisChart * @extends BI.Widget @@ -5600,7 +5601,7 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.MultiAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-multi-axis-chart" - }) + }); }, _init: function () { @@ -5609,10 +5610,10 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { this.xAxis = [{ type: "category", title: { - style: {"fontFamily": "inherit", "color": "#808080", "fontSize": "12px", "fontWeight": ""} + style: {fontFamily: "inherit", color: "#808080", fontSize: "12px", fontWeight: ""} }, labelStyle: { - "fontFamily": "inherit", "color": "#808080", "fontSize": "12px" + fontFamily: "inherit", color: "#808080", fontSize: "12px" }, position: "bottom", gridLineWidth: 0 @@ -5628,7 +5629,7 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.MultiAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -5709,13 +5710,13 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 if (config.dataSheet) { config.dataSheet.style = this.config.chartFont; } @@ -5750,14 +5751,14 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": { - "fontFamily": "inherit", - "color": "#808080", - "fontSize": "12px", - "fontWeight": "" + style: { + fontFamily: "inherit", + color: "#808080", + fontSize: "12px", + fontWeight: "" }, - "text": t.text, - "align": "top" + text: t.text, + align: "top" } }); }); @@ -5782,19 +5783,19 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": { - "fontFamily": "inherit", - "color": "#808080", - "fontSize": "12px", - "fontWeight": "" + style: { + fontFamily: "inherit", + color: "#808080", + fontSize: "12px", + fontWeight: "" }, - "text": t.text, - "align": "left" + text: t.text, + align: "left" } }); }); } - }) + }); }, getXYAxisUnit: function (numberLevelType, position) { @@ -5816,16 +5817,16 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { break; } if (position === this.constants.X_AXIS) { - this.config.xAxisUnit !== "" && (unit = unit + this.config.xAxisUnit) + this.config.xAxisUnit !== "" && (unit = unit + this.config.xAxisUnit); } if (position === this.constants.LEFT_AXIS) { - this.config.leftYAxisUnit !== "" && (unit = unit + this.config.leftYAxisUnit) + this.config.leftYAxisUnit !== "" && (unit = unit + this.config.leftYAxisUnit); } if (position === this.constants.RIGHT_AXIS) { - this.config.rightYAxisUnit !== "" && (unit = unit + this.config.rightYAxisUnit) + this.config.rightYAxisUnit !== "" && (unit = unit + this.config.rightYAxisUnit); } if (position === this.constants.RIGHT_AXIS_SECOND) { - this.config.rightYAxisSecondUnit !== "" && (unit = unit + this.config.rightYAxisSecondUnit) + this.config.rightYAxisSecondUnit !== "" && (unit = unit + this.config.rightYAxisSecondUnit); } return unit === "" ? unit : "(" + unit + ")"; }, @@ -5883,10 +5884,10 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { var newYAxis = { type: "value", title: { - style: {"fontFamily": "inherit", "color": "#808080", "fontSize": "12px", "fontWeight": ""} + style: {fontFamily: "inherit", color: "#808080", fontSize: "12px", fontWeight: ""} }, labelStyle: { - "fontFamily": "inherit", "color": "#808080", "fontSize": "12px" + fontFamily: "inherit", color: "#808080", fontSize: "12px" }, position: idx > 0 ? "right" : "left", lineWidth: 1, @@ -5908,7 +5909,7 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { } }); BI.MultiAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_axis_chart', BI.MultiAxisChart);/** +BI.shortcut("bi.multi_axis_chart", BI.MultiAxisChart);/** * 图表控件 * @class BI.MultiAxisChart * @extends BI.Widget @@ -5921,7 +5922,7 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.MultiAxisCombineChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-multi-axis-combine-chart" - }) + }); }, _init: function () { @@ -5930,10 +5931,10 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { this.xAxis = [{ type: "category", title: { - style: {"fontFamily": "inherit", "color": "#808080", "fontSize": "12px", "fontWeight": ""} + style: {fontFamily: "inherit", color: "#808080", fontSize: "12px", fontWeight: ""} }, labelStyle: { - "fontFamily": "inherit", "color": "#808080", "fontSize": "12px" + fontFamily: "inherit", color: "#808080", fontSize: "12px" }, position: "bottom", gridLineWidth: 0 @@ -5949,7 +5950,7 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.MultiAxisCombineChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -6033,13 +6034,13 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 if (config.dataSheet) { config.dataSheet.style = this.config.chartFont; } @@ -6074,14 +6075,14 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": { - "fontFamily": "inherit", - "color": "#808080", - "fontSize": "12px", - "fontWeight": "" + style: { + fontFamily: "inherit", + color: "#808080", + fontSize: "12px", + fontWeight: "" }, - "text": t.text, - "align": "top" + text: t.text, + align: "top" } }); }); @@ -6106,19 +6107,19 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": { - "fontFamily": "inherit", - "color": "#808080", - "fontSize": "12px", - "fontWeight": "" + style: { + fontFamily: "inherit", + color: "#808080", + fontSize: "12px", + fontWeight: "" }, - "text": t.text, - "align": "left" + text: t.text, + align: "left" } }); }); } - }) + }); }, getXYAxisUnit: function (numberLevelType, position) { @@ -6140,16 +6141,16 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { break; } if (position === this.constants.X_AXIS) { - this.config.xAxisUnit !== "" && (unit = unit + this.config.xAxisUnit) + this.config.xAxisUnit !== "" && (unit = unit + this.config.xAxisUnit); } if (position === this.constants.LEFT_AXIS) { - this.config.leftYAxisUnit !== "" && (unit = unit + this.config.leftYAxisUnit) + this.config.leftYAxisUnit !== "" && (unit = unit + this.config.leftYAxisUnit); } if (position === this.constants.RIGHT_AXIS) { - this.config.rightYAxisUnit !== "" && (unit = unit + this.config.rightYAxisUnit) + this.config.rightYAxisUnit !== "" && (unit = unit + this.config.rightYAxisUnit); } if (position === this.constants.RIGHT_AXIS_SECOND) { - this.config.rightYAxisSecondUnit !== "" && (unit = unit + this.config.rightYAxisSecondUnit) + this.config.rightYAxisSecondUnit !== "" && (unit = unit + this.config.rightYAxisSecondUnit); } return unit === "" ? unit : "(" + unit + ")"; }, @@ -6206,10 +6207,10 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { var newYAxis = { type: "value", title: { - style: {"fontFamily": "inherit", "color": "#808080", "fontSize": "12px", "fontWeight": ""} + style: {fontFamily: "inherit", color: "#808080", fontSize: "12px", fontWeight: ""} }, labelStyle: { - "fontFamily": "inherit", "color": "#808080", "fontSize": "12px" + fontFamily: "inherit", color: "#808080", fontSize: "12px" }, position: idx > 0 ? "right" : "left", lineWidth: 1, @@ -6231,7 +6232,7 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { } }); BI.MultiAxisCombineChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_axis_combine_chart', BI.MultiAxisCombineChart);/** +BI.shortcut("bi.multi_axis_combine_chart", BI.MultiAxisCombineChart);/** * 图表控件 * @class BI.PercentAccumulateAreaChart * @extends BI.Widget @@ -6241,7 +6242,7 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.PercentAccumulateAreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-percent-accumulate-area-chart" - }) + }); }, _init: function () { @@ -6276,7 +6277,7 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.PercentAccumulateAreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -6317,20 +6318,20 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.yAxis[0].formatter, this.config.chartFont, true); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -6340,7 +6341,7 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -6349,9 +6350,9 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -6374,17 +6375,17 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -6401,15 +6402,15 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } unit = unit === "" ? unit : "(" + unit + ")"; - return self.config.showLeftYAxisTitle === true ? self.config.leftYAxisTitle + unit : unit + return self.config.showLeftYAxisTitle === true ? self.config.leftYAxisTitle + unit : unit; } }, @@ -6475,7 +6476,7 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { } }); BI.PercentAccumulateAreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.percent_accumulate_area_chart', BI.PercentAccumulateAreaChart);/** +BI.shortcut("bi.percent_accumulate_area_chart", BI.PercentAccumulateAreaChart);/** * 图表控件 百分比堆积柱状 * @class BI.PercentAccumulateAxisChart * @extends BI.Widget @@ -6485,7 +6486,7 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.PercentAccumulateAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-percent-accumulate-axis-chart" - }) + }); }, _init: function () { @@ -6520,7 +6521,7 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.PercentAccumulateAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -6562,18 +6563,18 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.yAxis[0].formatter, this.config.chartFont, true); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -6583,7 +6584,7 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -6592,9 +6593,9 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -6617,17 +6618,17 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -6644,10 +6645,10 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -6714,7 +6715,7 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { } }); BI.PercentAccumulateAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.percent_accumulate_axis_chart', BI.PercentAccumulateAxisChart);/** +BI.shortcut("bi.percent_accumulate_axis_chart", BI.PercentAccumulateAxisChart);/** * 图表控件 * @class BI.PieChart * @extends BI.Widget @@ -6724,7 +6725,7 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.PieChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-pie-chart" - }) + }); }, _init: function () { @@ -6740,11 +6741,11 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.PieChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, - _formatConfig: function(config, items){ + _formatConfig: function (config, items) { var self = this, o = this.options; delete config.zoom; config.colors = this.config.chartColor; @@ -6766,14 +6767,14 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { da.y = self.formatXYDataWithMagnify(da.y, 1); - }) + }); }); config.legend.style = this.config.chartFont; return [items, config]; - function formatChartStyle(){ + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -6783,8 +6784,8 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { } } - function formatChartPieStyle(){ - switch (self.config.chartPieType){ + function formatChartPieStyle () { + switch (self.config.chartPieType) { case BICst.CHART_SHAPE.EQUAL_ARC_ROSE: config.plotOptions.roseType = "sameArc"; break; @@ -6802,31 +6803,31 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { }, - //目前饼图不会有多个系列,如果有多个就要把它们合并在一起 - _isNeedConvert: function(items){ - var result = BI.find(items, function(idx, item){ + // 目前饼图不会有多个系列,如果有多个就要把它们合并在一起 + _isNeedConvert: function (items) { + var result = BI.find(items, function (idx, item) { return item.length > 1; }); return BI.isNotNull(result); }, - _formatItems: function(items){ - if(this._isNeedConvert(items)){ - //把每个坐标轴所有的多个系列合并成一个系列 - return BI.map(items, function(idx, item){ + _formatItems: function (items) { + if(this._isNeedConvert(items)) { + // 把每个坐标轴所有的多个系列合并成一个系列 + return BI.map(items, function (idx, item) { var seriesItem = []; var obj = {data: [], name: ""}; seriesItem.push(obj); - BI.each(item, function(id, series){ - BI.each(series.data, function(i, da){ + BI.each(item, function (id, series) { + BI.each(series.data, function (i, da) { obj.data.push(BI.extend({}, da, {x: series.name})); }); }); return seriesItem; - }) - }else{ - return items; + }); } + return items; + }, populate: function (items, options) { @@ -6845,9 +6846,9 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { this.options.items = items; var types = []; - BI.each(items, function(idx, axisItems){ + BI.each(items, function (idx, axisItems) { var type = []; - BI.each(axisItems, function(id, item){ + BI.each(axisItems, function (id, item) { type.push(BICst.WIDGET.PIE); }); types.push(type); @@ -6860,12 +6861,12 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { this.combineChart.resize(); }, - magnify: function(){ + magnify: function () { this.combineChart.magnify(); } }); BI.PieChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.pie_chart', BI.PieChart); +BI.shortcut("bi.pie_chart", BI.PieChart); /** * 图表控件 @@ -6877,7 +6878,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.RadarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-radar-chart" - }) + }); }, _init: function () { @@ -6890,7 +6891,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { }, labelStyle: this.constants.FONT_STYLE, formatter: function () { - return this > 0 ? this : (-1) * this + return this > 0 ? this : (-1) * this; }, gridLineWidth: 0, position: "bottom" @@ -6914,7 +6915,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.RadarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -6941,17 +6942,17 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { config.chartType = "radar"; delete config.xAxis; delete config.yAxis; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.radiusAxis[0].formatter, this.config.chartFont); - //全局样式 + // 全局样式 config.legend.style = this.config.chartFont; config.radiusAxis[0].title.style = config.radiusAxis[0].labelStyle = this.config.chartFont; config.angleAxis[0].title.style = config.angleAxis[0].labelStyle = this.config.chartFont; return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -6961,7 +6962,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { } } - function formatChartRadarStyle() { + function formatChartRadarStyle () { switch (self.config.chartRadarType) { case BICst.CHART_SHAPE.POLYGON: config.plotOptions.shape = "polygon"; @@ -6972,19 +6973,19 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { } } - function formatNumberLevelInYaxis(type, position, formatter) { + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = formatter; } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -7001,13 +7002,13 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -7051,7 +7052,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { } }); BI.RadarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.radar_chart', BI.RadarChart);/** +BI.shortcut("bi.radar_chart", BI.RadarChart);/** * 图表控件 * @class BI.RangeAreaChart * @extends BI.Widget @@ -7062,7 +7063,7 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.RangeAreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-range-area-chart" - }) + }); }, _init: function () { @@ -7097,7 +7098,7 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.RangeAreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -7132,21 +7133,21 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; config.plotOptions.tooltip.formatter.identifier = "${CATEGORY}${VALUE}"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.yAxis[0].formatter, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -7156,7 +7157,7 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -7165,9 +7166,9 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -7190,29 +7191,29 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatNumberLevelInYaxis(type, position, formatter) { + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = formatter; } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -7229,10 +7230,10 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -7334,7 +7335,7 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { } }); BI.RangeAreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.range_area_chart', BI.RangeAreaChart);/** +BI.shortcut("bi.range_area_chart", BI.RangeAreaChart);/** * 图表控件 * @class BI.ScatterChart * @extends BI.Widget @@ -7344,7 +7345,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.ScatterChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-scatter-chart" - }) + }); }, _init: function () { @@ -7379,7 +7380,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.ScatterChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -7389,7 +7390,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { delete config.zoom; config.colors = this.config.chartColor; config.style = formatChartStyle(); - config.plotOptions.marker = {"symbol": "circle", "radius": 4.5, "enabled": true}; + config.plotOptions.marker = {symbol: "circle", radius: 4.5, enabled: true}; formatCordon(); this.formatChartLegend(config, this.config.chartLegend); config.plotOptions.dataLabels.enabled = this.config.showDataLabel; @@ -7404,7 +7405,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { config.yAxis[0].title.text = this.config.showLeftYAxisTitle === true ? this.config.leftYAxisTitle + config.yAxis[0].title.text : config.yAxis[0].title.text; config.yAxis[0].gridLineWidth = this.config.showGridLine === true ? 1 : 0; config.yAxis[0].title.rotation = this.constants.ROTATION; - config.yAxis[0].maxWidth = '40%'; + config.yAxis[0].maxWidth = "40%"; config.xAxis[0].formatter = self.formatTickInXYaxis(this.config.xAxisStyle, this.config.xAxisNumberLevel, this.config.rightNumSeparators); formatNumberLevelInXaxis(this.config.xAxisNumberLevel); @@ -7412,32 +7413,32 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { config.xAxis[0].title.text = this.config.showXAxisTitle === true ? this.config.xAxisTitle + config.xAxis[0].title.text : config.xAxis[0].title.text; config.xAxis[0].title.align = "center"; config.xAxis[0].gridLineWidth = this.config.showGridLine === true ? 1 : 0; - config.xAxis[0].maxHeight = '40%'; + config.xAxis[0].maxHeight = "40%"; config.chartType = "scatter"; if (BI.isNotEmptyArray(this.config.tooltip)) { config.plotOptions.tooltip.formatter = function () { var y = self.formatTickInXYaxis(self.config.leftYAxisStyle, self.config.leftYAxisNumberLevel, self.config.numSeparators)(this.y); var x = self.formatTickInXYaxis(self.config.xAxisStyle, self.config.xAxisNumberLevel, self.config.rightNumSeparators)(this.x); - return this.seriesName + '
    (X)' + self.config.tooltip[0] - + ':' + x + '
    (Y)' + self.config.tooltip[1] + ':' + y + '
    ' + return this.seriesName + "
    (X)" + self.config.tooltip[0] + + ":" + x + "
    (Y)" + self.config.tooltip[1] + ":" + y + "
    "; }; } if (config.plotOptions.dataLabels.enabled === true) { BI.each(items, function (idx, item) { item.dataLabels = { - "style": self.config.chartFont, - "align": "outside", - "autoAdjust": true, + style: self.config.chartFont, + align: "outside", + autoAdjust: true, enabled: true, formatter: { identifier: "${X}${Y}", - "XFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + XFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); }, - "YFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + YFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); } } }; @@ -7446,14 +7447,14 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { }); } - //全局样式图表文字 + // 全局样式图表文字 config.legend.style = this.config.chartFont; config.yAxis[0].title.style = config.yAxis[0].labelStyle = this.config.chartFont; config.xAxis[0].title.style = config.xAxis[0].labelStyle = this.config.chartFont; return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -7463,7 +7464,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -7472,9 +7473,9 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -7497,35 +7498,35 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatNumberLevelInXaxis(type) { + function formatNumberLevelInXaxis (type) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { da.x = self.formatXYDataWithMagnify(da.x, magnify); - }) - }) + }); + }); } - function formatNumberLevelInYaxis(type) { + function formatNumberLevelInYaxis (type) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { - da.y = self.formatXYDataWithMagnify(da.y, magnify); - }) + da.y = self.formatXYDataWithMagnify(da.y, magnify); + }); }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -7542,13 +7543,13 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -7599,4 +7600,4 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { } }); BI.ScatterChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.scatter_chart', BI.ScatterChart); \ No newline at end of file +BI.shortcut("bi.scatter_chart", BI.ScatterChart); \ No newline at end of file diff --git a/dist/core.js b/dist/core.js index 3f0fc9ad3..f350b6bbc 100644 --- a/dist/core.js +++ b/dist/core.js @@ -25715,10 +25715,10 @@ Data.Constant = BICst = {}; * 缓冲池 * @type {{Buffer: {}}} */ -; + (function () { var Buffer = {}; - var MODE = false;//设置缓存模式为关闭 + var MODE = false;// 设置缓存模式为关闭 Data.BufferPool = { put: function (name, cache) { @@ -25736,7 +25736,7 @@ Data.Constant = BICst = {}; * 共享池 * @type {{Shared: {}}} */ -; + (function () { var _Shared = {}; Data.SharingPool = { diff --git a/dist/polyfill.js b/dist/polyfill.js index f67d79a6e..0b8245d52 100644 --- a/dist/polyfill.js +++ b/dist/polyfill.js @@ -8,7 +8,7 @@ if (!Array.prototype.indexOf) { // 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'); + throw new TypeError("\"this\" is null or not defined"); } var o = Object(this); @@ -60,8 +60,8 @@ if (!Array.prototype.indexOf) { }; } if (!Array.prototype.lastIndexOf) { - Array.prototype.lastIndexOf = function (searchElement /*, fromIndex*/) { - 'use strict'; + Array.prototype.lastIndexOf = function (searchElement /* , fromIndex*/) { + "use strict"; if (this === void 0 || this === null) { throw new TypeError(); @@ -79,8 +79,7 @@ if (!Array.prototype.lastIndexOf) { n = Number(arguments[1]); if (n != n) { n = 0; - } - else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { + } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } @@ -99,14 +98,14 @@ if (!Array.prototype.lastIndexOf) { * 特殊情况 * Created by wang on 15/6/23. */ -//解决console未定义问题 guy +// 解决console未定义问题 guy window.console = window.console || (function () { - var c = {}; - c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile + var c = {}; + c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function () { }; - return c; - })(); + return c; +})(); /* * 前端缓存 */ @@ -127,29 +126,29 @@ window.localStorage || (window.localStorage = { clear: function () { this.items = {}; } -});if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) { +});if (typeof Set !== "undefined" && Set.toString().match(/native code/)) { } else { Set = function () { - this.set = {} + this.set = {}; }; Set.prototype.has = function (key) { return this.set[key] !== undefined; }; Set.prototype.add = function (key) { - this.set[key] = 1 + this.set[key] = 1; }; Set.prototype.clear = function () { - this.set = {} + this.set = {}; }; -}//修复ie9下sort方法的bug -;!function (window) { +}// 修复ie9下sort方法的bug +!function (window) { var ua = window.navigator.userAgent.toLowerCase(), reg = /msie|applewebkit.+safari/; if (reg.test(ua)) { var _sort = Array.prototype.sort; Array.prototype.sort = function (fn) { - if (!!fn && typeof fn === 'function') { + if (!!fn && typeof fn === "function") { if (this.length < 2) { return this; } @@ -157,8 +156,8 @@ window.localStorage || (window.localStorage = { for (; i < l; i++) { for (j = i + 1; j < l; j++) { t = fn.call(this, this[i], this[j]); - r = (typeof t === 'number' ? t : - !!t ? 1 : 0) > 0; + r = (typeof t === "number" ? t : + t ? 1 : 0) > 0; if (r === true) { tmp = this[i]; this[i] = this[j]; @@ -167,9 +166,9 @@ window.localStorage || (window.localStorage = { } } return this; - } else { - return _sort.call(this); } + return _sort.call(this); + }; } }(window); \ No newline at end of file diff --git a/dist/router.js b/dist/router.js index 4ee73d096..7e90df0a9 100644 --- a/dist/router.js +++ b/dist/router.js @@ -1,10 +1,10 @@ -;(function(){ +(function () { var Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function (name, callback, context) { - if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; + if (!eventsApi(this, "on", name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); @@ -14,7 +14,7 @@ // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function (name, callback, context) { - if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; + if (!eventsApi(this, "once", name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function () { self.off(name, once); @@ -29,7 +29,7 @@ // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function (name, callback, context) { - if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; + if (!this._events || !eventsApi(this, "off", name, [callback, context])) return this; // Remove all callbacks for all events. if (!name && !callback && !context) { @@ -86,7 +86,7 @@ trigger: function (name) { if (!this._events) return this; var args = slice.call(arguments, 1); - if (!eventsApi(this, 'trigger', name, args)) return this; + if (!eventsApi(this, "trigger", name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); @@ -103,15 +103,15 @@ // listening to. listenTo: function (obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); - var id = obj._listenId || (obj._listenId = _.uniqueId('l')); + var id = obj._listenId || (obj._listenId = _.uniqueId("l")); listeningTo[id] = obj; - if (!callback && typeof name === 'object') callback = this; + if (!callback && typeof name === "object") callback = this; obj.on(name, callback, this); return this; }, listenToOnce: function (obj, name, callback) { - if (typeof name === 'object') { + if (typeof name === "object") { for (var event in name) this.listenToOnce(obj, event, name[event]); return this; } @@ -137,7 +137,7 @@ var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; - if (!callback && typeof name === 'object') callback = this; + if (!callback && typeof name === "object") callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; @@ -159,7 +159,7 @@ if (!name) return true; // Handle event maps. - if (typeof name === 'object') { + if (typeof name === "object") { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } @@ -239,16 +239,16 @@ if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; - name = ''; + name = ""; } if (!callback) callback = this[name]; var router = this; BI.history.route(route, function (fragment) { var args = router._extractParameters(route, fragment); if (router.execute(callback, args, name) !== false) { - router.trigger.apply(router, ['route:' + name].concat(args)); - router.trigger('route', name, args); - BI.history.trigger('route', router, name, args); + router.trigger.apply(router, ["route:" + name].concat(args)); + router.trigger("route", name, args); + BI.history.trigger("route", router, name, args); } }); return this; @@ -271,7 +271,7 @@ // routes can be defined at the bottom of the route map. _bindRoutes: function () { if (!this.routes) return; - this.routes = _.result(this, 'routes'); + this.routes = _.result(this, "routes"); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); @@ -281,13 +281,13 @@ // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function (route) { - route = route.replace(escapeRegExp, '\\$&') - .replace(optionalParam, '(?:$1)?') + route = route.replace(escapeRegExp, "\\$&") + .replace(optionalParam, "(?:$1)?") .replace(namedParam, function (match, optional) { - return optional ? match : '([^/?]+)'; + return optional ? match : "([^/?]+)"; }) - .replace(splatParam, '([^?]*?)'); - return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); + .replace(splatParam, "([^?]*?)"); + return new RegExp("^" + route + "(?:\\?([\\s\\S]*))?$"); }, // Given a route, and a URL fragment that it matches, return the array of @@ -314,10 +314,10 @@ // falls back to polling. var History = function () { this.handlers = []; - _.bindAll(this, 'checkUrl'); + _.bindAll(this, "checkUrl"); // Ensure that `History` can be used outside of the browser. - if (typeof window !== 'undefined') { + if (typeof window !== "undefined") { this.location = window.location; this.history = window.history; } @@ -344,22 +344,22 @@ // Are we at the app root? atRoot: function () { - var path = this.location.pathname.replace(/[^\/]$/, '$&/'); + var path = this.location.pathname.replace(/[^\/]$/, "$&/"); return path === this.root && !this.getSearch(); }, // In IE6, the hash fragment and search params are incorrect if the // fragment contains `?`. getSearch: function () { - var match = this.location.href.replace(/#.*/, '').match(/\?.+/); - return match ? match[0] : ''; + var match = this.location.href.replace(/#.*/, "").match(/\?.+/); + return match ? match[0] : ""; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function (window) { var match = (window || this).location.href.match(/#(.*)$/); - return match ? match[1] : ''; + return match ? match[1] : ""; }, // Get the pathname and search params, without the root. @@ -367,7 +367,7 @@ var path = decodeURI(this.location.pathname + this.getSearch()); var root = this.root.slice(0, -1); if (!path.indexOf(root)) path = path.slice(root.length); - return path.charAt(0) === '/' ? path.slice(1) : path; + return path.charAt(0) === "/" ? path.slice(1) : path; }, // Get the cross-browser normalized URL fragment from the path or hash. @@ -379,27 +379,27 @@ fragment = this.getHash(); } } - return fragment.replace(routeStripper, ''); + return fragment.replace(routeStripper, ""); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function (options) { - if (History.started) throw new Error('BI.history has already been started'); + if (History.started) throw new Error("BI.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? - this.options = _.extend({root: '/'}, this.options, options); + this.options = _.extend({root: "/"}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; - this._hasHashChange = 'onhashchange' in window; + this._hasHashChange = "onhashchange" in window; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); this.fragment = this.getFragment(); // Normalize root to always include a leading and trailing slash. - this.root = ('/' + this.root + '/').replace(rootStripper, '/'); + this.root = ("/" + this.root + "/").replace(rootStripper, "/"); // Transition from hashChange to pushState or vice versa if both are // requested. @@ -408,8 +408,8 @@ // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { - var root = this.root.slice(0, -1) || '/'; - this.location.replace(root + '#' + this.getPath()); + var root = this.root.slice(0, -1) || "/"; + this.location.replace(root + "#" + this.getPath()); // Return immediately as browser will do redirect to new url return true; @@ -425,28 +425,28 @@ // support the `hashchange` event, HTML5 history, or the user wants // `hashChange` but not `pushState`. if (!this._hasHashChange && this._wantsHashChange && (!this._wantsPushState || !this._hasPushState)) { - var iframe = document.createElement('iframe'); - iframe.src = 'javascript:0'; - iframe.style.display = 'none'; + var iframe = document.createElement("iframe"); + iframe.src = "javascript:0"; + iframe.style.display = "none"; iframe.tabIndex = -1; var body = document.body; // Using `appendChild` will throw on IE < 9 if the document is not ready. this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow; this.iframe.document.open().close(); - this.iframe.location.hash = '#' + this.fragment; + this.iframe.location.hash = "#" + this.fragment; } // Add a cross-platform `addEventListener` shim for older browsers. var addEventListener = window.addEventListener || function (eventName, listener) { - return attachEvent('on' + eventName, listener); + return attachEvent("on" + eventName, listener); }; // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._hasPushState) { - addEventListener('popstate', this.checkUrl, false); + addEventListener("popstate", this.checkUrl, false); } else if (this._wantsHashChange && this._hasHashChange && !this.iframe) { - addEventListener('hashchange', this.checkUrl, false); + addEventListener("hashchange", this.checkUrl, false); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } @@ -459,14 +459,14 @@ stop: function () { // Add a cross-platform `removeEventListener` shim for older browsers. var removeEventListener = window.removeEventListener || function (eventName, listener) { - return detachEvent('on' + eventName, listener); + return detachEvent("on" + eventName, listener); }; // Remove window listeners. if (this._hasPushState) { - removeEventListener('popstate', this.checkUrl, false); + removeEventListener("popstate", this.checkUrl, false); } else if (this._wantsHashChange && this._hasHashChange && !this.iframe) { - removeEventListener('hashchange', this.checkUrl, false); + removeEventListener("hashchange", this.checkUrl, false); } // Clean up the iframe if necessary. @@ -527,24 +527,24 @@ if (!options || options === true) options = {trigger: !!options}; // Normalize the fragment. - fragment = this.getFragment(fragment || ''); + fragment = this.getFragment(fragment || ""); // Don't include a trailing slash on the root. var root = this.root; - if (fragment === '' || fragment.charAt(0) === '?') { - root = root.slice(0, -1) || '/'; + if (fragment === "" || fragment.charAt(0) === "?") { + root = root.slice(0, -1) || "/"; } var url = root + fragment; // Strip the hash and decode for matching. - fragment = decodeURI(fragment.replace(pathStripper, '')); + fragment = decodeURI(fragment.replace(pathStripper, "")); if (this.fragment === fragment) return; this.fragment = fragment; // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { - this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); + this.history[options.replace ? "replaceState" : "pushState"]({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. @@ -570,11 +570,11 @@ // a new one to the browser history. _updateHash: function (location, fragment, replace) { if (replace) { - var href = location.href.replace(/(javascript:|#).*$/, ''); - location.replace(href + '#' + fragment); + var href = location.href.replace(/(javascript:|#).*$/, ""); + location.replace(href + "#" + fragment); } else { // Some browsers require that `hash` contains a leading #. - location.hash = '#' + fragment; + location.hash = "#" + fragment; } } diff --git a/dist/widget.js b/dist/widget.js index 0a9fbe3f6..c996e889b 100644 --- a/dist/widget.js +++ b/dist/widget.js @@ -10,7 +10,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { return BI.extend(BI.SequenceTableTreeNumber.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-sequence-table-tree-number", isNeedFreeze: false, - startSequence: 1,//开始的序号 + startSequence: 1, // 开始的序号 scrollTop: 0, headerRowSize: 25, rowSize: 25, @@ -18,9 +18,9 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { sequenceHeaderCreator: null, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -65,7 +65,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { el: this.scrollContainer }] }); - //缓存第一行对应的序号 + // 缓存第一行对应的序号 this.start = this.options.startSequence; this.cache = {}; this._nextState(); @@ -78,8 +78,8 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { var start = this.start; var cnt = this.start; - function track(node) { - //如果已经有缓存了就不改计数了,复杂表会出现这种情况 + function track (node) { + // 如果已经有缓存了就不改计数了,复杂表会出现这种情况 self.cache[node.text || node.value] || (self.cache[node.text || node.value] = cnt); cnt++; } @@ -92,7 +92,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { start = cnt = self.cache[child.text || child.value]; } } - track(child) + track(child); }); } }); @@ -123,13 +123,13 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { var result = []; var count = this._getStart(nodes); - function getLeafCount(node) { + function getLeafCount (node) { var cnt = 0; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { cnt += getLeafCount(child); }); - if (/**node.children.length > 1 && **/BI.isNotEmptyArray(node.values)) { + if (/** node.children.length > 1 && **/BI.isNotEmptyArray(node.values)) { cnt++; } } else { @@ -290,7 +290,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { } : function (key) { return function () { return o.sequenceCellStyleGetter(key); - } + }; }(numbers[key].index) }, numbers[key])); renderedCells.push({ @@ -302,7 +302,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { } }); - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (BI.deepContains(self.renderedKeys, key)) { @@ -325,7 +325,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { }); var addedItems = []; BI.each(addSet, function (index) { - addedItems.push(renderedCells[index]) + addedItems.push(renderedCells[index]); }); BI.createWidget({ type: "bi.absolute", @@ -417,7 +417,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { this._populate(); } }); -BI.shortcut('bi.sequence_table_tree_number', BI.SequenceTableTreeNumber);/** +BI.shortcut("bi.sequence_table_tree_number", BI.SequenceTableTreeNumber);/** * 自适应布局 * * 1、resize @@ -489,7 +489,7 @@ BI.AdaptiveArrangement = BI.inherit(BI.Widget, { var self = this, o = this.options; item.element.css("zIndex", ++this.zIndex); item.element.mousedown(function () { - self._setSelect(item) + self._setSelect(item); }); }, @@ -715,7 +715,7 @@ BI.AdaptiveArrangement.EVENT_ELEMENT_RESIZE = "AdaptiveArrangement.EVENT_ELEMENT BI.AdaptiveArrangement.EVENT_ELEMENT_STOP_RESIZE = "AdaptiveArrangement.EVENT_ELEMENT_STOP_RESIZE"; BI.AdaptiveArrangement.EVENT_RESIZE = "AdaptiveArrangement.EVENT_RESIZE"; BI.AdaptiveArrangement.EVENT_SCROLL = "AdaptiveArrangement.EVENT_SCROLL"; -BI.shortcut('bi.adaptive_arrangement', BI.AdaptiveArrangement);/** +BI.shortcut("bi.adaptive_arrangement", BI.AdaptiveArrangement);/** * Arrangement的block面板 * * Created by GUY on 2016/3/1. @@ -730,7 +730,7 @@ BI.ArrangementBlock = BI.inherit(BI.Widget, { }); } }); -BI.shortcut('bi.arrangement_block', BI.ArrangementBlock);/** +BI.shortcut("bi.arrangement_block", BI.ArrangementBlock);/** * Arrangement的drop面板 * * Created by GUY on 2016/3/1. @@ -745,7 +745,7 @@ BI.ArrangementDroppable = BI.inherit(BI.Widget, { }); } }); -BI.shortcut('bi.arrangement_droppable', BI.ArrangementDroppable);/** +BI.shortcut("bi.arrangement_droppable", BI.ArrangementDroppable);/** * 布局 * * Created by GUY on 2016/2/23. @@ -809,7 +809,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { } }, - ////初始化操作//// + // //初始化操作//// _calculateRegions: function (items) { var self = this, o = this.options; this.regions = {}; @@ -839,7 +839,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return num1 >= num2 || this._isEqual(num1, num2); }, - //获取占有的最大Region + // 获取占有的最大Region _getRegionOccupied: function (regions) { var self = this, o = this.options; if (BI.size(regions || this.regions) <= 0) { @@ -848,7 +848,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: 0, width: 0, height: 0 - } + }; } var minLeft = BI.MAX, maxLeft = BI.MIN, minTop = BI.MAX, maxTop = BI.MIN; BI.each(regions || this.regions, function (id, region) { @@ -862,10 +862,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: minTop, width: maxLeft - minLeft, height: maxTop - minTop - } + }; }, - //两个区域的交叉面积 + // 两个区域的交叉面积 _getCrossArea: function (region1, region2) { if (region1.left <= region2.left) { if (region1.top <= region2.top) { @@ -903,7 +903,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return 0; }, - //是否有覆盖的组件 + // 是否有覆盖的组件 _isRegionOverlay: function (regions) { var reg = []; BI.each(regions || this.regions, function (id, region) { @@ -931,7 +931,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return false; }, - //布局是否是优良的 + // 布局是否是优良的 _isArrangeFine: function (regions) { switch (this.options.layoutType) { case BI.Arrangement.LAYOUT_TYPE.FREE: @@ -985,24 +985,24 @@ BI.Arrangement = BI.inherit(BI.Widget, { return clone; }, - //测试合法性 + // 测试合法性 _test: function (regions) { var self = this; return !BI.any(regions || this.regions, function (i, region) { if (BI.isNaN(region.width) || BI.isNaN(region.height) || region.width <= 21 || region.height <= 21) { return true; } - }) + }); }, _getScrollOffset: function () { return { left: this.container.element[0].scrollLeft, top: this.container.element[0].scrollTop - } + }; }, - ////操作//// + // //操作//// _createOneRegion: function (item) { var el = BI.createWidget(item.el); el.setVisible(true); @@ -1013,7 +1013,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { width: item.width, height: item.height, el: el - } + }; }, _applyRegion: function (regions) { @@ -1093,10 +1093,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: size.top, width: size.width, height: size.height - }) + }); }, - //Grid + // Grid _getOneWidthPortion: function () { return this.getClientWidth() / BI.Arrangement.PORTION; }, @@ -1131,7 +1131,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { y: topPortion, w: widthPortion, h: heightPortion - } + }; }, _getBlockPositionAndSize: function (position) { @@ -1151,7 +1151,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { BI.each(regions || this.regions, function (id, region) { result.push(BI.extend(self._getGridPositionAndSize(region), { i: region.id - })) + })); }); return result; }, @@ -1204,10 +1204,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { } var movingUp = y && l.y > y; - if (typeof x === 'number') { + if (typeof x === "number") { l.x = x; } - if (typeof y === 'number') { + if (typeof y === "number") { l.y = y; } l.moved = true; @@ -1237,7 +1237,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return layout; - function getAllCollisions(layout, layoutItem) { + function getAllCollisions (layout, layoutItem) { return BI.filter(layout, function (i, l) { return self._collides(l, layoutItem); }); @@ -1281,14 +1281,14 @@ BI.Arrangement = BI.inherit(BI.Widget, { }, _moveElementAwayFromCollision: function (layout, collidesWith, - itemToMove, isUserAction) { + itemToMove, isUserAction) { if (isUserAction) { var fakeItem = { x: itemToMove.x, y: itemToMove.y, w: itemToMove.w, h: itemToMove.h, - i: '-1' + i: "-1" }; fakeItem.y = Math.max(collidesWith.y - itemToMove.h, 0); if (!this._getFirstCollision(layout, fakeItem)) { @@ -1334,14 +1334,14 @@ BI.Arrangement = BI.inherit(BI.Widget, { return out; - function getStatics(layout) { + function getStatics (layout) { return BI.filter(layout, function (i, l) { return l._static; }); } }, - ////公有方法//// + // //公有方法//// getRegionByName: function (name) { var obj = {}; obj[name] = this.regions[name]; @@ -1380,7 +1380,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { this.block.setVisible(false); }, - ////公有操作//// + // //公有操作//// setLayoutType: function (type) { var self = this, o = this.options; if (type !== o.layoutType) { @@ -1405,7 +1405,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return { x: BI.parseFloat(BI.contentFormat((occupied.left + occupied.width) / width, "#.##;-#.##")), y: BI.parseFloat(BI.contentFormat((occupied.top + occupied.height) / height, "#.##;-#.##")) - } + }; }, addRegion: function (region, position) { @@ -1624,7 +1624,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { })); return function () { self.arrangement.setVisible(false); - } + }; }, scrollTo: function (scroll) { @@ -1643,13 +1643,13 @@ BI.Arrangement = BI.inherit(BI.Widget, { if (this._isArrangeFine()) { var width = this.getClientWidth(); var xRatio = (ratio.x || 1) * width / (occupied.left + occupied.width); - //var yRatio = ratio.y * height / (occupied.top + occupied.height); + // var yRatio = ratio.y * height / (occupied.top + occupied.height); var regions = this._cloneRegion(); BI.each(regions, function (i, region) { region.left = region.left * xRatio; - //region.top = region.top * yRatio; + // region.top = region.top * yRatio; region.width = region.width * xRatio; - //region.height = region.height * yRatio; + // region.height = region.height * yRatio; }); if (this._test(regions)) { this._modifyRegion(regions); @@ -1671,7 +1671,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { region.width = region.width * xRatio; region.top = region.top * yRatio; region.height = region.height * yRatio; - //做一下自适应布局到网格布局的兼容 + // 做一下自适应布局到网格布局的兼容 var perWidth = self._getOneWidthPortion(); var widthPortion = Math.round(region.width / perWidth); var leftPortion = Math.round(region.left / perWidth); @@ -1746,7 +1746,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { } store[row][col] = region; }); - //非4的倍数 + // 非4的倍数 // if (count % 4 !== 0) { // var lasts = store[rows - 1]; // var perWidth = width / (count % 4); @@ -1802,7 +1802,7 @@ BI.extend(BI.Arrangement, { FREE: 1 } }); -BI.shortcut('bi.arrangement', BI.Arrangement);/** +BI.shortcut("bi.arrangement", BI.Arrangement);/** * 日期控件中的月份下拉框 * * Created by GUY on 2015/9/7. @@ -1810,13 +1810,13 @@ BI.shortcut('bi.arrangement', BI.Arrangement);/** * @extends BI.Trigger */ BI.MonthDateCombo = BI.inherit(BI.Trigger, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.MonthDateCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-month-combo", height: 25 }); }, - _init: function() { + _init: function () { BI.MonthDateCombo.superclass._init.apply(this, arguments); var self = this, o = this.options; @@ -1828,9 +1828,9 @@ BI.MonthDateCombo = BI.inherit(BI.Trigger, { type: "bi.month_popup" }); - this.popup.on(BI.YearPopup.EVENT_CHANGE, function(){ + this.popup.on(BI.YearPopup.EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); - }) + }); this.combo = BI.createWidget({ @@ -1845,24 +1845,24 @@ BI.MonthDateCombo = BI.inherit(BI.Trigger, { stopPropagation: false, el: this.popup } - }) - this.combo.on(BI.Combo.EVENT_CHANGE, function(){ + }); + this.combo.on(BI.Combo.EVENT_CHANGE, function () { self.combo.hideView(); self.fireEvent(BI.MonthDateCombo.EVENT_CHANGE); }); }, - setValue: function(v){ + setValue: function (v) { this.trigger.setValue(v + 1); this.popup.setValue(v); }, - getValue: function(){ + getValue: function () { return this.popup.getValue(); } }); BI.MonthDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.month_date_combo', BI.MonthDateCombo);/** +BI.shortcut("bi.month_date_combo", BI.MonthDateCombo);/** * 年份下拉框 * * Created by GUY on 2015/9/7. @@ -1870,15 +1870,15 @@ BI.shortcut('bi.month_date_combo', BI.MonthDateCombo);/** * @extends BI.Trigger */ BI.YearDateCombo = BI.inherit(BI.Trigger, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.YearDateCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-combo", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 25 }); }, - _init: function() { + _init: function () { BI.YearDateCombo.superclass._init.apply(this, arguments); var self = this, o = this.options; @@ -1892,11 +1892,11 @@ BI.YearDateCombo = BI.inherit(BI.Trigger, { max: o.max }); - this.popup.on(BI.YearPopup.EVENT_CHANGE, function(){ + this.popup.on(BI.YearPopup.EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); self.combo.hideView(); self.fireEvent(BI.YearDateCombo.EVENT_CHANGE); - }) + }); this.combo = BI.createWidget({ @@ -1911,23 +1911,23 @@ BI.YearDateCombo = BI.inherit(BI.Trigger, { stopPropagation: false, el: this.popup } - }) - this.combo.on(BI.Combo.EVENT_CHANGE, function(){ + }); + this.combo.on(BI.Combo.EVENT_CHANGE, function () { self.fireEvent(BI.YearDateCombo.EVENT_CHANGE); - }) + }); }, - setValue: function(v){ + setValue: function (v) { this.trigger.setValue(v); this.popup.setValue(v); }, - getValue: function(){ + getValue: function () { return this.popup.getValue(); } }); BI.YearDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.year_date_combo', BI.YearDateCombo);/** +BI.shortcut("bi.year_date_combo", BI.YearDateCombo);/** * Created by GUY on 2015/9/7. * @class BI.DatePicker * @extends BI.Widget @@ -1938,9 +1938,9 @@ BI.DatePicker = BI.inherit(BI.Widget, { return BI.extend(conf, { baseCls: "bi-date-picker bi-background", height: 25, - min: '1900-01-01', //最小日期 - max: '2099-12-31' //最大日期 - }) + min: "1900-01-01", // 最小日期 + max: "2099-12-31" // 最大日期 + }); }, _init: function () { @@ -1959,12 +1959,12 @@ BI.DatePicker = BI.inherit(BI.Widget, { self.setValue({ year: self.year.getValue() - 1, month: 11 - }) + }); } else { self.setValue({ year: self.year.getValue(), month: self.month.getValue() - 1 - }) + }); } self.fireEvent(BI.DatePicker.EVENT_CHANGE); self._checkLeftValid(); @@ -1983,12 +1983,12 @@ BI.DatePicker = BI.inherit(BI.Widget, { self.setValue({ year: self.year.getValue() + 1, month: 0 - }) + }); } else { self.setValue({ year: self.year.getValue(), month: self.month.getValue() + 1 - }) + }); } self.fireEvent(BI.DatePicker.EVENT_CHANGE); self._checkLeftValid(); @@ -2006,7 +2006,7 @@ BI.DatePicker = BI.inherit(BI.Widget, { month: self.month.getValue() }); self.fireEvent(BI.DatePicker.EVENT_CHANGE); - }) + }); this.month = BI.createWidget({ type: "bi.month_date_combo" }); @@ -2035,11 +2035,11 @@ BI.DatePicker = BI.inherit(BI.Widget, { el: this.right, width: 25 }] - }) + }); this.setValue({ year: this._year, month: this._month - }) + }); }, _checkLeftValid: function () { @@ -2071,10 +2071,10 @@ BI.DatePicker = BI.inherit(BI.Widget, { return { year: this.year.getValue(), month: this.month.getValue() - } + }; } }); -BI.DatePicker.EVENT_CHANGE = "EVENT_CHANGE" +BI.DatePicker.EVENT_CHANGE = "EVENT_CHANGE"; BI.shortcut("bi.date_picker", BI.DatePicker);/** * Created by GUY on 2015/9/7. * @class BI.DateCalendarPopup @@ -2085,10 +2085,10 @@ BI.DateCalendarPopup = BI.inherit(BI.Widget, { var conf = BI.DateCalendarPopup.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: "bi-date-calendar-popup", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 selectedTime: null - }) + }); }, _createNav: function (v) { @@ -2104,7 +2104,7 @@ BI.DateCalendarPopup = BI.inherit(BI.Widget, { month: date.month, day: this.selectedTime.day }); - return calendar + return calendar; }, _init: function () { @@ -2185,13 +2185,13 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { iconHeight: 13 }, - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.DateTriangleTrigger.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-date-triangle-trigger pull-down-ha-font cursor-pointer", height: 25 }); }, - _init: function() { + _init: function () { BI.DateTriangleTrigger.superclass._init.apply(this, arguments); var o = this.options, c = this._const; this.text = BI.createWidget({ @@ -2201,7 +2201,7 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { text: o.text, value: o.value, height: c.height - }) + }); this.icon = BI.createWidget({ type: "bi.icon", width: c.iconWidth, @@ -2217,30 +2217,30 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { height: c.height, items: [this.text, this.icon] }] - }) + }); }, - setValue: function(v){ + setValue: function (v) { this.text.setValue(v); }, - getValue: function(){ + getValue: function () { return this.text.getValue(); }, - setText: function(v){ + setText: function (v) { this.text.setText(v); }, - getText: function(){ + getText: function () { return this.item.getText(); }, - getKey: function(){ + getKey: function () { } }); -BI.shortcut('bi.date_triangle_trigger', BI.DateTriangleTrigger);/** +BI.shortcut("bi.date_triangle_trigger", BI.DateTriangleTrigger);/** * 日期下拉框 * * Created by GUY on 2015/9/7. @@ -2287,7 +2287,7 @@ BI.DateCombo = BI.inherit(BI.Widget, { el: this.popup, stopPropagation: false } - }) + }); }, setValue: function (v) { @@ -2299,7 +2299,7 @@ BI.DateCombo = BI.inherit(BI.Widget, { return this.popup.getValue(); } }); -BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigger, { +BI.shortcut("bi.date_combo", BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigger, { _const: { hgap: 4, vgap: 2, @@ -2310,8 +2310,8 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge _defaultConfig: function () { return BI.extend(BI.DateTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-date-trigger", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24 }); }, @@ -2325,10 +2325,10 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge var date = v.match(/\d+/g); self._autoAppend(v, date); return self._dateCheck(v) && Date.checkLegal(v) && self._checkVoid({ - year: date[0], - month: date[1], - day: date[2] - }); + year: date[0], + month: date[1], + day: date[2] + }); }, quitChecker: function () { return false; @@ -2345,7 +2345,7 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge } }); this.editor.on(BI.SignEditor.EVENT_KEY_DOWN, function () { - self.fireEvent(BI.DateTrigger.EVENT_KEY_DOWN) + self.fireEvent(BI.DateTrigger.EVENT_KEY_DOWN); }); this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { self.fireEvent(BI.DateTrigger.EVENT_FOCUS); @@ -2369,7 +2369,7 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge var date = value.split("-"); self.store_value = { type: BI.DateTrigger.MULTI_DATE_CALENDAR, - value:{ + value: { year: date[0] | 0, month: date[1] - 1, day: date[2] | 0 @@ -2398,7 +2398,7 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge }, { el: this.editor }] - }) + }); }, _dateCheck: function (date) { return Date.parseDateTime(date, "%Y-%x-%d").print("%Y-%x-%d") == date || Date.parseDateTime(date, "%Y-%X-%d").print("%Y-%X-%d") == date || Date.parseDateTime(date, "%Y-%x-%e").print("%Y-%x-%e") == date || Date.parseDateTime(date, "%Y-%X-%e").print("%Y-%X-%e") == date; @@ -2437,7 +2437,7 @@ BI.shortcut('bi.date_combo', BI.DateCombo);BI.DateTrigger = BI.inherit(BI.Trigge this.store_value = v; if (BI.isNotNull(v)) { type = v.type || BI.DateTrigger.MULTI_DATE_CALENDAR; value = v.value; - if(BI.isNull(value)){ + if(BI.isNull(value)) { value = v; } } @@ -2622,10 +2622,10 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { var conf = BI.DatePaneWidget.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: "bi-date-pane", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 selectedTime: null - }) + }); }, _init: function () { BI.DatePaneWidget.superclass._init.apply(this, arguments); @@ -2636,9 +2636,9 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { this._month = this.today.getMonth(); this.selectedTime = o.selectedTime || { - year: this._year, - month: this._month - }; + year: this._year, + month: this._month + }; this.datePicker = BI.createWidget({ type: "bi.date_picker", @@ -2699,7 +2699,7 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { return { year: today.getFullYear(), month: today.getMonth() - } + }; }, _setCalenderValue: function (date) { @@ -2721,7 +2721,7 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { this.calendar.empty(); this._setCalenderValue(this._getNewCurrentDate()); } else { - this._setCalenderValue(timeOb) + this._setCalenderValue(timeOb); } }, @@ -2749,7 +2749,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { }, _defaultConfig: function () { return BI.extend(BI.DateTimeCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-date-time-combo bi-border', + baseCls: "bi-date-time-combo bi-border", width: 200, height: 24 }); @@ -2767,7 +2767,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { second: date.getSeconds() }; this.trigger = BI.createWidget({ - type: 'bi.date_time_trigger', + type: "bi.date_time_trigger", min: this.constants.DATE_MIN_VALUE, max: this.constants.DATE_MAX_VALUE }); @@ -2795,7 +2795,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { self.fireEvent(BI.DateTimeCombo.EVENT_CHANGE); }); this.combo = BI.createWidget({ - type: 'bi.combo', + type: "bi.combo", toggle: false, isNeedAdjustHeight: false, isNeedAdjustWidth: false, @@ -2844,7 +2844,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { left: 0 }] }] - }) + }); }, setValue: function (v) { @@ -2865,14 +2865,14 @@ BI.DateTimeCombo.EVENT_CANCEL = "EVENT_CANCEL"; BI.DateTimeCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.DateTimeCombo.EVENT_CHANGE = "EVENT_CHANGE"; BI.DateTimeCombo.EVENT_BEFORE_POPUPVIEW = "BI.DateTimeCombo.EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.date_time_combo', BI.DateTimeCombo); +BI.shortcut("bi.date_time_combo", BI.DateTimeCombo); /** * Created by Urthur on 2017/7/14. */ BI.DateTimePopup = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.DateTimePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-date-time-popup', + baseCls: "bi-date-time-popup", width: 268, height: 290 }); @@ -2881,9 +2881,9 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { BI.DateTimePopup.superclass._init.apply(this, arguments); var self = this, opts = this.options; this.cancelButton = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", forceCenter: true, - cls: 'multidate-popup-button bi-border-top bi-border-right', + cls: "multidate-popup-button bi-border-top bi-border-right", shadow: true, text: BI.i18nText("BI-Basic_Cancel") }); @@ -2894,7 +2894,7 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { this.okButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'multidate-popup-button bi-border-top', + cls: "multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_OK") }); @@ -3035,13 +3035,13 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { hour: this.hour.getValue(), minute: this.minute.getValue(), second: this.second.getValue() - } + }; } }); BI.DateTimePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; BI.DateTimePopup.BUTTON_CANCEL_EVENT_CHANGE = "BUTTON_CANCEL_EVENT_CHANGE"; BI.DateTimePopup.CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE"; -BI.shortcut('bi.date_time_popup', BI.DateTimePopup); +BI.shortcut("bi.date_time_popup", BI.DateTimePopup); /** * Created by Urthur on 2017/7/14. */ @@ -3051,7 +3051,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { baseCls: "bi-date-time-select bi-border", max: 23, min: 0 - }) + }); }, _init: function () { @@ -3062,11 +3062,11 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { value: this._alertInEditorValue(o.min), allowBlank: false, errorText: BI.i18nText("BI-Please_Input_Natural_Number"), - validationChecker: function(v){ + validationChecker: function (v) { return BI.isNaturalNumber(v); } }); - this.editor.on(BI.TextEditor.EVENT_CONFIRM, function(){ + this.editor.on(BI.TextEditor.EVENT_CONFIRM, function () { self._finetuning(0); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -3074,7 +3074,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { type: "bi.icon_button", cls: "column-pre-page-h-font top-button bi-border-left bi-border-bottom" }); - this.topBtn.on(BI.IconButton.EVENT_CHANGE, function(){ + this.topBtn.on(BI.IconButton.EVENT_CHANGE, function () { self._finetuning(1); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -3082,7 +3082,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { type: "bi.icon_button", cls: "column-next-page-h-font bottom-button bi-border-left" }); - this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function(){ + this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function () { self._finetuning(-1); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -3110,28 +3110,28 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { }); }, - _alertOutEditorValue: function(v){ - if (v > this.options.max){ + _alertOutEditorValue: function (v) { + if (v > this.options.max) { v = this.options.min; } - if (v < this.options.min){ - v = this.options.max + if (v < this.options.min) { + v = this.options.max; } return BI.parseInt(v); }, - _alertInEditorValue: function(v){ - if (v > this.options.max){ + _alertInEditorValue: function (v) { + if (v > this.options.max) { v = this.options.min; } - if (v < this.options.min){ + if (v < this.options.min) { v = this.options.max; } v = v < 10 ? "0" + v : v; return v; }, - _finetuning: function(add){ + _finetuning: function (add) { var v = BI.parseInt(this._alertOutEditorValue(this.editor.getValue())); this.editor.setValue(this._alertInEditorValue(v + add)); }, @@ -3159,8 +3159,8 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { _defaultConfig: function () { return BI.extend(BI.DateTimeTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-date-time-trigger", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24, width: 200 }); @@ -3185,7 +3185,7 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { }, { el: this.text }] - }) + }); }, _printTime: function (v) { @@ -3195,11 +3195,11 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { setValue: function (v) { var self = this; var value = v, dateStr; - if(BI.isNull(value)){ + if(BI.isNull(value)) { value = Date.getDate(); dateStr = value.print("%Y-%X-%d %H:%M:%S"); } else { - var date = Date.getDate(value.year,value.month,value.day,value.hour,value.minute,value.second); + var date = Date.getDate(value.year, value.month, value.day, value.hour, value.minute, value.second); dateStr = date.print("%Y-%X-%d %H:%M:%S"); } @@ -3238,7 +3238,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { items: o.items }); this.pathChooser.on(BI.PathChooser.EVENT_CHANGE, function (start, index) { - //self._unselectAllArrows(); + // self._unselectAllArrows(); self._setValue(start, index); self.fireEvent(BI.DirectionPathChooser.EVENT_CHANGE); }); @@ -3258,7 +3258,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { }, _drawOneArrow: function (dot, direction) { - //0,1,2,3 上右下左 + // 0,1,2,3 上右下左 var lineColor = this._const.lineColor; var selectLineColor = this._const.selectLineColor; var svg = this.pathChooser.svg; @@ -3356,17 +3356,17 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { } } }); - }) + }); }); - function getXoffsetByRegionIndex(regionIndex, diregion) { + function getXoffsetByRegionIndex (regionIndex, diregion) { if (diregion === -1) { return 100 * (regionIndex + 1) - 20; } return 100 * regionIndex + 20; } - function getYByXoffset(dots, xoffset) { + function getYByXoffset (dots, xoffset) { var finded = BI.find(dots, function (i, dot) { if (i > 0) { if (dots[i - 1].x < xoffset && dots[i].x > xoffset) { @@ -3426,7 +3426,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { if (array.length > 0) { result.push(array); } - //画这n条路径 + // 画这n条路径 BI.each(result, function (idx, path) { var start = path[0]; var index = BI.findIndex(routes[start], function (idx, p) { @@ -3450,7 +3450,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { } }); BI.DirectionPathChooser.EVENT_CHANGE = "DirectionPathChooser.EVENT_CHANGE"; -BI.shortcut('bi.direction_path_chooser', BI.DirectionPathChooser);/** +BI.shortcut("bi.direction_path_chooser", BI.DirectionPathChooser);/** * Created by roy on 15/8/14. */ BI.DownListCombo = BI.inherit(BI.Widget, { @@ -3465,7 +3465,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { trigger: "click", container: null, el: {} - }) + }); }, _init: function () { @@ -3490,7 +3490,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { this.downlistcombo = BI.createWidget({ element: this, - type: 'bi.combo', + type: "bi.combo", trigger: o.trigger, isNeedAdjustWidth: false, container: o.container, @@ -3530,7 +3530,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { this.popupview.setValue(v); }, getValue: function () { - return this.popupview.getValue() + return this.popupview.getValue(); } }); BI.DownListCombo.EVENT_CHANGE = "EVENT_CHANGE"; @@ -3552,7 +3552,7 @@ BI.DownListGroup = BI.inherit(BI.Widget, { el: {} } ] - }) + }); }, _init: function () { BI.DownListGroup.superclass._init.apply(this, arguments); @@ -3562,7 +3562,7 @@ BI.DownListGroup = BI.inherit(BI.Widget, { element: this, type: "bi.button_tree", items: o.items, - chooseType: 0,//0单选,1多选 + chooseType: 0, // 0单选,1多选 layouts: [{ type: "bi.vertical", hgap: 0, @@ -3574,17 +3574,17 @@ BI.DownListGroup = BI.inherit(BI.Widget, { if(type === BI.Events.CLICK) { self.fireEvent(BI.DownListGroup.EVENT_CHANGE, arguments); } - }) + }); }, - getValue:function(){ + getValue: function () { return this.downlistgroup.getValue(); }, - setValue:function(v){ + setValue: function (v) { this.downlistgroup.setValue(v); } -}) +}); BI.DownListGroup.EVENT_CHANGE = "EVENT_CHANGE"; BI.shortcut("bi.down_list_group", BI.DownListGroup);BI.DownListItem = BI.inherit(BI.Single, { _defaultConfig: function () { @@ -3603,7 +3603,7 @@ BI.shortcut("bi.down_list_group", BI.DownListGroup);BI.DownListItem = BI.inherit textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.DownListItem.superclass._init.apply(this, arguments); @@ -3675,7 +3675,7 @@ BI.shortcut("bi.down_list_item", BI.DownListItem);BI.DownListGroupItem = BI.inhe // invalid: true, iconCls1: "dot-e-font", iconCls2: "pull-right-e-font" - }) + }); }, _init: function () { BI.DownListGroupItem.superclass._init.apply(this, arguments); @@ -3731,7 +3731,7 @@ BI.shortcut("bi.down_list_item", BI.DownListItem);BI.DownListGroupItem = BI.inhe } }, function () { if (self.isEnabled()) { - self.dishover() + self.dishover(); } }); }, @@ -3771,10 +3771,10 @@ BI.shortcut("bi.down_list_item", BI.DownListItem);BI.DownListGroupItem = BI.inhe if (BI.contains(o.childValues, value)) { self.icon1.setSelected(true); return true; - } else { - self.icon1.setSelected(false); } - }) + self.icon1.setSelected(false); + + }); } }); BI.DownListGroupItem.EVENT_CHANGE = "EVENT_CHANGE"; @@ -3799,7 +3799,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { baseCls: "bi-down-list-popup", items: [], chooseType: BI.Selection.Multi - }) + }); }, _init: function () { BI.DownListPopup.superclass._init.apply(this, arguments); @@ -3826,7 +3826,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { var changedValue = value; if (BI.isNotNull(self.childValueMap[value])) { changedValue = self.childValueMap[value]; - self.fireEvent(BI.DownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, self.fatherValueMap[value]) + self.fireEvent(BI.DownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, self.fatherValueMap[value]); } else { self.fireEvent(BI.DownListPopup.EVENT_CHANGE, changedValue, object); } @@ -3902,7 +3902,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { self.childValueMap[self._createChildValue(fatherValue, childValue)] = childValue; child.value = self._createChildValue(fatherValue, childValue); item.el.childValues.push(child.value); - }) + }); } else { item.type = "bi.down_list_item"; item.title = item.title || item.text; @@ -3910,7 +3910,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { item.isNeedAdjustWidth = false; item.logic = { dynamic: true - } + }; } var el_done = {}; el_done.el = item; @@ -3919,7 +3919,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { if (self._isGroup(item_done.items)) { BI.each(item_done.items, function (i, item) { self.singleValues.push(item.el.value); - }) + }); } result.push(item_done); @@ -3953,7 +3953,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { }, _createChildValue: function (fatherValue, childValue) { - return fatherValue + "_" + childValue + return fatherValue + "_" + childValue; }, populate: function (items) { @@ -3975,14 +3975,14 @@ BI.DownListPopup = BI.inherit(BI.Pane, { var self = this; var valueArray = []; BI.each(valueItem, function (i, item) { - var value; - if (BI.isNotNull(item.childValue)) { - value = self._createChildValue(item.value, item.childValue); - } else { - value = item.value; - } - valueArray.push(value); + var value; + if (BI.isNotNull(item.childValue)) { + value = self._createChildValue(item.value, item.childValue); + } else { + value = item.value; } + valueArray.push(value); + } ); this.popup.setValue(valueArray); }, @@ -4093,34 +4093,34 @@ BI.SearchEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.SearchEditor.EVENT_KEY_DOWN, v); }); this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_SPACE) + self.fireEvent(BI.SearchEditor.EVENT_SPACE); }); this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_BACKSPACE) + self.fireEvent(BI.SearchEditor.EVENT_BACKSPACE); }); this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.SearchEditor.EVENT_VALID) + self.fireEvent(BI.SearchEditor.EVENT_VALID); }); this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.SearchEditor.EVENT_ERROR) + self.fireEvent(BI.SearchEditor.EVENT_ERROR); }); this.editor.on(BI.Editor.EVENT_ENTER, function () { self.fireEvent(BI.SearchEditor.EVENT_ENTER); }); this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.SearchEditor.EVENT_RESTRICT) + self.fireEvent(BI.SearchEditor.EVENT_RESTRICT); }); this.editor.on(BI.Editor.EVENT_EMPTY, function () { self._checkClear(); - self.fireEvent(BI.SearchEditor.EVENT_EMPTY) + self.fireEvent(BI.SearchEditor.EVENT_EMPTY); }); this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.SearchEditor.EVENT_REMOVE) + self.fireEvent(BI.SearchEditor.EVENT_REMOVE); }); this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.SearchEditor.EVENT_CONFIRM) + self.fireEvent(BI.SearchEditor.EVENT_CONFIRM); }); this.editor.on(BI.Editor.EVENT_START, function () { self.fireEvent(BI.SearchEditor.EVENT_START); @@ -4237,7 +4237,7 @@ BI.TextEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -4411,7 +4411,7 @@ BI.FileManagerButtonGroup = BI.inherit(BI.Widget, { return BI.extend(BI.FileManagerButtonGroup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-button_group", items: [] - }) + }); }, _init: function () { @@ -4490,7 +4490,7 @@ BI.FileManager = BI.inherit(BI.Widget, { baseCls: "bi-file-manager", el: {}, items: [] - }) + }); }, _init: function () { @@ -4505,7 +4505,7 @@ BI.FileManager = BI.inherit(BI.Widget, { items: BI.deepClone(items) }); this.nav.on(BI.FileManagerNav.EVENT_CHANGE, function (value, obj) { - if (value == "-1") {//根节点 + if (value == "-1") {// 根节点 self.populate({children: self.tree.toJSON()}); } else { var node = self.tree.search(obj.attr("id")); @@ -4603,7 +4603,7 @@ BI.FileManagerFileItem = BI.inherit(BI.Single, { return BI.extend(BI.FileManagerFileItem.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-file-item bi-list-item bi-border-bottom", height: 30 - }) + }); }, _init: function () { @@ -4641,10 +4641,10 @@ BI.FileManagerFileItem = BI.inherit(BI.Single, { value: o.value } }] - }) + }); }, - getAllLeaves: function(){ + getAllLeaves: function () { return [this.options.value]; }, @@ -4670,7 +4670,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { return BI.extend(BI.FileManagerFolderItem.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-folder-item bi-list-item bi-border-bottom", height: 30 - }) + }); }, _init: function () { @@ -4719,7 +4719,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { }, { el: this.button }] - }) + }); }, setAllSelected: function (v) { @@ -4729,7 +4729,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { setHalfSelected: function (v) { this.checked.setHalfSelected(v); - if(!v){ + if(!v) { this.selectValue = []; } }, @@ -4763,7 +4763,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { var res = []; this.tree.traverse(function (node) { if (node.isLeaf()) { - res.push(node.get("data").value) + res.push(node.get("data").value); } }); return res; @@ -4823,7 +4823,7 @@ BI.FileManagerList = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-list", el: {}, items: [] - }) + }); }, _init: function () { @@ -4884,7 +4884,7 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-nav-button", selected: false, height: 40 - }) + }); }, _init: function () { @@ -4913,8 +4913,8 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { height: o.height }); var path = svg.path("M0,0L15,20L0,40").attr({ - "stroke": c.select_color, - "fill": o.selected ? c.select_color : c.normal_color + stroke: c.select_color, + fill: o.selected ? c.select_color : c.normal_color }); this.button.on(BI.TextButton.EVENT_CHANGE, function () { if (this.isSelected()) { @@ -4937,7 +4937,7 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { top: 0, bottom: 0 }] - }) + }); }, isSelected: function () { @@ -4971,7 +4971,7 @@ BI.FileManagerNav = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-nav bi-border-left", height: 40, items: [] - }) + }); }, _init: function () { @@ -5045,7 +5045,7 @@ BI.FileManagerNav = BI.inherit(BI.Widget, { return ids; }, - refreshTreeData: function(items){ + refreshTreeData: function (items) { this.tree.initTree(BI.Tree.transformToTreeFormat(items)); this.tree.getRoot().set("data", { text: BI.i18nText("BI-Created_By_Me"), @@ -5155,7 +5155,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { top: top, middle: middle, bottom: bottom - } + }; }, _getRegionClientPosition: function (name) { @@ -5167,7 +5167,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { width: region.width, height: region.height, id: region.id - } + }; }, _vAlign: function (position, regions) { @@ -5293,14 +5293,14 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { _drawOneTag: function (start, end) { var s = BI.createWidget({ type: "bi.icon_button", - //invisible: true, + // invisible: true, width: 13, height: 13, cls: "drag-tag-font interactive-arrangement-dragtag-icon" }); var e = BI.createWidget({ type: "bi.icon_button", - //invisible: true, + // invisible: true, width: 13, height: 13, cls: "drag-tag-font interactive-arrangement-dragtag-icon" @@ -5308,7 +5308,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { if (this._isEqual(start.left, end.left)) { var line = BI.createWidget({ type: "bi.layout", - //invisible: true, + // invisible: true, cls: "interactive-arrangement-dragtag-line", width: 1, height: Math.abs(start.top - end.top) @@ -5316,7 +5316,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { } else { var line = BI.createWidget({ type: "bi.layout", - //invisible: true, + // invisible: true, cls: "interactive-arrangement-dragtag-line", height: 1, width: Math.abs(start.left - end.left) @@ -5412,7 +5412,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { return position; }, - //position不动 变size + // position不动 变size getSize: function (name, position, size) { var regions = this.getAllRegions(); var me; @@ -5552,7 +5552,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { return function () { callback(); self.stopDraw(); - } + }; }, scrollInterval: function () { @@ -5614,7 +5614,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { }); BI.InteractiveArrangement.EVENT_RESIZE = "InteractiveArrangement.EVENT_RESIZE"; BI.InteractiveArrangement.EVENT_SCROLL = "InteractiveArrangement.EVENT_SCROLL"; -BI.shortcut('bi.interactive_arrangement', BI.InteractiveArrangement);/** +BI.shortcut("bi.interactive_arrangement", BI.InteractiveArrangement);/** * Created by zcf on 2016/9/26. */ BI.IntervalSlider = BI.inherit(BI.Widget, { @@ -5633,7 +5633,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { baseCls: "bi-interval-slider bi-slider-track", digit: false, unit: "" - }) + }); }, _init: function () { @@ -5683,7 +5683,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var v = BI.parseFloat(this.getValue()); self.valueOne = v; var percent = self._getPercentByValue(v); - var significantPercent = BI.parseFloat(percent.toFixed(1));//分成1000份 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 分成1000份 self._setLabelOnePosition(significantPercent); self._setSliderOnePosition(significantPercent); self._setBlueTrack(); @@ -5748,10 +5748,10 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }, - this._createLabelWrapper(), - this._createSliderWrapper() + this._createLabelWrapper(), + this._createSliderWrapper() ] - }) + }); }, _rePosBySizeAfterMove: function (size, isLeft) { @@ -5761,7 +5761,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var v = this._getValueByPercent(significantPercent); v = this._assertValue(v); v = o.digit === false ? v : v.toFixed(o.digit); - if(isLeft){ + if(isLeft) { this._setLabelOnePosition(significantPercent); this._setSliderOnePosition(significantPercent); this.labelOne.setValue(v); @@ -5807,7 +5807,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { self.fireEvent(BI.IntervalSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -5815,7 +5815,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -5846,7 +5846,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { top: 0, left: 0, width: "100%" - } + }; }, _createSliderWrapper: function () { @@ -5875,7 +5875,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { top: 20, left: 0, width: "100%" - } + }; }, _createTrackWrapper: function () { @@ -5905,18 +5905,18 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { var o = this.options; var valid = false; - //像90.这样的既不属于整数又不属于小数,是不合法的值 + // 像90.这样的既不属于整数又不属于小数,是不合法的值 var dotText = (v + "").split(".")[1]; if (BI.isEmptyString(dotText)) { }else{ if (BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max)) { - if(o.digit === false){ + if(o.digit === false) { valid = true; }else{ dotText = dotText || ""; @@ -5932,43 +5932,43 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var labelTwoLeft = this.labelTwo.element[0].offsetLeft; if (labelOneLeft <= labelTwoLeft) { if ((labelTwoLeft - labelOneLeft) < 90) { - this.labelTwo.element.css({"top": 40}); + this.labelTwo.element.css({top: 40}); } else { - this.labelTwo.element.css({"top": 0}); + this.labelTwo.element.css({top: 0}); } } else { if ((labelOneLeft - labelTwoLeft) < 90) { - this.labelTwo.element.css({"top": 40}); + this.labelTwo.element.css({top: 40}); } else { - this.labelTwo.element.css({"top": 0}); + this.labelTwo.element.css({top: 0}); } } }, _setLabelOnePosition: function (percent) { - this.labelOne.element.css({"left": percent + "%"}); + this.labelOne.element.css({left: percent + "%"}); this._checkOverlap(); }, _setLabelTwoPosition: function (percent) { - this.labelTwo.element.css({"left": percent + "%"}); + this.labelTwo.element.css({left: percent + "%"}); this._checkOverlap(); }, _setSliderOnePosition: function (percent) { - this.sliderOne.element.css({"left": percent + "%"}); + this.sliderOne.element.css({left: percent + "%"}); }, _setSliderTwoPosition: function (percent) { - this.sliderTwo.element.css({"left": percent + "%"}); + this.sliderTwo.element.css({left: percent + "%"}); }, _setBlueTrackLeft: function (percent) { - this.blueTrack.element.css({"left": percent + "%"}); + this.blueTrack.element.css({left: percent + "%"}); }, _setBlueTrackWidth: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setBlueTrack: function () { @@ -6005,21 +6005,21 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, - //其中取max-min后保留4为有效数字后的值的小数位数为最终value的精度 - _getValueByPercent: function (percent) {//return (((max-min)*percent)/100+min) + // 其中取max-min后保留4为有效数字后的值的小数位数为最终value的精度 + _getValueByPercent: function (percent) {// return (((max-min)*percent)/100+min) var sub = this.calculation.accurateSubtraction(this.max, this.min); var mul = this.calculation.accurateMultiplication(sub, percent); var div = this.calculation.accurateDivisionTenExponent(mul, 2); - if(this.precision < 0){ + if(this.precision < 0) { var value = BI.parseFloat(this.calculation.accurateAddition(div, this.min)); var reduceValue = Math.round(this.calculation.accurateDivisionTenExponent(value, -this.precision)); return this.calculation.accurateMultiplication(reduceValue, Math.pow(10, -this.precision)); - }else{ - return BI.parseFloat(this.calculation.accurateAddition(div, this.min).toFixed(this.precision)); } + return BI.parseFloat(this.calculation.accurateAddition(div, this.min).toFixed(this.precision)); + }, _getPercentByValue: function (v) { @@ -6032,31 +6032,31 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { }, _getPrecision: function () { - //计算每一份值的精度(最大值和最小值的差值保留4为有效数字后的精度) - //如果差值的整数位数大于4,toPrecision(4)得到的是科学计数法123456 => 1.235e+5 - //返回非负值: 保留的小数位数 - //返回负值: 保留的10^n精度中的n + // 计算每一份值的精度(最大值和最小值的差值保留4为有效数字后的精度) + // 如果差值的整数位数大于4,toPrecision(4)得到的是科学计数法123456 => 1.235e+5 + // 返回非负值: 保留的小数位数 + // 返回负值: 保留的10^n精度中的n var sub = this.calculation.accurateSubtraction(this.max, this.min); var pre = sub.toPrecision(4); - //科学计数法 + // 科学计数法 var eIndex = pre.indexOf("e"); var arr = []; - if(eIndex > -1){ + if(eIndex > -1) { arr = pre.split("e"); var decimalPartLength = BI.size(arr[0].split(".")[1]); var sciencePartLength = BI.parseInt(arr[1].substring(1)); return decimalPartLength - sciencePartLength; - }else{ - arr = pre.split("."); - return arr.length > 1 ? arr[1].length : 0; } + arr = pre.split("."); + return arr.length > 1 ? arr[1].length : 0; + }, _assertValue: function (value) { - if(value <= this.min){ - return this.min + if(value <= this.min) { + return this.min; } - if(value >= this.max){ + if(value >= this.max) { return this.max; } return value; @@ -6064,10 +6064,10 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { getValue: function () { if (this.valueOne <= this.valueTwo) { - return {min: this.valueOne, max: this.valueTwo} - } else { - return {min: this.valueTwo, max: this.valueOne} + return {min: this.valueOne, max: this.valueTwo}; } + return {min: this.valueTwo, max: this.valueOne}; + }, setMinAndMax: function (v) { @@ -6130,7 +6130,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { } else { this.labelOne.setValue(this.min); this.labelTwo.setValue(this.max); - this._setAllPosition(0, 100) + this._setAllPosition(0, 100); } } } @@ -6145,7 +6145,7 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.AccurateCalculationModel.superclass._defaultConfig.apply(this, arguments), { baseCls: "" - }) + }); }, _init: function () { @@ -6166,16 +6166,16 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { } var magnitudeDiff = stringNumber1.numDecimalLength - stringNumber2.numDecimalLength; if (magnitudeDiff > 0) { - var needAddZero = stringNumber2 + var needAddZero = stringNumber2; } else { var needAddZero = stringNumber1; magnitudeDiff = (0 - magnitudeDiff); } for (var i = 0; i < magnitudeDiff; i++) { if (needAddZero.numDecimal === "0" && i === 0) { - continue + continue; } - needAddZero.numDecimal += "0" + needAddZero.numDecimal += "0"; } }, @@ -6191,25 +6191,25 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var numDecimalLength = numStrArray[1].length; } return { - "numInteger": numInteger, - "numDecimal": numDecimal, - "numDecimalLength": numDecimalLength - } + numInteger: numInteger, + numDecimal: numDecimal, + numDecimalLength: numDecimalLength + }; }, - _accurateSubtraction: function (num1, num2) {//num1-num2 && num1>num2 + _accurateSubtraction: function (num1, num2) {// num1-num2 && num1>num2 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) - BI.parseInt(stringNumber2.numInteger); - //小数部分 + // 小数部分 this._formatDecimal(stringNumber1, stringNumber2); var decimalMaxLength = getDecimalMaxLength(stringNumber1, stringNumber2); if (BI.parseInt(stringNumber1.numDecimal) >= BI.parseInt(stringNumber2.numDecimal)) { var decimalResultTemp = (BI.parseInt(stringNumber1.numDecimal) - BI.parseInt(stringNumber2.numDecimal)).toString(); var decimalResult = addZero(decimalResultTemp, decimalMaxLength); - } else {//否则借位 + } else {// 否则借位 integerResult--; var borrow = this._getMagnitude(decimalMaxLength); var decimalResultTemp = (borrow + BI.parseInt(stringNumber1.numDecimal) - BI.parseInt(stringNumber2.numDecimal)).toString(); @@ -6218,62 +6218,62 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var result = integerResult + "." + decimalResult; return BI.parseFloat(result); - function getDecimalMaxLength(num1, num2) { + function getDecimalMaxLength (num1, num2) { if (num1.numDecimal.length >= num2.numDecimal.length) { - return num1.numDecimal.length + return num1.numDecimal.length; } - return num2.numDecimal.length + return num2.numDecimal.length; } - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, - _accurateAddition: function (num1, num2) {//加法结合律 + _accurateAddition: function (num1, num2) {// 加法结合律 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) + BI.parseInt(stringNumber2.numInteger); - //小数部分 + // 小数部分 this._formatDecimal(stringNumber1, stringNumber2); var decimalResult = (BI.parseInt(stringNumber1.numDecimal) + BI.parseInt(stringNumber2.numDecimal)).toString(); if (decimalResult !== "0") { if (decimalResult.length <= stringNumber1.numDecimal.length) { - decimalResult = addZero(decimalResult, stringNumber1.numDecimal.length) + decimalResult = addZero(decimalResult, stringNumber1.numDecimal.length); } else { - integerResult++;//进一 + integerResult++;// 进一 decimalResult = decimalResult.slice(1); } } var result = integerResult + "." + decimalResult; return BI.parseFloat(result); - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, - _accurateMultiplication: function (num1, num2) {//乘法分配律 + _accurateMultiplication: function (num1, num2) {// 乘法分配律 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) * BI.parseInt(stringNumber2.numInteger); - //num1的小数和num2的整数 + // num1的小数和num2的整数 var dec1Int2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numDecimal) * BI.parseInt(stringNumber2.numInteger), stringNumber1.numDecimalLength); - //num1的整数和num2的小数 + // num1的整数和num2的小数 var int1dec2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numInteger) * BI.parseInt(stringNumber2.numDecimal), stringNumber2.numDecimalLength); - //小数*小数 + // 小数*小数 var dec1dec2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numDecimal) * BI.parseInt(stringNumber2.numDecimal), (stringNumber1.numDecimalLength + stringNumber2.numDecimalLength)); return this._accurateAddition(this._accurateAddition(this._accurateAddition(integerResult, dec1Int2), int1dec2), dec1dec2); @@ -6291,63 +6291,63 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var result = integerResult + "." + partDecimalResult + stringNumber.numDecimal; return BI.parseFloat(result); - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, accurateSubtraction: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { if (num1 >= num2) { - return this._accurateSubtraction(num1, num2) + return this._accurateSubtraction(num1, num2); } - return -this._accurateSubtraction(num2, num1) + return -this._accurateSubtraction(num2, num1); } if (num1 >= 0 && num2 < 0) { - return this._accurateAddition(num1, -num2) + return this._accurateAddition(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return -this._accurateAddition(-num1, num2) + return -this._accurateAddition(-num1, num2); } if (num1 < 0 && num2 < 0) { if (num1 >= num2) { - return this._accurateSubtraction(-num2, -num1) + return this._accurateSubtraction(-num2, -num1); } - return this._accurateSubtraction(-num1, -num2) + return this._accurateSubtraction(-num1, -num2); } }, accurateAddition: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { - return this._accurateAddition(num1, num2) + return this._accurateAddition(num1, num2); } if (num1 >= 0 && num2 < 0) { - return this.accurateSubtraction(num1, -num2) + return this.accurateSubtraction(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return this.accurateSubtraction(num2, -num1) + return this.accurateSubtraction(num2, -num1); } if (num1 < 0 && num2 < 0) { - return -this._accurateAddition(-num1, -num2) + return -this._accurateAddition(-num1, -num2); } }, accurateMultiplication: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { - return this._accurateMultiplication(num1, num2) + return this._accurateMultiplication(num1, num2); } if (num1 >= 0 && num2 < 0) { - return -this._accurateMultiplication(num1, -num2) + return -this._accurateMultiplication(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return -this._accurateMultiplication(-num1, num2) + return -this._accurateMultiplication(-num1, num2); } if (num1 < 0 && num2 < 0) { - return this._accurateMultiplication(-num1, -num2) + return this._accurateMultiplication(-num1, -num2); } }, @@ -6441,7 +6441,7 @@ BI.MonthCombo = BI.inherit(BI.Widget, { BI.MonthCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.MonthCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.month_combo', BI.MonthCombo);/** +BI.shortcut("bi.month_combo", BI.MonthCombo);/** * 月份展示面板 * * Created by GUY on 2015/9/2. @@ -6461,7 +6461,7 @@ BI.MonthPopup = BI.inherit(BI.Widget, { BI.MonthPopup.superclass._init.apply(this, arguments); var self = this, o = this.options; - //纵向排列月 + // 纵向排列月 var month = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; var items = []; items.push(month.slice(0, 2)); @@ -6511,7 +6511,7 @@ BI.MonthPopup = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MonthPopup.EVENT_CHANGE); } - }) + }); }, getValue: function () { @@ -6587,7 +6587,7 @@ BI.MonthTrigger = BI.inherit(BI.Trigger, { }); BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -6610,7 +6610,7 @@ BI.MonthTrigger = BI.inherit(BI.Trigger, { }); }, setValue: function (v) { - if(BI.isNotNull(v)){ + if(BI.isNotNull(v)) { this.editor.setState(v + 1); this.editor.setValue(v + 1); this.editor.setTitle(v + 1); @@ -6664,17 +6664,17 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { var self = this, opts = this.options; this.label = BI.createWidget({ - type: 'bi.label', + type: "bi.label", height: this.constants.itemHeight, textAlign: "left", text: BI.i18nText("BI-Multi_Date_Relative_Current_Time"), - cls: 'bi-multidate-inner-label bi-tips' + cls: "bi-multidate-inner-label bi-tips" }); this.radioGroup = BI.createWidget({ type: "bi.button_group", chooseType: 0, items: BI.createItems(this.dateConfig(), { - type: 'bi.multidate_segment', + type: "bi.multidate_segment", height: this.constants.itemHeight }), layouts: [{ @@ -6693,10 +6693,10 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { }); BI.createWidget({ element: this, - type: 'bi.center_adapt', + type: "bi.center_adapt", lgap: this.constants.lgap, items: [{ - type: 'bi.vertical', + type: "bi.vertical", items: [this.label, this.radioGroup] }] }); @@ -6708,7 +6708,7 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { return { type: type, value: value - } + }; }, _isTypeAvaliable: function (type) { @@ -6799,7 +6799,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { }, _defaultConfig: function () { return BI.extend(BI.MultiDateCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-combo bi-border', + baseCls: "bi-multidate-combo bi-border", height: 24 }); }, @@ -6810,7 +6810,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { var date = Date.getDate(); this.storeValue = null; this.trigger = BI.createWidget({ - type: 'bi.date_trigger', + type: "bi.date_trigger", min: this.constants.DATE_MIN_VALUE, max: this.constants.DATE_MAX_VALUE }); @@ -6891,11 +6891,11 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.popup.on(BI.MultiDatePopup.CALENDAR_EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); self.combo.hideView(); - //self.fireEvent(BI.MultiDateCombo.EVENT_CHANGE); + // self.fireEvent(BI.MultiDateCombo.EVENT_CHANGE); self.fireEvent(BI.MultiDateCombo.EVENT_CONFIRM); }); this.combo = BI.createWidget({ - type: 'bi.combo', + type: "bi.combo", toggle: false, isNeedAdjustHeight: false, isNeedAdjustWidth: false, @@ -6959,13 +6959,13 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { ref: function (_ref) { self.comboWrapper = _ref; } - }) + }); }, _checkDynamicValue: function (v) { var type = null; if (BI.isNotNull(v)) { - type = v.type + type = v.type; } switch (type) { case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV: @@ -7001,7 +7001,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.storeValue = v; this.popup.setValue(v); this.trigger.setValue(v); - this._checkDynamicValue(v) + this._checkDynamicValue(v); }, getValue: function () { return this.storeValue; @@ -7013,7 +7013,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.combo.hideView(); } }); -BI.shortcut('bi.multidate_combo', BI.MultiDateCombo); +BI.shortcut("bi.multidate_combo", BI.MultiDateCombo); BI.MultiDateCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.MultiDateCombo.EVENT_FOCUS = "EVENT_FOCUS"; @@ -7073,7 +7073,7 @@ BI.DayCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.DayCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-daycard' + baseCls: "bi-multidate-daycard" }); }, @@ -7088,24 +7088,24 @@ BI.DayCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Day_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Day_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY, - text: BI.i18nText("BI-Multi_Date_Today") - }]; + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Day_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY, + text: BI.i18nText("BI-Multi_Date_Today") + }]; }, defaultSelectedItem: function () { - return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV + return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV; } }); BI.DayCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.daycard', BI.DayCard); +BI.shortcut("bi.daycard", BI.DayCard); /** * 普通控件 * @@ -7115,7 +7115,7 @@ BI.shortcut('bi.daycard', BI.DayCard); BI.MonthCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.MonthCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-monthcard' + baseCls: "bi-multidate-monthcard" }); }, @@ -7130,21 +7130,21 @@ BI.MonthCard = BI.inherit(BI.MultiDateCard, { value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_PREV, text: BI.i18nText("BI-Multi_Date_Month_Prev") }, - { - isEditorExist: true, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER, - text: BI.i18nText("BI-Multi_Date_Month_Next") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Month_Begin") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Month_End") - }]; + { + isEditorExist: true, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER, + text: BI.i18nText("BI-Multi_Date_Month_Next") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Month_Begin") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Month_End") + }]; }, defaultSelectedItem: function () { @@ -7152,7 +7152,7 @@ BI.MonthCard = BI.inherit(BI.MultiDateCard, { } }); BI.MonthCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.monthcard', BI.MonthCard); +BI.shortcut("bi.monthcard", BI.MonthCard); /** * 日期控件 * @class BI.MultiDatePopup @@ -7178,7 +7178,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { }, _defaultConfig: function () { return BI.extend(BI.MultiDatePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-popup', + baseCls: "bi-multidate-popup", width: 268, height: 260 }); @@ -7188,9 +7188,9 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { var self = this, opts = this.options; this.storeValue = ""; this.textButton = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-label bi-border-left bi-border-right bi-border-top', + cls: "bi-multidate-popup-label bi-border-left bi-border-right bi-border-top", shadow: true, text: BI.i18nText("BI-Multi_Date_Today") }); @@ -7200,7 +7200,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { this.clearButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-button bi-border-top', + cls: "bi-multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_Clear") }); @@ -7210,7 +7210,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { this.okButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-button bi-border-top', + cls: "bi-multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_OK") }); @@ -7218,7 +7218,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { self.fireEvent(BI.MultiDatePopup.BUTTON_OK_EVENT_CHANGE); }); this.dateTab = BI.createWidget({ - type: 'bi.tab', + type: "bi.tab", tab: { cls: "bi-multidate-popup-tab bi-border-bottom", height: this.constants.tabHeight, @@ -7245,10 +7245,10 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { width: this.constants.tabWidth, textAlign: "center", height: this.constants.itemHeight, - cls: 'bi-multidate-popup-item bi-list-item-active' + cls: "bi-multidate-popup-item bi-list-item-active" }), layouts: [{ - type: 'bi.left' + type: "bi.left" }] }, cardCreator: function (v) { @@ -7273,7 +7273,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.year; case BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD: self.quarter = BI.createWidget({ - type: 'bi.quartercard' + type: "bi.quartercard" }); self.quarter.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.quarter, v); @@ -7281,7 +7281,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.quarter; case BI.MultiDateCombo.MULTI_DATE_MONTH_CARD: self.month = BI.createWidget({ - type: 'bi.monthcard' + type: "bi.monthcard" }); self.month.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.month, v); @@ -7289,7 +7289,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.month; case BI.MultiDateCombo.MULTI_DATE_WEEK_CARD: self.week = BI.createWidget({ - type: 'bi.weekcard' + type: "bi.weekcard" }); self.week.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.week, v); @@ -7297,7 +7297,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.week; case BI.MultiDateCombo.MULTI_DATE_DAY_CARD: self.day = BI.createWidget({ - type: 'bi.daycard' + type: "bi.daycard" }); self.day.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.day, v); @@ -7469,7 +7469,7 @@ BI.MultiDatePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; BI.MultiDatePopup.BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; BI.MultiDatePopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; BI.MultiDatePopup.CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE"; -BI.shortcut('bi.multidate_popup', BI.MultiDatePopup); +BI.shortcut("bi.multidate_popup", BI.MultiDatePopup); /** * 普通控件 * @@ -7480,7 +7480,7 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.QuarterCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-quartercard' + baseCls: "bi-multidate-quartercard" }); }, @@ -7495,21 +7495,21 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { isEditorExist: true, text: BI.i18nText("BI-Multi_Date_Quarter_Prev") }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER, - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Quarter_Next") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Quarter_Begin") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Quarter_End") - }] + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER, + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Quarter_Next") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Quarter_Begin") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Quarter_End") + }]; }, defaultSelectedItem: function () { @@ -7517,7 +7517,7 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { } }); BI.QuarterCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.quartercard', BI.QuarterCard); +BI.shortcut("bi.quartercard", BI.QuarterCard); /** * 普通控件 * @@ -7535,7 +7535,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.MultiDateSegment.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-segment', + baseCls: "bi-multidate-segment", text: "", height: 30, isEditorExist: true, @@ -7555,13 +7555,13 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); this.textEditor = BI.createWidget({ - type: 'bi.text_editor', + type: "bi.text_editor", value: this.constants.defaultEditorValue, title: function () { return self.textEditor.getValue(); }, tipType: "success", - cls: 'bi-multidate-editor', + cls: "bi-multidate-editor", width: this.constants.textWidth, height: this.constants.itemHeight }); @@ -7571,7 +7571,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { this.text = BI.createWidget({ type: "bi.label", textAlign: "left", - cls: 'bi-multidate-normal-label', + cls: "bi-multidate-normal-label", text: opts.text, height: this.constants.itemHeight }); @@ -7581,7 +7581,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { if (this.options.isEditorExist === true) { return BI.createWidget({ element: this, - type: 'bi.left', + type: "bi.left", items: [{ el: { type: "bi.center_adapt", @@ -7590,23 +7590,23 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { }, lgap: 0 }, - { - el: { - type: "bi.center_adapt", - items: [this.textEditor], - widgetName: 'textEditor' - }, - lgap: this.constants.maxGap + { + el: { + type: "bi.center_adapt", + items: [this.textEditor], + widgetName: "textEditor" }, - { - el: this.text, - lgap: this.constants.minGap - }] + lgap: this.constants.maxGap + }, + { + el: this.text, + lgap: this.constants.minGap + }] }); } return BI.createWidget({ element: this, - type: 'bi.left', + type: "bi.left", items: [{ el: { type: "bi.center_adapt", @@ -7615,11 +7615,11 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { }, lgap: 0 }, - { - el: this.text, - lgap: this.constants.maxGap - }] - }) + { + el: this.text, + lgap: this.constants.maxGap + }] + }); }, setSelected: function (v) { if (BI.isNotNull(this.radio)) { @@ -7644,7 +7644,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { } }); BI.MultiDateSegment.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multidate_segment', BI.MultiDateSegment);/** +BI.shortcut("bi.multidate_segment", BI.MultiDateSegment);/** * 普通控件 * * @class BI.WeekCard @@ -7653,7 +7653,7 @@ BI.shortcut('bi.multidate_segment', BI.MultiDateSegment);/** BI.WeekCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.WeekCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-weekcard' + baseCls: "bi-multidate-weekcard" }); }, @@ -7668,11 +7668,11 @@ BI.WeekCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Week_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Week_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER - }]; + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Week_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER + }]; }, defaultSelectedItem: function () { @@ -7680,7 +7680,7 @@ BI.WeekCard = BI.inherit(BI.MultiDateCard, { } }); BI.WeekCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.weekcard', BI.WeekCard); +BI.shortcut("bi.weekcard", BI.WeekCard); /** * 普通控件 * @@ -7690,7 +7690,7 @@ BI.shortcut('bi.weekcard', BI.WeekCard); BI.YearCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.YearCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-yearcard' + baseCls: "bi-multidate-yearcard" }); }, @@ -7705,21 +7705,21 @@ BI.YearCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Year_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Year_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN, - text: BI.i18nText("BI-Multi_Date_Year_Begin") - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END, - text: BI.i18nText("BI-Multi_Date_Year_End") - }] + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Year_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN, + text: BI.i18nText("BI-Multi_Date_Year_Begin") + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END, + text: BI.i18nText("BI-Multi_Date_Year_End") + }]; }, defaultSelectedItem: function () { @@ -7727,7 +7727,7 @@ BI.YearCard = BI.inherit(BI.MultiDateCard, { } }); BI.YearCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.yearcard', BI.YearCard); +BI.shortcut("bi.yearcard", BI.YearCard); /** * @class BI.MultiLayerSelectTreeCombo * @extends BI.Widget @@ -7810,7 +7810,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { isDefaultInit: false, items: [], itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -7862,7 +7862,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -7895,7 +7895,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MultiLayerSelectLevelTree.EVENT_CHANGE, arguments); } - }) + }); }, populate: function (nodes) { @@ -7949,7 +7949,7 @@ BI.MultiLayerSelectTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.multilayer_select_level_tree', + type: "bi.multilayer_select_level_tree", isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator @@ -8002,13 +8002,13 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-first-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -8041,7 +8041,7 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -8049,7 +8049,7 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, isOnce: function () { @@ -8096,13 +8096,13 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-last-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -8135,7 +8135,7 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -8143,7 +8143,7 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -8186,13 +8186,13 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-mid-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._init.apply(this, arguments); @@ -8225,7 +8225,7 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -8233,7 +8233,7 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -8351,7 +8351,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { isDefaultInit: false, items: [], itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -8403,7 +8403,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -8422,8 +8422,8 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { items: this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0), itemsCreator: function (op, callback) { o.itemsCreator(op, function (items) { - callback(BI.Tree.transformToTreeFormat(items), 0) - }) + callback(BI.Tree.transformToTreeFormat(items), 0); + }); }, el: { @@ -8439,7 +8439,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MultiLayerSingleLevelTree.EVENT_CHANGE, v); } - }) + }); }, populate: function (nodes) { @@ -8494,7 +8494,7 @@ BI.MultiLayerSingleTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.multilayer_single_level_tree', + type: "bi.multilayer_single_level_tree", isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator @@ -8547,12 +8547,12 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-first-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -8573,7 +8573,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -8586,7 +8586,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -8594,7 +8594,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -8630,12 +8630,12 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-last-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -8656,7 +8656,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -8669,7 +8669,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -8677,7 +8677,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -8713,12 +8713,12 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-mid-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._init.apply(this, arguments); @@ -8739,7 +8739,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -8752,7 +8752,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -8760,7 +8760,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -8801,7 +8801,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._init.apply(this, arguments); @@ -8821,7 +8821,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -8834,7 +8834,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -8842,7 +8842,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -8897,7 +8897,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._init.apply(this, arguments); @@ -8917,7 +8917,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -8930,7 +8930,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -8938,7 +8938,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -8993,7 +8993,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._init.apply(this, arguments); @@ -9013,7 +9013,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -9026,7 +9026,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -9034,7 +9034,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { @@ -9102,7 +9102,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { this.storeValue = {}; this.display = BI.createWidget({ - type: 'bi.display_selected_list', + type: "bi.display_selected_list", items: opts.items, itemsCreator: function (op, callback) { op = BI.extend(op || {}, { @@ -9116,7 +9116,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { text: txt, value: v, title: txt - } + }; }) }); return; @@ -9126,9 +9126,9 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }); this.continueSelect = BI.createWidget({ - type: 'bi.text_button', - text: BI.i18nText('BI-Continue_Select'), - cls: 'multi-select-check-selected bi-high-light' + type: "bi.text_button", + text: BI.i18nText("BI-Continue_Select"), + cls: "multi-select-check-selected bi-high-light" }); this.continueSelect.on(BI.TextButton.EVENT_CHANGE, function () { @@ -9136,18 +9136,18 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }); BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", element: this, items: [{ height: this.constants.height, el: { - type: 'bi.left', - cls: 'multi-select-continue-select', + type: "bi.left", + cls: "multi-select-continue-select", items: [ { el: { type: "bi.label", - text: BI.i18nText('BI-Selected_Data') + text: BI.i18nText("BI-Selected_Data") }, lgap: this.constants.lgap, tgap: this.constants.tgap @@ -9159,7 +9159,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }] } }, { - height: 'fill', + height: "fill", el: this.display }] }); @@ -9229,7 +9229,7 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { opts.itemsCreator(options, function (ob) { self.hasNext = !!ob.hasNext; callback(self._createItems(ob.items)); - }) + }); }, hasNext: function () { return self.hasNext; @@ -9239,8 +9239,8 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { _createItems: function (items) { return BI.createItems(items, { - type: 'bi.icon_text_item', - cls: 'cursor-default check-font display-list-item bi-tips', + type: "bi.icon_text_item", + cls: "cursor-default check-font display-list-item bi-tips", once: true, invalid: true, selected: true, @@ -9264,7 +9264,7 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { } }); -BI.shortcut('bi.display_selected_list', BI.DisplaySelectedList);/** +BI.shortcut("bi.display_selected_list", BI.DisplaySelectedList);/** * * @class BI.MultiSelectInsertCombo * @extends BI.Single @@ -9273,7 +9273,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiSelectInsertCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-insert-combo', + baseCls: "bi-multi-select-insert-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -9290,7 +9290,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { self.trigger.getCounter().setButtonChecked(self.storeValue); }; this.storeValue = {}; - //标记正在请求数据 + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -9309,7 +9309,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(BI.deepClone(self.getValue())); } callback.apply(self, arguments); @@ -9331,7 +9331,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { type: BI.Selection.Multi, value: [keyword] }, function () { - //如果在不选的状态下直接把该值添加进来 + // 如果在不选的状态下直接把该值添加进来 if (self.storeValue.type === BI.Selection.Multi) { self.storeValue.value.pushDistinct(keyword); } @@ -9340,7 +9340,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); // } }); this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -9387,7 +9387,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_select_popup_view', + type: "bi.multi_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -9434,10 +9434,10 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -9475,7 +9475,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -9505,7 +9505,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -9551,14 +9551,14 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { var self = this, o = this.options; adjust(); callback(); - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.MultiSelectInsertCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -9620,7 +9620,7 @@ BI.extend(BI.MultiSelectInsertCombo, { BI.MultiSelectInsertCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.multi_select_insert_combo', BI.MultiSelectInsertCombo);/** +BI.shortcut("bi.multi_select_insert_combo", BI.MultiSelectInsertCombo);/** * * @class BI.MultiSelectCombo * @extends BI.Single @@ -9629,7 +9629,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-combo', + baseCls: "bi-multi-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -9646,7 +9646,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { self.trigger.getCounter().setButtonChecked(self.storeValue); }; this.storeValue = {}; - //标记正在请求数据 + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -9665,7 +9665,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(BI.deepClone(self.getValue())); } callback.apply(self, arguments); @@ -9692,7 +9692,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -9739,7 +9739,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_select_popup_view', + type: "bi.multi_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -9786,10 +9786,10 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -9827,7 +9827,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -9857,7 +9857,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -9903,7 +9903,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -9922,17 +9922,17 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.storeValue.type === BI.Selection.All && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.Multi, value: [] - } + }; } else if (self.storeValue.type === BI.Selection.Multi && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.All, value: [] - } + }; } if (self.wants2Quit === true) { self.fireEvent(BI.MultiSelectCombo.EVENT_CONFIRM); @@ -9996,7 +9996,7 @@ BI.extend(BI.MultiSelectCombo, { BI.MultiSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.multi_select_combo', BI.MultiSelectCombo);/** +BI.shortcut("bi.multi_select_combo", BI.MultiSelectCombo);/** * 多选加载数据面板 * Created by guy on 15/11/2. * @class BI.MultiSelectLoader @@ -10006,7 +10006,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-loader', + baseCls: "bi-multi-select-loader", logic: { dynamic: true }, @@ -10068,7 +10068,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: self.storeValue.type === BI.Selection.Multi - } + }; }); if (BI.isKey(self._startValue) && !self.storeValue.value.contains(self._startValue)) { var txt = opts.valueFormatter(startValue) || startValue; @@ -10077,7 +10077,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { value: startValue, title: txt, selected: true - }) + }); } firstItems = self._createItems(json); } @@ -10107,7 +10107,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { logic: this.options.logic, height: 25, selected: this.isAllSelected() - }) + }); }, _scrollToTop: function () { @@ -10163,7 +10163,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { }); BI.MultiSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_loader', BI.MultiSelectLoader);/** +BI.shortcut("bi.multi_select_loader", BI.MultiSelectLoader);/** * 带加载的多选下拉面板 * @class BI.MultiSelectPopupView * @extends Widget @@ -10172,8 +10172,8 @@ BI.MultiSelectPopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectPopupView.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-popup-view', - maxWidth: 'auto', + baseCls: "bi-multi-select-popup-view", + maxWidth: "auto", minWidth: 135, maxHeight: 400, valueFormatter: BI.emptyFn, @@ -10200,7 +10200,7 @@ BI.MultiSelectPopupView = BI.inherit(BI.Widget, { minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.loader }); @@ -10253,7 +10253,7 @@ BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; BI.MultiSelectPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.shortcut('bi.multi_select_popup_view', BI.MultiSelectPopupView);/** +BI.shortcut("bi.multi_select_popup_view", BI.MultiSelectPopupView);/** * * 复选下拉框 * @class BI.MultiSelectTrigger @@ -10314,7 +10314,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { self.fireEvent(BI.MultiSelectTrigger.EVENT_CHANGE, arguments); }); this.numberCounter = BI.createWidget(o.switcher, { - type: 'bi.multi_select_check_selected_switcher', + type: "bi.multi_select_check_selected_switcher", valueFormatter: o.valueFormatter, itemsCreator: o.itemsCreator, adapter: o.adapter, @@ -10328,7 +10328,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapNumberCounter = BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", hgap: 4, items: [{ el: this.numberCounter @@ -10336,12 +10336,12 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: wrapNumberCounter, width: 0 @@ -10352,7 +10352,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {//自动调整宽度 + BI.nextTick(function () {// 自动调整宽度 wrapper.attr("items")[1].width = (b === true ? self.numberCounter.element.outerWidth() + 8 : 0); wrapper.resize(); }); @@ -10406,7 +10406,7 @@ BI.MultiSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.MultiSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.multi_select_trigger', BI.MultiSelectTrigger);/** +BI.shortcut("bi.multi_select_trigger", BI.MultiSelectTrigger);/** * 多选加载数据搜索loader面板 * Created by guy on 15/11/4. * @class BI.MultiSelectSearchLoader @@ -10416,7 +10416,7 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-search-loader', + baseCls: "bi-multi-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -10495,7 +10495,7 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: this.isAllSelected() - }) + }); }, isAllSelected: function () { @@ -10522,12 +10522,12 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: src.type === BI.Selection.All - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = BI.deepClone(v); this.button_group.setValue(v); }, @@ -10558,7 +10558,7 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.MultiSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_search_loader', BI.MultiSelectSearchLoader);/** +BI.shortcut("bi.multi_select_search_loader", BI.MultiSelectSearchLoader);/** * * 在搜索框中输入文本弹出的面板 * @class BI.MultiSelectSearchPane @@ -10589,8 +10589,8 @@ BI.MultiSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'multi-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "multi-select-toolbar", height: this.constants.height }); @@ -10668,12 +10668,12 @@ BI.shortcut("bi.multi_select_search_pane", BI.MultiSelectSearchPane);/** BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiSelectCheckSelectedButton.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-check-selected-button bi-high-light', + baseCls: "bi-multi-select-check-selected-button bi-high-light", itemsCreator: BI.emptyFn }); }, @@ -10682,11 +10682,11 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { BI.MultiSelectCheckSelectedButton.superclass._init.apply(this, arguments); var self = this; this.numberCounter = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", element: this, hgap: 4, text: "0", - textAlign: 'center', + textAlign: "center", textHeight: 15 }); this.numberCounter.on(BI.Controller.EVENT_CHANGE, function () { @@ -10716,17 +10716,17 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { type: BI.MultiSelectCombo.REQ_GET_DATA_LENGTH }, function (res) { var length = res.count - ob.value.length; - BI.nextTick(function(){ + BI.nextTick(function () { self.numberCounter.setText(length); self.setVisible(length > 0); }); }); return; } - BI.nextTick(function(){ + BI.nextTick(function () { self.numberCounter.setText(ob.value.length); self.setVisible(ob.value.length > 0); - }) + }); }, getValue: function () { @@ -10735,7 +10735,7 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { }); BI.MultiSelectCheckSelectedButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_check_selected_button', BI.MultiSelectCheckSelectedButton);/** +BI.shortcut("bi.multi_select_check_selected_button", BI.MultiSelectCheckSelectedButton);/** * 多选输入框 * Created by guy on 15/11/3. * @class BI.MultiSelectEditor @@ -10744,12 +10744,12 @@ BI.shortcut('bi.multi_select_check_selected_button', BI.MultiSelectCheckSelected BI.MultiSelectEditor = BI.inherit(BI.Widget, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiSelectEditor.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-editor', + baseCls: "bi-multi-select-editor", el: {} }); }, @@ -10758,10 +10758,10 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { BI.MultiSelectEditor.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.state_editor', + type: "bi.state_editor", element: this, height: o.height, - watermark: BI.i18nText('BI-Basic_Search'), + watermark: BI.i18nText("BI-Basic_Search"), allowBlank: true }); @@ -10797,16 +10797,16 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { var v = this.editor.getState(); if (BI.isArray(v) && v.length > 0) { return v[v.length - 1]; - } else { - return ""; } + return ""; + }, getKeywords: function () { var val = this.editor.getLastValidValue(); var keywords = val.match(/[\S]+/g); if (BI.isEndWithBlank(val)) { - return keywords.concat([' ']); + return keywords.concat([" "]); } return keywords; }, @@ -10816,7 +10816,7 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { } }); BI.MultiSelectEditor.EVENT_PAUSE = "MultiSelectEditor.EVENT_PAUSE"; -BI.shortcut('bi.multi_select_editor', BI.MultiSelectEditor);/** +BI.shortcut("bi.multi_select_editor", BI.MultiSelectEditor);/** * searcher * Created by guy on 15/11/3. * @class BI.MultiSelectSearcher @@ -10826,7 +10826,7 @@ BI.MultiSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-searcher', + baseCls: "bi-multi-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -10840,7 +10840,7 @@ BI.MultiSelectSearcher = BI.inherit(BI.Widget, { BI.MultiSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.multi_select_editor', + type: "bi.multi_select_editor", height: o.height }); @@ -10983,7 +10983,7 @@ BI.MultiSelectSearcher.EVENT_START = "EVENT_START"; BI.MultiSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.MultiSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.MultiSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.multi_select_searcher', BI.MultiSelectSearcher);/** +BI.shortcut("bi.multi_select_searcher", BI.MultiSelectSearcher);/** * 查看已选switcher * Created by guy on 15/11/3. * @class BI.MultiSelectCheckSelectedSwitcher @@ -10993,7 +10993,7 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectCheckSelectedSwitcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-check-selected-switcher', + baseCls: "bi-multi-select-check-selected-switcher", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, el: {}, @@ -11066,7 +11066,7 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { }, setButtonChecked: function (v) { - this.button.setValue(v) + this.button.setValue(v); }, getValue: function () { @@ -11080,16 +11080,16 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE = "MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE"; BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW = "MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.multi_select_check_selected_switcher', BI.MultiSelectCheckSelectedSwitcher);/** +BI.shortcut("bi.multi_select_check_selected_switcher", BI.MultiSelectCheckSelectedSwitcher);/** * Created by zcf_1 on 2017/5/2. */ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectInsertList.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-insert-list', + baseCls: "bi-multi-select-insert-list", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn - }) + }); }, _init: function () { BI.MultiSelectInsertList.superclass._init.apply(this, arguments); @@ -11115,8 +11115,8 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }); this.adapter.on(BI.MultiSelectLoader.EVENT_CHANGE, function () { self.storeValue = this.getValue(); - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); + assertShowValue(); + self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); }); this.searcherPane = BI.createWidget({ @@ -11158,7 +11158,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { self._showAdapter(); self._setStartValue(""); self.adapter.setValue(self.storeValue); - //需要刷新回到初始界面,否则搜索的结果不能放在最前面 + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 self.adapter.populate(); } }, { @@ -11171,7 +11171,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { value: [keyword] }, function () { if (self.storeValue.type === BI.Selection.Multi) { - self.storeValue.value.pushDistinct(keyword) + self.storeValue.value.pushDistinct(keyword); } self._showAdapter(); self.adapter.setValue(self.storeValue); @@ -11180,10 +11180,10 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { self.adapter.populate(); self._setStartValue(""); self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); - }) + }); } else { if (self.storeValue.type === BI.Selection.Multi) { - self.storeValue.value.pushDistinct(keyword) + self.storeValue.value.pushDistinct(keyword); } self._showAdapter(); self.adapter.setValue(self.storeValue); @@ -11252,7 +11252,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, _showAdapter: function () { @@ -11288,12 +11288,12 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }, function (ob) { self._allData = BI.pluck(ob.items, "value"); digest(self._allData); - }) + }); } else { - digest(this._allData) + digest(this._allData); } - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -11338,7 +11338,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); callback(); - }) + }); }, _join: function (res, callback) { @@ -11411,10 +11411,10 @@ BI.shortcut("bi.multi_select_insert_list", BI.MultiSelectInsertList);/** BI.MultiSelectList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectList.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-list', + baseCls: "bi-multi-select-list", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn - }) + }); }, _init: function () { BI.MultiSelectList.superclass._init.apply(this, arguments); @@ -11485,7 +11485,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { self._showAdapter(); self._setStartValue(""); self.adapter.setValue(self.storeValue); - //需要刷新回到初始界面,否则搜索的结果不能放在最前面 + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 self.adapter.populate(); } }, { @@ -11504,7 +11504,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { self.adapter.populate(); self._setStartValue(""); self.fireEvent(BI.MultiSelectList.EVENT_CHANGE); - }) + }); } } }, { @@ -11566,7 +11566,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, _showAdapter: function () { @@ -11602,12 +11602,12 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { }, function (ob) { self._allData = BI.pluck(ob.items, "value"); digest(self._allData); - }) + }); } else { - digest(this._allData) + digest(this._allData); } - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -11652,7 +11652,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -11670,17 +11670,17 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { callback(); } - function adjust() { + function adjust () { if (self.storeValue.type === BI.Selection.All && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.Multi, value: [] - } + }; } else if (self.storeValue.type === BI.Selection.Multi && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.All, value: [] - } + }; } } }, @@ -11755,9 +11755,9 @@ BI.shortcut("bi.multi_select_list", BI.MultiSelectList);/** BI.MultiSelectTree = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectTree.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-tree', + baseCls: "bi-multi-select-tree", itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -11779,7 +11779,7 @@ BI.MultiSelectTree = BI.inherit(BI.Widget, { self.fireEvent(BI.MultiSelectTree.EVENT_CHANGE); }); - //搜索中的时候用的是parttree,同adapter中的synctree不一样 + // 搜索中的时候用的是parttree,同adapter中的synctree不一样 this.searcherPane = BI.createWidget({ type: "bi.multi_tree_search_pane", cls: "bi-border-left bi-border-right bi-border-bottom", @@ -11862,7 +11862,7 @@ BI.MultiSelectTree = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, @@ -11930,10 +11930,10 @@ BI.MultiSelectTreePopup = BI.inherit(BI.Widget, { itemsCreator: o.itemsCreator }); this.popup.on(BI.TreeView.EVENT_AFTERINIT, function () { - self.fireEvent(BI.MultiSelectTreePopup.EVENT_AFTER_INIT) + self.fireEvent(BI.MultiSelectTreePopup.EVENT_AFTER_INIT); }); this.popup.on(BI.TreeView.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectTreePopup.EVENT_CHANGE) + self.fireEvent(BI.MultiSelectTreePopup.EVENT_CHANGE); }); }, @@ -11995,9 +11995,9 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { this.selectedValues = {}; var continueSelect = BI.createWidget({ - type: 'bi.text_button', - text: BI.i18nText('BI-Continue_Select'), - cls: 'multi-tree-check-selected' + type: "bi.text_button", + text: BI.i18nText("BI-Continue_Select"), + cls: "multi-tree-check-selected" }); continueSelect.on(BI.TextButton.EVENT_CHANGE, function () { opts.onClickContinueSelect(); @@ -12007,13 +12007,13 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { }); var backToPopup = BI.createWidget({ - type: 'bi.left', - cls: 'multi-tree-continue-select', + type: "bi.left", + cls: "multi-tree-continue-select", items: [ { el: { type: "bi.label", - text: BI.i18nText('BI-Selected_Data') + text: BI.i18nText("BI-Selected_Data") }, lgap: this.constants.lgap, tgap: this.constants.tgap @@ -12047,13 +12047,13 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { }); BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", element: this, items: [{ height: this.constants.height, el: backToPopup }, { - height: 'fill', + height: "fill", el: this.display }] }); @@ -12100,7 +12100,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiTreeCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-combo', + baseCls: "bi-multi-tree-combo", itemsCreator: BI.emptyFn, height: 25 }); @@ -12143,7 +12143,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_tree_popup_view', + type: "bi.multi_tree_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -12196,7 +12196,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { this.storeValue = {value: {}}; var change = false; - var clear = false; //标识当前是否点击了清空 + var clear = false; // 标识当前是否点击了清空 var isSearching = function () { return self.trigger.getSearcher().isSearching(); @@ -12220,7 +12220,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { }); }); - function showCounter() { + function showCounter () { if (isSearching()) { self.storeValue = {value: self.trigger.getValue()}; } else if (isPopupView()) { @@ -12316,7 +12316,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -12342,7 +12342,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { BI.MultiTreeCombo.EVENT_CONFIRM = "MultiTreeCombo.EVENT_CONFIRM"; -BI.shortcut('bi.multi_tree_combo', BI.MultiTreeCombo);/** +BI.shortcut("bi.multi_tree_combo", BI.MultiTreeCombo);/** * 带加载的多选下拉面板 * @class BI.MultiTreePopup * @extends BI.Pane @@ -12351,8 +12351,8 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { _defaultConfig: function () { return BI.extend(BI.MultiTreePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-popup', - maxWidth: 'auto', + baseCls: "bi-multi-tree-popup", + maxWidth: "auto", minWidth: 100, maxHeight: 400, onLoaded: BI.emptyFn @@ -12369,7 +12369,7 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { this.tree = BI.createWidget({ type: "bi.async_tree", height: 400, - cls:"popup-view-tree", + cls: "popup-view-tree", itemsCreator: opts.itemsCreator, onLoaded: opts.onLoaded }); @@ -12381,7 +12381,7 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { maxWidth: opts.maxWidth, minWidth: opts.minWidth, maxHeight: opts.maxHeight, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.tree }); @@ -12438,7 +12438,7 @@ BI.MultiTreePopup.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; BI.MultiTreePopup.EVENT_AFTERINIT = "EVENT_AFTERINIT"; -BI.shortcut('bi.multi_tree_popup_view', BI.MultiTreePopup);/** +BI.shortcut("bi.multi_tree_popup_view", BI.MultiTreePopup);/** * * 在搜索框中输入文本弹出的面板 * @class BI.MultiTreeSearchPane @@ -12519,12 +12519,12 @@ BI.shortcut("bi.multi_tree_search_pane", BI.MultiTreeSearchPane);/** BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiTreeCheckSelectedButton.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-check-selected-button', + baseCls: "bi-multi-tree-check-selected-button", itemsCreator: BI.emptyFn }); }, @@ -12533,20 +12533,20 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { BI.MultiTreeCheckSelectedButton.superclass._init.apply(this, arguments); var self = this; this.indicator = BI.createWidget({ - type: 'bi.icon_button', - cls: 'check-font trigger-check-selected', + type: "bi.icon_button", + cls: "check-font trigger-check-selected", width: 15, height: 15, stopPropagation: true }); this.checkSelected = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", cls: "trigger-check-selected", invisible: true, hgap: 4, text: this._const.checkSelected, - textAlign: 'center', + textAlign: "center", textHeight: 15 }); this.checkSelected.on(BI.Controller.EVENT_CHANGE, function () { @@ -12561,7 +12561,7 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { type: "bi.horizontal", element: this, items: [this.indicator, this.checkSelected] - }) + }); this.element.hover(function () { self.indicator.setVisible(false); @@ -12580,7 +12580,7 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { }); BI.MultiTreeCheckSelectedButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_tree_check_selected_button', BI.MultiTreeCheckSelectedButton);/** +BI.shortcut("bi.multi_tree_check_selected_button", BI.MultiTreeCheckSelectedButton);/** * searcher * Created by guy on 15/11/3. * @class BI.MultiTreeSearcher @@ -12590,7 +12590,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiTreeSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-searcher', + baseCls: "bi-multi-tree-searcher", itemsCreator: BI.emptyFn, popup: {}, @@ -12603,7 +12603,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { BI.MultiTreeSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget({ - type: 'bi.multi_select_editor', + type: "bi.multi_select_editor", height: o.height, el: { type: "bi.simple_state_editor", @@ -12698,7 +12698,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { this.editor.setState(text); } - function getChildrenNode(ob) { + function getChildrenNode (ob) { var text = ""; var index = 0, size = BI.size(ob); BI.each(ob, function (name, children) { @@ -12733,7 +12733,7 @@ BI.MultiTreeSearcher.EVENT_CHANGE = "EVENT_CHANGE"; BI.MultiTreeSearcher.EVENT_START = "EVENT_START"; BI.MultiTreeSearcher.EVENT_STOP = "EVENT_STOP"; BI.MultiTreeSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.shortcut('bi.multi_tree_searcher', BI.MultiTreeSearcher);/** +BI.shortcut("bi.multi_tree_searcher", BI.MultiTreeSearcher);/** * Created by windy on 2017/3/13. * 数值微调器 */ @@ -12751,7 +12751,7 @@ BI.NumberEditor = BI.inherit(BI.Widget, { allowBlank: false, errorText: "", step: 1 - }) + }); }, _init: function () { @@ -12815,7 +12815,7 @@ BI.NumberEditor = BI.inherit(BI.Widget, { }); }, - //微调 + // 微调 _finetuning: function (add) { var v = BI.parseFloat(this.getValue()); this.setValue(v.add(add)); @@ -12842,8 +12842,8 @@ BI.NumberEditor = BI.inherit(BI.Widget, { }); BI.NumberEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.NumberEditor.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut("bi.number_editor", BI.NumberEditor);//小于号的值为:0,小于等于号的值为:1 -//closeMIn:最小值的符号,closeMax:最大值的符号 +BI.shortcut("bi.number_editor", BI.NumberEditor);// 小于号的值为:0,小于等于号的值为:1 +// closeMIn:最小值的符号,closeMax:最大值的符号 /** * Created by roy on 15/9/17. * @@ -12864,16 +12864,16 @@ BI.NumberInterval = BI.inherit(BI.Single, { numTip: "" }, _defaultConfig: function () { - var conf = BI.NumberInterval.superclass._defaultConfig.apply(this, arguments) + var conf = BI.NumberInterval.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-number-interval", height: 25, validation: "valid" - }) + }); }, _init: function () { var self = this, c = this.constants, o = this.options; - BI.NumberInterval.superclass._init.apply(this, arguments) + BI.NumberInterval.superclass._init.apply(this, arguments); this.smallEditor = BI.createWidget({ type: "bi.editor", height: o.height - 2, @@ -12948,21 +12948,21 @@ BI.NumberInterval = BI.inherit(BI.Single, { }] }); - //this.smallCombo = BI.createWidget({ + // this.smallCombo = BI.createWidget({ // type: "bi.number_interval_combo", // cls: "number-interval-small-combo", // height: o.height, // value: o.closemin ? 1 : 0, // offsetStyle: "left" - //}); + // }); // - //this.bigCombo = BI.createWidget({ + // this.bigCombo = BI.createWidget({ // type: "bi.number_interval_combo", // cls: "number-interval-big-combo", // height: o.height, // value: o.closemax ? 1 : 0, // offsetStyle: "left" - //}); + // }); this.smallCombo = BI.createWidget({ type: "bi.icon_combo", cls: "number-interval-small-combo bi-border", @@ -13092,42 +13092,42 @@ BI.NumberInterval = BI.inherit(BI.Single, { self.element.removeClass("number-error"); o.validation = "invalid"; return c.typeError; - } else { - if (BI.isEmptyString(self.smallEditor.getValue()) || BI.isEmptyString(self.bigEditor.getValue())) { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } else { - var smallValue = parseFloat(self.smallEditor.getValue()), bigValue = parseFloat(self.bigEditor.getValue()), - bigComboValue = self.bigCombo.getValue(), smallComboValue = self.smallCombo.getValue(); - if (bigComboValue[0] === c.less_equal && smallComboValue[0] === c.less_equal) { - if (smallValue > bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.numberError; - } else { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } - } else { - if (smallValue > bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.numberError; - } else if (smallValue === bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.signalError; - } else { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } - } + } + if (BI.isEmptyString(self.smallEditor.getValue()) || BI.isEmptyString(self.bigEditor.getValue())) { + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + } + var smallValue = parseFloat(self.smallEditor.getValue()), bigValue = parseFloat(self.bigEditor.getValue()), + bigComboValue = self.bigCombo.getValue(), smallComboValue = self.smallCombo.getValue(); + if (bigComboValue[0] === c.less_equal && smallComboValue[0] === c.less_equal) { + if (smallValue > bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.numberError; } - + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + + } + if (smallValue > bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.numberError; + } else if (smallValue === bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.signalError; } + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + + + + + }, _setTitle: function (v) { @@ -13158,10 +13158,10 @@ BI.NumberInterval = BI.inherit(BI.Single, { }); break; default : - return + return; } - }) + }); }, _setBlurEvent: function (w) { var c = this.constants, self = this; @@ -13182,18 +13182,18 @@ BI.NumberInterval = BI.inherit(BI.Single, { default: self._setTitle(""); } - }) + }); }, _setErrorEvent: function (w) { - var c = this.constants, self = this + var c = this.constants, self = this; w.on(BI.Editor.EVENT_ERROR, function () { self._checkValidation(); BI.Bubbles.show(c.typeError, BI.i18nText("BI-Numerical_Interval_Input_Data"), self, { offsetStyle: "center" }); self.fireEvent(BI.NumberInterval.EVENT_ERROR); - }) + }); }, @@ -13216,7 +13216,7 @@ BI.NumberInterval = BI.inherit(BI.Single, { default: self.fireEvent(BI.NumberInterval.EVENT_VALID); } - }) + }); }, @@ -13266,7 +13266,7 @@ BI.NumberInterval = BI.inherit(BI.Single, { self.fireEvent(BI.NumberInterval.EVENT_CHANGE); self.fireEvent(BI.NumberInterval.EVENT_VALID); } - }) + }); }, isStateValid: function () { @@ -13299,12 +13299,12 @@ BI.NumberInterval = BI.inherit(BI.Single, { this.bigTip.setVisible(false); }, - setNumTip: function(numTip) { + setNumTip: function (numTip) { this.smallTip.setText(numTip); this.bigTip.setText(numTip); }, - getNumTip: function() { + getNumTip: function () { return this.smallTip.getText(); }, @@ -13329,18 +13329,18 @@ BI.NumberInterval = BI.inherit(BI.Single, { if (!BI.isNull(data.closemin)) { if (data.closemin === true) { - combo_value = 1 + combo_value = 1; } else { - combo_value = 0 + combo_value = 0; } self.smallCombo.setValue(combo_value); } if (!BI.isNull(data.closemax)) { if (data.closemax === true) { - combo_value = 1 + combo_value = 1; } else { - combo_value = 0 + combo_value = 0; } self.bigCombo.setValue(combo_value); } @@ -13352,15 +13352,15 @@ BI.NumberInterval = BI.inherit(BI.Single, { value.min = self.smallEditor.getValue(); value.max = self.bigEditor.getValue(); if (minComboValue[0] === 0) { - value.closemin = false + value.closemin = false; } else { - value.closemin = true + value.closemin = true; } if (maxComboValue[0] === 0) { - value.closemax = false + value.closemax = false; } else { - value.closemax = true + value.closemax = true; } return value; } @@ -13382,7 +13382,7 @@ BI.PageTableCell = BI.inherit(BI.Widget, { baseCls: "bi-page-table-cell", text: "", title: "" - }) + }); }, _init: function () { @@ -13428,8 +13428,8 @@ BI.PageTable = BI.inherit(BI.Widget, { }, pager: { horizontal: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -13437,8 +13437,8 @@ BI.PageTable = BI.inherit(BI.Widget, { lastPage: BI.emptyFn }, vertical: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -13449,11 +13449,11 @@ BI.PageTable = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -13469,9 +13469,9 @@ BI.PageTable = BI.inherit(BI.Widget, { sequenceCellStyleGetter: BI.emptyFn, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -13512,7 +13512,7 @@ BI.PageTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -13564,7 +13564,7 @@ BI.PageTable = BI.inherit(BI.Widget, { right: 0, bottom: 0 }] - }) + }); }, setHPage: function (v) { @@ -13683,7 +13683,7 @@ BI.PageTable = BI.inherit(BI.Widget, { BI.PageTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.page_table', BI.PageTable);/** +BI.shortcut("bi.page_table", BI.PageTable);/** * 路径选择 * * Created by GUY on 2015/12/4. @@ -13701,7 +13701,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return BI.extend(BI.PathChooser.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-path-chooser", items: [] - }) + }); }, _init: function () { @@ -13715,7 +13715,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return { type: "bi.path_region", title: self.texts[region] || region - } + }; })); this.regionMap = {}; BI.each(regions, function (i, region) { @@ -13808,7 +13808,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { left: x - 6.5, top: y - 6.5 }] - }) + }); }, _drawLine: function (start, lines) { @@ -13820,7 +13820,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { this.pathes[start] = []; } var startRegionIndex = this.getRegionIndexById(start); - //start所在的位置,然后接着往下画其他的路径 + // start所在的位置,然后接着往下画其他的路径 var offset = this.regions[startRegionIndex].getIndexByValue(start); BI.each(lines, function (i, line) { self.pathes[start][i] = []; @@ -13839,14 +13839,14 @@ BI.PathChooser = BI.inherit(BI.Widget, { self.pathes[start][i].push({ x: sleft - 50, y: stop - }) + }); } else if (idx === 0) { radioStartX = sleft + 50; path += "M" + sleft + "," + stop; self.pathes[start][i].push({ x: sleft, y: stop - }) + }); } else { radioStartX = sleft + 50; path += "M" + sleft + "," + 47.5 + "L" + (sleft + 50) + "," + 47.5 + "L" + (sleft + 50) + "," + stop; @@ -13889,13 +13889,13 @@ BI.PathChooser = BI.inherit(BI.Widget, { var graph = self.svg.path(path) .attr({ stroke: idx === 0 ? self._const.selectLineColor : self._const.lineColor, - 'stroke-dasharray': '-' + "stroke-dasharray": "-" }); self.lines[start].push(graph); if (lines.length > 1) { self.lines[start][0].toFront(); } - //第一个元素无论有多少个都要显示radio + // 第一个元素无论有多少个都要显示radio if (BI.contains(self.start, start)) { self.lines[self.regions[0].getValueByIndex(0)][0].toFront(); } @@ -13922,7 +13922,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { self.regionIndexes[k].push(regionIndex); } }); - }) + }); }); BI.each(routes, function (k, route) { self._drawLine(k, route); @@ -13990,16 +13990,16 @@ BI.PathChooser = BI.inherit(BI.Widget, { if (parent.getChildIndex(item.value) === -1) { tree.addNode(parent, node); } - }) + }); }); - //算出区域列表 + // 算出区域列表 tree.traverse(function (node) { BI.each(node.getChildren(), function (i, child) { if (BI.contains(regions, child.get("region"))) { var index1 = BI.indexOf(regions, node.get("region")); var index2 = BI.indexOf(regions, child.get("region")); - //交换区域 + // 交换区域 if (index1 > index2) { var t = regions[index2]; for (var j = index2; j < index1; j++) { @@ -14014,14 +14014,14 @@ BI.PathChooser = BI.inherit(BI.Widget, { }); this._createRegions(regions); - //算出节点 + // 算出节点 BI.each(branches, function (k, branch) { if (branch < max) { delete branches[k]; } }); - //过滤节点 + // 过滤节点 var nodes = []; var n = tree.getRoot(); while (n && n.getChildrenLength() === 1) { @@ -14039,7 +14039,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { } }); - //填充节点 + // 填充节点 var routes = {}; var s, e; for (var i = 0, len = nodes.length; i < len + 1; i++) { @@ -14080,7 +14080,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return true; } } - }) + }); }); } this.routes = routes; @@ -14145,7 +14145,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { if (array.length > 0) { result.push(array); } - //画这n条路径 + // 画这n条路径 BI.each(result, function (idx, path) { var start = path[0]; var index = BI.findIndex(self.routes[start], function (idx, p) { @@ -14187,7 +14187,7 @@ BI.PathRegion = BI.inherit(BI.Widget, { baseCls: "bi-path-region bi-background", width: 80, title: "" - }) + }); }, _init: function () { @@ -14208,7 +14208,7 @@ BI.PathRegion = BI.inherit(BI.Widget, { bgap: 5, hgap: 10, items: [title] - }) + }); }, hasItem: function (val) { @@ -14315,10 +14315,10 @@ BI.PreviewTableCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); -BI.shortcut('bi.preview_table_cell', BI.PreviewTableCell);/** +BI.shortcut("bi.preview_table_cell", BI.PreviewTableCell);/** * 预览表 * * Created by GUY on 2015/12/25. @@ -14346,10 +14346,10 @@ BI.PreviewTableHeaderCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); -BI.shortcut('bi.preview_table_header_cell', BI.PreviewTableHeaderCell);/** +BI.shortcut("bi.preview_table_header_cell", BI.PreviewTableHeaderCell);/** * 预览表 * * Created by GUY on 2015/12/25. @@ -14413,11 +14413,11 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }); }, - //是否有自适应调节的列,即列宽为"" + // 是否有自适应调节的列,即列宽为"" _hasAdaptCol: function (columnSize) { return BI.any(columnSize, function (i, size) { return size === ""; - }) + }); }, _isPercentage: function (columnSize) { @@ -14427,7 +14427,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { _adjustColumns: function () { var self = this, o = this.options; if (o.isNeedFreeze === true) { - //如果存在百分比的情况 + // 如果存在百分比的情况 if (this._isPercentage(o.columnSize)) { if (this._hasAdaptCol(o.columnSize)) { var findCols = [], remain = 0; @@ -14464,7 +14464,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { this.table.setColumnSize(isRight ? (notFreezeSize.concat(freezeSize)) : (freezeSize.concat(notFreezeSize))); } } else { - //如果存在自适应宽度的列或者是百分比计算的列,需要将整个表宽设为100% + // 如果存在自适应宽度的列或者是百分比计算的列,需要将整个表宽设为100% if (this._hasAdaptCol(o.columnSize) || this._isPercentage(o.columnSize)) { this.table.setRegionColumnSize(["100%"]); } @@ -14508,11 +14508,11 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }, getScrollRegionColumnSize: function () { - return this.table.getScrollRegionColumnSize() + return this.table.getScrollRegionColumnSize(); }, getScrollRegionRowSize: function () { - return this.table.getScrollRegionRowSize() + return this.table.getScrollRegionRowSize(); }, hasVerticalScroll: function () { @@ -14524,7 +14524,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }, setLeftHorizontalScroll: function (scrollLeft) { - return this.table.setLeftHorizontalScroll(scrollLeft) + return this.table.setLeftHorizontalScroll(scrollLeft); }, setRightHorizontalScroll: function (scrollLeft) { @@ -14552,7 +14552,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { } }); BI.PreviewTable.EVENT_CHANGE = "PreviewTable.EVENT_CHANGE"; -BI.shortcut('bi.preview_table', BI.PreviewTable);/** +BI.shortcut("bi.preview_table", BI.PreviewTable);/** * 季度下拉框 * * Created by GUY on 2015/8/28. @@ -14636,7 +14636,7 @@ BI.QuarterCombo = BI.inherit(BI.Widget, { BI.QuarterCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.QuarterCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.quarter_combo', BI.QuarterCombo);/** +BI.shortcut("bi.quarter_combo", BI.QuarterCombo);/** * 季度展示面板 * * Created by GUY on 2015/9/2. @@ -14696,7 +14696,7 @@ BI.QuarterPopup = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MonthPopup.EVENT_CHANGE); } - }) + }); }, getValue: function () { @@ -14774,7 +14774,7 @@ BI.QuarterTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -14872,7 +14872,7 @@ BI.RelationViewItem = BI.inherit(BI.BasicButton, { this.element[b ? "addClass" : "removeClass"]("active"); } }); -BI.shortcut('bi.relation_view_item', BI.RelationViewItem);/** +BI.shortcut("bi.relation_view_item", BI.RelationViewItem);/** * 关联视图 * * Created by GUY on 2015/12/22. @@ -14906,7 +14906,7 @@ BI.RelationView = BI.inherit(BI.Widget, { widths[j] = BI.MIN; } widths[j] = Math.max(widths[j], obj.getWidth()); - }) + }); }); return widths; }, @@ -14916,7 +14916,7 @@ BI.RelationView = BI.inherit(BI.Widget, { BI.each(this.views, function (i, items) { BI.each(items, function (j, obj) { heights[i] = Math.max(heights[i], obj.getHeight()); - }) + }); }); return heights; }, @@ -14947,7 +14947,7 @@ BI.RelationView = BI.inherit(BI.Widget, { }); }, - previewRelationTables: function(relationTables, show) { + previewRelationTables: function (relationTables, show) { if (!show) { BI.each(this.storeViews, function (i, view) { view.toggleRegion(true); @@ -14984,7 +14984,7 @@ BI.RelationView = BI.inherit(BI.Widget, { type: "bi.svg" }); - //算出所有的区域和关联 + // 算出所有的区域和关联 var regions = this.regions = {}, relations = this.relations = {}; BI.each(items, function (i, item) { var pr = item.primary.region, fr = item.foreign && item.foreign.region; @@ -15008,7 +15008,7 @@ BI.RelationView = BI.inherit(BI.Widget, { } pr && fr && relations[pr][fr].push(item); }); - //求拓扑 + // 求拓扑 var topology = []; var rs = BI.clone(regions), store = {}; while (!BI.isEmpty(rs)) { @@ -15024,7 +15024,7 @@ BI.RelationView = BI.inherit(BI.Widget, { delete rs[k]; }); } - //构建视图 + // 构建视图 var views = this.views = {}, storeViews = this.storeViews = {}, indexes = this.indexes = {}; var verticals = []; BI.each(topology, function (i, items) { @@ -15061,16 +15061,16 @@ BI.RelationView = BI.inherit(BI.Widget, { verticals.push({ type: "bi.horizontal", items: horizontal - }) + }); }); - //求每一行的高度 + // 求每一行的高度 var heights = this._calculateHeights(); - //求每一列的宽度 + // 求每一列的宽度 var widths = this._calculateWidths(); - //求相对宽度和高度 + // 求相对宽度和高度 var offsetWidths = [0], offsetHeights = [0]; BI.each(heights, function (i, h) { if (i === 0) { @@ -15085,8 +15085,8 @@ BI.RelationView = BI.inherit(BI.Widget, { offsetWidths[i] = offsetWidths[i - 1] + widths[i - 1]; }); - //画线 - var lines = this.lines = {};//缓存所有的线 + // 画线 + var lines = this.lines = {};// 缓存所有的线 BI.each(relations, function (start, rs) { BI.each(rs, function (end, relation) { var startIndex = indexes[start], endIndex = indexes[end]; @@ -15150,7 +15150,7 @@ BI.RelationView = BI.inherit(BI.Widget, { } path += "M" + si.x + "," + si.y + "L" + ei.x + "," + ei.y; var line = lines[start][end] = self.svg.path(path) - .attr({"stroke": c.lineColor, "stroke-width": "2"}) + .attr({stroke: c.lineColor, "stroke-width": "2"}) .hover(function () { line.attr("stroke", c.selectLineColor).toFront(); storeViews[start].setValue(relation[0].primary.value); @@ -15190,7 +15190,7 @@ BI.RelationView = BI.inherit(BI.Widget, { }); BI.RelationView.EVENT_CHANGE = "RelationView.EVENT_CHANGE"; BI.RelationView.EVENT_PREVIEW = "EVENT_PREVIEW"; -BI.shortcut('bi.relation_view', BI.RelationView);/** +BI.shortcut("bi.relation_view", BI.RelationView);/** * Created by Young's on 2017/3/10. */ BI.RelationViewRegionContainer = BI.inherit(BI.Widget, { @@ -15247,7 +15247,7 @@ BI.RelationViewRegionContainer = BI.inherit(BI.Widget, { return this.region.getHeight(); }, - //获取上方开始划线的位置 + // 获取上方开始划线的位置 getTopLeftPosition: function () { return this.region.getTopLeftPosition(); }, @@ -15276,7 +15276,7 @@ BI.RelationViewRegionContainer = BI.inherit(BI.Widget, { v === true ? this.region.element.fadeIn() : this.region.element.fadeOut(); }, - setPreviewSelected: function(v) { + setPreviewSelected: function (v) { this.region.setPreviewSelected(v); } }); @@ -15327,11 +15327,11 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { value: o.value, textAlign: "left" }); - //title放body上 + // title放body上 if (BI.isKey(o.header)) { this.title.setTitle(o.header, { container: "body" - }) + }); } this.button_group = BI.createWidget({ @@ -15356,7 +15356,7 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { }], hgap: 25, vgap: 20 - }) + }); }, _createItems: function (items) { @@ -15372,7 +15372,7 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { self.setValue([]); self.fireEvent(BI.RelationViewRegion.EVENT_HOVER_OUT, item.value); } - }) + }); }); }, @@ -15392,54 +15392,54 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { return this.button_group.getAllButtons().length * 25 + 25 + 2 * 20 + 3; }, - //获取上方开始划线的位置 + // 获取上方开始划线的位置 getTopLeftPosition: function () { return { x: 25 + 10, y: 20 - } + }; }, getTopRightPosition: function () { return { x: this.getWidth() - 25 - 10, y: 20 - } + }; }, getBottomPosition: function () { return { x: 25 + 10, y: this.getHeight() - 20 - } + }; }, getLeftPosition: function () { return { x: 25, y: 20 + 10 - } + }; }, getRightPosition: function () { return { x: this.getWidth() - 25, y: 20 + 10 - } + }; }, setValue: function (v) { this.button_group.setValue(v); }, - setPreviewSelected: function(v) { + setPreviewSelected: function (v) { this.preview.setSelected(v); } }); BI.RelationViewRegion.EVENT_HOVER_IN = "RelationViewRegion.EVENT_HOVER_IN"; BI.RelationViewRegion.EVENT_HOVER_OUT = "RelationViewRegion.EVENT_HOVER_OUT"; BI.RelationViewRegion.EVENT_PREVIEW = "RelationViewRegion.EVENT_PREVIEW"; -BI.shortcut('bi.relation_view_region', BI.RelationViewRegion);/** +BI.shortcut("bi.relation_view_region", BI.RelationViewRegion);/** * 自适应宽度的表格 * * Created by GUY on 2016/2/3. @@ -15455,12 +15455,12 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.ResponisveTable.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-responsive-table", - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 - mergeRule: function (row1, row2) { //合并规则, 默认相等时合并 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 + mergeRule: function (row1, row2) { // 合并规则, 默认相等时合并 return BI.isEqual(row1, row2); }, @@ -15473,9 +15473,9 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { header: [], footer: false, - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -15506,7 +15506,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { header: o.header, footer: o.footer, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -15528,7 +15528,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { self.fireEvent(BI.Table.EVENT_TABLE_BEFORE_REGION_RESIZE, arguments); }); this.table.on(BI.Table.EVENT_TABLE_REGION_RESIZE, function () { - //important:在冻结并自适应列宽的情况下要随时变更表头宽度 + // important:在冻结并自适应列宽的情况下要随时变更表头宽度 if (o.isNeedResize === true && self._isAdaptiveColumn()) { self._resizeHeader(); } @@ -15558,7 +15558,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { if (o.isNeedFreeze === true) { var regionColumnSize = this.table.getRegionColumnSize(); var maxWidth = this.table.element.width(); - if (!regionColumnSize[0] || (regionColumnSize[0] === 'fill') || regionColumnSize[0] > maxWidth || regionColumnSize[1] > maxWidth) { + if (!regionColumnSize[0] || (regionColumnSize[0] === "fill") || regionColumnSize[0] > maxWidth || regionColumnSize[1] > maxWidth) { var freezeCols = o.freezeCols; if (freezeCols.length === 0) { this.table.setRegionColumnSize([0, "fill"]); @@ -15587,7 +15587,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { columnSizeRight.push(size); } }); - //因为有边框,所以加上数组长度的参数调整 + // 因为有边框,所以加上数组长度的参数调整 var sumLeft = BI.sum(columnSizeLeft) + columnSizeLeft.length, sumRight = BI.sum(columnSizeRight) + columnSizeRight.length; return { @@ -15595,7 +15595,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { sumRight: sumRight, left: columnSizeLeft, right: columnSizeRight - } + }; } return { size: columnSize, @@ -15610,7 +15610,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { _resizeHeader: function () { var self = this, o = this.options; if (o.isNeedFreeze === true) { - //若是当前处于自适应调节阶段 + // 若是当前处于自适应调节阶段 if (this._isAdaptiveColumn()) { var columnSize = this.table.getCalculateColumnSize(); this.table.setHeaderColumnSize(columnSize); @@ -15629,10 +15629,10 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { block = self._getBlockSize(); if (columnSizeLeft[columnSizeLeft.length - 1] < block.left[block.left.length - 1]) { - columnSizeLeft[columnSizeLeft.length - 1] = block.left[block.left.length - 1] + columnSizeLeft[columnSizeLeft.length - 1] = block.left[block.left.length - 1]; } if (columnSizeRight[columnSizeRight.length - 1] < block.right[block.right.length - 1]) { - columnSizeRight[columnSizeRight.length - 1] = block.right[block.right.length - 1] + columnSizeRight[columnSizeRight.length - 1] = block.right[block.right.length - 1]; } self.table.setColumnSize(columnSizeLeft.concat(columnSizeRight)); @@ -15652,7 +15652,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { block = this._getBlockSize(); if (size[size.length - 1] < block.size[block.size.length - 1]) { - size[size.length - 1] = block.size[block.size.length - 1] + size[size.length - 1] = block.size[block.size.length - 1]; } this.table.setColumnSize(size); } @@ -15800,7 +15800,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { } } }); -BI.shortcut('bi.responsive_table', BI.ResponisveTable);/** +BI.shortcut("bi.responsive_table", BI.ResponisveTable);/** * 加号表示的组节点 * Created by GUY on 2015/9/6. * @class BI.SelectTreeFirstPlusGroupNode @@ -15819,7 +15819,7 @@ BI.SelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -15903,7 +15903,7 @@ BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -15911,7 +15911,7 @@ BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { this.checkbox = BI.createWidget({ type: "bi.last_tree_node_checkbox", stopPropagation: true - }) + }); this.text = BI.createWidget({ type: "bi.label", textAlign: "left", @@ -15987,7 +15987,7 @@ BI.SelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeMidPlusGroupNode.superclass._init.apply(this, arguments); @@ -16245,7 +16245,7 @@ BI.SelectTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.level_tree', + type: "bi.level_tree", expander: { type: "bi.select_tree_expander", isDefaultInit: true @@ -16310,7 +16310,7 @@ BI.SequenceTableDynamicNumber = BI.inherit(BI.SequenceTableTreeNumber, { var result = []; var count = this._getStart(nodes); - function getLeafCount(node) { + function getLeafCount (node) { var cnt = 0; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { @@ -16357,7 +16357,7 @@ BI.SequenceTableDynamicNumber = BI.inherit(BI.SequenceTableTreeNumber, { return result; } }); -BI.shortcut('bi.sequence_table_dynamic_number', BI.SequenceTableDynamicNumber);/** +BI.shortcut("bi.sequence_table_dynamic_number", BI.SequenceTableDynamicNumber);/** * * Created by GUY on 2016/5/26. * @class BI.SequenceTableListNumber @@ -16370,16 +16370,16 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { baseCls: "bi-sequence-table-list-number", isNeedFreeze: false, scrollTop: 0, - startSequence: 1,//开始的序号 + startSequence: 1, // 开始的序号 headerRowSize: 25, rowSize: 25, sequenceHeaderCreator: null, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [], @@ -16500,7 +16500,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { styleGetter: function (index) { return function () { return o.sequenceCellStyleGetter(self.start + i - 1); - } + }; }(cnt) })); renderedCells.push({ @@ -16513,7 +16513,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { renderedKeys.push(this.start + i); } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (BI.deepContains(self.renderedKeys, key)) { @@ -16536,7 +16536,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { }); var addedItems = []; BI.each(addSet, function (index) { - addedItems.push(renderedCells[index]) + addedItems.push(renderedCells[index]); }); BI.createWidget({ type: "bi.absolute", @@ -16600,7 +16600,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { this._populate(); } }); -BI.shortcut('bi.sequence_table_list_number', BI.SequenceTableListNumber);/** +BI.shortcut("bi.sequence_table_list_number", BI.SequenceTableListNumber);/** * 带有序号的表格 * * Created by GUY on 2016/5/26. @@ -16621,11 +16621,11 @@ BI.SequenceTable = BI.inherit(BI.Widget, { isNeedResize: true, isResizeAdapt: false, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -16641,14 +16641,14 @@ BI.SequenceTable = BI.inherit(BI.Widget, { sequenceCellStyleGetter: BI.emptyFn, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [], showSequence: false, - startSequence: 1//开始的序号 + startSequence: 1// 开始的序号 }); }, @@ -16702,7 +16702,7 @@ BI.SequenceTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -16852,7 +16852,7 @@ BI.SequenceTable = BI.inherit(BI.Widget, { BI.SequenceTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.sequence_table', BI.SequenceTable);/** +BI.shortcut("bi.sequence_table", BI.SequenceTable);/** * 单选加载数据搜索loader面板 * Created by guy on 15/11/4. * @class BI.SingleSelectSearchLoader @@ -16862,7 +16862,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-search-loader', + baseCls: "bi-single-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -16919,7 +16919,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -16949,7 +16949,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: false - }) + }); }, _filterValues: function (src) { @@ -16972,12 +16972,12 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: false - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = v; this.button_group.setValue(v); }, @@ -17008,7 +17008,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_search_loader', BI.SingleSelectSearchLoader);/** +BI.shortcut("bi.single_select_search_loader", BI.SingleSelectSearchLoader);/** * * 在搜索框中输入文本弹出的面板 * @class BI.SingleSelectSearchPane @@ -17039,8 +17039,8 @@ BI.SingleSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'single-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "single-select-toolbar", height: this.constants.height }); @@ -17114,7 +17114,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-combo', + baseCls: "bi-single-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -17129,8 +17129,8 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { BI.isKey(self._startValue) && (self.storeValue = self._startValue); self.trigger.getSearcher().setState(self.storeValue); }; - this.storeValue = ''; - //标记正在请求数据 + this.storeValue = ""; + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -17149,7 +17149,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(self.getValue()); } callback.apply(self, arguments); @@ -17176,7 +17176,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -17213,7 +17213,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.single_select_popup_view', + type: "bi.single_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -17259,10 +17259,10 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -17299,7 +17299,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -17308,7 +17308,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, _makeMap: function (values) { @@ -17327,7 +17327,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -17373,7 +17373,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -17392,7 +17392,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -17433,7 +17433,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); }, @@ -17455,7 +17455,7 @@ BI.extend(BI.SingleSelectCombo, { BI.SingleSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.single_select_combo', BI.SingleSelectCombo);/** +BI.shortcut("bi.single_select_combo", BI.SingleSelectCombo);/** * 选择列表 * * Created by GUY on 2015/11/1. @@ -17464,130 +17464,130 @@ BI.shortcut('bi.single_select_combo', BI.SingleSelectCombo);/** */ BI.SingleSelectList = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.SingleSelectList.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-select-list", - direction: BI.Direction.Top,//toolbar的位置 - logic: { - dynamic: true - }, - items: [], - itemsCreator: BI.emptyFn, - hasNext: BI.emptyFn, - onLoaded: BI.emptyFn, - el: { - type: "bi.list_pane" - } - }) - }, - _init: function () { - BI.SingleSelectList.superclass._init.apply(this, arguments); - var self = this, o = this.options; + _defaultConfig: function () { + return BI.extend(BI.SingleSelectList.superclass._defaultConfig.apply(this, arguments), { + baseCls: "bi-select-list", + direction: BI.Direction.Top, // toolbar的位置 + logic: { + dynamic: true + }, + items: [], + itemsCreator: BI.emptyFn, + hasNext: BI.emptyFn, + onLoaded: BI.emptyFn, + el: { + type: "bi.list_pane" + } + }); + }, + _init: function () { + BI.SingleSelectList.superclass._init.apply(this, arguments); + var self = this, o = this.options; - this.list = BI.createWidget(o.el, { - type: "bi.list_pane", - items: o.items, - itemsCreator: function (op, callback) { - o.itemsCreator(op, function (items) { - callback.apply(self, arguments); - }); - }, - onLoaded: o.onLoaded, - hasNext: o.hasNext - }); + this.list = BI.createWidget(o.el, { + type: "bi.list_pane", + items: o.items, + itemsCreator: function (op, callback) { + o.itemsCreator(op, function (items) { + callback.apply(self, arguments); + }); + }, + onLoaded: o.onLoaded, + hasNext: o.hasNext + }); - this.list.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (type === BI.Events.CLICK) { - self.fireEvent(BI.SingleSelectList.EVENT_CHANGE, value, obj); - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); + this.list.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { + if (type === BI.Events.CLICK) { + self.fireEvent(BI.SingleSelectList.EVENT_CHANGE, value, obj); + } + self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ - scrolly: true - }, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.list) - })))); + BI.createWidget(BI.extend({ + element: this + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ + scrolly: true + }, o.logic, { + items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.list) + })))); - }, + }, - hasPrev: function () { - return this.list.hasPrev(); - }, + hasPrev: function () { + return this.list.hasPrev(); + }, - hasNext: function () { - return this.list.hasNext(); - }, + hasNext: function () { + return this.list.hasNext(); + }, - prependItems: function (items) { - this.list.prependItems.apply(this.list, arguments); - }, + prependItems: function (items) { + this.list.prependItems.apply(this.list, arguments); + }, - addItems: function (items) { - this.list.addItems.apply(this.list, arguments); - }, + addItems: function (items) { + this.list.addItems.apply(this.list, arguments); + }, - setValue: function (v) { - this.list.setValue([v]); - }, + setValue: function (v) { + this.list.setValue([v]); + }, - getValue: function () { - return this.list.getValue()[0]; - }, + getValue: function () { + return this.list.getValue()[0]; + }, - empty: function () { - this.list.empty(); - }, + empty: function () { + this.list.empty(); + }, - populate: function (items) { - this.list.populate.apply(this.list, arguments); - }, + populate: function (items) { + this.list.populate.apply(this.list, arguments); + }, - resetHeight: function (h) { - this.list.resetHeight ? this.list.resetHeight(h) : - this.list.element.css({"max-height": h + "px"}) - }, + resetHeight: function (h) { + this.list.resetHeight ? this.list.resetHeight(h) : + this.list.element.css({"max-height": h + "px"}); + }, - setNotSelectedValue: function () { - this.list.setNotSelectedValue.apply(this.list, arguments); - }, + setNotSelectedValue: function () { + this.list.setNotSelectedValue.apply(this.list, arguments); + }, - getNotSelectedValue: function () { - return this.list.getNotSelectedValue(); - }, + getNotSelectedValue: function () { + return this.list.getNotSelectedValue(); + }, - getAllButtons: function () { - return this.list.getAllButtons(); - }, + getAllButtons: function () { + return this.list.getAllButtons(); + }, - getAllLeaves: function () { - return this.list.getAllLeaves(); - }, + getAllLeaves: function () { + return this.list.getAllLeaves(); + }, - getSelectedButtons: function () { - return this.list.getSelectedButtons(); - }, + getSelectedButtons: function () { + return this.list.getSelectedButtons(); + }, - getNotSelectedButtons: function () { - return this.list.getNotSelectedButtons(); - }, + getNotSelectedButtons: function () { + return this.list.getNotSelectedButtons(); + }, - getIndexByValue: function (value) { - return this.list.getIndexByValue(value); - }, + getIndexByValue: function (value) { + return this.list.getIndexByValue(value); + }, - getNodeById: function (id) { - return this.list.getNodeById(id); - }, + getNodeById: function (id) { + return this.list.getNodeById(id); + }, - getNodeByValue: function (value) { - return this.list.getNodeByValue(value); - } - }); - BI.SingleSelectList.EVENT_CHANGE = "EVENT_CHANGE"; - BI.shortcut("bi.single_select_list", BI.SingleSelectList);/** + getNodeByValue: function (value) { + return this.list.getNodeByValue(value); + } +}); +BI.SingleSelectList.EVENT_CHANGE = "EVENT_CHANGE"; +BI.shortcut("bi.single_select_list", BI.SingleSelectList);/** * 单选加载数据面板 * Created by guy on 15/11/2. * @class BI.SingleSelectLoader @@ -17597,7 +17597,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-loader', + baseCls: "bi-single-select-loader", logic: { dynamic: true }, @@ -17658,7 +17658,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -17688,7 +17688,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { logic: this.options.logic, height: 25, selected: false - }) + }); }, _scrollToTop: function () { @@ -17699,7 +17699,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, setStartValue: function (v) { @@ -17707,7 +17707,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.button_group.setValue(this.storeValue); }, @@ -17738,7 +17738,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_loader', BI.SingleSelectLoader);/** +BI.shortcut("bi.single_select_loader", BI.SingleSelectLoader);/** * 带加载的单选下拉面板 * @class BI.SingleSelectPopupView * @extends Widget @@ -17747,8 +17747,8 @@ BI.SingleSelectPopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectPopupView.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-popup-view', - maxWidth: 'auto', + baseCls: "bi-single-select-popup-view", + maxWidth: "auto", minWidth: 135, maxHeight: 400, valueFormatter: BI.emptyFn, @@ -17775,7 +17775,7 @@ BI.SingleSelectPopupView = BI.inherit(BI.Widget, { minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.loader }); @@ -17824,7 +17824,7 @@ BI.SingleSelectPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; BI.SingleSelectPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.shortcut('bi.single_select_popup_view', BI.SingleSelectPopupView);/** +BI.shortcut("bi.single_select_popup_view", BI.SingleSelectPopupView);/** * * 单选下拉框 * @class BI.SingleSelectTrigger @@ -17886,12 +17886,12 @@ BI.SingleSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: BI.createWidget(), width: 30 @@ -17933,7 +17933,7 @@ BI.SingleSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.single_select_trigger', BI.SingleSelectTrigger);/** +BI.shortcut("bi.single_select_trigger", BI.SingleSelectTrigger);/** * 单选输入框 * Created by guy on 15/11/3. * @class BI.SingleSelectEditor @@ -17942,12 +17942,12 @@ BI.shortcut('bi.single_select_trigger', BI.SingleSelectTrigger);/** BI.SingleSelectEditor = BI.inherit(BI.Widget, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.SingleSelectEditor.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-editor', + baseCls: "bi-single-select-editor", el: {} }); }, @@ -17956,10 +17956,10 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { BI.SingleSelectEditor.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.state_editor', + type: "bi.state_editor", element: this, height: o.height, - watermark: BI.i18nText('BI-Basic_Search'), + watermark: BI.i18nText("BI-Basic_Search"), allowBlank: true }); @@ -17995,16 +17995,16 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { var v = this.editor.getState(); if (BI.isArray(v) && v.length > 0) { return v[v.length - 1]; - } else { - return ""; } + return ""; + }, getKeywords: function () { var val = this.editor.getLastValidValue(); var keywords = val.match(/[\S]+/g); if (BI.isEndWithBlank(val)) { - return keywords.concat([' ']); + return keywords.concat([" "]); } return keywords; }, @@ -18014,7 +18014,7 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { } }); BI.SingleSelectEditor.EVENT_PAUSE = "SingleSelectEditor.EVENT_PAUSE"; -BI.shortcut('bi.single_select_editor', BI.SingleSelectEditor);/** +BI.shortcut("bi.single_select_editor", BI.SingleSelectEditor);/** * searcher * Created by guy on 15/11/3. * @class BI.SingleSelectSearcher @@ -18024,7 +18024,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-searcher', + baseCls: "bi-single-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -18038,7 +18038,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { BI.SingleSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.single_select_editor', + type: "bi.single_select_editor", height: o.height }); @@ -18120,11 +18120,11 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { setState: function (v) { var o = this.options; - v || (v = ''); - if (v === '') { + v || (v = ""); + if (v === "") { this.editor.setState(BI.Selection.None); } else { - this.editor.setState(o.valueFormatter(v + "") || (v + '')); + this.editor.setState(o.valueFormatter(v + "") || (v + "")); } }, @@ -18152,7 +18152,7 @@ BI.SingleSelectSearcher.EVENT_START = "EVENT_START"; BI.SingleSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.SingleSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.single_select_searcher', BI.SingleSelectSearcher);/** +BI.shortcut("bi.single_select_searcher", BI.SingleSelectSearcher);/** * 单选加载数据搜索loader面板 * Created by guy on 15/11/4. * @class BI.SingleSelectSearchLoader @@ -18162,7 +18162,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-search-loader', + baseCls: "bi-single-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -18219,7 +18219,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -18266,7 +18266,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: false - }) + }); }, _filterValues: function (src) { @@ -18289,12 +18289,12 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: false - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = v; this.button_group.setValue(v); }, @@ -18325,7 +18325,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_search_add_loader', BI.SingleSelectSearchLoader);/** +BI.shortcut("bi.single_select_search_add_loader", BI.SingleSelectSearchLoader);/** * * 在搜索框中输入文本弹出的面板 * @class BI.SingleSelectSearchPane @@ -18356,8 +18356,8 @@ BI.SingleSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'single-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "single-select-toolbar", height: this.constants.height }); @@ -18431,7 +18431,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-combo', + baseCls: "bi-single-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -18446,8 +18446,8 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { BI.isKey(self._startValue) && (self.storeValue = self._startValue); self.trigger.getSearcher().setState(self.storeValue); }; - this.storeValue = ''; - //标记正在请求数据 + this.storeValue = ""; + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -18466,7 +18466,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(self.getValue()); } callback.apply(self, arguments); @@ -18493,7 +18493,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -18530,7 +18530,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.single_select_popup_view', + type: "bi.single_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -18576,10 +18576,10 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -18616,7 +18616,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -18625,7 +18625,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, _makeMap: function (values) { @@ -18644,7 +18644,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -18690,7 +18690,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -18709,7 +18709,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -18750,7 +18750,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); }, @@ -18772,7 +18772,7 @@ BI.extend(BI.SingleSelectCombo, { BI.SingleSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.single_select_add_combo', BI.SingleSelectCombo);/** +BI.shortcut("bi.single_select_add_combo", BI.SingleSelectCombo);/** * * 单选下拉框 * @class BI.SingleSelectTrigger @@ -18834,12 +18834,12 @@ BI.SingleSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: BI.createWidget(), width: 30 @@ -18881,7 +18881,7 @@ BI.SingleSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.single_select_add_trigger', BI.SingleSelectTrigger);/** +BI.shortcut("bi.single_select_add_trigger", BI.SingleSelectTrigger);/** * searcher * Created by guy on 15/11/3. * @class BI.SingleSelectSearcher @@ -18891,7 +18891,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-searcher', + baseCls: "bi-single-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -18905,7 +18905,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { BI.SingleSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.single_select_editor', + type: "bi.single_select_editor", height: o.height }); @@ -18987,11 +18987,11 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { setState: function (v) { var o = this.options; - v || (v = ''); - if (v === '') { + v || (v = ""); + if (v === "") { this.editor.setState(BI.Selection.None); } else { - this.editor.setState(o.valueFormatter(v + "") || (v + '')); + this.editor.setState(o.valueFormatter(v + "") || (v + "")); } }, @@ -19019,7 +19019,7 @@ BI.SingleSelectSearcher.EVENT_START = "EVENT_START"; BI.SingleSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.SingleSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.single_select_add_searcher', BI.SingleSelectSearcher);/** +BI.shortcut("bi.single_select_add_searcher", BI.SingleSelectSearcher);/** * Created by User on 2017/11/16. */ BI.SignTextEditor = BI.inherit(BI.Widget, { @@ -19040,7 +19040,7 @@ BI.SignTextEditor = BI.inherit(BI.Widget, { errorText: "", text: "", height: 24 - }) + }); }, _init: function () { @@ -19079,7 +19079,7 @@ BI.SignTextEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignTextEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignTextEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ @@ -19313,13 +19313,13 @@ BI.SingleSlider = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -19395,7 +19395,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _draggable: function (widget) { @@ -19409,7 +19409,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setLabelPosition(significantPercent); self._setSliderPosition(significantPercent); @@ -19435,7 +19435,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -19443,7 +19443,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -19475,14 +19475,14 @@ BI.SingleSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { var o = this.options; var valid = false; if (BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max)) { - if(o.digit === false){ + if(o.digit === false) { valid = true; }else{ var dotText = (v + "").split(".")[1] || ""; @@ -19493,15 +19493,15 @@ BI.SingleSlider = BI.inherit(BI.Widget, { }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setLabelPosition: function (percent) { - this.label.element.css({"left": percent + "%"}); + this.label.element.css({left: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -19516,7 +19516,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { @@ -19643,13 +19643,13 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -19706,7 +19706,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _draggable: function (widget) { @@ -19720,7 +19720,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setLabelPosition(significantPercent); self._setSliderPosition(significantPercent); @@ -19746,7 +19746,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSliderLabel.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -19754,7 +19754,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -19786,23 +19786,23 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { - return BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max) + return BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max); }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setLabelPosition: function (percent) { - this.label.element.css({"left": percent + "%"}); + this.label.element.css({left: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -19817,7 +19817,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { @@ -19931,13 +19931,13 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -19973,7 +19973,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - } + }; }, _draggable: function (widget) { @@ -19987,7 +19987,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setSliderPosition(significantPercent); var v = self._getValueByPercent(significantPercent); @@ -20011,7 +20011,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -20019,7 +20019,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -20070,19 +20070,19 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { ref: function (ref) { self.track = ref; } - } + }; }, _checkValidation: function (v) { - return !(BI.isNull(v) || v < this.min || v > this.max) + return !(BI.isNull(v) || v < this.min || v > this.max); }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -20095,7 +20095,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { @@ -20251,7 +20251,7 @@ BI.SingleTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.level_tree', + type: "bi.level_tree", expander: { isDefaultInit: true }, @@ -20403,8 +20403,8 @@ BI.SwitchTree = BI.inherit(BI.Widget, { } }, - _removeIsParent: function(items) { - BI.each(items, function(i, item) { + _removeIsParent: function (items) { + BI.each(items, function (i, item) { BI.isNotNull(item.isParent) && delete item.isParent; }); return items; @@ -20460,7 +20460,7 @@ BI.SwitchTree.SelectType = { SingleSelect: BI.Selection.Single, MultiSelect: BI.Selection.Multi }; -BI.shortcut('bi.switch_tree', BI.SwitchTree); +BI.shortcut("bi.switch_tree", BI.SwitchTree); /** * Created by Baron on 2015/10/19. */ @@ -20478,7 +20478,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { var conf = BI.TimeInterval.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-time-interval" - }) + }); }, _init: function () { var self = this; @@ -20487,7 +20487,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { this.left = this._createCombo(); this.right = this._createCombo(); this.label = BI.createWidget({ - type: 'bi.label', + type: "bi.label", height: this.constants.height, width: this.constants.width, text: "-" @@ -20529,7 +20529,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { _createCombo: function () { var self = this; var combo = BI.createWidget({ - type: 'bi.multidate_combo' + type: "bi.multidate_combo" }); combo.on(BI.MultiDateCombo.EVENT_ERROR, function () { self._clearTitle(); @@ -20537,7 +20537,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { self.fireEvent(BI.TimeInterval.EVENT_ERROR); }); - combo.on(BI.MultiDateCombo.EVENT_VALID, function(){ + combo.on(BI.MultiDateCombo.EVENT_VALID, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -20553,7 +20553,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { } }); - combo.on(BI.MultiDateCombo.EVENT_FOCUS, function(){ + combo.on(BI.MultiDateCombo.EVENT_FOCUS, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -20573,7 +20573,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { self.left.hidePopupView(); self.right.hidePopupView(); }); - //combo.on(BI.MultiDateCombo.EVENT_CHANGE, function () { + // combo.on(BI.MultiDateCombo.EVENT_CHANGE, function () { // BI.Bubbles.hide("error"); // var smallDate = self.left.getKey(), bigDate = self.right.getKey(); // if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -20587,9 +20587,9 @@ BI.TimeInterval = BI.inherit(BI.Single, { // self._clearTitle(); // self.element.removeClass(self.constants.timeErrorCls); // } - //}); + // }); - combo.on(BI.MultiDateCombo.EVENT_CONFIRM, function(){ + combo.on(BI.MultiDateCombo.EVENT_CONFIRM, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -20613,14 +20613,14 @@ BI.TimeInterval = BI.inherit(BI.Single, { _check: function (smallDate, bigDate) { var smallObj = smallDate.match(/\d+/g), bigObj = bigDate.match(/\d+/g); return this._dateCheck(smallDate) && Date.checkLegal(smallDate) && this._checkVoid({ - year: smallObj[0], - month: smallObj[1], - day: smallObj[2] - }) && this._dateCheck(bigDate) && Date.checkLegal(bigDate) && this._checkVoid({ - year: bigObj[0], - month: bigObj[1], - day: bigObj[2] - }); + year: smallObj[0], + month: smallObj[1], + day: smallObj[2] + }) && this._dateCheck(bigDate) && Date.checkLegal(bigDate) && this._checkVoid({ + year: bigObj[0], + month: bigObj[1], + day: bigObj[2] + }); }, _compare: function (smallDate, bigDate) { smallDate = Date.parseDateTime(smallDate, "%Y-%X-%d").print("%Y-%X-%d"); @@ -20661,8 +20661,8 @@ BI.YearCombo = BI.inherit(BI.Widget, { return BI.extend(BI.YearCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-combo", behaviors: {}, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 25 }); }, @@ -20751,7 +20751,7 @@ BI.YearCombo = BI.inherit(BI.Widget, { }); BI.YearCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_combo', BI.YearCombo);/** +BI.shortcut("bi.year_combo", BI.YearCombo);/** * 年份展示面板 * * Created by GUY on 2015/9/2. @@ -20764,8 +20764,8 @@ BI.YearPopup = BI.inherit(BI.Widget, { return BI.extend(BI.YearPopup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-popup", behaviors: {}, - min: '1900-01-01', //最小日期 - max: '2099-12-31' //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31" // 最大日期 }); }, @@ -20874,8 +20874,8 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { _defaultConfig: function () { return BI.extend(BI.YearTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-year-trigger bi-border", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24 }); }, @@ -20896,7 +20896,7 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { vgap: c.vgap, allowBlank: true, errorText: c.errorText - }) + }); this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { self.fireEvent(BI.YearTrigger.EVENT_FOCUS); }); @@ -20924,7 +20924,7 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { }); BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -21027,7 +21027,7 @@ BI.YearMonthCombo = BI.inherit(BI.Widget, { }); BI.YearMonthCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearMonthCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_month_combo', BI.YearMonthCombo);/** +BI.shortcut("bi.year_month_combo", BI.YearMonthCombo);/** * 年份 + 月份下拉框 * * @class BI.YearQuarterCombo @@ -21094,7 +21094,7 @@ BI.YearQuarterCombo = BI.inherit(BI.Widget, { }); BI.YearQuarterCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearQuarterCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_quarter_combo', BI.YearQuarterCombo);/** +BI.shortcut("bi.year_quarter_combo", BI.YearQuarterCombo);/** * 简单的复选下拉框控件, 适用于数据量少的情况, 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值 * 封装了字段处理逻辑 * @@ -21141,7 +21141,7 @@ BI.AbstractAllValueChooser = BI.inherit(BI.Widget, { } else { call(this.items); } - function call(items) { + function call (items) { var keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); @@ -21150,7 +21150,7 @@ BI.AbstractAllValueChooser = BI.inherit(BI.Widget, { var search = BI.Func.getSearchResult(items, kw); items = search.matched.concat(search.finded); }); - if (options.selectedValues) {//过滤 + if (options.selectedValues) {// 过滤 var filter = BI.makeObject(options.selectedValues, true); items = BI.filter(items, function (i, ob) { return !filter[ob.value]; @@ -21200,7 +21200,7 @@ BI.AllValueChooserCombo = BI.inherit(BI.AbstractAllValueChooser, { this.items = o.items; } this.combo = BI.createWidget({ - type: 'bi.multi_select_combo', + type: "bi.multi_select_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -21233,7 +21233,7 @@ BI.AllValueChooserCombo = BI.inherit(BI.AbstractAllValueChooser, { } }); BI.AllValueChooserCombo.EVENT_CONFIRM = "AllValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.all_value_chooser_combo', BI.AllValueChooserCombo);/** +BI.shortcut("bi.all_value_chooser_combo", BI.AllValueChooserCombo);/** * 简单的复选下拉框控件, 适用于数据量少的情况, 与valuechooser的区别是allvaluechooser setValue和getValue返回的是所有值 * 封装了字段处理逻辑 * @@ -21261,7 +21261,7 @@ BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, { this.items = o.items; } this.list = BI.createWidget({ - type: 'bi.multi_select_list', + type: "bi.multi_select_list", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -21294,7 +21294,7 @@ BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, { } }); BI.AllValueChooserPane.EVENT_CHANGE = "AllValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { +BI.shortcut("bi.all_value_chooser_pane", BI.AllValueChooserPane);BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { _const: { perPage: 100 @@ -21324,7 +21324,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree } else { call(); } - function call() { + function call () { switch (options.type) { case BI.TreeView.REQ_TYPE_INIT_DATA: self._reqInitTreeNode(options, callback); @@ -21361,7 +21361,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree items: result }); - function doCheck(parentValues, node, selected) { + function doCheck (parentValues, node, selected) { if (selected == null || BI.isEmpty(selected)) { BI.each(node.getChildren(), function (i, child) { var newParents = BI.clone(parentValues); @@ -21378,10 +21378,10 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree newParents.push(node.value); createOneJson(node, node.parent && node.parent.id, getCount(selected[k], newParents)); doCheck(newParents, node, selected[k]); - }) + }); } - function getCount(jo, parentValues) { + function getCount (jo, parentValues) { if (jo == null) { return 0; } @@ -21392,7 +21392,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return BI.size(jo); } - function createOneJson(node, pId, llen) { + function createOneJson (node, pId, llen) { result.push({ id: node.id, pId: pId, @@ -21419,15 +21419,15 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree callback(selectedValues); - function dealWithSelectedValues(selectedValues) { + function dealWithSelectedValues (selectedValues) { var p = parentValues.concat(notSelectedValue); - //存储的值中存在这个值就把它删掉 - //例如选中了中国-江苏-南京, 取消中国或江苏或南京 + // 存储的值中存在这个值就把它删掉 + // 例如选中了中国-江苏-南京, 取消中国或江苏或南京 if (canFindKey(selectedValues, p)) { - //如果搜索的值在父亲链中 + // 如果搜索的值在父亲链中 if (isSearchValueInParent(p)) { - //例如选中了 中国-江苏, 搜索江苏, 取消江苏 - //例如选中了 中国-江苏, 搜索江苏, 取消中国 + // 例如选中了 中国-江苏, 搜索江苏, 取消江苏 + // 例如选中了 中国-江苏, 搜索江苏, 取消中国 self._deleteNode(selectedValues, p); } else { var searched = []; @@ -21436,50 +21436,50 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree BI.each(searched, function (i, arr) { var node = self._getNode(selectedValues, arr); if (node) { - //例如选中了 中国-江苏-南京,搜索南京,取消中国 + // 例如选中了 中国-江苏-南京,搜索南京,取消中国 self._deleteNode(selectedValues, arr); } else { - //例如选中了 中国-江苏,搜索南京,取消中国 + // 例如选中了 中国-江苏,搜索南京,取消中国 expandSelectedValue(selectedValues, arr, BI.last(arr)); } - }) + }); } } } - //存储的值中不存在这个值,但父亲节点是全选的情况 - //例如选中了中国-江苏,取消南京 - //important 选中了中国-江苏,取消了江苏,但是搜索的是南京 + // 存储的值中不存在这个值,但父亲节点是全选的情况 + // 例如选中了中国-江苏,取消南京 + // important 选中了中国-江苏,取消了江苏,但是搜索的是南京 if (isChild(selectedValues, p)) { var result = [], finded = false; - //如果parentValues中有匹配的值,说明搜索结果不在当前值下 + // 如果parentValues中有匹配的值,说明搜索结果不在当前值下 if (isSearchValueInParent(p)) { finded = true; } else { - //从当前值开始搜 + // 从当前值开始搜 finded = search(parentValues, notSelectedValue, result); p = parentValues; } if (finded === true) { - //去掉点击的节点之后的结果集 + // 去掉点击的节点之后的结果集 expandSelectedValue(selectedValues, p, notSelectedValue); - //添加去掉搜索的结果集 + // 添加去掉搜索的结果集 if (result.length > 0) { BI.each(result, function (i, strs) { self._buildTree(selectedValues, strs); - }) + }); } } } } - function expandSelectedValue(selectedValues, parents, notSelectedValue) { + function expandSelectedValue (selectedValues, parents, notSelectedValue) { var next = selectedValues; var childrenCount = []; var path = []; - //去掉点击的节点之后的结果集 + // 去掉点击的节点之后的结果集 BI.some(parents, function (i, v) { var t = next[v]; if (t == null) { @@ -21491,7 +21491,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree var expanded = self._getChildren(split); path.push(split); childrenCount.push(expanded.length); - //如果只有一个值且取消的就是这个值 + // 如果只有一个值且取消的就是这个值 if (i === parents.length - 1 && expanded.length === 1 && expanded[0] === notSelectedValue) { for (var j = childrenCount.length - 1; j >= 0; j--) { if (childrenCount[j] === 1) { @@ -21520,7 +21520,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function search(parents, current, result, searched) { + function search (parents, current, result, searched) { var newParents = BI.clone(parents); newParents.push(current); if (self._isMatch(parents, current, keyword)) { @@ -21550,7 +21550,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return can; } - function isSearchValueInParent(parentValues) { + function isSearchValueInParent (parentValues) { for (var i = 0, len = parentValues.length; i < len; i++) { if (self._isMatch(parentValues.slice(0, parentValues.length - 1), parentValues[i], keyword)) { return true; @@ -21559,7 +21559,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return false; } - function canFindKey(selectedValues, parents) { + function canFindKey (selectedValues, parents) { var t = selectedValues; for (var i = 0; i < parents.length; i++) { var v = parents[i]; @@ -21571,7 +21571,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return true; } - function isChild(selectedValues, parents) { + function isChild (selectedValues, parents) { var t = selectedValues; for (var i = 0; i < parents.length; i++) { var v = parents[i]; @@ -21607,7 +21607,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); callback(jo); - function dealWithSelectedValues(selected, parents) { + function dealWithSelectedValues (selected, parents) { if (selected == null || BI.isEmpty(selected)) { return true; } @@ -21627,7 +21627,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return can && isAllSelected(selected, parents); } - function isAllSelected(selected, parents) { + function isAllSelected (selected, parents) { return BI.isEmpty(selected) || self._getChildCount(parents) === BI.size(selected); } }, @@ -21644,10 +21644,10 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree hasNext: output.length > self._const.perPage, items: result, lastSearchValue: BI.last(output) - }) + }); }); - function search() { + function search () { var children = self._getChildren([]); var start = children.length; if (lastSearchValue !== "") { @@ -21677,7 +21677,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return output; } - function nodeSearch(deep, parentValues, current, isAllSelect, result) { + function nodeSearch (deep, parentValues, current, isAllSelect, result) { if (self._isMatch(parentValues, current, keyword)) { var checked = isAllSelect || isSelected(parentValues, current); createOneJson(parentValues, current, false, checked, !isAllSelect && isHalf(parentValues, current), true, result); @@ -21706,8 +21706,8 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return [can, checked]; } - function createOneJson(parentValues, value, isOpen, checked, half, flag, result) { - var node = self._getTreeNode(parentValues, value) + function createOneJson (parentValues, value, isOpen, checked, half, flag, result) { + var node = self._getTreeNode(parentValues, value); result.push({ id: node.id, pId: node.pId, @@ -21722,7 +21722,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function isHalf(parentValues, value) { + function isHalf (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return null; @@ -21736,7 +21736,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function isAllSelected(parentValues, value) { + function isAllSelected (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return null; @@ -21750,7 +21750,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function isSelected(parentValues, value) { + function isSelected (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return false; @@ -21762,7 +21762,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); } - function findSelectedObj(parentValues) { + function findSelectedObj (parentValues) { var find = selectedValues; if (find == null) { return null; @@ -21801,7 +21801,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree isParent: nodes[i].getChildrenLength() > 0, checked: state[0], halfCheck: state[1] - }) + }); } BI.nextTick(function () { callback({ @@ -21810,7 +21810,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree }); }); - function judgeState(parentValues, selected_value, checkState) { + function judgeState (parentValues, selected_value, checkState) { var checked = checkState.checked, half = checkState.half; if (parentValues.length > 0 && !checked) { return false; @@ -21818,7 +21818,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return (parentValues.length === 0 || (checked && half) && !BI.isEmpty(selected_value)); } - function dealWidthSelectedValue(parentValues, selectedValues) { + function dealWidthSelectedValue (parentValues, selectedValues) { var valueMap = {}; BI.each(parentValues, function (i, v) { selectedValues = selectedValues[v] || {}; @@ -21843,11 +21843,11 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree return valueMap; } - function getCheckState(current, parentValues, valueMap, checkState) { + function getCheckState (current, parentValues, valueMap, checkState) { var checked = checkState.checked, half = checkState.half; var tempCheck = false, halfCheck = false; if (BI.has(valueMap, current)) { - //可能是半选 + // 可能是半选 if (valueMap[current][0] === 1) { var values = BI.clone(parentValues); values.push(current); @@ -21886,7 +21886,7 @@ BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane);BI.AbstractTree var pNode = this._getNode(selectedValues, p); if (pNode != null && pNode[name]) { delete pNode[name]; - //递归删掉空父节点 + // 递归删掉空父节点 while (p.length > 0 && BI.isEmpty(pNode)) { name = p[p.length - 1]; p = p.slice(0, p.length - 1); @@ -21977,7 +21977,7 @@ BI.TreeValueChooserCombo = BI.inherit(BI.AbstractTreeValueChooser, { this._initData(o.items); } this.combo = BI.createWidget({ - type: 'bi.multi_tree_combo', + type: "bi.multi_tree_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), width: o.width, @@ -22002,7 +22002,7 @@ BI.TreeValueChooserCombo = BI.inherit(BI.AbstractTreeValueChooser, { } }); BI.TreeValueChooserCombo.EVENT_CONFIRM = "TreeValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.tree_value_chooser_combo', BI.TreeValueChooserCombo);/** +BI.shortcut("bi.tree_value_chooser_combo", BI.TreeValueChooserCombo);/** * 简单的复选下拉树控件, 适用于数据量少的情况 * * Created by GUY on 2015/10/29. @@ -22023,7 +22023,7 @@ BI.TreeValueChooserPane = BI.inherit(BI.AbstractTreeValueChooser, { BI.TreeValueChooserPane.superclass._init.apply(this, arguments); var self = this, o = this.options; this.pane = BI.createWidget({ - type: 'bi.multi_select_tree', + type: "bi.multi_select_tree", element: this, itemsCreator: BI.bind(this._itemsCreator, this) }); @@ -22054,7 +22054,7 @@ BI.TreeValueChooserPane = BI.inherit(BI.AbstractTreeValueChooser, { } }); BI.TreeValueChooserPane.EVENT_CHANGE = "TreeValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.tree_value_chooser_pane', BI.TreeValueChooserPane);/** +BI.shortcut("bi.tree_value_chooser_pane", BI.TreeValueChooserPane);/** * 简单的复选下拉框控件, 适用于数据量少的情况 * 封装了字段处理逻辑 * @@ -22111,7 +22111,7 @@ BI.AbstractValueChooser = BI.inherit(BI.Widget, { } else { call(this.items); } - function call(items) { + function call (items) { var keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); @@ -22120,7 +22120,7 @@ BI.AbstractValueChooser = BI.inherit(BI.Widget, { var search = BI.Func.getSearchResult(items, kw); items = search.matched.concat(search.finded); }); - if (options.selectedValues) {//过滤 + if (options.selectedValues) {// 过滤 var filter = BI.makeObject(options.selectedValues, true); items = BI.filter(items, function (i, ob) { return !filter[ob.value]; @@ -22170,7 +22170,7 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { this.items = o.items; } this.combo = BI.createWidget({ - type: 'bi.multi_select_combo', + type: "bi.multi_select_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -22192,7 +22192,7 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { return { type: val.type, value: val.value - } + }; }, populate: function () { @@ -22200,7 +22200,7 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { } }); BI.ValueChooserCombo.EVENT_CONFIRM = "ValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.value_chooser_combo', BI.ValueChooserCombo);/** +BI.shortcut("bi.value_chooser_combo", BI.ValueChooserCombo);/** * 简单的复选下拉框控件, 适用于数据量少的情况 * 封装了字段处理逻辑 * @@ -22223,7 +22223,7 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { BI.ValueChooserPane.superclass._init.apply(this, arguments); var self = this, o = this.options; this.list = BI.createWidget({ - type: 'bi.multi_select_list', + type: "bi.multi_select_list", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this) @@ -22247,7 +22247,7 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { return { type: val.type, value: val.value - } + }; }, populate: function () { @@ -22255,4 +22255,4 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { } }); BI.ValueChooserPane.EVENT_CHANGE = "ValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane); \ No newline at end of file +BI.shortcut("bi.value_chooser_pane", BI.ValueChooserPane); \ No newline at end of file diff --git a/src/addons/chart/chart.combine.js b/src/addons/chart/chart.combine.js index 59177b48b..11cb7c3c1 100644 --- a/src/addons/chart/chart.combine.js +++ b/src/addons/chart/chart.combine.js @@ -14,14 +14,14 @@ BI.CombineChart = BI.inherit(BI.Widget, { types: [[], []], popupItemsGetter: BI.emptyFn, formatConfig: BI.emptyFn - }) + }); }, _init: function () { BI.CombineChart.superclass._init.apply(this, arguments); var self = this, o = this.options; - //图可配置属性 + // 图可配置属性 this.CombineChart = BI.createWidget({ type: "bi.chart", element: this.element @@ -44,7 +44,7 @@ BI.CombineChart = BI.inherit(BI.Widget, { if (BI.isArray(axisItems)) { result = BI.concat(result, axisItems); } else { - result.push(BI.extend(axisItems, {"yAxis": yAxisIndex})); + result.push(BI.extend(axisItems, {yAxis: yAxisIndex})); } }); if (BI.isNotEmptyArray(combineItems)) { @@ -93,7 +93,7 @@ BI.CombineChart = BI.inherit(BI.Widget, { }, hgap: 10 }, item) - } + }; }) }) }, @@ -118,7 +118,7 @@ BI.CombineChart = BI.inherit(BI.Widget, { this.combo.showView(); this._debounce2Destroy(); - function destroyCombo() { + function destroyCombo () { if (self._doDestroy) { this.destroy(); } @@ -153,4 +153,4 @@ BI.CombineChart = BI.inherit(BI.Widget, { }); BI.CombineChart.EVENT_CHANGE = "EVENT_CHANGE"; BI.CombineChart.EVENT_ITEM_CLICK = "EVENT_ITEM_CLICK"; -BI.shortcut('bi.combine_chart', BI.CombineChart); \ No newline at end of file +BI.shortcut("bi.combine_chart", BI.CombineChart); \ No newline at end of file diff --git a/src/addons/chart/chart.js b/src/addons/chart/chart.js index cadcca0bc..37d8dfbb7 100644 --- a/src/addons/chart/chart.js +++ b/src/addons/chart/chart.js @@ -8,7 +8,7 @@ BI.Chart = BI.inherit(BI.Pane, { _defaultConfig: function () { return BI.extend(BI.Chart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-chart" - }) + }); }, _init: function () { @@ -35,7 +35,7 @@ BI.Chart = BI.inherit(BI.Pane, { }, magnify: function () { - this.vanCharts.refreshRestore() + this.vanCharts.refreshRestore(); }, populate: function (items, options) { @@ -52,4 +52,4 @@ BI.Chart = BI.inherit(BI.Pane, { } }); BI.Chart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.chart', BI.Chart); \ No newline at end of file +BI.shortcut("bi.chart", BI.Chart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.abstract.js b/src/addons/chart/chart/chart.abstract.js index 0607217e9..3ec61fec1 100644 --- a/src/addons/chart/chart/chart.abstract.js +++ b/src/addons/chart/chart/chart.abstract.js @@ -41,9 +41,9 @@ BI.AbstractChart = BI.inherit(BI.Widget, { LINE_WIDTH: 1, NUM_SEPARATORS: false, FONT_STYLE: { - "fontFamily": "inherit", - "color": "inherit", - "fontSize": "12px" + fontFamily: "inherit", + color: "inherit", + fontSize: "12px" } }, @@ -51,7 +51,7 @@ BI.AbstractChart = BI.inherit(BI.Widget, { return BI.extend(BI.AbstractChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-abstract-chart", popupItemsGetter: BI.emptyFn - }) + }); }, _init: function () { @@ -101,12 +101,12 @@ BI.AbstractChart = BI.inherit(BI.Widget, { da.x = BI.contentFormat(BI.parseFloat(da.x.div(magnify).toFixed(4)), "#.####;-#.####"); } }); - }) + }); }, formatXYDataWithMagnify: function (number, magnify) { if (BI.isNull(number)) { - return null + return null; } if (!BI.isNumber(number)) { number = BI.parseFloat(number); @@ -173,46 +173,46 @@ BI.AbstractChart = BI.inherit(BI.Widget, { }, formatTickInXYaxis: function (type, number_level, separators, isCompareBar) { - var formatter = '#.##'; + var formatter = "#.##"; switch (type) { case this.constants.NORMAL: - formatter = '#.##'; + formatter = "#.##"; if (separators) { - formatter = '#,###.##' + formatter = "#,###.##"; } break; case this.constants.ZERO2POINT: - formatter = '#0'; + formatter = "#0"; if (separators) { - formatter = '#,###'; + formatter = "#,###"; } break; case this.constants.ONE2POINT: - formatter = '#0.0'; + formatter = "#0.0"; if (separators) { - formatter = '#,###.0'; + formatter = "#,###.0"; } break; case this.constants.TWO2POINT: - formatter = '#0.00'; + formatter = "#0.00"; if (separators) { - formatter = '#,###.00'; + formatter = "#,###.00"; } break; } if (number_level === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT) { - formatter += '%'; + formatter += "%"; } formatter += ";-" + formatter; if(isCompareBar) { return function () { arguments[0] = arguments[0] > 0 ? arguments[0] : (-1) * arguments[0]; return BI.contentFormat(arguments[0], formatter); - } + }; } return function () { - return BI.contentFormat(arguments[0], formatter) - } + return BI.contentFormat(arguments[0], formatter); + }; }, formatDataLabel: function (state, items, config, style) { @@ -220,8 +220,8 @@ BI.AbstractChart = BI.inherit(BI.Widget, { if (state === true) { BI.each(items, function (idx, item) { item.dataLabels = { - "align": "outside", - "autoAdjust": true, + align: "outside", + autoAdjust: true, style: style, enabled: true, formatter: { @@ -238,13 +238,13 @@ BI.AbstractChart = BI.inherit(BI.Widget, { if (state === true) { BI.each(items, function (idx, item) { item.dataLabels = { - "align": "outside", - "autoAdjust": true, + align: "outside", + autoAdjust: true, style: style, enabled: true, formatter: { identifier: "${VALUE}", - valueFormat: format, + valueFormat: format } }; if(isPercentChart) { @@ -265,7 +265,7 @@ BI.AbstractChart = BI.inherit(BI.Widget, { BI.each(config.yAxis, function (idx, axis) { axis.labelStyle = fontStyle; axis.title.style = fontStyle; - }) + }); }, _formatItems: function (items) { diff --git a/src/addons/chart/chart/chart.accumulatearea.js b/src/addons/chart/chart/chart.accumulatearea.js index 8ccd9a81c..d0a9318cc 100644 --- a/src/addons/chart/chart/chart.accumulatearea.js +++ b/src/addons/chart/chart/chart.accumulatearea.js @@ -8,7 +8,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AccumulateAreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-accumulate-area-chart" - }) + }); }, _init: function () { @@ -35,7 +35,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AccumulateAreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -102,20 +102,20 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle(v) { + function formatChartStyle (v) { switch (v) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -125,7 +125,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatChartLineStyle(v) { + function formatChartLineStyle (v) { switch (v) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.curve = false; @@ -143,7 +143,7 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon(cordon) { + function formatCordon (cordon) { BI.each(cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -152,9 +152,9 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -177,14 +177,14 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } }, @@ -274,4 +274,4 @@ BI.AccumulateAreaChart = BI.inherit(BI.AbstractChart, { } }); BI.AccumulateAreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.accumulate_area_chart', BI.AccumulateAreaChart); \ No newline at end of file +BI.shortcut("bi.accumulate_area_chart", BI.AccumulateAreaChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.accumulateaxis.js b/src/addons/chart/chart/chart.accumulateaxis.js index 7f3de4cf4..4c1e61ff6 100644 --- a/src/addons/chart/chart/chart.accumulateaxis.js +++ b/src/addons/chart/chart/chart.accumulateaxis.js @@ -8,7 +8,7 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AccumulateAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-accumulate-axis-chart" - }) + }); }, _init: function () { @@ -33,7 +33,7 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AccumulateAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -93,20 +93,20 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { enableTick: self.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "column"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -115,9 +115,9 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -140,17 +140,17 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -160,7 +160,7 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { } } - function getTitleText(numberLevelType, position, show, title) { + function getTitleText (numberLevelType, position, show, title) { var unit = ""; switch (numberLevelType) { @@ -178,13 +178,13 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } unit = unit === "" ? unit : "(" + unit + ")"; @@ -277,4 +277,4 @@ BI.AccumulateAxisChart = BI.inherit(BI.AbstractChart, { } }); BI.AccumulateAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.accumulate_axis_chart', BI.AccumulateAxisChart); \ No newline at end of file +BI.shortcut("bi.accumulate_axis_chart", BI.AccumulateAxisChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.accumulatebar.js b/src/addons/chart/chart/chart.accumulatebar.js index fc614be8e..54480e057 100644 --- a/src/addons/chart/chart/chart.accumulatebar.js +++ b/src/addons/chart/chart/chart.accumulatebar.js @@ -8,7 +8,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AccumulateBarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-accumulate-bar-chart" - }) + }); }, _init: function () { @@ -21,7 +21,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { }, labelStyle: this.constants.FONT_STYLE, formatter: function () { - return this > 0 ? this : (-1) * this + return this > 0 ? this : (-1) * this; }, gridLineWidth: 0 }]; @@ -45,7 +45,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AccumulateBarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -67,7 +67,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, lineWidth: this.config.lineWidth, enableTick: this.config.enableTick, - maxWidth: '40%' + maxWidth: "40%" }); self.formatNumberLevelInXaxis(items, this.config.leftYAxisNumberLevel); @@ -82,17 +82,17 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { enableMinorTick: this.config.enableMinorTick }); config.chartType = "bar"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.xAxis[0].formatter, this.config.chartFont); config.plotOptions.tooltip.formatter.valueFormat = config.xAxis[0].formatter; - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -102,7 +102,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.leftYAxisNumberLevel); @@ -111,9 +111,9 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -136,17 +136,17 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -163,13 +163,13 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -184,7 +184,7 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { var tmp = t.x; t.x = t.y; t.y = tmp; - }) + }); }); }); return items; @@ -243,4 +243,4 @@ BI.AccumulateBarChart = BI.inherit(BI.AbstractChart, { } }); BI.AccumulateBarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.accumulate_bar_chart', BI.AccumulateBarChart); \ No newline at end of file +BI.shortcut("bi.accumulate_bar_chart", BI.AccumulateBarChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.accumulateradar.js b/src/addons/chart/chart/chart.accumulateradar.js index 86bb2c3ef..19ab625e8 100644 --- a/src/addons/chart/chart/chart.accumulateradar.js +++ b/src/addons/chart/chart/chart.accumulateradar.js @@ -8,7 +8,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AccumulateRadarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-accumulate-radar-chart" - }) + }); }, _init: function () { @@ -21,7 +21,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { }, labelStyle: this.constants.FONT_STYLE, formatter: function () { - return this > 0 ? this : (-1) * this + return this > 0 ? this : (-1) * this; }, gridLineWidth: 0, position: "bottom" @@ -45,7 +45,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AccumulateRadarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -81,17 +81,17 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { config.plotOptions.columnType = true; delete config.xAxis; delete config.yAxis; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.radiusAxis[0].formatter, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 config.radiusAxis[0].labelStyle = config.radiusAxis[0].title.style = this.config.chartFont; config.angleAxis[0].labelStyle = config.angleAxis[0].title.style = this.config.chartFont; config.legend.style = this.config.chartFont; return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -101,7 +101,7 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { } } - function formatChartRadarStyle() { + function formatChartRadarStyle () { switch (self.config.chartRadarType) { case BICst.CHART_SHAPE.POLYGON: config.plotOptions.shape = "polygon"; @@ -112,19 +112,19 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { } } - function formatNumberLevelInYaxis(type, position, formatter) { + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = formatter; } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -141,13 +141,13 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -191,4 +191,4 @@ BI.AccumulateRadarChart = BI.inherit(BI.AbstractChart, { } }); BI.AccumulateRadarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.accumulate_radar_chart', BI.AccumulateRadarChart); \ No newline at end of file +BI.shortcut("bi.accumulate_radar_chart", BI.AccumulateRadarChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.area.js b/src/addons/chart/chart/chart.area.js index 4119527cb..31a0720fa 100644 --- a/src/addons/chart/chart/chart.area.js +++ b/src/addons/chart/chart/chart.area.js @@ -8,7 +8,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-area-chart" - }) + }); }, _init: function () { @@ -34,7 +34,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -99,20 +99,20 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -122,7 +122,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -131,9 +131,9 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -156,17 +156,17 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartLineStyle() { + function formatChartLineStyle () { switch (self.config.chartLineType) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.curve = false; @@ -184,7 +184,7 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { } } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -201,13 +201,13 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -299,4 +299,4 @@ BI.AreaChart = BI.inherit(BI.AbstractChart, { } }); BI.AreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.area_chart', BI.AreaChart); \ No newline at end of file +BI.shortcut("bi.area_chart", BI.AreaChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.axis.js b/src/addons/chart/chart/chart.axis.js index 86330c600..20f029933 100644 --- a/src/addons/chart/chart/chart.axis.js +++ b/src/addons/chart/chart/chart.axis.js @@ -11,7 +11,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.AxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-axis-chart" - }) + }); }, _init: function () { @@ -37,7 +37,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.AxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -102,7 +102,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); var lineItem = []; @@ -115,15 +115,15 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { } }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [BI.concat(otherItem, lineItem), config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -133,7 +133,7 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -142,9 +142,9 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -164,17 +164,17 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -191,13 +191,13 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -273,4 +273,4 @@ BI.AxisChart = BI.inherit(BI.AbstractChart, { } }); BI.AxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.axis_chart', BI.AxisChart); \ No newline at end of file +BI.shortcut("bi.axis_chart", BI.AxisChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.bar.js b/src/addons/chart/chart/chart.bar.js index 36f5e38e7..372c2c67e 100644 --- a/src/addons/chart/chart/chart.bar.js +++ b/src/addons/chart/chart/chart.bar.js @@ -8,7 +8,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.BarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-bar-chart" - }) + }); }, _init: function () { @@ -21,7 +21,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { }, labelStyle: this.constants.FONT_STYLE, formatter: function () { - return this > 0 ? this : (-1) * this + return this > 0 ? this : (-1) * this; }, gridLineWidth: 0 }]; @@ -48,7 +48,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.BarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -60,7 +60,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { this.formatChartLegend(config, this.config.chartLegend); config.plotOptions.dataLabels.enabled = this.config.showDataLabel; - //分类轴 + // 分类轴 config.yAxis = this.yAxis; config.yAxis[0].title.text = this.config.showXAxisTitle === true ? this.config.xAxisTitle : ""; config.yAxis[0].title.rotation = this.constants.ROTATION; @@ -69,10 +69,10 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableTick: this.config.enableTick, lineWidth: this.config.lineWidth, - maxWidth: '40%' + maxWidth: "40%" }); - //值轴 + // 值轴 self.formatNumberLevelInXaxis(items, this.config.leftYAxisNumberLevel); config.xAxis[0].title.text = getXAxisTitle(this.config.leftYAxisNumberLevel, this.constants.X_AXIS); config.xAxis[0].title.align = "center"; @@ -90,12 +90,12 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { config.plotOptions.tooltip.formatter.valueFormat = config.xAxis[0].formatter; - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -105,7 +105,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.leftYAxisNumberLevel); @@ -114,9 +114,9 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -136,17 +136,17 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXAxisTitle(numberLevelType, position) { + function getXAxisTitle (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -163,10 +163,10 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } unit = unit === "" ? unit : "(" + unit + ")"; @@ -181,7 +181,7 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { var tmp = t.x; t.x = t.y; t.y = tmp; - }) + }); }); }); return items; @@ -238,4 +238,4 @@ BI.BarChart = BI.inherit(BI.AbstractChart, { } }); BI.BarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.bar_chart', BI.BarChart); \ No newline at end of file +BI.shortcut("bi.bar_chart", BI.BarChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.bubble.js b/src/addons/chart/chart/chart.bubble.js index d45e6efc3..8c045e010 100644 --- a/src/addons/chart/chart/chart.bubble.js +++ b/src/addons/chart/chart/chart.bubble.js @@ -8,7 +8,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.BubbleChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-bubble-chart" - }) + }); }, _init: function () { @@ -43,7 +43,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.BubbleChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -66,7 +66,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { config.yAxis[0].gridLineWidth = this.config.showGridLine === true ? 1 : 0; config.yAxis[0].lineWidth = 1; config.yAxis[0].title.rotation = this.constants.ROTATION; - config.yAxis[0].maxWidth = '40%'; + config.yAxis[0].maxWidth = "40%"; config.xAxis[0].formatter = self.formatTickInXYaxis(this.config.xAxisStyle, this.config.xAxisNumberLevel, this.config.rightNumSeparators); self.formatNumberLevelInXaxis(items, this.config.xAxisNumberLevel); @@ -74,41 +74,42 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { config.xAxis[0].title.text = this.config.showXAxisTitle === true ? this.config.xAxisTitle + config.xAxis[0].title.text : config.xAxis[0].title.text; config.xAxis[0].title.align = "center"; config.xAxis[0].gridLineWidth = this.config.showGridLine === true ? 1 : 0; - config.xAxis[0].maxHeith = '40%'; + config.xAxis[0].maxHeith = "40%"; config.chartType = "bubble"; if (BI.isNotEmptyArray(this.config.tooltip)) { config.plotOptions.bubble.tooltip = { useHtml: true, style: { - color: 'RGB(184, 184, 184)' + color: "RGB(184, 184, 184)" }, formatter: function () { - var y = self.formatTickInXYaxis(self.config.leftYAxisStyle, self.config.leftYAxisNumberLevel, self.config.numSeparators)(this.y); - var x = self.formatTickInXYaxis(self.config.xAxisStyle, self.config.xAxisNumberLevel, self.config.rightNumSeparators)(this.x); - return this.seriesName + '
    (X)' + self.config.tooltip[0] + ':' + x + '
    (Y)' + self.config.tooltip[1] - + ':' + y + '
    (' + BI.i18nText("BI-Size") + ')' + self.config.tooltip[2] + ':' + this.size + '
    '} + var y = self.formatTickInXYaxis(self.config.leftYAxisStyle, self.config.leftYAxisNumberLevel, self.config.numSeparators)(this.y); + var x = self.formatTickInXYaxis(self.config.xAxisStyle, self.config.xAxisNumberLevel, self.config.rightNumSeparators)(this.x); + return this.seriesName + "
    (X)" + self.config.tooltip[0] + ":" + x + "
    (Y)" + self.config.tooltip[1] + + ":" + y + "
    (" + BI.i18nText("BI-Size") + ")" + self.config.tooltip[2] + ":" + this.size + "
    "; + } }; } - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 if (config.plotOptions.dataLabels.enabled === true) { BI.each(items, function (idx, item) { item.dataLabels = { - "style" : self.config.chartFont, - "align": "outside", - "autoAdjust": true, + style: self.config.chartFont, + align: "outside", + autoAdjust: true, enabled: true, formatter: { identifier: "${X}${Y}${SIZE}", - "XFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + XFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); }, - "YFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + YFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); }, - "sizeFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + sizeFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); } } }; @@ -117,14 +118,14 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { }); } - //全局样式图表文字 + // 全局样式图表文字 config.yAxis[0].title.style = config.yAxis[0].labelStyle = this.config.chartFont; config.xAxis[0].title.style = config.xAxis[0].labelStyle = this.config.chartFont; config.legend.style = this.config.chartFont; return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -134,7 +135,7 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -143,9 +144,9 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -168,31 +169,31 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatNumberLevelInYaxis(type, position) { + function formatNumberLevelInYaxis (type, position) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); if (type === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT) { - //config.plotOptions.tooltip.formatter.valueFormat = "function(){return window.FR ? FR.contentFormat(arguments[0], '#0%') : arguments[0]}"; + // config.plotOptions.tooltip.formatter.valueFormat = "function(){return window.FR ? FR.contentFormat(arguments[0], '#0%') : arguments[0]}"; } } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -209,13 +210,13 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -226,9 +227,9 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { BI.each(item, function (id, it) { BI.each(it.data, function (i, da) { var data = da.size; - da.size = BI.contentFormat(data, '#.##;-#.##') - }) - }) + da.size = BI.contentFormat(data, "#.##;-#.##"); + }); + }); }); return items; }, @@ -279,4 +280,4 @@ BI.BubbleChart = BI.inherit(BI.AbstractChart, { } }); BI.BubbleChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.bubble_chart', BI.BubbleChart); +BI.shortcut("bi.bubble_chart", BI.BubbleChart); diff --git a/src/addons/chart/chart/chart.comparearea.js b/src/addons/chart/chart/chart.comparearea.js index f8d39e5c5..55dbc4dec 100644 --- a/src/addons/chart/chart/chart.comparearea.js +++ b/src/addons/chart/chart/chart.comparearea.js @@ -8,7 +8,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.CompareAreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-compare-area-chart" - }) + }); }, _init: function () { @@ -34,7 +34,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.CompareAreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -103,20 +103,20 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function _calculateValueNiceDomain(minValue, maxValue) { + function _calculateValueNiceDomain (minValue, maxValue) { minValue = Math.min(0, minValue); @@ -125,7 +125,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { return _linearNiceDomain(minValue, maxValue, tickInterval); } - function _linearTickInterval(minValue, maxValue, m) { + function _linearTickInterval (minValue, maxValue, m) { m = m || 5; var span = maxValue - minValue; @@ -137,7 +137,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { return step; } - function _linearNiceDomain(minValue, maxValue, tickInterval) { + function _linearNiceDomain (minValue, maxValue, tickInterval) { minValue = VanUtils.accMul(Math.floor(minValue / tickInterval), tickInterval); @@ -146,7 +146,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { return [minValue, maxValue]; } - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -156,7 +156,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -165,9 +165,9 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -190,17 +190,17 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartLineStyle() { + function formatChartLineStyle () { switch (self.config.chartLineType) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.area = { @@ -224,7 +224,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatNumberLevelInYaxis(type, position, formatter) { + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { var max = null; @@ -246,7 +246,7 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -263,13 +263,13 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -370,4 +370,4 @@ BI.CompareAreaChart = BI.inherit(BI.AbstractChart, { } }); BI.CompareAreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.compare_area_chart', BI.CompareAreaChart); \ No newline at end of file +BI.shortcut("bi.compare_area_chart", BI.CompareAreaChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.compareaxis.js b/src/addons/chart/chart/chart.compareaxis.js index 4162da484..5ea95826d 100644 --- a/src/addons/chart/chart/chart.compareaxis.js +++ b/src/addons/chart/chart/chart.compareaxis.js @@ -8,7 +8,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.CompareAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-compare-axis-chart" - }) + }); }, _init: function () { @@ -43,11 +43,11 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.CompareAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, - _formatConfig: function(config, items){ + _formatConfig: function (config, items) { var self = this, o = this.options; config.colors = this.config.chartColor; config.style = formatChartStyle(); @@ -58,15 +58,15 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { config.dataSheet.enabled = this.config.showDataTable; config.xAxis[0].showLabel = !config.dataSheet.enabled; config.zoom.zoomTool.enabled = this.config.showZoom; - if(this.config.showZoom === true){ + if(this.config.showZoom === true) { delete config.dataSheet; delete config.zoom.zoomType; } config.yAxis = this.yAxis; - BI.each(config.yAxis, function(idx, axis){ - var unit = ''; - switch (axis.axisIndex){ + BI.each(config.yAxis, function (idx, axis) { + var unit = ""; + switch (axis.axisIndex) { case self.constants.LEFT_AXIS: unit = getXYAxisUnit(self.config.leftYAxisNumberLevel, self.constants.LEFT_AXIS); axis.title.rotation = self.constants.ROTATION; @@ -112,7 +112,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); BI.extend(config.xAxis[1], { @@ -121,15 +121,15 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { enableMinorTick: this.config.enableMinorTick }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle(){ + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -139,23 +139,23 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon(){ - BI.each(self.config.cordon, function(idx, cor){ - if(idx === 0 && self.xAxis.length > 0){ + function formatCordon () { + BI.each(self.config.cordon, function (idx, cor) { + if(idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.leftYAxisNumberLevel); - self.xAxis[0].plotLines = BI.map(cor, function(i, t){ + self.xAxis[0].plotLines = BI.map(cor, function (i, t) { return BI.extend(t, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); } - if(idx > 0 && self.yAxis.length >= idx){ + if(idx > 0 && self.yAxis.length >= idx) { var magnify = 1; switch (idx - 1) { case self.constants.LEFT_AXIS: @@ -168,22 +168,22 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { magnify = self.calcMagnify(self.config.rightYAxisSecondNumberLevel); break; } - self.yAxis[idx - 1].plotLines = BI.map(cor, function(i, t){ + self.yAxis[idx - 1].plotLines = BI.map(cor, function (i, t) { return BI.extend(t, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartLineStyle(){ + function formatChartLineStyle () { switch (self.config.chartLineType) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.curve = false; @@ -201,29 +201,29 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { } } - function formatNumberLevelInYaxis(type, position, formatter){ + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { var max = null; BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); - if((BI.isNull(max) || BI.parseFloat(da.y) > BI.parseFloat(max))){ + if((BI.isNull(max) || BI.parseFloat(da.y) > BI.parseFloat(max))) { max = da.y; } } }); - if(position === item.yAxis){ + if(position === item.yAxis) { item.tooltip = BI.deepClone(config.plotOptions.tooltip); item.tooltip.formatter.valueFormat = formatter; } - if(BI.isNotNull(max)){ + if(BI.isNotNull(max)) { self.maxes.push(max); } }); } - function getXYAxisUnit(numberLevelType, position){ + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -239,19 +239,19 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { unit = BI.i18nText("BI-Yi"); break; } - if(position === self.constants.X_AXIS){ - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + if(position === self.constants.X_AXIS) { + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } - if(position === self.constants.LEFT_AXIS){ - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + if(position === self.constants.LEFT_AXIS) { + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } - if(position === self.constants.RIGHT_AXIS){ - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + if(position === self.constants.RIGHT_AXIS) { + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } - function _calculateValueNiceDomain(minValue, maxValue){ + function _calculateValueNiceDomain (minValue, maxValue) { minValue = Math.min(0, minValue); @@ -260,7 +260,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { return _linearNiceDomain(minValue, maxValue, tickInterval); } - function _linearTickInterval(minValue, maxValue, m){ + function _linearTickInterval (minValue, maxValue, m) { m = m || 5; var span = maxValue - minValue; @@ -272,7 +272,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { return step; } - function _linearNiceDomain(minValue, maxValue, tickInterval){ + function _linearNiceDomain (minValue, maxValue, tickInterval) { minValue = VanUtils.accMul(Math.floor(minValue / tickInterval), tickInterval); @@ -282,12 +282,12 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { } }, - _formatItems: function(items){ + _formatItems: function (items) { var self = this; this.maxes = []; - BI.each(items, function(idx, item){ - BI.each(item, function(id, it){ - if(idx > 0){ + BI.each(items, function (idx, item) { + BI.each(item, function (id, it) { + if(idx > 0) { BI.extend(it, {reversed: true, xAxis: 1}); }else{ BI.extend(it, {reversed: false, xAxis: 0}); @@ -314,7 +314,7 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { leftYAxisReversed: options.leftYAxisReversed || false, rightYAxisReversed: options.rightYAxisReversed || false, leftYAxisNumberLevel: options.leftYAxisNumberLevel || c.NORMAL, - rightYAxisNumberLevel: options.rightYAxisNumberLevel || c.NORMAL, + rightYAxisNumberLevel: options.rightYAxisNumberLevel || c.NORMAL, xAxisUnit: options.xAxisUnit || "", leftYAxisUnit: options.leftYAxisUnit || "", rightYAxisUnit: options.rightYAxisUnit || "", @@ -339,16 +339,16 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { this.yAxis = []; var types = []; - BI.each(items, function(idx, axisItems){ + BI.each(items, function (idx, axisItems) { var type = []; - BI.each(axisItems, function(id, item){ + BI.each(axisItems, function (id, item) { type.push(BICst.WIDGET.AXIS); }); types.push(type); }); - BI.each(types, function(idx, type){ - if(BI.isEmptyArray(type)){ + BI.each(types, function (idx, type) { + if(BI.isEmptyArray(type)) { return; } var newYAxis = { @@ -373,9 +373,9 @@ BI.CompareAxisChart = BI.inherit(BI.AbstractChart, { this.combineChart.resize(); }, - magnify: function(){ + magnify: function () { this.combineChart.magnify(); } }); BI.CompareAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.compare_axis_chart', BI.CompareAxisChart); \ No newline at end of file +BI.shortcut("bi.compare_axis_chart", BI.CompareAxisChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.comparebar.js b/src/addons/chart/chart/chart.comparebar.js index 50698004a..978b2031d 100644 --- a/src/addons/chart/chart/chart.comparebar.js +++ b/src/addons/chart/chart/chart.comparebar.js @@ -8,7 +8,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.CompareBarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-compare-bar-chart" - }) + }); }, _init: function () { @@ -45,7 +45,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.CompareBarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -67,7 +67,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { lineWidth: this.config.lineWidth, enableTick: this.config.enableTick, labelRotation: this.config.textDirection, - maxWidth: '40%' + maxWidth: "40%" }); self.formatNumberLevelInXaxis(items, this.config.leftYAxisNumberLevel); @@ -83,17 +83,17 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { }); config.chartType = "bar"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.xAxis[0].formatter, this.config.chartFont); config.plotOptions.tooltip.formatter.valueFormat = config.xAxis[0].formatter; - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -103,7 +103,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.leftYAxisNumberLevel); @@ -112,9 +112,9 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -137,17 +137,17 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -164,13 +164,13 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -190,7 +190,7 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { } }); it.stack = i; - }) + }); }); BI.each(items, function (idx, item) { result = BI.concat(result, item); @@ -250,4 +250,4 @@ BI.CompareBarChart = BI.inherit(BI.AbstractChart, { } }); BI.CompareBarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.compare_bar_chart', BI.CompareBarChart); \ No newline at end of file +BI.shortcut("bi.compare_bar_chart", BI.CompareBarChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.dashboard.js b/src/addons/chart/chart/chart.dashboard.js index 299413288..a95c448b0 100644 --- a/src/addons/chart/chart/chart.dashboard.js +++ b/src/addons/chart/chart/chart.dashboard.js @@ -9,18 +9,18 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.DashboardChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-dashboard-chart" - }) + }); }, _init: function () { BI.DashboardChart.superclass._init.apply(this, arguments); var self = this, o = this.options; this.gaugeAxis = [{ - "minorTickColor": "rgb(226,226,226)", - "tickColor": "rgb(186,186,186)", + minorTickColor: "rgb(226,226,226)", + tickColor: "rgb(186,186,186)", labelStyle: this.constants.FONT_STYLE, - "step": 0, - "showLabel": true + step: 0, + showLabel: true }]; this.combineChart = BI.createWidget({ type: "bi.combine_chart", @@ -32,7 +32,7 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.DashboardChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -48,13 +48,13 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { if (isDashboard && !isMultiPointers) { config.plotOptions.seriesLabel.enabled = false; if(BI.isNull(items[0].data[0].z)) { - config.plotOptions.tooltip.formatter.identifier = "${SERIES}${X}${Y}${SIZE}${VALUE}" + config.plotOptions.tooltip.formatter.identifier = "${SERIES}${X}${Y}${SIZE}${VALUE}"; } } config.gaugeAxis[0].labelStyle = this.config.chartFont; return [items, config]; - function formatChartDashboardStyle() { + function formatChartDashboardStyle () { var bands = getBandsStyles(self.config.bandsStyles, self.config.autoCustomStyle); var percentageLabel = BI.extend(config.plotOptions.percentageLabel, { enabled: self.config.showPercentage === BICst.PERCENTAGE.SHOW @@ -66,29 +66,29 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { formatter: function () { var value = this.value; if (self.config.dashboardNumberLevel === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT && self.config.numSeparators) { - value = BI.contentFormat(this.value, "#,##0%;-#,##0%") + value = BI.contentFormat(this.value, "#,##0%;-#,##0%"); } else if (self.config.dashboardNumberLevel === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT && !self.config.numSeparators) { value = BI.contentFormat(this.value, "#0.00%"); } else if (!(self.config.dashboardNumberLevel === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT) && self.config.numSeparators) { - value = BI.contentFormat(this.value, "#,###.##;-#,###.##") + value = BI.contentFormat(this.value, "#,###.##;-#,###.##"); } else { value = BI.contentFormat(this.value, "#.##;-#.##"); } - var label = '
    ' + this.seriesName + '
    ' + '
    ' + value + - getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS) + '
    '; + var label = "
    " + this.seriesName + "
    " + "
    " + value + + getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS) + "
    "; if (isDashboard && items[0].data.length > 1) { if (isMultiPointers) { - return '
    ' + this.seriesName + ':' + value + - getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS) + '
    '; + return "
    " + this.seriesName + ":" + value + + getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS) + "
    "; } - return label + return label; } else if (isDashboard && BI.isNull(items[0].data[0].z)) { - return label + return label; } - return '
    ' + this.category + '
    ' + label; + return "
    " + this.category + "
    " + label; }, style: self.config.chartFont, useHtml: true @@ -132,9 +132,9 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { config.gaugeAxis[0].formatter = function () { var scaleValue = this; if (self.config.numSeparators) { - scaleValue = BI.contentFormat(scaleValue, '#,##0%;-#,##0%') + scaleValue = BI.contentFormat(scaleValue, "#,##0%;-#,##0%"); } else { - scaleValue = BI.contentFormat(scaleValue, '#0.00%') + scaleValue = BI.contentFormat(scaleValue, "#0.00%"); } return scaleValue + getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS); }; @@ -142,14 +142,14 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { config.gaugeAxis[0].formatter = function () { var value = this; if (self.config.numSeparators) { - value = BI.contentFormat(value, "#,###;-#,###") + value = BI.contentFormat(value, "#,###;-#,###"); } return value + getXYAxisUnit(self.config.dashboardNumberLevel, self.constants.DASHBOARD_AXIS); }; } } - function setPlotOptions(style, bands, slotValueLAbel, percentageLabel, thermometerLayout, layout) { + function setPlotOptions (style, bands, slotValueLAbel, percentageLabel, thermometerLayout, layout) { config.style = style; config.plotOptions.bands = bands; config.plotOptions.valueLabel = slotValueLAbel; @@ -158,44 +158,44 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { config.plotOptions.layout = layout; } - function changeMaxMinScale() { + function changeMaxMinScale () { self.gaugeAxis[0].min = BI.parseFloat(self.config.minScale) || null; self.gaugeAxis[0].max = BI.parseFloat(self.config.maxScale) || null; } - function formatNumberLevelInYaxis(type, position) { + function formatNumberLevelInYaxis (type, position) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = function () { - return BI.contentFormat(this, '#.##;-#.##') + getXYAxisUnit(type, position) + return BI.contentFormat(this, "#.##;-#.##") + getXYAxisUnit(type, position); }; if (self.config.numSeparators) { config.plotOptions.tooltip.formatter.valueFormat = function () { - return BI.contentFormat(arguments[0], '#,###.##;-#,###.##') + return BI.contentFormat(arguments[0], "#,###.##;-#,###.##"); }; } if (type === BICst.TARGET_STYLE.NUM_LEVEL.PERCENT) { config.plotOptions.tooltip.formatter.valueFormat = function () { - return BI.contentFormat(arguments[0], '#0.00%') + return BI.contentFormat(arguments[0], "#0.00%"); }; if (self.config.numSeparators) { config.plotOptions.tooltip.formatter.valueFormat = function () { - return BI.contentFormat(arguments[0], '#,##0%;-#,##0%') + return BI.contentFormat(arguments[0], "#,##0%;-#,##0%"); }; } } } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -212,18 +212,18 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.DASHBOARD_AXIS) { - self.config.dashboardUnit !== "" && (unit = unit + self.config.dashboardUnit) + self.config.dashboardUnit !== "" && (unit = unit + self.config.dashboardUnit); } return unit; } - function getBandsStyles(styles, change) { + function getBandsStyles (styles, change) { var min = 0, bands = [], color = null, max = null, conditionMax = null; BI.each(items, function (idx, item) { var data = item.data[0]; if ((BI.isNull(max) || data.y > max)) { - max = data.y + max = data.y; } }); @@ -233,52 +233,52 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { break; case BICst.SCALE_SETTING.CUSTOM: if (styles.length === 0) { - return bands - } else { - var maxScale = _calculateValueNiceDomain(0, max)[1]; - - BI.each(styles, function (idx, style) { - if(BI.parseFloat(style.range.min) > BI.parseFloat(style.range.max)) { - return bands.push({ - color: color, - from: conditionMax, - to: maxScale - }); - } - bands.push({ - color: style.color, - from: style.range.min, - to: style.range.max + return bands; + } + var maxScale = _calculateValueNiceDomain(0, max)[1]; + + BI.each(styles, function (idx, style) { + if(BI.parseFloat(style.range.min) > BI.parseFloat(style.range.max)) { + return bands.push({ + color: color, + from: conditionMax, + to: maxScale }); - color = style.color; - conditionMax = style.range.max - }); - min = BI.parseInt(styles[0].range.min); + } bands.push({ - color: "#808080", - from: 0, - to: min + color: style.color, + from: style.range.min, + to: style.range.max }); + color = style.color; + conditionMax = style.range.max; + }); + min = BI.parseInt(styles[0].range.min); + bands.push({ + color: "#808080", + from: 0, + to: min + }); - bands.push({ - color: color, - from: conditionMax, - to: maxScale - }); + bands.push({ + color: color, + from: conditionMax, + to: maxScale + }); - return bands; - } + return bands; + } } - function _calculateValueNiceDomain(minValue, maxValue) { + function _calculateValueNiceDomain (minValue, maxValue) { minValue = Math.min(0, minValue); var tickInterval = _linearTickInterval(minValue, maxValue); return _linearNiceDomain(minValue, maxValue, tickInterval); } - function _linearTickInterval(minValue, maxValue, m) { + function _linearTickInterval (minValue, maxValue, m) { m = m || 5; var span = maxValue - minValue; var step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)); @@ -288,7 +288,7 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { return step; } - function _linearNiceDomain(minValue, maxValue, tickInterval) { + function _linearNiceDomain (minValue, maxValue, tickInterval) { minValue = VanUtils.accMul(Math.floor(minValue / tickInterval), tickInterval); maxValue = VanUtils.accMul(Math.ceil(maxValue / tickInterval), tickInterval); @@ -303,14 +303,14 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { var c = this.constants; if (this.config.chartDashboardType === c.NORMAL || this.config.chartDashboardType === c.HALF_DASHBOARD) { var result = []; - if (this.config.numberOfPointer === c.ONE_POINTER && items[0].length === 1) {//单个系列 + if (this.config.numberOfPointer === c.ONE_POINTER && items[0].length === 1) {// 单个系列 BI.each(items[0][0].data, function (idx, da) { result.push({ data: [BI.extend({}, da, { x: items[0][0].name })], name: da.x - }) + }); }); return [result]; } else if(this.config.numberOfPointer === c.ONE_POINTER && items[0].length > 1) { @@ -320,17 +320,17 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { x: item.name })], name: BI.UUID() - }) + }); }); - return [result] + return [result]; } - if (this.config.numberOfPointer === c.MULTI_POINTER && items[0].length > 1) {//多个系列 + if (this.config.numberOfPointer === c.MULTI_POINTER && items[0].length > 1) {// 多个系列 BI.each(items, function (idx, item) { BI.each(item, function (id, it) { var data = it.data[0]; data.x = it.name; result.push(data); - }) + }); }); return [[{ data: result, @@ -348,8 +348,8 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { y: da.y })], name: da.x - }) - }) + }); + }); }); return [others]; } @@ -395,4 +395,4 @@ BI.DashboardChart = BI.inherit(BI.AbstractChart, { } }); BI.DashboardChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.dashboard_chart', BI.DashboardChart); \ No newline at end of file +BI.shortcut("bi.dashboard_chart", BI.DashboardChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.donut.js b/src/addons/chart/chart/chart.donut.js index 0034d3177..966a3866d 100644 --- a/src/addons/chart/chart/chart.donut.js +++ b/src/addons/chart/chart/chart.donut.js @@ -8,7 +8,7 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.DonutChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-donut-chart" - }) + }); }, _init: function () { @@ -24,11 +24,11 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.DonutChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, - _formatConfig: function(config, items){ + _formatConfig: function (config, items) { var self = this; delete config.zoom; config.colors = this.config.chartColor; @@ -49,13 +49,13 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { da.y = self.formatXYDataWithMagnify(da.y, 1); - }) + }); }); config.legend.style = this.config.chartFont; return [items, config]; - function formatChartStyle(){ + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -80,9 +80,9 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { this.options.items = items; var types = []; - BI.each(items, function(idx, axisItems){ + BI.each(items, function (idx, axisItems) { var type = []; - BI.each(axisItems, function(id, item){ + BI.each(axisItems, function (id, item) { type.push(BICst.WIDGET.DONUT); }); types.push(type); @@ -95,9 +95,9 @@ BI.DonutChart = BI.inherit(BI.AbstractChart, { this.combineChart.resize(); }, - magnify: function(){ + magnify: function () { this.combineChart.magnify(); } }); BI.DonutChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.donut_chart', BI.DonutChart); \ No newline at end of file +BI.shortcut("bi.donut_chart", BI.DonutChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.fallaxis.js b/src/addons/chart/chart/chart.fallaxis.js index 9ced4197a..df940d146 100644 --- a/src/addons/chart/chart/chart.fallaxis.js +++ b/src/addons/chart/chart/chart.fallaxis.js @@ -8,7 +8,7 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.FallAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-fall-axis-chart" - }) + }); }, _init: function () { @@ -43,11 +43,11 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.FallAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, - _formatConfig: function(config, items){ + _formatConfig: function (config, items) { var self = this, o = this.options; var yTitle = getXYAxisUnit(this.config.leftYAxisNumberLevel, this.constants.LEFT_AXIS); config.colors = this.config.chartColor; @@ -56,11 +56,11 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { config.legend.enabled = false; config.plotOptions.dataLabels.enabled = this.config.showDataLabel; config.dataSheet.enabled = this.config.showDataTable; - if(config.dataSheet.enabled === true){ + if(config.dataSheet.enabled === true) { config.xAxis[0].showLabel = false; } config.zoom.zoomTool.enabled = this.config.showZoom; - if(this.config.showZoom === true){ + if(this.config.showZoom === true) { delete config.dataSheet; delete config.zoom.zoomType; } @@ -86,20 +86,20 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { enableMinorTick: this.config.enableMinorTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); - //为了给数据标签加个%,还要遍历所有的系列,唉 - if(config.plotOptions.dataLabels.enabled === true){ - BI.each(items, function(idx, item){ - if(idx === 0){ + // 为了给数据标签加个%,还要遍历所有的系列,唉 + if(config.plotOptions.dataLabels.enabled === true) { + BI.each(items, function (idx, item) { + if(idx === 0) { item.dataLabels = {}; return; } item.dataLabels = { - "style": self.config.chartFont, - "align": "outside", - "autoAdjust": true, + style: self.config.chartFont, + align: "outside", + autoAdjust: true, enabled: true, formatter: { identifier: "${VALUE}", @@ -109,12 +109,12 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { }); } - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle(){ + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -124,23 +124,23 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon(){ - BI.each(self.config.cordon, function(idx, cor){ - if(idx === 0 && self.xAxis.length > 0){ + function formatCordon () { + BI.each(self.config.cordon, function (idx, cor) { + if(idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); - self.xAxis[0].plotLines = BI.map(cor, function(i, t){ + self.xAxis[0].plotLines = BI.map(cor, function (i, t) { return BI.extend(t, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); } - if(idx > 0 && self.yAxis.length >= idx){ + if(idx > 0 && self.yAxis.length >= idx) { var magnify = 1; switch (idx - 1) { case self.constants.LEFT_AXIS: @@ -153,34 +153,34 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { magnify = self.calcMagnify(self.config.rightYAxisSecondNumberLevel); break; } - self.yAxis[idx - 1].plotLines = BI.map(cor, function(i, t){ + self.yAxis[idx - 1].plotLines = BI.map(cor, function (i, t) { return BI.extend(t, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatNumberLevelInYaxis(type, position, formatter){ + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = formatter; } - function getXYAxisUnit(numberLevelType, position){ + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -196,33 +196,33 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { unit = BI.i18nText("BI-Yi"); break; } - if(position === self.constants.X_AXIS){ - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + if(position === self.constants.X_AXIS) { + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } - if(position === self.constants.LEFT_AXIS){ - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + if(position === self.constants.LEFT_AXIS) { + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } - if(position === self.constants.RIGHT_AXIS){ - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + if(position === self.constants.RIGHT_AXIS) { + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } }, - _formatItems: function(items){ + _formatItems: function (items) { var o = this.options; - if(BI.isEmptyArray(items)){ + if(BI.isEmptyArray(items)) { return []; } items = items[0]; var tables = [], sum = 0; var colors = this.config.chartColor || []; - if(BI.isEmptyArray(colors)){ + if(BI.isEmptyArray(colors)) { colors = ["rgb(152, 118, 170)", "rgb(0, 157, 227)"]; } - BI.each(items, function(idx, item){ - BI.each(item.data, function(i, t){ - if(t.y < 0){ + BI.each(items, function (idx, item) { + BI.each(item.data, function (i, t) { + if(t.y < 0) { tables.push([t.x, t.y, sum + t.y, t]); }else{ tables.push([t.x, t.y, sum, t]); @@ -231,14 +231,14 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { }); }); - return [BI.map(BI.makeArray(2, null), function(idx, item){ + return [BI.map(BI.makeArray(2, null), function (idx, item) { return { - "data": BI.map(tables, function(id, cell){ + data: BI.map(tables, function (id, cell) { var axis = BI.extend({}, cell[3], { x: cell[0], y: Math.abs(cell[2 - idx]) }); - if(idx === 1){ + if(idx === 1) { axis.color = cell[2 - idx] < 0 ? colors[1] : colors[0]; }else{ axis.color = "rgba(0,0,0,0)"; @@ -248,7 +248,7 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { axis.mouseOverColor = "rgba(0,0,0,0)"; axis.tooltip = { enable: false - } + }; } return axis; }), @@ -287,9 +287,9 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { }; this.options.items = items; var types = []; - BI.each(items, function(idx, axisItems){ + BI.each(items, function (idx, axisItems) { var type = []; - BI.each(axisItems, function(id, item){ + BI.each(axisItems, function (id, item) { type.push(BICst.WIDGET.AXIS); }); types.push(type); @@ -302,9 +302,9 @@ BI.FallAxisChart = BI.inherit(BI.AbstractChart, { this.combineChart.resize(); }, - magnify: function(){ + magnify: function () { this.combineChart.magnify(); } }); BI.FallAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.fall_axis_chart', BI.FallAxisChart); \ No newline at end of file +BI.shortcut("bi.fall_axis_chart", BI.FallAxisChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.forcebubble.js b/src/addons/chart/chart/chart.forcebubble.js index e659dd033..d23696f64 100644 --- a/src/addons/chart/chart/chart.forcebubble.js +++ b/src/addons/chart/chart/chart.forcebubble.js @@ -8,7 +8,7 @@ BI.ForceBubbleChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.ForceBubbleChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-force-bubble-chart" - }) + }); }, _init: function () { @@ -24,13 +24,13 @@ BI.ForceBubbleChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.ForceBubbleChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, _formatConfig: function (config, items) { var self = this, o = this.options; - config.chartType = 'forceBubble'; + config.chartType = "forceBubble"; config.colors = this.config.chartColor; this.formatChartLegend(config, this.config.chartLegend); @@ -46,7 +46,7 @@ BI.ForceBubbleChart = BI.inherit(BI.AbstractChart, { BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { da.y = self.formatXYDataWithMagnify(da.y, 1); - }) + }); }); config.legend.style = this.config.chartFont; return [items, config]; @@ -84,4 +84,4 @@ BI.ForceBubbleChart = BI.inherit(BI.AbstractChart, { } }); BI.ForceBubbleChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.force_bubble_chart', BI.ForceBubbleChart); \ No newline at end of file +BI.shortcut("bi.force_bubble_chart", BI.ForceBubbleChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.gismap.js b/src/addons/chart/chart/chart.gismap.js index e26ebfa53..b217b0491 100644 --- a/src/addons/chart/chart/chart.gismap.js +++ b/src/addons/chart/chart/chart.gismap.js @@ -8,7 +8,7 @@ BI.GISMapChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.GISMapChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-gis-map-chart" - }) + }); }, _init: function () { @@ -24,7 +24,7 @@ BI.GISMapChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.GISMapChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -36,29 +36,29 @@ BI.GISMapChart = BI.inherit(BI.AbstractChart, { config.plotOptions.dataLabels.useHtml = true; config.plotOptions.dataLabels.style = this.config.chartFont; config.plotOptions.dataLabels.formatter = function () { - var name = (BI.isArray(this.name) ? '' : this.name + ',') + BI.contentFormat(this.value, '#.##;-#.##') ; + var name = (BI.isArray(this.name) ? "" : this.name + ",") + BI.contentFormat(this.value, "#.##;-#.##"); var style = "padding: 5px; background-color: rgba(0,0,0,0.4980392156862745);border-color: rgb(0,0,0); border-radius:2px; border-width:0px;"; - var a = '
    ' + name + '
    '; + var a = "
    " + name + "
    "; return a; }; config.plotOptions.tooltip.shared = true; config.plotOptions.tooltip.formatter = function () { - var tip = BI.isArray(this.name) ? '' : this.name; + var tip = BI.isArray(this.name) ? "" : this.name; BI.each(this.points, function (idx, point) { - tip += ('
    ' + point.seriesName + ':' + BI.contentFormat((point.size || point.y), '#.##;-#.##') + '
    '); + tip += ("
    " + point.seriesName + ":" + BI.contentFormat((point.size || point.y), "#.##;-#.##") + "
    "); }); return tip; }; config.geo = { - "tileLayer": "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}", - "attribution": "© 2016 AutoNavi" + tileLayer: "http://webrd01.is.autonavi.com/appmaptile?lang=zh_cn&size=1&scale=1&style=8&x={x}&y={y}&z={z}", + attribution: "© 2016 AutoNavi" }; if (this.config.showBackgroundLayer === true && BI.isNotNull(this.config.backgroundLayerInfo)) { config.geo = {}; if (this.config.backgroundLayerInfo.type === BICst.WMS_SERVER) { config.geo.tileLayer = false; config.geo.wmsUrl = this.config.backgroundLayerInfo.url; - config.geo.wmsLayer = this.config.backgroundLayerInfo.wmsLayer + config.geo.wmsLayer = this.config.backgroundLayerInfo.wmsLayer; } else { config.geo.tileLayer = this.config.backgroundLayerInfo.url; } @@ -157,4 +157,4 @@ BI.GISMapChart = BI.inherit(BI.AbstractChart, { } }); BI.GISMapChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.gis_map_chart', BI.GISMapChart); \ No newline at end of file +BI.shortcut("bi.gis_map_chart", BI.GISMapChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.line.js b/src/addons/chart/chart/chart.line.js index 69cb34598..aa42fe34a 100644 --- a/src/addons/chart/chart/chart.line.js +++ b/src/addons/chart/chart/chart.line.js @@ -8,7 +8,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.LineChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-line-chart" - }) + }); }, _init: function () { @@ -34,7 +34,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.LineChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -100,20 +100,20 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: self.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "line"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -123,7 +123,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -132,9 +132,9 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -157,17 +157,17 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatChartLineStyle() { + function formatChartLineStyle () { switch (self.config.chartLineType) { case BICst.CHART_SHAPE.RIGHT_ANGLE: config.plotOptions.curve = false; @@ -185,7 +185,7 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { } } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -202,13 +202,13 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -294,4 +294,4 @@ BI.LineChart = BI.inherit(BI.AbstractChart, { } }); BI.LineChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.line_chart', BI.LineChart); \ No newline at end of file +BI.shortcut("bi.line_chart", BI.LineChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.map.js b/src/addons/chart/chart/chart.map.js index 40b59bca1..90c79515f 100644 --- a/src/addons/chart/chart/chart.map.js +++ b/src/addons/chart/chart/chart.map.js @@ -8,7 +8,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.MapChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-map-chart" - }) + }); }, _init: function () { @@ -24,7 +24,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.MapChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -46,7 +46,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { var tip = this.name; var point = this.points[0]; var index = BI.isNull(point.size) ? 0 : 1; - tip += ('
    ' + point.seriesName + ':' + BI.contentFormat(point.size || point.y, formatterArray[index]) + '
    '); + tip += ("
    " + point.seriesName + ":" + BI.contentFormat(point.size || point.y, formatterArray[index]) + "
    "); return tip; }; config.plotOptions.dataLabels.formatter.valueFormat = function () { @@ -64,7 +64,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { if (this.config.backgroundLayerInfo.type === BICst.WMS_SERVER) { config.geo.tileLayer = false; config.geo.wmsUrl = this.config.backgroundLayerInfo.url; - config.geo.wmsLayer = this.config.backgroundLayerInfo.wmsLayer + config.geo.wmsLayer = this.config.backgroundLayerInfo.wmsLayer; } else { config.geo.tileLayer = this.config.backgroundLayerInfo.url; } @@ -89,12 +89,12 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { items.push({ type: "areaMap", data: [] - }) + }); } return [items, config]; - function formatRangeLegend() { + function formatRangeLegend () { config.rangeLegend.enabled = true; switch (self.config.chartLegend) { case BICst.CHART_LEGENDS.BOTTOM: @@ -117,36 +117,36 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { var settings = items[0].settings; var legendFormat = formatToolTipAndDataLabel(settings.format || c.NORMAL, settings.num_level || c.NORMAL, settings.unit || "", settings.numSeparators || c.NUM_SEPARATORS); - to = BI.contentFormat(to, legendFormat) + to = BI.contentFormat(to, legendFormat); } - return to + return to; }; } - function formatToolTipAndDataLabel(format, numberLevel, unit, numSeparators) { - var formatter = '#.##'; + function formatToolTipAndDataLabel (format, numberLevel, unit, numSeparators) { + var formatter = "#.##"; switch (format) { case self.constants.NORMAL: - formatter = '#.##'; - if (numSeparators) formatter = '#,###.##'; + formatter = "#.##"; + if (numSeparators) formatter = "#,###.##"; break; case self.constants.ZERO2POINT: - formatter = '#0'; - if (numSeparators) formatter = '#,###'; + formatter = "#0"; + if (numSeparators) formatter = "#,###"; break; case self.constants.ONE2POINT: - formatter = '#0.0'; - if (numSeparators) formatter = '#,###.0'; + formatter = "#0.0"; + if (numSeparators) formatter = "#,###.0"; break; case self.constants.TWO2POINT: - formatter = '#0.00'; - if (numSeparators) formatter = '#,###.00'; + formatter = "#0.00"; + if (numSeparators) formatter = "#,###.00"; break; } switch (numberLevel) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: - formatter += ''; + formatter += ""; break; case BICst.TARGET_STYLE.NUM_LEVEL.TEN_THOUSAND: formatter += BI.i18nText("BI-Wan"); @@ -158,23 +158,23 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { formatter += BI.i18nText("BI-Yi"); break; case BICst.TARGET_STYLE.NUM_LEVEL.PERCENT: - formatter += '%'; + formatter += "%"; break; } return formatter + unit; } - function getRangeStyle(styles, change, defaultColor) { + function getRangeStyle (styles, change, defaultColor) { var range = [], color = null, defaultStyle = {}; var conditionMax = null, conditionMin = null, min = null; BI.each(items, function (idx, item) { BI.each(item.data, function (id, it) { if (BI.isNull(min) || BI.parseFloat(min) > BI.parseFloat(it.y)) { - min = it.y + min = it.y; } - }) + }); }); switch (change) { @@ -196,11 +196,11 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { range.push({ color: style.color || "rgba(255,255,255,0)", from: style.range.min, - to: to, + to: to }); } color = style.color; - conditionMax = style.range.max + conditionMax = style.range.max; }); conditionMin = BI.parseFloat(styles[0].range.min); @@ -220,21 +220,21 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { }); } return range; - } else { - defaultStyle.color = defaultColor; - return defaultStyle; } + defaultStyle.color = defaultColor; + return defaultStyle; + } } - function _calculateValueNiceDomain(minValue, maxValue) { + function _calculateValueNiceDomain (minValue, maxValue) { minValue = Math.min(0, minValue); var tickInterval = _linearTickInterval(minValue, maxValue); return _linearNiceDomain(minValue, maxValue, tickInterval); } - function _linearTickInterval(minValue, maxValue, m) { + function _linearTickInterval (minValue, maxValue, m) { m = m || 5; var span = maxValue - minValue; var step = Math.pow(10, Math.floor(Math.log(span / m) / Math.LN10)); @@ -245,7 +245,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { return step; } - function _linearNiceDomain(minValue, maxValue, tickInterval) { + function _linearNiceDomain (minValue, maxValue, tickInterval) { minValue = VanUtils.accMul(Math.floor(minValue / tickInterval), tickInterval); maxValue = VanUtils.accMul(Math.ceil(maxValue / tickInterval), tickInterval); @@ -313,7 +313,7 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { self._formatDrillItems(da.drilldown); } }); - }) + }); }); return items; }, @@ -358,4 +358,4 @@ BI.MapChart = BI.inherit(BI.AbstractChart, { }); BI.MapChart.EVENT_CHANGE = "EVENT_CHANGE"; BI.MapChart.EVENT_CLICK_DTOOL = "EVENT_CLICK_DTOOL"; -BI.shortcut('bi.map_chart', BI.MapChart); \ No newline at end of file +BI.shortcut("bi.map_chart", BI.MapChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.multiaxis.js b/src/addons/chart/chart/chart.multiaxis.js index 9b627f587..33f869df3 100644 --- a/src/addons/chart/chart/chart.multiaxis.js +++ b/src/addons/chart/chart/chart.multiaxis.js @@ -11,7 +11,7 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.MultiAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-multi-axis-chart" - }) + }); }, _init: function () { @@ -20,10 +20,10 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { this.xAxis = [{ type: "category", title: { - style: {"fontFamily": "inherit", "color": "#808080", "fontSize": "12px", "fontWeight": ""} + style: {fontFamily: "inherit", color: "#808080", fontSize: "12px", fontWeight: ""} }, labelStyle: { - "fontFamily": "inherit", "color": "#808080", "fontSize": "12px" + fontFamily: "inherit", color: "#808080", fontSize: "12px" }, position: "bottom", gridLineWidth: 0 @@ -39,7 +39,7 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.MultiAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -120,13 +120,13 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 if (config.dataSheet) { config.dataSheet.style = this.config.chartFont; } @@ -161,14 +161,14 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": { - "fontFamily": "inherit", - "color": "#808080", - "fontSize": "12px", - "fontWeight": "" + style: { + fontFamily: "inherit", + color: "#808080", + fontSize: "12px", + fontWeight: "" }, - "text": t.text, - "align": "top" + text: t.text, + align: "top" } }); }); @@ -193,19 +193,19 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": { - "fontFamily": "inherit", - "color": "#808080", - "fontSize": "12px", - "fontWeight": "" + style: { + fontFamily: "inherit", + color: "#808080", + fontSize: "12px", + fontWeight: "" }, - "text": t.text, - "align": "left" + text: t.text, + align: "left" } }); }); } - }) + }); }, getXYAxisUnit: function (numberLevelType, position) { @@ -227,16 +227,16 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { break; } if (position === this.constants.X_AXIS) { - this.config.xAxisUnit !== "" && (unit = unit + this.config.xAxisUnit) + this.config.xAxisUnit !== "" && (unit = unit + this.config.xAxisUnit); } if (position === this.constants.LEFT_AXIS) { - this.config.leftYAxisUnit !== "" && (unit = unit + this.config.leftYAxisUnit) + this.config.leftYAxisUnit !== "" && (unit = unit + this.config.leftYAxisUnit); } if (position === this.constants.RIGHT_AXIS) { - this.config.rightYAxisUnit !== "" && (unit = unit + this.config.rightYAxisUnit) + this.config.rightYAxisUnit !== "" && (unit = unit + this.config.rightYAxisUnit); } if (position === this.constants.RIGHT_AXIS_SECOND) { - this.config.rightYAxisSecondUnit !== "" && (unit = unit + this.config.rightYAxisSecondUnit) + this.config.rightYAxisSecondUnit !== "" && (unit = unit + this.config.rightYAxisSecondUnit); } return unit === "" ? unit : "(" + unit + ")"; }, @@ -294,10 +294,10 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { var newYAxis = { type: "value", title: { - style: {"fontFamily": "inherit", "color": "#808080", "fontSize": "12px", "fontWeight": ""} + style: {fontFamily: "inherit", color: "#808080", fontSize: "12px", fontWeight: ""} }, labelStyle: { - "fontFamily": "inherit", "color": "#808080", "fontSize": "12px" + fontFamily: "inherit", color: "#808080", fontSize: "12px" }, position: idx > 0 ? "right" : "left", lineWidth: 1, @@ -319,4 +319,4 @@ BI.MultiAxisChart = BI.inherit(BI.AbstractChart, { } }); BI.MultiAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_axis_chart', BI.MultiAxisChart); \ No newline at end of file +BI.shortcut("bi.multi_axis_chart", BI.MultiAxisChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.multiaxiscombine.js b/src/addons/chart/chart/chart.multiaxiscombine.js index 1a2b9da7e..020c4bac4 100644 --- a/src/addons/chart/chart/chart.multiaxiscombine.js +++ b/src/addons/chart/chart/chart.multiaxiscombine.js @@ -11,7 +11,7 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.MultiAxisCombineChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-multi-axis-combine-chart" - }) + }); }, _init: function () { @@ -20,10 +20,10 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { this.xAxis = [{ type: "category", title: { - style: {"fontFamily": "inherit", "color": "#808080", "fontSize": "12px", "fontWeight": ""} + style: {fontFamily: "inherit", color: "#808080", fontSize: "12px", fontWeight: ""} }, labelStyle: { - "fontFamily": "inherit", "color": "#808080", "fontSize": "12px" + fontFamily: "inherit", color: "#808080", fontSize: "12px" }, position: "bottom", gridLineWidth: 0 @@ -39,7 +39,7 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.MultiAxisCombineChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -123,13 +123,13 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabel(config.plotOptions.dataLabels.enabled, items, config, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 if (config.dataSheet) { config.dataSheet.style = this.config.chartFont; } @@ -164,14 +164,14 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": { - "fontFamily": "inherit", - "color": "#808080", - "fontSize": "12px", - "fontWeight": "" + style: { + fontFamily: "inherit", + color: "#808080", + fontSize: "12px", + fontWeight: "" }, - "text": t.text, - "align": "top" + text: t.text, + align: "top" } }); }); @@ -196,19 +196,19 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": { - "fontFamily": "inherit", - "color": "#808080", - "fontSize": "12px", - "fontWeight": "" + style: { + fontFamily: "inherit", + color: "#808080", + fontSize: "12px", + fontWeight: "" }, - "text": t.text, - "align": "left" + text: t.text, + align: "left" } }); }); } - }) + }); }, getXYAxisUnit: function (numberLevelType, position) { @@ -230,16 +230,16 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { break; } if (position === this.constants.X_AXIS) { - this.config.xAxisUnit !== "" && (unit = unit + this.config.xAxisUnit) + this.config.xAxisUnit !== "" && (unit = unit + this.config.xAxisUnit); } if (position === this.constants.LEFT_AXIS) { - this.config.leftYAxisUnit !== "" && (unit = unit + this.config.leftYAxisUnit) + this.config.leftYAxisUnit !== "" && (unit = unit + this.config.leftYAxisUnit); } if (position === this.constants.RIGHT_AXIS) { - this.config.rightYAxisUnit !== "" && (unit = unit + this.config.rightYAxisUnit) + this.config.rightYAxisUnit !== "" && (unit = unit + this.config.rightYAxisUnit); } if (position === this.constants.RIGHT_AXIS_SECOND) { - this.config.rightYAxisSecondUnit !== "" && (unit = unit + this.config.rightYAxisSecondUnit) + this.config.rightYAxisSecondUnit !== "" && (unit = unit + this.config.rightYAxisSecondUnit); } return unit === "" ? unit : "(" + unit + ")"; }, @@ -296,10 +296,10 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { var newYAxis = { type: "value", title: { - style: {"fontFamily": "inherit", "color": "#808080", "fontSize": "12px", "fontWeight": ""} + style: {fontFamily: "inherit", color: "#808080", fontSize: "12px", fontWeight: ""} }, labelStyle: { - "fontFamily": "inherit", "color": "#808080", "fontSize": "12px" + fontFamily: "inherit", color: "#808080", fontSize: "12px" }, position: idx > 0 ? "right" : "left", lineWidth: 1, @@ -321,4 +321,4 @@ BI.MultiAxisCombineChart = BI.inherit(BI.AbstractChart, { } }); BI.MultiAxisCombineChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_axis_combine_chart', BI.MultiAxisCombineChart); \ No newline at end of file +BI.shortcut("bi.multi_axis_combine_chart", BI.MultiAxisCombineChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.percentaccumulatearea.js b/src/addons/chart/chart/chart.percentaccumulatearea.js index fb59cc175..c4020b36c 100644 --- a/src/addons/chart/chart/chart.percentaccumulatearea.js +++ b/src/addons/chart/chart/chart.percentaccumulatearea.js @@ -8,7 +8,7 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.PercentAccumulateAreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-percent-accumulate-area-chart" - }) + }); }, _init: function () { @@ -43,7 +43,7 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.PercentAccumulateAreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -84,20 +84,20 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.yAxis[0].formatter, this.config.chartFont, true); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -107,7 +107,7 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -116,9 +116,9 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -141,17 +141,17 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -168,15 +168,15 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } unit = unit === "" ? unit : "(" + unit + ")"; - return self.config.showLeftYAxisTitle === true ? self.config.leftYAxisTitle + unit : unit + return self.config.showLeftYAxisTitle === true ? self.config.leftYAxisTitle + unit : unit; } }, @@ -242,4 +242,4 @@ BI.PercentAccumulateAreaChart = BI.inherit(BI.AbstractChart, { } }); BI.PercentAccumulateAreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.percent_accumulate_area_chart', BI.PercentAccumulateAreaChart); \ No newline at end of file +BI.shortcut("bi.percent_accumulate_area_chart", BI.PercentAccumulateAreaChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.percentaccumulateaxis.js b/src/addons/chart/chart/chart.percentaccumulateaxis.js index b3a6a2e35..b7ced4edb 100644 --- a/src/addons/chart/chart/chart.percentaccumulateaxis.js +++ b/src/addons/chart/chart/chart.percentaccumulateaxis.js @@ -8,7 +8,7 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.PercentAccumulateAxisChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-percent-accumulate-axis-chart" - }) + }); }, _init: function () { @@ -43,7 +43,7 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.PercentAccumulateAxisChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -85,18 +85,18 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { labelRotation: this.config.textDirection, enableMinorTick: this.config.enableMinorTick, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.yAxis[0].formatter, this.config.chartFont, true); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -106,7 +106,7 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -115,9 +115,9 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -140,17 +140,17 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -167,10 +167,10 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -237,4 +237,4 @@ BI.PercentAccumulateAxisChart = BI.inherit(BI.AbstractChart, { } }); BI.PercentAccumulateAxisChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.percent_accumulate_axis_chart', BI.PercentAccumulateAxisChart); \ No newline at end of file +BI.shortcut("bi.percent_accumulate_axis_chart", BI.PercentAccumulateAxisChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.pie.js b/src/addons/chart/chart/chart.pie.js index a8a0029ef..7c9608af7 100644 --- a/src/addons/chart/chart/chart.pie.js +++ b/src/addons/chart/chart/chart.pie.js @@ -8,7 +8,7 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.PieChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-pie-chart" - }) + }); }, _init: function () { @@ -24,11 +24,11 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.PieChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, - _formatConfig: function(config, items){ + _formatConfig: function (config, items) { var self = this, o = this.options; delete config.zoom; config.colors = this.config.chartColor; @@ -50,14 +50,14 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { da.y = self.formatXYDataWithMagnify(da.y, 1); - }) + }); }); config.legend.style = this.config.chartFont; return [items, config]; - function formatChartStyle(){ + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -67,8 +67,8 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { } } - function formatChartPieStyle(){ - switch (self.config.chartPieType){ + function formatChartPieStyle () { + switch (self.config.chartPieType) { case BICst.CHART_SHAPE.EQUAL_ARC_ROSE: config.plotOptions.roseType = "sameArc"; break; @@ -86,31 +86,31 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { }, - //目前饼图不会有多个系列,如果有多个就要把它们合并在一起 - _isNeedConvert: function(items){ - var result = BI.find(items, function(idx, item){ + // 目前饼图不会有多个系列,如果有多个就要把它们合并在一起 + _isNeedConvert: function (items) { + var result = BI.find(items, function (idx, item) { return item.length > 1; }); return BI.isNotNull(result); }, - _formatItems: function(items){ - if(this._isNeedConvert(items)){ - //把每个坐标轴所有的多个系列合并成一个系列 - return BI.map(items, function(idx, item){ + _formatItems: function (items) { + if(this._isNeedConvert(items)) { + // 把每个坐标轴所有的多个系列合并成一个系列 + return BI.map(items, function (idx, item) { var seriesItem = []; var obj = {data: [], name: ""}; seriesItem.push(obj); - BI.each(item, function(id, series){ - BI.each(series.data, function(i, da){ + BI.each(item, function (id, series) { + BI.each(series.data, function (i, da) { obj.data.push(BI.extend({}, da, {x: series.name})); }); }); return seriesItem; - }) - }else{ - return items; + }); } + return items; + }, populate: function (items, options) { @@ -129,9 +129,9 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { this.options.items = items; var types = []; - BI.each(items, function(idx, axisItems){ + BI.each(items, function (idx, axisItems) { var type = []; - BI.each(axisItems, function(id, item){ + BI.each(axisItems, function (id, item) { type.push(BICst.WIDGET.PIE); }); types.push(type); @@ -144,10 +144,10 @@ BI.PieChart = BI.inherit(BI.AbstractChart, { this.combineChart.resize(); }, - magnify: function(){ + magnify: function () { this.combineChart.magnify(); } }); BI.PieChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.pie_chart', BI.PieChart); +BI.shortcut("bi.pie_chart", BI.PieChart); diff --git a/src/addons/chart/chart/chart.radar.js b/src/addons/chart/chart/chart.radar.js index 74d997afd..b64ae5e12 100644 --- a/src/addons/chart/chart/chart.radar.js +++ b/src/addons/chart/chart/chart.radar.js @@ -8,7 +8,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.RadarChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-radar-chart" - }) + }); }, _init: function () { @@ -21,7 +21,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { }, labelStyle: this.constants.FONT_STYLE, formatter: function () { - return this > 0 ? this : (-1) * this + return this > 0 ? this : (-1) * this; }, gridLineWidth: 0, position: "bottom" @@ -45,7 +45,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.RadarChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -72,17 +72,17 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { config.chartType = "radar"; delete config.xAxis; delete config.yAxis; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.radiusAxis[0].formatter, this.config.chartFont); - //全局样式 + // 全局样式 config.legend.style = this.config.chartFont; config.radiusAxis[0].title.style = config.radiusAxis[0].labelStyle = this.config.chartFont; config.angleAxis[0].title.style = config.angleAxis[0].labelStyle = this.config.chartFont; return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -92,7 +92,7 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { } } - function formatChartRadarStyle() { + function formatChartRadarStyle () { switch (self.config.chartRadarType) { case BICst.CHART_SHAPE.POLYGON: config.plotOptions.shape = "polygon"; @@ -103,19 +103,19 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { } } - function formatNumberLevelInYaxis(type, position, formatter) { + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = formatter; } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -132,13 +132,13 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -182,4 +182,4 @@ BI.RadarChart = BI.inherit(BI.AbstractChart, { } }); BI.RadarChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.radar_chart', BI.RadarChart); \ No newline at end of file +BI.shortcut("bi.radar_chart", BI.RadarChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.rangearea.js b/src/addons/chart/chart/chart.rangearea.js index 695359f57..d692a7455 100644 --- a/src/addons/chart/chart/chart.rangearea.js +++ b/src/addons/chart/chart/chart.rangearea.js @@ -9,7 +9,7 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.RangeAreaChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-range-area-chart" - }) + }); }, _init: function () { @@ -44,7 +44,7 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.RangeAreaChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -79,21 +79,21 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { enableTick: this.config.enableTick, labelRotation: this.config.textDirection, gridLineWidth: this.config.showGridLine === true ? 1 : 0, - maxHeight: '40%' + maxHeight: "40%" }); config.chartType = "area"; config.plotOptions.tooltip.formatter.identifier = "${CATEGORY}${VALUE}"; - //为了给数据标签加个%,还要遍历所有的系列,唉 + // 为了给数据标签加个%,还要遍历所有的系列,唉 this.formatDataLabelForAxis(config.plotOptions.dataLabels.enabled, items, config.yAxis[0].formatter, this.config.chartFont); - //全局样式的图表文字 + // 全局样式的图表文字 this.setFontStyle(this.config.chartFont, config); return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -103,7 +103,7 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -112,9 +112,9 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -137,29 +137,29 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style" : self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatNumberLevelInYaxis(type, position, formatter) { + function formatNumberLevelInYaxis (type, position, formatter) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { if (position === item.yAxis) { da.y = self.formatXYDataWithMagnify(da.y, magnify); } - }) + }); }); config.plotOptions.tooltip.formatter.valueFormat = formatter; } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -176,10 +176,10 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -281,4 +281,4 @@ BI.RangeAreaChart = BI.inherit(BI.AbstractChart, { } }); BI.RangeAreaChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.range_area_chart', BI.RangeAreaChart); \ No newline at end of file +BI.shortcut("bi.range_area_chart", BI.RangeAreaChart); \ No newline at end of file diff --git a/src/addons/chart/chart/chart.scatter.js b/src/addons/chart/chart/chart.scatter.js index 42b5945da..9fabe6808 100644 --- a/src/addons/chart/chart/chart.scatter.js +++ b/src/addons/chart/chart/chart.scatter.js @@ -8,7 +8,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { _defaultConfig: function () { return BI.extend(BI.ScatterChart.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-scatter-chart" - }) + }); }, _init: function () { @@ -43,7 +43,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { self.fireEvent(BI.ScatterChart.EVENT_CHANGE, obj); }); this.combineChart.on(BI.CombineChart.EVENT_ITEM_CLICK, function (obj) { - self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj) + self.fireEvent(BI.AbstractChart.EVENT_ITEM_CLICK, obj); }); }, @@ -53,7 +53,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { delete config.zoom; config.colors = this.config.chartColor; config.style = formatChartStyle(); - config.plotOptions.marker = {"symbol": "circle", "radius": 4.5, "enabled": true}; + config.plotOptions.marker = {symbol: "circle", radius: 4.5, enabled: true}; formatCordon(); this.formatChartLegend(config, this.config.chartLegend); config.plotOptions.dataLabels.enabled = this.config.showDataLabel; @@ -68,7 +68,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { config.yAxis[0].title.text = this.config.showLeftYAxisTitle === true ? this.config.leftYAxisTitle + config.yAxis[0].title.text : config.yAxis[0].title.text; config.yAxis[0].gridLineWidth = this.config.showGridLine === true ? 1 : 0; config.yAxis[0].title.rotation = this.constants.ROTATION; - config.yAxis[0].maxWidth = '40%'; + config.yAxis[0].maxWidth = "40%"; config.xAxis[0].formatter = self.formatTickInXYaxis(this.config.xAxisStyle, this.config.xAxisNumberLevel, this.config.rightNumSeparators); formatNumberLevelInXaxis(this.config.xAxisNumberLevel); @@ -76,32 +76,32 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { config.xAxis[0].title.text = this.config.showXAxisTitle === true ? this.config.xAxisTitle + config.xAxis[0].title.text : config.xAxis[0].title.text; config.xAxis[0].title.align = "center"; config.xAxis[0].gridLineWidth = this.config.showGridLine === true ? 1 : 0; - config.xAxis[0].maxHeight = '40%'; + config.xAxis[0].maxHeight = "40%"; config.chartType = "scatter"; if (BI.isNotEmptyArray(this.config.tooltip)) { config.plotOptions.tooltip.formatter = function () { var y = self.formatTickInXYaxis(self.config.leftYAxisStyle, self.config.leftYAxisNumberLevel, self.config.numSeparators)(this.y); var x = self.formatTickInXYaxis(self.config.xAxisStyle, self.config.xAxisNumberLevel, self.config.rightNumSeparators)(this.x); - return this.seriesName + '
    (X)' + self.config.tooltip[0] - + ':' + x + '
    (Y)' + self.config.tooltip[1] + ':' + y + '
    ' + return this.seriesName + "
    (X)" + self.config.tooltip[0] + + ":" + x + "
    (Y)" + self.config.tooltip[1] + ":" + y + "
    "; }; } if (config.plotOptions.dataLabels.enabled === true) { BI.each(items, function (idx, item) { item.dataLabels = { - "style": self.config.chartFont, - "align": "outside", - "autoAdjust": true, + style: self.config.chartFont, + align: "outside", + autoAdjust: true, enabled: true, formatter: { identifier: "${X}${Y}", - "XFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + XFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); }, - "YFormat": function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + YFormat: function () { + return BI.contentFormat(arguments[0], "#.##;-#.##"); } } }; @@ -110,14 +110,14 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { }); } - //全局样式图表文字 + // 全局样式图表文字 config.legend.style = this.config.chartFont; config.yAxis[0].title.style = config.yAxis[0].labelStyle = this.config.chartFont; config.xAxis[0].title.style = config.xAxis[0].labelStyle = this.config.chartFont; return [items, config]; - function formatChartStyle() { + function formatChartStyle () { switch (self.config.chartStyle) { case BICst.CHART_STYLE.STYLE_GRADUAL: return "gradual"; @@ -127,7 +127,7 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { } } - function formatCordon() { + function formatCordon () { BI.each(self.config.cordon, function (idx, cor) { if (idx === 0 && self.xAxis.length > 0) { var magnify = self.calcMagnify(self.config.xAxisNumberLevel); @@ -136,9 +136,9 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "top" + style: self.config.chartFont, + text: t.text, + align: "top" } }); }); @@ -161,35 +161,35 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { value: t.value.div(magnify), width: 1, label: { - "style": self.config.chartFont, - "text": t.text, - "align": "left" + style: self.config.chartFont, + text: t.text, + align: "left" } }); }); } - }) + }); } - function formatNumberLevelInXaxis(type) { + function formatNumberLevelInXaxis (type) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { da.x = self.formatXYDataWithMagnify(da.x, magnify); - }) - }) + }); + }); } - function formatNumberLevelInYaxis(type) { + function formatNumberLevelInYaxis (type) { var magnify = self.calcMagnify(type); BI.each(items, function (idx, item) { BI.each(item.data, function (id, da) { - da.y = self.formatXYDataWithMagnify(da.y, magnify); - }) + da.y = self.formatXYDataWithMagnify(da.y, magnify); + }); }); } - function getXYAxisUnit(numberLevelType, position) { + function getXYAxisUnit (numberLevelType, position) { var unit = ""; switch (numberLevelType) { case BICst.TARGET_STYLE.NUM_LEVEL.NORMAL: @@ -206,13 +206,13 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { break; } if (position === self.constants.X_AXIS) { - self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit) + self.config.xAxisUnit !== "" && (unit = unit + self.config.xAxisUnit); } if (position === self.constants.LEFT_AXIS) { - self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit) + self.config.leftYAxisUnit !== "" && (unit = unit + self.config.leftYAxisUnit); } if (position === self.constants.RIGHT_AXIS) { - self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit) + self.config.rightYAxisUnit !== "" && (unit = unit + self.config.rightYAxisUnit); } return unit === "" ? unit : "(" + unit + ")"; } @@ -263,4 +263,4 @@ BI.ScatterChart = BI.inherit(BI.AbstractChart, { } }); BI.ScatterChart.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.scatter_chart', BI.ScatterChart); \ No newline at end of file +BI.shortcut("bi.scatter_chart", BI.ScatterChart); \ No newline at end of file diff --git a/src/addons/chart/factory.charts.js b/src/addons/chart/factory.charts.js index 405943a22..f31b75a17 100644 --- a/src/addons/chart/factory.charts.js +++ b/src/addons/chart/factory.charts.js @@ -12,55 +12,55 @@ BI.ChartCombineFormatItemFactory = { case BICst.WIDGET.BAR: case BICst.WIDGET.ACCUMULATE_BAR: case BICst.WIDGET.COMPARE_BAR: - item = BI.extend({"type": "bar"}, items); + item = BI.extend({type: "bar"}, items); break; case BICst.WIDGET.BUBBLE: - item = BI.extend({"type": "bubble"}, items); + item = BI.extend({type: "bubble"}, items); break; case BICst.WIDGET.FORCE_BUBBLE: - item = BI.extend({"type": "forceBubble"}, items); + item = BI.extend({type: "forceBubble"}, items); break; case BICst.WIDGET.SCATTER: - item = BI.extend({"type": "scatter"}, items); + item = BI.extend({type: "scatter"}, items); break; case BICst.WIDGET.AXIS: case BICst.WIDGET.ACCUMULATE_AXIS: case BICst.WIDGET.PERCENT_ACCUMULATE_AXIS: case BICst.WIDGET.COMPARE_AXIS: case BICst.WIDGET.FALL_AXIS: - item = BI.extend({"type": "column"}, items); + item = BI.extend({type: "column"}, items); break; case BICst.WIDGET.LINE: - item = BI.extend({"type": "line"}, items); + item = BI.extend({type: "line"}, items); break; case BICst.WIDGET.AREA: case BICst.WIDGET.ACCUMULATE_AREA: case BICst.WIDGET.COMPARE_AREA: case BICst.WIDGET.RANGE_AREA: case BICst.WIDGET.PERCENT_ACCUMULATE_AREA: - item = BI.extend({"type": "area"}, items); + item = BI.extend({type: "area"}, items); break; case BICst.WIDGET.DONUT: - item = BI.extend({"type": "pie"}, items); + item = BI.extend({type: "pie"}, items); break; case BICst.WIDGET.RADAR: case BICst.WIDGET.ACCUMULATE_RADAR: - item = BI.extend({"type": "radar"}, items); + item = BI.extend({type: "radar"}, items); break; case BICst.WIDGET.PIE: - item = BI.extend({"type": "pie"}, items); + item = BI.extend({type: "pie"}, items); break; case BICst.WIDGET.DASHBOARD: - item = BI.extend({"type": "gauge"}, items); + item = BI.extend({type: "gauge"}, items); break; case BICst.WIDGET.MAP: - item = BI.extend({"type": "areaMap"}, items); + item = BI.extend({type: "areaMap"}, items); break; case BICst.WIDGET.GIS_MAP: - item = BI.extend({"type": "pointMap"}, items); + item = BI.extend({type: "pointMap"}, items); break; default: - item = BI.extend({"type": "column"}, items); + item = BI.extend({type: "column"}, items); break; } return item; @@ -68,177 +68,177 @@ BI.ChartCombineFormatItemFactory = { combineConfig: function () { return { - "title": "", - "chartType": "column", - "plotOptions": { - "rotatable": false, - "startAngle": 0, - "borderRadius": 0, - "endAngle": 360, - "innerRadius": "0.0%", - "layout": "horizontal", - "hinge": "rgb(101,107,109)", - "dataLabels": { - "autoAdjust": true, - "style": {"fontFamily": "inherit", "color": "inherit", "fontSize": "12px"}, - "formatter": { - "identifier": "${VALUE}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat, - "XFormat": this._contentFormat2Decimal, - "YFormat": this._contentFormat2Decimal, - "sizeFormat": this._contentFormat2Decimal + title: "", + chartType: "column", + plotOptions: { + rotatable: false, + startAngle: 0, + borderRadius: 0, + endAngle: 360, + innerRadius: "0.0%", + layout: "horizontal", + hinge: "rgb(101,107,109)", + dataLabels: { + autoAdjust: true, + style: {fontFamily: "inherit", color: "inherit", fontSize: "12px"}, + formatter: { + identifier: "${VALUE}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat, + XFormat: this._contentFormat2Decimal, + YFormat: this._contentFormat2Decimal, + sizeFormat: this._contentFormat2Decimal }, - "align": "outside", - "enabled": false + align: "outside", + enabled: false }, - "percentageLabel": { - "formatter": { - "identifier": "${PERCENT}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat + percentageLabel: { + formatter: { + identifier: "${PERCENT}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat }, - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" }, - "align": "bottom", - "enabled": true + align: "bottom", + enabled: true }, - "valueLabel": { - "formatter": { - "identifier": "${SERIES}${VALUE}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat + valueLabel: { + formatter: { + identifier: "${SERIES}${VALUE}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat }, - "backgroundColor": "rgb(255,255,0)", - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + backgroundColor: "rgb(255,255,0)", + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" }, - "align": "inside", - "enabled": true + align: "inside", + enabled: true }, - "hingeBackgroundColor": "rgb(220,242,249)", - "seriesLabel": { - "formatter": { - "identifier": "${CATEGORY}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat + hingeBackgroundColor: "rgb(220,242,249)", + seriesLabel: { + formatter: { + identifier: "${CATEGORY}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat }, - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" }, - "align": "bottom", - "enabled": true + align: "bottom", + enabled: true }, - "paneBackgroundColor": "rgb(252,252,252)", - "needle": "rgb(229,113,90)", - "large": false, - "connectNulls": false, - "shadow": true, - "curve": false, - "sizeBy": "area", - "tooltip": { - "formatter": { - "identifier": "${SERIES}${X}${Y}${SIZE}{CATEGORY}${SERIES}${VALUE}", - "valueFormat": this._contentFormat2Decimal, - "seriesFormat": this._contentFormat, - "percentFormat": this._contentFormatPercentage, - "categoryFormat": this._contentFormat, - "XFormat": this._contentFormat2Decimal, - "sizeFormat": this._contentFormat2Decimal, - "YFormat": this._contentFormat2Decimal + paneBackgroundColor: "rgb(252,252,252)", + needle: "rgb(229,113,90)", + large: false, + connectNulls: false, + shadow: true, + curve: false, + sizeBy: "area", + tooltip: { + formatter: { + identifier: "${SERIES}${X}${Y}${SIZE}{CATEGORY}${SERIES}${VALUE}", + valueFormat: this._contentFormat2Decimal, + seriesFormat: this._contentFormat, + percentFormat: this._contentFormatPercentage, + categoryFormat: this._contentFormat, + XFormat: this._contentFormat2Decimal, + sizeFormat: this._contentFormat2Decimal, + YFormat: this._contentFormat2Decimal }, - "shared": false, - "padding": 5, - "backgroundColor": "rgba(0,0,0,0.4980392156862745)", - "borderColor": "rgb(0,0,0)", - "shadow": false, - "borderRadius": 2, - "borderWidth": 0, - "follow": false, - "enabled": true, - "animation": true, - "style": { - "fontFamily": "Microsoft YaHei, Hiragino Sans GB W3", - "color": "#c4c6c6", - "fontSize": "12px", - "fontWeight": "" + shared: false, + padding: 5, + backgroundColor: "rgba(0,0,0,0.4980392156862745)", + borderColor: "rgb(0,0,0)", + shadow: false, + borderRadius: 2, + borderWidth: 0, + follow: false, + enabled: true, + animation: true, + style: { + fontFamily: "Microsoft YaHei, Hiragino Sans GB W3", + color: "#c4c6c6", + fontSize: "12px", + fontWeight: "" } }, - "maxSize": 80, - "fillColorOpacity": 0.5, - "step": false, - "force": false, - "minSize": 15, - "displayNegative": true, - "categoryGap": "16.0%", - "borderColor": "rgb(255,255,255)", - "borderWidth": 1, - "gap": "22.0%", - "animation": true, - "lineWidth": 2, - "bubble": { - "large": false, - "connectNulls": false, - "shadow": true, - "curve": false, - "sizeBy": "area", - "maxSize": 80, - "minSize": 15, - "lineWidth": 0, - "animation": true, - "fillColorOpacity": 0.699999988079071, - "marker": { - "symbol": "circle", - "radius": 28.39695010101295, - "enabled": true + maxSize: 80, + fillColorOpacity: 0.5, + step: false, + force: false, + minSize: 15, + displayNegative: true, + categoryGap: "16.0%", + borderColor: "rgb(255,255,255)", + borderWidth: 1, + gap: "22.0%", + animation: true, + lineWidth: 2, + bubble: { + large: false, + connectNulls: false, + shadow: true, + curve: false, + sizeBy: "area", + maxSize: 80, + minSize: 15, + lineWidth: 0, + animation: true, + fillColorOpacity: 0.699999988079071, + marker: { + symbol: "circle", + radius: 28.39695010101295, + enabled: true } } }, - "dTools": { - "enabled": false, - "style": { - "fontFamily": "Microsoft YaHei, Hiragino Sans GB W3", - "color": "#1a1a1a", - "fontSize": "12px" + dTools: { + enabled: false, + style: { + fontFamily: "Microsoft YaHei, Hiragino Sans GB W3", + color: "#1a1a1a", + fontSize: "12px" }, - "backgroundColor": 'white' + backgroundColor: "white" }, - "dataSheet": { - "enabled": false, - "borderColor": "rgb(0,0,0)", - "borderWidth": 1, - "formatter": this._contentFormat2Decimal, - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + dataSheet: { + enabled: false, + borderColor: "rgb(0,0,0)", + borderWidth: 1, + formatter: this._contentFormat2Decimal, + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" } }, - "borderColor": "rgb(238,238,238)", - "shadow": false, - "legend": { - "borderColor": "rgb(204,204,204)", - "borderRadius": 0, - "shadow": false, - "borderWidth": 0, - "visible": true, - "style": { - "fontFamily": "inherit", "color": "inherit", "fontSize": "12px" + borderColor: "rgb(238,238,238)", + shadow: false, + legend: { + borderColor: "rgb(204,204,204)", + borderRadius: 0, + shadow: false, + borderWidth: 0, + visible: true, + style: { + fontFamily: "inherit", color: "inherit", fontSize: "12px" }, - "position": "right", - "enabled": false + position: "right", + enabled: false }, - "rangeLegend": { - "range": { - "min": 0, - "color": [ + rangeLegend: { + range: { + min: 0, + color: [ [ 0, "rgb(182,226,255)" @@ -252,40 +252,40 @@ BI.ChartCombineFormatItemFactory = { "rgb(36,167,255)" ] ], - "max": 266393 + max: 266393 }, - "enabled": false + enabled: false }, - "zoom": {"zoomType": "xy", "zoomTool": {"visible": false, "resize": true, "from": "", "to": ""}}, - "plotBorderColor": "rgba(255,255,255,0)", - "tools": { - "hidden": false, - "toImage": {"enabled": false}, - "sort": {"enabled": false}, - "fullScreen": {"enabled": false}, - "refresh": { - "enabled": false + zoom: {zoomType: "xy", zoomTool: {visible: false, resize: true, from: "", to: ""}}, + plotBorderColor: "rgba(255,255,255,0)", + tools: { + hidden: false, + toImage: {enabled: false}, + sort: {enabled: false}, + fullScreen: {enabled: false}, + refresh: { + enabled: false } }, - "plotBorderWidth": 0, - "style": "normal", - "colors": ["rgb(99,178,238)", "rgb(118,218,145)"], - "borderRadius": 0, - "borderWidth": 0, - "plotShadow": false, - "plotBorderRadius": 0 + plotBorderWidth: 0, + style: "normal", + colors: ["rgb(99,178,238)", "rgb(118,218,145)"], + borderRadius: 0, + borderWidth: 0, + plotShadow: false, + plotBorderRadius: 0 }; }, _contentFormat: function () { - return BI.contentFormat(arguments[0], '') + return BI.contentFormat(arguments[0], ""); }, _contentFormat2Decimal: function () { - return BI.contentFormat(arguments[0], '#.##;-#.##') + return BI.contentFormat(arguments[0], "#.##;-#.##"); }, _contentFormatPercentage: function () { - return BI.contentFormat(arguments[0], '#.##%;-#.##%') + return BI.contentFormat(arguments[0], "#.##%;-#.##%"); } }; \ No newline at end of file diff --git a/src/base/canvas/canvas.js b/src/base/canvas/canvas.js index 0a80d0f28..3915f0b8f 100644 --- a/src/base/canvas/canvas.js +++ b/src/base/canvas/canvas.js @@ -10,14 +10,14 @@ BI.Canvas = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Canvas.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-canvas" - }) + }); }, _init: function () { BI.Canvas.superclass._init.apply(this, arguments); var self = this, o = this.options; var canvas = document.createElement("canvas"); - if (!document.createElement('canvas').getContext) { + if (!document.createElement("canvas").getContext) { canvas = window.G_vmlCanvasManager.initElement(canvas); } this.element.append(canvas); @@ -35,7 +35,7 @@ BI.Canvas = BI.inherit(BI.Widget, { _getContext: function () { if (!this.ctx) { - this.ctx = this.canvas.getContext('2d'); + this.ctx = this.canvas.getContext("2d"); } return this.ctx; }, @@ -119,7 +119,7 @@ BI.Canvas = BI.inherit(BI.Widget, { stroke: function () { var ctx = this._getContext(); - if(!ctx){ + if(!ctx) { return false; } BI.each(this._queue, function (i, q) { diff --git a/src/base/collection/collection.js b/src/base/collection/collection.js index 5e224e7ba..0b8b03587 100644 --- a/src/base/collection/collection.js +++ b/src/base/collection/collection.js @@ -100,7 +100,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { _cellRenderers: function (height, width, x, y) { this._lastRenderedCellIndices = this._sectionManager.getCellIndices(height, width, x, y); - return this._cellGroupRenderer() + return this._cellGroupRenderer(); }, _cellGroupRenderer: function () { @@ -122,13 +122,13 @@ BI.CollectionView = BI.inherit(BI.Widget, { var right = Math.min(this._width, scrollLeft + o.width + o.horizontalOverscanSize); var bottom = Math.min(this._height, scrollTop + o.height + o.verticalOverscanSize); if (right > 0 && bottom > 0) { - //如果滚动的区间并没有超出渲染的范围 + // 如果滚动的区间并没有超出渲染的范围 if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { return; } var childrenToDisplay = this._cellRenderers(bottom - top, right - left, left, top); var renderedCells = [], renderedKeys = {}, renderedWidgets = {}; - //存储所有的left和top + // 存储所有的left和top var lefts = {}, tops = {}; for (var i = 0, len = childrenToDisplay.length; i < len; i++) { var datum = childrenToDisplay[i]; @@ -141,7 +141,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { tops = BI.toArray(tops); var leftMap = BI.invert(lefts); var topMap = BI.invert(tops); - //存储上下左右四个边界 + // 存储上下左右四个边界 var leftBorder = {}, rightBorder = {}, topBorder = {}, bottomBorder = {}; var assertMinBorder = function (border, offset) { if (border[offset] == null) { @@ -215,7 +215,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { renderedKeys[datum.index] = [datum.index, i]; renderedWidgets[i] = child; } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (self.renderedKeys[i]) { @@ -234,21 +234,21 @@ BI.CollectionView = BI.inherit(BI.Widget, { deleteArray.push(key[1]); }); BI.each(deleteArray, function (i, index) { - //性能优化,不调用destroy方法防止触发destroy事件 + // 性能优化,不调用destroy方法防止触发destroy事件 self.renderedCells[index].el._destroy(); }); var addedItems = []; BI.each(addSet, function (index, key) { - addedItems.push(renderedCells[key[1]]) + addedItems.push(renderedCells[key[1]]); }); this.container.addItems(addedItems); - //拦截父子级关系 + // 拦截父子级关系 this.container._children = renderedWidgets; this.container.attr("items", renderedCells); this.renderedCells = renderedCells; this.renderedKeys = renderedKeys; - //Todo 左右比较特殊 + // Todo 左右比较特殊 var minX = BI.min(leftBorder); var maxX = BI.max(rightBorder); @@ -279,7 +279,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { this.container.setHeight(this._height); this._calculateChildrenToRender(); - //元素未挂载时不能设置scrollTop + // 元素未挂载时不能设置scrollTop try { this.element.scrollTop(o.scrollTop); this.element.scrollLeft(o.scrollLeft); @@ -315,7 +315,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; BI.nextTick(function () { - self.element.css({overflowX: !!b ? "auto" : "hidden"}); + self.element.css({overflowX: b ? "auto" : "hidden"}); }); } }, @@ -325,7 +325,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; BI.nextTick(function () { - self.element.css({overflowY: !!b ? "auto" : "hidden"}); + self.element.css({overflowY: b ? "auto" : "hidden"}); }); } }, @@ -346,7 +346,7 @@ BI.CollectionView = BI.inherit(BI.Widget, { return this._getMaxScrollTop(); }, - //重新计算children + // 重新计算children _reRange: function () { this.renderRange = {}; }, @@ -375,4 +375,4 @@ BI.CollectionView = BI.inherit(BI.Widget, { } }); BI.CollectionView.EVENT_SCROLL = "EVENT_SCROLL"; -BI.shortcut('bi.collection_view', BI.CollectionView); \ No newline at end of file +BI.shortcut("bi.collection_view", BI.CollectionView); \ No newline at end of file diff --git a/src/base/combination/combo.js b/src/base/combination/combo.js index 1877fecb6..6f98e55bf 100644 --- a/src/base/combination/combo.js +++ b/src/base/combination/combo.js @@ -9,24 +9,24 @@ BI.Combo = BI.inherit(BI.Widget, { baseCls: (conf.baseCls || "") + " bi-combo", trigger: "click", toggle: true, - direction: "bottom", //top||bottom||left||right||top,left||top,right||bottom,left||bottom,right - container: null,//popupview放置的容器,默认为this.element + direction: "bottom", // top||bottom||left||right||top,left||top,right||bottom,left||bottom,right + container: null, // popupview放置的容器,默认为this.element isDefaultInit: false, destroyWhenHide: false, - isNeedAdjustHeight: true,//是否需要高度调整 + isNeedAdjustHeight: true, // 是否需要高度调整 isNeedAdjustWidth: true, stopEvent: false, stopPropagation: false, - adjustLength: 0,//调整的距离 + adjustLength: 0, // 调整的距离 adjustXOffset: 0, adjustYOffset: 0, hideChecker: BI.emptyFn, - offsetStyle: "left", //left,right,center + offsetStyle: "left", // left,right,center el: {}, popup: {}, comboClass: "bi-combo-popup", hoverClass: "bi-combo-hover" - }) + }); }, _init: function () { @@ -108,7 +108,7 @@ BI.Combo = BI.inherit(BI.Widget, { var enterPopup = false; - function hide() { + function hide () { if (self.isEnabled() && self.isValid() && self.combo.isEnabled() && self.combo.isValid() && o.toggle === true) { self._hideView(); self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.combo); @@ -251,8 +251,8 @@ BI.Combo = BI.inherit(BI.Widget, { // if (this.element.__isMouseInBounds__(e) || (this.popupView && this.popupView.element.__isMouseInBounds__(e))) { // return; // } - //BI-10290 公式combo双击公式内容会收起 - if (this.element.find(e.target).length > 0 || e.target.className === "CodeMirror-cursor" || $(e.target).closest(".CodeMirror-hints").length > 0) {//BI-9887 CodeMirror的公式弹框需要特殊处理下 + // BI-10290 公式combo双击公式内容会收起 + if (this.element.find(e.target).length > 0 || e.target.className === "CodeMirror-cursor" || $(e.target).closest(".CodeMirror-hints").length > 0) {// BI-9887 CodeMirror的公式弹框需要特殊处理下 return; } var isHide = this.options.hideChecker.apply(this, [e]); @@ -319,31 +319,31 @@ BI.Combo = BI.inherit(BI.Widget, { switch (o.direction) { case "bottom": case "bottom,right": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['bottom', 'top', 'right', 'left'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["bottom", "top", "right", "left"], o.offsetStyle); break; case "top": case "top,right": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['top', 'bottom', 'right', 'left'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["top", "bottom", "right", "left"], o.offsetStyle); break; case "left": case "left,bottom": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['left', 'right', 'bottom', 'top'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["left", "right", "bottom", "top"], o.offsetStyle); break; case "right": case "right,bottom": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['right', 'left', 'bottom', 'top'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "bottom", "top"], o.offsetStyle); break; case "top,left": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['top', 'bottom', 'left', 'right'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["top", "bottom", "left", "right"], o.offsetStyle); break; case "bottom,left": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ['bottom', 'top', 'left', 'right'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset, o.adjustYOffset || o.adjustLength, o.isNeedAdjustHeight, ["bottom", "top", "left", "right"], o.offsetStyle); break; case "left,top": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['left', 'right', 'top', 'bottom'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["left", "right", "top", "bottom"], o.offsetStyle); break; case "right,top": - p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ['right', 'left', 'top', 'bottom'], o.offsetStyle); + p = $.getComboPosition(this.combo, this.popupView, o.adjustXOffset || o.adjustLength, o.adjustYOffset, o.isNeedAdjustHeight, ["right", "left", "top", "bottom"], o.offsetStyle); break; case "top,custom": case "custom,top": @@ -368,7 +368,7 @@ BI.Combo = BI.inherit(BI.Widget, { } if ("adaptHeight" in p) { - this.resetListHeight(p['adaptHeight']); + this.resetListHeight(p["adaptHeight"]); } if ("left" in p) { this.popupView.element.css({ diff --git a/src/base/combination/expander.js b/src/base/combination/expander.js index 55b9c2b61..eb824b3af 100644 --- a/src/base/combination/expander.js +++ b/src/base/combination/expander.js @@ -12,13 +12,13 @@ BI.Expander = BI.inherit(BI.Widget, { baseCls: "bi-expander", trigger: "click", toggle: true, - //direction: "bottom", //top,bottom四个方向 - isDefaultInit: false, //是否默认初始化子节点 + // direction: "bottom", //top,bottom四个方向 + isDefaultInit: false, // 是否默认初始化子节点 el: {}, popup: {}, expanderClass: "bi-expander-popup", hoverClass: "bi-expander-hover" - }) + }); }, _init: function () { @@ -92,13 +92,13 @@ BI.Expander = BI.inherit(BI.Widget, { self.element[e](function (e) { if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid()) { self._popupView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); self.fireEvent(BI.Expander.EVENT_EXPAND); } }, function () { if (self.isEnabled() && self.isValid() && self.expander.isEnabled() && self.expander.isValid() && o.toggle) { self._hideView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); self.fireEvent(BI.Expander.EVENT_COLLAPSE); } }); @@ -113,7 +113,7 @@ BI.Expander = BI.inherit(BI.Widget, { self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.expander); self.fireEvent(BI.Expander.EVENT_EXPAND); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.expander); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.expander); self.fireEvent(BI.Expander.EVENT_COLLAPSE); } } @@ -122,7 +122,7 @@ BI.Expander = BI.inherit(BI.Widget, { } break; } - }) + }); }, _initExpander: function () { @@ -144,7 +144,7 @@ BI.Expander = BI.inherit(BI.Widget, { this.popupView.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); if (type === BI.Events.CLICK) { - //self.setValue(self.getValue()); + // self.setValue(self.getValue()); self.fireEvent(BI.Expander.EVENT_CHANGE, value, obj); } }); @@ -191,7 +191,7 @@ BI.Expander = BI.inherit(BI.Widget, { }, populate: function (items) { - //this._assertPopupView(); + // this._assertPopupView(); this.popupView && this.popupView.populate.apply(this.popupView, arguments); this.expander.populate.apply(this.expander, arguments); }, @@ -203,13 +203,13 @@ BI.Expander = BI.inherit(BI.Widget, { }, setValue: function (v) { - //this._assertPopupView(); + // this._assertPopupView(); this.expander.setValue(v); this.popupView && this.popupView.setValue(v); }, getValue: function () { - //this._assertPopupView(); + // this._assertPopupView(); return this.popupView ? this.popupView.getValue() : []; }, diff --git a/src/base/combination/group.button.js b/src/base/combination/group.button.js index 76be065fb..27cfa7439 100644 --- a/src/base/combination/group.button.js +++ b/src/base/combination/group.button.js @@ -16,7 +16,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { hgap: 0, vgap: 0 }] - }) + }); }, _init: function () { @@ -25,7 +25,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { BI.each(this.options.behaviors, function (key, rule) { behaviors[key] = BI.BehaviorFactory.createBehavior(key, { rule: rule - }) + }); }); this.behaviors = behaviors; this.populate(this.options.items); @@ -65,7 +65,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { }); btn.on(BI.Events.DESTROY, function () { BI.remove(self.buttons, btn); - }) + }); }); return buttons; @@ -81,8 +81,8 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { el: it }) ] - }) - }) + }); + }); } return btns; }, @@ -95,8 +95,8 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { } return BI.extend({}, item, { el: btns[i] - }) - }) + }); + }); }, _packageItems: function (items, packBtns) { @@ -114,10 +114,10 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { return layout; }, - //如果是一个简单的layout + // 如果是一个简单的layout _isSimpleLayout: function () { var o = this.options; - return o.layouts.length === 1 && !BI.isArray(o.items[0]) + return o.layouts.length === 1 && !BI.isArray(o.items[0]); }, doBehavior: function () { @@ -125,7 +125,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { args.unshift(this.buttons); BI.each(this.behaviors, function (i, behavior) { behavior.doBehavior.apply(behavior, args); - }) + }); }, prependItems: function (items) { @@ -147,7 +147,7 @@ BI.ButtonGroup = BI.inherit(BI.Widget, { var btns = this._btnsCreator.apply(this, arguments); this.buttons = BI.concat(this.buttons, btns); - //如果是一个简单的layout + // 如果是一个简单的layout if (this._isSimpleLayout() && this.layouts && this.layouts.addItems) { this.layouts.addItems(btns); return; diff --git a/src/base/combination/group.combo.js b/src/base/combination/group.combo.js index 409788873..7374aedee 100644 --- a/src/base/combination/group.combo.js +++ b/src/base/combination/group.combo.js @@ -7,7 +7,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { return BI.extend(BI.ComboGroup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-combo-group bi-list-item", - //以下这些属性对每一个combo都是公用的 + // 以下这些属性对每一个combo都是公用的 trigger: "click,hover", direction: "right", adjustLength: 0, @@ -27,7 +27,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { }] } } - }) + }); }, _init: function () { @@ -57,7 +57,7 @@ BI.ComboGroup = BI.inherit(BI.Widget, { ch.adjustLength = o.adjustLength; ch.popup = o.popup; } - }) + }); this.combo = BI.createWidget({ type: "bi.combo", element: this, @@ -74,13 +74,13 @@ BI.ComboGroup = BI.inherit(BI.Widget, { items: children }, o.popup.el) }) - }) + }); this.combo.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); if (type === BI.Events.CLICK) { self.fireEvent(BI.ComboGroup.EVENT_CHANGE, obj); } - }) + }); }, getValue: function () { diff --git a/src/base/combination/group.virtual.js b/src/base/combination/group.virtual.js index 02d72aa4b..cf9cec58d 100644 --- a/src/base/combination/group.virtual.js +++ b/src/base/combination/group.virtual.js @@ -8,7 +8,7 @@ BI.VirtualGroup = BI.inherit(BI.Widget, { hgap: 0, vgap: 0 }] - }) + }); }, render: function () { @@ -26,8 +26,8 @@ BI.VirtualGroup = BI.inherit(BI.Widget, { el: BI.stripEL(it) }) ] - }) - }) + }); + }); } return items; }, diff --git a/src/base/combination/loader.js b/src/base/combination/loader.js index 9b6acbb9f..f2be21a8e 100644 --- a/src/base/combination/loader.js +++ b/src/base/combination/loader.js @@ -11,13 +11,13 @@ BI.Loader = BI.inherit(BI.Widget, { baseCls: "bi-loader", direction: "top", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 logic: { dynamic: true, scrolly: true }, - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -26,13 +26,13 @@ BI.Loader = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, prev: false, next: {}, hasPrev: BI.emptyFn, hasNext: BI.emptyFn - }) + }); }, _prevLoad: function () { @@ -95,7 +95,7 @@ BI.Loader = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self._nextLoad(); } - }) + }); } BI.createWidget(BI.extend({ @@ -122,7 +122,7 @@ BI.Loader = BI.inherit(BI.Widget, { return !!o.hasPrev.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, hasNext: function () { @@ -133,7 +133,7 @@ BI.Loader = BI.inherit(BI.Widget, { return !!o.hasNext.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, prependItems: function (items) { diff --git a/src/base/combination/navigation.js b/src/base/combination/navigation.js index 35f1e69d3..7b4059ed8 100644 --- a/src/base/combination/navigation.js +++ b/src/base/combination/navigation.js @@ -5,7 +5,7 @@ BI.Navigation = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Navigation.superclass._defaultConfig.apply(this, arguments), { - direction: "bottom",//top, bottom, left, right, custom + direction: "bottom", // top, bottom, left, right, custom logic: { dynamic: false }, @@ -18,7 +18,7 @@ BI.Navigation = BI.inherit(BI.Widget, { afterCardCreated: BI.emptyFn, afterCardShow: BI.emptyFn - }) + }); }, render: function () { diff --git a/src/base/combination/searcher.js b/src/base/combination/searcher.js index 604b923f5..1cf4f66b5 100644 --- a/src/base/combination/searcher.js +++ b/src/base/combination/searcher.js @@ -18,13 +18,13 @@ BI.Searcher = BI.inherit(BI.Widget, { hgap: 0, isDefaultInit: false, - isAutoSearch: true, //是否自动搜索 - isAutoSync: true, //是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一 + isAutoSearch: true, // 是否自动搜索 + isAutoSync: true, // 是否自动同步数据, 即是否保持搜索面板和adapter面板状态值的统一 chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, - //isAutoSearch为false时启用 + // isAutoSearch为false时启用 onSearch: function (op, callback) { - callback([]) + callback([]); }, el: { @@ -36,10 +36,10 @@ BI.Searcher = BI.inherit(BI.Widget, { }, adapter: null, - masker: { //masker层 + masker: { // masker层 offset: {} } - }) + }); }, _init: function () { @@ -79,7 +79,7 @@ BI.Searcher = BI.inherit(BI.Widget, { self._pauseSearch(); break; } - }) + }); }, _assertPopupView: function () { @@ -129,7 +129,7 @@ BI.Searcher = BI.inherit(BI.Widget, { this._isSearching = true; this.fireEvent(BI.Searcher.EVENT_START); this.popupView.startSearch && this.popupView.startSearch(); - //搜索前先清空dom + // 搜索前先清空dom // BI.Maskers.get(this.getName()).empty(); BI.nextTick(function (name) { BI.Maskers.show(name); @@ -206,8 +206,8 @@ BI.Searcher = BI.inherit(BI.Widget, { }, stopSearch: function () { - this._stopSearch();//先停止搜索,然后再去设置editor为空 - //important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) + this._stopSearch();// 先停止搜索,然后再去设置editor为空 + // important:停止搜索必须退出编辑状态,这里必须加上try(input框不显示时blur会抛异常) try { this.editor.blur(); } catch (e) { @@ -268,9 +268,9 @@ BI.Searcher = BI.inherit(BI.Widget, { return this.popupView.getValue(); } else if (o.adapter && o.adapter.getValue) { return o.adapter.getValue(); - } else { - return this.popupView.getValue(); } + return this.popupView.getValue(); + }, populate: function (result, searchResult, keyword) { diff --git a/src/base/combination/switcher.js b/src/base/combination/switcher.js index 650d91943..d199430c7 100644 --- a/src/base/combination/switcher.js +++ b/src/base/combination/switcher.js @@ -19,7 +19,7 @@ BI.Switcher = BI.inherit(BI.Widget, { masker: {}, switcherClass: "bi-switcher-popup", hoverClass: "bi-switcher-hover" - }) + }); }, _init: function () { @@ -89,13 +89,13 @@ BI.Switcher = BI.inherit(BI.Widget, { self.element[e](function (e) { if (self.isEnabled() && self.switcher.isEnabled()) { self._popupView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_EXPAND); } }, function () { if (self.isEnabled() && self.switcher.isEnabled() && o.toggle) { self._hideView(); - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_COLLAPSE); } }); @@ -107,10 +107,10 @@ BI.Switcher = BI.inherit(BI.Widget, { if (self.isEnabled() && self.switcher.isEnabled()) { o.toggle ? self._toggle() : self._popupView(); if (self.isExpanded()) { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_EXPAND); } else { - self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, '', self.switcher); + self.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, "", self.switcher); self.fireEvent(BI.Switcher.EVENT_COLLAPSE); } } @@ -119,7 +119,7 @@ BI.Switcher = BI.inherit(BI.Widget, { } break; } - }) + }); }, _initSwitcher: function () { diff --git a/src/base/combination/tab.js b/src/base/combination/tab.js index f52576a53..629fa6fe9 100644 --- a/src/base/combination/tab.js +++ b/src/base/combination/tab.js @@ -6,8 +6,8 @@ BI.Tab = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Tab.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-tab", - direction: "top",//top, bottom, left, right, custom - single: false, //是不是单页面 + direction: "top", // top, bottom, left, right, custom + single: false, // 是不是单页面 logic: { dynamic: false }, @@ -16,7 +16,7 @@ BI.Tab = BI.inherit(BI.Widget, { cardCreator: function (v) { return BI.createWidget(); } - }) + }); }, render: function () { @@ -25,7 +25,7 @@ BI.Tab = BI.inherit(BI.Widget, { this.tab = BI.createWidget(this.options.tab, {type: "bi.button_group"}); this.tab.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); } this.cardMap = {}; this.layout = BI.createWidget({ diff --git a/src/base/combination/tree.button.js b/src/base/combination/tree.button.js index 4eb615971..0235ebf25 100644 --- a/src/base/combination/tree.button.js +++ b/src/base/combination/tree.button.js @@ -8,7 +8,7 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { _defaultConfig: function () { return BI.extend(BI.ButtonTree.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-button-tree" - }) + }); }, _init: function () { @@ -116,7 +116,7 @@ BI.ButtonTree = BI.inherit(BI.ButtonGroup, { return btns; }, - //获取所有的叶子节点 + // 获取所有的叶子节点 getAllLeaves: function () { var leaves = []; BI.each(this.buttons, function (i, item) { diff --git a/src/base/el.js b/src/base/el.js index bf4b442f6..f3f3e7e15 100644 --- a/src/base/el.js +++ b/src/base/el.js @@ -24,7 +24,7 @@ BI.EL = BI.inherit(BI.Widget, { }); this.ele.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); }, setValue: function (v) { @@ -39,4 +39,4 @@ BI.EL = BI.inherit(BI.Widget, { this.ele.populate.apply(this, arguments); } }); -BI.shortcut('bi.el', BI.EL); \ No newline at end of file +BI.shortcut("bi.el", BI.EL); \ No newline at end of file diff --git a/src/base/formula/codemirror/codemirror.js b/src/base/formula/codemirror/codemirror.js index 94ae8faad..431238c02 100644 --- a/src/base/formula/codemirror/codemirror.js +++ b/src/base/formula/codemirror/codemirror.js @@ -7,8730 +7,8508 @@ // You can find some technical background for some of the code below // at http://marijnhaverbeke.nl/blog/#cm-internals . -(function(mod) { +(function (mod) { this.CodeMirror = mod(); -})(function() { - "use strict"; - - // BROWSER SNIFFING - - // Kludges for bugs and behavior differences that can't be feature - // detected are enabled based on userAgent etc sniffing. - - var gecko = /gecko\/\d/i.test(navigator.userAgent); - var ie_upto10 = /MSIE \d/.test(navigator.userAgent); - var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); - var ie = ie_upto10 || ie_11up; - var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); - var webkit = /WebKit\//.test(navigator.userAgent); - var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); - var chrome = /Chrome\//.test(navigator.userAgent); - var presto = /Opera\//.test(navigator.userAgent); - var safari = /Apple Computer/.test(navigator.vendor); - var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); - var phantom = /PhantomJS/.test(navigator.userAgent); - - var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); - // This is woefully incomplete. Suggestions for alternative methods welcome. - var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); - var mac = ios || /Mac/.test(navigator.platform); - var windows = /win/i.test(navigator.platform); - - var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); - if (presto_version) presto_version = Number(presto_version[1]); - if (presto_version && presto_version >= 15) { presto = false; webkit = true; } - // Some browsers use the wrong event properties to signal cmd/ctrl on OS X - var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); - var captureRightClick = gecko || (ie && ie_version >= 9); - - // Optimize some code when these features are not used. - var sawReadOnlySpans = false, sawCollapsedSpans = false; - - // EDITOR CONSTRUCTOR - - // A CodeMirror instance represents an editor. This is the object - // that user code is usually dealing with. - - function CodeMirror(place, options) { - if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); - - this.options = options = options ? copyObj(options) : {}; - // Determine effective options based on given values and defaults. - copyObj(defaults, options, false); - setGuttersForLineNumbers(options); - - var doc = options.value; - if (typeof doc == "string") doc = new Doc(doc, options.mode); - this.doc = doc; - - var input = new CodeMirror.inputStyles[options.inputStyle](this); - var display = this.display = new Display(place, doc, input); - display.wrapper.CodeMirror = this; - updateGutters(this); - themeChanged(this); - if (options.lineWrapping) - this.display.wrapper.className += " CodeMirror-wrap"; - if (options.autofocus && !mobile) display.input.focus(); - initScrollbars(this); - - this.state = { - keyMaps: [], // stores maps added by addKeyMap - overlays: [], // highlighting overlays, as added by addOverlay - modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info - overwrite: false, - delayingBlurEvent: false, - focused: false, - suppressEdits: false, // used to disable editing during key handlers when in readOnly mode - pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll - draggingText: false, - highlight: new Delayed(), // stores highlight worker timeout - keySeq: null, // Unfinished key sequence - specialChars: null - }; +})(function () { + "use strict"; + + // BROWSER SNIFFING + + // Kludges for bugs and behavior differences that can't be feature + // detected are enabled based on userAgent etc sniffing. + + var gecko = /gecko\/\d/i.test(navigator.userAgent); + var ie_upto10 = /MSIE \d/.test(navigator.userAgent); + var ie_11up = /Trident\/(?:[7-9]|\d{2,})\..*rv:(\d+)/.exec(navigator.userAgent); + var ie = ie_upto10 || ie_11up; + var ie_version = ie && (ie_upto10 ? document.documentMode || 6 : ie_11up[1]); + var webkit = /WebKit\//.test(navigator.userAgent); + var qtwebkit = webkit && /Qt\/\d+\.\d+/.test(navigator.userAgent); + var chrome = /Chrome\//.test(navigator.userAgent); + var presto = /Opera\//.test(navigator.userAgent); + var safari = /Apple Computer/.test(navigator.vendor); + var mac_geMountainLion = /Mac OS X 1\d\D([8-9]|\d\d)\D/.test(navigator.userAgent); + var phantom = /PhantomJS/.test(navigator.userAgent); + + var ios = /AppleWebKit/.test(navigator.userAgent) && /Mobile\/\w+/.test(navigator.userAgent); + // This is woefully incomplete. Suggestions for alternative methods welcome. + var mobile = ios || /Android|webOS|BlackBerry|Opera Mini|Opera Mobi|IEMobile/i.test(navigator.userAgent); + var mac = ios || /Mac/.test(navigator.platform); + var windows = /win/i.test(navigator.platform); + + var presto_version = presto && navigator.userAgent.match(/Version\/(\d*\.\d*)/); + if (presto_version) presto_version = Number(presto_version[1]); + if (presto_version && presto_version >= 15) { presto = false; webkit = true; } + // Some browsers use the wrong event properties to signal cmd/ctrl on OS X + var flipCtrlCmd = mac && (qtwebkit || presto && (presto_version == null || presto_version < 12.11)); + var captureRightClick = gecko || (ie && ie_version >= 9); + + // Optimize some code when these features are not used. + var sawReadOnlySpans = false, sawCollapsedSpans = false; + + // EDITOR CONSTRUCTOR + + // A CodeMirror instance represents an editor. This is the object + // that user code is usually dealing with. + + function CodeMirror (place, options) { + if (!(this instanceof CodeMirror)) return new CodeMirror(place, options); + + this.options = options = options ? copyObj(options) : {}; + // Determine effective options based on given values and defaults. + copyObj(defaults, options, false); + setGuttersForLineNumbers(options); + + var doc = options.value; + if (typeof doc === "string") doc = new Doc(doc, options.mode); + this.doc = doc; + + var input = new CodeMirror.inputStyles[options.inputStyle](this); + var display = this.display = new Display(place, doc, input); + display.wrapper.CodeMirror = this; + updateGutters(this); + themeChanged(this); + if (options.lineWrapping) {this.display.wrapper.className += " CodeMirror-wrap";} + if (options.autofocus && !mobile) display.input.focus(); + initScrollbars(this); + + this.state = { + keyMaps: [], // stores maps added by addKeyMap + overlays: [], // highlighting overlays, as added by addOverlay + modeGen: 0, // bumped when mode/overlay changes, used to invalidate highlighting info + overwrite: false, + delayingBlurEvent: false, + focused: false, + suppressEdits: false, // used to disable editing during key handlers when in readOnly mode + pasteIncoming: false, cutIncoming: false, // help recognize paste/cut edits in input.poll + draggingText: false, + highlight: new Delayed(), // stores highlight worker timeout + keySeq: null, // Unfinished key sequence + specialChars: null + }; - var cm = this; - - // Override magic textarea content restore that IE sometimes does - // on our hidden textarea on reload - if (ie && ie_version < 11) setTimeout(function() { cm.display.input.reset(true); }, 20); - - registerEventHandlers(this); - ensureGlobalHandlers(); - - startOperation(this); - this.curOp.forceUpdate = true; - attachDoc(this, doc); - - if ((options.autofocus && !mobile) || cm.hasFocus()) - setTimeout(bind(onFocus, this), 20); - else - onBlur(this); - - for (var opt in optionHandlers) if (optionHandlers.hasOwnProperty(opt)) - optionHandlers[opt](this, options[opt], Init); - maybeUpdateLineNumberWidth(this); - if (options.finishInit) options.finishInit(this); - for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); - endOperation(this); - // Suppress optimizelegibility in Webkit, since it breaks text - // measuring on line wrapping boundaries. - if (webkit && options.lineWrapping && - getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") - display.lineDiv.style.textRendering = "auto"; - } - - // DISPLAY CONSTRUCTOR - - // The display handles the DOM integration, both for input reading - // and content drawing. It holds references to DOM nodes and - // display-related state. - - function Display(place, doc, input) { - var d = this; - this.input = input; - - // Covers bottom-right square when both scrollbars are present. - d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); - d.scrollbarFiller.setAttribute("cm-not-content", "true"); - // Covers bottom of gutter when coverGutterNextToScrollbar is on - // and h scrollbar is present. - d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); - d.gutterFiller.setAttribute("cm-not-content", "true"); - // Will contain the actual code, positioned to cover the viewport. - d.lineDiv = elt("div", null, "CodeMirror-code"); - // Elements are added to these to represent selection and cursors. - d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); - d.cursorDiv = elt("div", null, "CodeMirror-cursors"); - // A visibility: hidden element used to find the size of things. - d.measure = elt("div", null, "CodeMirror-measure"); - // When lines outside of the viewport are measured, they are drawn in this. - d.lineMeasure = elt("div", null, "CodeMirror-measure"); - // Wraps everything that needs to exist inside the vertically-padded coordinate system - d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], - null, "position: relative; outline: none"); - // Moved around its parent to cover visible view. - d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); - // Set to the height of the document, allowing scrolling. - d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); - d.sizerWidth = null; - // Behavior of elts with overflow: auto and padding is - // inconsistent across browsers. This is used to ensure the - // scrollable area is big enough. - d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); - // Will contain the gutters, if any. - d.gutters = elt("div", null, "CodeMirror-gutters"); - d.lineGutter = null; - // Actual scrollable element. - d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); - d.scroller.setAttribute("tabIndex", "-1"); - // The element in which the editor lives. - d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); - - // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) - if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } - if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; - - if (place) { - if (place.appendChild) place.appendChild(d.wrapper); - else place(d.wrapper); - } - - // Current rendered range (may be bigger than the view window). - d.viewFrom = d.viewTo = doc.first; - d.reportedViewFrom = d.reportedViewTo = doc.first; - // Information about the rendered lines. - d.view = []; - d.renderedView = null; - // Holds info about a single rendered line when it was rendered - // for measurement, while not in view. - d.externalMeasured = null; - // Empty space (in pixels) above the view - d.viewOffset = 0; - d.lastWrapHeight = d.lastWrapWidth = 0; - d.updateLineNumbers = null; - - d.nativeBarWidth = d.barHeight = d.barWidth = 0; - d.scrollbarsClipped = false; - - // Used to only resize the line number gutter when necessary (when - // the amount of lines crosses a boundary that makes its width change) - d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; - // Set to true when a non-horizontal-scrolling line widget is - // added. As an optimization, line widget aligning is skipped when - // this is false. - d.alignWidgets = false; - - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - - // Tracks the maximum line length so that the horizontal scrollbar - // can be kept static when scrolling. - d.maxLine = null; - d.maxLineLength = 0; - d.maxLineChanged = false; - - // Used for measuring wheel scrolling granularity - d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; - - // True when shift is held down. - d.shift = false; - - // Used to track whether anything happened since the context menu - // was opened. - d.selForContextMenu = null; - - d.activeTouch = null; - - input.init(d); - } - - // STATE UPDATES - - // Used to get the editor into a consistent state again when options change. - - function loadMode(cm) { - cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); - resetModeState(cm); - } - - function resetModeState(cm) { - cm.doc.iter(function(line) { - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - }); - cm.doc.frontier = cm.doc.first; - startWorker(cm, 100); - cm.state.modeGen++; - if (cm.curOp) regChange(cm); - } - - function wrappingChanged(cm) { - if (cm.options.lineWrapping) { - addClass(cm.display.wrapper, "CodeMirror-wrap"); - cm.display.sizer.style.minWidth = ""; - cm.display.sizerWidth = null; - } else { - rmClass(cm.display.wrapper, "CodeMirror-wrap"); - findMaxLine(cm); - } - estimateLineHeights(cm); - regChange(cm); - clearCaches(cm); - setTimeout(function(){updateScrollbars(cm);}, 100); - } - - // Returns a function that estimates the height of a line, to use as - // first approximation until the line becomes visible (and is thus - // properly measurable). - function estimateHeight(cm) { - var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; - var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); - return function(line) { - if (lineIsHidden(cm.doc, line)) return 0; - - var widgetsHeight = 0; - if (line.widgets) for (var i = 0; i < line.widgets.length; i++) { - if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; - } - - if (wrapping) - return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th; - else - return widgetsHeight + th; - }; - } + var cm = this; - function estimateLineHeights(cm) { - var doc = cm.doc, est = estimateHeight(cm); - doc.iter(function(line) { - var estHeight = est(line); - if (estHeight != line.height) updateLineHeight(line, estHeight); - }); - } + // Override magic textarea content restore that IE sometimes does + // on our hidden textarea on reload + if (ie && ie_version < 11) setTimeout(function () { cm.display.input.reset(true); }, 20); - function themeChanged(cm) { - cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + - cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); - clearCaches(cm); - } - - function guttersChanged(cm) { - updateGutters(cm); - regChange(cm); - setTimeout(function(){alignHorizontally(cm);}, 20); - } - - // Rebuild the gutter elements, ensure the margin to the left of the - // code matches their width. - function updateGutters(cm) { - var gutters = cm.display.gutters, specs = cm.options.gutters; - removeChildren(gutters); - for (var i = 0; i < specs.length; ++i) { - var gutterClass = specs[i]; - var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); - if (gutterClass == "CodeMirror-linenumbers") { - cm.display.lineGutter = gElt; - gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; - } - } - gutters.style.display = i ? "" : "none"; - updateGutterSpace(cm); - } - - function updateGutterSpace(cm) { - var width = cm.display.gutters.offsetWidth; - cm.display.sizer.style.marginLeft = width + "px"; - } - - // Compute the character length of a line, taking into account - // collapsed ranges (see markText) that might hide parts, and join - // other lines onto it. - function lineLength(line) { - if (line.height == 0) return 0; - var len = line.text.length, merged, cur = line; - while (merged = collapsedSpanAtStart(cur)) { - var found = merged.find(0, true); - cur = found.from.line; - len += found.from.ch - found.to.ch; - } - cur = line; - while (merged = collapsedSpanAtEnd(cur)) { - var found = merged.find(0, true); - len -= cur.text.length - found.from.ch; - cur = found.to.line; - len += cur.text.length - found.to.ch; - } - return len; - } - - // Find the longest line in the document. - function findMaxLine(cm) { - var d = cm.display, doc = cm.doc; - d.maxLine = getLine(doc, doc.first); - d.maxLineLength = lineLength(d.maxLine); - d.maxLineChanged = true; - doc.iter(function(line) { - var len = lineLength(line); - if (len > d.maxLineLength) { - d.maxLineLength = len; - d.maxLine = line; - } - }); - } - - // Make sure the gutters options contains the element - // "CodeMirror-linenumbers" when the lineNumbers option is true. - function setGuttersForLineNumbers(options) { - var found = indexOf(options.gutters, "CodeMirror-linenumbers"); - if (found == -1 && options.lineNumbers) { - options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); - } else if (found > -1 && !options.lineNumbers) { - options.gutters = options.gutters.slice(0); - options.gutters.splice(found, 1); - } - } - - // SCROLLBARS - - // Prepare DOM reads needed to update the scrollbars. Done in one - // shot to minimize update/measure roundtrips. - function measureForScrollbars(cm) { - var d = cm.display, gutterW = d.gutters.offsetWidth; - var docH = Math.round(cm.doc.height + paddingVert(cm.display)); - return { - clientHeight: d.scroller.clientHeight, - viewHeight: d.wrapper.clientHeight, - scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, - viewWidth: d.wrapper.clientWidth, - barLeft: cm.options.fixedGutter ? gutterW : 0, - docHeight: docH, - scrollHeight: docH + scrollGap(cm) + d.barHeight, - nativeBarWidth: d.nativeBarWidth, - gutterWidth: gutterW - }; - } + registerEventHandlers(this); + ensureGlobalHandlers(); - function NativeScrollbars(place, scroll, cm) { - this.cm = cm; - var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); - var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); - place(vert); place(horiz); + startOperation(this); + this.curOp.forceUpdate = true; + attachDoc(this, doc); - on(vert, "scroll", function() { - if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); - }); - on(horiz, "scroll", function() { - if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); - }); + if ((options.autofocus && !mobile) || cm.hasFocus()) {setTimeout(bind(onFocus, this), 20);} else {onBlur(this);} - this.checkedOverlay = false; - // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). - if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; - } - - NativeScrollbars.prototype = copyObj({ - update: function(measure) { - var needsH = measure.scrollWidth > measure.clientWidth + 1; - var needsV = measure.scrollHeight > measure.clientHeight + 1; - var sWidth = measure.nativeBarWidth; - - if (needsV) { - this.vert.style.display = "block"; - this.vert.style.bottom = needsH ? sWidth + "px" : "0"; - var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); - // A bug in IE8 can cause this value to be negative, so guard it. - this.vert.firstChild.style.height = - Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; - } else { - this.vert.style.display = ""; - this.vert.firstChild.style.height = "0"; - } - - if (needsH) { - this.horiz.style.display = "block"; - this.horiz.style.right = needsV ? sWidth + "px" : "0"; - this.horiz.style.left = measure.barLeft + "px"; - var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); - this.horiz.firstChild.style.width = - (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; - } else { - this.horiz.style.display = ""; - this.horiz.firstChild.style.width = "0"; - } - - if (!this.checkedOverlay && measure.clientHeight > 0) { - if (sWidth == 0) this.overlayHack(); - this.checkedOverlay = true; - } - - return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; - }, - setScrollLeft: function(pos) { - if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; - }, - setScrollTop: function(pos) { - if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; - }, - overlayHack: function() { - var w = mac && !mac_geMountainLion ? "12px" : "18px"; - this.horiz.style.minHeight = this.vert.style.minWidth = w; - var self = this; - var barMouseDown = function(e) { - if (e_target(e) != self.vert && e_target(e) != self.horiz) - operation(self.cm, onMouseDown)(e); - }; - on(this.vert, "mousedown", barMouseDown); - on(this.horiz, "mousedown", barMouseDown); - }, - clear: function() { - var parent = this.horiz.parentNode; - parent.removeChild(this.horiz); - parent.removeChild(this.vert); - } - }, NativeScrollbars.prototype); - - function NullScrollbars() {} - - NullScrollbars.prototype = copyObj({ - update: function() { return {bottom: 0, right: 0}; }, - setScrollLeft: function() {}, - setScrollTop: function() {}, - clear: function() {} - }, NullScrollbars.prototype); - - CodeMirror.scrollbarModel = {"native": NativeScrollbars, "null": NullScrollbars}; - - function initScrollbars(cm) { - if (cm.display.scrollbars) { - cm.display.scrollbars.clear(); - if (cm.display.scrollbars.addClass) - rmClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - - cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function(node) { - cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); - // Prevent clicks in the scrollbars from killing focus - on(node, "mousedown", function() { - if (cm.state.focused) setTimeout(function() { cm.display.input.focus(); }, 0); - }); - node.setAttribute("cm-not-content", "true"); - }, function(pos, axis) { - if (axis == "horizontal") setScrollLeft(cm, pos); - else setScrollTop(cm, pos); - }, cm); - if (cm.display.scrollbars.addClass) - addClass(cm.display.wrapper, cm.display.scrollbars.addClass); - } - - function updateScrollbars(cm, measure) { - if (!measure) measure = measureForScrollbars(cm); - var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; - updateScrollbarsInner(cm, measure); - for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { - if (startWidth != cm.display.barWidth && cm.options.lineWrapping) - updateHeightsInViewport(cm); - updateScrollbarsInner(cm, measureForScrollbars(cm)); - startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; - } - } - - // Re-synchronize the fake scrollbars with the actual size of the - // content. - function updateScrollbarsInner(cm, measure) { - var d = cm.display; - var sizes = d.scrollbars.update(measure); - - d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; - d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; - - if (sizes.right && sizes.bottom) { - d.scrollbarFiller.style.display = "block"; - d.scrollbarFiller.style.height = sizes.bottom + "px"; - d.scrollbarFiller.style.width = sizes.right + "px"; - } else d.scrollbarFiller.style.display = ""; - if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { - d.gutterFiller.style.display = "block"; - d.gutterFiller.style.height = sizes.bottom + "px"; - d.gutterFiller.style.width = measure.gutterWidth + "px"; - } else d.gutterFiller.style.display = ""; - } - - // Compute the lines that are visible in a given viewport (defaults - // the the current scroll position). viewport may contain top, - // height, and ensure (see op.scrollToPos) properties. - function visibleLines(display, doc, viewport) { - var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; - top = Math.floor(top - paddingTop(display)); - var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; - - var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); - // Ensure is a {from: {line, ch}, to: {line, ch}} object, and - // forces those lines into the viewport (if possible). - if (viewport && viewport.ensure) { - var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; - if (ensureFrom < from) { - from = ensureFrom; - to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); - } else if (Math.min(ensureTo, doc.lastLine()) >= to) { - from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); - to = ensureTo; - } - } - return {from: from, to: Math.max(to, from + 1)}; - } - - // LINE NUMBERS - - // Re-align line numbers and gutter marks to compensate for - // horizontal scrolling. - function alignHorizontally(cm) { - var display = cm.display, view = display.view; - if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; - var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; - var gutterW = display.gutters.offsetWidth, left = comp + "px"; - for (var i = 0; i < view.length; i++) if (!view[i].hidden) { - if (cm.options.fixedGutter && view[i].gutter) - view[i].gutter.style.left = left; - var align = view[i].alignable; - if (align) for (var j = 0; j < align.length; j++) - align[j].style.left = left; - } - if (cm.options.fixedGutter) - display.gutters.style.left = (comp + gutterW) + "px"; - } - - // Used to ensure that the line number gutter is still the right - // size for the current document size. Returns true when an update - // is needed. - function maybeUpdateLineNumberWidth(cm) { - if (!cm.options.lineNumbers) return false; - var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; - if (last.length != display.lineNumChars) { - var test = display.measure.appendChild(elt("div", [elt("div", last)], - "CodeMirror-linenumber CodeMirror-gutter-elt")); - var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; - display.lineGutter.style.width = ""; - display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; - display.lineNumWidth = display.lineNumInnerWidth + padding; - display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; - display.lineGutter.style.width = display.lineNumWidth + "px"; - updateGutterSpace(cm); - return true; - } - return false; - } - - function lineNumberFor(options, i) { - return String(options.lineNumberFormatter(i + options.firstLineNumber)); - } - - // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, - // but using getBoundingClientRect to get a sub-pixel-accurate - // result. - function compensateForHScroll(display) { - return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; - } - - // DISPLAY DRAWING - - function DisplayUpdate(cm, viewport, force) { - var display = cm.display; - - this.viewport = viewport; - // Store some values that we'll need later (but don't want to force a relayout for) - this.visible = visibleLines(display, cm.doc, viewport); - this.editorIsHidden = !display.wrapper.offsetWidth; - this.wrapperHeight = display.wrapper.clientHeight; - this.wrapperWidth = display.wrapper.clientWidth; - this.oldDisplayWidth = displayWidth(cm); - this.force = force; - this.dims = getDimensions(cm); - this.events = []; - } - - DisplayUpdate.prototype.signal = function(emitter, type) { - if (hasHandler(emitter, type)) - this.events.push(arguments); - }; - DisplayUpdate.prototype.finish = function() { - for (var i = 0; i < this.events.length; i++) - signal.apply(null, this.events[i]); - }; - - function maybeClipScrollbars(cm) { - var display = cm.display; - if (!display.scrollbarsClipped && display.scroller.offsetWidth) { - display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; - display.heightForcer.style.height = scrollGap(cm) + "px"; - display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; - display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; - display.scrollbarsClipped = true; - } - } - - // Does the actual updating of the line display. Bails out - // (returning false) when there is nothing to be done and forced is - // false. - function updateDisplayIfNeeded(cm, update) { - var display = cm.display, doc = cm.doc; - - if (update.editorIsHidden) { - resetView(cm); - return false; - } - - // Bail out if the visible area is already rendered and nothing changed. - if (!update.force && - update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && - display.renderedView == display.view && countDirtyView(cm) == 0) - return false; + for (var opt in optionHandlers) { + if (optionHandlers.hasOwnProperty(opt)) {optionHandlers[opt](this, options[opt], Init);} + } + maybeUpdateLineNumberWidth(this); + if (options.finishInit) options.finishInit(this); + for (var i = 0; i < initHooks.length; ++i) initHooks[i](this); + endOperation(this); + // Suppress optimizelegibility in Webkit, since it breaks text + // measuring on line wrapping boundaries. + if (webkit && options.lineWrapping && + getComputedStyle(display.lineDiv).textRendering == "optimizelegibility") {display.lineDiv.style.textRendering = "auto";} + } + + // DISPLAY CONSTRUCTOR + + // The display handles the DOM integration, both for input reading + // and content drawing. It holds references to DOM nodes and + // display-related state. + + function Display (place, doc, input) { + var d = this; + this.input = input; + + // Covers bottom-right square when both scrollbars are present. + d.scrollbarFiller = elt("div", null, "CodeMirror-scrollbar-filler"); + d.scrollbarFiller.setAttribute("cm-not-content", "true"); + // Covers bottom of gutter when coverGutterNextToScrollbar is on + // and h scrollbar is present. + d.gutterFiller = elt("div", null, "CodeMirror-gutter-filler"); + d.gutterFiller.setAttribute("cm-not-content", "true"); + // Will contain the actual code, positioned to cover the viewport. + d.lineDiv = elt("div", null, "CodeMirror-code"); + // Elements are added to these to represent selection and cursors. + d.selectionDiv = elt("div", null, null, "position: relative; z-index: 1"); + d.cursorDiv = elt("div", null, "CodeMirror-cursors"); + // A visibility: hidden element used to find the size of things. + d.measure = elt("div", null, "CodeMirror-measure"); + // When lines outside of the viewport are measured, they are drawn in this. + d.lineMeasure = elt("div", null, "CodeMirror-measure"); + // Wraps everything that needs to exist inside the vertically-padded coordinate system + d.lineSpace = elt("div", [d.measure, d.lineMeasure, d.selectionDiv, d.cursorDiv, d.lineDiv], + null, "position: relative; outline: none"); + // Moved around its parent to cover visible view. + d.mover = elt("div", [elt("div", [d.lineSpace], "CodeMirror-lines")], null, "position: relative"); + // Set to the height of the document, allowing scrolling. + d.sizer = elt("div", [d.mover], "CodeMirror-sizer"); + d.sizerWidth = null; + // Behavior of elts with overflow: auto and padding is + // inconsistent across browsers. This is used to ensure the + // scrollable area is big enough. + d.heightForcer = elt("div", null, null, "position: absolute; height: " + scrollerGap + "px; width: 1px;"); + // Will contain the gutters, if any. + d.gutters = elt("div", null, "CodeMirror-gutters"); + d.lineGutter = null; + // Actual scrollable element. + d.scroller = elt("div", [d.sizer, d.heightForcer, d.gutters], "CodeMirror-scroll"); + d.scroller.setAttribute("tabIndex", "-1"); + // The element in which the editor lives. + d.wrapper = elt("div", [d.scrollbarFiller, d.gutterFiller, d.scroller], "CodeMirror"); + + // Work around IE7 z-index bug (not perfect, hence IE7 not really being supported) + if (ie && ie_version < 8) { d.gutters.style.zIndex = -1; d.scroller.style.paddingRight = 0; } + if (!webkit && !(gecko && mobile)) d.scroller.draggable = true; + + if (place) { + if (place.appendChild) place.appendChild(d.wrapper); + else place(d.wrapper); + } + + // Current rendered range (may be bigger than the view window). + d.viewFrom = d.viewTo = doc.first; + d.reportedViewFrom = d.reportedViewTo = doc.first; + // Information about the rendered lines. + d.view = []; + d.renderedView = null; + // Holds info about a single rendered line when it was rendered + // for measurement, while not in view. + d.externalMeasured = null; + // Empty space (in pixels) above the view + d.viewOffset = 0; + d.lastWrapHeight = d.lastWrapWidth = 0; + d.updateLineNumbers = null; + + d.nativeBarWidth = d.barHeight = d.barWidth = 0; + d.scrollbarsClipped = false; + + // Used to only resize the line number gutter when necessary (when + // the amount of lines crosses a boundary that makes its width change) + d.lineNumWidth = d.lineNumInnerWidth = d.lineNumChars = null; + // Set to true when a non-horizontal-scrolling line widget is + // added. As an optimization, line widget aligning is skipped when + // this is false. + d.alignWidgets = false; + + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + + // Tracks the maximum line length so that the horizontal scrollbar + // can be kept static when scrolling. + d.maxLine = null; + d.maxLineLength = 0; + d.maxLineChanged = false; + + // Used for measuring wheel scrolling granularity + d.wheelDX = d.wheelDY = d.wheelStartX = d.wheelStartY = null; + + // True when shift is held down. + d.shift = false; - if (maybeUpdateLineNumberWidth(cm)) { - resetView(cm); - update.dims = getDimensions(cm); + // Used to track whether anything happened since the context menu + // was opened. + d.selForContextMenu = null; + + d.activeTouch = null; + + input.init(d); } - // Compute a suitable new viewport (from & to) - var end = doc.first + doc.size; - var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); - var to = Math.min(end, update.visible.to + cm.options.viewportMargin); - if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); - if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); - if (sawCollapsedSpans) { - from = visualLineNo(cm.doc, from); - to = visualLineEndNo(cm.doc, to); + // STATE UPDATES + + // Used to get the editor into a consistent state again when options change. + + function loadMode (cm) { + cm.doc.mode = CodeMirror.getMode(cm.options, cm.doc.modeOption); + resetModeState(cm); } - var different = from != display.viewFrom || to != display.viewTo || - display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; - adjustView(cm, from, to); - - display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); - // Position the mover div to align with the current scroll position - cm.display.mover.style.top = display.viewOffset + "px"; - - var toUpdate = countDirtyView(cm); - if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && - (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) - return false; - - // For big changes, we hide the enclosing element during the - // update, since that speeds up the operations on most browsers. - var focused = activeElt(); - if (toUpdate > 4) display.lineDiv.style.display = "none"; - patchDisplay(cm, display.updateLineNumbers, update.dims); - if (toUpdate > 4) display.lineDiv.style.display = ""; - display.renderedView = display.view; - // There might have been a widget with a focused element that got - // hidden or updated, if so re-focus it. - if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); - - // Prevent selection and cursors from interfering with the scroll - // width and height. - removeChildren(display.cursorDiv); - removeChildren(display.selectionDiv); - display.gutters.style.height = 0; - - if (different) { - display.lastWrapHeight = update.wrapperHeight; - display.lastWrapWidth = update.wrapperWidth; - startWorker(cm, 400); - } - - display.updateLineNumbers = null; - - return true; - } - - function postUpdateDisplay(cm, update) { - var viewport = update.viewport; - for (var first = true;; first = false) { - if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { - // Clip forced viewport to actual scrollable area. - if (viewport && viewport.top != null) - viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)}; - // Updated line heights might result in the drawn area not - // actually covering the viewport. Keep looping until it does. - update.visible = visibleLines(cm.display, cm.doc, viewport); - if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) - break; - } - if (!updateDisplayIfNeeded(cm, update)) break; - updateHeightsInViewport(cm); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - setDocumentHeight(cm, barMeasure); - updateScrollbars(cm, barMeasure); - } - - update.signal(cm, "update", cm); - if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { - update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); - cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; - } - } - - function updateDisplaySimple(cm, viewport) { - var update = new DisplayUpdate(cm, viewport); - if (updateDisplayIfNeeded(cm, update)) { - updateHeightsInViewport(cm); - postUpdateDisplay(cm, update); - var barMeasure = measureForScrollbars(cm); - updateSelection(cm); - setDocumentHeight(cm, barMeasure); - updateScrollbars(cm, barMeasure); - update.finish(); - } - } - - function setDocumentHeight(cm, measure) { - cm.display.sizer.style.minHeight = measure.docHeight + "px"; - var total = measure.docHeight + cm.display.barHeight; - cm.display.heightForcer.style.top = total + "px"; - cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px"; - } - - // Read the actual heights of the rendered lines, and update their - // stored heights to match. - function updateHeightsInViewport(cm) { - var display = cm.display; - var prevBottom = display.lineDiv.offsetTop; - for (var i = 0; i < display.view.length; i++) { - var cur = display.view[i], height; - if (cur.hidden) continue; - if (ie && ie_version < 8) { - var bot = cur.node.offsetTop + cur.node.offsetHeight; - height = bot - prevBottom; - prevBottom = bot; - } else { - var box = cur.node.getBoundingClientRect(); - height = box.bottom - box.top; - } - var diff = cur.line.height - height; - if (height < 2) height = textHeight(display); - if (diff > .001 || diff < -.001) { - updateLineHeight(cur.line, height); - updateWidgetHeight(cur.line); - if (cur.rest) for (var j = 0; j < cur.rest.length; j++) - updateWidgetHeight(cur.rest[j]); - } - } - } - - // Read and store the height of line widgets associated with the - // given line. - function updateWidgetHeight(line) { - if (line.widgets) for (var i = 0; i < line.widgets.length; ++i) - line.widgets[i].height = line.widgets[i].node.offsetHeight; - } - - // Do a bulk-read of the DOM positions and sizes needed to draw the - // view, so that we don't interleave reading and writing to the DOM. - function getDimensions(cm) { - var d = cm.display, left = {}, width = {}; - var gutterLeft = d.gutters.clientLeft; - for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { - left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; - width[cm.options.gutters[i]] = n.clientWidth; - } - return {fixedPos: compensateForHScroll(d), - gutterTotalWidth: d.gutters.offsetWidth, - gutterLeft: left, - gutterWidth: width, - wrapperWidth: d.wrapper.clientWidth}; - } - - // Sync the actual display DOM structure with display.view, removing - // nodes for lines that are no longer in view, and creating the ones - // that are not there yet, and updating the ones that are out of - // date. - function patchDisplay(cm, updateNumbersFrom, dims) { - var display = cm.display, lineNumbers = cm.options.lineNumbers; - var container = display.lineDiv, cur = container.firstChild; - - function rm(node) { - var next = node.nextSibling; - // Works around a throw-scroll bug in OS X Webkit - if (webkit && mac && cm.display.currentWheelTarget == node) - node.style.display = "none"; - else - node.parentNode.removeChild(node); - return next; - } - - var view = display.view, lineN = display.viewFrom; - // Loop over the elements in the view, syncing cur (the DOM nodes - // in display.lineDiv) with the view as we go. - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (lineView.hidden) { - } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet - var node = buildLineElement(cm, lineView, lineN, dims); - container.insertBefore(node, cur); - } else { // Already drawn - while (cur != lineView.node) cur = rm(cur); - var updateNumber = lineNumbers && updateNumbersFrom != null && - updateNumbersFrom <= lineN && lineView.lineNumber; - if (lineView.changes) { - if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; - updateLineForChanges(cm, lineView, lineN, dims); - } - if (updateNumber) { - removeChildren(lineView.lineNumber); - lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); - } - cur = lineView.node.nextSibling; - } - lineN += lineView.size; - } - while (cur) cur = rm(cur); - } - - // When an aspect of a line changes, a string is added to - // lineView.changes. This updates the relevant part of the line's - // DOM structure. - function updateLineForChanges(cm, lineView, lineN, dims) { - for (var j = 0; j < lineView.changes.length; j++) { - var type = lineView.changes[j]; - if (type == "text") updateLineText(cm, lineView); - else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); - else if (type == "class") updateLineClasses(lineView); - else if (type == "widget") updateLineWidgets(cm, lineView, dims); - } - lineView.changes = null; - } - - // Lines with gutter elements, widgets or a background class need to - // be wrapped, and have the extra elements added to the wrapper div - function ensureLineWrapped(lineView) { - if (lineView.node == lineView.text) { - lineView.node = elt("div", null, null, "position: relative"); - if (lineView.text.parentNode) - lineView.text.parentNode.replaceChild(lineView.node, lineView.text); - lineView.node.appendChild(lineView.text); - if (ie && ie_version < 8) lineView.node.style.zIndex = 2; - } - return lineView.node; - } - - function updateLineBackground(lineView) { - var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; - if (cls) cls += " CodeMirror-linebackground"; - if (lineView.background) { - if (cls) lineView.background.className = cls; - else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } - } else if (cls) { - var wrap = ensureLineWrapped(lineView); - lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); - } - } - - // Wrapper around buildLineContent which will reuse the structure - // in display.externalMeasured when possible. - function getLineContent(cm, lineView) { - var ext = cm.display.externalMeasured; - if (ext && ext.line == lineView.line) { - cm.display.externalMeasured = null; - lineView.measure = ext.measure; - return ext.built; - } - return buildLineContent(cm, lineView); - } - - // Redraw the line's text. Interacts with the background and text - // classes because the mode may output tokens that influence these - // classes. - function updateLineText(cm, lineView) { - var cls = lineView.text.className; - var built = getLineContent(cm, lineView); - if (lineView.text == lineView.node) lineView.node = built.pre; - lineView.text.parentNode.replaceChild(built.pre, lineView.text); - lineView.text = built.pre; - if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { - lineView.bgClass = built.bgClass; - lineView.textClass = built.textClass; - updateLineClasses(lineView); - } else if (cls) { - lineView.text.className = cls; - } - } - - function updateLineClasses(lineView) { - updateLineBackground(lineView); - if (lineView.line.wrapClass) - ensureLineWrapped(lineView).className = lineView.line.wrapClass; - else if (lineView.node != lineView.text) - lineView.node.className = ""; - var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; - lineView.text.className = textClass || ""; - } - - function updateLineGutter(cm, lineView, lineN, dims) { - if (lineView.gutter) { - lineView.node.removeChild(lineView.gutter); - lineView.gutter = null; - } - var markers = lineView.line.gutterMarkers; - if (cm.options.lineNumbers || markers) { - var wrap = ensureLineWrapped(lineView); - var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + - (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + - "px; width: " + dims.gutterTotalWidth + "px"); - cm.display.input.setUneditable(gutterWrap); - wrap.insertBefore(gutterWrap, lineView.text); - if (lineView.line.gutterClass) - gutterWrap.className += " " + lineView.line.gutterClass; - if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) - lineView.lineNumber = gutterWrap.appendChild( - elt("div", lineNumberFor(cm.options, lineN), - "CodeMirror-linenumber CodeMirror-gutter-elt", - "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " - + cm.display.lineNumInnerWidth + "px")); - if (markers) for (var k = 0; k < cm.options.gutters.length; ++k) { - var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; - if (found) - gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + - dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); - } - } - } - - function updateLineWidgets(cm, lineView, dims) { - if (lineView.alignable) lineView.alignable = null; - for (var node = lineView.node.firstChild, next; node; node = next) { - var next = node.nextSibling; - if (node.className == "CodeMirror-linewidget") - lineView.node.removeChild(node); - } - insertLineWidgets(cm, lineView, dims); - } - - // Build a line's DOM representation from scratch - function buildLineElement(cm, lineView, lineN, dims) { - var built = getLineContent(cm, lineView); - lineView.text = lineView.node = built.pre; - if (built.bgClass) lineView.bgClass = built.bgClass; - if (built.textClass) lineView.textClass = built.textClass; - - updateLineClasses(lineView); - updateLineGutter(cm, lineView, lineN, dims); - insertLineWidgets(cm, lineView, dims); - return lineView.node; - } - - // A lineView may contain multiple logical lines (when merged by - // collapsed spans). The widgets for all of them need to be drawn. - function insertLineWidgets(cm, lineView, dims) { - insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); - if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) - insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false); - } - - function insertLineWidgetsFor(cm, line, lineView, dims, allowAbove) { - if (!line.widgets) return; - var wrap = ensureLineWrapped(lineView); - for (var i = 0, ws = line.widgets; i < ws.length; ++i) { - var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); - if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); - positionLineWidget(widget, node, lineView, dims); - cm.display.input.setUneditable(node); - if (allowAbove && widget.above) - wrap.insertBefore(node, lineView.gutter || lineView.text); - else - wrap.appendChild(node); - signalLater(widget, "redraw"); - } - } - - function positionLineWidget(widget, node, lineView, dims) { - if (widget.noHScroll) { - (lineView.alignable || (lineView.alignable = [])).push(node); - var width = dims.wrapperWidth; - node.style.left = dims.fixedPos + "px"; - if (!widget.coverGutter) { - width -= dims.gutterTotalWidth; - node.style.paddingLeft = dims.gutterTotalWidth + "px"; - } - node.style.width = width + "px"; - } - if (widget.coverGutter) { - node.style.zIndex = 5; - node.style.position = "relative"; - if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; - } - } - - // POSITION OBJECT - - // A Pos instance represents a position within the text. - var Pos = CodeMirror.Pos = function(line, ch) { - if (!(this instanceof Pos)) return new Pos(line, ch); - this.line = line; this.ch = ch; - }; - - // Compare two positions, return 0 if they are the same, a negative - // number when a is less, and a positive number otherwise. - var cmp = CodeMirror.cmpPos = function(a, b) { return a.line - b.line || a.ch - b.ch; }; - - function copyPos(x) {return Pos(x.line, x.ch);} - function maxPos(a, b) { return cmp(a, b) < 0 ? b : a; } - function minPos(a, b) { return cmp(a, b) < 0 ? a : b; } - - // INPUT HANDLING - - function ensureFocus(cm) { - if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } - } - - function isReadOnly(cm) { - return cm.options.readOnly || cm.doc.cantEdit; - } - - // This will be set to an array of strings when copying, so that, - // when pasting, we know what kind of selections the copied text - // was made out of. - var lastCopied = null; - - function applyTextInput(cm, inserted, deleted, sel, origin) { - var doc = cm.doc; - cm.display.shift = false; - if (!sel) sel = doc.sel; - - var paste = cm.state.pasteIncoming || origin == "paste"; - var textLines = splitLines(inserted), multiPaste = null; - // When pasing N lines into N selections, insert one line per selection - if (paste && sel.ranges.length > 1) { - if (lastCopied && lastCopied.join("\n") == inserted) - multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines); - else if (textLines.length == sel.ranges.length) - multiPaste = map(textLines, function(l) { return [l]; }); - } - - // Normal behavior is to insert the new text into every selection - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - var from = range.from(), to = range.to(); - if (range.empty()) { - if (deleted && deleted > 0) // Handle deletion - from = Pos(from.line, from.ch - deleted); - else if (cm.state.overwrite && !paste) // Handle overwrite - to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length)); - } - var updateInput = cm.curOp.updateInput; - var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, - origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; - makeChange(cm.doc, changeEvent); - signalLater(cm, "inputRead", cm, changeEvent); - } - if (inserted && !paste) - triggerElectric(cm, inserted); - - ensureCursorVisible(cm); - cm.curOp.updateInput = updateInput; - cm.curOp.typing = true; - cm.state.pasteIncoming = cm.state.cutIncoming = false; - } - - function handlePaste(e, cm) { - var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); - if (pasted) { - e.preventDefault(); - runInOp(cm, function() { applyTextInput(cm, pasted, 0, null, "paste"); }); - return true; - } - } - - function triggerElectric(cm, inserted) { - // When an 'electric' character is inserted, immediately trigger a reindent - if (!cm.options.electricChars || !cm.options.smartIndent) return; - var sel = cm.doc.sel; - - for (var i = sel.ranges.length - 1; i >= 0; i--) { - var range = sel.ranges[i]; - if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; - var mode = cm.getModeAt(range.head); - var indented = false; - if (mode.electricChars) { - for (var j = 0; j < mode.electricChars.length; j++) - if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { - indented = indentLine(cm, range.head.line, "smart"); - break; - } - } else if (mode.electricInput) { - if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) - indented = indentLine(cm, range.head.line, "smart"); - } - if (indented) signalLater(cm, "electricInput", cm, range.head.line); - } - } - - function copyableRanges(cm) { - var text = [], ranges = []; - for (var i = 0; i < cm.doc.sel.ranges.length; i++) { - var line = cm.doc.sel.ranges[i].head.line; - var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; - ranges.push(lineRange); - text.push(cm.getRange(lineRange.anchor, lineRange.head)); - } - return {text: text, ranges: ranges}; - } - - function disableBrowserMagic(field) { - field.setAttribute("autocorrect", "off"); - field.setAttribute("autocapitalize", "off"); - field.setAttribute("spellcheck", "false"); - } - - // TEXTAREA INPUT STYLE - - function TextareaInput(cm) { - this.cm = cm; - // See input.poll and input.reset - this.prevInput = ""; - - // Flag that indicates whether we expect input to appear real soon - // now (after some event like 'keypress' or 'input') and are - // polling intensively. - this.pollingFast = false; - // Self-resetting timeout for the poller - this.polling = new Delayed(); - // Tracks when input.reset has punted to just putting a short - // string into the textarea instead of the full selection. - this.inaccurateSelection = false; - // Used to work around IE issue with selection being forgotten when focus moves away from textarea - this.hasSelection = false; - this.composing = null; - }; - - function hiddenTextarea() { - var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); - var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); - // The textarea is kept positioned near the cursor to prevent the - // fact that it'll be scrolled into view on input from scrolling - // our fake cursor out of view. On webkit, when wrap=off, paste is - // very slow. So make the area wide instead. - if (webkit) te.style.width = "1000px"; - else te.setAttribute("wrap", "off"); - // If border: 0; -- iOS fails to open keyboard (issue #1287) - if (ios) te.style.border = "1px solid black"; - disableBrowserMagic(te); - return div; - } - - TextareaInput.prototype = copyObj({ - init: function(display) { - var input = this, cm = this.cm; - - // Wraps and hides input textarea - var div = this.wrapper = hiddenTextarea(); - // The semihidden textarea that is focused when the editor is - // focused, and receives input. - var te = this.textarea = div.firstChild; - display.wrapper.insertBefore(div, display.wrapper.firstChild); - - // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) - if (ios) te.style.width = "0px"; - - on(te, "input", function() { - if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; - input.poll(); - }); - - on(te, "paste", function(e) { - if (handlePaste(e, cm)) return true; - - cm.state.pasteIncoming = true; - input.fastPoll(); - }); - - function prepareCopyCut(e) { - if (cm.somethingSelected()) { - lastCopied = cm.getSelections(); - if (input.inaccurateSelection) { - input.prevInput = ""; - input.inaccurateSelection = false; - te.value = lastCopied.join("\n"); - selectInput(te); - } - } else if (!cm.options.lineWiseCopyCut) { - return; - } else { - var ranges = copyableRanges(cm); - lastCopied = ranges.text; - if (e.type == "cut") { - cm.setSelections(ranges.ranges, null, sel_dontScroll); - } else { - input.prevInput = ""; - te.value = ranges.text.join("\n"); - selectInput(te); - } - } - if (e.type == "cut") cm.state.cutIncoming = true; - } - on(te, "cut", prepareCopyCut); - on(te, "copy", prepareCopyCut); - - on(display.scroller, "paste", function(e) { - if (eventInWidget(display, e)) return; - cm.state.pasteIncoming = true; - input.focus(); - }); - - // Prevent normal selection in the editor (we handle our own) - on(display.lineSpace, "selectstart", function(e) { - if (!eventInWidget(display, e)) e_preventDefault(e); - }); - - on(te, "compositionstart", function() { - var start = cm.getCursor("from"); - input.composing = { - start: start, - range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) - }; - }); - on(te, "compositionend", function() { - if (input.composing) { - input.poll(); - input.composing.range.clear(); - input.composing = null; - } - }); - }, - - prepareSelection: function() { - // Redraw the selection and/or cursor - var cm = this.cm, display = cm.display, doc = cm.doc; - var result = prepareSelection(cm); - - // Move the hidden textarea near the cursor to prevent scrolling artifacts - if (cm.options.moveInputWithCursor) { - var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); - var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); - result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, - headPos.top + lineOff.top - wrapOff.top)); - result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, - headPos.left + lineOff.left - wrapOff.left)); - } - - return result; - }, - - showSelection: function(drawn) { - var cm = this.cm, display = cm.display; - removeChildrenAndAdd(display.cursorDiv, drawn.cursors); - removeChildrenAndAdd(display.selectionDiv, drawn.selection); - if (drawn.teTop != null) { - this.wrapper.style.top = drawn.teTop + "px"; - this.wrapper.style.left = drawn.teLeft + "px"; - } - }, - - // Reset the input to correspond to the selection (or to be empty, - // when not typing and nothing is selected) - reset: function(typing) { - if (this.contextMenuPending) return; - var minimal, selected, cm = this.cm, doc = cm.doc; - if (cm.somethingSelected()) { - this.prevInput = ""; - var range = doc.sel.primary(); - minimal = hasCopyEvent && - (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); - var content = minimal ? "-" : selected || cm.getSelection(); - this.textarea.value = content; - if (cm.state.focused) selectInput(this.textarea); - if (ie && ie_version >= 9) this.hasSelection = content; - } else if (!typing) { - this.prevInput = this.textarea.value = ""; - if (ie && ie_version >= 9) this.hasSelection = null; - } - this.inaccurateSelection = minimal; - }, - - getField: function() { return this.textarea; }, - - supportsTouch: function() { return false; }, - - focus: function() { - if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { - try { this.textarea.focus(); } - catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM - } - }, - - blur: function() { this.textarea.blur(); }, - - resetPosition: function() { - this.wrapper.style.top = this.wrapper.style.left = 0; - }, - - receivedFocus: function() { this.slowPoll(); }, - - // Poll for input changes, using the normal rate of polling. This - // runs as long as the editor is focused. - slowPoll: function() { - var input = this; - if (input.pollingFast) return; - input.polling.set(this.cm.options.pollInterval, function() { - input.poll(); - if (input.cm.state.focused) input.slowPoll(); - }); - }, - - // When an event has just come in that is likely to add or change - // something in the input textarea, we poll faster, to ensure that - // the change appears on the screen quickly. - fastPoll: function() { - var missed = false, input = this; - input.pollingFast = true; - function p() { - var changed = input.poll(); - if (!changed && !missed) {missed = true; input.polling.set(60, p);} - else {input.pollingFast = false; input.slowPoll();} - } - input.polling.set(20, p); - }, - - // Read input from the textarea, and update the document to match. - // When something is selected, it is present in the textarea, and - // selected (unless it is huge, in which case a placeholder is - // used). When nothing is selected, the cursor sits after previously - // seen text (can be empty), which is stored in prevInput (we must - // not reset the textarea when typing, because that breaks IME). - poll: function() { - var cm = this.cm, input = this.textarea, prevInput = this.prevInput; - // Since this is called a *lot*, try to bail out as cheaply as - // possible when it is clear that nothing happened. hasSelection - // will be the case when there is a lot of text in the textarea, - // in which case reading its value would be expensive. - if (this.contextMenuPending || !cm.state.focused || - (hasSelection(input) && !prevInput) || - isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq) - return false; + function resetModeState (cm) { + cm.doc.iter(function (line) { + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + }); + cm.doc.frontier = cm.doc.first; + startWorker(cm, 100); + cm.state.modeGen++; + if (cm.curOp) regChange(cm); + } - var text = input.value; - // If nothing changed, bail. - if (text == prevInput && !cm.somethingSelected()) return false; - // Work around nonsensical selection resetting in IE9/10, and - // inexplicable appearance of private area unicode characters on - // some key combos in Mac (#2689). - if (ie && ie_version >= 9 && this.hasSelection === text || - mac && /[\uf700-\uf7ff]/.test(text)) { - cm.display.input.reset(); - return false; - } - - if (cm.doc.sel == cm.display.selForContextMenu) { - var first = text.charCodeAt(0); - if (first == 0x200b && !prevInput) prevInput = "\u200b"; - if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } - } - // Find the part of the input that is actually new - var same = 0, l = Math.min(prevInput.length, text.length); - while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; - - var self = this; - runInOp(cm, function() { - applyTextInput(cm, text.slice(same), prevInput.length - same, - null, self.composing ? "*compose" : null); - - // Don't leave long text in the textarea, since it makes further polling slow - if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; - else self.prevInput = text; - - if (self.composing) { - self.composing.range.clear(); - self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), - {className: "CodeMirror-composing"}); - } - }); - return true; - }, - - ensurePolled: function() { - if (this.pollingFast && this.poll()) this.pollingFast = false; - }, - - onKeyPress: function() { - if (ie && ie_version >= 9) this.hasSelection = null; - this.fastPoll(); - }, - - onContextMenu: function(e) { - var input = this, cm = input.cm, display = cm.display, te = input.textarea; - var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; - if (!pos || presto) return; // Opera is difficult. - - // Reset the current text selection only if the click is done outside of the selection - // and 'resetSelectionOnContextMenu' option is true. - var reset = cm.options.resetSelectionOnContextMenu; - if (reset && cm.doc.sel.contains(pos) == -1) - operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll); - - var oldCSS = te.style.cssText; - input.wrapper.style.position = "absolute"; - te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + - "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + - (ie ? "rgba(255, 255, 255, .05)" : "transparent") + - "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; - if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) - display.input.focus(); - if (webkit) window.scrollTo(null, oldScrollY); - display.input.reset(); - // Adds "Select all" to context menu in FF - if (!cm.somethingSelected()) te.value = input.prevInput = " "; - input.contextMenuPending = true; - display.selForContextMenu = cm.doc.sel; - clearTimeout(display.detectingSelectAll); - - // Select-all will be greyed out if there's nothing to select, so - // this adds a zero-width space so that we can later check whether - // it got selected. - function prepareSelectAllHack() { - if (te.selectionStart != null) { - var selected = cm.somethingSelected(); - var extval = "\u200b" + (selected ? te.value : ""); - te.value = "\u21da"; // Used to catch context-menu undo - te.value = extval; - input.prevInput = selected ? "" : "\u200b"; - te.selectionStart = 1; te.selectionEnd = extval.length; - // Re-set this, in case some other handler touched the - // selection in the meantime. - display.selForContextMenu = cm.doc.sel; - } - } - function rehide() { - input.contextMenuPending = false; - input.wrapper.style.position = "relative"; - te.style.cssText = oldCSS; - if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); - - // Try to detect the user choosing select-all - if (te.selectionStart != null) { - if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); - var i = 0, poll = function() { - if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && - te.selectionEnd > 0 && input.prevInput == "\u200b") - operation(cm, commands.selectAll)(cm); - else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); - else display.input.reset(); - }; - display.detectingSelectAll = setTimeout(poll, 200); - } - } - - if (ie && ie_version >= 9) prepareSelectAllHack(); - if (captureRightClick) { - e_stop(e); - var mouseup = function() { - off(window, "mouseup", mouseup); - setTimeout(rehide, 20); - }; - on(window, "mouseup", mouseup); - } else { - setTimeout(rehide, 50); - } - }, - - setUneditable: nothing, - - needsContentAttribute: false - }, TextareaInput.prototype); - - // CONTENTEDITABLE INPUT STYLE - - function ContentEditableInput(cm) { - this.cm = cm; - this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; - this.polling = new Delayed(); - this.gracePeriod = false; - } - - ContentEditableInput.prototype = copyObj({ - init: function(display) { - var input = this, cm = input.cm; - var div = input.div = display.lineDiv; - div.contentEditable = "true"; - disableBrowserMagic(div); - - on(div, "paste", function(e) { handlePaste(e, cm); }) - - on(div, "compositionstart", function(e) { - var data = e.data; - input.composing = {sel: cm.doc.sel, data: data, startData: data}; - if (!data) return; - var prim = cm.doc.sel.primary(); - var line = cm.getLine(prim.head.line); - var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); - if (found > -1 && found <= prim.head.ch) - input.composing.sel = simpleSelection(Pos(prim.head.line, found), - Pos(prim.head.line, found + data.length)); - }); - on(div, "compositionupdate", function(e) { - input.composing.data = e.data; - }); - on(div, "compositionend", function(e) { - var ours = input.composing; - if (!ours) return; - if (e.data != ours.startData && !/\u200b/.test(e.data)) - ours.data = e.data; - // Need a small delay to prevent other code (input event, - // selection polling) from doing damage when fired right after - // compositionend. - setTimeout(function() { - if (!ours.handled) - input.applyComposition(ours); - if (input.composing == ours) - input.composing = null; - }, 50); - }); - - on(div, "touchstart", function() { - input.forceCompositionEnd(); - }); - - on(div, "input", function() { - if (input.composing) return; - if (!input.pollContent()) - runInOp(input.cm, function() {regChange(cm);}); - }); - - function onCopyCut(e) { - if (cm.somethingSelected()) { - lastCopied = cm.getSelections(); - if (e.type == "cut") cm.replaceSelection("", null, "cut"); - } else if (!cm.options.lineWiseCopyCut) { - return; + function wrappingChanged (cm) { + if (cm.options.lineWrapping) { + addClass(cm.display.wrapper, "CodeMirror-wrap"); + cm.display.sizer.style.minWidth = ""; + cm.display.sizerWidth = null; } else { - var ranges = copyableRanges(cm); - lastCopied = ranges.text; - if (e.type == "cut") { - cm.operation(function() { - cm.setSelections(ranges.ranges, 0, sel_dontScroll); - cm.replaceSelection("", null, "cut"); - }); - } + rmClass(cm.display.wrapper, "CodeMirror-wrap"); + findMaxLine(cm); } - // iOS exposes the clipboard API, but seems to discard content inserted into it - if (e.clipboardData && !ios) { - e.preventDefault(); - e.clipboardData.clearData(); - e.clipboardData.setData("text/plain", lastCopied.join("\n")); - } else { - // Old-fashioned briefly-focus-a-textarea hack - var kludge = hiddenTextarea(), te = kludge.firstChild; - cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); - te.value = lastCopied.join("\n"); - var hadFocus = document.activeElement; - selectInput(te); - setTimeout(function() { - cm.display.lineSpace.removeChild(kludge); - hadFocus.focus(); - }, 50); - } - } - on(div, "copy", onCopyCut); - on(div, "cut", onCopyCut); - }, - - prepareSelection: function() { - var result = prepareSelection(this.cm, false); - result.focus = this.cm.state.focused; - return result; - }, - - showSelection: function(info) { - if (!info || !this.cm.display.view.length) return; - if (info.focus) this.showPrimarySelection(); - this.showMultipleSelections(info); - }, - - showPrimarySelection: function() { - var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); - var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); - var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); - if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && - cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && - cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) - return; - - var start = posToDOM(this.cm, prim.from()); - var end = posToDOM(this.cm, prim.to()); - if (!start && !end) return; - - var view = this.cm.display.view; - var old = sel.rangeCount && sel.getRangeAt(0); - if (!start) { - start = {node: view[0].measure.map[2], offset: 0}; - } else if (!end) { // FIXME dangerously hacky - var measure = view[view.length - 1].measure; - var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; - end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; - } - - try { var rng = range(start.node, start.offset, end.offset, end.node); } - catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible - if (rng) { - sel.removeAllRanges(); - sel.addRange(rng); - if (old && sel.anchorNode == null) sel.addRange(old); - else if (gecko) this.startGracePeriod(); - } - this.rememberSelection(); - }, - - startGracePeriod: function() { - var input = this; - clearTimeout(this.gracePeriod); - this.gracePeriod = setTimeout(function() { - input.gracePeriod = false; - if (input.selectionChanged()) - input.cm.operation(function() { input.cm.curOp.selectionChanged = true; }); - }, 20); - }, - - showMultipleSelections: function(info) { - removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); - removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); - }, - - rememberSelection: function() { - var sel = window.getSelection(); - this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; - this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; - }, - - selectionInEditor: function() { - var sel = window.getSelection(); - if (!sel.rangeCount) return false; - var node = sel.getRangeAt(0).commonAncestorContainer; - return contains(this.div, node); - }, - - focus: function() { - if (this.cm.options.readOnly != "nocursor") this.div.focus(); - }, - blur: function() { this.div.blur(); }, - getField: function() { return this.div; }, - - supportsTouch: function() { return true; }, - - receivedFocus: function() { - var input = this; - if (this.selectionInEditor()) - this.pollSelection(); - else - runInOp(this.cm, function() { input.cm.curOp.selectionChanged = true; }); - - function poll() { - if (input.cm.state.focused) { - input.pollSelection(); - input.polling.set(input.cm.options.pollInterval, poll); - } - } - this.polling.set(this.cm.options.pollInterval, poll); - }, - - selectionChanged: function() { - var sel = window.getSelection(); - return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || - sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; - }, - - pollSelection: function() { - if (!this.composing && !this.gracePeriod && this.selectionChanged()) { - var sel = window.getSelection(), cm = this.cm; - this.rememberSelection(); - var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); - var head = domToPos(cm, sel.focusNode, sel.focusOffset); - if (anchor && head) runInOp(cm, function() { - setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); - if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; - }); - } - }, - - pollContent: function() { - var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); - var from = sel.from(), to = sel.to(); - if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; - - var fromIndex; - if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { - var fromLine = lineNo(display.view[0].line); - var fromNode = display.view[0].node; - } else { - var fromLine = lineNo(display.view[fromIndex].line); - var fromNode = display.view[fromIndex - 1].node.nextSibling; - } - var toIndex = findViewIndex(cm, to.line); - if (toIndex == display.view.length - 1) { - var toLine = display.viewTo - 1; - var toNode = display.lineDiv.lastChild; - } else { - var toLine = lineNo(display.view[toIndex + 1].line) - 1; - var toNode = display.view[toIndex + 1].node.previousSibling; - } - - var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); - var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); - while (newText.length > 1 && oldText.length > 1) { - if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } - else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } - else break; - } - - var cutFront = 0, cutEnd = 0; - var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); - while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) - ++cutFront; - var newBot = lst(newText), oldBot = lst(oldText); - var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), - oldBot.length - (oldText.length == 1 ? cutFront : 0)); - while (cutEnd < maxCutEnd && - newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) - ++cutEnd; - - newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); - newText[0] = newText[0].slice(cutFront); - - var chFrom = Pos(fromLine, cutFront); - var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); - if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { - replaceRange(cm.doc, newText, chFrom, chTo, "+input"); - return true; - } - }, - - ensurePolled: function() { - this.forceCompositionEnd(); - }, - reset: function() { - this.forceCompositionEnd(); - }, - forceCompositionEnd: function() { - if (!this.composing || this.composing.handled) return; - this.applyComposition(this.composing); - this.composing.handled = true; - this.div.blur(); - this.div.focus(); - }, - applyComposition: function(composing) { - if (composing.data && composing.data != composing.startData) - operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel); - }, - - setUneditable: function(node) { - node.setAttribute("contenteditable", "false"); - }, - - onKeyPress: function(e) { - e.preventDefault(); - operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); - }, - - onContextMenu: nothing, - resetPosition: nothing, - - needsContentAttribute: true - }, ContentEditableInput.prototype); - - function posToDOM(cm, pos) { - var view = findViewForLine(cm, pos.line); - if (!view || view.hidden) return null; - var line = getLine(cm.doc, pos.line); - var info = mapFromLineView(view, line, pos.line); - - var order = getOrder(line), side = "left"; - if (order) { - var partPos = getBidiPartAt(order, pos.ch); - side = partPos % 2 ? "right" : "left"; - } - var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); - result.offset = result.collapse == "right" ? result.end : result.start; - return result; - } - - function badPos(pos, bad) { if (bad) pos.bad = true; return pos; } - - function domToPos(cm, node, offset) { - var lineNode; - if (node == cm.display.lineDiv) { - lineNode = cm.display.lineDiv.childNodes[offset]; - if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); - node = null; offset = 0; - } else { - for (lineNode = node;; lineNode = lineNode.parentNode) { - if (!lineNode || lineNode == cm.display.lineDiv) return null; - if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; - } - } - for (var i = 0; i < cm.display.view.length; i++) { - var lineView = cm.display.view[i]; - if (lineView.node == lineNode) - return locateNodeInLineView(lineView, node, offset); - } - } - - function locateNodeInLineView(lineView, node, offset) { - var wrapper = lineView.text.firstChild, bad = false; - if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); - if (node == wrapper) { - bad = true; - node = wrapper.childNodes[offset]; - offset = 0; - if (!node) { - var line = lineView.rest ? lst(lineView.rest) : lineView.line; - return badPos(Pos(lineNo(line), line.text.length), bad); - } - } - - var textNode = node.nodeType == 3 ? node : null, topNode = node; - if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { - textNode = node.firstChild; - if (offset) offset = textNode.nodeValue.length; - } - while (topNode.parentNode != wrapper) topNode = topNode.parentNode; - var measure = lineView.measure, maps = measure.maps; - - function find(textNode, topNode, offset) { - for (var i = -1; i < (maps ? maps.length : 0); i++) { - var map = i < 0 ? measure.map : maps[i]; - for (var j = 0; j < map.length; j += 3) { - var curNode = map[j + 2]; - if (curNode == textNode || curNode == topNode) { - var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); - var ch = map[j] + offset; - if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; - return Pos(line, ch); - } - } - } - } - var found = find(textNode, topNode, offset); - if (found) return badPos(found, bad); - - // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems - for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { - found = find(after, after.firstChild, 0); - if (found) - return badPos(Pos(found.line, found.ch - dist), bad); - else - dist += after.textContent.length; - } - for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { - found = find(before, before.firstChild, -1); - if (found) - return badPos(Pos(found.line, found.ch + dist), bad); - else - dist += after.textContent.length; - } - } - - function domTextBetween(cm, from, to, fromLine, toLine) { - var text = "", closing = false; - function recognizeMarker(id) { return function(marker) { return marker.id == id; }; } - function walk(node) { - if (node.nodeType == 1) { - var cmText = node.getAttribute("cm-text"); - if (cmText != null) { - if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); - text += cmText; - return; - } - var markerID = node.getAttribute("cm-marker"), range; - if (markerID) { - var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); - if (found.length && (range = found[0].find())) - text += getBetween(cm.doc, range.from, range.to).join("\n"); - return; - } - if (node.getAttribute("contenteditable") == "false") return; - for (var i = 0; i < node.childNodes.length; i++) - walk(node.childNodes[i]); - if (/^(pre|div|p)$/i.test(node.nodeName)) - closing = true; - } else if (node.nodeType == 3) { - var val = node.nodeValue; - if (!val) return; - if (closing) { - text += "\n"; - closing = false; - } - text += val; - } - } - for (;;) { - walk(from); - if (from == to) break; - from = from.nextSibling; - } - return text; - } - - CodeMirror.inputStyles = {"textarea": TextareaInput, "contenteditable": ContentEditableInput}; - - // SELECTION / CURSOR - - // Selection objects are immutable. A new one is created every time - // the selection changes. A selection is one or more non-overlapping - // (and non-touching) ranges, sorted, and an integer that indicates - // which one is the primary selection (the one that's scrolled into - // view, that getCursor returns, etc). - function Selection(ranges, primIndex) { - this.ranges = ranges; - this.primIndex = primIndex; - } - - Selection.prototype = { - primary: function() { return this.ranges[this.primIndex]; }, - equals: function(other) { - if (other == this) return true; - if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; - for (var i = 0; i < this.ranges.length; i++) { - var here = this.ranges[i], there = other.ranges[i]; - if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; - } - return true; - }, - deepCopy: function() { - for (var out = [], i = 0; i < this.ranges.length; i++) - out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head)); - return new Selection(out, this.primIndex); - }, - somethingSelected: function() { - for (var i = 0; i < this.ranges.length; i++) - if (!this.ranges[i].empty()) return true; - return false; - }, - contains: function(pos, end) { - if (!end) end = pos; - for (var i = 0; i < this.ranges.length; i++) { - var range = this.ranges[i]; - if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) - return i; - } - return -1; - } - }; - - function Range(anchor, head) { - this.anchor = anchor; this.head = head; - } - - Range.prototype = { - from: function() { return minPos(this.anchor, this.head); }, - to: function() { return maxPos(this.anchor, this.head); }, - empty: function() { - return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; - } - }; - - // Take an unsorted, potentially overlapping set of ranges, and - // build a selection out of it. 'Consumes' ranges array (modifying - // it). - function normalizeSelection(ranges, primIndex) { - var prim = ranges[primIndex]; - ranges.sort(function(a, b) { return cmp(a.from(), b.from()); }); - primIndex = indexOf(ranges, prim); - for (var i = 1; i < ranges.length; i++) { - var cur = ranges[i], prev = ranges[i - 1]; - if (cmp(prev.to(), cur.from()) >= 0) { - var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); - var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; - if (i <= primIndex) --primIndex; - ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); - } - } - return new Selection(ranges, primIndex); - } - - function simpleSelection(anchor, head) { - return new Selection([new Range(anchor, head || anchor)], 0); - } - - // Most of the external API clips given positions to make sure they - // actually exist within the document. - function clipLine(doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} - function clipPos(doc, pos) { - if (pos.line < doc.first) return Pos(doc.first, 0); - var last = doc.first + doc.size - 1; - if (pos.line > last) return Pos(last, getLine(doc, last).text.length); - return clipToLen(pos, getLine(doc, pos.line).text.length); - } - function clipToLen(pos, linelen) { - var ch = pos.ch; - if (ch == null || ch > linelen) return Pos(pos.line, linelen); - else if (ch < 0) return Pos(pos.line, 0); - else return pos; - } - function isLine(doc, l) {return l >= doc.first && l < doc.first + doc.size;} - function clipPosArray(doc, array) { - for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); - return out; - } - - // SELECTION UPDATES - - // The 'scroll' parameter given to many of these indicated whether - // the new cursor position should be scrolled into view after - // modifying the selection. - - // If shift is held or the extend flag is set, extends a range to - // include a given position (and optionally a second position). - // Otherwise, simply returns the range between the given positions. - // Used for cursor motion and such. - function extendRange(doc, range, head, other) { - if (doc.cm && doc.cm.display.shift || doc.extend) { - var anchor = range.anchor; - if (other) { - var posBefore = cmp(head, anchor) < 0; - if (posBefore != (cmp(other, anchor) < 0)) { - anchor = head; - head = other; - } else if (posBefore != (cmp(head, other) < 0)) { - head = other; - } - } - return new Range(anchor, head); - } else { - return new Range(other || head, head); - } - } - - // Extend the primary selection range, discard the rest. - function extendSelection(doc, head, other, options) { - setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); - } - - // Extend all selections (pos is an array of selections with length - // equal the number of selections) - function extendSelections(doc, heads, options) { - for (var out = [], i = 0; i < doc.sel.ranges.length; i++) - out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null); - var newSel = normalizeSelection(out, doc.sel.primIndex); - setSelection(doc, newSel, options); - } - - // Updates a single range in the selection. - function replaceOneSelection(doc, i, range, options) { - var ranges = doc.sel.ranges.slice(0); - ranges[i] = range; - setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); - } - - // Reset the selection to a single range. - function setSimpleSelection(doc, anchor, head, options) { - setSelection(doc, simpleSelection(anchor, head), options); - } - - // Give beforeSelectionChange handlers a change to influence a - // selection update. - function filterSelectionChange(doc, sel) { - var obj = { - ranges: sel.ranges, - update: function(ranges) { - this.ranges = []; - for (var i = 0; i < ranges.length; i++) - this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), - clipPos(doc, ranges[i].head)); - } - }; - signal(doc, "beforeSelectionChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); - if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); - else return sel; - } - - function setSelectionReplaceHistory(doc, sel, options) { - var done = doc.history.done, last = lst(done); - if (last && last.ranges) { - done[done.length - 1] = sel; - setSelectionNoUndo(doc, sel, options); - } else { - setSelection(doc, sel, options); + estimateLineHeights(cm); + regChange(cm); + clearCaches(cm); + setTimeout(function () {updateScrollbars(cm);}, 100); + } + + // Returns a function that estimates the height of a line, to use as + // first approximation until the line becomes visible (and is thus + // properly measurable). + function estimateHeight (cm) { + var th = textHeight(cm.display), wrapping = cm.options.lineWrapping; + var perLine = wrapping && Math.max(5, cm.display.scroller.clientWidth / charWidth(cm.display) - 3); + return function (line) { + if (lineIsHidden(cm.doc, line)) return 0; + + var widgetsHeight = 0; + if (line.widgets) { + for (var i = 0; i < line.widgets.length; i++) { + if (line.widgets[i].height) widgetsHeight += line.widgets[i].height; + } + } + + if (wrapping) {return widgetsHeight + (Math.ceil(line.text.length / perLine) || 1) * th;} + return widgetsHeight + th; + }; } - } - // Set a new selection. - function setSelection(doc, sel, options) { - setSelectionNoUndo(doc, sel, options); - addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); - } + function estimateLineHeights (cm) { + var doc = cm.doc, est = estimateHeight(cm); + doc.iter(function (line) { + var estHeight = est(line); + if (estHeight != line.height) updateLineHeight(line, estHeight); + }); + } - function setSelectionNoUndo(doc, sel, options) { - if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) - sel = filterSelectionChange(doc, sel); + function themeChanged (cm) { + cm.display.wrapper.className = cm.display.wrapper.className.replace(/\s*cm-s-\S+/g, "") + + cm.options.theme.replace(/(^|\s)\s*/g, " cm-s-"); + clearCaches(cm); + } + + function guttersChanged (cm) { + updateGutters(cm); + regChange(cm); + setTimeout(function () {alignHorizontally(cm);}, 20); + } + + // Rebuild the gutter elements, ensure the margin to the left of the + // code matches their width. + function updateGutters (cm) { + var gutters = cm.display.gutters, specs = cm.options.gutters; + removeChildren(gutters); + for (var i = 0; i < specs.length; ++i) { + var gutterClass = specs[i]; + var gElt = gutters.appendChild(elt("div", null, "CodeMirror-gutter " + gutterClass)); + if (gutterClass == "CodeMirror-linenumbers") { + cm.display.lineGutter = gElt; + gElt.style.width = (cm.display.lineNumWidth || 1) + "px"; + } + } + gutters.style.display = i ? "" : "none"; + updateGutterSpace(cm); + } - var bias = options && options.bias || - (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); - setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); - - if (!(options && options.scroll === false) && doc.cm) - ensureCursorVisible(doc.cm); - } - - function setSelectionInner(doc, sel) { - if (sel.equals(doc.sel)) return; - - doc.sel = sel; - - if (doc.cm) { - doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; - signalCursorActivity(doc.cm); - } - signalLater(doc, "cursorActivity", doc); - } - - // Verify that the selection does not partially select any atomic - // marked ranges. - function reCheckSelection(doc) { - setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); - } - - // Return a selection that does not partially select any atomic - // ranges. - function skipAtomicInSelection(doc, sel, bias, mayClear) { - var out; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); - var newHead = skipAtomic(doc, range.head, bias, mayClear); - if (out || newAnchor != range.anchor || newHead != range.head) { - if (!out) out = sel.ranges.slice(0, i); - out[i] = new Range(newAnchor, newHead); - } - } - return out ? normalizeSelection(out, sel.primIndex) : sel; - } - - // Ensure a given position is not inside an atomic range. - function skipAtomic(doc, pos, bias, mayClear) { - var flipped = false, curPos = pos; - var dir = bias || 1; - doc.cantEdit = false; - search: for (;;) { - var line = getLine(doc, curPos.line); - if (line.markedSpans) { - for (var i = 0; i < line.markedSpans.length; ++i) { - var sp = line.markedSpans[i], m = sp.marker; - if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && - (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { - if (mayClear) { - signal(m, "beforeCursorEnter"); - if (m.explicitlyCleared) { - if (!line.markedSpans) break; - else {--i; continue;} - } - } - if (!m.atomic) continue; - var newPos = m.find(dir < 0 ? -1 : 1); - if (cmp(newPos, curPos) == 0) { - newPos.ch += dir; - if (newPos.ch < 0) { - if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); - else newPos = null; - } else if (newPos.ch > line.text.length) { - if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); - else newPos = null; - } - if (!newPos) { - if (flipped) { - // Driven in a corner -- no valid cursor position found at all - // -- try again *with* clearing, if we didn't already - if (!mayClear) return skipAtomic(doc, pos, bias, true); - // Otherwise, turn off editing until further notice, and return the start of the doc - doc.cantEdit = true; - return Pos(doc.first, 0); - } - flipped = true; newPos = pos; dir = -dir; - } - } - curPos = newPos; - continue search; - } - } - } - return curPos; - } - } - - // SELECTION DRAWING - - function updateSelection(cm) { - cm.display.input.showSelection(cm.display.input.prepareSelection()); - } - - function prepareSelection(cm, primary) { - var doc = cm.doc, result = {}; - var curFragment = result.cursors = document.createDocumentFragment(); - var selFragment = result.selection = document.createDocumentFragment(); - - for (var i = 0; i < doc.sel.ranges.length; i++) { - if (primary === false && i == doc.sel.primIndex) continue; - var range = doc.sel.ranges[i]; - var collapsed = range.empty(); - if (collapsed || cm.options.showCursorWhenSelecting) - drawSelectionCursor(cm, range, curFragment); - if (!collapsed) - drawSelectionRange(cm, range, selFragment); - } - return result; - } - - // Draws a cursor for the given range - function drawSelectionCursor(cm, range, output) { - var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine); - - var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); - cursor.style.left = pos.left + "px"; - cursor.style.top = pos.top + "px"; - cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; - - if (pos.other) { - // Secondary cursor, shown when on a 'jump' in bi-directional text - var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); - otherCursor.style.display = ""; - otherCursor.style.left = pos.other.left + "px"; - otherCursor.style.top = pos.other.top + "px"; - otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; - } - } - - // Draws the given range as a highlighted selection - function drawSelectionRange(cm, range, output) { - var display = cm.display, doc = cm.doc; - var fragment = document.createDocumentFragment(); - var padding = paddingH(cm.display), leftSide = padding.left; - var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; - - function add(left, top, width, bottom) { - if (top < 0) top = 0; - top = Math.round(top); - bottom = Math.round(bottom); - fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + - "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + - "px; height: " + (bottom - top) + "px")); + function updateGutterSpace (cm) { + var width = cm.display.gutters.offsetWidth; + cm.display.sizer.style.marginLeft = width + "px"; } - function drawForLine(line, fromArg, toArg) { - var lineObj = getLine(doc, line); - var lineLen = lineObj.text.length; - var start, end; - function coords(ch, bias) { - return charCoords(cm, Pos(line, ch), "div", lineObj, bias); - } + // Compute the character length of a line, taking into account + // collapsed ranges (see markText) that might hide parts, and join + // other lines onto it. + function lineLength (line) { + if (line.height == 0) return 0; + var len = line.text.length, merged, cur = line; + while (merged = collapsedSpanAtStart(cur)) { + var found = merged.find(0, true); + cur = found.from.line; + len += found.from.ch - found.to.ch; + } + cur = line; + while (merged = collapsedSpanAtEnd(cur)) { + var found = merged.find(0, true); + len -= cur.text.length - found.from.ch; + cur = found.to.line; + len += cur.text.length - found.to.ch; + } + return len; + } + + // Find the longest line in the document. + function findMaxLine (cm) { + var d = cm.display, doc = cm.doc; + d.maxLine = getLine(doc, doc.first); + d.maxLineLength = lineLength(d.maxLine); + d.maxLineChanged = true; + doc.iter(function (line) { + var len = lineLength(line); + if (len > d.maxLineLength) { + d.maxLineLength = len; + d.maxLine = line; + } + }); + } - iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function(from, to, dir) { - var leftPos = coords(from, "left"), rightPos, left, right; - if (from == to) { - rightPos = leftPos; - left = right = leftPos.left; - } else { - rightPos = coords(to - 1, "right"); - if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } - left = leftPos.left; - right = rightPos.right; - } - if (fromArg == null && from == 0) left = leftSide; - if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part - add(left, leftPos.top, null, leftPos.bottom); - left = leftSide; - if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); - } - if (toArg == null && to == lineLen) right = rightSide; - if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) - start = leftPos; - if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) - end = rightPos; - if (left < leftSide + 1) left = leftSide; - add(left, rightPos.top, right - left, rightPos.bottom); - }); - return {start: start, end: end}; - } - - var sFrom = range.from(), sTo = range.to(); - if (sFrom.line == sTo.line) { - drawForLine(sFrom.line, sFrom.ch, sTo.ch); - } else { - var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); - var singleVLine = visualLine(fromLine) == visualLine(toLine); - var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; - var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; - if (singleVLine) { - if (leftEnd.top < rightStart.top - 2) { - add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); - add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); - } else { - add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); - } - } - if (leftEnd.bottom < rightStart.top) - add(leftSide, leftEnd.bottom, null, rightStart.top); - } - - output.appendChild(fragment); - } - - // Cursor-blinking - function restartBlink(cm) { - if (!cm.state.focused) return; - var display = cm.display; - clearInterval(display.blinker); - var on = true; - display.cursorDiv.style.visibility = ""; - if (cm.options.cursorBlinkRate > 0) - display.blinker = setInterval(function() { - display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; - }, cm.options.cursorBlinkRate); - else if (cm.options.cursorBlinkRate < 0) - display.cursorDiv.style.visibility = "hidden"; - } - - // HIGHLIGHT WORKER - - function startWorker(cm, time) { - if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) - cm.state.highlight.set(time, bind(highlightWorker, cm)); - } - - function highlightWorker(cm) { - var doc = cm.doc; - if (doc.frontier < doc.first) doc.frontier = doc.first; - if (doc.frontier >= cm.display.viewTo) return; - var end = +new Date + cm.options.workTime; - var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); - var changedLines = []; - - doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function(line) { - if (doc.frontier >= cm.display.viewFrom) { // Visible - var oldStyles = line.styles; - var highlighted = highlightLine(cm, line, state, true); - line.styles = highlighted.styles; - var oldCls = line.styleClasses, newCls = highlighted.classes; - if (newCls) line.styleClasses = newCls; - else if (oldCls) line.styleClasses = null; - var ischange = !oldStyles || oldStyles.length != line.styles.length || - oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); - for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; - if (ischange) changedLines.push(doc.frontier); - line.stateAfter = copyState(doc.mode, state); - } else { - processLine(cm, line.text, state); - line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; - } - ++doc.frontier; - if (+new Date > end) { - startWorker(cm, cm.options.workDelay); - return true; - } - }); - if (changedLines.length) runInOp(cm, function() { - for (var i = 0; i < changedLines.length; i++) - regLineChange(cm, changedLines[i], "text"); - }); - } - - // Finds the line to start with when starting a parse. Tries to - // find a line with a stateAfter, so that it can start with a - // valid state. If that fails, it returns the line with the - // smallest indentation, which tends to need the least context to - // parse correctly. - function findStartLine(cm, n, precise) { - var minindent, minline, doc = cm.doc; - var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); - for (var search = n; search > lim; --search) { - if (search <= doc.first) return doc.first; - var line = getLine(doc, search - 1); - if (line.stateAfter && (!precise || search <= doc.frontier)) return search; - var indented = countColumn(line.text, null, cm.options.tabSize); - if (minline == null || minindent > indented) { - minline = search - 1; - minindent = indented; - } - } - return minline; - } - - function getStateBefore(cm, n, precise) { - var doc = cm.doc, display = cm.display; - if (!doc.mode.startState) return true; - var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos-1).stateAfter; - if (!state) state = startState(doc.mode); - else state = copyState(doc.mode, state); - doc.iter(pos, n, function(line) { - processLine(cm, line.text, state); - var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; - line.stateAfter = save ? copyState(doc.mode, state) : null; - ++pos; - }); - if (precise) doc.frontier = pos; - return state; - } - - // POSITION MEASUREMENT - - function paddingTop(display) {return display.lineSpace.offsetTop;} - function paddingVert(display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} - function paddingH(display) { - if (display.cachedPaddingH) return display.cachedPaddingH; - var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); - var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; - var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; - if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; - return data; - } - - function scrollGap(cm) { return scrollerGap - cm.display.nativeBarWidth; } - function displayWidth(cm) { - return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; - } - function displayHeight(cm) { - return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; - } - - // Ensure the lineView.wrapping.heights array is populated. This is - // an array of bottom offsets for the lines that make up a drawn - // line. When lineWrapping is on, there might be more than one - // height. - function ensureLineHeights(cm, lineView, rect) { - var wrapping = cm.options.lineWrapping; - var curWidth = wrapping && displayWidth(cm); - if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { - var heights = lineView.measure.heights = []; - if (wrapping) { - lineView.measure.width = curWidth; - var rects = lineView.text.firstChild.getClientRects(); - for (var i = 0; i < rects.length - 1; i++) { - var cur = rects[i], next = rects[i + 1]; - if (Math.abs(cur.bottom - next.bottom) > 2) - heights.push((cur.bottom + next.top) / 2 - rect.top); - } - } - heights.push(rect.bottom - rect.top); - } - } - - // Find a line map (mapping character offsets to text nodes) and a - // measurement cache for the given line number. (A line view might - // contain multiple lines when collapsed ranges are present.) - function mapFromLineView(lineView, line, lineN) { - if (lineView.line == line) - return {map: lineView.measure.map, cache: lineView.measure.cache}; - for (var i = 0; i < lineView.rest.length; i++) - if (lineView.rest[i] == line) - return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]}; - for (var i = 0; i < lineView.rest.length; i++) - if (lineNo(lineView.rest[i]) > lineN) - return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true}; - } - - // Render a line into the hidden node display.externalMeasured. Used - // when measurement is needed for a line that's not in the viewport. - function updateExternalMeasurement(cm, line) { - line = visualLine(line); - var lineN = lineNo(line); - var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); - view.lineN = lineN; - var built = view.built = buildLineContent(cm, view); - view.text = built.pre; - removeChildrenAndAdd(cm.display.lineMeasure, built.pre); - return view; - } - - // Get a {top, bottom, left, right} box (in line-local coordinates) - // for a given character. - function measureChar(cm, line, ch, bias) { - return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); - } - - // Find a line view that corresponds to the given line number. - function findViewForLine(cm, lineN) { - if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) - return cm.display.view[findViewIndex(cm, lineN)]; - var ext = cm.display.externalMeasured; - if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) - return ext; - } - - // Measurement can be split in two steps, the set-up work that - // applies to the whole line, and the measurement of the actual - // character. Functions like coordsChar, that need to do a lot of - // measurements in a row, can thus ensure that the set-up work is - // only done once. - function prepareMeasureForLine(cm, line) { - var lineN = lineNo(line); - var view = findViewForLine(cm, lineN); - if (view && !view.text) - view = null; - else if (view && view.changes) - updateLineForChanges(cm, view, lineN, getDimensions(cm)); - if (!view) - view = updateExternalMeasurement(cm, line); - - var info = mapFromLineView(view, line, lineN); - return { - line: line, view: view, rect: null, - map: info.map, cache: info.cache, before: info.before, - hasHeights: false - }; - } - - // Given a prepared measurement object, measures the position of an - // actual character (or fetches it from the cache). - function measureCharPrepared(cm, prepared, ch, bias, varHeight) { - if (prepared.before) ch = -1; - var key = ch + (bias || ""), found; - if (prepared.cache.hasOwnProperty(key)) { - found = prepared.cache[key]; - } else { - if (!prepared.rect) - prepared.rect = prepared.view.text.getBoundingClientRect(); - if (!prepared.hasHeights) { - ensureLineHeights(cm, prepared.view, prepared.rect); - prepared.hasHeights = true; - } - found = measureCharInner(cm, prepared, ch, bias); - if (!found.bogus) prepared.cache[key] = found; - } - return {left: found.left, right: found.right, - top: varHeight ? found.rtop : found.top, - bottom: varHeight ? found.rbottom : found.bottom}; - } - - var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; - - function nodeAndOffsetInLineMap(map, ch, bias) { - var node, start, end, collapse; - // First, search the line map for the text node corresponding to, - // or closest to, the target character. - for (var i = 0; i < map.length; i += 3) { - var mStart = map[i], mEnd = map[i + 1]; - if (ch < mStart) { - start = 0; end = 1; - collapse = "left"; - } else if (ch < mEnd) { - start = ch - mStart; - end = start + 1; - } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { - end = mEnd - mStart; - start = end - 1; - if (ch >= mEnd) collapse = "right"; - } - if (start != null) { - node = map[i + 2]; - if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) - collapse = bias; - if (bias == "left" && start == 0) - while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { - node = map[(i -= 3) + 2]; - collapse = "left"; - } - if (bias == "right" && start == mEnd - mStart) - while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { - node = map[(i += 3) + 2]; - collapse = "right"; - } - break; - } - } - return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; - } - - function measureCharInner(cm, prepared, ch, bias) { - var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); - var node = place.node, start = place.start, end = place.end, collapse = place.collapse; - - var rect; - if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. - for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned - while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; - while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; - if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { - rect = node.parentNode.getBoundingClientRect(); - } else if (ie && cm.options.lineWrapping) { - var rects = range(node, start, end).getClientRects(); - if (rects.length) - rect = rects[bias == "right" ? rects.length - 1 : 0]; - else - rect = nullRect; - } else { - rect = range(node, start, end).getBoundingClientRect() || nullRect; - } - if (rect.left || rect.right || start == 0) break; - end = start; - start = start - 1; - collapse = "right"; - } - if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); - } else { // If it is a widget, simply get the box for the whole widget. - if (start > 0) collapse = bias = "right"; - var rects; - if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) - rect = rects[bias == "right" ? rects.length - 1 : 0]; - else - rect = node.getBoundingClientRect(); - } - if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { - var rSpan = node.parentNode.getClientRects()[0]; - if (rSpan) - rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom}; - else - rect = nullRect; - } - - var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; - var mid = (rtop + rbot) / 2; - var heights = prepared.view.measure.heights; - for (var i = 0; i < heights.length - 1; i++) - if (mid < heights[i]) break; - var top = i ? heights[i - 1] : 0, bot = heights[i]; - var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, - right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, - top: top, bottom: bot}; - if (!rect.left && !rect.right) result.bogus = true; - if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } - - return result; - } - - // Work around problem with bounding client rects on ranges being - // returned incorrectly when zoomed on IE10 and below. - function maybeUpdateRectForZooming(measure, rect) { - if (!window.screen || screen.logicalXDPI == null || - screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) - return rect; - var scaleX = screen.logicalXDPI / screen.deviceXDPI; - var scaleY = screen.logicalYDPI / screen.deviceYDPI; - return {left: rect.left * scaleX, right: rect.right * scaleX, - top: rect.top * scaleY, bottom: rect.bottom * scaleY}; - } - - function clearLineMeasurementCacheFor(lineView) { - if (lineView.measure) { - lineView.measure.cache = {}; - lineView.measure.heights = null; - if (lineView.rest) for (var i = 0; i < lineView.rest.length; i++) - lineView.measure.caches[i] = {}; - } - } - - function clearLineMeasurementCache(cm) { - cm.display.externalMeasure = null; - removeChildren(cm.display.lineMeasure); - for (var i = 0; i < cm.display.view.length; i++) - clearLineMeasurementCacheFor(cm.display.view[i]); - } - - function clearCaches(cm) { - clearLineMeasurementCache(cm); - cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; - if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; - cm.display.lineNumChars = null; - } - - function pageScrollX() { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } - function pageScrollY() { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } - - // Converts a {top, bottom, left, right} box from line-local - // coordinates into another coordinate system. Context may be one of - // "line", "div" (display.lineDiv), "local"/null (editor), "window", - // or "page". - function intoCoordSystem(cm, lineObj, rect, context) { - if (lineObj.widgets) for (var i = 0; i < lineObj.widgets.length; ++i) if (lineObj.widgets[i].above) { - var size = widgetHeight(lineObj.widgets[i]); - rect.top += size; rect.bottom += size; - } - if (context == "line") return rect; - if (!context) context = "local"; - var yOff = heightAtLine(lineObj); - if (context == "local") yOff += paddingTop(cm.display); - else yOff -= cm.display.viewOffset; - if (context == "page" || context == "window") { - var lOff = cm.display.lineSpace.getBoundingClientRect(); - yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); - var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); - rect.left += xOff; rect.right += xOff; - } - rect.top += yOff; rect.bottom += yOff; - return rect; - } - - // Coverts a box from "div" coords to another coordinate system. - // Context may be "window", "page", "div", or "local"/null. - function fromCoordSystem(cm, coords, context) { - if (context == "div") return coords; - var left = coords.left, top = coords.top; - // First move into "page" coordinate system - if (context == "page") { - left -= pageScrollX(); - top -= pageScrollY(); - } else if (context == "local" || !context) { - var localBox = cm.display.sizer.getBoundingClientRect(); - left += localBox.left; - top += localBox.top; - } - - var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); - return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; - } - - function charCoords(cm, pos, context, lineObj, bias) { - if (!lineObj) lineObj = getLine(cm.doc, pos.line); - return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); - } - - // Returns a box for a given cursor position, which may have an - // 'other' property containing the position of the secondary cursor - // on a bidi boundary. - function cursorCoords(cm, pos, context, lineObj, preparedMeasure, varHeight) { - lineObj = lineObj || getLine(cm.doc, pos.line); - if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); - function get(ch, right) { - var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); - if (right) m.left = m.right; else m.right = m.left; - return intoCoordSystem(cm, lineObj, m, context); - } - function getBidi(ch, partPos) { - var part = order[partPos], right = part.level % 2; - if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { - part = order[--partPos]; - ch = bidiRight(part) - (part.level % 2 ? 0 : 1); - right = true; - } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { - part = order[++partPos]; - ch = bidiLeft(part) - part.level % 2; - right = false; - } - if (right && ch == part.to && ch > part.from) return get(ch - 1); - return get(ch, right); - } - var order = getOrder(lineObj), ch = pos.ch; - if (!order) return get(ch); - var partPos = getBidiPartAt(order, ch); - var val = getBidi(ch, partPos); - if (bidiOther != null) val.other = getBidi(ch, bidiOther); - return val; - } - - // Used to cheaply estimate the coordinates for a position. Used for - // intermediate scroll updates. - function estimateCoords(cm, pos) { - var left = 0, pos = clipPos(cm.doc, pos); - if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; - var lineObj = getLine(cm.doc, pos.line); - var top = heightAtLine(lineObj) + paddingTop(cm.display); - return {left: left, right: left, top: top, bottom: top + lineObj.height}; - } - - // Positions returned by coordsChar contain some extra information. - // xRel is the relative x position of the input coordinates compared - // to the found position (so xRel > 0 means the coordinates are to - // the right of the character position, for example). When outside - // is true, that means the coordinates lie outside the line's - // vertical range. - function PosWithInfo(line, ch, outside, xRel) { - var pos = Pos(line, ch); - pos.xRel = xRel; - if (outside) pos.outside = true; - return pos; - } - - // Compute the character position closest to the given coordinates. - // Input must be lineSpace-local ("div" coordinate system). - function coordsChar(cm, x, y) { - var doc = cm.doc; - y += cm.display.viewOffset; - if (y < 0) return PosWithInfo(doc.first, 0, true, -1); - var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; - if (lineN > last) - return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1); - if (x < 0) x = 0; - - var lineObj = getLine(doc, lineN); - for (;;) { - var found = coordsCharInner(cm, lineObj, lineN, x, y); - var merged = collapsedSpanAtEnd(lineObj); - var mergedPos = merged && merged.find(0, true); - if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) - lineN = lineNo(lineObj = mergedPos.to.line); - else - return found; + // Make sure the gutters options contains the element + // "CodeMirror-linenumbers" when the lineNumbers option is true. + function setGuttersForLineNumbers (options) { + var found = indexOf(options.gutters, "CodeMirror-linenumbers"); + if (found == -1 && options.lineNumbers) { + options.gutters = options.gutters.concat(["CodeMirror-linenumbers"]); + } else if (found > -1 && !options.lineNumbers) { + options.gutters = options.gutters.slice(0); + options.gutters.splice(found, 1); + } } - } - - function coordsCharInner(cm, lineObj, lineNo, x, y) { - var innerOff = y - heightAtLine(lineObj); - var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; - var preparedMeasure = prepareMeasureForLine(cm, lineObj); - - function getX(ch) { - var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); - wrongLine = true; - if (innerOff > sp.bottom) return sp.left - adjust; - else if (innerOff < sp.top) return sp.left + adjust; - else wrongLine = false; - return sp.left; - } - - var bidi = getOrder(lineObj), dist = lineObj.text.length; - var from = lineLeft(lineObj), to = lineRight(lineObj); - var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; - - if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); - // Do a binary search between these bounds. - for (;;) { - if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { - var ch = x < fromX || x - fromX <= toX - x ? from : to; - var xDiff = x - (ch == from ? fromX : toX); - while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; - var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, - xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); - return pos; - } - var step = Math.ceil(dist / 2), middle = from + step; - if (bidi) { - middle = from; - for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); - } - var middleX = getX(middle); - if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} - else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} - } - } - - var measureText; - // Compute the default text height. - function textHeight(display) { - if (display.cachedTextHeight != null) return display.cachedTextHeight; - if (measureText == null) { - measureText = elt("pre"); - // Measure a bunch of lines, for browsers that compute - // fractional heights. - for (var i = 0; i < 49; ++i) { - measureText.appendChild(document.createTextNode("x")); - measureText.appendChild(elt("br")); - } - measureText.appendChild(document.createTextNode("x")); - } - removeChildrenAndAdd(display.measure, measureText); - var height = measureText.offsetHeight / 50; - if (height > 3) display.cachedTextHeight = height; - removeChildren(display.measure); - return height || 1; - } - - // Compute the default character width. - function charWidth(display) { - if (display.cachedCharWidth != null) return display.cachedCharWidth; - var anchor = elt("span", "xxxxxxxxxx"); - var pre = elt("pre", [anchor]); - removeChildrenAndAdd(display.measure, pre); - var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; - if (width > 2) display.cachedCharWidth = width; - return width || 10; - } - - // OPERATIONS - - // Operations are used to wrap a series of changes to the editor - // state in such a way that each change won't have to update the - // cursor and display (which would be awkward, slow, and - // error-prone). Instead, display updates are batched and then all - // combined and executed at once. - - var operationGroup = null; - - var nextOpId = 0; - // Start a new operation. - function startOperation(cm) { - cm.curOp = { - cm: cm, - viewChanged: false, // Flag that indicates that lines might need to be redrawn - startHeight: cm.doc.height, // Used to detect need to update scrollbar - forceUpdate: false, // Used to force a redraw - updateInput: null, // Whether to reset the input textarea - typing: false, // Whether this reset should be careful to leave existing text (for compositing) - changeObjs: null, // Accumulated changes, for firing change events - cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on - cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already - selectionChanged: false, // Whether the selection needs to be redrawn - updateMaxLine: false, // Set when the widest line needs to be determined anew - scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet - scrollToPos: null, // Used to scroll to a specific position - focus: false, - id: ++nextOpId // Unique ID - }; - if (operationGroup) { - operationGroup.ops.push(cm.curOp); - } else { - cm.curOp.ownsGroup = operationGroup = { - ops: [cm.curOp], - delayedCallbacks: [] - }; + + // SCROLLBARS + + // Prepare DOM reads needed to update the scrollbars. Done in one + // shot to minimize update/measure roundtrips. + function measureForScrollbars (cm) { + var d = cm.display, gutterW = d.gutters.offsetWidth; + var docH = Math.round(cm.doc.height + paddingVert(cm.display)); + return { + clientHeight: d.scroller.clientHeight, + viewHeight: d.wrapper.clientHeight, + scrollWidth: d.scroller.scrollWidth, clientWidth: d.scroller.clientWidth, + viewWidth: d.wrapper.clientWidth, + barLeft: cm.options.fixedGutter ? gutterW : 0, + docHeight: docH, + scrollHeight: docH + scrollGap(cm) + d.barHeight, + nativeBarWidth: d.nativeBarWidth, + gutterWidth: gutterW + }; } - } - function fireCallbacksForOps(group) { - // Calls delayed callbacks and cursorActivity handlers until no - // new ones appear - var callbacks = group.delayedCallbacks, i = 0; - do { - for (; i < callbacks.length; i++) - callbacks[i](); - for (var j = 0; j < group.ops.length; j++) { - var op = group.ops[j]; - if (op.cursorActivityHandlers) - while (op.cursorActivityCalled < op.cursorActivityHandlers.length) - op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm); - } - } while (i < callbacks.length); - } - - // Finish an operation, updating the display and signalling delayed events - function endOperation(cm) { - var op = cm.curOp, group = op.ownsGroup; - if (!group) return; - - try { fireCallbacksForOps(group); } - finally { - operationGroup = null; - for (var i = 0; i < group.ops.length; i++) - group.ops[i].cm.curOp = null; - endOperations(group); - } - } - - // The DOM updates done when an operation finishes are batched so - // that the minimum number of relayouts are required. - function endOperations(group) { - var ops = group.ops; - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_R1(ops[i]); - for (var i = 0; i < ops.length; i++) // Write DOM (maybe) - endOperation_W1(ops[i]); - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_R2(ops[i]); - for (var i = 0; i < ops.length; i++) // Write DOM (maybe) - endOperation_W2(ops[i]); - for (var i = 0; i < ops.length; i++) // Read DOM - endOperation_finish(ops[i]); - } - - function endOperation_R1(op) { - var cm = op.cm, display = cm.display; - maybeClipScrollbars(cm); - if (op.updateMaxLine) findMaxLine(cm); - - op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || - op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || - op.scrollToPos.to.line >= display.viewTo) || - display.maxLineChanged && cm.options.lineWrapping; - op.update = op.mustUpdate && - new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); - } + function NativeScrollbars (place, scroll, cm) { + this.cm = cm; + var vert = this.vert = elt("div", [elt("div", null, null, "min-width: 1px")], "CodeMirror-vscrollbar"); + var horiz = this.horiz = elt("div", [elt("div", null, null, "height: 100%; min-height: 1px")], "CodeMirror-hscrollbar"); + place(vert); place(horiz); - function endOperation_W1(op) { - op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); - } + on(vert, "scroll", function () { + if (vert.clientHeight) scroll(vert.scrollTop, "vertical"); + }); + on(horiz, "scroll", function () { + if (horiz.clientWidth) scroll(horiz.scrollLeft, "horizontal"); + }); - function endOperation_R2(op) { - var cm = op.cm, display = cm.display; - if (op.updatedDisplay) updateHeightsInViewport(cm); + this.checkedOverlay = false; + // Need to set a minimum width to see the scrollbar on IE7 (but must not set it on IE8). + if (ie && ie_version < 8) this.horiz.style.minHeight = this.vert.style.minWidth = "18px"; + } - op.barMeasure = measureForScrollbars(cm); + NativeScrollbars.prototype = copyObj({ + update: function (measure) { + var needsH = measure.scrollWidth > measure.clientWidth + 1; + var needsV = measure.scrollHeight > measure.clientHeight + 1; + var sWidth = measure.nativeBarWidth; - // If the max line changed since it was last measured, measure it, - // and ensure the document's width matches it. - // updateDisplay_W2 will use these properties to do the actual resizing - if (display.maxLineChanged && !cm.options.lineWrapping) { - op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; - cm.display.sizerWidth = op.adjustWidthTo; - op.barMeasure.scrollWidth = - Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); - op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); - } - - if (op.updatedDisplay || op.selectionChanged) - op.preparedSelection = display.input.prepareSelection(); - } - - function endOperation_W2(op) { - var cm = op.cm; - - if (op.adjustWidthTo != null) { - cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; - if (op.maxScrollLeft < cm.doc.scrollLeft) - setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true); - cm.display.maxLineChanged = false; - } - - if (op.preparedSelection) - cm.display.input.showSelection(op.preparedSelection); - if (op.updatedDisplay) - setDocumentHeight(cm, op.barMeasure); - if (op.updatedDisplay || op.startHeight != cm.doc.height) - updateScrollbars(cm, op.barMeasure); - - if (op.selectionChanged) restartBlink(cm); - - if (cm.state.focused && op.updateInput) - cm.display.input.reset(op.typing); - if (op.focus && op.focus == activeElt()) ensureFocus(op.cm); - } - - function endOperation_finish(op) { - var cm = op.cm, display = cm.display, doc = cm.doc; - - if (op.updatedDisplay) postUpdateDisplay(cm, op.update); - - // Abort mouse wheel delta measurement, when scrolling explicitly - if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) - display.wheelStartX = display.wheelStartY = null; - - // Propagate the scroll position to the actual DOM scroller - if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { - doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); - display.scrollbars.setScrollTop(doc.scrollTop); - display.scroller.scrollTop = doc.scrollTop; - } - if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { - doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft)); - display.scrollbars.setScrollLeft(doc.scrollLeft); - display.scroller.scrollLeft = doc.scrollLeft; - alignHorizontally(cm); - } - // If we need to scroll a specific position into view, do so. - if (op.scrollToPos) { - var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), - clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); - if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); - } - - // Fire events for markers that are hidden/unidden by editing or - // undoing - var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; - if (hidden) for (var i = 0; i < hidden.length; ++i) - if (!hidden[i].lines.length) signal(hidden[i], "hide"); - if (unhidden) for (var i = 0; i < unhidden.length; ++i) - if (unhidden[i].lines.length) signal(unhidden[i], "unhide"); - - if (display.wrapper.offsetHeight) - doc.scrollTop = cm.display.scroller.scrollTop; - - // Fire change events, and delayed event handlers - if (op.changeObjs) - signal(cm, "changes", cm, op.changeObjs); - if (op.update) - op.update.finish(); - } - - // Run the given function in an operation - function runInOp(cm, f) { - if (cm.curOp) return f(); - startOperation(cm); - try { return f(); } - finally { endOperation(cm); } - } - // Wraps a function in an operation. Returns the wrapped function. - function operation(cm, f) { - return function() { - if (cm.curOp) return f.apply(cm, arguments); - startOperation(cm); - try { return f.apply(cm, arguments); } - finally { endOperation(cm); } - }; - } - // Used to add methods to editor and doc instances, wrapping them in - // operations. - function methodOp(f) { - return function() { - if (this.curOp) return f.apply(this, arguments); - startOperation(this); - try { return f.apply(this, arguments); } - finally { endOperation(this); } - }; - } - function docMethodOp(f) { - return function() { - var cm = this.cm; - if (!cm || cm.curOp) return f.apply(this, arguments); - startOperation(cm); - try { return f.apply(this, arguments); } - finally { endOperation(cm); } - }; - } + if (needsV) { + this.vert.style.display = "block"; + this.vert.style.bottom = needsH ? sWidth + "px" : "0"; + var totalHeight = measure.viewHeight - (needsH ? sWidth : 0); + // A bug in IE8 can cause this value to be negative, so guard it. + this.vert.firstChild.style.height = + Math.max(0, measure.scrollHeight - measure.clientHeight + totalHeight) + "px"; + } else { + this.vert.style.display = ""; + this.vert.firstChild.style.height = "0"; + } - // VIEW TRACKING + if (needsH) { + this.horiz.style.display = "block"; + this.horiz.style.right = needsV ? sWidth + "px" : "0"; + this.horiz.style.left = measure.barLeft + "px"; + var totalWidth = measure.viewWidth - measure.barLeft - (needsV ? sWidth : 0); + this.horiz.firstChild.style.width = + (measure.scrollWidth - measure.clientWidth + totalWidth) + "px"; + } else { + this.horiz.style.display = ""; + this.horiz.firstChild.style.width = "0"; + } - // These objects are used to represent the visible (currently drawn) - // part of the document. A LineView may correspond to multiple - // logical lines, if those are connected by collapsed ranges. - function LineView(doc, line, lineN) { - // The starting line - this.line = line; - // Continuing lines, if any - this.rest = visualLineContinued(line); - // Number of logical lines in this visual line - this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; - this.node = this.text = null; - this.hidden = lineIsHidden(doc, line); - } - - // Create a range of LineView objects for the given lines. - function buildViewArray(cm, from, to) { - var array = [], nextPos; - for (var pos = from; pos < to; pos = nextPos) { - var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); - nextPos = pos + view.size; - array.push(view); - } - return array; - } - - // Updates the display.view data structure for a given change to the - // document. From and to are in pre-change coordinates. Lendiff is - // the amount of lines added or subtracted by the change. This is - // used for changes that span multiple lines, or change the way - // lines are divided into visual lines. regLineChange (below) - // registers single-line changes. - function regChange(cm, from, to, lendiff) { - if (from == null) from = cm.doc.first; - if (to == null) to = cm.doc.first + cm.doc.size; - if (!lendiff) lendiff = 0; - - var display = cm.display; - if (lendiff && to < display.viewTo && - (display.updateLineNumbers == null || display.updateLineNumbers > from)) - display.updateLineNumbers = from; - - cm.curOp.viewChanged = true; - - if (from >= display.viewTo) { // Change after - if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) - resetView(cm); - } else if (to <= display.viewFrom) { // Change before - if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { - resetView(cm); - } else { - display.viewFrom += lendiff; - display.viewTo += lendiff; - } - } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap - resetView(cm); - } else if (from <= display.viewFrom) { // Top overlap - var cut = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cut) { - display.view = display.view.slice(cut.index); - display.viewFrom = cut.lineN; - display.viewTo += lendiff; - } else { - resetView(cm); - } - } else if (to >= display.viewTo) { // Bottom overlap - var cut = viewCuttingPoint(cm, from, from, -1); - if (cut) { - display.view = display.view.slice(0, cut.index); - display.viewTo = cut.lineN; - } else { - resetView(cm); - } - } else { // Gap in the middle - var cutTop = viewCuttingPoint(cm, from, from, -1); - var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); - if (cutTop && cutBot) { - display.view = display.view.slice(0, cutTop.index) - .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) - .concat(display.view.slice(cutBot.index)); - display.viewTo += lendiff; - } else { - resetView(cm); - } - } - - var ext = display.externalMeasured; - if (ext) { - if (to < ext.lineN) - ext.lineN += lendiff; - else if (from < ext.lineN + ext.size) - display.externalMeasured = null; - } - } - - // Register a change to a single line. Type must be one of "text", - // "gutter", "class", "widget" - function regLineChange(cm, line, type) { - cm.curOp.viewChanged = true; - var display = cm.display, ext = cm.display.externalMeasured; - if (ext && line >= ext.lineN && line < ext.lineN + ext.size) - display.externalMeasured = null; - - if (line < display.viewFrom || line >= display.viewTo) return; - var lineView = display.view[findViewIndex(cm, line)]; - if (lineView.node == null) return; - var arr = lineView.changes || (lineView.changes = []); - if (indexOf(arr, type) == -1) arr.push(type); - } - - // Clear the view. - function resetView(cm) { - cm.display.viewFrom = cm.display.viewTo = cm.doc.first; - cm.display.view = []; - cm.display.viewOffset = 0; - } - - // Find the view element corresponding to a given line. Return null - // when the line isn't visible. - function findViewIndex(cm, n) { - if (n >= cm.display.viewTo) return null; - n -= cm.display.viewFrom; - if (n < 0) return null; - var view = cm.display.view; - for (var i = 0; i < view.length; i++) { - n -= view[i].size; - if (n < 0) return i; - } - } - - function viewCuttingPoint(cm, oldN, newN, dir) { - var index = findViewIndex(cm, oldN), diff, view = cm.display.view; - if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) - return {index: index, lineN: newN}; - for (var i = 0, n = cm.display.viewFrom; i < index; i++) - n += view[i].size; - if (n != oldN) { - if (dir > 0) { - if (index == view.length - 1) return null; - diff = (n + view[index].size) - oldN; - index++; - } else { - diff = n - oldN; - } - oldN += diff; newN += diff; - } - while (visualLineNo(cm.doc, newN) != newN) { - if (index == (dir < 0 ? 0 : view.length - 1)) return null; - newN += dir * view[index - (dir < 0 ? 1 : 0)].size; - index += dir; - } - return {index: index, lineN: newN}; - } - - // Force the view to cover a given range, adding empty view element - // or clipping off existing ones as needed. - function adjustView(cm, from, to) { - var display = cm.display, view = display.view; - if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { - display.view = buildViewArray(cm, from, to); - display.viewFrom = from; - } else { - if (display.viewFrom > from) - display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view); - else if (display.viewFrom < from) - display.view = display.view.slice(findViewIndex(cm, from)); - display.viewFrom = from; - if (display.viewTo < to) - display.view = display.view.concat(buildViewArray(cm, display.viewTo, to)); - else if (display.viewTo > to) - display.view = display.view.slice(0, findViewIndex(cm, to)); - } - display.viewTo = to; - } - - // Count the number of lines in the view whose DOM representation is - // out of date (or nonexistent). - function countDirtyView(cm) { - var view = cm.display.view, dirty = 0; - for (var i = 0; i < view.length; i++) { - var lineView = view[i]; - if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; - } - return dirty; - } - - // EVENT HANDLERS - - // Attach the necessary event handlers when initializing the editor - function registerEventHandlers(cm) { - var d = cm.display; - on(d.scroller, "mousedown", operation(cm, onMouseDown)); - // Older IE's will not fire a second mousedown for a double click - if (ie && ie_version < 11) - on(d.scroller, "dblclick", operation(cm, function(e) { - if (signalDOMEvent(cm, e)) return; - var pos = posFromMouse(cm, e); - if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; - e_preventDefault(e); - var word = cm.findWordAt(pos); - extendSelection(cm.doc, word.anchor, word.head); - })); - else - on(d.scroller, "dblclick", function(e) { signalDOMEvent(cm, e) || e_preventDefault(e); }); - // Some browsers fire contextmenu *after* opening the menu, at - // which point we can't mess with it anymore. Context menu is - // handled in onMouseDown for these browsers. - if (!captureRightClick) on(d.scroller, "contextmenu", function(e) {onContextMenu(cm, e);}); - - // Used to suppress mouse event handling when a touch happens - var touchFinished, prevTouch = {end: 0}; - function finishTouch() { - if (d.activeTouch) { - touchFinished = setTimeout(function() {d.activeTouch = null;}, 1000); - prevTouch = d.activeTouch; - prevTouch.end = +new Date; - } - }; - function isMouseLikeTouchEvent(e) { - if (e.touches.length != 1) return false; - var touch = e.touches[0]; - return touch.radiusX <= 1 && touch.radiusY <= 1; - } - function farAway(touch, other) { - if (other.left == null) return true; - var dx = other.left - touch.left, dy = other.top - touch.top; - return dx * dx + dy * dy > 20 * 20; - } - on(d.scroller, "touchstart", function(e) { - if (!isMouseLikeTouchEvent(e)) { - clearTimeout(touchFinished); - var now = +new Date; - d.activeTouch = {start: now, moved: false, - prev: now - prevTouch.end <= 300 ? prevTouch : null}; - if (e.touches.length == 1) { - d.activeTouch.left = e.touches[0].pageX; - d.activeTouch.top = e.touches[0].pageY; - } - } - }); - on(d.scroller, "touchmove", function() { - if (d.activeTouch) d.activeTouch.moved = true; - }); - on(d.scroller, "touchend", function(e) { - var touch = d.activeTouch; - if (touch && !eventInWidget(d, e) && touch.left != null && - !touch.moved && new Date - touch.start < 300) { - var pos = cm.coordsChar(d.activeTouch, "page"), range; - if (!touch.prev || farAway(touch, touch.prev)) // Single tap - range = new Range(pos, pos); - else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap - range = cm.findWordAt(pos); - else // Triple tap - range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0))); - cm.setSelection(range.anchor, range.head); - cm.focus(); - e_preventDefault(e); - } - finishTouch(); - }); - on(d.scroller, "touchcancel", finishTouch); - - // Sync scrolling between fake scrollbars and real scrollable - // area, ensure viewport is updated when scrolling. - on(d.scroller, "scroll", function() { - if (d.scroller.clientHeight) { - setScrollTop(cm, d.scroller.scrollTop); - setScrollLeft(cm, d.scroller.scrollLeft, true); - signal(cm, "scroll", cm); - } - }); + if (!this.checkedOverlay && measure.clientHeight > 0) { + if (sWidth == 0) this.overlayHack(); + this.checkedOverlay = true; + } - // Listen to wheel events in order to try and update the viewport on time. - on(d.scroller, "mousewheel", function(e){onScrollWheel(cm, e);}); - on(d.scroller, "DOMMouseScroll", function(e){onScrollWheel(cm, e);}); + return {right: needsV ? sWidth : 0, bottom: needsH ? sWidth : 0}; + }, + setScrollLeft: function (pos) { + if (this.horiz.scrollLeft != pos) this.horiz.scrollLeft = pos; + }, + setScrollTop: function (pos) { + if (this.vert.scrollTop != pos) this.vert.scrollTop = pos; + }, + overlayHack: function () { + var w = mac && !mac_geMountainLion ? "12px" : "18px"; + this.horiz.style.minHeight = this.vert.style.minWidth = w; + var self = this; + var barMouseDown = function (e) { + if (e_target(e) != self.vert && e_target(e) != self.horiz) {operation(self.cm, onMouseDown)(e);} + }; + on(this.vert, "mousedown", barMouseDown); + on(this.horiz, "mousedown", barMouseDown); + }, + clear: function () { + var parent = this.horiz.parentNode; + parent.removeChild(this.horiz); + parent.removeChild(this.vert); + } + }, NativeScrollbars.prototype); - // Prevent wrapper from ever scrolling - on(d.wrapper, "scroll", function() { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + function NullScrollbars () {} - d.dragFunctions = { - simple: function(e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, - start: function(e){onDragStart(cm, e);}, - drop: operation(cm, onDrop) - }; + NullScrollbars.prototype = copyObj({ + update: function () { return {bottom: 0, right: 0}; }, + setScrollLeft: function () {}, + setScrollTop: function () {}, + clear: function () {} + }, NullScrollbars.prototype); - var inp = d.input.getField(); - on(inp, "keyup", function(e) { onKeyUp.call(cm, e); }); - on(inp, "keydown", operation(cm, onKeyDown)); - on(inp, "keypress", operation(cm, onKeyPress)); - on(inp, "focus", bind(onFocus, cm)); - on(inp, "blur", bind(onBlur, cm)); - } - - function dragDropChanged(cm, value, old) { - var wasOn = old && old != CodeMirror.Init; - if (!value != !wasOn) { - var funcs = cm.display.dragFunctions; - var toggle = value ? on : off; - toggle(cm.display.scroller, "dragstart", funcs.start); - toggle(cm.display.scroller, "dragenter", funcs.simple); - toggle(cm.display.scroller, "dragover", funcs.simple); - toggle(cm.display.scroller, "drop", funcs.drop); - } - } - - // Called when the window resizes - function onResize(cm) { - var d = cm.display; - if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) - return; - // Might be a text scaling operation, clear size caches. - d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; - d.scrollbarsClipped = false; - cm.setSize(); - } - - // MOUSE EVENTS - - // Return true when the given mouse event happened in a widget - function eventInWidget(display, e) { - for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { - if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || - (n.parentNode == display.sizer && n != display.mover)) - return true; + CodeMirror.scrollbarModel = {native: NativeScrollbars, null: NullScrollbars}; + + function initScrollbars (cm) { + if (cm.display.scrollbars) { + cm.display.scrollbars.clear(); + if (cm.display.scrollbars.addClass) {rmClass(cm.display.wrapper, cm.display.scrollbars.addClass);} + } + + cm.display.scrollbars = new CodeMirror.scrollbarModel[cm.options.scrollbarStyle](function (node) { + cm.display.wrapper.insertBefore(node, cm.display.scrollbarFiller); + // Prevent clicks in the scrollbars from killing focus + on(node, "mousedown", function () { + if (cm.state.focused) setTimeout(function () { cm.display.input.focus(); }, 0); + }); + node.setAttribute("cm-not-content", "true"); + }, function (pos, axis) { + if (axis == "horizontal") setScrollLeft(cm, pos); + else setScrollTop(cm, pos); + }, cm); + if (cm.display.scrollbars.addClass) {addClass(cm.display.wrapper, cm.display.scrollbars.addClass);} + } + + function updateScrollbars (cm, measure) { + if (!measure) measure = measureForScrollbars(cm); + var startWidth = cm.display.barWidth, startHeight = cm.display.barHeight; + updateScrollbarsInner(cm, measure); + for (var i = 0; i < 4 && startWidth != cm.display.barWidth || startHeight != cm.display.barHeight; i++) { + if (startWidth != cm.display.barWidth && cm.options.lineWrapping) {updateHeightsInViewport(cm);} + updateScrollbarsInner(cm, measureForScrollbars(cm)); + startWidth = cm.display.barWidth; startHeight = cm.display.barHeight; + } } - } - - // Given a mouse event, find the corresponding position. If liberal - // is false, it checks whether a gutter or scrollbar was clicked, - // and returns null if it was. forRect is used by rectangular - // selections, and tries to estimate a character position even for - // coordinates beyond the right of the text. - function posFromMouse(cm, e, liberal, forRect) { - var display = cm.display; - if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; - - var x, y, space = display.lineSpace.getBoundingClientRect(); - // Fails unpredictably on IE[67] when mouse is dragged around quickly. - try { x = e.clientX - space.left; y = e.clientY - space.top; } - catch (e) { return null; } - var coords = coordsChar(cm, x, y), line; - if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { - var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; - coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); - } - return coords; - } - - // A mouse down can be a single click, double click, triple click, - // start of selection drag, start of text drag, new cursor - // (ctrl-click), rectangle drag (alt-drag), or xwin - // middle-click-paste. Or it might be a click on something we should - // not interfere with, such as a scrollbar or widget. - function onMouseDown(e) { - var cm = this, display = cm.display; - if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return; - display.shift = e.shiftKey; - - if (eventInWidget(display, e)) { - if (!webkit) { - // Briefly turn off draggability, to allow widgets to do - // normal dragging things. - display.scroller.draggable = false; - setTimeout(function(){display.scroller.draggable = true;}, 100); - } - return; - } - if (clickInGutter(cm, e)) return; - var start = posFromMouse(cm, e); - window.focus(); - - switch (e_button(e)) { - case 1: - if (start) - leftButtonDown(cm, e, start); - else if (e_target(e) == display.scroller) - e_preventDefault(e); - break; - case 2: - if (webkit) cm.state.lastMiddleDown = +new Date; - if (start) extendSelection(cm.doc, start); - setTimeout(function() {display.input.focus();}, 20); - e_preventDefault(e); - break; - case 3: - if (captureRightClick) onContextMenu(cm, e); - else delayBlurEvent(cm); - break; - } - } - - var lastClick, lastDoubleClick; - function leftButtonDown(cm, e, start) { - if (ie) setTimeout(bind(ensureFocus, cm), 0); - else cm.curOp.focus = activeElt(); - - var now = +new Date, type; - if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { - type = "triple"; - } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { - type = "double"; - lastDoubleClick = {time: now, pos: start}; - } else { - type = "single"; - lastClick = {time: now, pos: start}; + + // Re-synchronize the fake scrollbars with the actual size of the + // content. + function updateScrollbarsInner (cm, measure) { + var d = cm.display; + var sizes = d.scrollbars.update(measure); + + d.sizer.style.paddingRight = (d.barWidth = sizes.right) + "px"; + d.sizer.style.paddingBottom = (d.barHeight = sizes.bottom) + "px"; + + if (sizes.right && sizes.bottom) { + d.scrollbarFiller.style.display = "block"; + d.scrollbarFiller.style.height = sizes.bottom + "px"; + d.scrollbarFiller.style.width = sizes.right + "px"; + } else d.scrollbarFiller.style.display = ""; + if (sizes.bottom && cm.options.coverGutterNextToScrollbar && cm.options.fixedGutter) { + d.gutterFiller.style.display = "block"; + d.gutterFiller.style.height = sizes.bottom + "px"; + d.gutterFiller.style.width = measure.gutterWidth + "px"; + } else d.gutterFiller.style.display = ""; + } + + // Compute the lines that are visible in a given viewport (defaults + // the the current scroll position). viewport may contain top, + // height, and ensure (see op.scrollToPos) properties. + function visibleLines (display, doc, viewport) { + var top = viewport && viewport.top != null ? Math.max(0, viewport.top) : display.scroller.scrollTop; + top = Math.floor(top - paddingTop(display)); + var bottom = viewport && viewport.bottom != null ? viewport.bottom : top + display.wrapper.clientHeight; + + var from = lineAtHeight(doc, top), to = lineAtHeight(doc, bottom); + // Ensure is a {from: {line, ch}, to: {line, ch}} object, and + // forces those lines into the viewport (if possible). + if (viewport && viewport.ensure) { + var ensureFrom = viewport.ensure.from.line, ensureTo = viewport.ensure.to.line; + if (ensureFrom < from) { + from = ensureFrom; + to = lineAtHeight(doc, heightAtLine(getLine(doc, ensureFrom)) + display.wrapper.clientHeight); + } else if (Math.min(ensureTo, doc.lastLine()) >= to) { + from = lineAtHeight(doc, heightAtLine(getLine(doc, ensureTo)) - display.wrapper.clientHeight); + to = ensureTo; + } + } + return {from: from, to: Math.max(to, from + 1)}; } - var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; - if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && - type == "single" && (contained = sel.contains(start)) > -1 && - (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && - (cmp(contained.to(), start) > 0 || start.xRel < 0)) - leftButtonStartDrag(cm, e, start, modifier); - else - leftButtonSelect(cm, e, start, type, modifier); - } - - // Start a text drag. When it ends, see if any dragging actually - // happen, and treat as a click if it didn't. - function leftButtonStartDrag(cm, e, start, modifier) { - var display = cm.display, startTime = +new Date; - var dragEnd = operation(cm, function(e2) { - if (webkit) display.scroller.draggable = false; - cm.state.draggingText = false; - off(document, "mouseup", dragEnd); - off(display.scroller, "drop", dragEnd); - if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { - e_preventDefault(e2); - if (!modifier && +new Date - 200 < startTime) - extendSelection(cm.doc, start); - // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) - if (webkit || ie && ie_version == 9) - setTimeout(function() {document.body.focus(); display.input.focus();}, 20); - else - display.input.focus(); - } - }); - // Let the drag handler handle this. - if (webkit) display.scroller.draggable = true; - cm.state.draggingText = dragEnd; - // IE's approach to draggable - if (display.scroller.dragDrop) display.scroller.dragDrop(); - on(document, "mouseup", dragEnd); - on(display.scroller, "drop", dragEnd); - } - - // Normal selection, as opposed to text dragging. - function leftButtonSelect(cm, e, start, type, addNew) { - var display = cm.display, doc = cm.doc; - e_preventDefault(e); - - var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; - if (addNew && !e.shiftKey) { - ourIndex = doc.sel.contains(start); - if (ourIndex > -1) - ourRange = ranges[ourIndex]; - else - ourRange = new Range(start, start); - } else { - ourRange = doc.sel.primary(); - ourIndex = doc.sel.primIndex; - } - - if (e.altKey) { - type = "rect"; - if (!addNew) ourRange = new Range(start, start); - start = posFromMouse(cm, e, true, true); - ourIndex = -1; - } else if (type == "double") { - var word = cm.findWordAt(start); - if (cm.display.shift || doc.extend) - ourRange = extendRange(doc, ourRange, word.anchor, word.head); - else - ourRange = word; - } else if (type == "triple") { - var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); - if (cm.display.shift || doc.extend) - ourRange = extendRange(doc, ourRange, line.anchor, line.head); - else - ourRange = line; - } else { - ourRange = extendRange(doc, ourRange, start); - } - - if (!addNew) { - ourIndex = 0; - setSelection(doc, new Selection([ourRange], 0), sel_mouse); - startSel = doc.sel; - } else if (ourIndex == -1) { - ourIndex = ranges.length; - setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), - {scroll: false, origin: "*mouse"}); - } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { - setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0)); - startSel = doc.sel; - } else { - replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); - } - - var lastPos = start; - function extendTo(pos) { - if (cmp(lastPos, pos) == 0) return; - lastPos = pos; - - if (type == "rect") { - var ranges = [], tabSize = cm.options.tabSize; - var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); - var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); - var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); - for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); - line <= end; line++) { - var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); - if (left == right) - ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos))); - else if (text.length > leftPos) - ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize)))); - } - if (!ranges.length) ranges.push(new Range(start, start)); - setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), - {origin: "*mouse", scroll: false}); - cm.scrollIntoView(pos); - } else { - var oldRange = ourRange; - var anchor = oldRange.anchor, head = pos; - if (type != "single") { - if (type == "double") - var range = cm.findWordAt(pos); - else - var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0))); - if (cmp(range.anchor, anchor) > 0) { - head = range.head; - anchor = minPos(oldRange.from(), range.anchor); - } else { - head = range.anchor; - anchor = maxPos(oldRange.to(), range.head); - } - } - var ranges = startSel.ranges.slice(0); - ranges[ourIndex] = new Range(clipPos(doc, anchor), head); - setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); - } - } - - var editorSize = display.wrapper.getBoundingClientRect(); - // Used to ensure timeout re-tries don't fire when another extend - // happened in the meantime (clearTimeout isn't reliable -- at - // least on Chrome, the timeouts still happen even when cleared, - // if the clear happens after their scheduled firing time). - var counter = 0; - - function extend(e) { - var curCount = ++counter; - var cur = posFromMouse(cm, e, true, type == "rect"); - if (!cur) return; - if (cmp(cur, lastPos) != 0) { - cm.curOp.focus = activeElt(); - extendTo(cur); - var visible = visibleLines(display, doc); - if (cur.line >= visible.to || cur.line < visible.from) - setTimeout(operation(cm, function(){if (counter == curCount) extend(e);}), 150); - } else { - var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; - if (outside) setTimeout(operation(cm, function() { - if (counter != curCount) return; - display.scroller.scrollTop += outside; - extend(e); - }), 50); - } - } - - function done(e) { - counter = Infinity; - e_preventDefault(e); - display.input.focus(); - off(document, "mousemove", move); - off(document, "mouseup", up); - doc.history.lastSelOrigin = null; - } - - var move = operation(cm, function(e) { - if (!e_button(e)) done(e); - else extend(e); - }); - var up = operation(cm, done); - on(document, "mousemove", move); - on(document, "mouseup", up); - } - - // Determines whether an event happened in the gutter, and fires the - // handlers for the corresponding event. - function gutterEvent(cm, e, type, prevent, signalfn) { - try { var mX = e.clientX, mY = e.clientY; } - catch(e) { return false; } - if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; - if (prevent) e_preventDefault(e); - - var display = cm.display; - var lineBox = display.lineDiv.getBoundingClientRect(); - - if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); - mY -= lineBox.top - display.viewOffset; - - for (var i = 0; i < cm.options.gutters.length; ++i) { - var g = display.gutters.childNodes[i]; - if (g && g.getBoundingClientRect().right >= mX) { - var line = lineAtHeight(cm.doc, mY); - var gutter = cm.options.gutters[i]; - signalfn(cm, type, cm, line, gutter, e); - return e_defaultPrevented(e); - } - } - } - - function clickInGutter(cm, e) { - return gutterEvent(cm, e, "gutterClick", true, signalLater); - } - - // Kludge to work around strange IE behavior where it'll sometimes - // re-fire a series of drag-related events right after the drop (#1551) - var lastDrop = 0; - - function onDrop(e) { - var cm = this; - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) - return; - e_preventDefault(e); - if (ie) lastDrop = +new Date; - var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; - if (!pos || isReadOnly(cm)) return; - // Might be a file drop, in which case we simply extract the text - // and insert it. - if (files && files.length && window.FileReader && window.File) { - var n = files.length, text = Array(n), read = 0; - var loadFile = function(file, i) { - var reader = new FileReader; - reader.onload = operation(cm, function() { - text[i] = reader.result; - if (++read == n) { - pos = clipPos(cm.doc, pos); - var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}; - makeChange(cm.doc, change); - setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); - } - }); - reader.readAsText(file); - }; - for (var i = 0; i < n; ++i) loadFile(files[i], i); - } else { // Normal drop - // Don't do a replace if the drop happened inside of the selected text. - if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { - cm.state.draggingText(e); - // Ensure the editor is re-focused - setTimeout(function() {cm.display.input.focus();}, 20); - return; - } - try { - var text = e.dataTransfer.getData("Text"); - if (text) { - if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) - var selected = cm.listSelections(); - setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); - if (selected) for (var i = 0; i < selected.length; ++i) - replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag"); - cm.replaceSelection(text, "around", "paste"); - cm.display.input.focus(); - } - } - catch(e){} - } - } - - function onDragStart(cm, e) { - if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } - if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; - - e.dataTransfer.setData("Text", cm.getSelection()); - - // Use dummy image instead of default browsers image. - // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. - if (e.dataTransfer.setDragImage && !safari) { - var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); - img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; - if (presto) { - img.width = img.height = 1; - cm.display.wrapper.appendChild(img); - // Force a relayout, or Opera won't use our image for some obscure reason - img._top = img.offsetTop; - } - e.dataTransfer.setDragImage(img, 0, 0); - if (presto) img.parentNode.removeChild(img); - } - } - - // SCROLL EVENTS - - // Sync the scrollable area and scrollbars, ensure the viewport - // covers the visible area. - function setScrollTop(cm, val) { - if (Math.abs(cm.doc.scrollTop - val) < 2) return; - cm.doc.scrollTop = val; - if (!gecko) updateDisplaySimple(cm, {top: val}); - if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; - cm.display.scrollbars.setScrollTop(val); - if (gecko) updateDisplaySimple(cm); - startWorker(cm, 100); - } - // Sync scroller and scrollbar, ensure the gutter elements are - // aligned. - function setScrollLeft(cm, val, isScroller) { - if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; - val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); - cm.doc.scrollLeft = val; - alignHorizontally(cm); - if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; - cm.display.scrollbars.setScrollLeft(val); - } - - // Since the delta values reported on mouse wheel events are - // unstandardized between browsers and even browser versions, and - // generally horribly unpredictable, this code starts by measuring - // the scroll effect that the first few mouse wheel events have, - // and, from that, detects the way it can convert deltas to pixel - // offsets afterwards. - // - // The reason we want to know the amount a wheel event will scroll - // is that it gives us a chance to update the display before the - // actual scrolling happens, reducing flickering. - - var wheelSamples = 0, wheelPixelsPerUnit = null; - // Fill in a browser-detected starting value on browsers where we - // know one. These don't have to be accurate -- the result of them - // being wrong would just be a slight flicker on the first wheel - // scroll (if it is large enough). - if (ie) wheelPixelsPerUnit = -.53; - else if (gecko) wheelPixelsPerUnit = 15; - else if (chrome) wheelPixelsPerUnit = -.7; - else if (safari) wheelPixelsPerUnit = -1/3; - - var wheelEventDelta = function(e) { - var dx = e.wheelDeltaX, dy = e.wheelDeltaY; - if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; - if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; - else if (dy == null) dy = e.wheelDelta; - return {x: dx, y: dy}; - }; - CodeMirror.wheelEventPixels = function(e) { - var delta = wheelEventDelta(e); - delta.x *= wheelPixelsPerUnit; - delta.y *= wheelPixelsPerUnit; - return delta; - }; - - function onScrollWheel(cm, e) { - var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; - - var display = cm.display, scroll = display.scroller; - // Quit if there's nothing to scroll here - if (!(dx && scroll.scrollWidth > scroll.clientWidth || - dy && scroll.scrollHeight > scroll.clientHeight)) return; + // LINE NUMBERS - // Webkit browsers on OS X abort momentum scrolls when the target - // of the scroll event is removed from the scrollable element. - // This hack (see related code in patchDisplay) makes sure the - // element is kept around. - if (dy && mac && webkit) { - outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + // Re-align line numbers and gutter marks to compensate for + // horizontal scrolling. + function alignHorizontally (cm) { + var display = cm.display, view = display.view; + if (!display.alignWidgets && (!display.gutters.firstChild || !cm.options.fixedGutter)) return; + var comp = compensateForHScroll(display) - display.scroller.scrollLeft + cm.doc.scrollLeft; + var gutterW = display.gutters.offsetWidth, left = comp + "px"; for (var i = 0; i < view.length; i++) { - if (view[i].node == cur) { - cm.display.currentWheelTarget = cur; - break outer; - } - } - } - } - - // On some browsers, horizontal scrolling will cause redraws to - // happen before the gutter has been realigned, causing it to - // wriggle around in a most unseemly way. When we have an - // estimated pixels/delta value, we just handle horizontal - // scrolling entirely here. It'll be slightly off from native, but - // better than glitching out. - if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { - if (dy) - setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight))); - setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); - e_preventDefault(e); - display.wheelStartX = null; // Abort measurement, if in progress - return; - } - - // 'Project' the visible viewport to cover the area that is being - // scrolled into view (if we know enough to estimate it). - if (dy && wheelPixelsPerUnit != null) { - var pixels = dy * wheelPixelsPerUnit; - var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; - if (pixels < 0) top = Math.max(0, top + pixels - 50); - else bot = Math.min(cm.doc.height, bot + pixels + 50); - updateDisplaySimple(cm, {top: top, bottom: bot}); - } - - if (wheelSamples < 20) { - if (display.wheelStartX == null) { - display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; - display.wheelDX = dx; display.wheelDY = dy; - setTimeout(function() { - if (display.wheelStartX == null) return; - var movedX = scroll.scrollLeft - display.wheelStartX; - var movedY = scroll.scrollTop - display.wheelStartY; - var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || - (movedX && display.wheelDX && movedX / display.wheelDX); - display.wheelStartX = display.wheelStartY = null; - if (!sample) return; - wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); - ++wheelSamples; - }, 200); - } else { - display.wheelDX += dx; display.wheelDY += dy; - } - } - } - - // KEY EVENTS - - // Run a handler that was bound to a key. - function doHandleBinding(cm, bound, dropShift) { - if (typeof bound == "string") { - bound = commands[bound]; - if (!bound) return false; - } - // Ensure previous input has been read, so that the handler sees a - // consistent view of the document - cm.display.input.ensurePolled(); - var prevShift = cm.display.shift, done = false; - try { - if (isReadOnly(cm)) cm.state.suppressEdits = true; - if (dropShift) cm.display.shift = false; - done = bound(cm) != Pass; - } finally { - cm.display.shift = prevShift; - cm.state.suppressEdits = false; - } - return done; - } - - function lookupKeyForEditor(cm, name, handle) { - for (var i = 0; i < cm.state.keyMaps.length; i++) { - var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); - if (result) return result; - } - return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) - || lookupKey(name, cm.options.keyMap, handle, cm); - } - - var stopSeq = new Delayed; - function dispatchKey(cm, name, e, handle) { - var seq = cm.state.keySeq; - if (seq) { - if (isModifierKey(name)) return "handled"; - stopSeq.set(50, function() { - if (cm.state.keySeq == seq) { - cm.state.keySeq = null; - cm.display.input.reset(); - } - }); - name = seq + " " + name; - } - var result = lookupKeyForEditor(cm, name, handle); - - if (result == "multi") - cm.state.keySeq = name; - if (result == "handled") - signalLater(cm, "keyHandled", cm, name, e); - - if (result == "handled" || result == "multi") { - e_preventDefault(e); - restartBlink(cm); - } - - if (seq && !result && /\'$/.test(name)) { - e_preventDefault(e); - return true; - } - return !!result; - } - - // Handle a key from the keydown event. - function handleKeyBinding(cm, e) { - var name = keyName(e, true); - if (!name) return false; - - if (e.shiftKey && !cm.state.keySeq) { - // First try to resolve full name (including 'Shift-'). Failing - // that, see if there is a cursor-motion command (starting with - // 'go') bound to the keyname without 'Shift-'. - return dispatchKey(cm, "Shift-" + name, e, function(b) {return doHandleBinding(cm, b, true);}) - || dispatchKey(cm, name, e, function(b) { - if (typeof b == "string" ? /^go[A-Z]/.test(b) : b.motion) - return doHandleBinding(cm, b); - }); - } else { - return dispatchKey(cm, name, e, function(b) { return doHandleBinding(cm, b); }); - } - } - - // Handle a key from the keypress event - function handleCharBinding(cm, e, ch) { - return dispatchKey(cm, "'" + ch + "'", e, - function(b) { return doHandleBinding(cm, b, true); }); - } - - var lastStoppedKey = null; - function onKeyDown(e) { - var cm = this; - cm.curOp.focus = activeElt(); - if (signalDOMEvent(cm, e)) return; - // IE does strange things with escape. - if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; - var code = e.keyCode; - cm.display.shift = code == 16 || e.shiftKey; - var handled = handleKeyBinding(cm, e); - if (presto) { - lastStoppedKey = handled ? code : null; - // Opera has no cut event... we try to at least catch the key combo - if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) - cm.replaceSelection("", null, "cut"); - } - - // Turn mouse into crosshair when Alt is held on Mac. - if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) - showCrossHair(cm); - } - - function showCrossHair(cm) { - var lineDiv = cm.display.lineDiv; - addClass(lineDiv, "CodeMirror-crosshair"); - - function up(e) { - if (e.keyCode == 18 || !e.altKey) { - rmClass(lineDiv, "CodeMirror-crosshair"); - off(document, "keyup", up); - off(document, "mouseover", up); - } - } - on(document, "keyup", up); - on(document, "mouseover", up); - } - - function onKeyUp(e) { - if (e.keyCode == 16) this.doc.sel.shift = false; - signalDOMEvent(this, e); - } - - function onKeyPress(e) { - var cm = this; - if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; - var keyCode = e.keyCode, charCode = e.charCode; - if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} - if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; - var ch = String.fromCharCode(charCode == null ? keyCode : charCode); - if (handleCharBinding(cm, e, ch)) return; - cm.display.input.onKeyPress(e); - } - - // FOCUS/BLUR EVENTS - - function delayBlurEvent(cm) { - cm.state.delayingBlurEvent = true; - setTimeout(function() { - if (cm.state.delayingBlurEvent) { - cm.state.delayingBlurEvent = false; - onBlur(cm); - } - }, 100); - } - - function onFocus(cm) { - if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; - - if (cm.options.readOnly == "nocursor") return; - if (!cm.state.focused) { - signal(cm, "focus", cm); - cm.state.focused = true; - addClass(cm.display.wrapper, "CodeMirror-focused"); - // This test prevents this from firing when a context - // menu is closed (since the input reset would kill the - // select-all detection hack) - if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { - cm.display.input.reset(); - if (webkit) setTimeout(function() { cm.display.input.reset(true); }, 20); // Issue #1730 - } - cm.display.input.receivedFocus(); - } - restartBlink(cm); - } - function onBlur(cm) { - if (cm.state.delayingBlurEvent) return; - - if (cm.state.focused) { - signal(cm, "blur", cm); - cm.state.focused = false; - rmClass(cm.display.wrapper, "CodeMirror-focused"); - } - clearInterval(cm.display.blinker); - setTimeout(function() {if (!cm.state.focused) cm.display.shift = false;}, 150); - } - - // CONTEXT MENU HANDLING - - // To make the context menu work, we need to briefly unhide the - // textarea (making it as unobtrusive as possible) to let the - // right-click take effect on it. - function onContextMenu(cm, e) { - if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; - cm.display.input.onContextMenu(e); - } - - function contextMenuInGutter(cm, e) { - if (!hasHandler(cm, "gutterContextMenu")) return false; - return gutterEvent(cm, e, "gutterContextMenu", false, signal); - } - - // UPDATING - - // Compute the position of the end of a change (its 'to' property - // refers to the pre-change end). - var changeEnd = CodeMirror.changeEnd = function(change) { - if (!change.text) return change.to; - return Pos(change.from.line + change.text.length - 1, - lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); - }; - - // Adjust a position to refer to the post-change position of the - // same text, or the end of the change if the change covers it. - function adjustForChange(pos, change) { - if (cmp(pos, change.from) < 0) return pos; - if (cmp(pos, change.to) <= 0) return changeEnd(change); - - var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; - if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; - return Pos(line, ch); - } - - function computeSelAfterChange(doc, change) { - var out = []; - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - out.push(new Range(adjustForChange(range.anchor, change), - adjustForChange(range.head, change))); - } - return normalizeSelection(out, doc.sel.primIndex); - } - - function offsetPos(pos, old, nw) { - if (pos.line == old.line) - return Pos(nw.line, pos.ch - old.ch + nw.ch); - else - return Pos(nw.line + (pos.line - old.line), pos.ch); - } - - // Used by replaceSelections to allow moving the selection to the - // start or around the replaced test. Hint may be "start" or "around". - function computeReplacedSel(doc, changes, hint) { - var out = []; - var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; - for (var i = 0; i < changes.length; i++) { - var change = changes[i]; - var from = offsetPos(change.from, oldPrev, newPrev); - var to = offsetPos(changeEnd(change), oldPrev, newPrev); - oldPrev = change.to; - newPrev = to; - if (hint == "around") { - var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; - out[i] = new Range(inv ? to : from, inv ? from : to); - } else { - out[i] = new Range(from, from); - } - } - return new Selection(out, doc.sel.primIndex); - } - - // Allow "beforeChange" event handlers to influence a change - function filterChange(doc, change, update) { - var obj = { - canceled: false, - from: change.from, - to: change.to, - text: change.text, - origin: change.origin, - cancel: function() { this.canceled = true; } - }; - if (update) obj.update = function(from, to, text, origin) { - if (from) this.from = clipPos(doc, from); - if (to) this.to = clipPos(doc, to); - if (text) this.text = text; - if (origin !== undefined) this.origin = origin; - }; - signal(doc, "beforeChange", doc, obj); - if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); - - if (obj.canceled) return null; - return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; - } - - // Apply a change to a document, and add it to the document's - // history, and propagating it to all linked documents. - function makeChange(doc, change, ignoreReadOnly) { - if (doc.cm) { - if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); - if (doc.cm.state.suppressEdits) return; + if (!view[i].hidden) { + if (cm.options.fixedGutter && view[i].gutter) {view[i].gutter.style.left = left;} + var align = view[i].alignable; + if (align) { + for (var j = 0; j < align.length; j++) {align[j].style.left = left;} + } + } + } + if (cm.options.fixedGutter) {display.gutters.style.left = (comp + gutterW) + "px";} + } + + // Used to ensure that the line number gutter is still the right + // size for the current document size. Returns true when an update + // is needed. + function maybeUpdateLineNumberWidth (cm) { + if (!cm.options.lineNumbers) return false; + var doc = cm.doc, last = lineNumberFor(cm.options, doc.first + doc.size - 1), display = cm.display; + if (last.length != display.lineNumChars) { + var test = display.measure.appendChild(elt("div", [elt("div", last)], + "CodeMirror-linenumber CodeMirror-gutter-elt")); + var innerW = test.firstChild.offsetWidth, padding = test.offsetWidth - innerW; + display.lineGutter.style.width = ""; + display.lineNumInnerWidth = Math.max(innerW, display.lineGutter.offsetWidth - padding) + 1; + display.lineNumWidth = display.lineNumInnerWidth + padding; + display.lineNumChars = display.lineNumInnerWidth ? last.length : -1; + display.lineGutter.style.width = display.lineNumWidth + "px"; + updateGutterSpace(cm); + return true; + } + return false; } - if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { - change = filterChange(doc, change, true); - if (!change) return; + function lineNumberFor (options, i) { + return String(options.lineNumberFormatter(i + options.firstLineNumber)); } - // Possibly split or suppress the update based on the presence - // of read-only spans in its range. - var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); - if (split) { - for (var i = split.length - 1; i >= 0; --i) - makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text}); - } else { - makeChangeInner(doc, change); + // Computes display.scroller.scrollLeft + display.gutters.offsetWidth, + // but using getBoundingClientRect to get a sub-pixel-accurate + // result. + function compensateForHScroll (display) { + return display.scroller.getBoundingClientRect().left - display.sizer.getBoundingClientRect().left; } - } - function makeChangeInner(doc, change) { - if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; - var selAfter = computeSelAfterChange(doc, change); - addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + // DISPLAY DRAWING - makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); - var rebased = []; + function DisplayUpdate (cm, viewport, force) { + var display = cm.display; - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); - }); - } - - // Revert a change stored in a document's history. - function makeChangeFromHistory(doc, type, allowSelectionOnly) { - if (doc.cm && doc.cm.state.suppressEdits) return; - - var hist = doc.history, event, selAfter = doc.sel; - var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; - - // Verify that there is a useable event (so that ctrl-z won't - // needlessly clear selection events) - for (var i = 0; i < source.length; i++) { - event = source[i]; - if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) - break; - } - if (i == source.length) return; - hist.lastOrigin = hist.lastSelOrigin = null; - - for (;;) { - event = source.pop(); - if (event.ranges) { - pushSelectionToHistory(event, dest); - if (allowSelectionOnly && !event.equals(doc.sel)) { - setSelection(doc, event, {clearRedo: false}); - return; - } - selAfter = event; - } - else break; - } - - // Build up a reverse change object to add to the opposite history - // stack (redo when undoing, and vice versa). - var antiChanges = []; - pushSelectionToHistory(selAfter, dest); - dest.push({changes: antiChanges, generation: hist.generation}); - hist.generation = event.generation || ++hist.maxGeneration; - - var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); - - for (var i = event.changes.length - 1; i >= 0; --i) { - var change = event.changes[i]; - change.origin = type; - if (filter && !filterChange(doc, change, false)) { - source.length = 0; - return; - } - - antiChanges.push(historyChangeFromChange(doc, change)); - - var after = i ? computeSelAfterChange(doc, change) : lst(source); - makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); - if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); - var rebased = []; - - // Propagate to the linked documents - linkedDocs(doc, function(doc, sharedHist) { - if (!sharedHist && indexOf(rebased, doc.history) == -1) { - rebaseHist(doc.history, change); - rebased.push(doc.history); - } - makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); - }); - } - } - - // Sub-views need their line numbers shifted when text is added - // above or below them in the parent document. - function shiftDoc(doc, distance) { - if (distance == 0) return; - doc.first += distance; - doc.sel = new Selection(map(doc.sel.ranges, function(range) { - return new Range(Pos(range.anchor.line + distance, range.anchor.ch), - Pos(range.head.line + distance, range.head.ch)); - }), doc.sel.primIndex); - if (doc.cm) { - regChange(doc.cm, doc.first, doc.first - distance, distance); - for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) - regLineChange(doc.cm, l, "gutter"); - } - } - - // More lower-level change function, handling only a single document - // (not linked ones). - function makeChangeSingleDoc(doc, change, selAfter, spans) { - if (doc.cm && !doc.cm.curOp) - return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans); - - if (change.to.line < doc.first) { - shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); - return; - } - if (change.from.line > doc.lastLine()) return; - - // Clip the change to the size of this doc - if (change.from.line < doc.first) { - var shift = change.text.length - 1 - (doc.first - change.from.line); - shiftDoc(doc, shift); - change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), - text: [lst(change.text)], origin: change.origin}; + this.viewport = viewport; + // Store some values that we'll need later (but don't want to force a relayout for) + this.visible = visibleLines(display, cm.doc, viewport); + this.editorIsHidden = !display.wrapper.offsetWidth; + this.wrapperHeight = display.wrapper.clientHeight; + this.wrapperWidth = display.wrapper.clientWidth; + this.oldDisplayWidth = displayWidth(cm); + this.force = force; + this.dims = getDimensions(cm); + this.events = []; } - var last = doc.lastLine(); - if (change.to.line > last) { - change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), - text: [change.text[0]], origin: change.origin}; + + DisplayUpdate.prototype.signal = function (emitter, type) { + if (hasHandler(emitter, type)) {this.events.push(arguments);} + }; + DisplayUpdate.prototype.finish = function () { + for (var i = 0; i < this.events.length; i++) {signal.apply(null, this.events[i]);} + }; + + function maybeClipScrollbars (cm) { + var display = cm.display; + if (!display.scrollbarsClipped && display.scroller.offsetWidth) { + display.nativeBarWidth = display.scroller.offsetWidth - display.scroller.clientWidth; + display.heightForcer.style.height = scrollGap(cm) + "px"; + display.sizer.style.marginBottom = -display.nativeBarWidth + "px"; + display.sizer.style.borderRightWidth = scrollGap(cm) + "px"; + display.scrollbarsClipped = true; + } } - change.removed = getBetween(doc, change.from, change.to); - - if (!selAfter) selAfter = computeSelAfterChange(doc, change); - if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); - else updateDoc(doc, change, spans); - setSelectionNoUndo(doc, selAfter, sel_dontScroll); - } - - // Handle the interaction of a change to a document with the editor - // that this document is part of. - function makeChangeSingleDocInEditor(cm, change, spans) { - var doc = cm.doc, display = cm.display, from = change.from, to = change.to; - - var recomputeMaxLength = false, checkWidthStart = from.line; - if (!cm.options.lineWrapping) { - checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); - doc.iter(checkWidthStart, to.line + 1, function(line) { - if (line == display.maxLine) { - recomputeMaxLength = true; - return true; - } - }); - } - - if (doc.sel.contains(change.from, change.to) > -1) - signalCursorActivity(cm); - - updateDoc(doc, change, spans, estimateHeight(cm)); - - if (!cm.options.lineWrapping) { - doc.iter(checkWidthStart, from.line + change.text.length, function(line) { - var len = lineLength(line); - if (len > display.maxLineLength) { - display.maxLine = line; - display.maxLineLength = len; - display.maxLineChanged = true; - recomputeMaxLength = false; - } - }); - if (recomputeMaxLength) cm.curOp.updateMaxLine = true; - } - - // Adjust frontier, schedule worker - doc.frontier = Math.min(doc.frontier, from.line); - startWorker(cm, 400); - - var lendiff = change.text.length - (to.line - from.line) - 1; - // Remember that these lines changed, for updating the display - if (change.full) - regChange(cm); - else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) - regLineChange(cm, from.line, "text"); - else - regChange(cm, from.line, to.line + 1, lendiff); - - var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); - if (changeHandler || changesHandler) { - var obj = { - from: from, to: to, - text: change.text, - removed: change.removed, - origin: change.origin - }; - if (changeHandler) signalLater(cm, "change", cm, obj); - if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); - } - cm.display.selForContextMenu = null; - } - - function replaceRange(doc, code, from, to, origin) { - if (!to) to = from; - if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } - if (typeof code == "string") code = splitLines(code); - makeChange(doc, {from: from, to: to, text: code, origin: origin}); - } - - // SCROLLING THINGS INTO VIEW - - // If an editor sits on the top or bottom of the window, partially - // scrolled out of view, this ensures that the cursor is visible. - function maybeScrollWindow(cm, coords) { - if (signalDOMEvent(cm, "scrollCursorIntoView")) return; - - var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; - if (coords.top + box.top < 0) doScroll = true; - else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; - if (doScroll != null && !phantom) { - var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + - (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + - (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + - coords.left + "px; width: 2px;"); - cm.display.lineSpace.appendChild(scrollNode); - scrollNode.scrollIntoView(doScroll); - cm.display.lineSpace.removeChild(scrollNode); - } - } - - // Scroll a given position into view (immediately), verifying that - // it actually became visible (as line heights are accurately - // measured, the position of something may 'drift' during drawing). - function scrollPosIntoView(cm, pos, end, margin) { - if (margin == null) margin = 0; - for (var limit = 0; limit < 5; limit++) { - var changed = false, coords = cursorCoords(cm, pos); - var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); - var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), - Math.min(coords.top, endCoords.top) - margin, - Math.max(coords.left, endCoords.left), - Math.max(coords.bottom, endCoords.bottom) + margin); - var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; - if (scrollPos.scrollTop != null) { - setScrollTop(cm, scrollPos.scrollTop); - if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; - } - if (scrollPos.scrollLeft != null) { - setScrollLeft(cm, scrollPos.scrollLeft); - if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; - } - if (!changed) break; - } - return coords; - } - - // Scroll a given set of coordinates into view (immediately). - function scrollIntoView(cm, x1, y1, x2, y2) { - var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); - if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); - if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); - } - - // Calculate a new scroll position needed to scroll the given - // rectangle into view. Returns an object with scrollTop and - // scrollLeft properties. When these are undefined, the - // vertical/horizontal position does not need to be adjusted. - function calculateScrollPos(cm, x1, y1, x2, y2) { - var display = cm.display, snapMargin = textHeight(cm.display); - if (y1 < 0) y1 = 0; - var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; - var screen = displayHeight(cm), result = {}; - if (y2 - y1 > screen) y2 = y1 + screen; - var docBottom = cm.doc.height + paddingVert(display); - var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; - if (y1 < screentop) { - result.scrollTop = atTop ? 0 : y1; - } else if (y2 > screentop + screen) { - var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); - if (newTop != screentop) result.scrollTop = newTop; - } - - var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; - var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); - var tooWide = x2 - x1 > screenw; - if (tooWide) x2 = x1 + screenw; - if (x1 < 10) - result.scrollLeft = 0; - else if (x1 < screenleft) - result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10)); - else if (x2 > screenw + screenleft - 3) - result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw; - return result; - } - - // Store a relative adjustment to the scroll position in the current - // operation (to be applied when the operation finishes). - function addToScrollPos(cm, left, top) { - if (left != null || top != null) resolveScrollToPos(cm); - if (left != null) - cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left; - if (top != null) - cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top; - } - - // Make sure that at the end of the operation the current cursor is - // shown. - function ensureCursorVisible(cm) { - resolveScrollToPos(cm); - var cur = cm.getCursor(), from = cur, to = cur; - if (!cm.options.lineWrapping) { - from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; - to = Pos(cur.line, cur.ch + 1); - } - cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; - } - - // When an operation has its scrollToPos property set, and another - // scroll action is applied before the end of the operation, this - // 'simulates' scrolling that position into view in a cheap way, so - // that the effect of intermediate scroll commands is not ignored. - function resolveScrollToPos(cm) { - var range = cm.curOp.scrollToPos; - if (range) { - cm.curOp.scrollToPos = null; - var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); - var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), - Math.min(from.top, to.top) - range.margin, - Math.max(from.right, to.right), - Math.max(from.bottom, to.bottom) + range.margin); - cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); - } - } - - // API UTILITIES - - // Indent the given line. The how parameter can be "smart", - // "add"/null, "subtract", or "prev". When aggressive is false - // (typically set to true for forced single-line indents), empty - // lines are not indented, and places where the mode returns Pass - // are left alone. - function indentLine(cm, n, how, aggressive) { - var doc = cm.doc, state; - if (how == null) how = "add"; - if (how == "smart") { - // Fall back to "prev" when the mode doesn't have an indentation - // method. - if (!doc.mode.indent) how = "prev"; - else state = getStateBefore(cm, n); - } - - var tabSize = cm.options.tabSize; - var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); - if (line.stateAfter) line.stateAfter = null; - var curSpaceString = line.text.match(/^\s*/)[0], indentation; - if (!aggressive && !/\S/.test(line.text)) { - indentation = 0; - how = "not"; - } else if (how == "smart") { - indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); - if (indentation == Pass || indentation > 150) { - if (!aggressive) return; - how = "prev"; - } - } - if (how == "prev") { - if (n > doc.first) indentation = countColumn(getLine(doc, n-1).text, null, tabSize); - else indentation = 0; - } else if (how == "add") { - indentation = curSpace + cm.options.indentUnit; - } else if (how == "subtract") { - indentation = curSpace - cm.options.indentUnit; - } else if (typeof how == "number") { - indentation = curSpace + how; - } - indentation = Math.max(0, indentation); - - var indentString = "", pos = 0; - if (cm.options.indentWithTabs) - for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";} - if (pos < indentation) indentString += spaceStr(indentation - pos); - - if (indentString != curSpaceString) { - replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); - line.stateAfter = null; - return true; - } else { - // Ensure that, if the cursor was in the whitespace at the start - // of the line, it is moved to the end of that space. - for (var i = 0; i < doc.sel.ranges.length; i++) { - var range = doc.sel.ranges[i]; - if (range.head.line == n && range.head.ch < curSpaceString.length) { - var pos = Pos(n, curSpaceString.length); - replaceOneSelection(doc, i, new Range(pos, pos)); - break; - } - } - } - } - - // Utility for applying a change to a line by handle or number, - // returning the number and optionally registering the line as - // changed. - function changeLine(doc, handle, changeType, op) { - var no = handle, line = handle; - if (typeof handle == "number") line = getLine(doc, clipLine(doc, handle)); - else no = lineNo(handle); - if (no == null) return null; - if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); - return line; - } - - // Helper for deleting text near the selection(s), used to implement - // backspace, delete, and similar functionality. - function deleteNearSelection(cm, compute) { - var ranges = cm.doc.sel.ranges, kill = []; - // Build up a set of ranges to kill first, merging overlapping - // ranges. - for (var i = 0; i < ranges.length; i++) { - var toKill = compute(ranges[i]); - while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { - var replaced = kill.pop(); - if (cmp(replaced.from, toKill.from) < 0) { - toKill.from = replaced.from; - break; - } - } - kill.push(toKill); - } - // Next, remove those actual ranges. - runInOp(cm, function() { - for (var i = kill.length - 1; i >= 0; i--) - replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete"); - ensureCursorVisible(cm); - }); - } - - // Used for horizontal relative motion. Dir is -1 or 1 (left or - // right), unit can be "char", "column" (like char, but doesn't - // cross line boundaries), "word" (across next word), or "group" (to - // the start of next group of word or non-word-non-whitespace - // chars). The visually param controls whether, in right-to-left - // text, direction 1 means to move towards the next index in the - // string, or towards the character to the right of the current - // position. The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosH(doc, pos, dir, unit, visually) { - var line = pos.line, ch = pos.ch, origDir = dir; - var lineObj = getLine(doc, line); - var possible = true; - function findNextLine() { - var l = line + dir; - if (l < doc.first || l >= doc.first + doc.size) return (possible = false); - line = l; - return lineObj = getLine(doc, l); - } - function moveOnce(boundToLine) { - var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); - if (next == null) { - if (!boundToLine && findNextLine()) { - if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); - else ch = dir < 0 ? lineObj.text.length : 0; - } else return (possible = false); - } else ch = next; - return true; - } - - if (unit == "char") moveOnce(); - else if (unit == "column") moveOnce(true); - else if (unit == "word" || unit == "group") { - var sawType = null, group = unit == "group"; - var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); - for (var first = true;; first = false) { - if (dir < 0 && !moveOnce(!first)) break; - var cur = lineObj.text.charAt(ch) || "\n"; - var type = isWordChar(cur, helper) ? "w" - : group && cur == "\n" ? "n" - : !group || /\s/.test(cur) ? null - : "p"; - if (group && !first && !type) type = "s"; - if (sawType && sawType != type) { - if (dir < 0) {dir = 1; moveOnce();} - break; - } - - if (type) sawType = type; - if (dir > 0 && !moveOnce(!first)) break; - } - } - var result = skipAtomic(doc, Pos(line, ch), origDir, true); - if (!possible) result.hitSide = true; - return result; - } - - // For relative vertical movement. Dir may be -1 or 1. Unit can be - // "page" or "line". The resulting position will have a hitSide=true - // property if it reached the end of the document. - function findPosV(cm, pos, dir, unit) { - var doc = cm.doc, x = pos.left, y; - if (unit == "page") { - var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); - y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); - } else if (unit == "line") { - y = dir > 0 ? pos.bottom + 3 : pos.top - 3; - } - for (;;) { - var target = coordsChar(cm, x, y); - if (!target.outside) break; - if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } - y += dir * 5; - } - return target; - } - - // EDITOR METHODS - - // The publicly visible API. Note that methodOp(f) means - // 'wrap f in an operation, performed on its `this` parameter'. - - // This is not the complete set of editor methods. Most of the - // methods defined on the Doc type are also injected into - // CodeMirror.prototype, for backwards compatibility and - // convenience. - - CodeMirror.prototype = { - constructor: CodeMirror, - focus: function(){window.focus(); this.display.input.focus();}, - - setOption: function(option, value) { - var options = this.options, old = options[option]; - if (options[option] == value && option != "mode") return; - options[option] = value; - if (optionHandlers.hasOwnProperty(option)) - operation(this, optionHandlers[option])(this, value, old); - }, - - getOption: function(option) {return this.options[option];}, - getDoc: function() {return this.doc;}, - - addKeyMap: function(map, bottom) { - this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); - }, - removeKeyMap: function(map) { - var maps = this.state.keyMaps; - for (var i = 0; i < maps.length; ++i) - if (maps[i] == map || maps[i].name == map) { - maps.splice(i, 1); - return true; - } - }, - - addOverlay: methodOp(function(spec, options) { - var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); - if (mode.startState) throw new Error("Overlays may not be stateful."); - this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); - this.state.modeGen++; - regChange(this); - }), - removeOverlay: methodOp(function(spec) { - var overlays = this.state.overlays; - for (var i = 0; i < overlays.length; ++i) { - var cur = overlays[i].modeSpec; - if (cur == spec || typeof spec == "string" && cur.name == spec) { - overlays.splice(i, 1); - this.state.modeGen++; - regChange(this); - return; - } - } - }), - - indentLine: methodOp(function(n, dir, aggressive) { - if (typeof dir != "string" && typeof dir != "number") { - if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; - else dir = dir ? "add" : "subtract"; - } - if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); - }), - indentSelection: methodOp(function(how) { - var ranges = this.doc.sel.ranges, end = -1; - for (var i = 0; i < ranges.length; i++) { - var range = ranges[i]; - if (!range.empty()) { - var from = range.from(), to = range.to(); - var start = Math.max(end, from.line); - end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; - for (var j = start; j < end; ++j) - indentLine(this, j, how); - var newRanges = this.doc.sel.ranges; - if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) - replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll); - } else if (range.head.line > end) { - indentLine(this, range.head.line, how, true); - end = range.head.line; - if (i == this.doc.sel.primIndex) ensureCursorVisible(this); - } - } - }), - - // Fetch the parser token for a given character. Useful for hacks - // that want to inspect the mode state (say, for completion). - getTokenAt: function(pos, precise) { - return takeToken(this, pos, precise); - }, - - getLineTokens: function(line, precise) { - return takeToken(this, Pos(line), precise, true); - }, - - getTokenTypeAt: function(pos) { - pos = clipPos(this.doc, pos); - var styles = getLineStyles(this, getLine(this.doc, pos.line)); - var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; - var type; - if (ch == 0) type = styles[2]; - else for (;;) { - var mid = (before + after) >> 1; - if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; - else if (styles[mid * 2 + 1] < ch) before = mid + 1; - else { type = styles[mid * 2 + 2]; break; } - } - var cut = type ? type.indexOf("cm-overlay ") : -1; - return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); - }, - - getModeAt: function(pos) { - var mode = this.doc.mode; - if (!mode.innerMode) return mode; - return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; - }, - - getHelper: function(pos, type) { - return this.getHelpers(pos, type)[0]; - }, - - getHelpers: function(pos, type) { - var found = []; - if (!helpers.hasOwnProperty(type)) return found; - var help = helpers[type], mode = this.getModeAt(pos); - if (typeof mode[type] == "string") { - if (help[mode[type]]) found.push(help[mode[type]]); - } else if (mode[type]) { - for (var i = 0; i < mode[type].length; i++) { - var val = help[mode[type][i]]; - if (val) found.push(val); - } - } else if (mode.helperType && help[mode.helperType]) { - found.push(help[mode.helperType]); - } else if (help[mode.name]) { - found.push(help[mode.name]); - } - for (var i = 0; i < help._global.length; i++) { - var cur = help._global[i]; - if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) - found.push(cur.val); - } - return found; - }, - - getStateAfter: function(line, precise) { - var doc = this.doc; - line = clipLine(doc, line == null ? doc.first + doc.size - 1: line); - return getStateBefore(this, line + 1, precise); - }, - - cursorCoords: function(start, mode) { - var pos, range = this.doc.sel.primary(); - if (start == null) pos = range.head; - else if (typeof start == "object") pos = clipPos(this.doc, start); - else pos = start ? range.from() : range.to(); - return cursorCoords(this, pos, mode || "page"); - }, - - charCoords: function(pos, mode) { - return charCoords(this, clipPos(this.doc, pos), mode || "page"); - }, - - coordsChar: function(coords, mode) { - coords = fromCoordSystem(this, coords, mode || "page"); - return coordsChar(this, coords.left, coords.top); - }, - - lineAtHeight: function(height, mode) { - height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; - return lineAtHeight(this.doc, height + this.display.viewOffset); - }, - heightAtLine: function(line, mode) { - var end = false, lineObj; - if (typeof line == "number") { - var last = this.doc.first + this.doc.size - 1; - if (line < this.doc.first) line = this.doc.first; - else if (line > last) { line = last; end = true; } - lineObj = getLine(this.doc, line); - } else { - lineObj = line; - } - return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + - (end ? this.doc.height - heightAtLine(lineObj) : 0); - }, + // Does the actual updating of the line display. Bails out + // (returning false) when there is nothing to be done and forced is + // false. + function updateDisplayIfNeeded (cm, update) { + var display = cm.display, doc = cm.doc; + + if (update.editorIsHidden) { + resetView(cm); + return false; + } + + // Bail out if the visible area is already rendered and nothing changed. + if (!update.force && + update.visible.from >= display.viewFrom && update.visible.to <= display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo) && + display.renderedView == display.view && countDirtyView(cm) == 0) {return false;} + + if (maybeUpdateLineNumberWidth(cm)) { + resetView(cm); + update.dims = getDimensions(cm); + } + + // Compute a suitable new viewport (from & to) + var end = doc.first + doc.size; + var from = Math.max(update.visible.from - cm.options.viewportMargin, doc.first); + var to = Math.min(end, update.visible.to + cm.options.viewportMargin); + if (display.viewFrom < from && from - display.viewFrom < 20) from = Math.max(doc.first, display.viewFrom); + if (display.viewTo > to && display.viewTo - to < 20) to = Math.min(end, display.viewTo); + if (sawCollapsedSpans) { + from = visualLineNo(cm.doc, from); + to = visualLineEndNo(cm.doc, to); + } + + var different = from != display.viewFrom || to != display.viewTo || + display.lastWrapHeight != update.wrapperHeight || display.lastWrapWidth != update.wrapperWidth; + adjustView(cm, from, to); + + display.viewOffset = heightAtLine(getLine(cm.doc, display.viewFrom)); + // Position the mover div to align with the current scroll position + cm.display.mover.style.top = display.viewOffset + "px"; + + var toUpdate = countDirtyView(cm); + if (!different && toUpdate == 0 && !update.force && display.renderedView == display.view && + (display.updateLineNumbers == null || display.updateLineNumbers >= display.viewTo)) {return false;} + + // For big changes, we hide the enclosing element during the + // update, since that speeds up the operations on most browsers. + var focused = activeElt(); + if (toUpdate > 4) display.lineDiv.style.display = "none"; + patchDisplay(cm, display.updateLineNumbers, update.dims); + if (toUpdate > 4) display.lineDiv.style.display = ""; + display.renderedView = display.view; + // There might have been a widget with a focused element that got + // hidden or updated, if so re-focus it. + if (focused && activeElt() != focused && focused.offsetHeight) focused.focus(); + + // Prevent selection and cursors from interfering with the scroll + // width and height. + removeChildren(display.cursorDiv); + removeChildren(display.selectionDiv); + display.gutters.style.height = 0; + + if (different) { + display.lastWrapHeight = update.wrapperHeight; + display.lastWrapWidth = update.wrapperWidth; + startWorker(cm, 400); + } - defaultTextHeight: function() { return textHeight(this.display); }, - defaultCharWidth: function() { return charWidth(this.display); }, + display.updateLineNumbers = null; - setGutterMarker: methodOp(function(line, gutterID, value) { - return changeLine(this.doc, line, "gutter", function(line) { - var markers = line.gutterMarkers || (line.gutterMarkers = {}); - markers[gutterID] = value; - if (!value && isEmpty(markers)) line.gutterMarkers = null; return true; - }); - }), - - clearGutter: methodOp(function(gutterID) { - var cm = this, doc = cm.doc, i = doc.first; - doc.iter(function(line) { - if (line.gutterMarkers && line.gutterMarkers[gutterID]) { - line.gutterMarkers[gutterID] = null; - regLineChange(cm, i, "gutter"); - if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; - } - ++i; - }); - }), - - lineInfo: function(line) { - if (typeof line == "number") { - if (!isLine(this.doc, line)) return null; - var n = line; - line = getLine(this.doc, line); - if (!line) return null; - } else { - var n = lineNo(line); - if (n == null) return null; - } - return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, - textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, - widgets: line.widgets}; - }, - - getViewport: function() { return {from: this.display.viewFrom, to: this.display.viewTo};}, - - addWidget: function(pos, node, scroll, vert, horiz) { - var display = this.display; - pos = cursorCoords(this, clipPos(this.doc, pos)); - var top = pos.bottom, left = pos.left; - node.style.position = "absolute"; - node.setAttribute("cm-ignore-events", "true"); - this.display.input.setUneditable(node); - display.sizer.appendChild(node); - if (vert == "over") { - top = pos.top; - } else if (vert == "above" || vert == "near") { - var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), - hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); - // Default to positioning above (if specified and possible); otherwise default to positioning below - if ((vert == 'above' || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) - top = pos.top - node.offsetHeight; - else if (pos.bottom + node.offsetHeight <= vspace) - top = pos.bottom; - if (left + node.offsetWidth > hspace) - left = hspace - node.offsetWidth; - } - node.style.top = top + "px"; - node.style.left = node.style.right = ""; - if (horiz == "right") { - left = display.sizer.clientWidth - node.offsetWidth; - node.style.right = "0px"; - } else { - if (horiz == "left") left = 0; - else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; - node.style.left = left + "px"; - } - if (scroll) - scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight); - }, - - triggerOnKeyDown: methodOp(onKeyDown), - triggerOnKeyPress: methodOp(onKeyPress), - triggerOnKeyUp: onKeyUp, - - execCommand: function(cmd) { - if (commands.hasOwnProperty(cmd)) - return commands[cmd](this); - }, - - triggerElectric: methodOp(function(text) { triggerElectric(this, text); }), - - findPosH: function(from, amount, unit, visually) { - var dir = 1; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - cur = findPosH(this.doc, cur, dir, unit, visually); - if (cur.hitSide) break; - } - return cur; - }, - - moveH: methodOp(function(dir, unit) { - var cm = this; - cm.extendSelectionsBy(function(range) { - if (cm.display.shift || cm.doc.extend || range.empty()) - return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually); - else - return dir < 0 ? range.from() : range.to(); - }, sel_move); - }), - - deleteH: methodOp(function(dir, unit) { - var sel = this.doc.sel, doc = this.doc; - if (sel.somethingSelected()) - doc.replaceSelection("", null, "+delete"); - else - deleteNearSelection(this, function(range) { - var other = findPosH(doc, range.head, dir, unit, false); - return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; - }); - }), - - findPosV: function(from, amount, unit, goalColumn) { - var dir = 1, x = goalColumn; - if (amount < 0) { dir = -1; amount = -amount; } - for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { - var coords = cursorCoords(this, cur, "div"); - if (x == null) x = coords.left; - else coords.left = x; - cur = findPosV(this, coords, dir, unit); - if (cur.hitSide) break; - } - return cur; - }, - - moveV: methodOp(function(dir, unit) { - var cm = this, doc = this.doc, goals = []; - var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); - doc.extendSelectionsBy(function(range) { - if (collapse) - return dir < 0 ? range.from() : range.to(); - var headPos = cursorCoords(cm, range.head, "div"); - if (range.goalColumn != null) headPos.left = range.goalColumn; - goals.push(headPos.left); - var pos = findPosV(cm, headPos, dir, unit); - if (unit == "page" && range == doc.sel.primary()) - addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top); - return pos; - }, sel_move); - if (goals.length) for (var i = 0; i < doc.sel.ranges.length; i++) - doc.sel.ranges[i].goalColumn = goals[i]; - }), - - // Find the word at the given position (as returned by coordsChar). - findWordAt: function(pos) { - var doc = this.doc, line = getLine(doc, pos.line).text; - var start = pos.ch, end = pos.ch; - if (line) { - var helper = this.getHelper(pos, "wordChars"); - if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; - var startChar = line.charAt(start); - var check = isWordChar(startChar, helper) - ? function(ch) { return isWordChar(ch, helper); } - : /\s/.test(startChar) ? function(ch) {return /\s/.test(ch);} - : function(ch) {return !/\s/.test(ch) && !isWordChar(ch);}; - while (start > 0 && check(line.charAt(start - 1))) --start; - while (end < line.length && check(line.charAt(end))) ++end; - } - return new Range(Pos(pos.line, start), Pos(pos.line, end)); - }, - - toggleOverwrite: function(value) { - if (value != null && value == this.state.overwrite) return; - if (this.state.overwrite = !this.state.overwrite) - addClass(this.display.cursorDiv, "CodeMirror-overwrite"); - else - rmClass(this.display.cursorDiv, "CodeMirror-overwrite"); - - signal(this, "overwriteToggle", this, this.state.overwrite); - }, - hasFocus: function() { return this.display.input.getField() == activeElt(); }, - - scrollTo: methodOp(function(x, y) { - if (x != null || y != null) resolveScrollToPos(this); - if (x != null) this.curOp.scrollLeft = x; - if (y != null) this.curOp.scrollTop = y; - }), - getScrollInfo: function() { - var scroller = this.display.scroller; - return {left: scroller.scrollLeft, top: scroller.scrollTop, - height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, - width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, - clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; - }, - - scrollIntoView: methodOp(function(range, margin) { - if (range == null) { - range = {from: this.doc.sel.primary().head, to: null}; - if (margin == null) margin = this.options.cursorScrollMargin; - } else if (typeof range == "number") { - range = {from: Pos(range, 0), to: null}; - } else if (range.from == null) { - range = {from: range, to: null}; - } - if (!range.to) range.to = range.from; - range.margin = margin || 0; - - if (range.from.line != null) { - resolveScrollToPos(this); - this.curOp.scrollToPos = range; - } else { - var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), - Math.min(range.from.top, range.to.top) - range.margin, - Math.max(range.from.right, range.to.right), - Math.max(range.from.bottom, range.to.bottom) + range.margin); - this.scrollTo(sPos.scrollLeft, sPos.scrollTop); - } - }), - - setSize: methodOp(function(width, height) { - var cm = this; - function interpret(val) { - return typeof val == "number" || /^\d+$/.test(String(val)) ? val + "px" : val; - } - if (width != null) cm.display.wrapper.style.width = interpret(width); - if (height != null) cm.display.wrapper.style.height = interpret(height); - if (cm.options.lineWrapping) clearLineMeasurementCache(this); - var lineNo = cm.display.viewFrom; - cm.doc.iter(lineNo, cm.display.viewTo, function(line) { - if (line.widgets) for (var i = 0; i < line.widgets.length; i++) - if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; } - ++lineNo; - }); - cm.curOp.forceUpdate = true; - signal(cm, "refresh", this); - }), - - operation: function(f){return runInOp(this, f);}, - - refresh: methodOp(function() { - var oldHeight = this.display.cachedTextHeight; - regChange(this); - this.curOp.forceUpdate = true; - clearCaches(this); - this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); - updateGutterSpace(this); - if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) - estimateLineHeights(this); - signal(this, "refresh", this); - }), - - swapDoc: methodOp(function(doc) { - var old = this.doc; - old.cm = null; - attachDoc(this, doc); - clearCaches(this); - this.display.input.reset(); - this.scrollTo(doc.scrollLeft, doc.scrollTop); - this.curOp.forceScroll = true; - signalLater(this, "swapDoc", this, old); - return old; - }), - - getInputField: function(){return this.display.input.getField();}, - getWrapperElement: function(){return this.display.wrapper;}, - getScrollerElement: function(){return this.display.scroller;}, - getGutterElement: function(){return this.display.gutters;} - }; - eventMixin(CodeMirror); - - // OPTION DEFAULTS - - // The default configuration options. - var defaults = CodeMirror.defaults = {}; - // Functions to run when options are changed. - var optionHandlers = CodeMirror.optionHandlers = {}; - - function option(name, deflt, handle, notOnInit) { - CodeMirror.defaults[name] = deflt; - if (handle) optionHandlers[name] = - notOnInit ? function(cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; - } - - // Passed to option handlers when there is no old value. - var Init = CodeMirror.Init = {toString: function(){return "CodeMirror.Init";}}; - - // These two are, on init, called from the constructor because they - // have to be initialized before the editor can start at all. - option("value", "", function(cm, val) { - cm.setValue(val); - }, true); - option("mode", null, function(cm, val) { - cm.doc.modeOption = val; - loadMode(cm); - }, true); - - option("indentUnit", 2, loadMode, true); - option("indentWithTabs", false); - option("smartIndent", true); - option("tabSize", 4, function(cm) { - resetModeState(cm); - clearCaches(cm); - regChange(cm); - }, true); - option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function(cm, val, old) { - cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); - if (old != CodeMirror.Init) cm.refresh(); - }); - option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function(cm) {cm.refresh();}, true); - option("electricChars", true); - option("inputStyle", mobile ? "contenteditable" : "textarea", function() { - throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME - }, true); - option("rtlMoveVisually", !windows); - option("wholeLineUpdateBefore", true); - - option("theme", "default", function(cm) { - themeChanged(cm); - guttersChanged(cm); - }, true); - option("keyMap", "default", function(cm, val, old) { - var next = getKeyMap(val); - var prev = old != CodeMirror.Init && getKeyMap(old); - if (prev && prev.detach) prev.detach(cm, next); - if (next.attach) next.attach(cm, prev || null); - }); - option("extraKeys", null); - - option("lineWrapping", false, wrappingChanged, true); - option("gutters", [], function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("fixedGutter", true, function(cm, val) { - cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; - cm.refresh(); - }, true); - option("coverGutterNextToScrollbar", false, function(cm) {updateScrollbars(cm);}, true); - option("scrollbarStyle", "native", function(cm) { - initScrollbars(cm); - updateScrollbars(cm); - cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); - cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); - }, true); - option("lineNumbers", false, function(cm) { - setGuttersForLineNumbers(cm.options); - guttersChanged(cm); - }, true); - option("firstLineNumber", 1, guttersChanged, true); - option("lineNumberFormatter", function(integer) {return integer;}, guttersChanged, true); - option("showCursorWhenSelecting", false, updateSelection, true); - - option("resetSelectionOnContextMenu", true); - option("lineWiseCopyCut", true); - - option("readOnly", false, function(cm, val) { - if (val == "nocursor") { - onBlur(cm); - cm.display.input.blur(); - cm.display.disabled = true; - } else { - cm.display.disabled = false; - if (!val) cm.display.input.reset(); - } - }); - option("disableInput", false, function(cm, val) {if (!val) cm.display.input.reset();}, true); - option("dragDrop", true, dragDropChanged); - - option("cursorBlinkRate", 530); - option("cursorScrollMargin", 0); - option("cursorHeight", 1, updateSelection, true); - option("singleCursorHeightPerLine", true, updateSelection, true); - option("workTime", 100); - option("workDelay", 100); - option("flattenSpans", true, resetModeState, true); - option("addModeClass", false, resetModeState, true); - option("pollInterval", 100); - option("undoDepth", 200, function(cm, val){cm.doc.history.undoDepth = val;}); - option("historyEventDelay", 1250); - option("viewportMargin", 10, function(cm){cm.refresh();}, true); - option("maxHighlightLength", 10000, resetModeState, true); - option("moveInputWithCursor", true, function(cm, val) { - if (!val) cm.display.input.resetPosition(); - }); - - option("tabindex", null, function(cm, val) { - cm.display.input.getField().tabIndex = val || ""; - }); - option("autofocus", null); - - // MODE DEFINITION AND QUERYING - - // Known modes, by name and by MIME - var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; - - // Extra arguments are stored as the mode's dependencies, which is - // used by (legacy) mechanisms like loadmode.js to automatically - // load a mode. (Preferred mechanism is the require/define calls.) - CodeMirror.defineMode = function(name, mode) { - if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; - if (arguments.length > 2) - mode.dependencies = Array.prototype.slice.call(arguments, 2); - modes[name] = mode; - }; - - CodeMirror.defineMIME = function(mime, spec) { - mimeModes[mime] = spec; - }; - - // Given a MIME type, a {name, ...options} config object, or a name - // string, return a mode config object. - CodeMirror.resolveMode = function(spec) { - if (typeof spec == "string" && mimeModes.hasOwnProperty(spec)) { - spec = mimeModes[spec]; - } else if (spec && typeof spec.name == "string" && mimeModes.hasOwnProperty(spec.name)) { - var found = mimeModes[spec.name]; - if (typeof found == "string") found = {name: found}; - spec = createObj(found, spec); - spec.name = found.name; - } else if (typeof spec == "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { - return CodeMirror.resolveMode("application/xml"); - } - if (typeof spec == "string") return {name: spec}; - else return spec || {name: "null"}; - }; - - // Given a mode spec (anything that resolveMode accepts), find and - // initialize an actual mode object. - CodeMirror.getMode = function(options, spec) { - var spec = CodeMirror.resolveMode(spec); - var mfactory = modes[spec.name]; - if (!mfactory) return CodeMirror.getMode(options, "text/plain"); - var modeObj = mfactory(options, spec); - if (modeExtensions.hasOwnProperty(spec.name)) { - var exts = modeExtensions[spec.name]; - for (var prop in exts) { - if (!exts.hasOwnProperty(prop)) continue; - if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; - modeObj[prop] = exts[prop]; - } - } - modeObj.name = spec.name; - if (spec.helperType) modeObj.helperType = spec.helperType; - if (spec.modeProps) for (var prop in spec.modeProps) - modeObj[prop] = spec.modeProps[prop]; - - return modeObj; - }; - - // Minimal default mode. - CodeMirror.defineMode("null", function() { - return {token: function(stream) {stream.skipToEnd();}}; - }); - CodeMirror.defineMIME("text/plain", "null"); - - // This can be used to attach properties to mode objects from - // outside the actual mode definition. - var modeExtensions = CodeMirror.modeExtensions = {}; - CodeMirror.extendMode = function(mode, properties) { - var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); - copyObj(properties, exts); - }; - - // EXTENSIONS - - CodeMirror.defineExtension = function(name, func) { - CodeMirror.prototype[name] = func; - }; - CodeMirror.defineDocExtension = function(name, func) { - Doc.prototype[name] = func; - }; - CodeMirror.defineOption = option; - - var initHooks = []; - CodeMirror.defineInitHook = function(f) {initHooks.push(f);}; - - var helpers = CodeMirror.helpers = {}; - CodeMirror.registerHelper = function(type, name, value) { - if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; - helpers[type][name] = value; - }; - CodeMirror.registerGlobalHelper = function(type, name, predicate, value) { - CodeMirror.registerHelper(type, name, value); - helpers[type]._global.push({pred: predicate, val: value}); - }; - - // MODE STATE HANDLING - - // Utility functions for working with state. Exported because nested - // modes need to do this for their inner modes. - - var copyState = CodeMirror.copyState = function(mode, state) { - if (state === true) return state; - if (mode.copyState) return mode.copyState(state); - var nstate = {}; - for (var n in state) { - var val = state[n]; - if (val instanceof Array) val = val.concat([]); - nstate[n] = val; - } - return nstate; - }; - - var startState = CodeMirror.startState = function(mode, a1, a2) { - return mode.startState ? mode.startState(a1, a2) : true; - }; - - // Given a mode and a state (for that mode), find the inner mode and - // state at the position that the state refers to. - CodeMirror.innerMode = function(mode, state) { - while (mode.innerMode) { - var info = mode.innerMode(state); - if (!info || info.mode == mode) break; - state = info.state; - mode = info.mode; - } - return info || {mode: mode, state: state}; - }; - - // STANDARD COMMANDS - - // Commands are parameter-less actions that can be performed on an - // editor, mostly used for keybindings. - var commands = CodeMirror.commands = { - selectAll: function(cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, - singleSelection: function(cm) { - cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); - }, - killLine: function(cm) { - deleteNearSelection(cm, function(range) { - if (range.empty()) { - var len = getLine(cm.doc, range.head.line).text.length; - if (range.head.ch == len && range.head.line < cm.lastLine()) - return {from: range.head, to: Pos(range.head.line + 1, 0)}; - else - return {from: range.head, to: Pos(range.head.line, len)}; - } else { - return {from: range.from(), to: range.to()}; - } - }); - }, - deleteLine: function(cm) { - deleteNearSelection(cm, function(range) { - return {from: Pos(range.from().line, 0), - to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; - }); - }, - delLineLeft: function(cm) { - deleteNearSelection(cm, function(range) { - return {from: Pos(range.from().line, 0), to: range.from()}; - }); - }, - delWrappedLineLeft: function(cm) { - deleteNearSelection(cm, function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var leftPos = cm.coordsChar({left: 0, top: top}, "div"); - return {from: leftPos, to: range.from()}; - }); - }, - delWrappedLineRight: function(cm) { - deleteNearSelection(cm, function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - return {from: range.from(), to: rightPos }; - }); - }, - undo: function(cm) {cm.undo();}, - redo: function(cm) {cm.redo();}, - undoSelection: function(cm) {cm.undoSelection();}, - redoSelection: function(cm) {cm.redoSelection();}, - goDocStart: function(cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, - goDocEnd: function(cm) {cm.extendSelection(Pos(cm.lastLine()));}, - goLineStart: function(cm) { - cm.extendSelectionsBy(function(range) { return lineStart(cm, range.head.line); }, - {origin: "+move", bias: 1}); - }, - goLineStartSmart: function(cm) { - cm.extendSelectionsBy(function(range) { - return lineStartSmart(cm, range.head); - }, {origin: "+move", bias: 1}); - }, - goLineEnd: function(cm) { - cm.extendSelectionsBy(function(range) { return lineEnd(cm, range.head.line); }, - {origin: "+move", bias: -1}); - }, - goLineRight: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); - }, sel_move); - }, - goLineLeft: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - return cm.coordsChar({left: 0, top: top}, "div"); - }, sel_move); - }, - goLineLeftSmart: function(cm) { - cm.extendSelectionsBy(function(range) { - var top = cm.charCoords(range.head, "div").top + 5; - var pos = cm.coordsChar({left: 0, top: top}, "div"); - if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); - return pos; - }, sel_move); - }, - goLineUp: function(cm) {cm.moveV(-1, "line");}, - goLineDown: function(cm) {cm.moveV(1, "line");}, - goPageUp: function(cm) {cm.moveV(-1, "page");}, - goPageDown: function(cm) {cm.moveV(1, "page");}, - goCharLeft: function(cm) {cm.moveH(-1, "char");}, - goCharRight: function(cm) {cm.moveH(1, "char");}, - goColumnLeft: function(cm) {cm.moveH(-1, "column");}, - goColumnRight: function(cm) {cm.moveH(1, "column");}, - goWordLeft: function(cm) {cm.moveH(-1, "word");}, - goGroupRight: function(cm) {cm.moveH(1, "group");}, - goGroupLeft: function(cm) {cm.moveH(-1, "group");}, - goWordRight: function(cm) {cm.moveH(1, "word");}, - delCharBefore: function(cm) {cm.deleteH(-1, "char");}, - delCharAfter: function(cm) {cm.deleteH(1, "char");}, - delWordBefore: function(cm) {cm.deleteH(-1, "word");}, - delWordAfter: function(cm) {cm.deleteH(1, "word");}, - delGroupBefore: function(cm) {cm.deleteH(-1, "group");}, - delGroupAfter: function(cm) {cm.deleteH(1, "group");}, - indentAuto: function(cm) {cm.indentSelection("smart");}, - indentMore: function(cm) {cm.indentSelection("add");}, - indentLess: function(cm) {cm.indentSelection("subtract");}, - insertTab: function(cm) {cm.replaceSelection("\t");}, - insertSoftTab: function(cm) { - var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; - for (var i = 0; i < ranges.length; i++) { - var pos = ranges[i].from(); - var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); - spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); - } - cm.replaceSelections(spaces); - }, - defaultTab: function(cm) { - if (cm.somethingSelected()) cm.indentSelection("add"); - else cm.execCommand("insertTab"); - }, - transposeChars: function(cm) { - runInOp(cm, function() { - var ranges = cm.listSelections(), newSel = []; - for (var i = 0; i < ranges.length; i++) { - var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; - if (line) { - if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); - if (cur.ch > 0) { - cur = new Pos(cur.line, cur.ch + 1); - cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), - Pos(cur.line, cur.ch - 2), cur, "+transpose"); - } else if (cur.line > cm.doc.first) { - var prev = getLine(cm.doc, cur.line - 1).text; - if (prev) - cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1), - Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); - } - } - newSel.push(new Range(cur, cur)); - } - cm.setSelections(newSel); - }); - }, - newlineAndIndent: function(cm) { - runInOp(cm, function() { - var len = cm.listSelections().length; - for (var i = 0; i < len; i++) { - var range = cm.listSelections()[i]; - cm.replaceRange("\n", range.anchor, range.head, "+input"); - cm.indentLine(range.from().line + 1, null, true); - ensureCursorVisible(cm); - } - }); - }, - toggleOverwrite: function(cm) {cm.toggleOverwrite();} - }; - - - // STANDARD KEYMAPS - - var keyMap = CodeMirror.keyMap = {}; - - keyMap.basic = { - "Left": "goCharLeft", "Right": "goCharRight", "Up": "goLineUp", "Down": "goLineDown", - "End": "goLineEnd", "Home": "goLineStartSmart", "PageUp": "goPageUp", "PageDown": "goPageDown", - "Delete": "delCharAfter", "Backspace": "delCharBefore", "Shift-Backspace": "delCharBefore", - "Tab": "defaultTab", "Shift-Tab": "indentAuto", - "Enter": "newlineAndIndent", "Insert": "toggleOverwrite", - "Esc": "singleSelection" - }; - // Note that the save and find-related commands aren't defined by - // default. User code or addons can define them. Unknown commands - // are simply ignored. - keyMap.pcDefault = { - "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", - "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", - "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", - "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", - "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", - "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", - "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", - fallthrough: "basic" - }; - // Very basic readline/emacs-style bindings, which are standard on Mac. - keyMap.emacsy = { - "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", - "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", - "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", - "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" - }; - keyMap.macDefault = { - "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", - "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", - "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", - "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", - "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", - "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", - "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", - fallthrough: ["basic", "emacsy"] - }; - keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; - - // KEYMAP DISPATCH - - function normalizeKeyName(name) { - var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; - var alt, ctrl, shift, cmd; - for (var i = 0; i < parts.length - 1; i++) { - var mod = parts[i]; - if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; - else if (/^a(lt)?$/i.test(mod)) alt = true; - else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; - else if (/^s(hift)$/i.test(mod)) shift = true; - else throw new Error("Unrecognized modifier name: " + mod); - } - if (alt) name = "Alt-" + name; - if (ctrl) name = "Ctrl-" + name; - if (cmd) name = "Cmd-" + name; - if (shift) name = "Shift-" + name; - return name; - } - - // This is a kludge to keep keymaps mostly working as raw objects - // (backwards compatibility) while at the same time support features - // like normalization and multi-stroke key bindings. It compiles a - // new normalized keymap, and then updates the old object to reflect - // this. - CodeMirror.normalizeKeyMap = function(keymap) { - var copy = {}; - for (var keyname in keymap) if (keymap.hasOwnProperty(keyname)) { - var value = keymap[keyname]; - if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; - if (value == "...") { delete keymap[keyname]; continue; } - - var keys = map(keyname.split(" "), normalizeKeyName); - for (var i = 0; i < keys.length; i++) { - var val, name; - if (i == keys.length - 1) { - name = keys.join(" "); - val = value; - } else { - name = keys.slice(0, i + 1).join(" "); - val = "..."; - } - var prev = copy[name]; - if (!prev) copy[name] = val; - else if (prev != val) throw new Error("Inconsistent bindings for " + name); - } - delete keymap[keyname]; - } - for (var prop in copy) keymap[prop] = copy[prop]; - return keymap; - }; - - var lookupKey = CodeMirror.lookupKey = function(key, map, handle, context) { - map = getKeyMap(map); - var found = map.call ? map.call(key, context) : map[key]; - if (found === false) return "nothing"; - if (found === "...") return "multi"; - if (found != null && handle(found)) return "handled"; - - if (map.fallthrough) { - if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") - return lookupKey(key, map.fallthrough, handle, context); - for (var i = 0; i < map.fallthrough.length; i++) { - var result = lookupKey(key, map.fallthrough[i], handle, context); - if (result) return result; - } - } - }; - - // Modifier key presses don't count as 'real' key presses for the - // purpose of keymap fallthrough. - var isModifierKey = CodeMirror.isModifierKey = function(value) { - var name = typeof value == "string" ? value : keyNames[value.keyCode]; - return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; - }; - - // Look up the name of a key as indicated by an event object. - var keyName = CodeMirror.keyName = function(event, noShift) { - if (presto && event.keyCode == 34 && event["char"]) return false; - var base = keyNames[event.keyCode], name = base; - if (name == null || event.altGraphKey) return false; - if (event.altKey && base != "Alt") name = "Alt-" + name; - if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; - if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; - if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; - return name; - }; - - function getKeyMap(val) { - return typeof val == "string" ? keyMap[val] : val; - } - - // FROMTEXTAREA - - CodeMirror.fromTextArea = function(textarea, options) { - options = options ? copyObj(options) : {}; - options.value = textarea.value; - if (!options.tabindex && textarea.tabIndex) - options.tabindex = textarea.tabIndex; - if (!options.placeholder && textarea.placeholder) - options.placeholder = textarea.placeholder; - // Set autofocus to true if this textarea is focused, or if it has - // autofocus and no other element is focused. - if (options.autofocus == null) { - var hasFocus = activeElt(); - options.autofocus = hasFocus == textarea || - textarea.getAttribute("autofocus") != null && hasFocus == document.body; } - function save() {textarea.value = cm.getValue();} - if (textarea.form) { - on(textarea.form, "submit", save); - // Deplorable hack to make the submit method do the right thing. - if (!options.leaveSubmitMethodAlone) { - var form = textarea.form, realSubmit = form.submit; - try { - var wrappedSubmit = form.submit = function() { - save(); - form.submit = realSubmit; - form.submit(); - form.submit = wrappedSubmit; - }; - } catch(e) {} - } - } - - options.finishInit = function(cm) { - cm.save = save; - cm.getTextArea = function() { return textarea; }; - cm.toTextArea = function() { - cm.toTextArea = isNaN; // Prevent this from being ran twice - save(); - textarea.parentNode.removeChild(cm.getWrapperElement()); - textarea.style.display = ""; - if (textarea.form) { - off(textarea.form, "submit", save); - if (typeof textarea.form.submit == "function") - textarea.form.submit = realSubmit; + function postUpdateDisplay (cm, update) { + var viewport = update.viewport; + for (var first = true; ; first = false) { + if (!first || !cm.options.lineWrapping || update.oldDisplayWidth == displayWidth(cm)) { + // Clip forced viewport to actual scrollable area. + if (viewport && viewport.top != null) {viewport = {top: Math.min(cm.doc.height + paddingVert(cm.display) - displayHeight(cm), viewport.top)};} + // Updated line heights might result in the drawn area not + // actually covering the viewport. Keep looping until it does. + update.visible = visibleLines(cm.display, cm.doc, viewport); + if (update.visible.from >= cm.display.viewFrom && update.visible.to <= cm.display.viewTo) {break;} + } + if (!updateDisplayIfNeeded(cm, update)) break; + updateHeightsInViewport(cm); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); } - }; - }; - textarea.style.display = "none"; - var cm = CodeMirror(function(node) { - textarea.parentNode.insertBefore(node, textarea.nextSibling); - }, options); - return cm; - }; - - // STRING STREAM - - // Fed to the mode parsers, provides helper functions to make - // parsers more succinct. - - var StringStream = CodeMirror.StringStream = function(string, tabSize) { - this.pos = this.start = 0; - this.string = string; - this.tabSize = tabSize || 8; - this.lastColumnPos = this.lastColumnValue = 0; - this.lineStart = 0; - }; - - StringStream.prototype = { - eol: function() {return this.pos >= this.string.length;}, - sol: function() {return this.pos == this.lineStart;}, - peek: function() {return this.string.charAt(this.pos) || undefined;}, - next: function() { - if (this.pos < this.string.length) - return this.string.charAt(this.pos++); - }, - eat: function(match) { - var ch = this.string.charAt(this.pos); - if (typeof match == "string") var ok = ch == match; - else var ok = ch && (match.test ? match.test(ch) : match(ch)); - if (ok) {++this.pos; return ch;} - }, - eatWhile: function(match) { - var start = this.pos; - while (this.eat(match)){} - return this.pos > start; - }, - eatSpace: function() { - var start = this.pos; - while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; - return this.pos > start; - }, - skipToEnd: function() {this.pos = this.string.length;}, - skipTo: function(ch) { - var found = this.string.indexOf(ch, this.pos); - if (found > -1) {this.pos = found; return true;} - }, - backUp: function(n) {this.pos -= n;}, - column: function() { - if (this.lastColumnPos < this.start) { - this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); - this.lastColumnPos = this.start; - } - return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }, - indentation: function() { - return countColumn(this.string, null, this.tabSize) - - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); - }, - match: function(pattern, consume, caseInsensitive) { - if (typeof pattern == "string") { - var cased = function(str) {return caseInsensitive ? str.toLowerCase() : str;}; - var substr = this.string.substr(this.pos, pattern.length); - if (cased(substr) == cased(pattern)) { - if (consume !== false) this.pos += pattern.length; - return true; - } - } else { - var match = this.string.slice(this.pos).match(pattern); - if (match && match.index > 0) return null; - if (match && consume !== false) this.pos += match[0].length; - return match; - } - }, - current: function(){return this.string.slice(this.start, this.pos);}, - hideFirstChars: function(n, inner) { - this.lineStart += n; - try { return inner(); } - finally { this.lineStart -= n; } - } - }; - - // TEXTMARKERS - - // Created with markText and setBookmark methods. A TextMarker is a - // handle that can be used to clear or find a marked position in the - // document. Line objects hold arrays (markedSpans) containing - // {from, to, marker} object pointing to such marker objects, and - // indicating that such a marker is present on that line. Multiple - // lines may point to the same marker when it spans across lines. - // The spans will have null for their from/to properties when the - // marker continues beyond the start/end of the line. Markers have - // links back to the lines they currently touch. - - var nextMarkerId = 0; - - var TextMarker = CodeMirror.TextMarker = function(doc, type) { - this.lines = []; - this.type = type; - this.doc = doc; - this.id = ++nextMarkerId; - }; - eventMixin(TextMarker); - - // Clear the marker. - TextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - var cm = this.doc.cm, withOp = cm && !cm.curOp; - if (withOp) startOperation(cm); - if (hasHandler(this, "clear")) { - var found = this.find(); - if (found) signalLater(this, "clear", found.from, found.to); - } - var min = null, max = null; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); - else if (cm) { - if (span.to != null) max = lineNo(line); - if (span.from != null) min = lineNo(line); - } - line.markedSpans = removeMarkedSpan(line.markedSpans, span); - if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) - updateLineHeight(line, textHeight(cm.display)); - } - if (cm && this.collapsed && !cm.options.lineWrapping) for (var i = 0; i < this.lines.length; ++i) { - var visual = visualLine(this.lines[i]), len = lineLength(visual); - if (len > cm.display.maxLineLength) { - cm.display.maxLine = visual; - cm.display.maxLineLength = len; - cm.display.maxLineChanged = true; - } - } - - if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); - this.lines.length = 0; - this.explicitlyCleared = true; - if (this.atomic && this.doc.cantEdit) { - this.doc.cantEdit = false; - if (cm) reCheckSelection(cm.doc); - } - if (cm) signalLater(cm, "markerCleared", cm, this); - if (withOp) endOperation(cm); - if (this.parent) this.parent.clear(); - }; - - // Find the position of the marker in the document. Returns a {from, - // to} object by default. Side can be passed to get a specific side - // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the - // Pos objects returned contain a line object, rather than a line - // number (used to prevent looking up the same line twice). - TextMarker.prototype.find = function(side, lineObj) { - if (side == null && this.type == "bookmark") side = 1; - var from, to; - for (var i = 0; i < this.lines.length; ++i) { - var line = this.lines[i]; - var span = getMarkedSpanFor(line.markedSpans, this); - if (span.from != null) { - from = Pos(lineObj ? line : lineNo(line), span.from); - if (side == -1) return from; - } - if (span.to != null) { - to = Pos(lineObj ? line : lineNo(line), span.to); - if (side == 1) return to; - } - } - return from && {from: from, to: to}; - }; - - // Signals that the marker's widget changed, and surrounding layout - // should be recomputed. - TextMarker.prototype.changed = function() { - var pos = this.find(-1, true), widget = this, cm = this.doc.cm; - if (!pos || !cm) return; - runInOp(cm, function() { - var line = pos.line, lineN = lineNo(pos.line); - var view = findViewForLine(cm, lineN); - if (view) { - clearLineMeasurementCacheFor(view); - cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; - } - cm.curOp.updateMaxLine = true; - if (!lineIsHidden(widget.doc, line) && widget.height != null) { - var oldHeight = widget.height; - widget.height = null; - var dHeight = widgetHeight(widget) - oldHeight; - if (dHeight) - updateLineHeight(line, line.height + dHeight); - } - }); - }; - - TextMarker.prototype.attachLine = function(line) { - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) - (op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this); - } - this.lines.push(line); - }; - TextMarker.prototype.detachLine = function(line) { - this.lines.splice(indexOf(this.lines, line), 1); - if (!this.lines.length && this.doc.cm) { - var op = this.doc.cm.curOp; - (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); - } - }; - - // Collapsed markers have unique ids, in order to be able to order - // them, which is needed for uniquely determining an outer marker - // when they overlap (they may nest, but not partially overlap). - var nextMarkerId = 0; - - // Create a marker, wire it up to the right lines, and - function markText(doc, from, to, options, type) { - // Shared markers (across linked documents) are handled separately - // (markTextShared will call out to this again, once per - // document). - if (options && options.shared) return markTextShared(doc, from, to, options, type); - // Ensure we are in an operation. - if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); - - var marker = new TextMarker(doc, type), diff = cmp(from, to); - if (options) copyObj(options, marker, false); - // Don't connect empty markers unless clearWhenEmpty is false - if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) - return marker; - if (marker.replacedWith) { - // Showing up as a widget implies collapsed (widget replaces text) - marker.collapsed = true; - marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); - if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); - if (options.insertLeft) marker.widgetNode.insertLeft = true; - } - if (marker.collapsed) { - if (conflictingCollapsedRange(doc, from.line, from, to, marker) || - from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) - throw new Error("Inserting collapsed marker partially overlapping an existing one"); - sawCollapsedSpans = true; - } - - if (marker.addToHistory) - addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN); - - var curLine = from.line, cm = doc.cm, updateMaxLine; - doc.iter(curLine, to.line + 1, function(line) { - if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) - updateMaxLine = true; - if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); - addMarkedSpan(line, new MarkedSpan(marker, - curLine == from.line ? from.ch : null, - curLine == to.line ? to.ch : null)); - ++curLine; - }); - // lineIsHidden depends on the presence of the spans, so needs a second pass - if (marker.collapsed) doc.iter(from.line, to.line + 1, function(line) { - if (lineIsHidden(doc, line)) updateLineHeight(line, 0); - }); + update.signal(cm, "update", cm); + if (cm.display.viewFrom != cm.display.reportedViewFrom || cm.display.viewTo != cm.display.reportedViewTo) { + update.signal(cm, "viewportChange", cm, cm.display.viewFrom, cm.display.viewTo); + cm.display.reportedViewFrom = cm.display.viewFrom; cm.display.reportedViewTo = cm.display.viewTo; + } + } - if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function() { marker.clear(); }); - - if (marker.readOnly) { - sawReadOnlySpans = true; - if (doc.history.done.length || doc.history.undone.length) - doc.clearHistory(); - } - if (marker.collapsed) { - marker.id = ++nextMarkerId; - marker.atomic = true; - } - if (cm) { - // Sync editor state - if (updateMaxLine) cm.curOp.updateMaxLine = true; - if (marker.collapsed) - regChange(cm, from.line, to.line + 1); - else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) - for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text"); - if (marker.atomic) reCheckSelection(cm.doc); - signalLater(cm, "markerAdded", cm, marker); - } - return marker; - } - - // SHARED TEXTMARKERS - - // A shared marker spans multiple linked documents. It is - // implemented as a meta-marker-object controlling multiple normal - // markers. - var SharedTextMarker = CodeMirror.SharedTextMarker = function(markers, primary) { - this.markers = markers; - this.primary = primary; - for (var i = 0; i < markers.length; ++i) - markers[i].parent = this; - }; - eventMixin(SharedTextMarker); - - SharedTextMarker.prototype.clear = function() { - if (this.explicitlyCleared) return; - this.explicitlyCleared = true; - for (var i = 0; i < this.markers.length; ++i) - this.markers[i].clear(); - signalLater(this, "clear"); - }; - SharedTextMarker.prototype.find = function(side, lineObj) { - return this.primary.find(side, lineObj); - }; - - function markTextShared(doc, from, to, options, type) { - options = copyObj(options); - options.shared = false; - var markers = [markText(doc, from, to, options, type)], primary = markers[0]; - var widget = options.widgetNode; - linkedDocs(doc, function(doc) { - if (widget) options.widgetNode = widget.cloneNode(true); - markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); - for (var i = 0; i < doc.linked.length; ++i) - if (doc.linked[i].isParent) return; - primary = lst(markers); - }); - return new SharedTextMarker(markers, primary); - } - - function findSharedMarkers(doc) { - return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), - function(m) { return m.parent; }); - } - - function copySharedMarkers(doc, markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], pos = marker.find(); - var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); - if (cmp(mFrom, mTo)) { - var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); - marker.markers.push(subMark); - subMark.parent = marker; - } - } - } - - function detachSharedMarkers(markers) { - for (var i = 0; i < markers.length; i++) { - var marker = markers[i], linked = [marker.primary.doc];; - linkedDocs(marker.primary.doc, function(d) { linked.push(d); }); - for (var j = 0; j < marker.markers.length; j++) { - var subMarker = marker.markers[j]; - if (indexOf(linked, subMarker.doc) == -1) { - subMarker.parent = null; - marker.markers.splice(j--, 1); - } - } - } - } - - // TEXTMARKER SPANS - - function MarkedSpan(marker, from, to) { - this.marker = marker; - this.from = from; this.to = to; - } - - // Search an array of spans for a span matching the given marker. - function getMarkedSpanFor(spans, marker) { - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.marker == marker) return span; - } - } - // Remove a span from an array, returning undefined if no spans are - // left (we don't store arrays for lines without spans). - function removeMarkedSpan(spans, span) { - for (var r, i = 0; i < spans.length; ++i) - if (spans[i] != span) (r || (r = [])).push(spans[i]); - return r; - } - // Add a span to a line. - function addMarkedSpan(line, span) { - line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; - span.marker.attachLine(line); - } - - // Used for the algorithm that adjusts markers for a change in the - // document. These functions cut an array of spans at a given - // character position, returning an array of remaining chunks (or - // undefined if nothing remains). - function markedSpansBefore(old, startCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); - if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); - (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); - } - } - return nw; - } - function markedSpansAfter(old, endCh, isInsert) { - if (old) for (var i = 0, nw; i < old.length; ++i) { - var span = old[i], marker = span.marker; - var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); - if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { - var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); - (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, - span.to == null ? null : span.to - endCh)); - } - } - return nw; - } - - // Given a change object, compute the new set of marker spans that - // cover the line in which the change took place. Removes spans - // entirely within the change, reconnects spans belonging to the - // same marker that appear on both sides of the change, and cuts off - // spans partially within the change. Returns an array of span - // arrays with one element for each line in (after) the change. - function stretchSpansOverChange(doc, change) { - if (change.full) return null; - var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; - var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; - if (!oldFirst && !oldLast) return null; - - var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; - // Get the spans that 'stick out' on both sides - var first = markedSpansBefore(oldFirst, startCh, isInsert); - var last = markedSpansAfter(oldLast, endCh, isInsert); - - // Next, merge those two ends - var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); - if (first) { - // Fix up .to properties of first - for (var i = 0; i < first.length; ++i) { - var span = first[i]; - if (span.to == null) { - var found = getMarkedSpanFor(last, span.marker); - if (!found) span.to = startCh; - else if (sameLine) span.to = found.to == null ? null : found.to + offset; - } - } - } - if (last) { - // Fix up .from in last (or move them into first in case of sameLine) - for (var i = 0; i < last.length; ++i) { - var span = last[i]; - if (span.to != null) span.to += offset; - if (span.from == null) { - var found = getMarkedSpanFor(first, span.marker); - if (!found) { - span.from = offset; - if (sameLine) (first || (first = [])).push(span); - } - } else { - span.from += offset; - if (sameLine) (first || (first = [])).push(span); - } - } - } - // Make sure we didn't create any zero-length spans - if (first) first = clearEmptySpans(first); - if (last && last != first) last = clearEmptySpans(last); - - var newMarkers = [first]; - if (!sameLine) { - // Fill gap with whole-line-spans - var gap = change.text.length - 2, gapMarkers; - if (gap > 0 && first) - for (var i = 0; i < first.length; ++i) - if (first[i].to == null) - (gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null)); - for (var i = 0; i < gap; ++i) - newMarkers.push(gapMarkers); - newMarkers.push(last); - } - return newMarkers; - } - - // Remove spans that are empty and don't have a clearWhenEmpty - // option of false. - function clearEmptySpans(spans) { - for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) - spans.splice(i--, 1); - } - if (!spans.length) return null; - return spans; - } - - // Used for un/re-doing changes from the history. Combines the - // result of computing the existing spans with the set of spans that - // existed in the history (so that deleting around a span and then - // undoing brings back the span). - function mergeOldSpans(doc, change) { - var old = getOldSpans(doc, change); - var stretched = stretchSpansOverChange(doc, change); - if (!old) return stretched; - if (!stretched) return old; - - for (var i = 0; i < old.length; ++i) { - var oldCur = old[i], stretchCur = stretched[i]; - if (oldCur && stretchCur) { - spans: for (var j = 0; j < stretchCur.length; ++j) { - var span = stretchCur[j]; - for (var k = 0; k < oldCur.length; ++k) - if (oldCur[k].marker == span.marker) continue spans; - oldCur.push(span); - } - } else if (stretchCur) { - old[i] = stretchCur; - } - } - return old; - } - - // Used to 'clip' out readOnly ranges when making a change. - function removeReadOnlyRanges(doc, from, to) { - var markers = null; - doc.iter(from.line, to.line + 1, function(line) { - if (line.markedSpans) for (var i = 0; i < line.markedSpans.length; ++i) { - var mark = line.markedSpans[i].marker; - if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) - (markers || (markers = [])).push(mark); - } - }); - if (!markers) return null; - var parts = [{from: from, to: to}]; - for (var i = 0; i < markers.length; ++i) { - var mk = markers[i], m = mk.find(0); - for (var j = 0; j < parts.length; ++j) { - var p = parts[j]; - if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; - var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); - if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) - newParts.push({from: p.from, to: m.from}); - if (dto > 0 || !mk.inclusiveRight && !dto) - newParts.push({from: m.to, to: p.to}); - parts.splice.apply(parts, newParts); - j += newParts.length - 1; - } - } - return parts; - } - - // Connect or disconnect spans from a line. - function detachMarkedSpans(line) { - var spans = line.markedSpans; - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.detachLine(line); - line.markedSpans = null; - } - function attachMarkedSpans(line, spans) { - if (!spans) return; - for (var i = 0; i < spans.length; ++i) - spans[i].marker.attachLine(line); - line.markedSpans = spans; - } - - // Helpers used when computing which overlapping collapsed span - // counts as the larger one. - function extraLeft(marker) { return marker.inclusiveLeft ? -1 : 0; } - function extraRight(marker) { return marker.inclusiveRight ? 1 : 0; } - - // Returns a number indicating which of two overlapping collapsed - // spans is larger (and thus includes the other). Falls back to - // comparing ids when the spans cover exactly the same range. - function compareCollapsedMarkers(a, b) { - var lenDiff = a.lines.length - b.lines.length; - if (lenDiff != 0) return lenDiff; - var aPos = a.find(), bPos = b.find(); - var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); - if (fromCmp) return -fromCmp; - var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); - if (toCmp) return toCmp; - return b.id - a.id; - } - - // Find out whether a line ends or starts in a collapsed span. If - // so, return the marker for that span. - function collapsedSpanAtSide(line, start) { - var sps = sawCollapsedSpans && line.markedSpans, found; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && - (!found || compareCollapsedMarkers(found, sp.marker) < 0)) - found = sp.marker; - } - return found; - } - function collapsedSpanAtStart(line) { return collapsedSpanAtSide(line, true); } - function collapsedSpanAtEnd(line) { return collapsedSpanAtSide(line, false); } - - // Test whether there exists a collapsed span that partially - // overlaps (covers the start or end, but not both) of a new span. - // Such overlap is not allowed. - function conflictingCollapsedRange(doc, lineNo, from, to, marker) { - var line = getLine(doc, lineNo); - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) { - var sp = sps[i]; - if (!sp.marker.collapsed) continue; - var found = sp.marker.find(0); - var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); - var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); - if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; - if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || - fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) - return true; + function updateDisplaySimple (cm, viewport) { + var update = new DisplayUpdate(cm, viewport); + if (updateDisplayIfNeeded(cm, update)) { + updateHeightsInViewport(cm); + postUpdateDisplay(cm, update); + var barMeasure = measureForScrollbars(cm); + updateSelection(cm); + setDocumentHeight(cm, barMeasure); + updateScrollbars(cm, barMeasure); + update.finish(); + } } - } - - // A visual line is a line as drawn on the screen. Folding, for - // example, can cause multiple logical lines to appear on the same - // visual line. This finds the start of the visual line that the - // given line is part of (usually that is the line itself). - function visualLine(line) { - var merged; - while (merged = collapsedSpanAtStart(line)) - line = merged.find(-1, true).line; - return line; - } - - // Returns an array of logical lines that continue the visual line - // started by the argument, or undefined if there are no such lines. - function visualLineContinued(line) { - var merged, lines; - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - (lines || (lines = [])).push(line); - } - return lines; - } - - // Get the line number of the start of the visual line that the - // given line number is part of. - function visualLineNo(doc, lineN) { - var line = getLine(doc, lineN), vis = visualLine(line); - if (line == vis) return lineN; - return lineNo(vis); - } - // Get the line number of the start of the next visual line after - // the given line. - function visualLineEndNo(doc, lineN) { - if (lineN > doc.lastLine()) return lineN; - var line = getLine(doc, lineN), merged; - if (!lineIsHidden(doc, line)) return lineN; - while (merged = collapsedSpanAtEnd(line)) - line = merged.find(1, true).line; - return lineNo(line) + 1; - } - - // Compute whether a line is hidden. Lines count as hidden when they - // are part of a visual line that starts with another line, or when - // they are entirely covered by collapsed, non-widget span. - function lineIsHidden(doc, line) { - var sps = sawCollapsedSpans && line.markedSpans; - if (sps) for (var sp, i = 0; i < sps.length; ++i) { - sp = sps[i]; - if (!sp.marker.collapsed) continue; - if (sp.from == null) return true; - if (sp.marker.widgetNode) continue; - if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) - return true; + + function setDocumentHeight (cm, measure) { + cm.display.sizer.style.minHeight = measure.docHeight + "px"; + var total = measure.docHeight + cm.display.barHeight; + cm.display.heightForcer.style.top = total + "px"; + cm.display.gutters.style.height = Math.max(total + scrollGap(cm), measure.clientHeight) + "px"; + } + + // Read the actual heights of the rendered lines, and update their + // stored heights to match. + function updateHeightsInViewport (cm) { + var display = cm.display; + var prevBottom = display.lineDiv.offsetTop; + for (var i = 0; i < display.view.length; i++) { + var cur = display.view[i], height; + if (cur.hidden) continue; + if (ie && ie_version < 8) { + var bot = cur.node.offsetTop + cur.node.offsetHeight; + height = bot - prevBottom; + prevBottom = bot; + } else { + var box = cur.node.getBoundingClientRect(); + height = box.bottom - box.top; + } + var diff = cur.line.height - height; + if (height < 2) height = textHeight(display); + if (diff > .001 || diff < -.001) { + updateLineHeight(cur.line, height); + updateWidgetHeight(cur.line); + if (cur.rest) { + for (var j = 0; j < cur.rest.length; j++) {updateWidgetHeight(cur.rest[j]);} + } + } + } } - } - function lineIsHiddenInner(doc, line, span) { - if (span.to == null) { - var end = span.marker.find(1, true); - return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); - } - if (span.marker.inclusiveRight && span.to == line.text.length) - return true; - for (var sp, i = 0; i < line.markedSpans.length; ++i) { - sp = line.markedSpans[i]; - if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && - (sp.to == null || sp.to != span.from) && - (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && - lineIsHiddenInner(doc, line, sp)) return true; + + // Read and store the height of line widgets associated with the + // given line. + function updateWidgetHeight (line) { + if (line.widgets) { + for (var i = 0; i < line.widgets.length; ++i) {line.widgets[i].height = line.widgets[i].node.offsetHeight;} + } } - } - - // LINE WIDGETS - - // Line widgets are block elements displayed above or below a line. - - var LineWidget = CodeMirror.LineWidget = function(doc, node, options) { - if (options) for (var opt in options) if (options.hasOwnProperty(opt)) - this[opt] = options[opt]; - this.doc = doc; - this.node = node; - }; - eventMixin(LineWidget); - - function adjustScrollWhenAboveVisible(cm, line, diff) { - if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) - addToScrollPos(cm, null, diff); - } - - LineWidget.prototype.clear = function() { - var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); - if (no == null || !ws) return; - for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); - if (!ws.length) line.widgets = null; - var height = widgetHeight(this); - updateLineHeight(line, Math.max(0, line.height - height)); - if (cm) runInOp(cm, function() { - adjustScrollWhenAboveVisible(cm, line, -height); - regLineChange(cm, no, "widget"); - }); - }; - LineWidget.prototype.changed = function() { - var oldH = this.height, cm = this.doc.cm, line = this.line; - this.height = null; - var diff = widgetHeight(this) - oldH; - if (!diff) return; - updateLineHeight(line, line.height + diff); - if (cm) runInOp(cm, function() { - cm.curOp.forceUpdate = true; - adjustScrollWhenAboveVisible(cm, line, diff); - }); - }; - - function widgetHeight(widget) { - if (widget.height != null) return widget.height; - var cm = widget.doc.cm; - if (!cm) return 0; - if (!contains(document.body, widget.node)) { - var parentStyle = "position: relative;"; - if (widget.coverGutter) - parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;"; - if (widget.noHScroll) - parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;"; - removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); - } - return widget.height = widget.node.offsetHeight; - } - - function addLineWidget(doc, handle, node, options) { - var widget = new LineWidget(doc, node, options); - var cm = doc.cm; - if (cm && widget.noHScroll) cm.display.alignWidgets = true; - changeLine(doc, handle, "widget", function(line) { - var widgets = line.widgets || (line.widgets = []); - if (widget.insertAt == null) widgets.push(widget); - else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); - widget.line = line; - if (cm && !lineIsHidden(doc, line)) { - var aboveVisible = heightAtLine(line) < doc.scrollTop; - updateLineHeight(line, line.height + widgetHeight(widget)); - if (aboveVisible) addToScrollPos(cm, null, widget.height); - cm.curOp.forceUpdate = true; - } - return true; - }); - return widget; - } - - // LINE DATA STRUCTURE - - // Line objects. These hold state related to a line, including - // highlighting info (the styles array). - var Line = CodeMirror.Line = function(text, markedSpans, estimateHeight) { - this.text = text; - attachMarkedSpans(this, markedSpans); - this.height = estimateHeight ? estimateHeight(this) : 1; - }; - eventMixin(Line); - Line.prototype.lineNo = function() { return lineNo(this); }; - - // Change the content (text, markers) of a line. Automatically - // invalidates cached information and tries to re-estimate the - // line's height. - function updateLine(line, text, markedSpans, estimateHeight) { - line.text = text; - if (line.stateAfter) line.stateAfter = null; - if (line.styles) line.styles = null; - if (line.order != null) line.order = null; - detachMarkedSpans(line); - attachMarkedSpans(line, markedSpans); - var estHeight = estimateHeight ? estimateHeight(line) : 1; - if (estHeight != line.height) updateLineHeight(line, estHeight); - } - - // Detach a line from the document tree and its markers. - function cleanUpLine(line) { - line.parent = null; - detachMarkedSpans(line); - } - - function extractLineClasses(type, output) { - if (type) for (;;) { - var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); - if (!lineClass) break; - type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); - var prop = lineClass[1] ? "bgClass" : "textClass"; - if (output[prop] == null) - output[prop] = lineClass[2]; - else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) - output[prop] += " " + lineClass[2]; - } - return type; - } - - function callBlankLine(mode, state) { - if (mode.blankLine) return mode.blankLine(state); - if (!mode.innerMode) return; - var inner = CodeMirror.innerMode(mode, state); - if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); - } - - function readToken(mode, stream, state, inner) { - for (var i = 0; i < 10; i++) { - if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; - var style = mode.token(stream, state); - if (stream.pos > stream.start) return style; - } - throw new Error("Mode " + mode.name + " failed to advance stream."); - } - - // Utility for getTokenAt and getLineTokens - function takeToken(cm, pos, precise, asArray) { - function getObj(copy) { - return {start: stream.start, end: stream.pos, - string: stream.current(), - type: style || null, - state: copy ? copyState(doc.mode, state) : state}; - } - - var doc = cm.doc, mode = doc.mode, style; - pos = clipPos(doc, pos); - var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); - var stream = new StringStream(line.text, cm.options.tabSize), tokens; - if (asArray) tokens = []; - while ((asArray || stream.pos < pos.ch) && !stream.eol()) { - stream.start = stream.pos; - style = readToken(mode, stream, state); - if (asArray) tokens.push(getObj(true)); - } - return asArray ? tokens : getObj(); - } - - // Run the given mode's parser over a line, calling f for each token. - function runMode(cm, text, mode, state, f, lineClasses, forceToEnd) { - var flattenSpans = mode.flattenSpans; - if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; - var curStart = 0, curStyle = null; - var stream = new StringStream(text, cm.options.tabSize), style; - var inner = cm.options.addModeClass && [null]; - if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); - while (!stream.eol()) { - if (stream.pos > cm.options.maxHighlightLength) { - flattenSpans = false; - if (forceToEnd) processLine(cm, text, state, stream.pos); - stream.pos = text.length; - style = null; - } else { - style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); - } - if (inner) { - var mName = inner[0].name; - if (mName) style = "m-" + (style ? mName + " " + style : mName); - } - if (!flattenSpans || curStyle != style) { - while (curStart < stream.start) { - curStart = Math.min(stream.start, curStart + 50000); - f(curStart, curStyle); - } - curStyle = style; - } - stream.start = stream.pos; - } - while (curStart < stream.pos) { - // Webkit seems to refuse to render text nodes longer than 57444 characters - var pos = Math.min(stream.pos, curStart + 50000); - f(pos, curStyle); - curStart = pos; - } - } - - // Compute a style array (an array starting with a mode generation - // -- for invalidation -- followed by pairs of end positions and - // style strings), which is used to highlight the tokens on the - // line. - function highlightLine(cm, line, state, forceToEnd) { - // A styles array always starts with a number identifying the - // mode/overlays that it is based on (for easy invalidation). - var st = [cm.state.modeGen], lineClasses = {}; - // Compute the base array of styles - runMode(cm, line.text, cm.doc.mode, state, function(end, style) { - st.push(end, style); - }, lineClasses, forceToEnd); - - // Run overlays, adjust style array. - for (var o = 0; o < cm.state.overlays.length; ++o) { - var overlay = cm.state.overlays[o], i = 1, at = 0; - runMode(cm, line.text, overlay.mode, true, function(end, style) { - var start = i; - // Ensure there's a token end at the current position, and that i points at it - while (at < end) { - var i_end = st[i]; - if (i_end > end) - st.splice(i, 1, end, st[i+1], i_end); - i += 2; - at = Math.min(end, i_end); - } - if (!style) return; - if (overlay.opaque) { - st.splice(start, i - start, end, "cm-overlay " + style); - i = start + 2; - } else { - for (; start < i; start += 2) { - var cur = st[start+1]; - st[start+1] = (cur ? cur + " " : "") + "cm-overlay " + style; - } - } - }, lineClasses); - } - - return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; - } - - function getLineStyles(cm, line, updateFrontier) { - if (!line.styles || line.styles[0] != cm.state.modeGen) { - var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); - line.styles = result.styles; - if (result.classes) line.styleClasses = result.classes; - else if (line.styleClasses) line.styleClasses = null; - if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; - } - return line.styles; - } - - // Lightweight form of highlight -- proceed over this line and - // update state, but don't save a style array. Used for lines that - // aren't currently visible. - function processLine(cm, text, state, startAt) { - var mode = cm.doc.mode; - var stream = new StringStream(text, cm.options.tabSize); - stream.start = stream.pos = startAt || 0; - if (text == "") callBlankLine(mode, state); - while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { - readToken(mode, stream, state); - stream.start = stream.pos; - } - } - - // Convert a style as returned by a mode (either null, or a string - // containing one or more styles) to a CSS style. This is cached, - // and also looks for line-wide styles. - var styleToClassCache = {}, styleToClassCacheWithMode = {}; - function interpretTokenStyle(style, options) { - if (!style || /^\s*$/.test(style)) return null; - var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; - return cache[style] || - (cache[style] = style.replace(/\S+/g, "cm-$&")); - } - - // Render the DOM representation of the text of a line. Also builds - // up a 'line map', which points at the DOM nodes that represent - // specific stretches of text, and is used by the measuring code. - // The returned object contains the DOM node, this map, and - // information about line-wide styles that were set by the mode. - function buildLineContent(cm, lineView) { - // The padding-right forces the element to have a 'border', which - // is needed on Webkit to be able to get line-level bounding - // rectangles for it (in measureChar). - var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); - var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, - col: 0, pos: 0, cm: cm, - splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; - lineView.measure = {}; - - // Iterate over the logical lines that make up this visual line. - for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { - var line = i ? lineView.rest[i - 1] : lineView.line, order; - builder.pos = 0; - builder.addToken = buildToken; - // Optionally wire in some hacks into the token-rendering - // algorithm, to deal with browser quirks. - if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) - builder.addToken = buildTokenBadBidi(builder.addToken, order); - builder.map = []; - var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); - insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); - if (line.styleClasses) { - if (line.styleClasses.bgClass) - builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || ""); - if (line.styleClasses.textClass) - builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || ""); - } - - // Ensure at least a single node is present, for measuring. - if (builder.map.length == 0) - builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure))); - - // Store the map and a cache object for the current logical line - if (i == 0) { - lineView.measure.map = builder.map; - lineView.measure.cache = {}; - } else { - (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); - (lineView.measure.caches || (lineView.measure.caches = [])).push({}); - } - } - - // See issue #2901 - if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className)) - builder.content.className = "cm-tab-wrap-hack"; - - signal(cm, "renderLine", cm, lineView.line, builder.pre); - if (builder.pre.className) - builder.textClass = joinClasses(builder.pre.className, builder.textClass || ""); - - return builder; - } - - function defaultSpecialCharPlaceholder(ch) { - var token = elt("span", "\u2022", "cm-invalidchar"); - token.title = "\\u" + ch.charCodeAt(0).toString(16); - token.setAttribute("aria-label", token.title); - return token; - } - - // Build up the DOM representation for a single token, and add it to - // the line map. Takes care to render special characters separately. - function buildToken(builder, text, style, startStyle, endStyle, title, css) { - if (!text) return; - var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; - var special = builder.cm.state.specialChars, mustWrap = false; - if (!special.test(text)) { - builder.col += text.length; - var content = document.createTextNode(displayText); - builder.map.push(builder.pos, builder.pos + text.length, content); - if (ie && ie_version < 9) mustWrap = true; - builder.pos += text.length; - } else { - var content = document.createDocumentFragment(), pos = 0; - while (true) { - special.lastIndex = pos; - var m = special.exec(text); - var skipped = m ? m.index - pos : text.length - pos; - if (skipped) { - var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); - if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); - else content.appendChild(txt); - builder.map.push(builder.pos, builder.pos + skipped, txt); - builder.col += skipped; - builder.pos += skipped; - } - if (!m) break; - pos += skipped + 1; - if (m[0] == "\t") { - var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; - var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); - txt.setAttribute("role", "presentation"); - txt.setAttribute("cm-text", "\t"); - builder.col += tabWidth; - } else { - var txt = builder.cm.options.specialCharPlaceholder(m[0]); - txt.setAttribute("cm-text", m[0]); - if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); - else content.appendChild(txt); - builder.col += 1; - } - builder.map.push(builder.pos, builder.pos + 1, txt); - builder.pos++; - } - } - if (style || startStyle || endStyle || mustWrap || css) { - var fullStyle = style || ""; - if (startStyle) fullStyle += startStyle; - if (endStyle) fullStyle += endStyle; - var token = elt("span", [content], fullStyle, css); - if (title) token.title = title; - return builder.content.appendChild(token); - } - builder.content.appendChild(content); - } - - function splitSpaces(old) { - var out = " "; - for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; - out += " "; - return out; - } - - // Work around nonsense dimensions being reported for stretches of - // right-to-left text. - function buildTokenBadBidi(inner, order) { - return function(builder, text, style, startStyle, endStyle, title, css) { - style = style ? style + " cm-force-border" : "cm-force-border"; - var start = builder.pos, end = start + text.length; - for (;;) { - // Find the part that overlaps with the start of this text - for (var i = 0; i < order.length; i++) { - var part = order[i]; - if (part.to > start && part.from <= start) break; - } - if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); - inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); - startStyle = null; - text = text.slice(part.to - start); - start = part.to; - } - }; - } - - function buildCollapsedSpan(builder, size, marker, ignoreWidget) { - var widget = !ignoreWidget && marker.widgetNode; - if (widget) builder.map.push(builder.pos, builder.pos + size, widget); - if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { - if (!widget) - widget = builder.content.appendChild(document.createElement("span")); - widget.setAttribute("cm-marker", marker.id); - } - if (widget) { - builder.cm.display.input.setUneditable(widget); - builder.content.appendChild(widget); - } - builder.pos += size; - } - - // Outputs a number of spans to make up a line, taking highlighting - // and marked text into account. - function insertLineContent(line, builder, styles) { - var spans = line.markedSpans, allText = line.text, at = 0; - if (!spans) { - for (var i = 1; i < styles.length; i+=2) - builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i+1], builder.cm.options)); - return; - } - - var len = allText.length, pos = 0, i = 1, text = "", style, css; - var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; - for (;;) { - if (nextChange == pos) { // Update current marker set - spanStyle = spanEndStyle = spanStartStyle = title = css = ""; - collapsed = null; nextChange = Infinity; - var foundBookmarks = []; - for (var j = 0; j < spans.length; ++j) { - var sp = spans[j], m = sp.marker; - if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { - foundBookmarks.push(m); - } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { - if (sp.to != null && sp.to != pos && nextChange > sp.to) { - nextChange = sp.to; - spanEndStyle = ""; - } - if (m.className) spanStyle += " " + m.className; - if (m.css) css = m.css; - if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; - if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; - if (m.title && !title) title = m.title; - if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) - collapsed = sp; - } else if (sp.from > pos && nextChange > sp.from) { - nextChange = sp.from; - } - } - if (collapsed && (collapsed.from || 0) == pos) { - buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, - collapsed.marker, collapsed.from == null); - if (collapsed.to == null) return; - if (collapsed.to == pos) collapsed = false; - } - if (!collapsed && foundBookmarks.length) for (var j = 0; j < foundBookmarks.length; ++j) - buildCollapsedSpan(builder, 0, foundBookmarks[j]); - } - if (pos >= len) break; - - var upto = Math.min(len, nextChange); - while (true) { - if (text) { - var end = pos + text.length; - if (!collapsed) { - var tokenText = end > upto ? text.slice(0, upto - pos) : text; - builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, - spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); - } - if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} - pos = end; - spanStartStyle = ""; - } - text = allText.slice(at, at = styles[i++]); - style = interpretTokenStyle(styles[i++], builder.cm.options); - } - } - } - - // DOCUMENT DATA STRUCTURE - - // By default, updates that start and end at the beginning of a line - // are treated specially, in order to make the association of line - // widgets and marker elements with the text behave more intuitive. - function isWholeLineUpdate(doc, change) { - return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && - (!doc.cm || doc.cm.options.wholeLineUpdateBefore); - } - - // Perform a change on the document data structure. - function updateDoc(doc, change, markedSpans, estimateHeight) { - function spansFor(n) {return markedSpans ? markedSpans[n] : null;} - function update(line, text, spans) { - updateLine(line, text, spans, estimateHeight); - signalLater(line, "change", line, change); - } - function linesFor(start, end) { - for (var i = start, result = []; i < end; ++i) - result.push(new Line(text[i], spansFor(i), estimateHeight)); - return result; - } - - var from = change.from, to = change.to, text = change.text; - var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); - var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; - - // Adjust the line structure - if (change.full) { - doc.insert(0, linesFor(0, text.length)); - doc.remove(text.length, doc.size - text.length); - } else if (isWholeLineUpdate(doc, change)) { - // This is a whole-line replace. Treated specially to make - // sure line objects move the way they are supposed to. - var added = linesFor(0, text.length - 1); - update(lastLine, lastLine.text, lastSpans); - if (nlines) doc.remove(from.line, nlines); - if (added.length) doc.insert(from.line, added); - } else if (firstLine == lastLine) { - if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); - } else { - var added = linesFor(1, text.length - 1); - added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - doc.insert(from.line + 1, added); - } - } else if (text.length == 1) { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); - doc.remove(from.line + 1, nlines); - } else { - update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); - update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); - var added = linesFor(1, text.length - 1); - if (nlines > 1) doc.remove(from.line + 1, nlines - 1); - doc.insert(from.line + 1, added); - } - - signalLater(doc, "change", doc, change); - } - - // The document is represented as a BTree consisting of leaves, with - // chunk of lines in them, and branches, with up to ten leaves or - // other branch nodes below them. The top node is always a branch - // node, and is the document object itself (meaning it has - // additional methods and properties). - // - // All nodes have parent links. The tree is used both to go from - // line numbers to line objects, and to go from objects to numbers. - // It also indexes by height, and is used to convert between height - // and line object, and to find the total height of the document. - // - // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html - - function LeafChunk(lines) { - this.lines = lines; - this.parent = null; - for (var i = 0, height = 0; i < lines.length; ++i) { - lines[i].parent = this; - height += lines[i].height; - } - this.height = height; - } - - LeafChunk.prototype = { - chunkSize: function() { return this.lines.length; }, - // Remove the n lines at offset 'at'. - removeInner: function(at, n) { - for (var i = at, e = at + n; i < e; ++i) { - var line = this.lines[i]; - this.height -= line.height; - cleanUpLine(line); - signalLater(line, "delete"); - } - this.lines.splice(at, n); - }, - // Helper used to collapse a small branch into a single leaf. - collapse: function(lines) { - lines.push.apply(lines, this.lines); - }, - // Insert the given array of lines at offset 'at', count them as - // having the given height. - insertInner: function(at, lines, height) { - this.height += height; - this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); - for (var i = 0; i < lines.length; ++i) lines[i].parent = this; - }, - // Used to iterate over a part of the tree. - iterN: function(at, n, op) { - for (var e = at + n; at < e; ++at) - if (op(this.lines[at])) return true; - } - }; - - function BranchChunk(children) { - this.children = children; - var size = 0, height = 0; - for (var i = 0; i < children.length; ++i) { - var ch = children[i]; - size += ch.chunkSize(); height += ch.height; - ch.parent = this; - } - this.size = size; - this.height = height; - this.parent = null; - } - - BranchChunk.prototype = { - chunkSize: function() { return this.size; }, - removeInner: function(at, n) { - this.size -= n; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var rm = Math.min(n, sz - at), oldHeight = child.height; - child.removeInner(at, rm); - this.height -= oldHeight - child.height; - if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } - if ((n -= rm) == 0) break; - at = 0; - } else at -= sz; - } - // If the result is smaller than 25 lines, ensure that it is a - // single leaf node. - if (this.size - n < 25 && - (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { - var lines = []; - this.collapse(lines); - this.children = [new LeafChunk(lines)]; - this.children[0].parent = this; - } - }, - collapse: function(lines) { - for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); - }, - insertInner: function(at, lines, height) { - this.size += lines.length; - this.height += height; - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at <= sz) { - child.insertInner(at, lines, height); - if (child.lines && child.lines.length > 50) { - while (child.lines.length > 50) { - var spilled = child.lines.splice(child.lines.length - 25, 25); - var newleaf = new LeafChunk(spilled); - child.height -= newleaf.height; - this.children.splice(i + 1, 0, newleaf); - newleaf.parent = this; - } - this.maybeSpill(); - } - break; - } - at -= sz; - } - }, - // When a node has grown, check whether it should be split. - maybeSpill: function() { - if (this.children.length <= 10) return; - var me = this; - do { - var spilled = me.children.splice(me.children.length - 5, 5); - var sibling = new BranchChunk(spilled); - if (!me.parent) { // Become the parent node - var copy = new BranchChunk(me.children); - copy.parent = me; - me.children = [copy, sibling]; - me = copy; - } else { - me.size -= sibling.size; - me.height -= sibling.height; - var myIndex = indexOf(me.parent.children, me); - me.parent.children.splice(myIndex + 1, 0, sibling); - } - sibling.parent = me.parent; - } while (me.children.length > 10); - me.parent.maybeSpill(); - }, - iterN: function(at, n, op) { - for (var i = 0; i < this.children.length; ++i) { - var child = this.children[i], sz = child.chunkSize(); - if (at < sz) { - var used = Math.min(n, sz - at); - if (child.iterN(at, used, op)) return true; - if ((n -= used) == 0) break; - at = 0; - } else at -= sz; - } - } - }; - - var nextDocId = 0; - var Doc = CodeMirror.Doc = function(text, mode, firstLine) { - if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); - if (firstLine == null) firstLine = 0; - - BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); - this.first = firstLine; - this.scrollTop = this.scrollLeft = 0; - this.cantEdit = false; - this.cleanGeneration = 1; - this.frontier = firstLine; - var start = Pos(firstLine, 0); - this.sel = simpleSelection(start); - this.history = new History(null); - this.id = ++nextDocId; - this.modeOption = mode; - - if (typeof text == "string") text = splitLines(text); - updateDoc(this, {from: start, to: start, text: text}); - setSelection(this, simpleSelection(start), sel_dontScroll); - }; - - Doc.prototype = createObj(BranchChunk.prototype, { - constructor: Doc, - // Iterate over the document. Supports two forms -- with only one - // argument, it calls that for each line in the document. With - // three, it iterates over the range given by the first two (with - // the second being non-inclusive). - iter: function(from, to, op) { - if (op) this.iterN(from - this.first, to - from, op); - else this.iterN(this.first, this.first + this.size, from); - }, - - // Non-public interface for adding and removing lines. - insert: function(at, lines) { - var height = 0; - for (var i = 0; i < lines.length; ++i) height += lines[i].height; - this.insertInner(at - this.first, lines, height); - }, - remove: function(at, n) { this.removeInner(at - this.first, n); }, - - // From here, the methods are part of the public interface. Most - // are also available from CodeMirror (editor) instances. - - getValue: function(lineSep, lineFilter) { - var lines = getLines(this, this.first, this.first + this.size, lineFilter); - if (lineSep === false) return lines; - return lines.join(lineSep || "\n"); - }, - setValue: docMethodOp(function(code) { - var top = Pos(this.first, 0), last = this.first + this.size - 1; - makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), - text: splitLines(code), origin: "setValue", full: true}, true); - setSelection(this, simpleSelection(top)); - }), - replaceRange: function(code, from, to, origin) { - from = clipPos(this, from); - to = to ? clipPos(this, to) : from; - replaceRange(this, code, from, to, origin); - }, - getRange: function(from, to, lineSep) { - var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); - if (lineSep === false) return lines; - return lines.join(lineSep || "\n"); - }, - - getLine: function(line) {var l = this.getLineHandle(line); return l && l.text;}, - - getLineHandle: function(line) {if (isLine(this, line)) return getLine(this, line);}, - getLineNumber: function(line) {return lineNo(line);}, - - getLineHandleVisualStart: function(line) { - if (typeof line == "number") line = getLine(this, line); - return visualLine(line); - }, - - lineCount: function() {return this.size;}, - firstLine: function() {return this.first;}, - lastLine: function() {return this.first + this.size - 1;}, - - clipPos: function(pos) {return clipPos(this, pos);}, - - getCursor: function(start) { - var range = this.sel.primary(), pos; - if (start == null || start == "head") pos = range.head; - else if (start == "anchor") pos = range.anchor; - else if (start == "end" || start == "to" || start === false) pos = range.to(); - else pos = range.from(); - return pos; - }, - listSelections: function() { return this.sel.ranges; }, - somethingSelected: function() {return this.sel.somethingSelected();}, - - setCursor: docMethodOp(function(line, ch, options) { - setSimpleSelection(this, clipPos(this, typeof line == "number" ? Pos(line, ch || 0) : line), null, options); - }), - setSelection: docMethodOp(function(anchor, head, options) { - setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); - }), - extendSelection: docMethodOp(function(head, other, options) { - extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); - }), - extendSelections: docMethodOp(function(heads, options) { - extendSelections(this, clipPosArray(this, heads, options)); - }), - extendSelectionsBy: docMethodOp(function(f, options) { - extendSelections(this, map(this.sel.ranges, f), options); - }), - setSelections: docMethodOp(function(ranges, primary, options) { - if (!ranges.length) return; - for (var i = 0, out = []; i < ranges.length; i++) - out[i] = new Range(clipPos(this, ranges[i].anchor), - clipPos(this, ranges[i].head)); - if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); - setSelection(this, normalizeSelection(out, primary), options); - }), - addSelection: docMethodOp(function(anchor, head, options) { - var ranges = this.sel.ranges.slice(0); - ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); - setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); - }), - - getSelection: function(lineSep) { - var ranges = this.sel.ranges, lines; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - lines = lines ? lines.concat(sel) : sel; - } - if (lineSep === false) return lines; - else return lines.join(lineSep || "\n"); - }, - getSelections: function(lineSep) { - var parts = [], ranges = this.sel.ranges; - for (var i = 0; i < ranges.length; i++) { - var sel = getBetween(this, ranges[i].from(), ranges[i].to()); - if (lineSep !== false) sel = sel.join(lineSep || "\n"); - parts[i] = sel; - } - return parts; - }, - replaceSelection: function(code, collapse, origin) { - var dup = []; - for (var i = 0; i < this.sel.ranges.length; i++) - dup[i] = code; - this.replaceSelections(dup, collapse, origin || "+input"); - }, - replaceSelections: docMethodOp(function(code, collapse, origin) { - var changes = [], sel = this.sel; - for (var i = 0; i < sel.ranges.length; i++) { - var range = sel.ranges[i]; - changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin}; - } - var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); - for (var i = changes.length - 1; i >= 0; i--) - makeChange(this, changes[i]); - if (newSel) setSelectionReplaceHistory(this, newSel); - else if (this.cm) ensureCursorVisible(this.cm); - }), - undo: docMethodOp(function() {makeChangeFromHistory(this, "undo");}), - redo: docMethodOp(function() {makeChangeFromHistory(this, "redo");}), - undoSelection: docMethodOp(function() {makeChangeFromHistory(this, "undo", true);}), - redoSelection: docMethodOp(function() {makeChangeFromHistory(this, "redo", true);}), - - setExtending: function(val) {this.extend = val;}, - getExtending: function() {return this.extend;}, - - historySize: function() { - var hist = this.history, done = 0, undone = 0; - for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; - for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; - return {undo: done, redo: undone}; - }, - clearHistory: function() {this.history = new History(this.history.maxGeneration);}, - - markClean: function() { - this.cleanGeneration = this.changeGeneration(true); - }, - changeGeneration: function(forceSplit) { - if (forceSplit) - this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null; - return this.history.generation; - }, - isClean: function (gen) { - return this.history.generation == (gen || this.cleanGeneration); - }, - - getHistory: function() { - return {done: copyHistoryArray(this.history.done), - undone: copyHistoryArray(this.history.undone)}; - }, - setHistory: function(histData) { - var hist = this.history = new History(this.history.maxGeneration); - hist.done = copyHistoryArray(histData.done.slice(0), null, true); - hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); - }, - - addLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - if (!line[prop]) line[prop] = cls; - else if (classTest(cls).test(line[prop])) return false; - else line[prop] += " " + cls; - return true; - }); - }), - removeLineClass: docMethodOp(function(handle, where, cls) { - return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function(line) { - var prop = where == "text" ? "textClass" - : where == "background" ? "bgClass" - : where == "gutter" ? "gutterClass" : "wrapClass"; - var cur = line[prop]; - if (!cur) return false; - else if (cls == null) line[prop] = null; - else { - var found = cur.match(classTest(cls)); - if (!found) return false; - var end = found.index + found[0].length; - line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + + // Do a bulk-read of the DOM positions and sizes needed to draw the + // view, so that we don't interleave reading and writing to the DOM. + function getDimensions (cm) { + var d = cm.display, left = {}, width = {}; + var gutterLeft = d.gutters.clientLeft; + for (var n = d.gutters.firstChild, i = 0; n; n = n.nextSibling, ++i) { + left[cm.options.gutters[i]] = n.offsetLeft + n.clientLeft + gutterLeft; + width[cm.options.gutters[i]] = n.clientWidth; } - return true; - }); - }), - - addLineWidget: docMethodOp(function(handle, node, options) { - return addLineWidget(this, handle, node, options); - }), - removeLineWidget: function(widget) { widget.clear(); }, - - markText: function(from, to, options) { - return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); - }, - setBookmark: function(pos, options) { - var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), - insertLeft: options && options.insertLeft, - clearWhenEmpty: false, shared: options && options.shared, - handleMouseEvents: options && options.handleMouseEvents}; - pos = clipPos(this, pos); - return markText(this, pos, pos, realOpts, "bookmark"); - }, - findMarksAt: function(pos) { - pos = clipPos(this, pos); - var markers = [], spans = getLine(this, pos.line).markedSpans; - if (spans) for (var i = 0; i < spans.length; ++i) { - var span = spans[i]; - if ((span.from == null || span.from <= pos.ch) && - (span.to == null || span.to >= pos.ch)) - markers.push(span.marker.parent || span.marker); - } - return markers; - }, - findMarks: function(from, to, filter) { - from = clipPos(this, from); to = clipPos(this, to); - var found = [], lineNo = from.line; - this.iter(from.line, to.line + 1, function(line) { - var spans = line.markedSpans; - if (spans) for (var i = 0; i < spans.length; i++) { - var span = spans[i]; - if (!(lineNo == from.line && from.ch > span.to || - span.from == null && lineNo != from.line|| - lineNo == to.line && span.from > to.ch) && - (!filter || filter(span.marker))) - found.push(span.marker.parent || span.marker); - } - ++lineNo; - }); - return found; - }, - getAllMarks: function() { - var markers = []; - this.iter(function(line) { - var sps = line.markedSpans; - if (sps) for (var i = 0; i < sps.length; ++i) - if (sps[i].from != null) markers.push(sps[i].marker); - }); - return markers; - }, - - posFromIndex: function(off) { - var ch, lineNo = this.first; - this.iter(function(line) { - var sz = line.text.length + 1; - if (sz > off) { ch = off; return true; } - off -= sz; - ++lineNo; - }); - return clipPos(this, Pos(lineNo, ch)); - }, - indexFromPos: function (coords) { - coords = clipPos(this, coords); - var index = coords.ch; - if (coords.line < this.first || coords.ch < 0) return 0; - this.iter(this.first, coords.line, function (line) { - index += line.text.length + 1; - }); - return index; - }, - - copy: function(copyHistory) { - var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); - doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; - doc.sel = this.sel; - doc.extend = false; - if (copyHistory) { - doc.history.undoDepth = this.history.undoDepth; - doc.setHistory(this.getHistory()); - } - return doc; - }, - - linkedDoc: function(options) { - if (!options) options = {}; - var from = this.first, to = this.first + this.size; - if (options.from != null && options.from > from) from = options.from; - if (options.to != null && options.to < to) to = options.to; - var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); - if (options.sharedHist) copy.history = this.history; - (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); - copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; - copySharedMarkers(copy, findSharedMarkers(this)); - return copy; - }, - unlinkDoc: function(other) { - if (other instanceof CodeMirror) other = other.doc; - if (this.linked) for (var i = 0; i < this.linked.length; ++i) { - var link = this.linked[i]; - if (link.doc != other) continue; - this.linked.splice(i, 1); - other.unlinkDoc(this); - detachSharedMarkers(findSharedMarkers(this)); - break; - } - // If the histories were shared, split them again - if (other.history == this.history) { - var splitIds = [other.id]; - linkedDocs(other, function(doc) {splitIds.push(doc.id);}, true); - other.history = new History(null); - other.history.done = copyHistoryArray(this.history.done, splitIds); - other.history.undone = copyHistoryArray(this.history.undone, splitIds); - } - }, - iterLinkedDocs: function(f) {linkedDocs(this, f);}, - - getMode: function() {return this.mode;}, - getEditor: function() {return this.cm;} - }); - - // Public alias. - Doc.prototype.eachLine = Doc.prototype.iter; - - // Set up methods on CodeMirror's prototype to redirect to the editor's document. - var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); - for (var prop in Doc.prototype) if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) - CodeMirror.prototype[prop] = (function(method) { - return function() {return method.apply(this.doc, arguments);}; - })(Doc.prototype[prop]); - - eventMixin(Doc); - - // Call f for all linked documents. - function linkedDocs(doc, f, sharedHistOnly) { - function propagate(doc, skip, sharedHist) { - if (doc.linked) for (var i = 0; i < doc.linked.length; ++i) { - var rel = doc.linked[i]; - if (rel.doc == skip) continue; - var shared = sharedHist && rel.sharedHist; - if (sharedHistOnly && !shared) continue; - f(rel.doc, shared); - propagate(rel.doc, doc, shared); - } - } - propagate(doc, null, true); - } - - // Attach a document to an editor. - function attachDoc(cm, doc) { - if (doc.cm) throw new Error("This document is already in use."); - cm.doc = doc; - doc.cm = cm; - estimateLineHeights(cm); - loadMode(cm); - if (!cm.options.lineWrapping) findMaxLine(cm); - cm.options.mode = doc.modeOption; - regChange(cm); - } - - // LINE UTILITIES - - // Find the line object corresponding to the given line number. - function getLine(doc, n) { - n -= doc.first; - if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); - for (var chunk = doc; !chunk.lines;) { - for (var i = 0;; ++i) { - var child = chunk.children[i], sz = child.chunkSize(); - if (n < sz) { chunk = child; break; } - n -= sz; - } - } - return chunk.lines[n]; - } - - // Get the part of a document between two positions, as an array of - // strings. - function getBetween(doc, start, end) { - var out = [], n = start.line; - doc.iter(start.line, end.line + 1, function(line) { - var text = line.text; - if (n == end.line) text = text.slice(0, end.ch); - if (n == start.line) text = text.slice(start.ch); - out.push(text); - ++n; + return {fixedPos: compensateForHScroll(d), + gutterTotalWidth: d.gutters.offsetWidth, + gutterLeft: left, + gutterWidth: width, + wrapperWidth: d.wrapper.clientWidth}; + } + + // Sync the actual display DOM structure with display.view, removing + // nodes for lines that are no longer in view, and creating the ones + // that are not there yet, and updating the ones that are out of + // date. + function patchDisplay (cm, updateNumbersFrom, dims) { + var display = cm.display, lineNumbers = cm.options.lineNumbers; + var container = display.lineDiv, cur = container.firstChild; + + function rm (node) { + var next = node.nextSibling; + // Works around a throw-scroll bug in OS X Webkit + if (webkit && mac && cm.display.currentWheelTarget == node) {node.style.display = "none";} else {node.parentNode.removeChild(node);} + return next; + } + + var view = display.view, lineN = display.viewFrom; + // Loop over the elements in the view, syncing cur (the DOM nodes + // in display.lineDiv) with the view as we go. + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (lineView.hidden) { + } else if (!lineView.node || lineView.node.parentNode != container) { // Not drawn yet + var node = buildLineElement(cm, lineView, lineN, dims); + container.insertBefore(node, cur); + } else { // Already drawn + while (cur != lineView.node) cur = rm(cur); + var updateNumber = lineNumbers && updateNumbersFrom != null && + updateNumbersFrom <= lineN && lineView.lineNumber; + if (lineView.changes) { + if (indexOf(lineView.changes, "gutter") > -1) updateNumber = false; + updateLineForChanges(cm, lineView, lineN, dims); + } + if (updateNumber) { + removeChildren(lineView.lineNumber); + lineView.lineNumber.appendChild(document.createTextNode(lineNumberFor(cm.options, lineN))); + } + cur = lineView.node.nextSibling; + } + lineN += lineView.size; + } + while (cur) cur = rm(cur); + } + + // When an aspect of a line changes, a string is added to + // lineView.changes. This updates the relevant part of the line's + // DOM structure. + function updateLineForChanges (cm, lineView, lineN, dims) { + for (var j = 0; j < lineView.changes.length; j++) { + var type = lineView.changes[j]; + if (type == "text") updateLineText(cm, lineView); + else if (type == "gutter") updateLineGutter(cm, lineView, lineN, dims); + else if (type == "class") updateLineClasses(lineView); + else if (type == "widget") updateLineWidgets(cm, lineView, dims); + } + lineView.changes = null; + } + + // Lines with gutter elements, widgets or a background class need to + // be wrapped, and have the extra elements added to the wrapper div + function ensureLineWrapped (lineView) { + if (lineView.node == lineView.text) { + lineView.node = elt("div", null, null, "position: relative"); + if (lineView.text.parentNode) {lineView.text.parentNode.replaceChild(lineView.node, lineView.text);} + lineView.node.appendChild(lineView.text); + if (ie && ie_version < 8) lineView.node.style.zIndex = 2; + } + return lineView.node; + } + + function updateLineBackground (lineView) { + var cls = lineView.bgClass ? lineView.bgClass + " " + (lineView.line.bgClass || "") : lineView.line.bgClass; + if (cls) cls += " CodeMirror-linebackground"; + if (lineView.background) { + if (cls) lineView.background.className = cls; + else { lineView.background.parentNode.removeChild(lineView.background); lineView.background = null; } + } else if (cls) { + var wrap = ensureLineWrapped(lineView); + lineView.background = wrap.insertBefore(elt("div", null, cls), wrap.firstChild); + } + } + + // Wrapper around buildLineContent which will reuse the structure + // in display.externalMeasured when possible. + function getLineContent (cm, lineView) { + var ext = cm.display.externalMeasured; + if (ext && ext.line == lineView.line) { + cm.display.externalMeasured = null; + lineView.measure = ext.measure; + return ext.built; + } + return buildLineContent(cm, lineView); + } + + // Redraw the line's text. Interacts with the background and text + // classes because the mode may output tokens that influence these + // classes. + function updateLineText (cm, lineView) { + var cls = lineView.text.className; + var built = getLineContent(cm, lineView); + if (lineView.text == lineView.node) lineView.node = built.pre; + lineView.text.parentNode.replaceChild(built.pre, lineView.text); + lineView.text = built.pre; + if (built.bgClass != lineView.bgClass || built.textClass != lineView.textClass) { + lineView.bgClass = built.bgClass; + lineView.textClass = built.textClass; + updateLineClasses(lineView); + } else if (cls) { + lineView.text.className = cls; + } + } + + function updateLineClasses (lineView) { + updateLineBackground(lineView); + if (lineView.line.wrapClass) {ensureLineWrapped(lineView).className = lineView.line.wrapClass;} else if (lineView.node != lineView.text) {lineView.node.className = "";} + var textClass = lineView.textClass ? lineView.textClass + " " + (lineView.line.textClass || "") : lineView.line.textClass; + lineView.text.className = textClass || ""; + } + + function updateLineGutter (cm, lineView, lineN, dims) { + if (lineView.gutter) { + lineView.node.removeChild(lineView.gutter); + lineView.gutter = null; + } + var markers = lineView.line.gutterMarkers; + if (cm.options.lineNumbers || markers) { + var wrap = ensureLineWrapped(lineView); + var gutterWrap = lineView.gutter = elt("div", null, "CodeMirror-gutter-wrapper", "left: " + + (cm.options.fixedGutter ? dims.fixedPos : -dims.gutterTotalWidth) + + "px; width: " + dims.gutterTotalWidth + "px"); + cm.display.input.setUneditable(gutterWrap); + wrap.insertBefore(gutterWrap, lineView.text); + if (lineView.line.gutterClass) {gutterWrap.className += " " + lineView.line.gutterClass;} + if (cm.options.lineNumbers && (!markers || !markers["CodeMirror-linenumbers"])) { + lineView.lineNumber = gutterWrap.appendChild( + elt("div", lineNumberFor(cm.options, lineN), + "CodeMirror-linenumber CodeMirror-gutter-elt", + "left: " + dims.gutterLeft["CodeMirror-linenumbers"] + "px; width: " + + cm.display.lineNumInnerWidth + "px")); + } + if (markers) { + for (var k = 0; k < cm.options.gutters.length; ++k) { + var id = cm.options.gutters[k], found = markers.hasOwnProperty(id) && markers[id]; + if (found) { + gutterWrap.appendChild(elt("div", [found], "CodeMirror-gutter-elt", "left: " + + dims.gutterLeft[id] + "px; width: " + dims.gutterWidth[id] + "px")); + } + } + } + } + } + + function updateLineWidgets (cm, lineView, dims) { + if (lineView.alignable) lineView.alignable = null; + for (var node = lineView.node.firstChild, next; node; node = next) { + var next = node.nextSibling; + if (node.className == "CodeMirror-linewidget") {lineView.node.removeChild(node);} + } + insertLineWidgets(cm, lineView, dims); + } + + // Build a line's DOM representation from scratch + function buildLineElement (cm, lineView, lineN, dims) { + var built = getLineContent(cm, lineView); + lineView.text = lineView.node = built.pre; + if (built.bgClass) lineView.bgClass = built.bgClass; + if (built.textClass) lineView.textClass = built.textClass; + + updateLineClasses(lineView); + updateLineGutter(cm, lineView, lineN, dims); + insertLineWidgets(cm, lineView, dims); + return lineView.node; + } + + // A lineView may contain multiple logical lines (when merged by + // collapsed spans). The widgets for all of them need to be drawn. + function insertLineWidgets (cm, lineView, dims) { + insertLineWidgetsFor(cm, lineView.line, lineView, dims, true); + if (lineView.rest) { + for (var i = 0; i < lineView.rest.length; i++) {insertLineWidgetsFor(cm, lineView.rest[i], lineView, dims, false);} + } + } + + function insertLineWidgetsFor (cm, line, lineView, dims, allowAbove) { + if (!line.widgets) return; + var wrap = ensureLineWrapped(lineView); + for (var i = 0, ws = line.widgets; i < ws.length; ++i) { + var widget = ws[i], node = elt("div", [widget.node], "CodeMirror-linewidget"); + if (!widget.handleMouseEvents) node.setAttribute("cm-ignore-events", "true"); + positionLineWidget(widget, node, lineView, dims); + cm.display.input.setUneditable(node); + if (allowAbove && widget.above) {wrap.insertBefore(node, lineView.gutter || lineView.text);} else {wrap.appendChild(node);} + signalLater(widget, "redraw"); + } + } + + function positionLineWidget (widget, node, lineView, dims) { + if (widget.noHScroll) { + (lineView.alignable || (lineView.alignable = [])).push(node); + var width = dims.wrapperWidth; + node.style.left = dims.fixedPos + "px"; + if (!widget.coverGutter) { + width -= dims.gutterTotalWidth; + node.style.paddingLeft = dims.gutterTotalWidth + "px"; + } + node.style.width = width + "px"; + } + if (widget.coverGutter) { + node.style.zIndex = 5; + node.style.position = "relative"; + if (!widget.noHScroll) node.style.marginLeft = -dims.gutterTotalWidth + "px"; + } + } + + // POSITION OBJECT + + // A Pos instance represents a position within the text. + var Pos = CodeMirror.Pos = function (line, ch) { + if (!(this instanceof Pos)) return new Pos(line, ch); + this.line = line; this.ch = ch; + }; + + // Compare two positions, return 0 if they are the same, a negative + // number when a is less, and a positive number otherwise. + var cmp = CodeMirror.cmpPos = function (a, b) { return a.line - b.line || a.ch - b.ch; }; + + function copyPos (x) {return Pos(x.line, x.ch);} + function maxPos (a, b) { return cmp(a, b) < 0 ? b : a; } + function minPos (a, b) { return cmp(a, b) < 0 ? a : b; } + + // INPUT HANDLING + + function ensureFocus (cm) { + if (!cm.state.focused) { cm.display.input.focus(); onFocus(cm); } + } + + function isReadOnly (cm) { + return cm.options.readOnly || cm.doc.cantEdit; + } + + // This will be set to an array of strings when copying, so that, + // when pasting, we know what kind of selections the copied text + // was made out of. + var lastCopied = null; + + function applyTextInput (cm, inserted, deleted, sel, origin) { + var doc = cm.doc; + cm.display.shift = false; + if (!sel) sel = doc.sel; + + var paste = cm.state.pasteIncoming || origin == "paste"; + var textLines = splitLines(inserted), multiPaste = null; + // When pasing N lines into N selections, insert one line per selection + if (paste && sel.ranges.length > 1) { + if (lastCopied && lastCopied.join("\n") == inserted) {multiPaste = sel.ranges.length % lastCopied.length == 0 && map(lastCopied, splitLines);} else if (textLines.length == sel.ranges.length) {multiPaste = map(textLines, function (l) { return [l]; });} + } + + // Normal behavior is to insert the new text into every selection + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + var from = range.from(), to = range.to(); + if (range.empty()) { + if (deleted && deleted > 0) // Handle deletion + {from = Pos(from.line, from.ch - deleted);} else if (cm.state.overwrite && !paste) // Handle overwrite + {to = Pos(to.line, Math.min(getLine(doc, to.line).text.length, to.ch + lst(textLines).length));} + } + var updateInput = cm.curOp.updateInput; + var changeEvent = {from: from, to: to, text: multiPaste ? multiPaste[i % multiPaste.length] : textLines, + origin: origin || (paste ? "paste" : cm.state.cutIncoming ? "cut" : "+input")}; + makeChange(cm.doc, changeEvent); + signalLater(cm, "inputRead", cm, changeEvent); + } + if (inserted && !paste) {triggerElectric(cm, inserted);} + + ensureCursorVisible(cm); + cm.curOp.updateInput = updateInput; + cm.curOp.typing = true; + cm.state.pasteIncoming = cm.state.cutIncoming = false; + } + + function handlePaste (e, cm) { + var pasted = e.clipboardData && e.clipboardData.getData("text/plain"); + if (pasted) { + e.preventDefault(); + runInOp(cm, function () { applyTextInput(cm, pasted, 0, null, "paste"); }); + return true; + } + } + + function triggerElectric (cm, inserted) { + // When an 'electric' character is inserted, immediately trigger a reindent + if (!cm.options.electricChars || !cm.options.smartIndent) return; + var sel = cm.doc.sel; + + for (var i = sel.ranges.length - 1; i >= 0; i--) { + var range = sel.ranges[i]; + if (range.head.ch > 100 || (i && sel.ranges[i - 1].head.line == range.head.line)) continue; + var mode = cm.getModeAt(range.head); + var indented = false; + if (mode.electricChars) { + for (var j = 0; j < mode.electricChars.length; j++) { + if (inserted.indexOf(mode.electricChars.charAt(j)) > -1) { + indented = indentLine(cm, range.head.line, "smart"); + break; + } + } + } else if (mode.electricInput) { + if (mode.electricInput.test(getLine(cm.doc, range.head.line).text.slice(0, range.head.ch))) {indented = indentLine(cm, range.head.line, "smart");} + } + if (indented) signalLater(cm, "electricInput", cm, range.head.line); + } + } + + function copyableRanges (cm) { + var text = [], ranges = []; + for (var i = 0; i < cm.doc.sel.ranges.length; i++) { + var line = cm.doc.sel.ranges[i].head.line; + var lineRange = {anchor: Pos(line, 0), head: Pos(line + 1, 0)}; + ranges.push(lineRange); + text.push(cm.getRange(lineRange.anchor, lineRange.head)); + } + return {text: text, ranges: ranges}; + } + + function disableBrowserMagic (field) { + field.setAttribute("autocorrect", "off"); + field.setAttribute("autocapitalize", "off"); + field.setAttribute("spellcheck", "false"); + } + + // TEXTAREA INPUT STYLE + + function TextareaInput (cm) { + this.cm = cm; + // See input.poll and input.reset + this.prevInput = ""; + + // Flag that indicates whether we expect input to appear real soon + // now (after some event like 'keypress' or 'input') and are + // polling intensively. + this.pollingFast = false; + // Self-resetting timeout for the poller + this.polling = new Delayed(); + // Tracks when input.reset has punted to just putting a short + // string into the textarea instead of the full selection. + this.inaccurateSelection = false; + // Used to work around IE issue with selection being forgotten when focus moves away from textarea + this.hasSelection = false; + this.composing = null; + } + + function hiddenTextarea () { + var te = elt("textarea", null, null, "position: absolute; padding: 0; width: 1px; height: 1em; outline: none"); + var div = elt("div", [te], null, "overflow: hidden; position: relative; width: 3px; height: 0px;"); + // The textarea is kept positioned near the cursor to prevent the + // fact that it'll be scrolled into view on input from scrolling + // our fake cursor out of view. On webkit, when wrap=off, paste is + // very slow. So make the area wide instead. + if (webkit) te.style.width = "1000px"; + else te.setAttribute("wrap", "off"); + // If border: 0; -- iOS fails to open keyboard (issue #1287) + if (ios) te.style.border = "1px solid black"; + disableBrowserMagic(te); + return div; + } + + TextareaInput.prototype = copyObj({ + init: function (display) { + var input = this, cm = this.cm; + + // Wraps and hides input textarea + var div = this.wrapper = hiddenTextarea(); + // The semihidden textarea that is focused when the editor is + // focused, and receives input. + var te = this.textarea = div.firstChild; + display.wrapper.insertBefore(div, display.wrapper.firstChild); + + // Needed to hide big blue blinking cursor on Mobile Safari (doesn't seem to work in iOS 8 anymore) + if (ios) te.style.width = "0px"; + + on(te, "input", function () { + if (ie && ie_version >= 9 && input.hasSelection) input.hasSelection = null; + input.poll(); + }); + + on(te, "paste", function (e) { + if (handlePaste(e, cm)) return true; + + cm.state.pasteIncoming = true; + input.fastPoll(); + }); + + function prepareCopyCut (e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (input.inaccurateSelection) { + input.prevInput = ""; + input.inaccurateSelection = false; + te.value = lastCopied.join("\n"); + selectInput(te); + } + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.setSelections(ranges.ranges, null, sel_dontScroll); + } else { + input.prevInput = ""; + te.value = ranges.text.join("\n"); + selectInput(te); + } + } + if (e.type == "cut") cm.state.cutIncoming = true; + } + on(te, "cut", prepareCopyCut); + on(te, "copy", prepareCopyCut); + + on(display.scroller, "paste", function (e) { + if (eventInWidget(display, e)) return; + cm.state.pasteIncoming = true; + input.focus(); + }); + + // Prevent normal selection in the editor (we handle our own) + on(display.lineSpace, "selectstart", function (e) { + if (!eventInWidget(display, e)) e_preventDefault(e); + }); + + on(te, "compositionstart", function () { + var start = cm.getCursor("from"); + input.composing = { + start: start, + range: cm.markText(start, cm.getCursor("to"), {className: "CodeMirror-composing"}) + }; + }); + on(te, "compositionend", function () { + if (input.composing) { + input.poll(); + input.composing.range.clear(); + input.composing = null; + } + }); + }, + + prepareSelection: function () { + // Redraw the selection and/or cursor + var cm = this.cm, display = cm.display, doc = cm.doc; + var result = prepareSelection(cm); + + // Move the hidden textarea near the cursor to prevent scrolling artifacts + if (cm.options.moveInputWithCursor) { + var headPos = cursorCoords(cm, doc.sel.primary().head, "div"); + var wrapOff = display.wrapper.getBoundingClientRect(), lineOff = display.lineDiv.getBoundingClientRect(); + result.teTop = Math.max(0, Math.min(display.wrapper.clientHeight - 10, + headPos.top + lineOff.top - wrapOff.top)); + result.teLeft = Math.max(0, Math.min(display.wrapper.clientWidth - 10, + headPos.left + lineOff.left - wrapOff.left)); + } + + return result; + }, + + showSelection: function (drawn) { + var cm = this.cm, display = cm.display; + removeChildrenAndAdd(display.cursorDiv, drawn.cursors); + removeChildrenAndAdd(display.selectionDiv, drawn.selection); + if (drawn.teTop != null) { + this.wrapper.style.top = drawn.teTop + "px"; + this.wrapper.style.left = drawn.teLeft + "px"; + } + }, + + // Reset the input to correspond to the selection (or to be empty, + // when not typing and nothing is selected) + reset: function (typing) { + if (this.contextMenuPending) return; + var minimal, selected, cm = this.cm, doc = cm.doc; + if (cm.somethingSelected()) { + this.prevInput = ""; + var range = doc.sel.primary(); + minimal = hasCopyEvent && + (range.to().line - range.from().line > 100 || (selected = cm.getSelection()).length > 1000); + var content = minimal ? "-" : selected || cm.getSelection(); + this.textarea.value = content; + if (cm.state.focused) selectInput(this.textarea); + if (ie && ie_version >= 9) this.hasSelection = content; + } else if (!typing) { + this.prevInput = this.textarea.value = ""; + if (ie && ie_version >= 9) this.hasSelection = null; + } + this.inaccurateSelection = minimal; + }, + + getField: function () { return this.textarea; }, + + supportsTouch: function () { return false; }, + + focus: function () { + if (this.cm.options.readOnly != "nocursor" && (!mobile || activeElt() != this.textarea)) { + try { this.textarea.focus(); } catch (e) {} // IE8 will throw if the textarea is display: none or not in DOM + } + }, + + blur: function () { this.textarea.blur(); }, + + resetPosition: function () { + this.wrapper.style.top = this.wrapper.style.left = 0; + }, + + receivedFocus: function () { this.slowPoll(); }, + + // Poll for input changes, using the normal rate of polling. This + // runs as long as the editor is focused. + slowPoll: function () { + var input = this; + if (input.pollingFast) return; + input.polling.set(this.cm.options.pollInterval, function () { + input.poll(); + if (input.cm.state.focused) input.slowPoll(); + }); + }, + + // When an event has just come in that is likely to add or change + // something in the input textarea, we poll faster, to ensure that + // the change appears on the screen quickly. + fastPoll: function () { + var missed = false, input = this; + input.pollingFast = true; + function p () { + var changed = input.poll(); + if (!changed && !missed) {missed = true; input.polling.set(60, p);} else {input.pollingFast = false; input.slowPoll();} + } + input.polling.set(20, p); + }, + + // Read input from the textarea, and update the document to match. + // When something is selected, it is present in the textarea, and + // selected (unless it is huge, in which case a placeholder is + // used). When nothing is selected, the cursor sits after previously + // seen text (can be empty), which is stored in prevInput (we must + // not reset the textarea when typing, because that breaks IME). + poll: function () { + var cm = this.cm, input = this.textarea, prevInput = this.prevInput; + // Since this is called a *lot*, try to bail out as cheaply as + // possible when it is clear that nothing happened. hasSelection + // will be the case when there is a lot of text in the textarea, + // in which case reading its value would be expensive. + if (this.contextMenuPending || !cm.state.focused || + (hasSelection(input) && !prevInput) || + isReadOnly(cm) || cm.options.disableInput || cm.state.keySeq) {return false;} + + var text = input.value; + // If nothing changed, bail. + if (text == prevInput && !cm.somethingSelected()) return false; + // Work around nonsensical selection resetting in IE9/10, and + // inexplicable appearance of private area unicode characters on + // some key combos in Mac (#2689). + if (ie && ie_version >= 9 && this.hasSelection === text || + mac && /[\uf700-\uf7ff]/.test(text)) { + cm.display.input.reset(); + return false; + } + + if (cm.doc.sel == cm.display.selForContextMenu) { + var first = text.charCodeAt(0); + if (first == 0x200b && !prevInput) prevInput = "\u200b"; + if (first == 0x21da) { this.reset(); return this.cm.execCommand("undo"); } + } + // Find the part of the input that is actually new + var same = 0, l = Math.min(prevInput.length, text.length); + while (same < l && prevInput.charCodeAt(same) == text.charCodeAt(same)) ++same; + + var self = this; + runInOp(cm, function () { + applyTextInput(cm, text.slice(same), prevInput.length - same, + null, self.composing ? "*compose" : null); + + // Don't leave long text in the textarea, since it makes further polling slow + if (text.length > 1000 || text.indexOf("\n") > -1) input.value = self.prevInput = ""; + else self.prevInput = text; + + if (self.composing) { + self.composing.range.clear(); + self.composing.range = cm.markText(self.composing.start, cm.getCursor("to"), + {className: "CodeMirror-composing"}); + } + }); + return true; + }, + + ensurePolled: function () { + if (this.pollingFast && this.poll()) this.pollingFast = false; + }, + + onKeyPress: function () { + if (ie && ie_version >= 9) this.hasSelection = null; + this.fastPoll(); + }, + + onContextMenu: function (e) { + var input = this, cm = input.cm, display = cm.display, te = input.textarea; + var pos = posFromMouse(cm, e), scrollPos = display.scroller.scrollTop; + if (!pos || presto) return; // Opera is difficult. + + // Reset the current text selection only if the click is done outside of the selection + // and 'resetSelectionOnContextMenu' option is true. + var reset = cm.options.resetSelectionOnContextMenu; + if (reset && cm.doc.sel.contains(pos) == -1) {operation(cm, setSelection)(cm.doc, simpleSelection(pos), sel_dontScroll);} + + var oldCSS = te.style.cssText; + input.wrapper.style.position = "absolute"; + te.style.cssText = "position: fixed; width: 30px; height: 30px; top: " + (e.clientY - 5) + + "px; left: " + (e.clientX - 5) + "px; z-index: 1000; background: " + + (ie ? "rgba(255, 255, 255, .05)" : "transparent") + + "; outline: none; border-width: 0; outline: none; overflow: hidden; opacity: .05; filter: alpha(opacity=5);"; + if (webkit) var oldScrollY = window.scrollY; // Work around Chrome issue (#2712) + display.input.focus(); + if (webkit) window.scrollTo(null, oldScrollY); + display.input.reset(); + // Adds "Select all" to context menu in FF + if (!cm.somethingSelected()) te.value = input.prevInput = " "; + input.contextMenuPending = true; + display.selForContextMenu = cm.doc.sel; + clearTimeout(display.detectingSelectAll); + + // Select-all will be greyed out if there's nothing to select, so + // this adds a zero-width space so that we can later check whether + // it got selected. + function prepareSelectAllHack () { + if (te.selectionStart != null) { + var selected = cm.somethingSelected(); + var extval = "\u200b" + (selected ? te.value : ""); + te.value = "\u21da"; // Used to catch context-menu undo + te.value = extval; + input.prevInput = selected ? "" : "\u200b"; + te.selectionStart = 1; te.selectionEnd = extval.length; + // Re-set this, in case some other handler touched the + // selection in the meantime. + display.selForContextMenu = cm.doc.sel; + } + } + function rehide () { + input.contextMenuPending = false; + input.wrapper.style.position = "relative"; + te.style.cssText = oldCSS; + if (ie && ie_version < 9) display.scrollbars.setScrollTop(display.scroller.scrollTop = scrollPos); + + // Try to detect the user choosing select-all + if (te.selectionStart != null) { + if (!ie || (ie && ie_version < 9)) prepareSelectAllHack(); + var i = 0, poll = function () { + if (display.selForContextMenu == cm.doc.sel && te.selectionStart == 0 && + te.selectionEnd > 0 && input.prevInput == "\u200b") {operation(cm, commands.selectAll)(cm);} else if (i++ < 10) display.detectingSelectAll = setTimeout(poll, 500); + else display.input.reset(); + }; + display.detectingSelectAll = setTimeout(poll, 200); + } + } + + if (ie && ie_version >= 9) prepareSelectAllHack(); + if (captureRightClick) { + e_stop(e); + var mouseup = function () { + off(window, "mouseup", mouseup); + setTimeout(rehide, 20); + }; + on(window, "mouseup", mouseup); + } else { + setTimeout(rehide, 50); + } + }, + + setUneditable: nothing, + + needsContentAttribute: false + }, TextareaInput.prototype); + + // CONTENTEDITABLE INPUT STYLE + + function ContentEditableInput (cm) { + this.cm = cm; + this.lastAnchorNode = this.lastAnchorOffset = this.lastFocusNode = this.lastFocusOffset = null; + this.polling = new Delayed(); + this.gracePeriod = false; + } + + ContentEditableInput.prototype = copyObj({ + init: function (display) { + var input = this, cm = input.cm; + var div = input.div = display.lineDiv; + div.contentEditable = "true"; + disableBrowserMagic(div); + + on(div, "paste", function (e) { handlePaste(e, cm); }); + + on(div, "compositionstart", function (e) { + var data = e.data; + input.composing = {sel: cm.doc.sel, data: data, startData: data}; + if (!data) return; + var prim = cm.doc.sel.primary(); + var line = cm.getLine(prim.head.line); + var found = line.indexOf(data, Math.max(0, prim.head.ch - data.length)); + if (found > -1 && found <= prim.head.ch) { + input.composing.sel = simpleSelection(Pos(prim.head.line, found), + Pos(prim.head.line, found + data.length)); + } + }); + on(div, "compositionupdate", function (e) { + input.composing.data = e.data; + }); + on(div, "compositionend", function (e) { + var ours = input.composing; + if (!ours) return; + if (e.data != ours.startData && !/\u200b/.test(e.data)) {ours.data = e.data;} + // Need a small delay to prevent other code (input event, + // selection polling) from doing damage when fired right after + // compositionend. + setTimeout(function () { + if (!ours.handled) {input.applyComposition(ours);} + if (input.composing == ours) {input.composing = null;} + }, 50); + }); + + on(div, "touchstart", function () { + input.forceCompositionEnd(); + }); + + on(div, "input", function () { + if (input.composing) return; + if (!input.pollContent()) {runInOp(input.cm, function () {regChange(cm);});} + }); + + function onCopyCut (e) { + if (cm.somethingSelected()) { + lastCopied = cm.getSelections(); + if (e.type == "cut") cm.replaceSelection("", null, "cut"); + } else if (!cm.options.lineWiseCopyCut) { + return; + } else { + var ranges = copyableRanges(cm); + lastCopied = ranges.text; + if (e.type == "cut") { + cm.operation(function () { + cm.setSelections(ranges.ranges, 0, sel_dontScroll); + cm.replaceSelection("", null, "cut"); + }); + } + } + // iOS exposes the clipboard API, but seems to discard content inserted into it + if (e.clipboardData && !ios) { + e.preventDefault(); + e.clipboardData.clearData(); + e.clipboardData.setData("text/plain", lastCopied.join("\n")); + } else { + // Old-fashioned briefly-focus-a-textarea hack + var kludge = hiddenTextarea(), te = kludge.firstChild; + cm.display.lineSpace.insertBefore(kludge, cm.display.lineSpace.firstChild); + te.value = lastCopied.join("\n"); + var hadFocus = document.activeElement; + selectInput(te); + setTimeout(function () { + cm.display.lineSpace.removeChild(kludge); + hadFocus.focus(); + }, 50); + } + } + on(div, "copy", onCopyCut); + on(div, "cut", onCopyCut); + }, + + prepareSelection: function () { + var result = prepareSelection(this.cm, false); + result.focus = this.cm.state.focused; + return result; + }, + + showSelection: function (info) { + if (!info || !this.cm.display.view.length) return; + if (info.focus) this.showPrimarySelection(); + this.showMultipleSelections(info); + }, + + showPrimarySelection: function () { + var sel = window.getSelection(), prim = this.cm.doc.sel.primary(); + var curAnchor = domToPos(this.cm, sel.anchorNode, sel.anchorOffset); + var curFocus = domToPos(this.cm, sel.focusNode, sel.focusOffset); + if (curAnchor && !curAnchor.bad && curFocus && !curFocus.bad && + cmp(minPos(curAnchor, curFocus), prim.from()) == 0 && + cmp(maxPos(curAnchor, curFocus), prim.to()) == 0) {return;} + + var start = posToDOM(this.cm, prim.from()); + var end = posToDOM(this.cm, prim.to()); + if (!start && !end) return; + + var view = this.cm.display.view; + var old = sel.rangeCount && sel.getRangeAt(0); + if (!start) { + start = {node: view[0].measure.map[2], offset: 0}; + } else if (!end) { // FIXME dangerously hacky + var measure = view[view.length - 1].measure; + var map = measure.maps ? measure.maps[measure.maps.length - 1] : measure.map; + end = {node: map[map.length - 1], offset: map[map.length - 2] - map[map.length - 3]}; + } + + try { var rng = range(start.node, start.offset, end.offset, end.node); } catch(e) {} // Our model of the DOM might be outdated, in which case the range we try to set can be impossible + if (rng) { + sel.removeAllRanges(); + sel.addRange(rng); + if (old && sel.anchorNode == null) sel.addRange(old); + else if (gecko) this.startGracePeriod(); + } + this.rememberSelection(); + }, + + startGracePeriod: function () { + var input = this; + clearTimeout(this.gracePeriod); + this.gracePeriod = setTimeout(function () { + input.gracePeriod = false; + if (input.selectionChanged()) {input.cm.operation(function () { input.cm.curOp.selectionChanged = true; });} + }, 20); + }, + + showMultipleSelections: function (info) { + removeChildrenAndAdd(this.cm.display.cursorDiv, info.cursors); + removeChildrenAndAdd(this.cm.display.selectionDiv, info.selection); + }, + + rememberSelection: function () { + var sel = window.getSelection(); + this.lastAnchorNode = sel.anchorNode; this.lastAnchorOffset = sel.anchorOffset; + this.lastFocusNode = sel.focusNode; this.lastFocusOffset = sel.focusOffset; + }, + + selectionInEditor: function () { + var sel = window.getSelection(); + if (!sel.rangeCount) return false; + var node = sel.getRangeAt(0).commonAncestorContainer; + return contains(this.div, node); + }, + + focus: function () { + if (this.cm.options.readOnly != "nocursor") this.div.focus(); + }, + blur: function () { this.div.blur(); }, + getField: function () { return this.div; }, + + supportsTouch: function () { return true; }, + + receivedFocus: function () { + var input = this; + if (this.selectionInEditor()) {this.pollSelection();} else {runInOp(this.cm, function () { input.cm.curOp.selectionChanged = true; });} + + function poll () { + if (input.cm.state.focused) { + input.pollSelection(); + input.polling.set(input.cm.options.pollInterval, poll); + } + } + this.polling.set(this.cm.options.pollInterval, poll); + }, + + selectionChanged: function () { + var sel = window.getSelection(); + return sel.anchorNode != this.lastAnchorNode || sel.anchorOffset != this.lastAnchorOffset || + sel.focusNode != this.lastFocusNode || sel.focusOffset != this.lastFocusOffset; + }, + + pollSelection: function () { + if (!this.composing && !this.gracePeriod && this.selectionChanged()) { + var sel = window.getSelection(), cm = this.cm; + this.rememberSelection(); + var anchor = domToPos(cm, sel.anchorNode, sel.anchorOffset); + var head = domToPos(cm, sel.focusNode, sel.focusOffset); + if (anchor && head) { + runInOp(cm, function () { + setSelection(cm.doc, simpleSelection(anchor, head), sel_dontScroll); + if (anchor.bad || head.bad) cm.curOp.selectionChanged = true; + }); + } + } + }, + + pollContent: function () { + var cm = this.cm, display = cm.display, sel = cm.doc.sel.primary(); + var from = sel.from(), to = sel.to(); + if (from.line < display.viewFrom || to.line > display.viewTo - 1) return false; + + var fromIndex; + if (from.line == display.viewFrom || (fromIndex = findViewIndex(cm, from.line)) == 0) { + var fromLine = lineNo(display.view[0].line); + var fromNode = display.view[0].node; + } else { + var fromLine = lineNo(display.view[fromIndex].line); + var fromNode = display.view[fromIndex - 1].node.nextSibling; + } + var toIndex = findViewIndex(cm, to.line); + if (toIndex == display.view.length - 1) { + var toLine = display.viewTo - 1; + var toNode = display.lineDiv.lastChild; + } else { + var toLine = lineNo(display.view[toIndex + 1].line) - 1; + var toNode = display.view[toIndex + 1].node.previousSibling; + } + + var newText = splitLines(domTextBetween(cm, fromNode, toNode, fromLine, toLine)); + var oldText = getBetween(cm.doc, Pos(fromLine, 0), Pos(toLine, getLine(cm.doc, toLine).text.length)); + while (newText.length > 1 && oldText.length > 1) { + if (lst(newText) == lst(oldText)) { newText.pop(); oldText.pop(); toLine--; } else if (newText[0] == oldText[0]) { newText.shift(); oldText.shift(); fromLine++; } else break; + } + + var cutFront = 0, cutEnd = 0; + var newTop = newText[0], oldTop = oldText[0], maxCutFront = Math.min(newTop.length, oldTop.length); + while (cutFront < maxCutFront && newTop.charCodeAt(cutFront) == oldTop.charCodeAt(cutFront)) {++cutFront;} + var newBot = lst(newText), oldBot = lst(oldText); + var maxCutEnd = Math.min(newBot.length - (newText.length == 1 ? cutFront : 0), + oldBot.length - (oldText.length == 1 ? cutFront : 0)); + while (cutEnd < maxCutEnd && + newBot.charCodeAt(newBot.length - cutEnd - 1) == oldBot.charCodeAt(oldBot.length - cutEnd - 1)) {++cutEnd;} + + newText[newText.length - 1] = newBot.slice(0, newBot.length - cutEnd); + newText[0] = newText[0].slice(cutFront); + + var chFrom = Pos(fromLine, cutFront); + var chTo = Pos(toLine, oldText.length ? lst(oldText).length - cutEnd : 0); + if (newText.length > 1 || newText[0] || cmp(chFrom, chTo)) { + replaceRange(cm.doc, newText, chFrom, chTo, "+input"); + return true; + } + }, + + ensurePolled: function () { + this.forceCompositionEnd(); + }, + reset: function () { + this.forceCompositionEnd(); + }, + forceCompositionEnd: function () { + if (!this.composing || this.composing.handled) return; + this.applyComposition(this.composing); + this.composing.handled = true; + this.div.blur(); + this.div.focus(); + }, + applyComposition: function (composing) { + if (composing.data && composing.data != composing.startData) {operation(this.cm, applyTextInput)(this.cm, composing.data, 0, composing.sel);} + }, + + setUneditable: function (node) { + node.setAttribute("contenteditable", "false"); + }, + + onKeyPress: function (e) { + e.preventDefault(); + operation(this.cm, applyTextInput)(this.cm, String.fromCharCode(e.charCode == null ? e.keyCode : e.charCode), 0); + }, + + onContextMenu: nothing, + resetPosition: nothing, + + needsContentAttribute: true + }, ContentEditableInput.prototype); + + function posToDOM (cm, pos) { + var view = findViewForLine(cm, pos.line); + if (!view || view.hidden) return null; + var line = getLine(cm.doc, pos.line); + var info = mapFromLineView(view, line, pos.line); + + var order = getOrder(line), side = "left"; + if (order) { + var partPos = getBidiPartAt(order, pos.ch); + side = partPos % 2 ? "right" : "left"; + } + var result = nodeAndOffsetInLineMap(info.map, pos.ch, side); + result.offset = result.collapse == "right" ? result.end : result.start; + return result; + } + + function badPos (pos, bad) { if (bad) pos.bad = true; return pos; } + + function domToPos (cm, node, offset) { + var lineNode; + if (node == cm.display.lineDiv) { + lineNode = cm.display.lineDiv.childNodes[offset]; + if (!lineNode) return badPos(cm.clipPos(Pos(cm.display.viewTo - 1)), true); + node = null; offset = 0; + } else { + for (lineNode = node; ; lineNode = lineNode.parentNode) { + if (!lineNode || lineNode == cm.display.lineDiv) return null; + if (lineNode.parentNode && lineNode.parentNode == cm.display.lineDiv) break; + } + } + for (var i = 0; i < cm.display.view.length; i++) { + var lineView = cm.display.view[i]; + if (lineView.node == lineNode) {return locateNodeInLineView(lineView, node, offset);} + } + } + + function locateNodeInLineView (lineView, node, offset) { + var wrapper = lineView.text.firstChild, bad = false; + if (!node || !contains(wrapper, node)) return badPos(Pos(lineNo(lineView.line), 0), true); + if (node == wrapper) { + bad = true; + node = wrapper.childNodes[offset]; + offset = 0; + if (!node) { + var line = lineView.rest ? lst(lineView.rest) : lineView.line; + return badPos(Pos(lineNo(line), line.text.length), bad); + } + } + + var textNode = node.nodeType == 3 ? node : null, topNode = node; + if (!textNode && node.childNodes.length == 1 && node.firstChild.nodeType == 3) { + textNode = node.firstChild; + if (offset) offset = textNode.nodeValue.length; + } + while (topNode.parentNode != wrapper) topNode = topNode.parentNode; + var measure = lineView.measure, maps = measure.maps; + + function find (textNode, topNode, offset) { + for (var i = -1; i < (maps ? maps.length : 0); i++) { + var map = i < 0 ? measure.map : maps[i]; + for (var j = 0; j < map.length; j += 3) { + var curNode = map[j + 2]; + if (curNode == textNode || curNode == topNode) { + var line = lineNo(i < 0 ? lineView.line : lineView.rest[i]); + var ch = map[j] + offset; + if (offset < 0 || curNode != textNode) ch = map[j + (offset ? 1 : 0)]; + return Pos(line, ch); + } + } + } + } + var found = find(textNode, topNode, offset); + if (found) return badPos(found, bad); + + // FIXME this is all really shaky. might handle the few cases it needs to handle, but likely to cause problems + for (var after = topNode.nextSibling, dist = textNode ? textNode.nodeValue.length - offset : 0; after; after = after.nextSibling) { + found = find(after, after.firstChild, 0); + if (found) {return badPos(Pos(found.line, found.ch - dist), bad);} + dist += after.textContent.length; + } + for (var before = topNode.previousSibling, dist = offset; before; before = before.previousSibling) { + found = find(before, before.firstChild, -1); + if (found) {return badPos(Pos(found.line, found.ch + dist), bad);} + dist += after.textContent.length; + } + } + + function domTextBetween (cm, from, to, fromLine, toLine) { + var text = "", closing = false; + function recognizeMarker (id) { return function (marker) { return marker.id == id; }; } + function walk (node) { + if (node.nodeType == 1) { + var cmText = node.getAttribute("cm-text"); + if (cmText != null) { + if (cmText == "") cmText = node.textContent.replace(/\u200b/g, ""); + text += cmText; + return; + } + var markerID = node.getAttribute("cm-marker"), range; + if (markerID) { + var found = cm.findMarks(Pos(fromLine, 0), Pos(toLine + 1, 0), recognizeMarker(+markerID)); + if (found.length && (range = found[0].find())) {text += getBetween(cm.doc, range.from, range.to).join("\n");} + return; + } + if (node.getAttribute("contenteditable") == "false") return; + for (var i = 0; i < node.childNodes.length; i++) {walk(node.childNodes[i]);} + if (/^(pre|div|p)$/i.test(node.nodeName)) {closing = true;} + } else if (node.nodeType == 3) { + var val = node.nodeValue; + if (!val) return; + if (closing) { + text += "\n"; + closing = false; + } + text += val; + } + } + for (;;) { + walk(from); + if (from == to) break; + from = from.nextSibling; + } + return text; + } + + CodeMirror.inputStyles = {textarea: TextareaInput, contenteditable: ContentEditableInput}; + + // SELECTION / CURSOR + + // Selection objects are immutable. A new one is created every time + // the selection changes. A selection is one or more non-overlapping + // (and non-touching) ranges, sorted, and an integer that indicates + // which one is the primary selection (the one that's scrolled into + // view, that getCursor returns, etc). + function Selection (ranges, primIndex) { + this.ranges = ranges; + this.primIndex = primIndex; + } + + Selection.prototype = { + primary: function () { return this.ranges[this.primIndex]; }, + equals: function (other) { + if (other == this) return true; + if (other.primIndex != this.primIndex || other.ranges.length != this.ranges.length) return false; + for (var i = 0; i < this.ranges.length; i++) { + var here = this.ranges[i], there = other.ranges[i]; + if (cmp(here.anchor, there.anchor) != 0 || cmp(here.head, there.head) != 0) return false; + } + return true; + }, + deepCopy: function () { + for (var out = [], i = 0; i < this.ranges.length; i++) {out[i] = new Range(copyPos(this.ranges[i].anchor), copyPos(this.ranges[i].head));} + return new Selection(out, this.primIndex); + }, + somethingSelected: function () { + for (var i = 0; i < this.ranges.length; i++) {if (!this.ranges[i].empty()) return true;} + return false; + }, + contains: function (pos, end) { + if (!end) end = pos; + for (var i = 0; i < this.ranges.length; i++) { + var range = this.ranges[i]; + if (cmp(end, range.from()) >= 0 && cmp(pos, range.to()) <= 0) {return i;} + } + return -1; + } + }; + + function Range (anchor, head) { + this.anchor = anchor; this.head = head; + } + + Range.prototype = { + from: function () { return minPos(this.anchor, this.head); }, + to: function () { return maxPos(this.anchor, this.head); }, + empty: function () { + return this.head.line == this.anchor.line && this.head.ch == this.anchor.ch; + } + }; + + // Take an unsorted, potentially overlapping set of ranges, and + // build a selection out of it. 'Consumes' ranges array (modifying + // it). + function normalizeSelection (ranges, primIndex) { + var prim = ranges[primIndex]; + ranges.sort(function (a, b) { return cmp(a.from(), b.from()); }); + primIndex = indexOf(ranges, prim); + for (var i = 1; i < ranges.length; i++) { + var cur = ranges[i], prev = ranges[i - 1]; + if (cmp(prev.to(), cur.from()) >= 0) { + var from = minPos(prev.from(), cur.from()), to = maxPos(prev.to(), cur.to()); + var inv = prev.empty() ? cur.from() == cur.head : prev.from() == prev.head; + if (i <= primIndex) --primIndex; + ranges.splice(--i, 2, new Range(inv ? to : from, inv ? from : to)); + } + } + return new Selection(ranges, primIndex); + } + + function simpleSelection (anchor, head) { + return new Selection([new Range(anchor, head || anchor)], 0); + } + + // Most of the external API clips given positions to make sure they + // actually exist within the document. + function clipLine (doc, n) {return Math.max(doc.first, Math.min(n, doc.first + doc.size - 1));} + function clipPos (doc, pos) { + if (pos.line < doc.first) return Pos(doc.first, 0); + var last = doc.first + doc.size - 1; + if (pos.line > last) return Pos(last, getLine(doc, last).text.length); + return clipToLen(pos, getLine(doc, pos.line).text.length); + } + function clipToLen (pos, linelen) { + var ch = pos.ch; + if (ch == null || ch > linelen) return Pos(pos.line, linelen); + else if (ch < 0) return Pos(pos.line, 0); + return pos; + } + function isLine (doc, l) {return l >= doc.first && l < doc.first + doc.size;} + function clipPosArray (doc, array) { + for (var out = [], i = 0; i < array.length; i++) out[i] = clipPos(doc, array[i]); + return out; + } + + // SELECTION UPDATES + + // The 'scroll' parameter given to many of these indicated whether + // the new cursor position should be scrolled into view after + // modifying the selection. + + // If shift is held or the extend flag is set, extends a range to + // include a given position (and optionally a second position). + // Otherwise, simply returns the range between the given positions. + // Used for cursor motion and such. + function extendRange (doc, range, head, other) { + if (doc.cm && doc.cm.display.shift || doc.extend) { + var anchor = range.anchor; + if (other) { + var posBefore = cmp(head, anchor) < 0; + if (posBefore != (cmp(other, anchor) < 0)) { + anchor = head; + head = other; + } else if (posBefore != (cmp(head, other) < 0)) { + head = other; + } + } + return new Range(anchor, head); + } + return new Range(other || head, head); + + } + + // Extend the primary selection range, discard the rest. + function extendSelection (doc, head, other, options) { + setSelection(doc, new Selection([extendRange(doc, doc.sel.primary(), head, other)], 0), options); + } + + // Extend all selections (pos is an array of selections with length + // equal the number of selections) + function extendSelections (doc, heads, options) { + for (var out = [], i = 0; i < doc.sel.ranges.length; i++) {out[i] = extendRange(doc, doc.sel.ranges[i], heads[i], null);} + var newSel = normalizeSelection(out, doc.sel.primIndex); + setSelection(doc, newSel, options); + } + + // Updates a single range in the selection. + function replaceOneSelection (doc, i, range, options) { + var ranges = doc.sel.ranges.slice(0); + ranges[i] = range; + setSelection(doc, normalizeSelection(ranges, doc.sel.primIndex), options); + } + + // Reset the selection to a single range. + function setSimpleSelection (doc, anchor, head, options) { + setSelection(doc, simpleSelection(anchor, head), options); + } + + // Give beforeSelectionChange handlers a change to influence a + // selection update. + function filterSelectionChange (doc, sel) { + var obj = { + ranges: sel.ranges, + update: function (ranges) { + this.ranges = []; + for (var i = 0; i < ranges.length; i++) { + this.ranges[i] = new Range(clipPos(doc, ranges[i].anchor), + clipPos(doc, ranges[i].head)); + } + } + }; + signal(doc, "beforeSelectionChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeSelectionChange", doc.cm, obj); + if (obj.ranges != sel.ranges) return normalizeSelection(obj.ranges, obj.ranges.length - 1); + return sel; + } + + function setSelectionReplaceHistory (doc, sel, options) { + var done = doc.history.done, last = lst(done); + if (last && last.ranges) { + done[done.length - 1] = sel; + setSelectionNoUndo(doc, sel, options); + } else { + setSelection(doc, sel, options); + } + } + + // Set a new selection. + function setSelection (doc, sel, options) { + setSelectionNoUndo(doc, sel, options); + addSelectionToHistory(doc, doc.sel, doc.cm ? doc.cm.curOp.id : NaN, options); + } + + function setSelectionNoUndo (doc, sel, options) { + if (hasHandler(doc, "beforeSelectionChange") || doc.cm && hasHandler(doc.cm, "beforeSelectionChange")) {sel = filterSelectionChange(doc, sel);} + + var bias = options && options.bias || + (cmp(sel.primary().head, doc.sel.primary().head) < 0 ? -1 : 1); + setSelectionInner(doc, skipAtomicInSelection(doc, sel, bias, true)); + + if (!(options && options.scroll === false) && doc.cm) {ensureCursorVisible(doc.cm);} + } + + function setSelectionInner (doc, sel) { + if (sel.equals(doc.sel)) return; + + doc.sel = sel; + + if (doc.cm) { + doc.cm.curOp.updateInput = doc.cm.curOp.selectionChanged = true; + signalCursorActivity(doc.cm); + } + signalLater(doc, "cursorActivity", doc); + } + + // Verify that the selection does not partially select any atomic + // marked ranges. + function reCheckSelection (doc) { + setSelectionInner(doc, skipAtomicInSelection(doc, doc.sel, null, false), sel_dontScroll); + } + + // Return a selection that does not partially select any atomic + // ranges. + function skipAtomicInSelection (doc, sel, bias, mayClear) { + var out; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + var newAnchor = skipAtomic(doc, range.anchor, bias, mayClear); + var newHead = skipAtomic(doc, range.head, bias, mayClear); + if (out || newAnchor != range.anchor || newHead != range.head) { + if (!out) out = sel.ranges.slice(0, i); + out[i] = new Range(newAnchor, newHead); + } + } + return out ? normalizeSelection(out, sel.primIndex) : sel; + } + + // Ensure a given position is not inside an atomic range. + function skipAtomic (doc, pos, bias, mayClear) { + var flipped = false, curPos = pos; + var dir = bias || 1; + doc.cantEdit = false; + search: for (;;) { + var line = getLine(doc, curPos.line); + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var sp = line.markedSpans[i], m = sp.marker; + if ((sp.from == null || (m.inclusiveLeft ? sp.from <= curPos.ch : sp.from < curPos.ch)) && + (sp.to == null || (m.inclusiveRight ? sp.to >= curPos.ch : sp.to > curPos.ch))) { + if (mayClear) { + signal(m, "beforeCursorEnter"); + if (m.explicitlyCleared) { + if (!line.markedSpans) break; + else {--i; continue;} + } + } + if (!m.atomic) continue; + var newPos = m.find(dir < 0 ? -1 : 1); + if (cmp(newPos, curPos) == 0) { + newPos.ch += dir; + if (newPos.ch < 0) { + if (newPos.line > doc.first) newPos = clipPos(doc, Pos(newPos.line - 1)); + else newPos = null; + } else if (newPos.ch > line.text.length) { + if (newPos.line < doc.first + doc.size - 1) newPos = Pos(newPos.line + 1, 0); + else newPos = null; + } + if (!newPos) { + if (flipped) { + // Driven in a corner -- no valid cursor position found at all + // -- try again *with* clearing, if we didn't already + if (!mayClear) return skipAtomic(doc, pos, bias, true); + // Otherwise, turn off editing until further notice, and return the start of the doc + doc.cantEdit = true; + return Pos(doc.first, 0); + } + flipped = true; newPos = pos; dir = -dir; + } + } + curPos = newPos; + continue search; + } + } + } + return curPos; + } + } + + // SELECTION DRAWING + + function updateSelection (cm) { + cm.display.input.showSelection(cm.display.input.prepareSelection()); + } + + function prepareSelection (cm, primary) { + var doc = cm.doc, result = {}; + var curFragment = result.cursors = document.createDocumentFragment(); + var selFragment = result.selection = document.createDocumentFragment(); + + for (var i = 0; i < doc.sel.ranges.length; i++) { + if (primary === false && i == doc.sel.primIndex) continue; + var range = doc.sel.ranges[i]; + var collapsed = range.empty(); + if (collapsed || cm.options.showCursorWhenSelecting) {drawSelectionCursor(cm, range, curFragment);} + if (!collapsed) {drawSelectionRange(cm, range, selFragment);} + } + return result; + } + + // Draws a cursor for the given range + function drawSelectionCursor (cm, range, output) { + var pos = cursorCoords(cm, range.head, "div", null, null, !cm.options.singleCursorHeightPerLine); + + var cursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor")); + cursor.style.left = pos.left + "px"; + cursor.style.top = pos.top + "px"; + cursor.style.height = Math.max(0, pos.bottom - pos.top) * cm.options.cursorHeight + "px"; + + if (pos.other) { + // Secondary cursor, shown when on a 'jump' in bi-directional text + var otherCursor = output.appendChild(elt("div", "\u00a0", "CodeMirror-cursor CodeMirror-secondarycursor")); + otherCursor.style.display = ""; + otherCursor.style.left = pos.other.left + "px"; + otherCursor.style.top = pos.other.top + "px"; + otherCursor.style.height = (pos.other.bottom - pos.other.top) * .85 + "px"; + } + } + + // Draws the given range as a highlighted selection + function drawSelectionRange (cm, range, output) { + var display = cm.display, doc = cm.doc; + var fragment = document.createDocumentFragment(); + var padding = paddingH(cm.display), leftSide = padding.left; + var rightSide = Math.max(display.sizerWidth, displayWidth(cm) - display.sizer.offsetLeft) - padding.right; + + function add (left, top, width, bottom) { + if (top < 0) top = 0; + top = Math.round(top); + bottom = Math.round(bottom); + fragment.appendChild(elt("div", null, "CodeMirror-selected", "position: absolute; left: " + left + + "px; top: " + top + "px; width: " + (width == null ? rightSide - left : width) + + "px; height: " + (bottom - top) + "px")); + } + + function drawForLine (line, fromArg, toArg) { + var lineObj = getLine(doc, line); + var lineLen = lineObj.text.length; + var start, end; + function coords (ch, bias) { + return charCoords(cm, Pos(line, ch), "div", lineObj, bias); + } + + iterateBidiSections(getOrder(lineObj), fromArg || 0, toArg == null ? lineLen : toArg, function (from, to, dir) { + var leftPos = coords(from, "left"), rightPos, left, right; + if (from == to) { + rightPos = leftPos; + left = right = leftPos.left; + } else { + rightPos = coords(to - 1, "right"); + if (dir == "rtl") { var tmp = leftPos; leftPos = rightPos; rightPos = tmp; } + left = leftPos.left; + right = rightPos.right; + } + if (fromArg == null && from == 0) left = leftSide; + if (rightPos.top - leftPos.top > 3) { // Different lines, draw top part + add(left, leftPos.top, null, leftPos.bottom); + left = leftSide; + if (leftPos.bottom < rightPos.top) add(left, leftPos.bottom, null, rightPos.top); + } + if (toArg == null && to == lineLen) right = rightSide; + if (!start || leftPos.top < start.top || leftPos.top == start.top && leftPos.left < start.left) {start = leftPos;} + if (!end || rightPos.bottom > end.bottom || rightPos.bottom == end.bottom && rightPos.right > end.right) {end = rightPos;} + if (left < leftSide + 1) left = leftSide; + add(left, rightPos.top, right - left, rightPos.bottom); + }); + return {start: start, end: end}; + } + + var sFrom = range.from(), sTo = range.to(); + if (sFrom.line == sTo.line) { + drawForLine(sFrom.line, sFrom.ch, sTo.ch); + } else { + var fromLine = getLine(doc, sFrom.line), toLine = getLine(doc, sTo.line); + var singleVLine = visualLine(fromLine) == visualLine(toLine); + var leftEnd = drawForLine(sFrom.line, sFrom.ch, singleVLine ? fromLine.text.length + 1 : null).end; + var rightStart = drawForLine(sTo.line, singleVLine ? 0 : null, sTo.ch).start; + if (singleVLine) { + if (leftEnd.top < rightStart.top - 2) { + add(leftEnd.right, leftEnd.top, null, leftEnd.bottom); + add(leftSide, rightStart.top, rightStart.left, rightStart.bottom); + } else { + add(leftEnd.right, leftEnd.top, rightStart.left - leftEnd.right, leftEnd.bottom); + } + } + if (leftEnd.bottom < rightStart.top) {add(leftSide, leftEnd.bottom, null, rightStart.top);} + } + + output.appendChild(fragment); + } + + // Cursor-blinking + function restartBlink (cm) { + if (!cm.state.focused) return; + var display = cm.display; + clearInterval(display.blinker); + var on = true; + display.cursorDiv.style.visibility = ""; + if (cm.options.cursorBlinkRate > 0) { + display.blinker = setInterval(function () { + display.cursorDiv.style.visibility = (on = !on) ? "" : "hidden"; + }, cm.options.cursorBlinkRate); + } else if (cm.options.cursorBlinkRate < 0) {display.cursorDiv.style.visibility = "hidden";} + } + + // HIGHLIGHT WORKER + + function startWorker (cm, time) { + if (cm.doc.mode.startState && cm.doc.frontier < cm.display.viewTo) {cm.state.highlight.set(time, bind(highlightWorker, cm));} + } + + function highlightWorker (cm) { + var doc = cm.doc; + if (doc.frontier < doc.first) doc.frontier = doc.first; + if (doc.frontier >= cm.display.viewTo) return; + var end = +new Date + cm.options.workTime; + var state = copyState(doc.mode, getStateBefore(cm, doc.frontier)); + var changedLines = []; + + doc.iter(doc.frontier, Math.min(doc.first + doc.size, cm.display.viewTo + 500), function (line) { + if (doc.frontier >= cm.display.viewFrom) { // Visible + var oldStyles = line.styles; + var highlighted = highlightLine(cm, line, state, true); + line.styles = highlighted.styles; + var oldCls = line.styleClasses, newCls = highlighted.classes; + if (newCls) line.styleClasses = newCls; + else if (oldCls) line.styleClasses = null; + var ischange = !oldStyles || oldStyles.length != line.styles.length || + oldCls != newCls && (!oldCls || !newCls || oldCls.bgClass != newCls.bgClass || oldCls.textClass != newCls.textClass); + for (var i = 0; !ischange && i < oldStyles.length; ++i) ischange = oldStyles[i] != line.styles[i]; + if (ischange) changedLines.push(doc.frontier); + line.stateAfter = copyState(doc.mode, state); + } else { + processLine(cm, line.text, state); + line.stateAfter = doc.frontier % 5 == 0 ? copyState(doc.mode, state) : null; + } + ++doc.frontier; + if (+new Date > end) { + startWorker(cm, cm.options.workDelay); + return true; + } + }); + if (changedLines.length) { + runInOp(cm, function () { + for (var i = 0; i < changedLines.length; i++) {regLineChange(cm, changedLines[i], "text");} + }); + } + } + + // Finds the line to start with when starting a parse. Tries to + // find a line with a stateAfter, so that it can start with a + // valid state. If that fails, it returns the line with the + // smallest indentation, which tends to need the least context to + // parse correctly. + function findStartLine (cm, n, precise) { + var minindent, minline, doc = cm.doc; + var lim = precise ? -1 : n - (cm.doc.mode.innerMode ? 1000 : 100); + for (var search = n; search > lim; --search) { + if (search <= doc.first) return doc.first; + var line = getLine(doc, search - 1); + if (line.stateAfter && (!precise || search <= doc.frontier)) return search; + var indented = countColumn(line.text, null, cm.options.tabSize); + if (minline == null || minindent > indented) { + minline = search - 1; + minindent = indented; + } + } + return minline; + } + + function getStateBefore (cm, n, precise) { + var doc = cm.doc, display = cm.display; + if (!doc.mode.startState) return true; + var pos = findStartLine(cm, n, precise), state = pos > doc.first && getLine(doc, pos - 1).stateAfter; + if (!state) state = startState(doc.mode); + else state = copyState(doc.mode, state); + doc.iter(pos, n, function (line) { + processLine(cm, line.text, state); + var save = pos == n - 1 || pos % 5 == 0 || pos >= display.viewFrom && pos < display.viewTo; + line.stateAfter = save ? copyState(doc.mode, state) : null; + ++pos; + }); + if (precise) doc.frontier = pos; + return state; + } + + // POSITION MEASUREMENT + + function paddingTop (display) {return display.lineSpace.offsetTop;} + function paddingVert (display) {return display.mover.offsetHeight - display.lineSpace.offsetHeight;} + function paddingH (display) { + if (display.cachedPaddingH) return display.cachedPaddingH; + var e = removeChildrenAndAdd(display.measure, elt("pre", "x")); + var style = window.getComputedStyle ? window.getComputedStyle(e) : e.currentStyle; + var data = {left: parseInt(style.paddingLeft), right: parseInt(style.paddingRight)}; + if (!isNaN(data.left) && !isNaN(data.right)) display.cachedPaddingH = data; + return data; + } + + function scrollGap (cm) { return scrollerGap - cm.display.nativeBarWidth; } + function displayWidth (cm) { + return cm.display.scroller.clientWidth - scrollGap(cm) - cm.display.barWidth; + } + function displayHeight (cm) { + return cm.display.scroller.clientHeight - scrollGap(cm) - cm.display.barHeight; + } + + // Ensure the lineView.wrapping.heights array is populated. This is + // an array of bottom offsets for the lines that make up a drawn + // line. When lineWrapping is on, there might be more than one + // height. + function ensureLineHeights (cm, lineView, rect) { + var wrapping = cm.options.lineWrapping; + var curWidth = wrapping && displayWidth(cm); + if (!lineView.measure.heights || wrapping && lineView.measure.width != curWidth) { + var heights = lineView.measure.heights = []; + if (wrapping) { + lineView.measure.width = curWidth; + var rects = lineView.text.firstChild.getClientRects(); + for (var i = 0; i < rects.length - 1; i++) { + var cur = rects[i], next = rects[i + 1]; + if (Math.abs(cur.bottom - next.bottom) > 2) {heights.push((cur.bottom + next.top) / 2 - rect.top);} + } + } + heights.push(rect.bottom - rect.top); + } + } + + // Find a line map (mapping character offsets to text nodes) and a + // measurement cache for the given line number. (A line view might + // contain multiple lines when collapsed ranges are present.) + function mapFromLineView (lineView, line, lineN) { + if (lineView.line == line) {return {map: lineView.measure.map, cache: lineView.measure.cache};} + for (var i = 0; i < lineView.rest.length; i++) { + if (lineView.rest[i] == line) {return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i]};} + } + for (var i = 0; i < lineView.rest.length; i++) { + if (lineNo(lineView.rest[i]) > lineN) {return {map: lineView.measure.maps[i], cache: lineView.measure.caches[i], before: true};} + } + } + + // Render a line into the hidden node display.externalMeasured. Used + // when measurement is needed for a line that's not in the viewport. + function updateExternalMeasurement (cm, line) { + line = visualLine(line); + var lineN = lineNo(line); + var view = cm.display.externalMeasured = new LineView(cm.doc, line, lineN); + view.lineN = lineN; + var built = view.built = buildLineContent(cm, view); + view.text = built.pre; + removeChildrenAndAdd(cm.display.lineMeasure, built.pre); + return view; + } + + // Get a {top, bottom, left, right} box (in line-local coordinates) + // for a given character. + function measureChar (cm, line, ch, bias) { + return measureCharPrepared(cm, prepareMeasureForLine(cm, line), ch, bias); + } + + // Find a line view that corresponds to the given line number. + function findViewForLine (cm, lineN) { + if (lineN >= cm.display.viewFrom && lineN < cm.display.viewTo) {return cm.display.view[findViewIndex(cm, lineN)];} + var ext = cm.display.externalMeasured; + if (ext && lineN >= ext.lineN && lineN < ext.lineN + ext.size) {return ext;} + } + + // Measurement can be split in two steps, the set-up work that + // applies to the whole line, and the measurement of the actual + // character. Functions like coordsChar, that need to do a lot of + // measurements in a row, can thus ensure that the set-up work is + // only done once. + function prepareMeasureForLine (cm, line) { + var lineN = lineNo(line); + var view = findViewForLine(cm, lineN); + if (view && !view.text) {view = null;} else if (view && view.changes) {updateLineForChanges(cm, view, lineN, getDimensions(cm));} + if (!view) {view = updateExternalMeasurement(cm, line);} + + var info = mapFromLineView(view, line, lineN); + return { + line: line, view: view, rect: null, + map: info.map, cache: info.cache, before: info.before, + hasHeights: false + }; + } + + // Given a prepared measurement object, measures the position of an + // actual character (or fetches it from the cache). + function measureCharPrepared (cm, prepared, ch, bias, varHeight) { + if (prepared.before) ch = -1; + var key = ch + (bias || ""), found; + if (prepared.cache.hasOwnProperty(key)) { + found = prepared.cache[key]; + } else { + if (!prepared.rect) {prepared.rect = prepared.view.text.getBoundingClientRect();} + if (!prepared.hasHeights) { + ensureLineHeights(cm, prepared.view, prepared.rect); + prepared.hasHeights = true; + } + found = measureCharInner(cm, prepared, ch, bias); + if (!found.bogus) prepared.cache[key] = found; + } + return {left: found.left, right: found.right, + top: varHeight ? found.rtop : found.top, + bottom: varHeight ? found.rbottom : found.bottom}; + } + + var nullRect = {left: 0, right: 0, top: 0, bottom: 0}; + + function nodeAndOffsetInLineMap (map, ch, bias) { + var node, start, end, collapse; + // First, search the line map for the text node corresponding to, + // or closest to, the target character. + for (var i = 0; i < map.length; i += 3) { + var mStart = map[i], mEnd = map[i + 1]; + if (ch < mStart) { + start = 0; end = 1; + collapse = "left"; + } else if (ch < mEnd) { + start = ch - mStart; + end = start + 1; + } else if (i == map.length - 3 || ch == mEnd && map[i + 3] > ch) { + end = mEnd - mStart; + start = end - 1; + if (ch >= mEnd) collapse = "right"; + } + if (start != null) { + node = map[i + 2]; + if (mStart == mEnd && bias == (node.insertLeft ? "left" : "right")) {collapse = bias;} + if (bias == "left" && start == 0) { + while (i && map[i - 2] == map[i - 3] && map[i - 1].insertLeft) { + node = map[(i -= 3) + 2]; + collapse = "left"; + } + } + if (bias == "right" && start == mEnd - mStart) { + while (i < map.length - 3 && map[i + 3] == map[i + 4] && !map[i + 5].insertLeft) { + node = map[(i += 3) + 2]; + collapse = "right"; + } + } + break; + } + } + return {node: node, start: start, end: end, collapse: collapse, coverStart: mStart, coverEnd: mEnd}; + } + + function measureCharInner (cm, prepared, ch, bias) { + var place = nodeAndOffsetInLineMap(prepared.map, ch, bias); + var node = place.node, start = place.start, end = place.end, collapse = place.collapse; + + var rect; + if (node.nodeType == 3) { // If it is a text node, use a range to retrieve the coordinates. + for (var i = 0; i < 4; i++) { // Retry a maximum of 4 times when nonsense rectangles are returned + while (start && isExtendingChar(prepared.line.text.charAt(place.coverStart + start))) --start; + while (place.coverStart + end < place.coverEnd && isExtendingChar(prepared.line.text.charAt(place.coverStart + end))) ++end; + if (ie && ie_version < 9 && start == 0 && end == place.coverEnd - place.coverStart) { + rect = node.parentNode.getBoundingClientRect(); + } else if (ie && cm.options.lineWrapping) { + var rects = range(node, start, end).getClientRects(); + if (rects.length) {rect = rects[bias == "right" ? rects.length - 1 : 0];} else {rect = nullRect;} + } else { + rect = range(node, start, end).getBoundingClientRect() || nullRect; + } + if (rect.left || rect.right || start == 0) break; + end = start; + start = start - 1; + collapse = "right"; + } + if (ie && ie_version < 11) rect = maybeUpdateRectForZooming(cm.display.measure, rect); + } else { // If it is a widget, simply get the box for the whole widget. + if (start > 0) collapse = bias = "right"; + var rects; + if (cm.options.lineWrapping && (rects = node.getClientRects()).length > 1) {rect = rects[bias == "right" ? rects.length - 1 : 0];} else {rect = node.getBoundingClientRect();} + } + if (ie && ie_version < 9 && !start && (!rect || !rect.left && !rect.right)) { + var rSpan = node.parentNode.getClientRects()[0]; + if (rSpan) {rect = {left: rSpan.left, right: rSpan.left + charWidth(cm.display), top: rSpan.top, bottom: rSpan.bottom};} else {rect = nullRect;} + } + + var rtop = rect.top - prepared.rect.top, rbot = rect.bottom - prepared.rect.top; + var mid = (rtop + rbot) / 2; + var heights = prepared.view.measure.heights; + for (var i = 0; i < heights.length - 1; i++) {if (mid < heights[i]) break;} + var top = i ? heights[i - 1] : 0, bot = heights[i]; + var result = {left: (collapse == "right" ? rect.right : rect.left) - prepared.rect.left, + right: (collapse == "left" ? rect.left : rect.right) - prepared.rect.left, + top: top, bottom: bot}; + if (!rect.left && !rect.right) result.bogus = true; + if (!cm.options.singleCursorHeightPerLine) { result.rtop = rtop; result.rbottom = rbot; } + + return result; + } + + // Work around problem with bounding client rects on ranges being + // returned incorrectly when zoomed on IE10 and below. + function maybeUpdateRectForZooming (measure, rect) { + if (!window.screen || screen.logicalXDPI == null || + screen.logicalXDPI == screen.deviceXDPI || !hasBadZoomedRects(measure)) {return rect;} + var scaleX = screen.logicalXDPI / screen.deviceXDPI; + var scaleY = screen.logicalYDPI / screen.deviceYDPI; + return {left: rect.left * scaleX, right: rect.right * scaleX, + top: rect.top * scaleY, bottom: rect.bottom * scaleY}; + } + + function clearLineMeasurementCacheFor (lineView) { + if (lineView.measure) { + lineView.measure.cache = {}; + lineView.measure.heights = null; + if (lineView.rest) { + for (var i = 0; i < lineView.rest.length; i++) {lineView.measure.caches[i] = {};} + } + } + } + + function clearLineMeasurementCache (cm) { + cm.display.externalMeasure = null; + removeChildren(cm.display.lineMeasure); + for (var i = 0; i < cm.display.view.length; i++) {clearLineMeasurementCacheFor(cm.display.view[i]);} + } + + function clearCaches (cm) { + clearLineMeasurementCache(cm); + cm.display.cachedCharWidth = cm.display.cachedTextHeight = cm.display.cachedPaddingH = null; + if (!cm.options.lineWrapping) cm.display.maxLineChanged = true; + cm.display.lineNumChars = null; + } + + function pageScrollX () { return window.pageXOffset || (document.documentElement || document.body).scrollLeft; } + function pageScrollY () { return window.pageYOffset || (document.documentElement || document.body).scrollTop; } + + // Converts a {top, bottom, left, right} box from line-local + // coordinates into another coordinate system. Context may be one of + // "line", "div" (display.lineDiv), "local"/null (editor), "window", + // or "page". + function intoCoordSystem (cm, lineObj, rect, context) { + if (lineObj.widgets) { + for (var i = 0; i < lineObj.widgets.length; ++i) { + if (lineObj.widgets[i].above) { + var size = widgetHeight(lineObj.widgets[i]); + rect.top += size; rect.bottom += size; + } + } + } + if (context == "line") return rect; + if (!context) context = "local"; + var yOff = heightAtLine(lineObj); + if (context == "local") yOff += paddingTop(cm.display); + else yOff -= cm.display.viewOffset; + if (context == "page" || context == "window") { + var lOff = cm.display.lineSpace.getBoundingClientRect(); + yOff += lOff.top + (context == "window" ? 0 : pageScrollY()); + var xOff = lOff.left + (context == "window" ? 0 : pageScrollX()); + rect.left += xOff; rect.right += xOff; + } + rect.top += yOff; rect.bottom += yOff; + return rect; + } + + // Coverts a box from "div" coords to another coordinate system. + // Context may be "window", "page", "div", or "local"/null. + function fromCoordSystem (cm, coords, context) { + if (context == "div") return coords; + var left = coords.left, top = coords.top; + // First move into "page" coordinate system + if (context == "page") { + left -= pageScrollX(); + top -= pageScrollY(); + } else if (context == "local" || !context) { + var localBox = cm.display.sizer.getBoundingClientRect(); + left += localBox.left; + top += localBox.top; + } + + var lineSpaceBox = cm.display.lineSpace.getBoundingClientRect(); + return {left: left - lineSpaceBox.left, top: top - lineSpaceBox.top}; + } + + function charCoords (cm, pos, context, lineObj, bias) { + if (!lineObj) lineObj = getLine(cm.doc, pos.line); + return intoCoordSystem(cm, lineObj, measureChar(cm, lineObj, pos.ch, bias), context); + } + + // Returns a box for a given cursor position, which may have an + // 'other' property containing the position of the secondary cursor + // on a bidi boundary. + function cursorCoords (cm, pos, context, lineObj, preparedMeasure, varHeight) { + lineObj = lineObj || getLine(cm.doc, pos.line); + if (!preparedMeasure) preparedMeasure = prepareMeasureForLine(cm, lineObj); + function get (ch, right) { + var m = measureCharPrepared(cm, preparedMeasure, ch, right ? "right" : "left", varHeight); + if (right) m.left = m.right; else m.right = m.left; + return intoCoordSystem(cm, lineObj, m, context); + } + function getBidi (ch, partPos) { + var part = order[partPos], right = part.level % 2; + if (ch == bidiLeft(part) && partPos && part.level < order[partPos - 1].level) { + part = order[--partPos]; + ch = bidiRight(part) - (part.level % 2 ? 0 : 1); + right = true; + } else if (ch == bidiRight(part) && partPos < order.length - 1 && part.level < order[partPos + 1].level) { + part = order[++partPos]; + ch = bidiLeft(part) - part.level % 2; + right = false; + } + if (right && ch == part.to && ch > part.from) return get(ch - 1); + return get(ch, right); + } + var order = getOrder(lineObj), ch = pos.ch; + if (!order) return get(ch); + var partPos = getBidiPartAt(order, ch); + var val = getBidi(ch, partPos); + if (bidiOther != null) val.other = getBidi(ch, bidiOther); + return val; + } + + // Used to cheaply estimate the coordinates for a position. Used for + // intermediate scroll updates. + function estimateCoords (cm, pos) { + var left = 0, pos = clipPos(cm.doc, pos); + if (!cm.options.lineWrapping) left = charWidth(cm.display) * pos.ch; + var lineObj = getLine(cm.doc, pos.line); + var top = heightAtLine(lineObj) + paddingTop(cm.display); + return {left: left, right: left, top: top, bottom: top + lineObj.height}; + } + + // Positions returned by coordsChar contain some extra information. + // xRel is the relative x position of the input coordinates compared + // to the found position (so xRel > 0 means the coordinates are to + // the right of the character position, for example). When outside + // is true, that means the coordinates lie outside the line's + // vertical range. + function PosWithInfo (line, ch, outside, xRel) { + var pos = Pos(line, ch); + pos.xRel = xRel; + if (outside) pos.outside = true; + return pos; + } + + // Compute the character position closest to the given coordinates. + // Input must be lineSpace-local ("div" coordinate system). + function coordsChar (cm, x, y) { + var doc = cm.doc; + y += cm.display.viewOffset; + if (y < 0) return PosWithInfo(doc.first, 0, true, -1); + var lineN = lineAtHeight(doc, y), last = doc.first + doc.size - 1; + if (lineN > last) {return PosWithInfo(doc.first + doc.size - 1, getLine(doc, last).text.length, true, 1);} + if (x < 0) x = 0; + + var lineObj = getLine(doc, lineN); + for (;;) { + var found = coordsCharInner(cm, lineObj, lineN, x, y); + var merged = collapsedSpanAtEnd(lineObj); + var mergedPos = merged && merged.find(0, true); + if (merged && (found.ch > mergedPos.from.ch || found.ch == mergedPos.from.ch && found.xRel > 0)) {lineN = lineNo(lineObj = mergedPos.to.line);} else {return found;} + } + } + + function coordsCharInner (cm, lineObj, lineNo, x, y) { + var innerOff = y - heightAtLine(lineObj); + var wrongLine = false, adjust = 2 * cm.display.wrapper.clientWidth; + var preparedMeasure = prepareMeasureForLine(cm, lineObj); + + function getX (ch) { + var sp = cursorCoords(cm, Pos(lineNo, ch), "line", lineObj, preparedMeasure); + wrongLine = true; + if (innerOff > sp.bottom) return sp.left - adjust; + else if (innerOff < sp.top) return sp.left + adjust; + wrongLine = false; + return sp.left; + } + + var bidi = getOrder(lineObj), dist = lineObj.text.length; + var from = lineLeft(lineObj), to = lineRight(lineObj); + var fromX = getX(from), fromOutside = wrongLine, toX = getX(to), toOutside = wrongLine; + + if (x > toX) return PosWithInfo(lineNo, to, toOutside, 1); + // Do a binary search between these bounds. + for (;;) { + if (bidi ? to == from || to == moveVisually(lineObj, from, 1) : to - from <= 1) { + var ch = x < fromX || x - fromX <= toX - x ? from : to; + var xDiff = x - (ch == from ? fromX : toX); + while (isExtendingChar(lineObj.text.charAt(ch))) ++ch; + var pos = PosWithInfo(lineNo, ch, ch == from ? fromOutside : toOutside, + xDiff < -1 ? -1 : xDiff > 1 ? 1 : 0); + return pos; + } + var step = Math.ceil(dist / 2), middle = from + step; + if (bidi) { + middle = from; + for (var i = 0; i < step; ++i) middle = moveVisually(lineObj, middle, 1); + } + var middleX = getX(middle); + if (middleX > x) {to = middle; toX = middleX; if (toOutside = wrongLine) toX += 1000; dist = step;} else {from = middle; fromX = middleX; fromOutside = wrongLine; dist -= step;} + } + } + + var measureText; + // Compute the default text height. + function textHeight (display) { + if (display.cachedTextHeight != null) return display.cachedTextHeight; + if (measureText == null) { + measureText = elt("pre"); + // Measure a bunch of lines, for browsers that compute + // fractional heights. + for (var i = 0; i < 49; ++i) { + measureText.appendChild(document.createTextNode("x")); + measureText.appendChild(elt("br")); + } + measureText.appendChild(document.createTextNode("x")); + } + removeChildrenAndAdd(display.measure, measureText); + var height = measureText.offsetHeight / 50; + if (height > 3) display.cachedTextHeight = height; + removeChildren(display.measure); + return height || 1; + } + + // Compute the default character width. + function charWidth (display) { + if (display.cachedCharWidth != null) return display.cachedCharWidth; + var anchor = elt("span", "xxxxxxxxxx"); + var pre = elt("pre", [anchor]); + removeChildrenAndAdd(display.measure, pre); + var rect = anchor.getBoundingClientRect(), width = (rect.right - rect.left) / 10; + if (width > 2) display.cachedCharWidth = width; + return width || 10; + } + + // OPERATIONS + + // Operations are used to wrap a series of changes to the editor + // state in such a way that each change won't have to update the + // cursor and display (which would be awkward, slow, and + // error-prone). Instead, display updates are batched and then all + // combined and executed at once. + + var operationGroup = null; + + var nextOpId = 0; + // Start a new operation. + function startOperation (cm) { + cm.curOp = { + cm: cm, + viewChanged: false, // Flag that indicates that lines might need to be redrawn + startHeight: cm.doc.height, // Used to detect need to update scrollbar + forceUpdate: false, // Used to force a redraw + updateInput: null, // Whether to reset the input textarea + typing: false, // Whether this reset should be careful to leave existing text (for compositing) + changeObjs: null, // Accumulated changes, for firing change events + cursorActivityHandlers: null, // Set of handlers to fire cursorActivity on + cursorActivityCalled: 0, // Tracks which cursorActivity handlers have been called already + selectionChanged: false, // Whether the selection needs to be redrawn + updateMaxLine: false, // Set when the widest line needs to be determined anew + scrollLeft: null, scrollTop: null, // Intermediate scroll position, not pushed to DOM yet + scrollToPos: null, // Used to scroll to a specific position + focus: false, + id: ++nextOpId // Unique ID + }; + if (operationGroup) { + operationGroup.ops.push(cm.curOp); + } else { + cm.curOp.ownsGroup = operationGroup = { + ops: [cm.curOp], + delayedCallbacks: [] + }; + } + } + + function fireCallbacksForOps (group) { + // Calls delayed callbacks and cursorActivity handlers until no + // new ones appear + var callbacks = group.delayedCallbacks, i = 0; + do { + for (; i < callbacks.length; i++) {callbacks[i]();} + for (var j = 0; j < group.ops.length; j++) { + var op = group.ops[j]; + if (op.cursorActivityHandlers) { + while (op.cursorActivityCalled < op.cursorActivityHandlers.length) {op.cursorActivityHandlers[op.cursorActivityCalled++](op.cm);} + } + } + } while (i < callbacks.length); + } + + // Finish an operation, updating the display and signalling delayed events + function endOperation (cm) { + var op = cm.curOp, group = op.ownsGroup; + if (!group) return; + + try { fireCallbacksForOps(group); } finally { + operationGroup = null; + for (var i = 0; i < group.ops.length; i++) {group.ops[i].cm.curOp = null;} + endOperations(group); + } + } + + // The DOM updates done when an operation finishes are batched so + // that the minimum number of relayouts are required. + function endOperations (group) { + var ops = group.ops; + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_R1(ops[i]);} + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + {endOperation_W1(ops[i]);} + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_R2(ops[i]);} + for (var i = 0; i < ops.length; i++) // Write DOM (maybe) + {endOperation_W2(ops[i]);} + for (var i = 0; i < ops.length; i++) // Read DOM + {endOperation_finish(ops[i]);} + } + + function endOperation_R1 (op) { + var cm = op.cm, display = cm.display; + maybeClipScrollbars(cm); + if (op.updateMaxLine) findMaxLine(cm); + + op.mustUpdate = op.viewChanged || op.forceUpdate || op.scrollTop != null || + op.scrollToPos && (op.scrollToPos.from.line < display.viewFrom || + op.scrollToPos.to.line >= display.viewTo) || + display.maxLineChanged && cm.options.lineWrapping; + op.update = op.mustUpdate && + new DisplayUpdate(cm, op.mustUpdate && {top: op.scrollTop, ensure: op.scrollToPos}, op.forceUpdate); + } + + function endOperation_W1 (op) { + op.updatedDisplay = op.mustUpdate && updateDisplayIfNeeded(op.cm, op.update); + } + + function endOperation_R2 (op) { + var cm = op.cm, display = cm.display; + if (op.updatedDisplay) updateHeightsInViewport(cm); + + op.barMeasure = measureForScrollbars(cm); + + // If the max line changed since it was last measured, measure it, + // and ensure the document's width matches it. + // updateDisplay_W2 will use these properties to do the actual resizing + if (display.maxLineChanged && !cm.options.lineWrapping) { + op.adjustWidthTo = measureChar(cm, display.maxLine, display.maxLine.text.length).left + 3; + cm.display.sizerWidth = op.adjustWidthTo; + op.barMeasure.scrollWidth = + Math.max(display.scroller.clientWidth, display.sizer.offsetLeft + op.adjustWidthTo + scrollGap(cm) + cm.display.barWidth); + op.maxScrollLeft = Math.max(0, display.sizer.offsetLeft + op.adjustWidthTo - displayWidth(cm)); + } + + if (op.updatedDisplay || op.selectionChanged) {op.preparedSelection = display.input.prepareSelection();} + } + + function endOperation_W2 (op) { + var cm = op.cm; + + if (op.adjustWidthTo != null) { + cm.display.sizer.style.minWidth = op.adjustWidthTo + "px"; + if (op.maxScrollLeft < cm.doc.scrollLeft) {setScrollLeft(cm, Math.min(cm.display.scroller.scrollLeft, op.maxScrollLeft), true);} + cm.display.maxLineChanged = false; + } + + if (op.preparedSelection) {cm.display.input.showSelection(op.preparedSelection);} + if (op.updatedDisplay) {setDocumentHeight(cm, op.barMeasure);} + if (op.updatedDisplay || op.startHeight != cm.doc.height) {updateScrollbars(cm, op.barMeasure);} + + if (op.selectionChanged) restartBlink(cm); + + if (cm.state.focused && op.updateInput) {cm.display.input.reset(op.typing);} + if (op.focus && op.focus == activeElt()) ensureFocus(op.cm); + } + + function endOperation_finish (op) { + var cm = op.cm, display = cm.display, doc = cm.doc; + + if (op.updatedDisplay) postUpdateDisplay(cm, op.update); + + // Abort mouse wheel delta measurement, when scrolling explicitly + if (display.wheelStartX != null && (op.scrollTop != null || op.scrollLeft != null || op.scrollToPos)) {display.wheelStartX = display.wheelStartY = null;} + + // Propagate the scroll position to the actual DOM scroller + if (op.scrollTop != null && (display.scroller.scrollTop != op.scrollTop || op.forceScroll)) { + doc.scrollTop = Math.max(0, Math.min(display.scroller.scrollHeight - display.scroller.clientHeight, op.scrollTop)); + display.scrollbars.setScrollTop(doc.scrollTop); + display.scroller.scrollTop = doc.scrollTop; + } + if (op.scrollLeft != null && (display.scroller.scrollLeft != op.scrollLeft || op.forceScroll)) { + doc.scrollLeft = Math.max(0, Math.min(display.scroller.scrollWidth - displayWidth(cm), op.scrollLeft)); + display.scrollbars.setScrollLeft(doc.scrollLeft); + display.scroller.scrollLeft = doc.scrollLeft; + alignHorizontally(cm); + } + // If we need to scroll a specific position into view, do so. + if (op.scrollToPos) { + var coords = scrollPosIntoView(cm, clipPos(doc, op.scrollToPos.from), + clipPos(doc, op.scrollToPos.to), op.scrollToPos.margin); + if (op.scrollToPos.isCursor && cm.state.focused) maybeScrollWindow(cm, coords); + } + + // Fire events for markers that are hidden/unidden by editing or + // undoing + var hidden = op.maybeHiddenMarkers, unhidden = op.maybeUnhiddenMarkers; + if (hidden) { + for (var i = 0; i < hidden.length; ++i) {if (!hidden[i].lines.length) signal(hidden[i], "hide");} + } + if (unhidden) { + for (var i = 0; i < unhidden.length; ++i) {if (unhidden[i].lines.length) signal(unhidden[i], "unhide");} + } + + if (display.wrapper.offsetHeight) {doc.scrollTop = cm.display.scroller.scrollTop;} + + // Fire change events, and delayed event handlers + if (op.changeObjs) {signal(cm, "changes", cm, op.changeObjs);} + if (op.update) {op.update.finish();} + } + + // Run the given function in an operation + function runInOp (cm, f) { + if (cm.curOp) return f(); + startOperation(cm); + try { return f(); } finally { endOperation(cm); } + } + // Wraps a function in an operation. Returns the wrapped function. + function operation (cm, f) { + return function () { + if (cm.curOp) return f.apply(cm, arguments); + startOperation(cm); + try { return f.apply(cm, arguments); } finally { endOperation(cm); } + }; + } + // Used to add methods to editor and doc instances, wrapping them in + // operations. + function methodOp (f) { + return function () { + if (this.curOp) return f.apply(this, arguments); + startOperation(this); + try { return f.apply(this, arguments); } finally { endOperation(this); } + }; + } + function docMethodOp (f) { + return function () { + var cm = this.cm; + if (!cm || cm.curOp) return f.apply(this, arguments); + startOperation(cm); + try { return f.apply(this, arguments); } finally { endOperation(cm); } + }; + } + + // VIEW TRACKING + + // These objects are used to represent the visible (currently drawn) + // part of the document. A LineView may correspond to multiple + // logical lines, if those are connected by collapsed ranges. + function LineView (doc, line, lineN) { + // The starting line + this.line = line; + // Continuing lines, if any + this.rest = visualLineContinued(line); + // Number of logical lines in this visual line + this.size = this.rest ? lineNo(lst(this.rest)) - lineN + 1 : 1; + this.node = this.text = null; + this.hidden = lineIsHidden(doc, line); + } + + // Create a range of LineView objects for the given lines. + function buildViewArray (cm, from, to) { + var array = [], nextPos; + for (var pos = from; pos < to; pos = nextPos) { + var view = new LineView(cm.doc, getLine(cm.doc, pos), pos); + nextPos = pos + view.size; + array.push(view); + } + return array; + } + + // Updates the display.view data structure for a given change to the + // document. From and to are in pre-change coordinates. Lendiff is + // the amount of lines added or subtracted by the change. This is + // used for changes that span multiple lines, or change the way + // lines are divided into visual lines. regLineChange (below) + // registers single-line changes. + function regChange (cm, from, to, lendiff) { + if (from == null) from = cm.doc.first; + if (to == null) to = cm.doc.first + cm.doc.size; + if (!lendiff) lendiff = 0; + + var display = cm.display; + if (lendiff && to < display.viewTo && + (display.updateLineNumbers == null || display.updateLineNumbers > from)) {display.updateLineNumbers = from;} + + cm.curOp.viewChanged = true; + + if (from >= display.viewTo) { // Change after + if (sawCollapsedSpans && visualLineNo(cm.doc, from) < display.viewTo) {resetView(cm);} + } else if (to <= display.viewFrom) { // Change before + if (sawCollapsedSpans && visualLineEndNo(cm.doc, to + lendiff) > display.viewFrom) { + resetView(cm); + } else { + display.viewFrom += lendiff; + display.viewTo += lendiff; + } + } else if (from <= display.viewFrom && to >= display.viewTo) { // Full overlap + resetView(cm); + } else if (from <= display.viewFrom) { // Top overlap + var cut = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cut) { + display.view = display.view.slice(cut.index); + display.viewFrom = cut.lineN; + display.viewTo += lendiff; + } else { + resetView(cm); + } + } else if (to >= display.viewTo) { // Bottom overlap + var cut = viewCuttingPoint(cm, from, from, -1); + if (cut) { + display.view = display.view.slice(0, cut.index); + display.viewTo = cut.lineN; + } else { + resetView(cm); + } + } else { // Gap in the middle + var cutTop = viewCuttingPoint(cm, from, from, -1); + var cutBot = viewCuttingPoint(cm, to, to + lendiff, 1); + if (cutTop && cutBot) { + display.view = display.view.slice(0, cutTop.index) + .concat(buildViewArray(cm, cutTop.lineN, cutBot.lineN)) + .concat(display.view.slice(cutBot.index)); + display.viewTo += lendiff; + } else { + resetView(cm); + } + } + + var ext = display.externalMeasured; + if (ext) { + if (to < ext.lineN) {ext.lineN += lendiff;} else if (from < ext.lineN + ext.size) {display.externalMeasured = null;} + } + } + + // Register a change to a single line. Type must be one of "text", + // "gutter", "class", "widget" + function regLineChange (cm, line, type) { + cm.curOp.viewChanged = true; + var display = cm.display, ext = cm.display.externalMeasured; + if (ext && line >= ext.lineN && line < ext.lineN + ext.size) {display.externalMeasured = null;} + + if (line < display.viewFrom || line >= display.viewTo) return; + var lineView = display.view[findViewIndex(cm, line)]; + if (lineView.node == null) return; + var arr = lineView.changes || (lineView.changes = []); + if (indexOf(arr, type) == -1) arr.push(type); + } + + // Clear the view. + function resetView (cm) { + cm.display.viewFrom = cm.display.viewTo = cm.doc.first; + cm.display.view = []; + cm.display.viewOffset = 0; + } + + // Find the view element corresponding to a given line. Return null + // when the line isn't visible. + function findViewIndex (cm, n) { + if (n >= cm.display.viewTo) return null; + n -= cm.display.viewFrom; + if (n < 0) return null; + var view = cm.display.view; + for (var i = 0; i < view.length; i++) { + n -= view[i].size; + if (n < 0) return i; + } + } + + function viewCuttingPoint (cm, oldN, newN, dir) { + var index = findViewIndex(cm, oldN), diff, view = cm.display.view; + if (!sawCollapsedSpans || newN == cm.doc.first + cm.doc.size) {return {index: index, lineN: newN};} + for (var i = 0, n = cm.display.viewFrom; i < index; i++) {n += view[i].size;} + if (n != oldN) { + if (dir > 0) { + if (index == view.length - 1) return null; + diff = (n + view[index].size) - oldN; + index++; + } else { + diff = n - oldN; + } + oldN += diff; newN += diff; + } + while (visualLineNo(cm.doc, newN) != newN) { + if (index == (dir < 0 ? 0 : view.length - 1)) return null; + newN += dir * view[index - (dir < 0 ? 1 : 0)].size; + index += dir; + } + return {index: index, lineN: newN}; + } + + // Force the view to cover a given range, adding empty view element + // or clipping off existing ones as needed. + function adjustView (cm, from, to) { + var display = cm.display, view = display.view; + if (view.length == 0 || from >= display.viewTo || to <= display.viewFrom) { + display.view = buildViewArray(cm, from, to); + display.viewFrom = from; + } else { + if (display.viewFrom > from) {display.view = buildViewArray(cm, from, display.viewFrom).concat(display.view);} else if (display.viewFrom < from) {display.view = display.view.slice(findViewIndex(cm, from));} + display.viewFrom = from; + if (display.viewTo < to) {display.view = display.view.concat(buildViewArray(cm, display.viewTo, to));} else if (display.viewTo > to) {display.view = display.view.slice(0, findViewIndex(cm, to));} + } + display.viewTo = to; + } + + // Count the number of lines in the view whose DOM representation is + // out of date (or nonexistent). + function countDirtyView (cm) { + var view = cm.display.view, dirty = 0; + for (var i = 0; i < view.length; i++) { + var lineView = view[i]; + if (!lineView.hidden && (!lineView.node || lineView.changes)) ++dirty; + } + return dirty; + } + + // EVENT HANDLERS + + // Attach the necessary event handlers when initializing the editor + function registerEventHandlers (cm) { + var d = cm.display; + on(d.scroller, "mousedown", operation(cm, onMouseDown)); + // Older IE's will not fire a second mousedown for a double click + if (ie && ie_version < 11) { + on(d.scroller, "dblclick", operation(cm, function (e) { + if (signalDOMEvent(cm, e)) return; + var pos = posFromMouse(cm, e); + if (!pos || clickInGutter(cm, e) || eventInWidget(cm.display, e)) return; + e_preventDefault(e); + var word = cm.findWordAt(pos); + extendSelection(cm.doc, word.anchor, word.head); + })); + } else {on(d.scroller, "dblclick", function (e) { signalDOMEvent(cm, e) || e_preventDefault(e); });} + // Some browsers fire contextmenu *after* opening the menu, at + // which point we can't mess with it anymore. Context menu is + // handled in onMouseDown for these browsers. + if (!captureRightClick) on(d.scroller, "contextmenu", function (e) {onContextMenu(cm, e);}); + + // Used to suppress mouse event handling when a touch happens + var touchFinished, prevTouch = {end: 0}; + function finishTouch () { + if (d.activeTouch) { + touchFinished = setTimeout(function () {d.activeTouch = null;}, 1000); + prevTouch = d.activeTouch; + prevTouch.end = +new Date; + } + } + function isMouseLikeTouchEvent (e) { + if (e.touches.length != 1) return false; + var touch = e.touches[0]; + return touch.radiusX <= 1 && touch.radiusY <= 1; + } + function farAway (touch, other) { + if (other.left == null) return true; + var dx = other.left - touch.left, dy = other.top - touch.top; + return dx * dx + dy * dy > 20 * 20; + } + on(d.scroller, "touchstart", function (e) { + if (!isMouseLikeTouchEvent(e)) { + clearTimeout(touchFinished); + var now = +new Date; + d.activeTouch = {start: now, moved: false, + prev: now - prevTouch.end <= 300 ? prevTouch : null}; + if (e.touches.length == 1) { + d.activeTouch.left = e.touches[0].pageX; + d.activeTouch.top = e.touches[0].pageY; + } + } + }); + on(d.scroller, "touchmove", function () { + if (d.activeTouch) d.activeTouch.moved = true; + }); + on(d.scroller, "touchend", function (e) { + var touch = d.activeTouch; + if (touch && !eventInWidget(d, e) && touch.left != null && + !touch.moved && new Date - touch.start < 300) { + var pos = cm.coordsChar(d.activeTouch, "page"), range; + if (!touch.prev || farAway(touch, touch.prev)) // Single tap + {range = new Range(pos, pos);} else if (!touch.prev.prev || farAway(touch, touch.prev.prev)) // Double tap + {range = cm.findWordAt(pos);} else // Triple tap + {range = new Range(Pos(pos.line, 0), clipPos(cm.doc, Pos(pos.line + 1, 0)));} + cm.setSelection(range.anchor, range.head); + cm.focus(); + e_preventDefault(e); + } + finishTouch(); + }); + on(d.scroller, "touchcancel", finishTouch); + + // Sync scrolling between fake scrollbars and real scrollable + // area, ensure viewport is updated when scrolling. + on(d.scroller, "scroll", function () { + if (d.scroller.clientHeight) { + setScrollTop(cm, d.scroller.scrollTop); + setScrollLeft(cm, d.scroller.scrollLeft, true); + signal(cm, "scroll", cm); + } + }); + + // Listen to wheel events in order to try and update the viewport on time. + on(d.scroller, "mousewheel", function (e) {onScrollWheel(cm, e);}); + on(d.scroller, "DOMMouseScroll", function (e) {onScrollWheel(cm, e);}); + + // Prevent wrapper from ever scrolling + on(d.wrapper, "scroll", function () { d.wrapper.scrollTop = d.wrapper.scrollLeft = 0; }); + + d.dragFunctions = { + simple: function (e) {if (!signalDOMEvent(cm, e)) e_stop(e);}, + start: function (e) {onDragStart(cm, e);}, + drop: operation(cm, onDrop) + }; + + var inp = d.input.getField(); + on(inp, "keyup", function (e) { onKeyUp.call(cm, e); }); + on(inp, "keydown", operation(cm, onKeyDown)); + on(inp, "keypress", operation(cm, onKeyPress)); + on(inp, "focus", bind(onFocus, cm)); + on(inp, "blur", bind(onBlur, cm)); + } + + function dragDropChanged (cm, value, old) { + var wasOn = old && old != CodeMirror.Init; + if (!value != !wasOn) { + var funcs = cm.display.dragFunctions; + var toggle = value ? on : off; + toggle(cm.display.scroller, "dragstart", funcs.start); + toggle(cm.display.scroller, "dragenter", funcs.simple); + toggle(cm.display.scroller, "dragover", funcs.simple); + toggle(cm.display.scroller, "drop", funcs.drop); + } + } + + // Called when the window resizes + function onResize (cm) { + var d = cm.display; + if (d.lastWrapHeight == d.wrapper.clientHeight && d.lastWrapWidth == d.wrapper.clientWidth) {return;} + // Might be a text scaling operation, clear size caches. + d.cachedCharWidth = d.cachedTextHeight = d.cachedPaddingH = null; + d.scrollbarsClipped = false; + cm.setSize(); + } + + // MOUSE EVENTS + + // Return true when the given mouse event happened in a widget + function eventInWidget (display, e) { + for (var n = e_target(e); n != display.wrapper; n = n.parentNode) { + if (!n || (n.nodeType == 1 && n.getAttribute("cm-ignore-events") == "true") || + (n.parentNode == display.sizer && n != display.mover)) {return true;} + } + } + + // Given a mouse event, find the corresponding position. If liberal + // is false, it checks whether a gutter or scrollbar was clicked, + // and returns null if it was. forRect is used by rectangular + // selections, and tries to estimate a character position even for + // coordinates beyond the right of the text. + function posFromMouse (cm, e, liberal, forRect) { + var display = cm.display; + if (!liberal && e_target(e).getAttribute("cm-not-content") == "true") return null; + + var x, y, space = display.lineSpace.getBoundingClientRect(); + // Fails unpredictably on IE[67] when mouse is dragged around quickly. + try { x = e.clientX - space.left; y = e.clientY - space.top; } catch (e) { return null; } + var coords = coordsChar(cm, x, y), line; + if (forRect && coords.xRel == 1 && (line = getLine(cm.doc, coords.line).text).length == coords.ch) { + var colDiff = countColumn(line, line.length, cm.options.tabSize) - line.length; + coords = Pos(coords.line, Math.max(0, Math.round((x - paddingH(cm.display).left) / charWidth(cm.display)) - colDiff)); + } + return coords; + } + + // A mouse down can be a single click, double click, triple click, + // start of selection drag, start of text drag, new cursor + // (ctrl-click), rectangle drag (alt-drag), or xwin + // middle-click-paste. Or it might be a click on something we should + // not interfere with, such as a scrollbar or widget. + function onMouseDown (e) { + var cm = this, display = cm.display; + if (display.activeTouch && display.input.supportsTouch() || signalDOMEvent(cm, e)) return; + display.shift = e.shiftKey; + + if (eventInWidget(display, e)) { + if (!webkit) { + // Briefly turn off draggability, to allow widgets to do + // normal dragging things. + display.scroller.draggable = false; + setTimeout(function () {display.scroller.draggable = true;}, 100); + } + return; + } + if (clickInGutter(cm, e)) return; + var start = posFromMouse(cm, e); + window.focus(); + + switch (e_button(e)) { + case 1: + if (start) {leftButtonDown(cm, e, start);} else if (e_target(e) == display.scroller) {e_preventDefault(e);} + break; + case 2: + if (webkit) cm.state.lastMiddleDown = +new Date; + if (start) extendSelection(cm.doc, start); + setTimeout(function () {display.input.focus();}, 20); + e_preventDefault(e); + break; + case 3: + if (captureRightClick) onContextMenu(cm, e); + else delayBlurEvent(cm); + break; + } + } + + var lastClick, lastDoubleClick; + function leftButtonDown (cm, e, start) { + if (ie) setTimeout(bind(ensureFocus, cm), 0); + else cm.curOp.focus = activeElt(); + + var now = +new Date, type; + if (lastDoubleClick && lastDoubleClick.time > now - 400 && cmp(lastDoubleClick.pos, start) == 0) { + type = "triple"; + } else if (lastClick && lastClick.time > now - 400 && cmp(lastClick.pos, start) == 0) { + type = "double"; + lastDoubleClick = {time: now, pos: start}; + } else { + type = "single"; + lastClick = {time: now, pos: start}; + } + + var sel = cm.doc.sel, modifier = mac ? e.metaKey : e.ctrlKey, contained; + if (cm.options.dragDrop && dragAndDrop && !isReadOnly(cm) && + type == "single" && (contained = sel.contains(start)) > -1 && + (cmp((contained = sel.ranges[contained]).from(), start) < 0 || start.xRel > 0) && + (cmp(contained.to(), start) > 0 || start.xRel < 0)) {leftButtonStartDrag(cm, e, start, modifier);} else {leftButtonSelect(cm, e, start, type, modifier);} + } + + // Start a text drag. When it ends, see if any dragging actually + // happen, and treat as a click if it didn't. + function leftButtonStartDrag (cm, e, start, modifier) { + var display = cm.display, startTime = +new Date; + var dragEnd = operation(cm, function (e2) { + if (webkit) display.scroller.draggable = false; + cm.state.draggingText = false; + off(document, "mouseup", dragEnd); + off(display.scroller, "drop", dragEnd); + if (Math.abs(e.clientX - e2.clientX) + Math.abs(e.clientY - e2.clientY) < 10) { + e_preventDefault(e2); + if (!modifier && +new Date - 200 < startTime) {extendSelection(cm.doc, start);} + // Work around unexplainable focus problem in IE9 (#2127) and Chrome (#3081) + if (webkit || ie && ie_version == 9) {setTimeout(function () {document.body.focus(); display.input.focus();}, 20);} else {display.input.focus();} + } + }); + // Let the drag handler handle this. + if (webkit) display.scroller.draggable = true; + cm.state.draggingText = dragEnd; + // IE's approach to draggable + if (display.scroller.dragDrop) display.scroller.dragDrop(); + on(document, "mouseup", dragEnd); + on(display.scroller, "drop", dragEnd); + } + + // Normal selection, as opposed to text dragging. + function leftButtonSelect (cm, e, start, type, addNew) { + var display = cm.display, doc = cm.doc; + e_preventDefault(e); + + var ourRange, ourIndex, startSel = doc.sel, ranges = startSel.ranges; + if (addNew && !e.shiftKey) { + ourIndex = doc.sel.contains(start); + if (ourIndex > -1) {ourRange = ranges[ourIndex];} else {ourRange = new Range(start, start);} + } else { + ourRange = doc.sel.primary(); + ourIndex = doc.sel.primIndex; + } + + if (e.altKey) { + type = "rect"; + if (!addNew) ourRange = new Range(start, start); + start = posFromMouse(cm, e, true, true); + ourIndex = -1; + } else if (type == "double") { + var word = cm.findWordAt(start); + if (cm.display.shift || doc.extend) {ourRange = extendRange(doc, ourRange, word.anchor, word.head);} else {ourRange = word;} + } else if (type == "triple") { + var line = new Range(Pos(start.line, 0), clipPos(doc, Pos(start.line + 1, 0))); + if (cm.display.shift || doc.extend) {ourRange = extendRange(doc, ourRange, line.anchor, line.head);} else {ourRange = line;} + } else { + ourRange = extendRange(doc, ourRange, start); + } + + if (!addNew) { + ourIndex = 0; + setSelection(doc, new Selection([ourRange], 0), sel_mouse); + startSel = doc.sel; + } else if (ourIndex == -1) { + ourIndex = ranges.length; + setSelection(doc, normalizeSelection(ranges.concat([ourRange]), ourIndex), + {scroll: false, origin: "*mouse"}); + } else if (ranges.length > 1 && ranges[ourIndex].empty() && type == "single" && !e.shiftKey) { + setSelection(doc, normalizeSelection(ranges.slice(0, ourIndex).concat(ranges.slice(ourIndex + 1)), 0)); + startSel = doc.sel; + } else { + replaceOneSelection(doc, ourIndex, ourRange, sel_mouse); + } + + var lastPos = start; + function extendTo (pos) { + if (cmp(lastPos, pos) == 0) return; + lastPos = pos; + + if (type == "rect") { + var ranges = [], tabSize = cm.options.tabSize; + var startCol = countColumn(getLine(doc, start.line).text, start.ch, tabSize); + var posCol = countColumn(getLine(doc, pos.line).text, pos.ch, tabSize); + var left = Math.min(startCol, posCol), right = Math.max(startCol, posCol); + for (var line = Math.min(start.line, pos.line), end = Math.min(cm.lastLine(), Math.max(start.line, pos.line)); + line <= end; line++) { + var text = getLine(doc, line).text, leftPos = findColumn(text, left, tabSize); + if (left == right) {ranges.push(new Range(Pos(line, leftPos), Pos(line, leftPos)));} else if (text.length > leftPos) {ranges.push(new Range(Pos(line, leftPos), Pos(line, findColumn(text, right, tabSize))));} + } + if (!ranges.length) ranges.push(new Range(start, start)); + setSelection(doc, normalizeSelection(startSel.ranges.slice(0, ourIndex).concat(ranges), ourIndex), + {origin: "*mouse", scroll: false}); + cm.scrollIntoView(pos); + } else { + var oldRange = ourRange; + var anchor = oldRange.anchor, head = pos; + if (type != "single") { + if (type == "double") {var range = cm.findWordAt(pos);} else {var range = new Range(Pos(pos.line, 0), clipPos(doc, Pos(pos.line + 1, 0)));} + if (cmp(range.anchor, anchor) > 0) { + head = range.head; + anchor = minPos(oldRange.from(), range.anchor); + } else { + head = range.anchor; + anchor = maxPos(oldRange.to(), range.head); + } + } + var ranges = startSel.ranges.slice(0); + ranges[ourIndex] = new Range(clipPos(doc, anchor), head); + setSelection(doc, normalizeSelection(ranges, ourIndex), sel_mouse); + } + } + + var editorSize = display.wrapper.getBoundingClientRect(); + // Used to ensure timeout re-tries don't fire when another extend + // happened in the meantime (clearTimeout isn't reliable -- at + // least on Chrome, the timeouts still happen even when cleared, + // if the clear happens after their scheduled firing time). + var counter = 0; + + function extend (e) { + var curCount = ++counter; + var cur = posFromMouse(cm, e, true, type == "rect"); + if (!cur) return; + if (cmp(cur, lastPos) != 0) { + cm.curOp.focus = activeElt(); + extendTo(cur); + var visible = visibleLines(display, doc); + if (cur.line >= visible.to || cur.line < visible.from) {setTimeout(operation(cm, function () {if (counter == curCount) extend(e);}), 150);} + } else { + var outside = e.clientY < editorSize.top ? -20 : e.clientY > editorSize.bottom ? 20 : 0; + if (outside) { + setTimeout(operation(cm, function () { + if (counter != curCount) return; + display.scroller.scrollTop += outside; + extend(e); + }), 50); + } + } + } + + function done (e) { + counter = Infinity; + e_preventDefault(e); + display.input.focus(); + off(document, "mousemove", move); + off(document, "mouseup", up); + doc.history.lastSelOrigin = null; + } + + var move = operation(cm, function (e) { + if (!e_button(e)) done(e); + else extend(e); + }); + var up = operation(cm, done); + on(document, "mousemove", move); + on(document, "mouseup", up); + } + + // Determines whether an event happened in the gutter, and fires the + // handlers for the corresponding event. + function gutterEvent (cm, e, type, prevent, signalfn) { + try { var mX = e.clientX, mY = e.clientY; } catch(e) { return false; } + if (mX >= Math.floor(cm.display.gutters.getBoundingClientRect().right)) return false; + if (prevent) e_preventDefault(e); + + var display = cm.display; + var lineBox = display.lineDiv.getBoundingClientRect(); + + if (mY > lineBox.bottom || !hasHandler(cm, type)) return e_defaultPrevented(e); + mY -= lineBox.top - display.viewOffset; + + for (var i = 0; i < cm.options.gutters.length; ++i) { + var g = display.gutters.childNodes[i]; + if (g && g.getBoundingClientRect().right >= mX) { + var line = lineAtHeight(cm.doc, mY); + var gutter = cm.options.gutters[i]; + signalfn(cm, type, cm, line, gutter, e); + return e_defaultPrevented(e); + } + } + } + + function clickInGutter (cm, e) { + return gutterEvent(cm, e, "gutterClick", true, signalLater); + } + + // Kludge to work around strange IE behavior where it'll sometimes + // re-fire a series of drag-related events right after the drop (#1551) + var lastDrop = 0; + + function onDrop (e) { + var cm = this; + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) {return;} + e_preventDefault(e); + if (ie) lastDrop = +new Date; + var pos = posFromMouse(cm, e, true), files = e.dataTransfer.files; + if (!pos || isReadOnly(cm)) return; + // Might be a file drop, in which case we simply extract the text + // and insert it. + if (files && files.length && window.FileReader && window.File) { + var n = files.length, text = Array(n), read = 0; + var loadFile = function (file, i) { + var reader = new FileReader; + reader.onload = operation(cm, function () { + text[i] = reader.result; + if (++read == n) { + pos = clipPos(cm.doc, pos); + var change = {from: pos, to: pos, text: splitLines(text.join("\n")), origin: "paste"}; + makeChange(cm.doc, change); + setSelectionReplaceHistory(cm.doc, simpleSelection(pos, changeEnd(change))); + } + }); + reader.readAsText(file); + }; + for (var i = 0; i < n; ++i) loadFile(files[i], i); + } else { // Normal drop + // Don't do a replace if the drop happened inside of the selected text. + if (cm.state.draggingText && cm.doc.sel.contains(pos) > -1) { + cm.state.draggingText(e); + // Ensure the editor is re-focused + setTimeout(function () {cm.display.input.focus();}, 20); + return; + } + try { + var text = e.dataTransfer.getData("Text"); + if (text) { + if (cm.state.draggingText && !(mac ? e.altKey : e.ctrlKey)) {var selected = cm.listSelections();} + setSelectionNoUndo(cm.doc, simpleSelection(pos, pos)); + if (selected) { + for (var i = 0; i < selected.length; ++i) {replaceRange(cm.doc, "", selected[i].anchor, selected[i].head, "drag");} + } + cm.replaceSelection(text, "around", "paste"); + cm.display.input.focus(); + } + } catch(e) {} + } + } + + function onDragStart (cm, e) { + if (ie && (!cm.state.draggingText || +new Date - lastDrop < 100)) { e_stop(e); return; } + if (signalDOMEvent(cm, e) || eventInWidget(cm.display, e)) return; + + e.dataTransfer.setData("Text", cm.getSelection()); + + // Use dummy image instead of default browsers image. + // Recent Safari (~6.0.2) have a tendency to segfault when this happens, so we don't do it there. + if (e.dataTransfer.setDragImage && !safari) { + var img = elt("img", null, null, "position: fixed; left: 0; top: 0;"); + img.src = "data:image/gif;base64,R0lGODlhAQABAAAAACH5BAEKAAEALAAAAAABAAEAAAICTAEAOw=="; + if (presto) { + img.width = img.height = 1; + cm.display.wrapper.appendChild(img); + // Force a relayout, or Opera won't use our image for some obscure reason + img._top = img.offsetTop; + } + e.dataTransfer.setDragImage(img, 0, 0); + if (presto) img.parentNode.removeChild(img); + } + } + + // SCROLL EVENTS + + // Sync the scrollable area and scrollbars, ensure the viewport + // covers the visible area. + function setScrollTop (cm, val) { + if (Math.abs(cm.doc.scrollTop - val) < 2) return; + cm.doc.scrollTop = val; + if (!gecko) updateDisplaySimple(cm, {top: val}); + if (cm.display.scroller.scrollTop != val) cm.display.scroller.scrollTop = val; + cm.display.scrollbars.setScrollTop(val); + if (gecko) updateDisplaySimple(cm); + startWorker(cm, 100); + } + // Sync scroller and scrollbar, ensure the gutter elements are + // aligned. + function setScrollLeft (cm, val, isScroller) { + if (isScroller ? val == cm.doc.scrollLeft : Math.abs(cm.doc.scrollLeft - val) < 2) return; + val = Math.min(val, cm.display.scroller.scrollWidth - cm.display.scroller.clientWidth); + cm.doc.scrollLeft = val; + alignHorizontally(cm); + if (cm.display.scroller.scrollLeft != val) cm.display.scroller.scrollLeft = val; + cm.display.scrollbars.setScrollLeft(val); + } + + // Since the delta values reported on mouse wheel events are + // unstandardized between browsers and even browser versions, and + // generally horribly unpredictable, this code starts by measuring + // the scroll effect that the first few mouse wheel events have, + // and, from that, detects the way it can convert deltas to pixel + // offsets afterwards. + // + // The reason we want to know the amount a wheel event will scroll + // is that it gives us a chance to update the display before the + // actual scrolling happens, reducing flickering. + + var wheelSamples = 0, wheelPixelsPerUnit = null; + // Fill in a browser-detected starting value on browsers where we + // know one. These don't have to be accurate -- the result of them + // being wrong would just be a slight flicker on the first wheel + // scroll (if it is large enough). + if (ie) wheelPixelsPerUnit = -.53; + else if (gecko) wheelPixelsPerUnit = 15; + else if (chrome) wheelPixelsPerUnit = -.7; + else if (safari) wheelPixelsPerUnit = -1 / 3; + + var wheelEventDelta = function (e) { + var dx = e.wheelDeltaX, dy = e.wheelDeltaY; + if (dx == null && e.detail && e.axis == e.HORIZONTAL_AXIS) dx = e.detail; + if (dy == null && e.detail && e.axis == e.VERTICAL_AXIS) dy = e.detail; + else if (dy == null) dy = e.wheelDelta; + return {x: dx, y: dy}; + }; + CodeMirror.wheelEventPixels = function (e) { + var delta = wheelEventDelta(e); + delta.x *= wheelPixelsPerUnit; + delta.y *= wheelPixelsPerUnit; + return delta; + }; + + function onScrollWheel (cm, e) { + var delta = wheelEventDelta(e), dx = delta.x, dy = delta.y; + + var display = cm.display, scroll = display.scroller; + // Quit if there's nothing to scroll here + if (!(dx && scroll.scrollWidth > scroll.clientWidth || + dy && scroll.scrollHeight > scroll.clientHeight)) return; + + // Webkit browsers on OS X abort momentum scrolls when the target + // of the scroll event is removed from the scrollable element. + // This hack (see related code in patchDisplay) makes sure the + // element is kept around. + if (dy && mac && webkit) { + outer: for (var cur = e.target, view = display.view; cur != scroll; cur = cur.parentNode) { + for (var i = 0; i < view.length; i++) { + if (view[i].node == cur) { + cm.display.currentWheelTarget = cur; + break outer; + } + } + } + } + + // On some browsers, horizontal scrolling will cause redraws to + // happen before the gutter has been realigned, causing it to + // wriggle around in a most unseemly way. When we have an + // estimated pixels/delta value, we just handle horizontal + // scrolling entirely here. It'll be slightly off from native, but + // better than glitching out. + if (dx && !gecko && !presto && wheelPixelsPerUnit != null) { + if (dy) {setScrollTop(cm, Math.max(0, Math.min(scroll.scrollTop + dy * wheelPixelsPerUnit, scroll.scrollHeight - scroll.clientHeight)));} + setScrollLeft(cm, Math.max(0, Math.min(scroll.scrollLeft + dx * wheelPixelsPerUnit, scroll.scrollWidth - scroll.clientWidth))); + e_preventDefault(e); + display.wheelStartX = null; // Abort measurement, if in progress + return; + } + + // 'Project' the visible viewport to cover the area that is being + // scrolled into view (if we know enough to estimate it). + if (dy && wheelPixelsPerUnit != null) { + var pixels = dy * wheelPixelsPerUnit; + var top = cm.doc.scrollTop, bot = top + display.wrapper.clientHeight; + if (pixels < 0) top = Math.max(0, top + pixels - 50); + else bot = Math.min(cm.doc.height, bot + pixels + 50); + updateDisplaySimple(cm, {top: top, bottom: bot}); + } + + if (wheelSamples < 20) { + if (display.wheelStartX == null) { + display.wheelStartX = scroll.scrollLeft; display.wheelStartY = scroll.scrollTop; + display.wheelDX = dx; display.wheelDY = dy; + setTimeout(function () { + if (display.wheelStartX == null) return; + var movedX = scroll.scrollLeft - display.wheelStartX; + var movedY = scroll.scrollTop - display.wheelStartY; + var sample = (movedY && display.wheelDY && movedY / display.wheelDY) || + (movedX && display.wheelDX && movedX / display.wheelDX); + display.wheelStartX = display.wheelStartY = null; + if (!sample) return; + wheelPixelsPerUnit = (wheelPixelsPerUnit * wheelSamples + sample) / (wheelSamples + 1); + ++wheelSamples; + }, 200); + } else { + display.wheelDX += dx; display.wheelDY += dy; + } + } + } + + // KEY EVENTS + + // Run a handler that was bound to a key. + function doHandleBinding (cm, bound, dropShift) { + if (typeof bound === "string") { + bound = commands[bound]; + if (!bound) return false; + } + // Ensure previous input has been read, so that the handler sees a + // consistent view of the document + cm.display.input.ensurePolled(); + var prevShift = cm.display.shift, done = false; + try { + if (isReadOnly(cm)) cm.state.suppressEdits = true; + if (dropShift) cm.display.shift = false; + done = bound(cm) != Pass; + } finally { + cm.display.shift = prevShift; + cm.state.suppressEdits = false; + } + return done; + } + + function lookupKeyForEditor (cm, name, handle) { + for (var i = 0; i < cm.state.keyMaps.length; i++) { + var result = lookupKey(name, cm.state.keyMaps[i], handle, cm); + if (result) return result; + } + return (cm.options.extraKeys && lookupKey(name, cm.options.extraKeys, handle, cm)) + || lookupKey(name, cm.options.keyMap, handle, cm); + } + + var stopSeq = new Delayed; + function dispatchKey (cm, name, e, handle) { + var seq = cm.state.keySeq; + if (seq) { + if (isModifierKey(name)) return "handled"; + stopSeq.set(50, function () { + if (cm.state.keySeq == seq) { + cm.state.keySeq = null; + cm.display.input.reset(); + } + }); + name = seq + " " + name; + } + var result = lookupKeyForEditor(cm, name, handle); + + if (result == "multi") {cm.state.keySeq = name;} + if (result == "handled") {signalLater(cm, "keyHandled", cm, name, e);} + + if (result == "handled" || result == "multi") { + e_preventDefault(e); + restartBlink(cm); + } + + if (seq && !result && /\'$/.test(name)) { + e_preventDefault(e); + return true; + } + return !!result; + } + + // Handle a key from the keydown event. + function handleKeyBinding (cm, e) { + var name = keyName(e, true); + if (!name) return false; + + if (e.shiftKey && !cm.state.keySeq) { + // First try to resolve full name (including 'Shift-'). Failing + // that, see if there is a cursor-motion command (starting with + // 'go') bound to the keyname without 'Shift-'. + return dispatchKey(cm, "Shift-" + name, e, function (b) {return doHandleBinding(cm, b, true);}) + || dispatchKey(cm, name, e, function (b) { + if (typeof b === "string" ? /^go[A-Z]/.test(b) : b.motion) {return doHandleBinding(cm, b);} + }); + } + return dispatchKey(cm, name, e, function (b) { return doHandleBinding(cm, b); }); + + } + + // Handle a key from the keypress event + function handleCharBinding (cm, e, ch) { + return dispatchKey(cm, "'" + ch + "'", e, + function (b) { return doHandleBinding(cm, b, true); }); + } + + var lastStoppedKey = null; + function onKeyDown (e) { + var cm = this; + cm.curOp.focus = activeElt(); + if (signalDOMEvent(cm, e)) return; + // IE does strange things with escape. + if (ie && ie_version < 11 && e.keyCode == 27) e.returnValue = false; + var code = e.keyCode; + cm.display.shift = code == 16 || e.shiftKey; + var handled = handleKeyBinding(cm, e); + if (presto) { + lastStoppedKey = handled ? code : null; + // Opera has no cut event... we try to at least catch the key combo + if (!handled && code == 88 && !hasCopyEvent && (mac ? e.metaKey : e.ctrlKey)) {cm.replaceSelection("", null, "cut");} + } + + // Turn mouse into crosshair when Alt is held on Mac. + if (code == 18 && !/\bCodeMirror-crosshair\b/.test(cm.display.lineDiv.className)) {showCrossHair(cm);} + } + + function showCrossHair (cm) { + var lineDiv = cm.display.lineDiv; + addClass(lineDiv, "CodeMirror-crosshair"); + + function up (e) { + if (e.keyCode == 18 || !e.altKey) { + rmClass(lineDiv, "CodeMirror-crosshair"); + off(document, "keyup", up); + off(document, "mouseover", up); + } + } + on(document, "keyup", up); + on(document, "mouseover", up); + } + + function onKeyUp (e) { + if (e.keyCode == 16) this.doc.sel.shift = false; + signalDOMEvent(this, e); + } + + function onKeyPress (e) { + var cm = this; + if (eventInWidget(cm.display, e) || signalDOMEvent(cm, e) || e.ctrlKey && !e.altKey || mac && e.metaKey) return; + var keyCode = e.keyCode, charCode = e.charCode; + if (presto && keyCode == lastStoppedKey) {lastStoppedKey = null; e_preventDefault(e); return;} + if ((presto && (!e.which || e.which < 10)) && handleKeyBinding(cm, e)) return; + var ch = String.fromCharCode(charCode == null ? keyCode : charCode); + if (handleCharBinding(cm, e, ch)) return; + cm.display.input.onKeyPress(e); + } + + // FOCUS/BLUR EVENTS + + function delayBlurEvent (cm) { + cm.state.delayingBlurEvent = true; + setTimeout(function () { + if (cm.state.delayingBlurEvent) { + cm.state.delayingBlurEvent = false; + onBlur(cm); + } + }, 100); + } + + function onFocus (cm) { + if (cm.state.delayingBlurEvent) cm.state.delayingBlurEvent = false; + + if (cm.options.readOnly == "nocursor") return; + if (!cm.state.focused) { + signal(cm, "focus", cm); + cm.state.focused = true; + addClass(cm.display.wrapper, "CodeMirror-focused"); + // This test prevents this from firing when a context + // menu is closed (since the input reset would kill the + // select-all detection hack) + if (!cm.curOp && cm.display.selForContextMenu != cm.doc.sel) { + cm.display.input.reset(); + if (webkit) setTimeout(function () { cm.display.input.reset(true); }, 20); // Issue #1730 + } + cm.display.input.receivedFocus(); + } + restartBlink(cm); + } + function onBlur (cm) { + if (cm.state.delayingBlurEvent) return; + + if (cm.state.focused) { + signal(cm, "blur", cm); + cm.state.focused = false; + rmClass(cm.display.wrapper, "CodeMirror-focused"); + } + clearInterval(cm.display.blinker); + setTimeout(function () {if (!cm.state.focused) cm.display.shift = false;}, 150); + } + + // CONTEXT MENU HANDLING + + // To make the context menu work, we need to briefly unhide the + // textarea (making it as unobtrusive as possible) to let the + // right-click take effect on it. + function onContextMenu (cm, e) { + if (eventInWidget(cm.display, e) || contextMenuInGutter(cm, e)) return; + cm.display.input.onContextMenu(e); + } + + function contextMenuInGutter (cm, e) { + if (!hasHandler(cm, "gutterContextMenu")) return false; + return gutterEvent(cm, e, "gutterContextMenu", false, signal); + } + + // UPDATING + + // Compute the position of the end of a change (its 'to' property + // refers to the pre-change end). + var changeEnd = CodeMirror.changeEnd = function (change) { + if (!change.text) return change.to; + return Pos(change.from.line + change.text.length - 1, + lst(change.text).length + (change.text.length == 1 ? change.from.ch : 0)); + }; + + // Adjust a position to refer to the post-change position of the + // same text, or the end of the change if the change covers it. + function adjustForChange (pos, change) { + if (cmp(pos, change.from) < 0) return pos; + if (cmp(pos, change.to) <= 0) return changeEnd(change); + + var line = pos.line + change.text.length - (change.to.line - change.from.line) - 1, ch = pos.ch; + if (pos.line == change.to.line) ch += changeEnd(change).ch - change.to.ch; + return Pos(line, ch); + } + + function computeSelAfterChange (doc, change) { + var out = []; + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + out.push(new Range(adjustForChange(range.anchor, change), + adjustForChange(range.head, change))); + } + return normalizeSelection(out, doc.sel.primIndex); + } + + function offsetPos (pos, old, nw) { + if (pos.line == old.line) {return Pos(nw.line, pos.ch - old.ch + nw.ch);} + return Pos(nw.line + (pos.line - old.line), pos.ch); + } + + // Used by replaceSelections to allow moving the selection to the + // start or around the replaced test. Hint may be "start" or "around". + function computeReplacedSel (doc, changes, hint) { + var out = []; + var oldPrev = Pos(doc.first, 0), newPrev = oldPrev; + for (var i = 0; i < changes.length; i++) { + var change = changes[i]; + var from = offsetPos(change.from, oldPrev, newPrev); + var to = offsetPos(changeEnd(change), oldPrev, newPrev); + oldPrev = change.to; + newPrev = to; + if (hint == "around") { + var range = doc.sel.ranges[i], inv = cmp(range.head, range.anchor) < 0; + out[i] = new Range(inv ? to : from, inv ? from : to); + } else { + out[i] = new Range(from, from); + } + } + return new Selection(out, doc.sel.primIndex); + } + + // Allow "beforeChange" event handlers to influence a change + function filterChange (doc, change, update) { + var obj = { + canceled: false, + from: change.from, + to: change.to, + text: change.text, + origin: change.origin, + cancel: function () { this.canceled = true; } + }; + if (update) { + obj.update = function (from, to, text, origin) { + if (from) this.from = clipPos(doc, from); + if (to) this.to = clipPos(doc, to); + if (text) this.text = text; + if (origin !== undefined) this.origin = origin; + }; + } + signal(doc, "beforeChange", doc, obj); + if (doc.cm) signal(doc.cm, "beforeChange", doc.cm, obj); + + if (obj.canceled) return null; + return {from: obj.from, to: obj.to, text: obj.text, origin: obj.origin}; + } + + // Apply a change to a document, and add it to the document's + // history, and propagating it to all linked documents. + function makeChange (doc, change, ignoreReadOnly) { + if (doc.cm) { + if (!doc.cm.curOp) return operation(doc.cm, makeChange)(doc, change, ignoreReadOnly); + if (doc.cm.state.suppressEdits) return; + } + + if (hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange")) { + change = filterChange(doc, change, true); + if (!change) return; + } + + // Possibly split or suppress the update based on the presence + // of read-only spans in its range. + var split = sawReadOnlySpans && !ignoreReadOnly && removeReadOnlyRanges(doc, change.from, change.to); + if (split) { + for (var i = split.length - 1; i >= 0; --i) {makeChangeInner(doc, {from: split[i].from, to: split[i].to, text: i ? [""] : change.text});} + } else { + makeChangeInner(doc, change); + } + } + + function makeChangeInner (doc, change) { + if (change.text.length == 1 && change.text[0] == "" && cmp(change.from, change.to) == 0) return; + var selAfter = computeSelAfterChange(doc, change); + addChangeToHistory(doc, change, selAfter, doc.cm ? doc.cm.curOp.id : NaN); + + makeChangeSingleDoc(doc, change, selAfter, stretchSpansOverChange(doc, change)); + var rebased = []; + + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, stretchSpansOverChange(doc, change)); + }); + } + + // Revert a change stored in a document's history. + function makeChangeFromHistory (doc, type, allowSelectionOnly) { + if (doc.cm && doc.cm.state.suppressEdits) return; + + var hist = doc.history, event, selAfter = doc.sel; + var source = type == "undo" ? hist.done : hist.undone, dest = type == "undo" ? hist.undone : hist.done; + + // Verify that there is a useable event (so that ctrl-z won't + // needlessly clear selection events) + for (var i = 0; i < source.length; i++) { + event = source[i]; + if (allowSelectionOnly ? event.ranges && !event.equals(doc.sel) : !event.ranges) {break;} + } + if (i == source.length) return; + hist.lastOrigin = hist.lastSelOrigin = null; + + for (;;) { + event = source.pop(); + if (event.ranges) { + pushSelectionToHistory(event, dest); + if (allowSelectionOnly && !event.equals(doc.sel)) { + setSelection(doc, event, {clearRedo: false}); + return; + } + selAfter = event; + } else break; + } + + // Build up a reverse change object to add to the opposite history + // stack (redo when undoing, and vice versa). + var antiChanges = []; + pushSelectionToHistory(selAfter, dest); + dest.push({changes: antiChanges, generation: hist.generation}); + hist.generation = event.generation || ++hist.maxGeneration; + + var filter = hasHandler(doc, "beforeChange") || doc.cm && hasHandler(doc.cm, "beforeChange"); + + for (var i = event.changes.length - 1; i >= 0; --i) { + var change = event.changes[i]; + change.origin = type; + if (filter && !filterChange(doc, change, false)) { + source.length = 0; + return; + } + + antiChanges.push(historyChangeFromChange(doc, change)); + + var after = i ? computeSelAfterChange(doc, change) : lst(source); + makeChangeSingleDoc(doc, change, after, mergeOldSpans(doc, change)); + if (!i && doc.cm) doc.cm.scrollIntoView({from: change.from, to: changeEnd(change)}); + var rebased = []; + + // Propagate to the linked documents + linkedDocs(doc, function (doc, sharedHist) { + if (!sharedHist && indexOf(rebased, doc.history) == -1) { + rebaseHist(doc.history, change); + rebased.push(doc.history); + } + makeChangeSingleDoc(doc, change, null, mergeOldSpans(doc, change)); + }); + } + } + + // Sub-views need their line numbers shifted when text is added + // above or below them in the parent document. + function shiftDoc (doc, distance) { + if (distance == 0) return; + doc.first += distance; + doc.sel = new Selection(map(doc.sel.ranges, function (range) { + return new Range(Pos(range.anchor.line + distance, range.anchor.ch), + Pos(range.head.line + distance, range.head.ch)); + }), doc.sel.primIndex); + if (doc.cm) { + regChange(doc.cm, doc.first, doc.first - distance, distance); + for (var d = doc.cm.display, l = d.viewFrom; l < d.viewTo; l++) {regLineChange(doc.cm, l, "gutter");} + } + } + + // More lower-level change function, handling only a single document + // (not linked ones). + function makeChangeSingleDoc (doc, change, selAfter, spans) { + if (doc.cm && !doc.cm.curOp) {return operation(doc.cm, makeChangeSingleDoc)(doc, change, selAfter, spans);} + + if (change.to.line < doc.first) { + shiftDoc(doc, change.text.length - 1 - (change.to.line - change.from.line)); + return; + } + if (change.from.line > doc.lastLine()) return; + + // Clip the change to the size of this doc + if (change.from.line < doc.first) { + var shift = change.text.length - 1 - (doc.first - change.from.line); + shiftDoc(doc, shift); + change = {from: Pos(doc.first, 0), to: Pos(change.to.line + shift, change.to.ch), + text: [lst(change.text)], origin: change.origin}; + } + var last = doc.lastLine(); + if (change.to.line > last) { + change = {from: change.from, to: Pos(last, getLine(doc, last).text.length), + text: [change.text[0]], origin: change.origin}; + } + + change.removed = getBetween(doc, change.from, change.to); + + if (!selAfter) selAfter = computeSelAfterChange(doc, change); + if (doc.cm) makeChangeSingleDocInEditor(doc.cm, change, spans); + else updateDoc(doc, change, spans); + setSelectionNoUndo(doc, selAfter, sel_dontScroll); + } + + // Handle the interaction of a change to a document with the editor + // that this document is part of. + function makeChangeSingleDocInEditor (cm, change, spans) { + var doc = cm.doc, display = cm.display, from = change.from, to = change.to; + + var recomputeMaxLength = false, checkWidthStart = from.line; + if (!cm.options.lineWrapping) { + checkWidthStart = lineNo(visualLine(getLine(doc, from.line))); + doc.iter(checkWidthStart, to.line + 1, function (line) { + if (line == display.maxLine) { + recomputeMaxLength = true; + return true; + } + }); + } + + if (doc.sel.contains(change.from, change.to) > -1) {signalCursorActivity(cm);} + + updateDoc(doc, change, spans, estimateHeight(cm)); + + if (!cm.options.lineWrapping) { + doc.iter(checkWidthStart, from.line + change.text.length, function (line) { + var len = lineLength(line); + if (len > display.maxLineLength) { + display.maxLine = line; + display.maxLineLength = len; + display.maxLineChanged = true; + recomputeMaxLength = false; + } + }); + if (recomputeMaxLength) cm.curOp.updateMaxLine = true; + } + + // Adjust frontier, schedule worker + doc.frontier = Math.min(doc.frontier, from.line); + startWorker(cm, 400); + + var lendiff = change.text.length - (to.line - from.line) - 1; + // Remember that these lines changed, for updating the display + if (change.full) {regChange(cm);} else if (from.line == to.line && change.text.length == 1 && !isWholeLineUpdate(cm.doc, change)) {regLineChange(cm, from.line, "text");} else {regChange(cm, from.line, to.line + 1, lendiff);} + + var changesHandler = hasHandler(cm, "changes"), changeHandler = hasHandler(cm, "change"); + if (changeHandler || changesHandler) { + var obj = { + from: from, to: to, + text: change.text, + removed: change.removed, + origin: change.origin + }; + if (changeHandler) signalLater(cm, "change", cm, obj); + if (changesHandler) (cm.curOp.changeObjs || (cm.curOp.changeObjs = [])).push(obj); + } + cm.display.selForContextMenu = null; + } + + function replaceRange (doc, code, from, to, origin) { + if (!to) to = from; + if (cmp(to, from) < 0) { var tmp = to; to = from; from = tmp; } + if (typeof code === "string") code = splitLines(code); + makeChange(doc, {from: from, to: to, text: code, origin: origin}); + } + + // SCROLLING THINGS INTO VIEW + + // If an editor sits on the top or bottom of the window, partially + // scrolled out of view, this ensures that the cursor is visible. + function maybeScrollWindow (cm, coords) { + if (signalDOMEvent(cm, "scrollCursorIntoView")) return; + + var display = cm.display, box = display.sizer.getBoundingClientRect(), doScroll = null; + if (coords.top + box.top < 0) doScroll = true; + else if (coords.bottom + box.top > (window.innerHeight || document.documentElement.clientHeight)) doScroll = false; + if (doScroll != null && !phantom) { + var scrollNode = elt("div", "\u200b", null, "position: absolute; top: " + + (coords.top - display.viewOffset - paddingTop(cm.display)) + "px; height: " + + (coords.bottom - coords.top + scrollGap(cm) + display.barHeight) + "px; left: " + + coords.left + "px; width: 2px;"); + cm.display.lineSpace.appendChild(scrollNode); + scrollNode.scrollIntoView(doScroll); + cm.display.lineSpace.removeChild(scrollNode); + } + } + + // Scroll a given position into view (immediately), verifying that + // it actually became visible (as line heights are accurately + // measured, the position of something may 'drift' during drawing). + function scrollPosIntoView (cm, pos, end, margin) { + if (margin == null) margin = 0; + for (var limit = 0; limit < 5; limit++) { + var changed = false, coords = cursorCoords(cm, pos); + var endCoords = !end || end == pos ? coords : cursorCoords(cm, end); + var scrollPos = calculateScrollPos(cm, Math.min(coords.left, endCoords.left), + Math.min(coords.top, endCoords.top) - margin, + Math.max(coords.left, endCoords.left), + Math.max(coords.bottom, endCoords.bottom) + margin); + var startTop = cm.doc.scrollTop, startLeft = cm.doc.scrollLeft; + if (scrollPos.scrollTop != null) { + setScrollTop(cm, scrollPos.scrollTop); + if (Math.abs(cm.doc.scrollTop - startTop) > 1) changed = true; + } + if (scrollPos.scrollLeft != null) { + setScrollLeft(cm, scrollPos.scrollLeft); + if (Math.abs(cm.doc.scrollLeft - startLeft) > 1) changed = true; + } + if (!changed) break; + } + return coords; + } + + // Scroll a given set of coordinates into view (immediately). + function scrollIntoView (cm, x1, y1, x2, y2) { + var scrollPos = calculateScrollPos(cm, x1, y1, x2, y2); + if (scrollPos.scrollTop != null) setScrollTop(cm, scrollPos.scrollTop); + if (scrollPos.scrollLeft != null) setScrollLeft(cm, scrollPos.scrollLeft); + } + + // Calculate a new scroll position needed to scroll the given + // rectangle into view. Returns an object with scrollTop and + // scrollLeft properties. When these are undefined, the + // vertical/horizontal position does not need to be adjusted. + function calculateScrollPos (cm, x1, y1, x2, y2) { + var display = cm.display, snapMargin = textHeight(cm.display); + if (y1 < 0) y1 = 0; + var screentop = cm.curOp && cm.curOp.scrollTop != null ? cm.curOp.scrollTop : display.scroller.scrollTop; + var screen = displayHeight(cm), result = {}; + if (y2 - y1 > screen) y2 = y1 + screen; + var docBottom = cm.doc.height + paddingVert(display); + var atTop = y1 < snapMargin, atBottom = y2 > docBottom - snapMargin; + if (y1 < screentop) { + result.scrollTop = atTop ? 0 : y1; + } else if (y2 > screentop + screen) { + var newTop = Math.min(y1, (atBottom ? docBottom : y2) - screen); + if (newTop != screentop) result.scrollTop = newTop; + } + + var screenleft = cm.curOp && cm.curOp.scrollLeft != null ? cm.curOp.scrollLeft : display.scroller.scrollLeft; + var screenw = displayWidth(cm) - (cm.options.fixedGutter ? display.gutters.offsetWidth : 0); + var tooWide = x2 - x1 > screenw; + if (tooWide) x2 = x1 + screenw; + if (x1 < 10) {result.scrollLeft = 0;} else if (x1 < screenleft) {result.scrollLeft = Math.max(0, x1 - (tooWide ? 0 : 10));} else if (x2 > screenw + screenleft - 3) {result.scrollLeft = x2 + (tooWide ? 0 : 10) - screenw;} + return result; + } + + // Store a relative adjustment to the scroll position in the current + // operation (to be applied when the operation finishes). + function addToScrollPos (cm, left, top) { + if (left != null || top != null) resolveScrollToPos(cm); + if (left != null) {cm.curOp.scrollLeft = (cm.curOp.scrollLeft == null ? cm.doc.scrollLeft : cm.curOp.scrollLeft) + left;} + if (top != null) {cm.curOp.scrollTop = (cm.curOp.scrollTop == null ? cm.doc.scrollTop : cm.curOp.scrollTop) + top;} + } + + // Make sure that at the end of the operation the current cursor is + // shown. + function ensureCursorVisible (cm) { + resolveScrollToPos(cm); + var cur = cm.getCursor(), from = cur, to = cur; + if (!cm.options.lineWrapping) { + from = cur.ch ? Pos(cur.line, cur.ch - 1) : cur; + to = Pos(cur.line, cur.ch + 1); + } + cm.curOp.scrollToPos = {from: from, to: to, margin: cm.options.cursorScrollMargin, isCursor: true}; + } + + // When an operation has its scrollToPos property set, and another + // scroll action is applied before the end of the operation, this + // 'simulates' scrolling that position into view in a cheap way, so + // that the effect of intermediate scroll commands is not ignored. + function resolveScrollToPos (cm) { + var range = cm.curOp.scrollToPos; + if (range) { + cm.curOp.scrollToPos = null; + var from = estimateCoords(cm, range.from), to = estimateCoords(cm, range.to); + var sPos = calculateScrollPos(cm, Math.min(from.left, to.left), + Math.min(from.top, to.top) - range.margin, + Math.max(from.right, to.right), + Math.max(from.bottom, to.bottom) + range.margin); + cm.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + } + + // API UTILITIES + + // Indent the given line. The how parameter can be "smart", + // "add"/null, "subtract", or "prev". When aggressive is false + // (typically set to true for forced single-line indents), empty + // lines are not indented, and places where the mode returns Pass + // are left alone. + function indentLine (cm, n, how, aggressive) { + var doc = cm.doc, state; + if (how == null) how = "add"; + if (how == "smart") { + // Fall back to "prev" when the mode doesn't have an indentation + // method. + if (!doc.mode.indent) how = "prev"; + else state = getStateBefore(cm, n); + } + + var tabSize = cm.options.tabSize; + var line = getLine(doc, n), curSpace = countColumn(line.text, null, tabSize); + if (line.stateAfter) line.stateAfter = null; + var curSpaceString = line.text.match(/^\s*/)[0], indentation; + if (!aggressive && !/\S/.test(line.text)) { + indentation = 0; + how = "not"; + } else if (how == "smart") { + indentation = doc.mode.indent(state, line.text.slice(curSpaceString.length), line.text); + if (indentation == Pass || indentation > 150) { + if (!aggressive) return; + how = "prev"; + } + } + if (how == "prev") { + if (n > doc.first) indentation = countColumn(getLine(doc, n - 1).text, null, tabSize); + else indentation = 0; + } else if (how == "add") { + indentation = curSpace + cm.options.indentUnit; + } else if (how == "subtract") { + indentation = curSpace - cm.options.indentUnit; + } else if (typeof how === "number") { + indentation = curSpace + how; + } + indentation = Math.max(0, indentation); + + var indentString = "", pos = 0; + if (cm.options.indentWithTabs) {for (var i = Math.floor(indentation / tabSize); i; --i) {pos += tabSize; indentString += "\t";}} + if (pos < indentation) indentString += spaceStr(indentation - pos); + + if (indentString != curSpaceString) { + replaceRange(doc, indentString, Pos(n, 0), Pos(n, curSpaceString.length), "+input"); + line.stateAfter = null; + return true; + } + // Ensure that, if the cursor was in the whitespace at the start + // of the line, it is moved to the end of that space. + for (var i = 0; i < doc.sel.ranges.length; i++) { + var range = doc.sel.ranges[i]; + if (range.head.line == n && range.head.ch < curSpaceString.length) { + var pos = Pos(n, curSpaceString.length); + replaceOneSelection(doc, i, new Range(pos, pos)); + break; + } + } + + } + + // Utility for applying a change to a line by handle or number, + // returning the number and optionally registering the line as + // changed. + function changeLine (doc, handle, changeType, op) { + var no = handle, line = handle; + if (typeof handle === "number") line = getLine(doc, clipLine(doc, handle)); + else no = lineNo(handle); + if (no == null) return null; + if (op(line, no) && doc.cm) regLineChange(doc.cm, no, changeType); + return line; + } + + // Helper for deleting text near the selection(s), used to implement + // backspace, delete, and similar functionality. + function deleteNearSelection (cm, compute) { + var ranges = cm.doc.sel.ranges, kill = []; + // Build up a set of ranges to kill first, merging overlapping + // ranges. + for (var i = 0; i < ranges.length; i++) { + var toKill = compute(ranges[i]); + while (kill.length && cmp(toKill.from, lst(kill).to) <= 0) { + var replaced = kill.pop(); + if (cmp(replaced.from, toKill.from) < 0) { + toKill.from = replaced.from; + break; + } + } + kill.push(toKill); + } + // Next, remove those actual ranges. + runInOp(cm, function () { + for (var i = kill.length - 1; i >= 0; i--) {replaceRange(cm.doc, "", kill[i].from, kill[i].to, "+delete");} + ensureCursorVisible(cm); + }); + } + + // Used for horizontal relative motion. Dir is -1 or 1 (left or + // right), unit can be "char", "column" (like char, but doesn't + // cross line boundaries), "word" (across next word), or "group" (to + // the start of next group of word or non-word-non-whitespace + // chars). The visually param controls whether, in right-to-left + // text, direction 1 means to move towards the next index in the + // string, or towards the character to the right of the current + // position. The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosH (doc, pos, dir, unit, visually) { + var line = pos.line, ch = pos.ch, origDir = dir; + var lineObj = getLine(doc, line); + var possible = true; + function findNextLine () { + var l = line + dir; + if (l < doc.first || l >= doc.first + doc.size) return (possible = false); + line = l; + return lineObj = getLine(doc, l); + } + function moveOnce (boundToLine) { + var next = (visually ? moveVisually : moveLogically)(lineObj, ch, dir, true); + if (next == null) { + if (!boundToLine && findNextLine()) { + if (visually) ch = (dir < 0 ? lineRight : lineLeft)(lineObj); + else ch = dir < 0 ? lineObj.text.length : 0; + } else return (possible = false); + } else ch = next; + return true; + } + + if (unit == "char") moveOnce(); + else if (unit == "column") moveOnce(true); + else if (unit == "word" || unit == "group") { + var sawType = null, group = unit == "group"; + var helper = doc.cm && doc.cm.getHelper(pos, "wordChars"); + for (var first = true; ; first = false) { + if (dir < 0 && !moveOnce(!first)) break; + var cur = lineObj.text.charAt(ch) || "\n"; + var type = isWordChar(cur, helper) ? "w" + : group && cur == "\n" ? "n" + : !group || /\s/.test(cur) ? null + : "p"; + if (group && !first && !type) type = "s"; + if (sawType && sawType != type) { + if (dir < 0) {dir = 1; moveOnce();} + break; + } + + if (type) sawType = type; + if (dir > 0 && !moveOnce(!first)) break; + } + } + var result = skipAtomic(doc, Pos(line, ch), origDir, true); + if (!possible) result.hitSide = true; + return result; + } + + // For relative vertical movement. Dir may be -1 or 1. Unit can be + // "page" or "line". The resulting position will have a hitSide=true + // property if it reached the end of the document. + function findPosV (cm, pos, dir, unit) { + var doc = cm.doc, x = pos.left, y; + if (unit == "page") { + var pageSize = Math.min(cm.display.wrapper.clientHeight, window.innerHeight || document.documentElement.clientHeight); + y = pos.top + dir * (pageSize - (dir < 0 ? 1.5 : .5) * textHeight(cm.display)); + } else if (unit == "line") { + y = dir > 0 ? pos.bottom + 3 : pos.top - 3; + } + for (;;) { + var target = coordsChar(cm, x, y); + if (!target.outside) break; + if (dir < 0 ? y <= 0 : y >= doc.height) { target.hitSide = true; break; } + y += dir * 5; + } + return target; + } + + // EDITOR METHODS + + // The publicly visible API. Note that methodOp(f) means + // 'wrap f in an operation, performed on its `this` parameter'. + + // This is not the complete set of editor methods. Most of the + // methods defined on the Doc type are also injected into + // CodeMirror.prototype, for backwards compatibility and + // convenience. + + CodeMirror.prototype = { + constructor: CodeMirror, + focus: function () {window.focus(); this.display.input.focus();}, + + setOption: function (option, value) { + var options = this.options, old = options[option]; + if (options[option] == value && option != "mode") return; + options[option] = value; + if (optionHandlers.hasOwnProperty(option)) {operation(this, optionHandlers[option])(this, value, old);} + }, + + getOption: function (option) {return this.options[option];}, + getDoc: function () {return this.doc;}, + + addKeyMap: function (map, bottom) { + this.state.keyMaps[bottom ? "push" : "unshift"](getKeyMap(map)); + }, + removeKeyMap: function (map) { + var maps = this.state.keyMaps; + for (var i = 0; i < maps.length; ++i) { + if (maps[i] == map || maps[i].name == map) { + maps.splice(i, 1); + return true; + } + } + }, + + addOverlay: methodOp(function (spec, options) { + var mode = spec.token ? spec : CodeMirror.getMode(this.options, spec); + if (mode.startState) throw new Error("Overlays may not be stateful."); + this.state.overlays.push({mode: mode, modeSpec: spec, opaque: options && options.opaque}); + this.state.modeGen++; + regChange(this); + }), + removeOverlay: methodOp(function (spec) { + var overlays = this.state.overlays; + for (var i = 0; i < overlays.length; ++i) { + var cur = overlays[i].modeSpec; + if (cur == spec || typeof spec === "string" && cur.name == spec) { + overlays.splice(i, 1); + this.state.modeGen++; + regChange(this); + return; + } + } + }), + + indentLine: methodOp(function (n, dir, aggressive) { + if (typeof dir !== "string" && typeof dir !== "number") { + if (dir == null) dir = this.options.smartIndent ? "smart" : "prev"; + else dir = dir ? "add" : "subtract"; + } + if (isLine(this.doc, n)) indentLine(this, n, dir, aggressive); + }), + indentSelection: methodOp(function (how) { + var ranges = this.doc.sel.ranges, end = -1; + for (var i = 0; i < ranges.length; i++) { + var range = ranges[i]; + if (!range.empty()) { + var from = range.from(), to = range.to(); + var start = Math.max(end, from.line); + end = Math.min(this.lastLine(), to.line - (to.ch ? 0 : 1)) + 1; + for (var j = start; j < end; ++j) {indentLine(this, j, how);} + var newRanges = this.doc.sel.ranges; + if (from.ch == 0 && ranges.length == newRanges.length && newRanges[i].from().ch > 0) {replaceOneSelection(this.doc, i, new Range(from, newRanges[i].to()), sel_dontScroll);} + } else if (range.head.line > end) { + indentLine(this, range.head.line, how, true); + end = range.head.line; + if (i == this.doc.sel.primIndex) ensureCursorVisible(this); + } + } + }), + + // Fetch the parser token for a given character. Useful for hacks + // that want to inspect the mode state (say, for completion). + getTokenAt: function (pos, precise) { + return takeToken(this, pos, precise); + }, + + getLineTokens: function (line, precise) { + return takeToken(this, Pos(line), precise, true); + }, + + getTokenTypeAt: function (pos) { + pos = clipPos(this.doc, pos); + var styles = getLineStyles(this, getLine(this.doc, pos.line)); + var before = 0, after = (styles.length - 1) / 2, ch = pos.ch; + var type; + if (ch == 0) type = styles[2]; + else { + for (;;) { + var mid = (before + after) >> 1; + if ((mid ? styles[mid * 2 - 1] : 0) >= ch) after = mid; + else if (styles[mid * 2 + 1] < ch) before = mid + 1; + else { type = styles[mid * 2 + 2]; break; } + } + } + var cut = type ? type.indexOf("cm-overlay ") : -1; + return cut < 0 ? type : cut == 0 ? null : type.slice(0, cut - 1); + }, + + getModeAt: function (pos) { + var mode = this.doc.mode; + if (!mode.innerMode) return mode; + return CodeMirror.innerMode(mode, this.getTokenAt(pos).state).mode; + }, + + getHelper: function (pos, type) { + return this.getHelpers(pos, type)[0]; + }, + + getHelpers: function (pos, type) { + var found = []; + if (!helpers.hasOwnProperty(type)) return found; + var help = helpers[type], mode = this.getModeAt(pos); + if (typeof mode[type] === "string") { + if (help[mode[type]]) found.push(help[mode[type]]); + } else if (mode[type]) { + for (var i = 0; i < mode[type].length; i++) { + var val = help[mode[type][i]]; + if (val) found.push(val); + } + } else if (mode.helperType && help[mode.helperType]) { + found.push(help[mode.helperType]); + } else if (help[mode.name]) { + found.push(help[mode.name]); + } + for (var i = 0; i < help._global.length; i++) { + var cur = help._global[i]; + if (cur.pred(mode, this) && indexOf(found, cur.val) == -1) {found.push(cur.val);} + } + return found; + }, + + getStateAfter: function (line, precise) { + var doc = this.doc; + line = clipLine(doc, line == null ? doc.first + doc.size - 1 : line); + return getStateBefore(this, line + 1, precise); + }, + + cursorCoords: function (start, mode) { + var pos, range = this.doc.sel.primary(); + if (start == null) pos = range.head; + else if (typeof start === "object") pos = clipPos(this.doc, start); + else pos = start ? range.from() : range.to(); + return cursorCoords(this, pos, mode || "page"); + }, + + charCoords: function (pos, mode) { + return charCoords(this, clipPos(this.doc, pos), mode || "page"); + }, + + coordsChar: function (coords, mode) { + coords = fromCoordSystem(this, coords, mode || "page"); + return coordsChar(this, coords.left, coords.top); + }, + + lineAtHeight: function (height, mode) { + height = fromCoordSystem(this, {top: height, left: 0}, mode || "page").top; + return lineAtHeight(this.doc, height + this.display.viewOffset); + }, + heightAtLine: function (line, mode) { + var end = false, lineObj; + if (typeof line === "number") { + var last = this.doc.first + this.doc.size - 1; + if (line < this.doc.first) line = this.doc.first; + else if (line > last) { line = last; end = true; } + lineObj = getLine(this.doc, line); + } else { + lineObj = line; + } + return intoCoordSystem(this, lineObj, {top: 0, left: 0}, mode || "page").top + + (end ? this.doc.height - heightAtLine(lineObj) : 0); + }, + + defaultTextHeight: function () { return textHeight(this.display); }, + defaultCharWidth: function () { return charWidth(this.display); }, + + setGutterMarker: methodOp(function (line, gutterID, value) { + return changeLine(this.doc, line, "gutter", function (line) { + var markers = line.gutterMarkers || (line.gutterMarkers = {}); + markers[gutterID] = value; + if (!value && isEmpty(markers)) line.gutterMarkers = null; + return true; + }); + }), + + clearGutter: methodOp(function (gutterID) { + var cm = this, doc = cm.doc, i = doc.first; + doc.iter(function (line) { + if (line.gutterMarkers && line.gutterMarkers[gutterID]) { + line.gutterMarkers[gutterID] = null; + regLineChange(cm, i, "gutter"); + if (isEmpty(line.gutterMarkers)) line.gutterMarkers = null; + } + ++i; + }); + }), + + lineInfo: function (line) { + if (typeof line === "number") { + if (!isLine(this.doc, line)) return null; + var n = line; + line = getLine(this.doc, line); + if (!line) return null; + } else { + var n = lineNo(line); + if (n == null) return null; + } + return {line: n, handle: line, text: line.text, gutterMarkers: line.gutterMarkers, + textClass: line.textClass, bgClass: line.bgClass, wrapClass: line.wrapClass, + widgets: line.widgets}; + }, + + getViewport: function () { return {from: this.display.viewFrom, to: this.display.viewTo};}, + + addWidget: function (pos, node, scroll, vert, horiz) { + var display = this.display; + pos = cursorCoords(this, clipPos(this.doc, pos)); + var top = pos.bottom, left = pos.left; + node.style.position = "absolute"; + node.setAttribute("cm-ignore-events", "true"); + this.display.input.setUneditable(node); + display.sizer.appendChild(node); + if (vert == "over") { + top = pos.top; + } else if (vert == "above" || vert == "near") { + var vspace = Math.max(display.wrapper.clientHeight, this.doc.height), + hspace = Math.max(display.sizer.clientWidth, display.lineSpace.clientWidth); + // Default to positioning above (if specified and possible); otherwise default to positioning below + if ((vert == "above" || pos.bottom + node.offsetHeight > vspace) && pos.top > node.offsetHeight) {top = pos.top - node.offsetHeight;} else if (pos.bottom + node.offsetHeight <= vspace) {top = pos.bottom;} + if (left + node.offsetWidth > hspace) {left = hspace - node.offsetWidth;} + } + node.style.top = top + "px"; + node.style.left = node.style.right = ""; + if (horiz == "right") { + left = display.sizer.clientWidth - node.offsetWidth; + node.style.right = "0px"; + } else { + if (horiz == "left") left = 0; + else if (horiz == "middle") left = (display.sizer.clientWidth - node.offsetWidth) / 2; + node.style.left = left + "px"; + } + if (scroll) {scrollIntoView(this, left, top, left + node.offsetWidth, top + node.offsetHeight);} + }, + + triggerOnKeyDown: methodOp(onKeyDown), + triggerOnKeyPress: methodOp(onKeyPress), + triggerOnKeyUp: onKeyUp, + + execCommand: function (cmd) { + if (commands.hasOwnProperty(cmd)) {return commands[cmd](this);} + }, + + triggerElectric: methodOp(function (text) { triggerElectric(this, text); }), + + findPosH: function (from, amount, unit, visually) { + var dir = 1; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + cur = findPosH(this.doc, cur, dir, unit, visually); + if (cur.hitSide) break; + } + return cur; + }, + + moveH: methodOp(function (dir, unit) { + var cm = this; + cm.extendSelectionsBy(function (range) { + if (cm.display.shift || cm.doc.extend || range.empty()) {return findPosH(cm.doc, range.head, dir, unit, cm.options.rtlMoveVisually);} + return dir < 0 ? range.from() : range.to(); + }, sel_move); + }), + + deleteH: methodOp(function (dir, unit) { + var sel = this.doc.sel, doc = this.doc; + if (sel.somethingSelected()) {doc.replaceSelection("", null, "+delete");} else { + deleteNearSelection(this, function (range) { + var other = findPosH(doc, range.head, dir, unit, false); + return dir < 0 ? {from: other, to: range.head} : {from: range.head, to: other}; + }); + } + }), + + findPosV: function (from, amount, unit, goalColumn) { + var dir = 1, x = goalColumn; + if (amount < 0) { dir = -1; amount = -amount; } + for (var i = 0, cur = clipPos(this.doc, from); i < amount; ++i) { + var coords = cursorCoords(this, cur, "div"); + if (x == null) x = coords.left; + else coords.left = x; + cur = findPosV(this, coords, dir, unit); + if (cur.hitSide) break; + } + return cur; + }, + + moveV: methodOp(function (dir, unit) { + var cm = this, doc = this.doc, goals = []; + var collapse = !cm.display.shift && !doc.extend && doc.sel.somethingSelected(); + doc.extendSelectionsBy(function (range) { + if (collapse) {return dir < 0 ? range.from() : range.to();} + var headPos = cursorCoords(cm, range.head, "div"); + if (range.goalColumn != null) headPos.left = range.goalColumn; + goals.push(headPos.left); + var pos = findPosV(cm, headPos, dir, unit); + if (unit == "page" && range == doc.sel.primary()) {addToScrollPos(cm, null, charCoords(cm, pos, "div").top - headPos.top);} + return pos; + }, sel_move); + if (goals.length) { + for (var i = 0; i < doc.sel.ranges.length; i++) {doc.sel.ranges[i].goalColumn = goals[i];} + } + }), + + // Find the word at the given position (as returned by coordsChar). + findWordAt: function (pos) { + var doc = this.doc, line = getLine(doc, pos.line).text; + var start = pos.ch, end = pos.ch; + if (line) { + var helper = this.getHelper(pos, "wordChars"); + if ((pos.xRel < 0 || end == line.length) && start) --start; else ++end; + var startChar = line.charAt(start); + var check = isWordChar(startChar, helper) + ? function (ch) { return isWordChar(ch, helper); } + : /\s/.test(startChar) ? function (ch) {return /\s/.test(ch);} + : function (ch) {return !/\s/.test(ch) && !isWordChar(ch);}; + while (start > 0 && check(line.charAt(start - 1))) --start; + while (end < line.length && check(line.charAt(end))) ++end; + } + return new Range(Pos(pos.line, start), Pos(pos.line, end)); + }, + + toggleOverwrite: function (value) { + if (value != null && value == this.state.overwrite) return; + if (this.state.overwrite = !this.state.overwrite) {addClass(this.display.cursorDiv, "CodeMirror-overwrite");} else {rmClass(this.display.cursorDiv, "CodeMirror-overwrite");} + + signal(this, "overwriteToggle", this, this.state.overwrite); + }, + hasFocus: function () { return this.display.input.getField() == activeElt(); }, + + scrollTo: methodOp(function (x, y) { + if (x != null || y != null) resolveScrollToPos(this); + if (x != null) this.curOp.scrollLeft = x; + if (y != null) this.curOp.scrollTop = y; + }), + getScrollInfo: function () { + var scroller = this.display.scroller; + return {left: scroller.scrollLeft, top: scroller.scrollTop, + height: scroller.scrollHeight - scrollGap(this) - this.display.barHeight, + width: scroller.scrollWidth - scrollGap(this) - this.display.barWidth, + clientHeight: displayHeight(this), clientWidth: displayWidth(this)}; + }, + + scrollIntoView: methodOp(function (range, margin) { + if (range == null) { + range = {from: this.doc.sel.primary().head, to: null}; + if (margin == null) margin = this.options.cursorScrollMargin; + } else if (typeof range === "number") { + range = {from: Pos(range, 0), to: null}; + } else if (range.from == null) { + range = {from: range, to: null}; + } + if (!range.to) range.to = range.from; + range.margin = margin || 0; + + if (range.from.line != null) { + resolveScrollToPos(this); + this.curOp.scrollToPos = range; + } else { + var sPos = calculateScrollPos(this, Math.min(range.from.left, range.to.left), + Math.min(range.from.top, range.to.top) - range.margin, + Math.max(range.from.right, range.to.right), + Math.max(range.from.bottom, range.to.bottom) + range.margin); + this.scrollTo(sPos.scrollLeft, sPos.scrollTop); + } + }), + + setSize: methodOp(function (width, height) { + var cm = this; + function interpret (val) { + return typeof val === "number" || /^\d+$/.test(String(val)) ? val + "px" : val; + } + if (width != null) cm.display.wrapper.style.width = interpret(width); + if (height != null) cm.display.wrapper.style.height = interpret(height); + if (cm.options.lineWrapping) clearLineMeasurementCache(this); + var lineNo = cm.display.viewFrom; + cm.doc.iter(lineNo, cm.display.viewTo, function (line) { + if (line.widgets) { + for (var i = 0; i < line.widgets.length; i++) {if (line.widgets[i].noHScroll) { regLineChange(cm, lineNo, "widget"); break; }} + } + ++lineNo; + }); + cm.curOp.forceUpdate = true; + signal(cm, "refresh", this); + }), + + operation: function (f) {return runInOp(this, f);}, + + refresh: methodOp(function () { + var oldHeight = this.display.cachedTextHeight; + regChange(this); + this.curOp.forceUpdate = true; + clearCaches(this); + this.scrollTo(this.doc.scrollLeft, this.doc.scrollTop); + updateGutterSpace(this); + if (oldHeight == null || Math.abs(oldHeight - textHeight(this.display)) > .5) {estimateLineHeights(this);} + signal(this, "refresh", this); + }), + + swapDoc: methodOp(function (doc) { + var old = this.doc; + old.cm = null; + attachDoc(this, doc); + clearCaches(this); + this.display.input.reset(); + this.scrollTo(doc.scrollLeft, doc.scrollTop); + this.curOp.forceScroll = true; + signalLater(this, "swapDoc", this, old); + return old; + }), + + getInputField: function () {return this.display.input.getField();}, + getWrapperElement: function () {return this.display.wrapper;}, + getScrollerElement: function () {return this.display.scroller;}, + getGutterElement: function () {return this.display.gutters;} + }; + eventMixin(CodeMirror); + + // OPTION DEFAULTS + + // The default configuration options. + var defaults = CodeMirror.defaults = {}; + // Functions to run when options are changed. + var optionHandlers = CodeMirror.optionHandlers = {}; + + function option (name, deflt, handle, notOnInit) { + CodeMirror.defaults[name] = deflt; + if (handle) { + optionHandlers[name] = + notOnInit ? function (cm, val, old) {if (old != Init) handle(cm, val, old);} : handle; + } + } + + // Passed to option handlers when there is no old value. + var Init = CodeMirror.Init = {toString: function () {return "CodeMirror.Init";}}; + + // These two are, on init, called from the constructor because they + // have to be initialized before the editor can start at all. + option("value", "", function (cm, val) { + cm.setValue(val); + }, true); + option("mode", null, function (cm, val) { + cm.doc.modeOption = val; + loadMode(cm); + }, true); + + option("indentUnit", 2, loadMode, true); + option("indentWithTabs", false); + option("smartIndent", true); + option("tabSize", 4, function (cm) { + resetModeState(cm); + clearCaches(cm); + regChange(cm); + }, true); + option("specialChars", /[\t\u0000-\u0019\u00ad\u200b-\u200f\u2028\u2029\ufeff]/g, function (cm, val, old) { + cm.state.specialChars = new RegExp(val.source + (val.test("\t") ? "" : "|\t"), "g"); + if (old != CodeMirror.Init) cm.refresh(); + }); + option("specialCharPlaceholder", defaultSpecialCharPlaceholder, function (cm) {cm.refresh();}, true); + option("electricChars", true); + option("inputStyle", mobile ? "contenteditable" : "textarea", function () { + throw new Error("inputStyle can not (yet) be changed in a running editor"); // FIXME + }, true); + option("rtlMoveVisually", !windows); + option("wholeLineUpdateBefore", true); + + option("theme", "default", function (cm) { + themeChanged(cm); + guttersChanged(cm); + }, true); + option("keyMap", "default", function (cm, val, old) { + var next = getKeyMap(val); + var prev = old != CodeMirror.Init && getKeyMap(old); + if (prev && prev.detach) prev.detach(cm, next); + if (next.attach) next.attach(cm, prev || null); + }); + option("extraKeys", null); + + option("lineWrapping", false, wrappingChanged, true); + option("gutters", [], function (cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("fixedGutter", true, function (cm, val) { + cm.display.gutters.style.left = val ? compensateForHScroll(cm.display) + "px" : "0"; + cm.refresh(); + }, true); + option("coverGutterNextToScrollbar", false, function (cm) {updateScrollbars(cm);}, true); + option("scrollbarStyle", "native", function (cm) { + initScrollbars(cm); + updateScrollbars(cm); + cm.display.scrollbars.setScrollTop(cm.doc.scrollTop); + cm.display.scrollbars.setScrollLeft(cm.doc.scrollLeft); + }, true); + option("lineNumbers", false, function (cm) { + setGuttersForLineNumbers(cm.options); + guttersChanged(cm); + }, true); + option("firstLineNumber", 1, guttersChanged, true); + option("lineNumberFormatter", function (integer) {return integer;}, guttersChanged, true); + option("showCursorWhenSelecting", false, updateSelection, true); + + option("resetSelectionOnContextMenu", true); + option("lineWiseCopyCut", true); + + option("readOnly", false, function (cm, val) { + if (val == "nocursor") { + onBlur(cm); + cm.display.input.blur(); + cm.display.disabled = true; + } else { + cm.display.disabled = false; + if (!val) cm.display.input.reset(); + } + }); + option("disableInput", false, function (cm, val) {if (!val) cm.display.input.reset();}, true); + option("dragDrop", true, dragDropChanged); + + option("cursorBlinkRate", 530); + option("cursorScrollMargin", 0); + option("cursorHeight", 1, updateSelection, true); + option("singleCursorHeightPerLine", true, updateSelection, true); + option("workTime", 100); + option("workDelay", 100); + option("flattenSpans", true, resetModeState, true); + option("addModeClass", false, resetModeState, true); + option("pollInterval", 100); + option("undoDepth", 200, function (cm, val) {cm.doc.history.undoDepth = val;}); + option("historyEventDelay", 1250); + option("viewportMargin", 10, function (cm) {cm.refresh();}, true); + option("maxHighlightLength", 10000, resetModeState, true); + option("moveInputWithCursor", true, function (cm, val) { + if (!val) cm.display.input.resetPosition(); + }); + + option("tabindex", null, function (cm, val) { + cm.display.input.getField().tabIndex = val || ""; }); - return out; - } - // Get the lines between from and to, as array of strings. - function getLines(doc, from, to, lineFilter) { - var out = []; - doc.iter(from, to, function(line) { - var text = line.text; - if(lineFilter){ - text = lineFilter(line); - } - out.push(text); + option("autofocus", null); + + // MODE DEFINITION AND QUERYING + + // Known modes, by name and by MIME + var modes = CodeMirror.modes = {}, mimeModes = CodeMirror.mimeModes = {}; + + // Extra arguments are stored as the mode's dependencies, which is + // used by (legacy) mechanisms like loadmode.js to automatically + // load a mode. (Preferred mechanism is the require/define calls.) + CodeMirror.defineMode = function (name, mode) { + if (!CodeMirror.defaults.mode && name != "null") CodeMirror.defaults.mode = name; + if (arguments.length > 2) {mode.dependencies = Array.prototype.slice.call(arguments, 2);} + modes[name] = mode; + }; + + CodeMirror.defineMIME = function (mime, spec) { + mimeModes[mime] = spec; + }; + + // Given a MIME type, a {name, ...options} config object, or a name + // string, return a mode config object. + CodeMirror.resolveMode = function (spec) { + if (typeof spec === "string" && mimeModes.hasOwnProperty(spec)) { + spec = mimeModes[spec]; + } else if (spec && typeof spec.name === "string" && mimeModes.hasOwnProperty(spec.name)) { + var found = mimeModes[spec.name]; + if (typeof found === "string") found = {name: found}; + spec = createObj(found, spec); + spec.name = found.name; + } else if (typeof spec === "string" && /^[\w\-]+\/[\w\-]+\+xml$/.test(spec)) { + return CodeMirror.resolveMode("application/xml"); + } + if (typeof spec === "string") return {name: spec}; + return spec || {name: "null"}; + }; + + // Given a mode spec (anything that resolveMode accepts), find and + // initialize an actual mode object. + CodeMirror.getMode = function (options, spec) { + var spec = CodeMirror.resolveMode(spec); + var mfactory = modes[spec.name]; + if (!mfactory) return CodeMirror.getMode(options, "text/plain"); + var modeObj = mfactory(options, spec); + if (modeExtensions.hasOwnProperty(spec.name)) { + var exts = modeExtensions[spec.name]; + for (var prop in exts) { + if (!exts.hasOwnProperty(prop)) continue; + if (modeObj.hasOwnProperty(prop)) modeObj["_" + prop] = modeObj[prop]; + modeObj[prop] = exts[prop]; + } + } + modeObj.name = spec.name; + if (spec.helperType) modeObj.helperType = spec.helperType; + if (spec.modeProps) { + for (var prop in spec.modeProps) {modeObj[prop] = spec.modeProps[prop];} + } + + return modeObj; + }; + + // Minimal default mode. + CodeMirror.defineMode("null", function () { + return {token: function (stream) {stream.skipToEnd();}}; + }); + CodeMirror.defineMIME("text/plain", "null"); + + // This can be used to attach properties to mode objects from + // outside the actual mode definition. + var modeExtensions = CodeMirror.modeExtensions = {}; + CodeMirror.extendMode = function (mode, properties) { + var exts = modeExtensions.hasOwnProperty(mode) ? modeExtensions[mode] : (modeExtensions[mode] = {}); + copyObj(properties, exts); + }; + + // EXTENSIONS + + CodeMirror.defineExtension = function (name, func) { + CodeMirror.prototype[name] = func; + }; + CodeMirror.defineDocExtension = function (name, func) { + Doc.prototype[name] = func; + }; + CodeMirror.defineOption = option; + + var initHooks = []; + CodeMirror.defineInitHook = function (f) {initHooks.push(f);}; + + var helpers = CodeMirror.helpers = {}; + CodeMirror.registerHelper = function (type, name, value) { + if (!helpers.hasOwnProperty(type)) helpers[type] = CodeMirror[type] = {_global: []}; + helpers[type][name] = value; + }; + CodeMirror.registerGlobalHelper = function (type, name, predicate, value) { + CodeMirror.registerHelper(type, name, value); + helpers[type]._global.push({pred: predicate, val: value}); + }; + + // MODE STATE HANDLING + + // Utility functions for working with state. Exported because nested + // modes need to do this for their inner modes. + + var copyState = CodeMirror.copyState = function (mode, state) { + if (state === true) return state; + if (mode.copyState) return mode.copyState(state); + var nstate = {}; + for (var n in state) { + var val = state[n]; + if (val instanceof Array) val = val.concat([]); + nstate[n] = val; + } + return nstate; + }; + + var startState = CodeMirror.startState = function (mode, a1, a2) { + return mode.startState ? mode.startState(a1, a2) : true; + }; + + // Given a mode and a state (for that mode), find the inner mode and + // state at the position that the state refers to. + CodeMirror.innerMode = function (mode, state) { + while (mode.innerMode) { + var info = mode.innerMode(state); + if (!info || info.mode == mode) break; + state = info.state; + mode = info.mode; + } + return info || {mode: mode, state: state}; + }; + + // STANDARD COMMANDS + + // Commands are parameter-less actions that can be performed on an + // editor, mostly used for keybindings. + var commands = CodeMirror.commands = { + selectAll: function (cm) {cm.setSelection(Pos(cm.firstLine(), 0), Pos(cm.lastLine()), sel_dontScroll);}, + singleSelection: function (cm) { + cm.setSelection(cm.getCursor("anchor"), cm.getCursor("head"), sel_dontScroll); + }, + killLine: function (cm) { + deleteNearSelection(cm, function (range) { + if (range.empty()) { + var len = getLine(cm.doc, range.head.line).text.length; + if (range.head.ch == len && range.head.line < cm.lastLine()) {return {from: range.head, to: Pos(range.head.line + 1, 0)};} + return {from: range.head, to: Pos(range.head.line, len)}; + } + return {from: range.from(), to: range.to()}; + + }); + }, + deleteLine: function (cm) { + deleteNearSelection(cm, function (range) { + return {from: Pos(range.from().line, 0), + to: clipPos(cm.doc, Pos(range.to().line + 1, 0))}; + }); + }, + delLineLeft: function (cm) { + deleteNearSelection(cm, function (range) { + return {from: Pos(range.from().line, 0), to: range.from()}; + }); + }, + delWrappedLineLeft: function (cm) { + deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var leftPos = cm.coordsChar({left: 0, top: top}, "div"); + return {from: leftPos, to: range.from()}; + }); + }, + delWrappedLineRight: function (cm) { + deleteNearSelection(cm, function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var rightPos = cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + return {from: range.from(), to: rightPos }; + }); + }, + undo: function (cm) {cm.undo();}, + redo: function (cm) {cm.redo();}, + undoSelection: function (cm) {cm.undoSelection();}, + redoSelection: function (cm) {cm.redoSelection();}, + goDocStart: function (cm) {cm.extendSelection(Pos(cm.firstLine(), 0));}, + goDocEnd: function (cm) {cm.extendSelection(Pos(cm.lastLine()));}, + goLineStart: function (cm) { + cm.extendSelectionsBy(function (range) { return lineStart(cm, range.head.line); }, + {origin: "+move", bias: 1}); + }, + goLineStartSmart: function (cm) { + cm.extendSelectionsBy(function (range) { + return lineStartSmart(cm, range.head); + }, {origin: "+move", bias: 1}); + }, + goLineEnd: function (cm) { + cm.extendSelectionsBy(function (range) { return lineEnd(cm, range.head.line); }, + {origin: "+move", bias: -1}); + }, + goLineRight: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: cm.display.lineDiv.offsetWidth + 100, top: top}, "div"); + }, sel_move); + }, + goLineLeft: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + return cm.coordsChar({left: 0, top: top}, "div"); + }, sel_move); + }, + goLineLeftSmart: function (cm) { + cm.extendSelectionsBy(function (range) { + var top = cm.charCoords(range.head, "div").top + 5; + var pos = cm.coordsChar({left: 0, top: top}, "div"); + if (pos.ch < cm.getLine(pos.line).search(/\S/)) return lineStartSmart(cm, range.head); + return pos; + }, sel_move); + }, + goLineUp: function (cm) {cm.moveV(-1, "line");}, + goLineDown: function (cm) {cm.moveV(1, "line");}, + goPageUp: function (cm) {cm.moveV(-1, "page");}, + goPageDown: function (cm) {cm.moveV(1, "page");}, + goCharLeft: function (cm) {cm.moveH(-1, "char");}, + goCharRight: function (cm) {cm.moveH(1, "char");}, + goColumnLeft: function (cm) {cm.moveH(-1, "column");}, + goColumnRight: function (cm) {cm.moveH(1, "column");}, + goWordLeft: function (cm) {cm.moveH(-1, "word");}, + goGroupRight: function (cm) {cm.moveH(1, "group");}, + goGroupLeft: function (cm) {cm.moveH(-1, "group");}, + goWordRight: function (cm) {cm.moveH(1, "word");}, + delCharBefore: function (cm) {cm.deleteH(-1, "char");}, + delCharAfter: function (cm) {cm.deleteH(1, "char");}, + delWordBefore: function (cm) {cm.deleteH(-1, "word");}, + delWordAfter: function (cm) {cm.deleteH(1, "word");}, + delGroupBefore: function (cm) {cm.deleteH(-1, "group");}, + delGroupAfter: function (cm) {cm.deleteH(1, "group");}, + indentAuto: function (cm) {cm.indentSelection("smart");}, + indentMore: function (cm) {cm.indentSelection("add");}, + indentLess: function (cm) {cm.indentSelection("subtract");}, + insertTab: function (cm) {cm.replaceSelection("\t");}, + insertSoftTab: function (cm) { + var spaces = [], ranges = cm.listSelections(), tabSize = cm.options.tabSize; + for (var i = 0; i < ranges.length; i++) { + var pos = ranges[i].from(); + var col = countColumn(cm.getLine(pos.line), pos.ch, tabSize); + spaces.push(new Array(tabSize - col % tabSize + 1).join(" ")); + } + cm.replaceSelections(spaces); + }, + defaultTab: function (cm) { + if (cm.somethingSelected()) cm.indentSelection("add"); + else cm.execCommand("insertTab"); + }, + transposeChars: function (cm) { + runInOp(cm, function () { + var ranges = cm.listSelections(), newSel = []; + for (var i = 0; i < ranges.length; i++) { + var cur = ranges[i].head, line = getLine(cm.doc, cur.line).text; + if (line) { + if (cur.ch == line.length) cur = new Pos(cur.line, cur.ch - 1); + if (cur.ch > 0) { + cur = new Pos(cur.line, cur.ch + 1); + cm.replaceRange(line.charAt(cur.ch - 1) + line.charAt(cur.ch - 2), + Pos(cur.line, cur.ch - 2), cur, "+transpose"); + } else if (cur.line > cm.doc.first) { + var prev = getLine(cm.doc, cur.line - 1).text; + if (prev) { + cm.replaceRange(line.charAt(0) + "\n" + prev.charAt(prev.length - 1), + Pos(cur.line - 1, prev.length - 1), Pos(cur.line, 1), "+transpose"); + } + } + } + newSel.push(new Range(cur, cur)); + } + cm.setSelections(newSel); + }); + }, + newlineAndIndent: function (cm) { + runInOp(cm, function () { + var len = cm.listSelections().length; + for (var i = 0; i < len; i++) { + var range = cm.listSelections()[i]; + cm.replaceRange("\n", range.anchor, range.head, "+input"); + cm.indentLine(range.from().line + 1, null, true); + ensureCursorVisible(cm); + } + }); + }, + toggleOverwrite: function (cm) {cm.toggleOverwrite();} + }; + + + // STANDARD KEYMAPS + + var keyMap = CodeMirror.keyMap = {}; + + keyMap.basic = { + Left: "goCharLeft", Right: "goCharRight", Up: "goLineUp", Down: "goLineDown", + End: "goLineEnd", Home: "goLineStartSmart", PageUp: "goPageUp", PageDown: "goPageDown", + Delete: "delCharAfter", Backspace: "delCharBefore", "Shift-Backspace": "delCharBefore", + Tab: "defaultTab", "Shift-Tab": "indentAuto", + Enter: "newlineAndIndent", Insert: "toggleOverwrite", + Esc: "singleSelection" + }; + // Note that the save and find-related commands aren't defined by + // default. User code or addons can define them. Unknown commands + // are simply ignored. + keyMap.pcDefault = { + "Ctrl-A": "selectAll", "Ctrl-D": "deleteLine", "Ctrl-Z": "undo", "Shift-Ctrl-Z": "redo", "Ctrl-Y": "redo", + "Ctrl-Home": "goDocStart", "Ctrl-End": "goDocEnd", "Ctrl-Up": "goLineUp", "Ctrl-Down": "goLineDown", + "Ctrl-Left": "goGroupLeft", "Ctrl-Right": "goGroupRight", "Alt-Left": "goLineStart", "Alt-Right": "goLineEnd", + "Ctrl-Backspace": "delGroupBefore", "Ctrl-Delete": "delGroupAfter", "Ctrl-S": "save", "Ctrl-F": "find", + "Ctrl-G": "findNext", "Shift-Ctrl-G": "findPrev", "Shift-Ctrl-F": "replace", "Shift-Ctrl-R": "replaceAll", + "Ctrl-[": "indentLess", "Ctrl-]": "indentMore", + "Ctrl-U": "undoSelection", "Shift-Ctrl-U": "redoSelection", "Alt-U": "redoSelection", + fallthrough: "basic" + }; + // Very basic readline/emacs-style bindings, which are standard on Mac. + keyMap.emacsy = { + "Ctrl-F": "goCharRight", "Ctrl-B": "goCharLeft", "Ctrl-P": "goLineUp", "Ctrl-N": "goLineDown", + "Alt-F": "goWordRight", "Alt-B": "goWordLeft", "Ctrl-A": "goLineStart", "Ctrl-E": "goLineEnd", + "Ctrl-V": "goPageDown", "Shift-Ctrl-V": "goPageUp", "Ctrl-D": "delCharAfter", "Ctrl-H": "delCharBefore", + "Alt-D": "delWordAfter", "Alt-Backspace": "delWordBefore", "Ctrl-K": "killLine", "Ctrl-T": "transposeChars" + }; + keyMap.macDefault = { + "Cmd-A": "selectAll", "Cmd-D": "deleteLine", "Cmd-Z": "undo", "Shift-Cmd-Z": "redo", "Cmd-Y": "redo", + "Cmd-Home": "goDocStart", "Cmd-Up": "goDocStart", "Cmd-End": "goDocEnd", "Cmd-Down": "goDocEnd", "Alt-Left": "goGroupLeft", + "Alt-Right": "goGroupRight", "Cmd-Left": "goLineLeft", "Cmd-Right": "goLineRight", "Alt-Backspace": "delGroupBefore", + "Ctrl-Alt-Backspace": "delGroupAfter", "Alt-Delete": "delGroupAfter", "Cmd-S": "save", "Cmd-F": "find", + "Cmd-G": "findNext", "Shift-Cmd-G": "findPrev", "Cmd-Alt-F": "replace", "Shift-Cmd-Alt-F": "replaceAll", + "Cmd-[": "indentLess", "Cmd-]": "indentMore", "Cmd-Backspace": "delWrappedLineLeft", "Cmd-Delete": "delWrappedLineRight", + "Cmd-U": "undoSelection", "Shift-Cmd-U": "redoSelection", "Ctrl-Up": "goDocStart", "Ctrl-Down": "goDocEnd", + fallthrough: ["basic", "emacsy"] + }; + keyMap["default"] = mac ? keyMap.macDefault : keyMap.pcDefault; + + // KEYMAP DISPATCH + + function normalizeKeyName (name) { + var parts = name.split(/-(?!$)/), name = parts[parts.length - 1]; + var alt, ctrl, shift, cmd; + for (var i = 0; i < parts.length - 1; i++) { + var mod = parts[i]; + if (/^(cmd|meta|m)$/i.test(mod)) cmd = true; + else if (/^a(lt)?$/i.test(mod)) alt = true; + else if (/^(c|ctrl|control)$/i.test(mod)) ctrl = true; + else if (/^s(hift)$/i.test(mod)) shift = true; + else throw new Error("Unrecognized modifier name: " + mod); + } + if (alt) name = "Alt-" + name; + if (ctrl) name = "Ctrl-" + name; + if (cmd) name = "Cmd-" + name; + if (shift) name = "Shift-" + name; + return name; + } + + // This is a kludge to keep keymaps mostly working as raw objects + // (backwards compatibility) while at the same time support features + // like normalization and multi-stroke key bindings. It compiles a + // new normalized keymap, and then updates the old object to reflect + // this. + CodeMirror.normalizeKeyMap = function (keymap) { + var copy = {}; + for (var keyname in keymap) { + if (keymap.hasOwnProperty(keyname)) { + var value = keymap[keyname]; + if (/^(name|fallthrough|(de|at)tach)$/.test(keyname)) continue; + if (value == "...") { delete keymap[keyname]; continue; } + + var keys = map(keyname.split(" "), normalizeKeyName); + for (var i = 0; i < keys.length; i++) { + var val, name; + if (i == keys.length - 1) { + name = keys.join(" "); + val = value; + } else { + name = keys.slice(0, i + 1).join(" "); + val = "..."; + } + var prev = copy[name]; + if (!prev) copy[name] = val; + else if (prev != val) throw new Error("Inconsistent bindings for " + name); + } + delete keymap[keyname]; + } + } + for (var prop in copy) keymap[prop] = copy[prop]; + return keymap; + }; + + var lookupKey = CodeMirror.lookupKey = function (key, map, handle, context) { + map = getKeyMap(map); + var found = map.call ? map.call(key, context) : map[key]; + if (found === false) return "nothing"; + if (found === "...") return "multi"; + if (found != null && handle(found)) return "handled"; + + if (map.fallthrough) { + if (Object.prototype.toString.call(map.fallthrough) != "[object Array]") {return lookupKey(key, map.fallthrough, handle, context);} + for (var i = 0; i < map.fallthrough.length; i++) { + var result = lookupKey(key, map.fallthrough[i], handle, context); + if (result) return result; + } + } + }; + + // Modifier key presses don't count as 'real' key presses for the + // purpose of keymap fallthrough. + var isModifierKey = CodeMirror.isModifierKey = function (value) { + var name = typeof value === "string" ? value : keyNames[value.keyCode]; + return name == "Ctrl" || name == "Alt" || name == "Shift" || name == "Mod"; + }; + + // Look up the name of a key as indicated by an event object. + var keyName = CodeMirror.keyName = function (event, noShift) { + if (presto && event.keyCode == 34 && event["char"]) return false; + var base = keyNames[event.keyCode], name = base; + if (name == null || event.altGraphKey) return false; + if (event.altKey && base != "Alt") name = "Alt-" + name; + if ((flipCtrlCmd ? event.metaKey : event.ctrlKey) && base != "Ctrl") name = "Ctrl-" + name; + if ((flipCtrlCmd ? event.ctrlKey : event.metaKey) && base != "Cmd") name = "Cmd-" + name; + if (!noShift && event.shiftKey && base != "Shift") name = "Shift-" + name; + return name; + }; + + function getKeyMap (val) { + return typeof val === "string" ? keyMap[val] : val; + } + + // FROMTEXTAREA + + CodeMirror.fromTextArea = function (textarea, options) { + options = options ? copyObj(options) : {}; + options.value = textarea.value; + if (!options.tabindex && textarea.tabIndex) {options.tabindex = textarea.tabIndex;} + if (!options.placeholder && textarea.placeholder) {options.placeholder = textarea.placeholder;} + // Set autofocus to true if this textarea is focused, or if it has + // autofocus and no other element is focused. + if (options.autofocus == null) { + var hasFocus = activeElt(); + options.autofocus = hasFocus == textarea || + textarea.getAttribute("autofocus") != null && hasFocus == document.body; + } + + function save () {textarea.value = cm.getValue();} + if (textarea.form) { + on(textarea.form, "submit", save); + // Deplorable hack to make the submit method do the right thing. + if (!options.leaveSubmitMethodAlone) { + var form = textarea.form, realSubmit = form.submit; + try { + var wrappedSubmit = form.submit = function () { + save(); + form.submit = realSubmit; + form.submit(); + form.submit = wrappedSubmit; + }; + } catch(e) {} + } + } + + options.finishInit = function (cm) { + cm.save = save; + cm.getTextArea = function () { return textarea; }; + cm.toTextArea = function () { + cm.toTextArea = isNaN; // Prevent this from being ran twice + save(); + textarea.parentNode.removeChild(cm.getWrapperElement()); + textarea.style.display = ""; + if (textarea.form) { + off(textarea.form, "submit", save); + if (typeof textarea.form.submit === "function") {textarea.form.submit = realSubmit;} + } + }; + }; + + textarea.style.display = "none"; + var cm = CodeMirror(function (node) { + textarea.parentNode.insertBefore(node, textarea.nextSibling); + }, options); + return cm; + }; + + // STRING STREAM + + // Fed to the mode parsers, provides helper functions to make + // parsers more succinct. + + var StringStream = CodeMirror.StringStream = function (string, tabSize) { + this.pos = this.start = 0; + this.string = string; + this.tabSize = tabSize || 8; + this.lastColumnPos = this.lastColumnValue = 0; + this.lineStart = 0; + }; + + StringStream.prototype = { + eol: function () {return this.pos >= this.string.length;}, + sol: function () {return this.pos == this.lineStart;}, + peek: function () {return this.string.charAt(this.pos) || undefined;}, + next: function () { + if (this.pos < this.string.length) {return this.string.charAt(this.pos++);} + }, + eat: function (match) { + var ch = this.string.charAt(this.pos); + if (typeof match === "string") var ok = ch == match; + else var ok = ch && (match.test ? match.test(ch) : match(ch)); + if (ok) {++this.pos; return ch;} + }, + eatWhile: function (match) { + var start = this.pos; + while (this.eat(match)) {} + return this.pos > start; + }, + eatSpace: function () { + var start = this.pos; + while (/[\s\u00a0]/.test(this.string.charAt(this.pos))) ++this.pos; + return this.pos > start; + }, + skipToEnd: function () {this.pos = this.string.length;}, + skipTo: function (ch) { + var found = this.string.indexOf(ch, this.pos); + if (found > -1) {this.pos = found; return true;} + }, + backUp: function (n) {this.pos -= n;}, + column: function () { + if (this.lastColumnPos < this.start) { + this.lastColumnValue = countColumn(this.string, this.start, this.tabSize, this.lastColumnPos, this.lastColumnValue); + this.lastColumnPos = this.start; + } + return this.lastColumnValue - (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + indentation: function () { + return countColumn(this.string, null, this.tabSize) - + (this.lineStart ? countColumn(this.string, this.lineStart, this.tabSize) : 0); + }, + match: function (pattern, consume, caseInsensitive) { + if (typeof pattern === "string") { + var cased = function (str) {return caseInsensitive ? str.toLowerCase() : str;}; + var substr = this.string.substr(this.pos, pattern.length); + if (cased(substr) == cased(pattern)) { + if (consume !== false) this.pos += pattern.length; + return true; + } + } else { + var match = this.string.slice(this.pos).match(pattern); + if (match && match.index > 0) return null; + if (match && consume !== false) this.pos += match[0].length; + return match; + } + }, + current: function () {return this.string.slice(this.start, this.pos);}, + hideFirstChars: function (n, inner) { + this.lineStart += n; + try { return inner(); } finally { this.lineStart -= n; } + } + }; + + // TEXTMARKERS + + // Created with markText and setBookmark methods. A TextMarker is a + // handle that can be used to clear or find a marked position in the + // document. Line objects hold arrays (markedSpans) containing + // {from, to, marker} object pointing to such marker objects, and + // indicating that such a marker is present on that line. Multiple + // lines may point to the same marker when it spans across lines. + // The spans will have null for their from/to properties when the + // marker continues beyond the start/end of the line. Markers have + // links back to the lines they currently touch. + + var nextMarkerId = 0; + + var TextMarker = CodeMirror.TextMarker = function (doc, type) { + this.lines = []; + this.type = type; + this.doc = doc; + this.id = ++nextMarkerId; + }; + eventMixin(TextMarker); + + // Clear the marker. + TextMarker.prototype.clear = function () { + if (this.explicitlyCleared) return; + var cm = this.doc.cm, withOp = cm && !cm.curOp; + if (withOp) startOperation(cm); + if (hasHandler(this, "clear")) { + var found = this.find(); + if (found) signalLater(this, "clear", found.from, found.to); + } + var min = null, max = null; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (cm && !this.collapsed) regLineChange(cm, lineNo(line), "text"); + else if (cm) { + if (span.to != null) max = lineNo(line); + if (span.from != null) min = lineNo(line); + } + line.markedSpans = removeMarkedSpan(line.markedSpans, span); + if (span.from == null && this.collapsed && !lineIsHidden(this.doc, line) && cm) {updateLineHeight(line, textHeight(cm.display));} + } + if (cm && this.collapsed && !cm.options.lineWrapping) { + for (var i = 0; i < this.lines.length; ++i) { + var visual = visualLine(this.lines[i]), len = lineLength(visual); + if (len > cm.display.maxLineLength) { + cm.display.maxLine = visual; + cm.display.maxLineLength = len; + cm.display.maxLineChanged = true; + } + } + } + + if (min != null && cm && this.collapsed) regChange(cm, min, max + 1); + this.lines.length = 0; + this.explicitlyCleared = true; + if (this.atomic && this.doc.cantEdit) { + this.doc.cantEdit = false; + if (cm) reCheckSelection(cm.doc); + } + if (cm) signalLater(cm, "markerCleared", cm, this); + if (withOp) endOperation(cm); + if (this.parent) this.parent.clear(); + }; + + // Find the position of the marker in the document. Returns a {from, + // to} object by default. Side can be passed to get a specific side + // -- 0 (both), -1 (left), or 1 (right). When lineObj is true, the + // Pos objects returned contain a line object, rather than a line + // number (used to prevent looking up the same line twice). + TextMarker.prototype.find = function (side, lineObj) { + if (side == null && this.type == "bookmark") side = 1; + var from, to; + for (var i = 0; i < this.lines.length; ++i) { + var line = this.lines[i]; + var span = getMarkedSpanFor(line.markedSpans, this); + if (span.from != null) { + from = Pos(lineObj ? line : lineNo(line), span.from); + if (side == -1) return from; + } + if (span.to != null) { + to = Pos(lineObj ? line : lineNo(line), span.to); + if (side == 1) return to; + } + } + return from && {from: from, to: to}; + }; + + // Signals that the marker's widget changed, and surrounding layout + // should be recomputed. + TextMarker.prototype.changed = function () { + var pos = this.find(-1, true), widget = this, cm = this.doc.cm; + if (!pos || !cm) return; + runInOp(cm, function () { + var line = pos.line, lineN = lineNo(pos.line); + var view = findViewForLine(cm, lineN); + if (view) { + clearLineMeasurementCacheFor(view); + cm.curOp.selectionChanged = cm.curOp.forceUpdate = true; + } + cm.curOp.updateMaxLine = true; + if (!lineIsHidden(widget.doc, line) && widget.height != null) { + var oldHeight = widget.height; + widget.height = null; + var dHeight = widgetHeight(widget) - oldHeight; + if (dHeight) {updateLineHeight(line, line.height + dHeight);} + } + }); + }; + + TextMarker.prototype.attachLine = function (line) { + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + if (!op.maybeHiddenMarkers || indexOf(op.maybeHiddenMarkers, this) == -1) {(op.maybeUnhiddenMarkers || (op.maybeUnhiddenMarkers = [])).push(this);} + } + this.lines.push(line); + }; + TextMarker.prototype.detachLine = function (line) { + this.lines.splice(indexOf(this.lines, line), 1); + if (!this.lines.length && this.doc.cm) { + var op = this.doc.cm.curOp; + (op.maybeHiddenMarkers || (op.maybeHiddenMarkers = [])).push(this); + } + }; + + // Collapsed markers have unique ids, in order to be able to order + // them, which is needed for uniquely determining an outer marker + // when they overlap (they may nest, but not partially overlap). + var nextMarkerId = 0; + + // Create a marker, wire it up to the right lines, and + function markText (doc, from, to, options, type) { + // Shared markers (across linked documents) are handled separately + // (markTextShared will call out to this again, once per + // document). + if (options && options.shared) return markTextShared(doc, from, to, options, type); + // Ensure we are in an operation. + if (doc.cm && !doc.cm.curOp) return operation(doc.cm, markText)(doc, from, to, options, type); + + var marker = new TextMarker(doc, type), diff = cmp(from, to); + if (options) copyObj(options, marker, false); + // Don't connect empty markers unless clearWhenEmpty is false + if (diff > 0 || diff == 0 && marker.clearWhenEmpty !== false) {return marker;} + if (marker.replacedWith) { + // Showing up as a widget implies collapsed (widget replaces text) + marker.collapsed = true; + marker.widgetNode = elt("span", [marker.replacedWith], "CodeMirror-widget"); + if (!options.handleMouseEvents) marker.widgetNode.setAttribute("cm-ignore-events", "true"); + if (options.insertLeft) marker.widgetNode.insertLeft = true; + } + if (marker.collapsed) { + if (conflictingCollapsedRange(doc, from.line, from, to, marker) || + from.line != to.line && conflictingCollapsedRange(doc, to.line, from, to, marker)) {throw new Error("Inserting collapsed marker partially overlapping an existing one");} + sawCollapsedSpans = true; + } + + if (marker.addToHistory) {addChangeToHistory(doc, {from: from, to: to, origin: "markText"}, doc.sel, NaN);} + + var curLine = from.line, cm = doc.cm, updateMaxLine; + doc.iter(curLine, to.line + 1, function (line) { + if (cm && marker.collapsed && !cm.options.lineWrapping && visualLine(line) == cm.display.maxLine) {updateMaxLine = true;} + if (marker.collapsed && curLine != from.line) updateLineHeight(line, 0); + addMarkedSpan(line, new MarkedSpan(marker, + curLine == from.line ? from.ch : null, + curLine == to.line ? to.ch : null)); + ++curLine; + }); + // lineIsHidden depends on the presence of the spans, so needs a second pass + if (marker.collapsed) { + doc.iter(from.line, to.line + 1, function (line) { + if (lineIsHidden(doc, line)) updateLineHeight(line, 0); + }); + } + + if (marker.clearOnEnter) on(marker, "beforeCursorEnter", function () { marker.clear(); }); + + if (marker.readOnly) { + sawReadOnlySpans = true; + if (doc.history.done.length || doc.history.undone.length) {doc.clearHistory();} + } + if (marker.collapsed) { + marker.id = ++nextMarkerId; + marker.atomic = true; + } + if (cm) { + // Sync editor state + if (updateMaxLine) cm.curOp.updateMaxLine = true; + if (marker.collapsed) {regChange(cm, from.line, to.line + 1);} else if (marker.className || marker.title || marker.startStyle || marker.endStyle || marker.css) {for (var i = from.line; i <= to.line; i++) regLineChange(cm, i, "text");} + if (marker.atomic) reCheckSelection(cm.doc); + signalLater(cm, "markerAdded", cm, marker); + } + return marker; + } + + // SHARED TEXTMARKERS + + // A shared marker spans multiple linked documents. It is + // implemented as a meta-marker-object controlling multiple normal + // markers. + var SharedTextMarker = CodeMirror.SharedTextMarker = function (markers, primary) { + this.markers = markers; + this.primary = primary; + for (var i = 0; i < markers.length; ++i) {markers[i].parent = this;} + }; + eventMixin(SharedTextMarker); + + SharedTextMarker.prototype.clear = function () { + if (this.explicitlyCleared) return; + this.explicitlyCleared = true; + for (var i = 0; i < this.markers.length; ++i) {this.markers[i].clear();} + signalLater(this, "clear"); + }; + SharedTextMarker.prototype.find = function (side, lineObj) { + return this.primary.find(side, lineObj); + }; + + function markTextShared (doc, from, to, options, type) { + options = copyObj(options); + options.shared = false; + var markers = [markText(doc, from, to, options, type)], primary = markers[0]; + var widget = options.widgetNode; + linkedDocs(doc, function (doc) { + if (widget) options.widgetNode = widget.cloneNode(true); + markers.push(markText(doc, clipPos(doc, from), clipPos(doc, to), options, type)); + for (var i = 0; i < doc.linked.length; ++i) {if (doc.linked[i].isParent) return;} + primary = lst(markers); + }); + return new SharedTextMarker(markers, primary); + } + + function findSharedMarkers (doc) { + return doc.findMarks(Pos(doc.first, 0), doc.clipPos(Pos(doc.lastLine())), + function (m) { return m.parent; }); + } + + function copySharedMarkers (doc, markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], pos = marker.find(); + var mFrom = doc.clipPos(pos.from), mTo = doc.clipPos(pos.to); + if (cmp(mFrom, mTo)) { + var subMark = markText(doc, mFrom, mTo, marker.primary, marker.primary.type); + marker.markers.push(subMark); + subMark.parent = marker; + } + } + } + + function detachSharedMarkers (markers) { + for (var i = 0; i < markers.length; i++) { + var marker = markers[i], linked = [marker.primary.doc]; + linkedDocs(marker.primary.doc, function (d) { linked.push(d); }); + for (var j = 0; j < marker.markers.length; j++) { + var subMarker = marker.markers[j]; + if (indexOf(linked, subMarker.doc) == -1) { + subMarker.parent = null; + marker.markers.splice(j--, 1); + } + } + } + } + + // TEXTMARKER SPANS + + function MarkedSpan (marker, from, to) { + this.marker = marker; + this.from = from; this.to = to; + } + + // Search an array of spans for a span matching the given marker. + function getMarkedSpanFor (spans, marker) { + if (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.marker == marker) return span; + } + } + } + // Remove a span from an array, returning undefined if no spans are + // left (we don't store arrays for lines without spans). + function removeMarkedSpan (spans, span) { + for (var r, i = 0; i < spans.length; ++i) {if (spans[i] != span) (r || (r = [])).push(spans[i]);} + return r; + } + // Add a span to a line. + function addMarkedSpan (line, span) { + line.markedSpans = line.markedSpans ? line.markedSpans.concat([span]) : [span]; + span.marker.attachLine(line); + } + + // Used for the algorithm that adjusts markers for a change in the + // document. These functions cut an array of spans at a given + // character position, returning an array of remaining chunks (or + // undefined if nothing remains). + function markedSpansBefore (old, startCh, isInsert) { + if (old) { + for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= startCh : span.from < startCh); + if (startsBefore || span.from == startCh && marker.type == "bookmark" && (!isInsert || !span.marker.insertLeft)) { + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= startCh : span.to > startCh); + (nw || (nw = [])).push(new MarkedSpan(marker, span.from, endsAfter ? null : span.to)); + } + } + } + return nw; + } + function markedSpansAfter (old, endCh, isInsert) { + if (old) { + for (var i = 0, nw; i < old.length; ++i) { + var span = old[i], marker = span.marker; + var endsAfter = span.to == null || (marker.inclusiveRight ? span.to >= endCh : span.to > endCh); + if (endsAfter || span.from == endCh && marker.type == "bookmark" && (!isInsert || span.marker.insertLeft)) { + var startsBefore = span.from == null || (marker.inclusiveLeft ? span.from <= endCh : span.from < endCh); + (nw || (nw = [])).push(new MarkedSpan(marker, startsBefore ? null : span.from - endCh, + span.to == null ? null : span.to - endCh)); + } + } + } + return nw; + } + + // Given a change object, compute the new set of marker spans that + // cover the line in which the change took place. Removes spans + // entirely within the change, reconnects spans belonging to the + // same marker that appear on both sides of the change, and cuts off + // spans partially within the change. Returns an array of span + // arrays with one element for each line in (after) the change. + function stretchSpansOverChange (doc, change) { + if (change.full) return null; + var oldFirst = isLine(doc, change.from.line) && getLine(doc, change.from.line).markedSpans; + var oldLast = isLine(doc, change.to.line) && getLine(doc, change.to.line).markedSpans; + if (!oldFirst && !oldLast) return null; + + var startCh = change.from.ch, endCh = change.to.ch, isInsert = cmp(change.from, change.to) == 0; + // Get the spans that 'stick out' on both sides + var first = markedSpansBefore(oldFirst, startCh, isInsert); + var last = markedSpansAfter(oldLast, endCh, isInsert); + + // Next, merge those two ends + var sameLine = change.text.length == 1, offset = lst(change.text).length + (sameLine ? startCh : 0); + if (first) { + // Fix up .to properties of first + for (var i = 0; i < first.length; ++i) { + var span = first[i]; + if (span.to == null) { + var found = getMarkedSpanFor(last, span.marker); + if (!found) span.to = startCh; + else if (sameLine) span.to = found.to == null ? null : found.to + offset; + } + } + } + if (last) { + // Fix up .from in last (or move them into first in case of sameLine) + for (var i = 0; i < last.length; ++i) { + var span = last[i]; + if (span.to != null) span.to += offset; + if (span.from == null) { + var found = getMarkedSpanFor(first, span.marker); + if (!found) { + span.from = offset; + if (sameLine) (first || (first = [])).push(span); + } + } else { + span.from += offset; + if (sameLine) (first || (first = [])).push(span); + } + } + } + // Make sure we didn't create any zero-length spans + if (first) first = clearEmptySpans(first); + if (last && last != first) last = clearEmptySpans(last); + + var newMarkers = [first]; + if (!sameLine) { + // Fill gap with whole-line-spans + var gap = change.text.length - 2, gapMarkers; + if (gap > 0 && first) { + for (var i = 0; i < first.length; ++i) { + if (first[i].to == null) {(gapMarkers || (gapMarkers = [])).push(new MarkedSpan(first[i].marker, null, null));} + } + } + for (var i = 0; i < gap; ++i) {newMarkers.push(gapMarkers);} + newMarkers.push(last); + } + return newMarkers; + } + + // Remove spans that are empty and don't have a clearWhenEmpty + // option of false. + function clearEmptySpans (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if (span.from != null && span.from == span.to && span.marker.clearWhenEmpty !== false) {spans.splice(i--, 1);} + } + if (!spans.length) return null; + return spans; + } + + // Used for un/re-doing changes from the history. Combines the + // result of computing the existing spans with the set of spans that + // existed in the history (so that deleting around a span and then + // undoing brings back the span). + function mergeOldSpans (doc, change) { + var old = getOldSpans(doc, change); + var stretched = stretchSpansOverChange(doc, change); + if (!old) return stretched; + if (!stretched) return old; + + for (var i = 0; i < old.length; ++i) { + var oldCur = old[i], stretchCur = stretched[i]; + if (oldCur && stretchCur) { + spans: for (var j = 0; j < stretchCur.length; ++j) { + var span = stretchCur[j]; + for (var k = 0; k < oldCur.length; ++k) {if (oldCur[k].marker == span.marker) continue spans;} + oldCur.push(span); + } + } else if (stretchCur) { + old[i] = stretchCur; + } + } + return old; + } + + // Used to 'clip' out readOnly ranges when making a change. + function removeReadOnlyRanges (doc, from, to) { + var markers = null; + doc.iter(from.line, to.line + 1, function (line) { + if (line.markedSpans) { + for (var i = 0; i < line.markedSpans.length; ++i) { + var mark = line.markedSpans[i].marker; + if (mark.readOnly && (!markers || indexOf(markers, mark) == -1)) {(markers || (markers = [])).push(mark);} + } + } + }); + if (!markers) return null; + var parts = [{from: from, to: to}]; + for (var i = 0; i < markers.length; ++i) { + var mk = markers[i], m = mk.find(0); + for (var j = 0; j < parts.length; ++j) { + var p = parts[j]; + if (cmp(p.to, m.from) < 0 || cmp(p.from, m.to) > 0) continue; + var newParts = [j, 1], dfrom = cmp(p.from, m.from), dto = cmp(p.to, m.to); + if (dfrom < 0 || !mk.inclusiveLeft && !dfrom) {newParts.push({from: p.from, to: m.from});} + if (dto > 0 || !mk.inclusiveRight && !dto) {newParts.push({from: m.to, to: p.to});} + parts.splice.apply(parts, newParts); + j += newParts.length - 1; + } + } + return parts; + } + + // Connect or disconnect spans from a line. + function detachMarkedSpans (line) { + var spans = line.markedSpans; + if (!spans) return; + for (var i = 0; i < spans.length; ++i) {spans[i].marker.detachLine(line);} + line.markedSpans = null; + } + function attachMarkedSpans (line, spans) { + if (!spans) return; + for (var i = 0; i < spans.length; ++i) {spans[i].marker.attachLine(line);} + line.markedSpans = spans; + } + + // Helpers used when computing which overlapping collapsed span + // counts as the larger one. + function extraLeft (marker) { return marker.inclusiveLeft ? -1 : 0; } + function extraRight (marker) { return marker.inclusiveRight ? 1 : 0; } + + // Returns a number indicating which of two overlapping collapsed + // spans is larger (and thus includes the other). Falls back to + // comparing ids when the spans cover exactly the same range. + function compareCollapsedMarkers (a, b) { + var lenDiff = a.lines.length - b.lines.length; + if (lenDiff != 0) return lenDiff; + var aPos = a.find(), bPos = b.find(); + var fromCmp = cmp(aPos.from, bPos.from) || extraLeft(a) - extraLeft(b); + if (fromCmp) return -fromCmp; + var toCmp = cmp(aPos.to, bPos.to) || extraRight(a) - extraRight(b); + if (toCmp) return toCmp; + return b.id - a.id; + } + + // Find out whether a line ends or starts in a collapsed span. If + // so, return the marker for that span. + function collapsedSpanAtSide (line, start) { + var sps = sawCollapsedSpans && line.markedSpans, found; + if (sps) { + for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (sp.marker.collapsed && (start ? sp.from : sp.to) == null && + (!found || compareCollapsedMarkers(found, sp.marker) < 0)) {found = sp.marker;} + } + } + return found; + } + function collapsedSpanAtStart (line) { return collapsedSpanAtSide(line, true); } + function collapsedSpanAtEnd (line) { return collapsedSpanAtSide(line, false); } + + // Test whether there exists a collapsed span that partially + // overlaps (covers the start or end, but not both) of a new span. + // Such overlap is not allowed. + function conflictingCollapsedRange (doc, lineNo, from, to, marker) { + var line = getLine(doc, lineNo); + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var i = 0; i < sps.length; ++i) { + var sp = sps[i]; + if (!sp.marker.collapsed) continue; + var found = sp.marker.find(0); + var fromCmp = cmp(found.from, from) || extraLeft(sp.marker) - extraLeft(marker); + var toCmp = cmp(found.to, to) || extraRight(sp.marker) - extraRight(marker); + if (fromCmp >= 0 && toCmp <= 0 || fromCmp <= 0 && toCmp >= 0) continue; + if (fromCmp <= 0 && (cmp(found.to, from) > 0 || (sp.marker.inclusiveRight && marker.inclusiveLeft)) || + fromCmp >= 0 && (cmp(found.from, to) < 0 || (sp.marker.inclusiveLeft && marker.inclusiveRight))) {return true;} + } + } + } + + // A visual line is a line as drawn on the screen. Folding, for + // example, can cause multiple logical lines to appear on the same + // visual line. This finds the start of the visual line that the + // given line is part of (usually that is the line itself). + function visualLine (line) { + var merged; + while (merged = collapsedSpanAtStart(line)) {line = merged.find(-1, true).line;} + return line; + } + + // Returns an array of logical lines that continue the visual line + // started by the argument, or undefined if there are no such lines. + function visualLineContinued (line) { + var merged, lines; + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + (lines || (lines = [])).push(line); + } + return lines; + } + + // Get the line number of the start of the visual line that the + // given line number is part of. + function visualLineNo (doc, lineN) { + var line = getLine(doc, lineN), vis = visualLine(line); + if (line == vis) return lineN; + return lineNo(vis); + } + // Get the line number of the start of the next visual line after + // the given line. + function visualLineEndNo (doc, lineN) { + if (lineN > doc.lastLine()) return lineN; + var line = getLine(doc, lineN), merged; + if (!lineIsHidden(doc, line)) return lineN; + while (merged = collapsedSpanAtEnd(line)) {line = merged.find(1, true).line;} + return lineNo(line) + 1; + } + + // Compute whether a line is hidden. Lines count as hidden when they + // are part of a visual line that starts with another line, or when + // they are entirely covered by collapsed, non-widget span. + function lineIsHidden (doc, line) { + var sps = sawCollapsedSpans && line.markedSpans; + if (sps) { + for (var sp, i = 0; i < sps.length; ++i) { + sp = sps[i]; + if (!sp.marker.collapsed) continue; + if (sp.from == null) return true; + if (sp.marker.widgetNode) continue; + if (sp.from == 0 && sp.marker.inclusiveLeft && lineIsHiddenInner(doc, line, sp)) {return true;} + } + } + } + function lineIsHiddenInner (doc, line, span) { + if (span.to == null) { + var end = span.marker.find(1, true); + return lineIsHiddenInner(doc, end.line, getMarkedSpanFor(end.line.markedSpans, span.marker)); + } + if (span.marker.inclusiveRight && span.to == line.text.length) {return true;} + for (var sp, i = 0; i < line.markedSpans.length; ++i) { + sp = line.markedSpans[i]; + if (sp.marker.collapsed && !sp.marker.widgetNode && sp.from == span.to && + (sp.to == null || sp.to != span.from) && + (sp.marker.inclusiveLeft || span.marker.inclusiveRight) && + lineIsHiddenInner(doc, line, sp)) return true; + } + } + + // LINE WIDGETS + + // Line widgets are block elements displayed above or below a line. + + var LineWidget = CodeMirror.LineWidget = function (doc, node, options) { + if (options) { + for (var opt in options) { + if (options.hasOwnProperty(opt)) {this[opt] = options[opt];} + } + } + this.doc = doc; + this.node = node; + }; + eventMixin(LineWidget); + + function adjustScrollWhenAboveVisible (cm, line, diff) { + if (heightAtLine(line) < ((cm.curOp && cm.curOp.scrollTop) || cm.doc.scrollTop)) {addToScrollPos(cm, null, diff);} + } + + LineWidget.prototype.clear = function () { + var cm = this.doc.cm, ws = this.line.widgets, line = this.line, no = lineNo(line); + if (no == null || !ws) return; + for (var i = 0; i < ws.length; ++i) if (ws[i] == this) ws.splice(i--, 1); + if (!ws.length) line.widgets = null; + var height = widgetHeight(this); + updateLineHeight(line, Math.max(0, line.height - height)); + if (cm) { + runInOp(cm, function () { + adjustScrollWhenAboveVisible(cm, line, -height); + regLineChange(cm, no, "widget"); + }); + } + }; + LineWidget.prototype.changed = function () { + var oldH = this.height, cm = this.doc.cm, line = this.line; + this.height = null; + var diff = widgetHeight(this) - oldH; + if (!diff) return; + updateLineHeight(line, line.height + diff); + if (cm) { + runInOp(cm, function () { + cm.curOp.forceUpdate = true; + adjustScrollWhenAboveVisible(cm, line, diff); + }); + } + }; + + function widgetHeight (widget) { + if (widget.height != null) return widget.height; + var cm = widget.doc.cm; + if (!cm) return 0; + if (!contains(document.body, widget.node)) { + var parentStyle = "position: relative;"; + if (widget.coverGutter) {parentStyle += "margin-left: -" + cm.display.gutters.offsetWidth + "px;";} + if (widget.noHScroll) {parentStyle += "width: " + cm.display.wrapper.clientWidth + "px;";} + removeChildrenAndAdd(cm.display.measure, elt("div", [widget.node], null, parentStyle)); + } + return widget.height = widget.node.offsetHeight; + } + + function addLineWidget (doc, handle, node, options) { + var widget = new LineWidget(doc, node, options); + var cm = doc.cm; + if (cm && widget.noHScroll) cm.display.alignWidgets = true; + changeLine(doc, handle, "widget", function (line) { + var widgets = line.widgets || (line.widgets = []); + if (widget.insertAt == null) widgets.push(widget); + else widgets.splice(Math.min(widgets.length - 1, Math.max(0, widget.insertAt)), 0, widget); + widget.line = line; + if (cm && !lineIsHidden(doc, line)) { + var aboveVisible = heightAtLine(line) < doc.scrollTop; + updateLineHeight(line, line.height + widgetHeight(widget)); + if (aboveVisible) addToScrollPos(cm, null, widget.height); + cm.curOp.forceUpdate = true; + } + return true; + }); + return widget; + } + + // LINE DATA STRUCTURE + + // Line objects. These hold state related to a line, including + // highlighting info (the styles array). + var Line = CodeMirror.Line = function (text, markedSpans, estimateHeight) { + this.text = text; + attachMarkedSpans(this, markedSpans); + this.height = estimateHeight ? estimateHeight(this) : 1; + }; + eventMixin(Line); + Line.prototype.lineNo = function () { return lineNo(this); }; + + // Change the content (text, markers) of a line. Automatically + // invalidates cached information and tries to re-estimate the + // line's height. + function updateLine (line, text, markedSpans, estimateHeight) { + line.text = text; + if (line.stateAfter) line.stateAfter = null; + if (line.styles) line.styles = null; + if (line.order != null) line.order = null; + detachMarkedSpans(line); + attachMarkedSpans(line, markedSpans); + var estHeight = estimateHeight ? estimateHeight(line) : 1; + if (estHeight != line.height) updateLineHeight(line, estHeight); + } + + // Detach a line from the document tree and its markers. + function cleanUpLine (line) { + line.parent = null; + detachMarkedSpans(line); + } + + function extractLineClasses (type, output) { + if (type) { + for (;;) { + var lineClass = type.match(/(?:^|\s+)line-(background-)?(\S+)/); + if (!lineClass) break; + type = type.slice(0, lineClass.index) + type.slice(lineClass.index + lineClass[0].length); + var prop = lineClass[1] ? "bgClass" : "textClass"; + if (output[prop] == null) {output[prop] = lineClass[2];} else if (!(new RegExp("(?:^|\s)" + lineClass[2] + "(?:$|\s)")).test(output[prop])) {output[prop] += " " + lineClass[2];} + } + } + return type; + } + + function callBlankLine (mode, state) { + if (mode.blankLine) return mode.blankLine(state); + if (!mode.innerMode) return; + var inner = CodeMirror.innerMode(mode, state); + if (inner.mode.blankLine) return inner.mode.blankLine(inner.state); + } + + function readToken (mode, stream, state, inner) { + for (var i = 0; i < 10; i++) { + if (inner) inner[0] = CodeMirror.innerMode(mode, state).mode; + var style = mode.token(stream, state); + if (stream.pos > stream.start) return style; + } + throw new Error("Mode " + mode.name + " failed to advance stream."); + } + + // Utility for getTokenAt and getLineTokens + function takeToken (cm, pos, precise, asArray) { + function getObj (copy) { + return {start: stream.start, end: stream.pos, + string: stream.current(), + type: style || null, + state: copy ? copyState(doc.mode, state) : state}; + } + + var doc = cm.doc, mode = doc.mode, style; + pos = clipPos(doc, pos); + var line = getLine(doc, pos.line), state = getStateBefore(cm, pos.line, precise); + var stream = new StringStream(line.text, cm.options.tabSize), tokens; + if (asArray) tokens = []; + while ((asArray || stream.pos < pos.ch) && !stream.eol()) { + stream.start = stream.pos; + style = readToken(mode, stream, state); + if (asArray) tokens.push(getObj(true)); + } + return asArray ? tokens : getObj(); + } + + // Run the given mode's parser over a line, calling f for each token. + function runMode (cm, text, mode, state, f, lineClasses, forceToEnd) { + var flattenSpans = mode.flattenSpans; + if (flattenSpans == null) flattenSpans = cm.options.flattenSpans; + var curStart = 0, curStyle = null; + var stream = new StringStream(text, cm.options.tabSize), style; + var inner = cm.options.addModeClass && [null]; + if (text == "") extractLineClasses(callBlankLine(mode, state), lineClasses); + while (!stream.eol()) { + if (stream.pos > cm.options.maxHighlightLength) { + flattenSpans = false; + if (forceToEnd) processLine(cm, text, state, stream.pos); + stream.pos = text.length; + style = null; + } else { + style = extractLineClasses(readToken(mode, stream, state, inner), lineClasses); + } + if (inner) { + var mName = inner[0].name; + if (mName) style = "m-" + (style ? mName + " " + style : mName); + } + if (!flattenSpans || curStyle != style) { + while (curStart < stream.start) { + curStart = Math.min(stream.start, curStart + 50000); + f(curStart, curStyle); + } + curStyle = style; + } + stream.start = stream.pos; + } + while (curStart < stream.pos) { + // Webkit seems to refuse to render text nodes longer than 57444 characters + var pos = Math.min(stream.pos, curStart + 50000); + f(pos, curStyle); + curStart = pos; + } + } + + // Compute a style array (an array starting with a mode generation + // -- for invalidation -- followed by pairs of end positions and + // style strings), which is used to highlight the tokens on the + // line. + function highlightLine (cm, line, state, forceToEnd) { + // A styles array always starts with a number identifying the + // mode/overlays that it is based on (for easy invalidation). + var st = [cm.state.modeGen], lineClasses = {}; + // Compute the base array of styles + runMode(cm, line.text, cm.doc.mode, state, function (end, style) { + st.push(end, style); + }, lineClasses, forceToEnd); + + // Run overlays, adjust style array. + for (var o = 0; o < cm.state.overlays.length; ++o) { + var overlay = cm.state.overlays[o], i = 1, at = 0; + runMode(cm, line.text, overlay.mode, true, function (end, style) { + var start = i; + // Ensure there's a token end at the current position, and that i points at it + while (at < end) { + var i_end = st[i]; + if (i_end > end) {st.splice(i, 1, end, st[i + 1], i_end);} + i += 2; + at = Math.min(end, i_end); + } + if (!style) return; + if (overlay.opaque) { + st.splice(start, i - start, end, "cm-overlay " + style); + i = start + 2; + } else { + for (; start < i; start += 2) { + var cur = st[start + 1]; + st[start + 1] = (cur ? cur + " " : "") + "cm-overlay " + style; + } + } + }, lineClasses); + } + + return {styles: st, classes: lineClasses.bgClass || lineClasses.textClass ? lineClasses : null}; + } + + function getLineStyles (cm, line, updateFrontier) { + if (!line.styles || line.styles[0] != cm.state.modeGen) { + var result = highlightLine(cm, line, line.stateAfter = getStateBefore(cm, lineNo(line))); + line.styles = result.styles; + if (result.classes) line.styleClasses = result.classes; + else if (line.styleClasses) line.styleClasses = null; + if (updateFrontier === cm.doc.frontier) cm.doc.frontier++; + } + return line.styles; + } + + // Lightweight form of highlight -- proceed over this line and + // update state, but don't save a style array. Used for lines that + // aren't currently visible. + function processLine (cm, text, state, startAt) { + var mode = cm.doc.mode; + var stream = new StringStream(text, cm.options.tabSize); + stream.start = stream.pos = startAt || 0; + if (text == "") callBlankLine(mode, state); + while (!stream.eol() && stream.pos <= cm.options.maxHighlightLength) { + readToken(mode, stream, state); + stream.start = stream.pos; + } + } + + // Convert a style as returned by a mode (either null, or a string + // containing one or more styles) to a CSS style. This is cached, + // and also looks for line-wide styles. + var styleToClassCache = {}, styleToClassCacheWithMode = {}; + function interpretTokenStyle (style, options) { + if (!style || /^\s*$/.test(style)) return null; + var cache = options.addModeClass ? styleToClassCacheWithMode : styleToClassCache; + return cache[style] || + (cache[style] = style.replace(/\S+/g, "cm-$&")); + } + + // Render the DOM representation of the text of a line. Also builds + // up a 'line map', which points at the DOM nodes that represent + // specific stretches of text, and is used by the measuring code. + // The returned object contains the DOM node, this map, and + // information about line-wide styles that were set by the mode. + function buildLineContent (cm, lineView) { + // The padding-right forces the element to have a 'border', which + // is needed on Webkit to be able to get line-level bounding + // rectangles for it (in measureChar). + var content = elt("span", null, null, webkit ? "padding-right: .1px" : null); + var builder = {pre: elt("pre", [content], "CodeMirror-line"), content: content, + col: 0, pos: 0, cm: cm, + splitSpaces: (ie || webkit) && cm.getOption("lineWrapping")}; + lineView.measure = {}; + + // Iterate over the logical lines that make up this visual line. + for (var i = 0; i <= (lineView.rest ? lineView.rest.length : 0); i++) { + var line = i ? lineView.rest[i - 1] : lineView.line, order; + builder.pos = 0; + builder.addToken = buildToken; + // Optionally wire in some hacks into the token-rendering + // algorithm, to deal with browser quirks. + if (hasBadBidiRects(cm.display.measure) && (order = getOrder(line))) {builder.addToken = buildTokenBadBidi(builder.addToken, order);} + builder.map = []; + var allowFrontierUpdate = lineView != cm.display.externalMeasured && lineNo(line); + insertLineContent(line, builder, getLineStyles(cm, line, allowFrontierUpdate)); + if (line.styleClasses) { + if (line.styleClasses.bgClass) {builder.bgClass = joinClasses(line.styleClasses.bgClass, builder.bgClass || "");} + if (line.styleClasses.textClass) {builder.textClass = joinClasses(line.styleClasses.textClass, builder.textClass || "");} + } + + // Ensure at least a single node is present, for measuring. + if (builder.map.length == 0) {builder.map.push(0, 0, builder.content.appendChild(zeroWidthElement(cm.display.measure)));} + + // Store the map and a cache object for the current logical line + if (i == 0) { + lineView.measure.map = builder.map; + lineView.measure.cache = {}; + } else { + (lineView.measure.maps || (lineView.measure.maps = [])).push(builder.map); + (lineView.measure.caches || (lineView.measure.caches = [])).push({}); + } + } + + // See issue #2901 + if (webkit && /\bcm-tab\b/.test(builder.content.lastChild.className)) {builder.content.className = "cm-tab-wrap-hack";} + + signal(cm, "renderLine", cm, lineView.line, builder.pre); + if (builder.pre.className) {builder.textClass = joinClasses(builder.pre.className, builder.textClass || "");} + + return builder; + } + + function defaultSpecialCharPlaceholder (ch) { + var token = elt("span", "\u2022", "cm-invalidchar"); + token.title = "\\u" + ch.charCodeAt(0).toString(16); + token.setAttribute("aria-label", token.title); + return token; + } + + // Build up the DOM representation for a single token, and add it to + // the line map. Takes care to render special characters separately. + function buildToken (builder, text, style, startStyle, endStyle, title, css) { + if (!text) return; + var displayText = builder.splitSpaces ? text.replace(/ {3,}/g, splitSpaces) : text; + var special = builder.cm.state.specialChars, mustWrap = false; + if (!special.test(text)) { + builder.col += text.length; + var content = document.createTextNode(displayText); + builder.map.push(builder.pos, builder.pos + text.length, content); + if (ie && ie_version < 9) mustWrap = true; + builder.pos += text.length; + } else { + var content = document.createDocumentFragment(), pos = 0; + while (true) { + special.lastIndex = pos; + var m = special.exec(text); + var skipped = m ? m.index - pos : text.length - pos; + if (skipped) { + var txt = document.createTextNode(displayText.slice(pos, pos + skipped)); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.map.push(builder.pos, builder.pos + skipped, txt); + builder.col += skipped; + builder.pos += skipped; + } + if (!m) break; + pos += skipped + 1; + if (m[0] == "\t") { + var tabSize = builder.cm.options.tabSize, tabWidth = tabSize - builder.col % tabSize; + var txt = content.appendChild(elt("span", spaceStr(tabWidth), "cm-tab")); + txt.setAttribute("role", "presentation"); + txt.setAttribute("cm-text", "\t"); + builder.col += tabWidth; + } else { + var txt = builder.cm.options.specialCharPlaceholder(m[0]); + txt.setAttribute("cm-text", m[0]); + if (ie && ie_version < 9) content.appendChild(elt("span", [txt])); + else content.appendChild(txt); + builder.col += 1; + } + builder.map.push(builder.pos, builder.pos + 1, txt); + builder.pos++; + } + } + if (style || startStyle || endStyle || mustWrap || css) { + var fullStyle = style || ""; + if (startStyle) fullStyle += startStyle; + if (endStyle) fullStyle += endStyle; + var token = elt("span", [content], fullStyle, css); + if (title) token.title = title; + return builder.content.appendChild(token); + } + builder.content.appendChild(content); + } + + function splitSpaces (old) { + var out = " "; + for (var i = 0; i < old.length - 2; ++i) out += i % 2 ? " " : "\u00a0"; + out += " "; + return out; + } + + // Work around nonsense dimensions being reported for stretches of + // right-to-left text. + function buildTokenBadBidi (inner, order) { + return function (builder, text, style, startStyle, endStyle, title, css) { + style = style ? style + " cm-force-border" : "cm-force-border"; + var start = builder.pos, end = start + text.length; + for (;;) { + // Find the part that overlaps with the start of this text + for (var i = 0; i < order.length; i++) { + var part = order[i]; + if (part.to > start && part.from <= start) break; + } + if (part.to >= end) return inner(builder, text, style, startStyle, endStyle, title, css); + inner(builder, text.slice(0, part.to - start), style, startStyle, null, title, css); + startStyle = null; + text = text.slice(part.to - start); + start = part.to; + } + }; + } + + function buildCollapsedSpan (builder, size, marker, ignoreWidget) { + var widget = !ignoreWidget && marker.widgetNode; + if (widget) builder.map.push(builder.pos, builder.pos + size, widget); + if (!ignoreWidget && builder.cm.display.input.needsContentAttribute) { + if (!widget) {widget = builder.content.appendChild(document.createElement("span"));} + widget.setAttribute("cm-marker", marker.id); + } + if (widget) { + builder.cm.display.input.setUneditable(widget); + builder.content.appendChild(widget); + } + builder.pos += size; + } + + // Outputs a number of spans to make up a line, taking highlighting + // and marked text into account. + function insertLineContent (line, builder, styles) { + var spans = line.markedSpans, allText = line.text, at = 0; + if (!spans) { + for (var i = 1; i < styles.length; i += 2) {builder.addToken(builder, allText.slice(at, at = styles[i]), interpretTokenStyle(styles[i + 1], builder.cm.options));} + return; + } + + var len = allText.length, pos = 0, i = 1, text = "", style, css; + var nextChange = 0, spanStyle, spanEndStyle, spanStartStyle, title, collapsed; + for (;;) { + if (nextChange == pos) { // Update current marker set + spanStyle = spanEndStyle = spanStartStyle = title = css = ""; + collapsed = null; nextChange = Infinity; + var foundBookmarks = []; + for (var j = 0; j < spans.length; ++j) { + var sp = spans[j], m = sp.marker; + if (m.type == "bookmark" && sp.from == pos && m.widgetNode) { + foundBookmarks.push(m); + } else if (sp.from <= pos && (sp.to == null || sp.to > pos || m.collapsed && sp.to == pos && sp.from == pos)) { + if (sp.to != null && sp.to != pos && nextChange > sp.to) { + nextChange = sp.to; + spanEndStyle = ""; + } + if (m.className) spanStyle += " " + m.className; + if (m.css) css = m.css; + if (m.startStyle && sp.from == pos) spanStartStyle += " " + m.startStyle; + if (m.endStyle && sp.to == nextChange) spanEndStyle += " " + m.endStyle; + if (m.title && !title) title = m.title; + if (m.collapsed && (!collapsed || compareCollapsedMarkers(collapsed.marker, m) < 0)) {collapsed = sp;} + } else if (sp.from > pos && nextChange > sp.from) { + nextChange = sp.from; + } + } + if (collapsed && (collapsed.from || 0) == pos) { + buildCollapsedSpan(builder, (collapsed.to == null ? len + 1 : collapsed.to) - pos, + collapsed.marker, collapsed.from == null); + if (collapsed.to == null) return; + if (collapsed.to == pos) collapsed = false; + } + if (!collapsed && foundBookmarks.length) { + for (var j = 0; j < foundBookmarks.length; ++j) {buildCollapsedSpan(builder, 0, foundBookmarks[j]);} + } + } + if (pos >= len) break; + + var upto = Math.min(len, nextChange); + while (true) { + if (text) { + var end = pos + text.length; + if (!collapsed) { + var tokenText = end > upto ? text.slice(0, upto - pos) : text; + builder.addToken(builder, tokenText, style ? style + spanStyle : spanStyle, + spanStartStyle, pos + tokenText.length == nextChange ? spanEndStyle : "", title, css); + } + if (end >= upto) {text = text.slice(upto - pos); pos = upto; break;} + pos = end; + spanStartStyle = ""; + } + text = allText.slice(at, at = styles[i++]); + style = interpretTokenStyle(styles[i++], builder.cm.options); + } + } + } + + // DOCUMENT DATA STRUCTURE + + // By default, updates that start and end at the beginning of a line + // are treated specially, in order to make the association of line + // widgets and marker elements with the text behave more intuitive. + function isWholeLineUpdate (doc, change) { + return change.from.ch == 0 && change.to.ch == 0 && lst(change.text) == "" && + (!doc.cm || doc.cm.options.wholeLineUpdateBefore); + } + + // Perform a change on the document data structure. + function updateDoc (doc, change, markedSpans, estimateHeight) { + function spansFor (n) {return markedSpans ? markedSpans[n] : null;} + function update (line, text, spans) { + updateLine(line, text, spans, estimateHeight); + signalLater(line, "change", line, change); + } + function linesFor (start, end) { + for (var i = start, result = []; i < end; ++i) {result.push(new Line(text[i], spansFor(i), estimateHeight));} + return result; + } + + var from = change.from, to = change.to, text = change.text; + var firstLine = getLine(doc, from.line), lastLine = getLine(doc, to.line); + var lastText = lst(text), lastSpans = spansFor(text.length - 1), nlines = to.line - from.line; + + // Adjust the line structure + if (change.full) { + doc.insert(0, linesFor(0, text.length)); + doc.remove(text.length, doc.size - text.length); + } else if (isWholeLineUpdate(doc, change)) { + // This is a whole-line replace. Treated specially to make + // sure line objects move the way they are supposed to. + var added = linesFor(0, text.length - 1); + update(lastLine, lastLine.text, lastSpans); + if (nlines) doc.remove(from.line, nlines); + if (added.length) doc.insert(from.line, added); + } else if (firstLine == lastLine) { + if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + lastText + firstLine.text.slice(to.ch), lastSpans); + } else { + var added = linesFor(1, text.length - 1); + added.push(new Line(lastText + firstLine.text.slice(to.ch), lastSpans, estimateHeight)); + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + doc.insert(from.line + 1, added); + } + } else if (text.length == 1) { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0] + lastLine.text.slice(to.ch), spansFor(0)); + doc.remove(from.line + 1, nlines); + } else { + update(firstLine, firstLine.text.slice(0, from.ch) + text[0], spansFor(0)); + update(lastLine, lastText + lastLine.text.slice(to.ch), lastSpans); + var added = linesFor(1, text.length - 1); + if (nlines > 1) doc.remove(from.line + 1, nlines - 1); + doc.insert(from.line + 1, added); + } + + signalLater(doc, "change", doc, change); + } + + // The document is represented as a BTree consisting of leaves, with + // chunk of lines in them, and branches, with up to ten leaves or + // other branch nodes below them. The top node is always a branch + // node, and is the document object itself (meaning it has + // additional methods and properties). + // + // All nodes have parent links. The tree is used both to go from + // line numbers to line objects, and to go from objects to numbers. + // It also indexes by height, and is used to convert between height + // and line object, and to find the total height of the document. + // + // See also http://marijnhaverbeke.nl/blog/codemirror-line-tree.html + + function LeafChunk (lines) { + this.lines = lines; + this.parent = null; + for (var i = 0, height = 0; i < lines.length; ++i) { + lines[i].parent = this; + height += lines[i].height; + } + this.height = height; + } + + LeafChunk.prototype = { + chunkSize: function () { return this.lines.length; }, + // Remove the n lines at offset 'at'. + removeInner: function (at, n) { + for (var i = at, e = at + n; i < e; ++i) { + var line = this.lines[i]; + this.height -= line.height; + cleanUpLine(line); + signalLater(line, "delete"); + } + this.lines.splice(at, n); + }, + // Helper used to collapse a small branch into a single leaf. + collapse: function (lines) { + lines.push.apply(lines, this.lines); + }, + // Insert the given array of lines at offset 'at', count them as + // having the given height. + insertInner: function (at, lines, height) { + this.height += height; + this.lines = this.lines.slice(0, at).concat(lines).concat(this.lines.slice(at)); + for (var i = 0; i < lines.length; ++i) lines[i].parent = this; + }, + // Used to iterate over a part of the tree. + iterN: function (at, n, op) { + for (var e = at + n; at < e; ++at) {if (op(this.lines[at])) return true;} + } + }; + + function BranchChunk (children) { + this.children = children; + var size = 0, height = 0; + for (var i = 0; i < children.length; ++i) { + var ch = children[i]; + size += ch.chunkSize(); height += ch.height; + ch.parent = this; + } + this.size = size; + this.height = height; + this.parent = null; + } + + BranchChunk.prototype = { + chunkSize: function () { return this.size; }, + removeInner: function (at, n) { + this.size -= n; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var rm = Math.min(n, sz - at), oldHeight = child.height; + child.removeInner(at, rm); + this.height -= oldHeight - child.height; + if (sz == rm) { this.children.splice(i--, 1); child.parent = null; } + if ((n -= rm) == 0) break; + at = 0; + } else at -= sz; + } + // If the result is smaller than 25 lines, ensure that it is a + // single leaf node. + if (this.size - n < 25 && + (this.children.length > 1 || !(this.children[0] instanceof LeafChunk))) { + var lines = []; + this.collapse(lines); + this.children = [new LeafChunk(lines)]; + this.children[0].parent = this; + } + }, + collapse: function (lines) { + for (var i = 0; i < this.children.length; ++i) this.children[i].collapse(lines); + }, + insertInner: function (at, lines, height) { + this.size += lines.length; + this.height += height; + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at <= sz) { + child.insertInner(at, lines, height); + if (child.lines && child.lines.length > 50) { + while (child.lines.length > 50) { + var spilled = child.lines.splice(child.lines.length - 25, 25); + var newleaf = new LeafChunk(spilled); + child.height -= newleaf.height; + this.children.splice(i + 1, 0, newleaf); + newleaf.parent = this; + } + this.maybeSpill(); + } + break; + } + at -= sz; + } + }, + // When a node has grown, check whether it should be split. + maybeSpill: function () { + if (this.children.length <= 10) return; + var me = this; + do { + var spilled = me.children.splice(me.children.length - 5, 5); + var sibling = new BranchChunk(spilled); + if (!me.parent) { // Become the parent node + var copy = new BranchChunk(me.children); + copy.parent = me; + me.children = [copy, sibling]; + me = copy; + } else { + me.size -= sibling.size; + me.height -= sibling.height; + var myIndex = indexOf(me.parent.children, me); + me.parent.children.splice(myIndex + 1, 0, sibling); + } + sibling.parent = me.parent; + } while (me.children.length > 10); + me.parent.maybeSpill(); + }, + iterN: function (at, n, op) { + for (var i = 0; i < this.children.length; ++i) { + var child = this.children[i], sz = child.chunkSize(); + if (at < sz) { + var used = Math.min(n, sz - at); + if (child.iterN(at, used, op)) return true; + if ((n -= used) == 0) break; + at = 0; + } else at -= sz; + } + } + }; + + var nextDocId = 0; + var Doc = CodeMirror.Doc = function (text, mode, firstLine) { + if (!(this instanceof Doc)) return new Doc(text, mode, firstLine); + if (firstLine == null) firstLine = 0; + + BranchChunk.call(this, [new LeafChunk([new Line("", null)])]); + this.first = firstLine; + this.scrollTop = this.scrollLeft = 0; + this.cantEdit = false; + this.cleanGeneration = 1; + this.frontier = firstLine; + var start = Pos(firstLine, 0); + this.sel = simpleSelection(start); + this.history = new History(null); + this.id = ++nextDocId; + this.modeOption = mode; + + if (typeof text === "string") text = splitLines(text); + updateDoc(this, {from: start, to: start, text: text}); + setSelection(this, simpleSelection(start), sel_dontScroll); + }; + + Doc.prototype = createObj(BranchChunk.prototype, { + constructor: Doc, + // Iterate over the document. Supports two forms -- with only one + // argument, it calls that for each line in the document. With + // three, it iterates over the range given by the first two (with + // the second being non-inclusive). + iter: function (from, to, op) { + if (op) this.iterN(from - this.first, to - from, op); + else this.iterN(this.first, this.first + this.size, from); + }, + + // Non-public interface for adding and removing lines. + insert: function (at, lines) { + var height = 0; + for (var i = 0; i < lines.length; ++i) height += lines[i].height; + this.insertInner(at - this.first, lines, height); + }, + remove: function (at, n) { this.removeInner(at - this.first, n); }, + + // From here, the methods are part of the public interface. Most + // are also available from CodeMirror (editor) instances. + + getValue: function (lineSep, lineFilter) { + var lines = getLines(this, this.first, this.first + this.size, lineFilter); + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + setValue: docMethodOp(function (code) { + var top = Pos(this.first, 0), last = this.first + this.size - 1; + makeChange(this, {from: top, to: Pos(last, getLine(this, last).text.length), + text: splitLines(code), origin: "setValue", full: true}, true); + setSelection(this, simpleSelection(top)); + }), + replaceRange: function (code, from, to, origin) { + from = clipPos(this, from); + to = to ? clipPos(this, to) : from; + replaceRange(this, code, from, to, origin); + }, + getRange: function (from, to, lineSep) { + var lines = getBetween(this, clipPos(this, from), clipPos(this, to)); + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + + getLine: function (line) {var l = this.getLineHandle(line); return l && l.text;}, + + getLineHandle: function (line) {if (isLine(this, line)) return getLine(this, line);}, + getLineNumber: function (line) {return lineNo(line);}, + + getLineHandleVisualStart: function (line) { + if (typeof line === "number") line = getLine(this, line); + return visualLine(line); + }, + + lineCount: function () {return this.size;}, + firstLine: function () {return this.first;}, + lastLine: function () {return this.first + this.size - 1;}, + + clipPos: function (pos) {return clipPos(this, pos);}, + + getCursor: function (start) { + var range = this.sel.primary(), pos; + if (start == null || start == "head") pos = range.head; + else if (start == "anchor") pos = range.anchor; + else if (start == "end" || start == "to" || start === false) pos = range.to(); + else pos = range.from(); + return pos; + }, + listSelections: function () { return this.sel.ranges; }, + somethingSelected: function () {return this.sel.somethingSelected();}, + + setCursor: docMethodOp(function (line, ch, options) { + setSimpleSelection(this, clipPos(this, typeof line === "number" ? Pos(line, ch || 0) : line), null, options); + }), + setSelection: docMethodOp(function (anchor, head, options) { + setSimpleSelection(this, clipPos(this, anchor), clipPos(this, head || anchor), options); + }), + extendSelection: docMethodOp(function (head, other, options) { + extendSelection(this, clipPos(this, head), other && clipPos(this, other), options); + }), + extendSelections: docMethodOp(function (heads, options) { + extendSelections(this, clipPosArray(this, heads, options)); + }), + extendSelectionsBy: docMethodOp(function (f, options) { + extendSelections(this, map(this.sel.ranges, f), options); + }), + setSelections: docMethodOp(function (ranges, primary, options) { + if (!ranges.length) return; + for (var i = 0, out = []; i < ranges.length; i++) { + out[i] = new Range(clipPos(this, ranges[i].anchor), + clipPos(this, ranges[i].head)); + } + if (primary == null) primary = Math.min(ranges.length - 1, this.sel.primIndex); + setSelection(this, normalizeSelection(out, primary), options); + }), + addSelection: docMethodOp(function (anchor, head, options) { + var ranges = this.sel.ranges.slice(0); + ranges.push(new Range(clipPos(this, anchor), clipPos(this, head || anchor))); + setSelection(this, normalizeSelection(ranges, ranges.length - 1), options); + }), + + getSelection: function (lineSep) { + var ranges = this.sel.ranges, lines; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + lines = lines ? lines.concat(sel) : sel; + } + if (lineSep === false) return lines; + return lines.join(lineSep || "\n"); + }, + getSelections: function (lineSep) { + var parts = [], ranges = this.sel.ranges; + for (var i = 0; i < ranges.length; i++) { + var sel = getBetween(this, ranges[i].from(), ranges[i].to()); + if (lineSep !== false) sel = sel.join(lineSep || "\n"); + parts[i] = sel; + } + return parts; + }, + replaceSelection: function (code, collapse, origin) { + var dup = []; + for (var i = 0; i < this.sel.ranges.length; i++) {dup[i] = code;} + this.replaceSelections(dup, collapse, origin || "+input"); + }, + replaceSelections: docMethodOp(function (code, collapse, origin) { + var changes = [], sel = this.sel; + for (var i = 0; i < sel.ranges.length; i++) { + var range = sel.ranges[i]; + changes[i] = {from: range.from(), to: range.to(), text: splitLines(code[i]), origin: origin}; + } + var newSel = collapse && collapse != "end" && computeReplacedSel(this, changes, collapse); + for (var i = changes.length - 1; i >= 0; i--) {makeChange(this, changes[i]);} + if (newSel) setSelectionReplaceHistory(this, newSel); + else if (this.cm) ensureCursorVisible(this.cm); + }), + undo: docMethodOp(function () {makeChangeFromHistory(this, "undo");}), + redo: docMethodOp(function () {makeChangeFromHistory(this, "redo");}), + undoSelection: docMethodOp(function () {makeChangeFromHistory(this, "undo", true);}), + redoSelection: docMethodOp(function () {makeChangeFromHistory(this, "redo", true);}), + + setExtending: function (val) {this.extend = val;}, + getExtending: function () {return this.extend;}, + + historySize: function () { + var hist = this.history, done = 0, undone = 0; + for (var i = 0; i < hist.done.length; i++) if (!hist.done[i].ranges) ++done; + for (var i = 0; i < hist.undone.length; i++) if (!hist.undone[i].ranges) ++undone; + return {undo: done, redo: undone}; + }, + clearHistory: function () {this.history = new History(this.history.maxGeneration);}, + + markClean: function () { + this.cleanGeneration = this.changeGeneration(true); + }, + changeGeneration: function (forceSplit) { + if (forceSplit) {this.history.lastOp = this.history.lastSelOp = this.history.lastOrigin = null;} + return this.history.generation; + }, + isClean: function (gen) { + return this.history.generation == (gen || this.cleanGeneration); + }, + + getHistory: function () { + return {done: copyHistoryArray(this.history.done), + undone: copyHistoryArray(this.history.undone)}; + }, + setHistory: function (histData) { + var hist = this.history = new History(this.history.maxGeneration); + hist.done = copyHistoryArray(histData.done.slice(0), null, true); + hist.undone = copyHistoryArray(histData.undone.slice(0), null, true); + }, + + addLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + if (!line[prop]) line[prop] = cls; + else if (classTest(cls).test(line[prop])) return false; + else line[prop] += " " + cls; + return true; + }); + }), + removeLineClass: docMethodOp(function (handle, where, cls) { + return changeLine(this, handle, where == "gutter" ? "gutter" : "class", function (line) { + var prop = where == "text" ? "textClass" + : where == "background" ? "bgClass" + : where == "gutter" ? "gutterClass" : "wrapClass"; + var cur = line[prop]; + if (!cur) return false; + else if (cls == null) line[prop] = null; + else { + var found = cur.match(classTest(cls)); + if (!found) return false; + var end = found.index + found[0].length; + line[prop] = cur.slice(0, found.index) + (!found.index || end == cur.length ? "" : " ") + cur.slice(end) || null; + } + return true; + }); + }), + + addLineWidget: docMethodOp(function (handle, node, options) { + return addLineWidget(this, handle, node, options); + }), + removeLineWidget: function (widget) { widget.clear(); }, + + markText: function (from, to, options) { + return markText(this, clipPos(this, from), clipPos(this, to), options, "range"); + }, + setBookmark: function (pos, options) { + var realOpts = {replacedWith: options && (options.nodeType == null ? options.widget : options), + insertLeft: options && options.insertLeft, + clearWhenEmpty: false, shared: options && options.shared, + handleMouseEvents: options && options.handleMouseEvents}; + pos = clipPos(this, pos); + return markText(this, pos, pos, realOpts, "bookmark"); + }, + findMarksAt: function (pos) { + pos = clipPos(this, pos); + var markers = [], spans = getLine(this, pos.line).markedSpans; + if (spans) { + for (var i = 0; i < spans.length; ++i) { + var span = spans[i]; + if ((span.from == null || span.from <= pos.ch) && + (span.to == null || span.to >= pos.ch)) {markers.push(span.marker.parent || span.marker);} + } + } + return markers; + }, + findMarks: function (from, to, filter) { + from = clipPos(this, from); to = clipPos(this, to); + var found = [], lineNo = from.line; + this.iter(from.line, to.line + 1, function (line) { + var spans = line.markedSpans; + if (spans) { + for (var i = 0; i < spans.length; i++) { + var span = spans[i]; + if (!(lineNo == from.line && from.ch > span.to || + span.from == null && lineNo != from.line || + lineNo == to.line && span.from > to.ch) && + (!filter || filter(span.marker))) {found.push(span.marker.parent || span.marker);} + } + } + ++lineNo; + }); + return found; + }, + getAllMarks: function () { + var markers = []; + this.iter(function (line) { + var sps = line.markedSpans; + if (sps) { + for (var i = 0; i < sps.length; ++i) {if (sps[i].from != null) markers.push(sps[i].marker);} + } + }); + return markers; + }, + + posFromIndex: function (off) { + var ch, lineNo = this.first; + this.iter(function (line) { + var sz = line.text.length + 1; + if (sz > off) { ch = off; return true; } + off -= sz; + ++lineNo; + }); + return clipPos(this, Pos(lineNo, ch)); + }, + indexFromPos: function (coords) { + coords = clipPos(this, coords); + var index = coords.ch; + if (coords.line < this.first || coords.ch < 0) return 0; + this.iter(this.first, coords.line, function (line) { + index += line.text.length + 1; + }); + return index; + }, + + copy: function (copyHistory) { + var doc = new Doc(getLines(this, this.first, this.first + this.size), this.modeOption, this.first); + doc.scrollTop = this.scrollTop; doc.scrollLeft = this.scrollLeft; + doc.sel = this.sel; + doc.extend = false; + if (copyHistory) { + doc.history.undoDepth = this.history.undoDepth; + doc.setHistory(this.getHistory()); + } + return doc; + }, + + linkedDoc: function (options) { + if (!options) options = {}; + var from = this.first, to = this.first + this.size; + if (options.from != null && options.from > from) from = options.from; + if (options.to != null && options.to < to) to = options.to; + var copy = new Doc(getLines(this, from, to), options.mode || this.modeOption, from); + if (options.sharedHist) copy.history = this.history; + (this.linked || (this.linked = [])).push({doc: copy, sharedHist: options.sharedHist}); + copy.linked = [{doc: this, isParent: true, sharedHist: options.sharedHist}]; + copySharedMarkers(copy, findSharedMarkers(this)); + return copy; + }, + unlinkDoc: function (other) { + if (other instanceof CodeMirror) other = other.doc; + if (this.linked) { + for (var i = 0; i < this.linked.length; ++i) { + var link = this.linked[i]; + if (link.doc != other) continue; + this.linked.splice(i, 1); + other.unlinkDoc(this); + detachSharedMarkers(findSharedMarkers(this)); + break; + } + } + // If the histories were shared, split them again + if (other.history == this.history) { + var splitIds = [other.id]; + linkedDocs(other, function (doc) {splitIds.push(doc.id);}, true); + other.history = new History(null); + other.history.done = copyHistoryArray(this.history.done, splitIds); + other.history.undone = copyHistoryArray(this.history.undone, splitIds); + } + }, + iterLinkedDocs: function (f) {linkedDocs(this, f);}, + + getMode: function () {return this.mode;}, + getEditor: function () {return this.cm;} }); - return out; - } - - // Update the height of a line, propagating the height change - // upwards to parent nodes. - function updateLineHeight(line, height) { - var diff = height - line.height; - if (diff) for (var n = line; n; n = n.parent) n.height += diff; - } - - // Given a line object, find its line number by walking up through - // its parent links. - function lineNo(line) { - if (line.parent == null) return null; - var cur = line.parent, no = indexOf(cur.lines, line); - for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { - for (var i = 0;; ++i) { - if (chunk.children[i] == cur) break; - no += chunk.children[i].chunkSize(); - } - } - return no + cur.first; - } - - // Find the line at the given vertical position, using the height - // information in the document tree. - function lineAtHeight(chunk, h) { - var n = chunk.first; - outer: do { - for (var i = 0; i < chunk.children.length; ++i) { - var child = chunk.children[i], ch = child.height; - if (h < ch) { chunk = child; continue outer; } - h -= ch; - n += child.chunkSize(); - } - return n; - } while (!chunk.lines); - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i], lh = line.height; - if (h < lh) break; - h -= lh; - } - return n + i; - } - - - // Find the height above the given line. - function heightAtLine(lineObj) { - lineObj = visualLine(lineObj); - - var h = 0, chunk = lineObj.parent; - for (var i = 0; i < chunk.lines.length; ++i) { - var line = chunk.lines[i]; - if (line == lineObj) break; - else h += line.height; - } - for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { - for (var i = 0; i < p.children.length; ++i) { - var cur = p.children[i]; - if (cur == chunk) break; - else h += cur.height; - } - } - return h; - } - - // Get the bidi ordering for the given line (and cache it). Returns - // false for lines that are fully left-to-right, and an array of - // BidiSpan objects otherwise. - function getOrder(line) { - var order = line.order; - if (order == null) order = line.order = bidiOrdering(line.text); - return order; - } - - // HISTORY - - function History(startGen) { + + // Public alias. + Doc.prototype.eachLine = Doc.prototype.iter; + + // Set up methods on CodeMirror's prototype to redirect to the editor's document. + var dontDelegate = "iter insert remove copy getEditor constructor".split(" "); + for (var prop in Doc.prototype) { + if (Doc.prototype.hasOwnProperty(prop) && indexOf(dontDelegate, prop) < 0) { + CodeMirror.prototype[prop] = (function (method) { + return function () {return method.apply(this.doc, arguments);}; + })(Doc.prototype[prop]); + } + } + + eventMixin(Doc); + + // Call f for all linked documents. + function linkedDocs (doc, f, sharedHistOnly) { + function propagate (doc, skip, sharedHist) { + if (doc.linked) { + for (var i = 0; i < doc.linked.length; ++i) { + var rel = doc.linked[i]; + if (rel.doc == skip) continue; + var shared = sharedHist && rel.sharedHist; + if (sharedHistOnly && !shared) continue; + f(rel.doc, shared); + propagate(rel.doc, doc, shared); + } + } + } + propagate(doc, null, true); + } + + // Attach a document to an editor. + function attachDoc (cm, doc) { + if (doc.cm) throw new Error("This document is already in use."); + cm.doc = doc; + doc.cm = cm; + estimateLineHeights(cm); + loadMode(cm); + if (!cm.options.lineWrapping) findMaxLine(cm); + cm.options.mode = doc.modeOption; + regChange(cm); + } + + // LINE UTILITIES + + // Find the line object corresponding to the given line number. + function getLine (doc, n) { + n -= doc.first; + if (n < 0 || n >= doc.size) throw new Error("There is no line " + (n + doc.first) + " in the document."); + for (var chunk = doc; !chunk.lines;) { + for (var i = 0; ; ++i) { + var child = chunk.children[i], sz = child.chunkSize(); + if (n < sz) { chunk = child; break; } + n -= sz; + } + } + return chunk.lines[n]; + } + + // Get the part of a document between two positions, as an array of + // strings. + function getBetween (doc, start, end) { + var out = [], n = start.line; + doc.iter(start.line, end.line + 1, function (line) { + var text = line.text; + if (n == end.line) text = text.slice(0, end.ch); + if (n == start.line) text = text.slice(start.ch); + out.push(text); + ++n; + }); + return out; + } + // Get the lines between from and to, as array of strings. + function getLines (doc, from, to, lineFilter) { + var out = []; + doc.iter(from, to, function (line) { + var text = line.text; + if(lineFilter) { + text = lineFilter(line); + } + out.push(text); + }); + return out; + } + + // Update the height of a line, propagating the height change + // upwards to parent nodes. + function updateLineHeight (line, height) { + var diff = height - line.height; + if (diff) for (var n = line; n; n = n.parent) n.height += diff; + } + + // Given a line object, find its line number by walking up through + // its parent links. + function lineNo (line) { + if (line.parent == null) return null; + var cur = line.parent, no = indexOf(cur.lines, line); + for (var chunk = cur.parent; chunk; cur = chunk, chunk = chunk.parent) { + for (var i = 0; ; ++i) { + if (chunk.children[i] == cur) break; + no += chunk.children[i].chunkSize(); + } + } + return no + cur.first; + } + + // Find the line at the given vertical position, using the height + // information in the document tree. + function lineAtHeight (chunk, h) { + var n = chunk.first; + outer: do { + for (var i = 0; i < chunk.children.length; ++i) { + var child = chunk.children[i], ch = child.height; + if (h < ch) { chunk = child; continue outer; } + h -= ch; + n += child.chunkSize(); + } + return n; + } while (!chunk.lines); + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i], lh = line.height; + if (h < lh) break; + h -= lh; + } + return n + i; + } + + + // Find the height above the given line. + function heightAtLine (lineObj) { + lineObj = visualLine(lineObj); + + var h = 0, chunk = lineObj.parent; + for (var i = 0; i < chunk.lines.length; ++i) { + var line = chunk.lines[i]; + if (line == lineObj) break; + else h += line.height; + } + for (var p = chunk.parent; p; chunk = p, p = chunk.parent) { + for (var i = 0; i < p.children.length; ++i) { + var cur = p.children[i]; + if (cur == chunk) break; + else h += cur.height; + } + } + return h; + } + + // Get the bidi ordering for the given line (and cache it). Returns + // false for lines that are fully left-to-right, and an array of + // BidiSpan objects otherwise. + function getOrder (line) { + var order = line.order; + if (order == null) order = line.order = bidiOrdering(line.text); + return order; + } + + // HISTORY + + function History (startGen) { // Arrays of change events and selections. Doing something adds an // event to done and clears undo. Undoing moves events from done // to undone, redoing moves them in the other direction. - this.done = []; this.undone = []; - this.undoDepth = Infinity; - // Used to track when changes can be merged into a single undo - // event - this.lastModTime = this.lastSelTime = 0; - this.lastOp = this.lastSelOp = null; - this.lastOrigin = this.lastSelOrigin = null; - // Used by the isClean() method - this.generation = this.maxGeneration = startGen || 1; - } - - // Create a history change event from an updateDoc-style change - // object. - function historyChangeFromChange(doc, change) { - var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; - attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); - linkedDocs(doc, function(doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); - return histChange; - } - - // Pop all selection events off the end of a history array. Stop at - // a change event. - function clearSelectionEvents(array) { - while (array.length) { - var last = lst(array); - if (last.ranges) array.pop(); - else break; - } - } - - // Find the top change event in the history. Pop off selection - // events that are in the way. - function lastChangeEvent(hist, force) { - if (force) { - clearSelectionEvents(hist.done); - return lst(hist.done); - } else if (hist.done.length && !lst(hist.done).ranges) { - return lst(hist.done); - } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { - hist.done.pop(); - return lst(hist.done); - } - } - - // Register a change in the history. Merges changes that are within - // a single operation, ore are close together with an origin that - // allows merging (starting with "+") into a single event. - function addChangeToHistory(doc, change, selAfter, opId) { - var hist = doc.history; - hist.undone.length = 0; - var time = +new Date, cur; - - if ((hist.lastOp == opId || + this.done = []; this.undone = []; + this.undoDepth = Infinity; + // Used to track when changes can be merged into a single undo + // event + this.lastModTime = this.lastSelTime = 0; + this.lastOp = this.lastSelOp = null; + this.lastOrigin = this.lastSelOrigin = null; + // Used by the isClean() method + this.generation = this.maxGeneration = startGen || 1; + } + + // Create a history change event from an updateDoc-style change + // object. + function historyChangeFromChange (doc, change) { + var histChange = {from: copyPos(change.from), to: changeEnd(change), text: getBetween(doc, change.from, change.to)}; + attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1); + linkedDocs(doc, function (doc) {attachLocalSpans(doc, histChange, change.from.line, change.to.line + 1);}, true); + return histChange; + } + + // Pop all selection events off the end of a history array. Stop at + // a change event. + function clearSelectionEvents (array) { + while (array.length) { + var last = lst(array); + if (last.ranges) array.pop(); + else break; + } + } + + // Find the top change event in the history. Pop off selection + // events that are in the way. + function lastChangeEvent (hist, force) { + if (force) { + clearSelectionEvents(hist.done); + return lst(hist.done); + } else if (hist.done.length && !lst(hist.done).ranges) { + return lst(hist.done); + } else if (hist.done.length > 1 && !hist.done[hist.done.length - 2].ranges) { + hist.done.pop(); + return lst(hist.done); + } + } + + // Register a change in the history. Merges changes that are within + // a single operation, ore are close together with an origin that + // allows merging (starting with "+") into a single event. + function addChangeToHistory (doc, change, selAfter, opId) { + var hist = doc.history; + hist.undone.length = 0; + var time = +new Date, cur; + + if ((hist.lastOp == opId || hist.lastOrigin == change.origin && change.origin && ((change.origin.charAt(0) == "+" && doc.cm && hist.lastModTime > time - doc.cm.options.historyEventDelay) || change.origin.charAt(0) == "*")) && (cur = lastChangeEvent(hist, hist.lastOp == opId))) { - // Merge this change into the last event - var last = lst(cur.changes); - if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { - // Optimized case for simple insertion -- don't want to add - // new changesets for every character typed - last.to = changeEnd(change); - } else { - // Add new sub-event - cur.changes.push(historyChangeFromChange(doc, change)); - } - } else { - // Can not be merged, start a new event. - var before = lst(hist.done); - if (!before || !before.ranges) - pushSelectionToHistory(doc.sel, hist.done); - cur = {changes: [historyChangeFromChange(doc, change)], - generation: hist.generation}; - hist.done.push(cur); - while (hist.done.length > hist.undoDepth) { - hist.done.shift(); - if (!hist.done[0].ranges) hist.done.shift(); - } - } - hist.done.push(selAfter); - hist.generation = ++hist.maxGeneration; - hist.lastModTime = hist.lastSelTime = time; - hist.lastOp = hist.lastSelOp = opId; - hist.lastOrigin = hist.lastSelOrigin = change.origin; - - if (!last) signal(doc, "historyAdded"); - } - - function selectionEventCanBeMerged(doc, origin, prev, sel) { - var ch = origin.charAt(0); - return ch == "*" || + // Merge this change into the last event + var last = lst(cur.changes); + if (cmp(change.from, change.to) == 0 && cmp(change.from, last.to) == 0) { + // Optimized case for simple insertion -- don't want to add + // new changesets for every character typed + last.to = changeEnd(change); + } else { + // Add new sub-event + cur.changes.push(historyChangeFromChange(doc, change)); + } + } else { + // Can not be merged, start a new event. + var before = lst(hist.done); + if (!before || !before.ranges) {pushSelectionToHistory(doc.sel, hist.done);} + cur = {changes: [historyChangeFromChange(doc, change)], + generation: hist.generation}; + hist.done.push(cur); + while (hist.done.length > hist.undoDepth) { + hist.done.shift(); + if (!hist.done[0].ranges) hist.done.shift(); + } + } + hist.done.push(selAfter); + hist.generation = ++hist.maxGeneration; + hist.lastModTime = hist.lastSelTime = time; + hist.lastOp = hist.lastSelOp = opId; + hist.lastOrigin = hist.lastSelOrigin = change.origin; + + if (!last) signal(doc, "historyAdded"); + } + + function selectionEventCanBeMerged (doc, origin, prev, sel) { + var ch = origin.charAt(0); + return ch == "*" || ch == "+" && prev.ranges.length == sel.ranges.length && prev.somethingSelected() == sel.somethingSelected() && new Date - doc.history.lastSelTime <= (doc.cm ? doc.cm.options.historyEventDelay : 500); - } - - // Called whenever the selection changes, sets the new selection as - // the pending selection in the history, and pushes the old pending - // selection into the 'done' array when it was significantly - // different (in number of selected ranges, emptiness, or time). - function addSelectionToHistory(doc, sel, opId, options) { - var hist = doc.history, origin = options && options.origin; - - // A new event is started when the previous origin does not match - // the current, or the origins don't allow matching. Origins - // starting with * are always merged, those starting with + are - // merged when similar and close together in time. - if (opId == hist.lastSelOp || + } + + // Called whenever the selection changes, sets the new selection as + // the pending selection in the history, and pushes the old pending + // selection into the 'done' array when it was significantly + // different (in number of selected ranges, emptiness, or time). + function addSelectionToHistory (doc, sel, opId, options) { + var hist = doc.history, origin = options && options.origin; + + // A new event is started when the previous origin does not match + // the current, or the origins don't allow matching. Origins + // starting with * are always merged, those starting with + are + // merged when similar and close together in time. + if (opId == hist.lastSelOp || (origin && hist.lastSelOrigin == origin && (hist.lastModTime == hist.lastSelTime && hist.lastOrigin == origin || - selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) - hist.done[hist.done.length - 1] = sel; - else - pushSelectionToHistory(sel, hist.done); - - hist.lastSelTime = +new Date; - hist.lastSelOrigin = origin; - hist.lastSelOp = opId; - if (options && options.clearRedo !== false) - clearSelectionEvents(hist.undone); - } - - function pushSelectionToHistory(sel, dest) { - var top = lst(dest); - if (!(top && top.ranges && top.equals(sel))) - dest.push(sel); - } - - // Used to store marked span information in the history. - function attachLocalSpans(doc, change, from, to) { - var existing = change["spans_" + doc.id], n = 0; - doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function(line) { - if (line.markedSpans) - (existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans; - ++n; - }); - } - - // When un/re-doing restores text containing marked spans, those - // that have been explicitly cleared should not be restored. - function removeClearedSpans(spans) { - if (!spans) return null; - for (var i = 0, out; i < spans.length; ++i) { - if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } - else if (out) out.push(spans[i]); - } - return !out ? spans : out.length ? out : null; - } - - // Retrieve and filter the old marked spans stored in a change event. - function getOldSpans(doc, change) { - var found = change["spans_" + doc.id]; - if (!found) return null; - for (var i = 0, nw = []; i < change.text.length; ++i) - nw.push(removeClearedSpans(found[i])); - return nw; - } - - // Used both to provide a JSON-safe object in .getHistory, and, when - // detaching a document, to split the history in two - function copyHistoryArray(events, newGroup, instantiateSel) { - for (var i = 0, copy = []; i < events.length; ++i) { - var event = events[i]; - if (event.ranges) { - copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); - continue; - } - var changes = event.changes, newChanges = []; - copy.push({changes: newChanges}); - for (var j = 0; j < changes.length; ++j) { - var change = changes[j], m; - newChanges.push({from: change.from, to: change.to, text: change.text}); - if (newGroup) for (var prop in change) if (m = prop.match(/^spans_(\d+)$/)) { - if (indexOf(newGroup, Number(m[1])) > -1) { - lst(newChanges)[prop] = change[prop]; - delete change[prop]; - } - } - } - } - return copy; - } - - // Rebasing/resetting history to deal with externally-sourced changes - - function rebaseHistSelSingle(pos, from, to, diff) { - if (to < pos.line) { - pos.line += diff; - } else if (from < pos.line) { - pos.line = from; - pos.ch = 0; - } - } - - // Tries to rebase an array of history events given a change in the - // document. If the change touches the same lines as the event, the - // event, and everything 'behind' it, is discarded. If the change is - // before the event, the event's positions are updated. Uses a - // copy-on-write scheme for the positions, to avoid having to - // reallocate them all on every rebase, but also avoid problems with - // shared position objects being unsafely updated. - function rebaseHistArray(array, from, to, diff) { - for (var i = 0; i < array.length; ++i) { - var sub = array[i], ok = true; - if (sub.ranges) { - if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } - for (var j = 0; j < sub.ranges.length; j++) { - rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); - rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); - } - continue; - } - for (var j = 0; j < sub.changes.length; ++j) { - var cur = sub.changes[j]; - if (to < cur.from.line) { - cur.from = Pos(cur.from.line + diff, cur.from.ch); - cur.to = Pos(cur.to.line + diff, cur.to.ch); - } else if (from <= cur.to.line) { - ok = false; - break; - } - } - if (!ok) { - array.splice(0, i + 1); - i = 0; - } - } - } - - function rebaseHist(hist, change) { - var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; - rebaseHistArray(hist.done, from, to, diff); - rebaseHistArray(hist.undone, from, to, diff); - } - - // EVENT UTILITIES - - // Due to the fact that we still support jurassic IE versions, some - // compatibility wrappers are needed. - - var e_preventDefault = CodeMirror.e_preventDefault = function(e) { - if (e.preventDefault) e.preventDefault(); - else e.returnValue = false; - }; - var e_stopPropagation = CodeMirror.e_stopPropagation = function(e) { - if (e.stopPropagation) e.stopPropagation(); - else e.cancelBubble = true; - }; - function e_defaultPrevented(e) { - return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; - } - var e_stop = CodeMirror.e_stop = function(e) {e_preventDefault(e); e_stopPropagation(e);}; - - function e_target(e) {return e.target || e.srcElement;} - function e_button(e) { - var b = e.which; - if (b == null) { - if (e.button & 1) b = 1; - else if (e.button & 2) b = 3; - else if (e.button & 4) b = 2; - } - if (mac && e.ctrlKey && b == 1) b = 3; - return b; - } - - // EVENT HANDLING - - // Lightweight event framework. on/off also work on DOM nodes, - // registering native DOM handlers. - - var on = CodeMirror.on = function(emitter, type, f) { - if (emitter.addEventListener) - emitter.addEventListener(type, f, false); - else if (emitter.attachEvent) - emitter.attachEvent("on" + type, f); - else { - var map = emitter._handlers || (emitter._handlers = {}); - var arr = map[type] || (map[type] = []); - arr.push(f); - } - }; - - var off = CodeMirror.off = function(emitter, type, f) { - if (emitter.removeEventListener) - emitter.removeEventListener(type, f, false); - else if (emitter.detachEvent) - emitter.detachEvent("on" + type, f); - else { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - for (var i = 0; i < arr.length; ++i) - if (arr[i] == f) { arr.splice(i, 1); break; } - } - }; - - var signal = CodeMirror.signal = function(emitter, type /*, values...*/) { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - var args = Array.prototype.slice.call(arguments, 2); - for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); - }; - - var orphanDelayedCallbacks = null; - - // Often, we want to signal events at a point where we are in the - // middle of some work, but don't want the handler to start calling - // other methods on the editor, which might be in an inconsistent - // state or simply not expect any other events to happen. - // signalLater looks whether there are any handlers, and schedules - // them to be executed when the last operation ends, or, if no - // operation is active, when a timeout fires. - function signalLater(emitter, type /*, values...*/) { - var arr = emitter._handlers && emitter._handlers[type]; - if (!arr) return; - var args = Array.prototype.slice.call(arguments, 2), list; - if (operationGroup) { - list = operationGroup.delayedCallbacks; - } else if (orphanDelayedCallbacks) { - list = orphanDelayedCallbacks; - } else { - list = orphanDelayedCallbacks = []; - setTimeout(fireOrphanDelayed, 0); - } - function bnd(f) {return function(){f.apply(null, args);};}; - for (var i = 0; i < arr.length; ++i) - list.push(bnd(arr[i])); - } - - function fireOrphanDelayed() { - var delayed = orphanDelayedCallbacks; - orphanDelayedCallbacks = null; - for (var i = 0; i < delayed.length; ++i) delayed[i](); - } - - // The DOM events that CodeMirror handles can be overridden by - // registering a (non-DOM) handler on the editor for the event name, - // and preventDefault-ing the event in that handler. - function signalDOMEvent(cm, e, override) { - if (typeof e == "string") - e = {type: e, preventDefault: function() { this.defaultPrevented = true; }}; - signal(cm, override || e.type, cm, e); - return e_defaultPrevented(e) || e.codemirrorIgnore; - } - - function signalCursorActivity(cm) { - var arr = cm._handlers && cm._handlers.cursorActivity; - if (!arr) return; - var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); - for (var i = 0; i < arr.length; ++i) if (indexOf(set, arr[i]) == -1) - set.push(arr[i]); - } - - function hasHandler(emitter, type) { - var arr = emitter._handlers && emitter._handlers[type]; - return arr && arr.length > 0; - } - - // Add on and off methods to a constructor's prototype, to make - // registering events on such objects more convenient. - function eventMixin(ctor) { - ctor.prototype.on = function(type, f) {on(this, type, f);}; - ctor.prototype.off = function(type, f) {off(this, type, f);}; - } - - // MISC UTILITIES - - // Number of pixels added to scroller and sizer to hide scrollbar - var scrollerGap = 30; - - // Returned or thrown by various protocols to signal 'I'm not - // handling this'. - var Pass = CodeMirror.Pass = {toString: function(){return "CodeMirror.Pass";}}; - - // Reused option objects for setSelection & friends - var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; - - function Delayed() {this.id = null;} - Delayed.prototype.set = function(ms, f) { - clearTimeout(this.id); - this.id = setTimeout(f, ms); - }; - - // Counts the column offset in a string, taking tabs into account. - // Used mostly to find indentation. - var countColumn = CodeMirror.countColumn = function(string, end, tabSize, startIndex, startValue) { - if (end == null) { - end = string.search(/[^\s\u00a0]/); - if (end == -1) end = string.length; - } - for (var i = startIndex || 0, n = startValue || 0;;) { - var nextTab = string.indexOf("\t", i); - if (nextTab < 0 || nextTab >= end) - return n + (end - i); - n += nextTab - i; - n += tabSize - (n % tabSize); - i = nextTab + 1; - } - }; - - // The inverse of countColumn -- find the offset that corresponds to - // a particular column. - function findColumn(string, goal, tabSize) { - for (var pos = 0, col = 0;;) { - var nextTab = string.indexOf("\t", pos); - if (nextTab == -1) nextTab = string.length; - var skipped = nextTab - pos; - if (nextTab == string.length || col + skipped >= goal) - return pos + Math.min(skipped, goal - col); - col += nextTab - pos; - col += tabSize - (col % tabSize); - pos = nextTab + 1; - if (col >= goal) return pos; - } - } - - var spaceStrs = [""]; - function spaceStr(n) { - while (spaceStrs.length <= n) - spaceStrs.push(lst(spaceStrs) + " "); - return spaceStrs[n]; - } - - function lst(arr) { return arr[arr.length-1]; } - - var selectInput = function(node) { node.select(); }; - if (ios) // Mobile Safari apparently has a bug where select() is broken. - selectInput = function(node) { node.selectionStart = 0; node.selectionEnd = node.value.length; }; - else if (ie) // Suppress mysterious IE10 errors - selectInput = function(node) { try { node.select(); } catch(_e) {} }; - - function indexOf(array, elt) { - for (var i = 0; i < array.length; ++i) - if (array[i] == elt) return i; - return -1; - } - function map(array, f) { - var out = []; - for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); - return out; - } - - function nothing() {} - - function createObj(base, props) { - var inst; - if (Object.create) { - inst = Object.create(base); - } else { - nothing.prototype = base; - inst = new nothing(); - } - if (props) copyObj(props, inst); - return inst; - }; - - function copyObj(obj, target, overwrite) { - if (!target) target = {}; - for (var prop in obj) - if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) - target[prop] = obj[prop]; - return target; - } - - function bind(f) { - var args = Array.prototype.slice.call(arguments, 1); - return function(){return f.apply(null, args);}; - } - - var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; - var isWordCharBasic = CodeMirror.isWordChar = function(ch) { - return /\w/.test(ch) || ch > "\x80" && + selectionEventCanBeMerged(doc, origin, lst(hist.done), sel)))) {hist.done[hist.done.length - 1] = sel;} else {pushSelectionToHistory(sel, hist.done);} + + hist.lastSelTime = +new Date; + hist.lastSelOrigin = origin; + hist.lastSelOp = opId; + if (options && options.clearRedo !== false) {clearSelectionEvents(hist.undone);} + } + + function pushSelectionToHistory (sel, dest) { + var top = lst(dest); + if (!(top && top.ranges && top.equals(sel))) {dest.push(sel);} + } + + // Used to store marked span information in the history. + function attachLocalSpans (doc, change, from, to) { + var existing = change["spans_" + doc.id], n = 0; + doc.iter(Math.max(doc.first, from), Math.min(doc.first + doc.size, to), function (line) { + if (line.markedSpans) {(existing || (existing = change["spans_" + doc.id] = {}))[n] = line.markedSpans;} + ++n; + }); + } + + // When un/re-doing restores text containing marked spans, those + // that have been explicitly cleared should not be restored. + function removeClearedSpans (spans) { + if (!spans) return null; + for (var i = 0, out; i < spans.length; ++i) { + if (spans[i].marker.explicitlyCleared) { if (!out) out = spans.slice(0, i); } else if (out) out.push(spans[i]); + } + return !out ? spans : out.length ? out : null; + } + + // Retrieve and filter the old marked spans stored in a change event. + function getOldSpans (doc, change) { + var found = change["spans_" + doc.id]; + if (!found) return null; + for (var i = 0, nw = []; i < change.text.length; ++i) {nw.push(removeClearedSpans(found[i]));} + return nw; + } + + // Used both to provide a JSON-safe object in .getHistory, and, when + // detaching a document, to split the history in two + function copyHistoryArray (events, newGroup, instantiateSel) { + for (var i = 0, copy = []; i < events.length; ++i) { + var event = events[i]; + if (event.ranges) { + copy.push(instantiateSel ? Selection.prototype.deepCopy.call(event) : event); + continue; + } + var changes = event.changes, newChanges = []; + copy.push({changes: newChanges}); + for (var j = 0; j < changes.length; ++j) { + var change = changes[j], m; + newChanges.push({from: change.from, to: change.to, text: change.text}); + if (newGroup) { + for (var prop in change) { + if (m = prop.match(/^spans_(\d+)$/)) { + if (indexOf(newGroup, Number(m[1])) > -1) { + lst(newChanges)[prop] = change[prop]; + delete change[prop]; + } + } + } + } + } + } + return copy; + } + + // Rebasing/resetting history to deal with externally-sourced changes + + function rebaseHistSelSingle (pos, from, to, diff) { + if (to < pos.line) { + pos.line += diff; + } else if (from < pos.line) { + pos.line = from; + pos.ch = 0; + } + } + + // Tries to rebase an array of history events given a change in the + // document. If the change touches the same lines as the event, the + // event, and everything 'behind' it, is discarded. If the change is + // before the event, the event's positions are updated. Uses a + // copy-on-write scheme for the positions, to avoid having to + // reallocate them all on every rebase, but also avoid problems with + // shared position objects being unsafely updated. + function rebaseHistArray (array, from, to, diff) { + for (var i = 0; i < array.length; ++i) { + var sub = array[i], ok = true; + if (sub.ranges) { + if (!sub.copied) { sub = array[i] = sub.deepCopy(); sub.copied = true; } + for (var j = 0; j < sub.ranges.length; j++) { + rebaseHistSelSingle(sub.ranges[j].anchor, from, to, diff); + rebaseHistSelSingle(sub.ranges[j].head, from, to, diff); + } + continue; + } + for (var j = 0; j < sub.changes.length; ++j) { + var cur = sub.changes[j]; + if (to < cur.from.line) { + cur.from = Pos(cur.from.line + diff, cur.from.ch); + cur.to = Pos(cur.to.line + diff, cur.to.ch); + } else if (from <= cur.to.line) { + ok = false; + break; + } + } + if (!ok) { + array.splice(0, i + 1); + i = 0; + } + } + } + + function rebaseHist (hist, change) { + var from = change.from.line, to = change.to.line, diff = change.text.length - (to - from) - 1; + rebaseHistArray(hist.done, from, to, diff); + rebaseHistArray(hist.undone, from, to, diff); + } + + // EVENT UTILITIES + + // Due to the fact that we still support jurassic IE versions, some + // compatibility wrappers are needed. + + var e_preventDefault = CodeMirror.e_preventDefault = function (e) { + if (e.preventDefault) e.preventDefault(); + else e.returnValue = false; + }; + var e_stopPropagation = CodeMirror.e_stopPropagation = function (e) { + if (e.stopPropagation) e.stopPropagation(); + else e.cancelBubble = true; + }; + function e_defaultPrevented (e) { + return e.defaultPrevented != null ? e.defaultPrevented : e.returnValue == false; + } + var e_stop = CodeMirror.e_stop = function (e) {e_preventDefault(e); e_stopPropagation(e);}; + + function e_target (e) {return e.target || e.srcElement;} + function e_button (e) { + var b = e.which; + if (b == null) { + if (e.button & 1) b = 1; + else if (e.button & 2) b = 3; + else if (e.button & 4) b = 2; + } + if (mac && e.ctrlKey && b == 1) b = 3; + return b; + } + + // EVENT HANDLING + + // Lightweight event framework. on/off also work on DOM nodes, + // registering native DOM handlers. + + var on = CodeMirror.on = function (emitter, type, f) { + if (emitter.addEventListener) {emitter.addEventListener(type, f, false);} else if (emitter.attachEvent) {emitter.attachEvent("on" + type, f);} else { + var map = emitter._handlers || (emitter._handlers = {}); + var arr = map[type] || (map[type] = []); + arr.push(f); + } + }; + + var off = CodeMirror.off = function (emitter, type, f) { + if (emitter.removeEventListener) {emitter.removeEventListener(type, f, false);} else if (emitter.detachEvent) {emitter.detachEvent("on" + type, f);} else { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + for (var i = 0; i < arr.length; ++i) {if (arr[i] == f) { arr.splice(i, 1); break; }} + } + }; + + var signal = CodeMirror.signal = function (emitter, type /* , values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2); + for (var i = 0; i < arr.length; ++i) arr[i].apply(null, args); + }; + + var orphanDelayedCallbacks = null; + + // Often, we want to signal events at a point where we are in the + // middle of some work, but don't want the handler to start calling + // other methods on the editor, which might be in an inconsistent + // state or simply not expect any other events to happen. + // signalLater looks whether there are any handlers, and schedules + // them to be executed when the last operation ends, or, if no + // operation is active, when a timeout fires. + function signalLater (emitter, type /* , values...*/) { + var arr = emitter._handlers && emitter._handlers[type]; + if (!arr) return; + var args = Array.prototype.slice.call(arguments, 2), list; + if (operationGroup) { + list = operationGroup.delayedCallbacks; + } else if (orphanDelayedCallbacks) { + list = orphanDelayedCallbacks; + } else { + list = orphanDelayedCallbacks = []; + setTimeout(fireOrphanDelayed, 0); + } + function bnd (f) {return function () {f.apply(null, args);};} + for (var i = 0; i < arr.length; ++i) {list.push(bnd(arr[i]));} + } + + function fireOrphanDelayed () { + var delayed = orphanDelayedCallbacks; + orphanDelayedCallbacks = null; + for (var i = 0; i < delayed.length; ++i) delayed[i](); + } + + // The DOM events that CodeMirror handles can be overridden by + // registering a (non-DOM) handler on the editor for the event name, + // and preventDefault-ing the event in that handler. + function signalDOMEvent (cm, e, override) { + if (typeof e === "string") {e = {type: e, preventDefault: function () { this.defaultPrevented = true; }};} + signal(cm, override || e.type, cm, e); + return e_defaultPrevented(e) || e.codemirrorIgnore; + } + + function signalCursorActivity (cm) { + var arr = cm._handlers && cm._handlers.cursorActivity; + if (!arr) return; + var set = cm.curOp.cursorActivityHandlers || (cm.curOp.cursorActivityHandlers = []); + for (var i = 0; i < arr.length; ++i) { + if (indexOf(set, arr[i]) == -1) {set.push(arr[i]);} + } + } + + function hasHandler (emitter, type) { + var arr = emitter._handlers && emitter._handlers[type]; + return arr && arr.length > 0; + } + + // Add on and off methods to a constructor's prototype, to make + // registering events on such objects more convenient. + function eventMixin (ctor) { + ctor.prototype.on = function (type, f) {on(this, type, f);}; + ctor.prototype.off = function (type, f) {off(this, type, f);}; + } + + // MISC UTILITIES + + // Number of pixels added to scroller and sizer to hide scrollbar + var scrollerGap = 30; + + // Returned or thrown by various protocols to signal 'I'm not + // handling this'. + var Pass = CodeMirror.Pass = {toString: function () {return "CodeMirror.Pass";}}; + + // Reused option objects for setSelection & friends + var sel_dontScroll = {scroll: false}, sel_mouse = {origin: "*mouse"}, sel_move = {origin: "+move"}; + + function Delayed () {this.id = null;} + Delayed.prototype.set = function (ms, f) { + clearTimeout(this.id); + this.id = setTimeout(f, ms); + }; + + // Counts the column offset in a string, taking tabs into account. + // Used mostly to find indentation. + var countColumn = CodeMirror.countColumn = function (string, end, tabSize, startIndex, startValue) { + if (end == null) { + end = string.search(/[^\s\u00a0]/); + if (end == -1) end = string.length; + } + for (var i = startIndex || 0, n = startValue || 0; ;) { + var nextTab = string.indexOf("\t", i); + if (nextTab < 0 || nextTab >= end) {return n + (end - i);} + n += nextTab - i; + n += tabSize - (n % tabSize); + i = nextTab + 1; + } + }; + + // The inverse of countColumn -- find the offset that corresponds to + // a particular column. + function findColumn (string, goal, tabSize) { + for (var pos = 0, col = 0; ;) { + var nextTab = string.indexOf("\t", pos); + if (nextTab == -1) nextTab = string.length; + var skipped = nextTab - pos; + if (nextTab == string.length || col + skipped >= goal) {return pos + Math.min(skipped, goal - col);} + col += nextTab - pos; + col += tabSize - (col % tabSize); + pos = nextTab + 1; + if (col >= goal) return pos; + } + } + + var spaceStrs = [""]; + function spaceStr (n) { + while (spaceStrs.length <= n) {spaceStrs.push(lst(spaceStrs) + " ");} + return spaceStrs[n]; + } + + function lst (arr) { return arr[arr.length - 1]; } + + var selectInput = function (node) { node.select(); }; + if (ios) // Mobile Safari apparently has a bug where select() is broken. + {selectInput = function (node) { node.selectionStart = 0; node.selectionEnd = node.value.length; };} else if (ie) // Suppress mysterious IE10 errors + {selectInput = function (node) { try { node.select(); } catch(_e) {} };} + + function indexOf (array, elt) { + for (var i = 0; i < array.length; ++i) {if (array[i] == elt) return i;} + return -1; + } + function map (array, f) { + var out = []; + for (var i = 0; i < array.length; i++) out[i] = f(array[i], i); + return out; + } + + function nothing () {} + + function createObj (base, props) { + var inst; + if (Object.create) { + inst = Object.create(base); + } else { + nothing.prototype = base; + inst = new nothing(); + } + if (props) copyObj(props, inst); + return inst; + } + + function copyObj (obj, target, overwrite) { + if (!target) target = {}; + for (var prop in obj) { + if (obj.hasOwnProperty(prop) && (overwrite !== false || !target.hasOwnProperty(prop))) {target[prop] = obj[prop];} + } + return target; + } + + function bind (f) { + var args = Array.prototype.slice.call(arguments, 1); + return function () {return f.apply(null, args);}; + } + + var nonASCIISingleCaseWordChar = /[\u00df\u0587\u0590-\u05f4\u0600-\u06ff\u3040-\u309f\u30a0-\u30ff\u3400-\u4db5\u4e00-\u9fcc\uac00-\ud7af]/; + var isWordCharBasic = CodeMirror.isWordChar = function (ch) { + return /\w/.test(ch) || ch > "\x80" && (ch.toUpperCase() != ch.toLowerCase() || nonASCIISingleCaseWordChar.test(ch)); - }; - function isWordChar(ch, helper) { - if (!helper) return isWordCharBasic(ch); - if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; - return helper.test(ch); - } - - function isEmpty(obj) { - for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; - return true; - } - - // Extending unicode characters. A series of a non-extending char + - // any number of extending chars is treated as a single unit as far - // as editing and measuring is concerned. This is not fully correct, - // since some scripts/font/browsers also treat other configurations - // of code points as a group. - var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; - function isExtendingChar(ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } - - // DOM UTILITIES - - function elt(tag, content, className, style) { - var e = document.createElement(tag); - if (className) e.className = className; - if (style) e.style.cssText = style; - if (typeof content == "string") e.appendChild(document.createTextNode(content)); - else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); - return e; - } - - var range; - if (document.createRange) range = function(node, start, end, endNode) { - var r = document.createRange(); - r.setEnd(endNode || node, end); - r.setStart(node, start); - return r; - }; - else range = function(node, start, end) { - var r = document.body.createTextRange(); - try { r.moveToElementText(node.parentNode); } - catch(e) { return r; } - r.collapse(true); - r.moveEnd("character", end); - r.moveStart("character", start); - return r; - }; - - function removeChildren(e) { - for (var count = e.childNodes.length; count > 0; --count) - e.removeChild(e.firstChild); - return e; - } - - function removeChildrenAndAdd(parent, e) { - return removeChildren(parent).appendChild(e); - } - - var contains = CodeMirror.contains = function(parent, child) { - if (child.nodeType == 3) // Android browser always returns false when child is a textnode - child = child.parentNode; - if (parent.contains) - return parent.contains(child); - do { - if (child.nodeType == 11) child = child.host; - if (child == parent) return true; - } while (child = child.parentNode); - }; - - function activeElt() { return document.activeElement; } - // Older versions of IE throws unspecified error when touching - // document.activeElement in some cases (during loading, in iframe) - if (ie && ie_version < 11) activeElt = function() { - try { return document.activeElement; } - catch(e) { return document.body; } - }; - - function classTest(cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } - var rmClass = CodeMirror.rmClass = function(node, cls) { - var current = node.className; - var match = classTest(cls).exec(current); - if (match) { - var after = current.slice(match.index + match[0].length); - node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); - } - }; - var addClass = CodeMirror.addClass = function(node, cls) { - var current = node.className; - if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; - }; - function joinClasses(a, b) { - var as = a.split(" "); - for (var i = 0; i < as.length; i++) - if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i]; - return b; - } - - // WINDOW-WIDE EVENTS - - // These must be handled carefully, because naively registering a - // handler for each editor will cause the editors to never be - // garbage collected. - - function forEachCodeMirror(f) { - if (!document.body.getElementsByClassName) return; - var byClass = document.body.getElementsByClassName("CodeMirror"); - for (var i = 0; i < byClass.length; i++) { - var cm = byClass[i].CodeMirror; - if (cm) f(cm); - } - } - - var globalsRegistered = false; - function ensureGlobalHandlers() { - if (globalsRegistered) return; - registerGlobalHandlers(); - globalsRegistered = true; - } - function registerGlobalHandlers() { + }; + function isWordChar (ch, helper) { + if (!helper) return isWordCharBasic(ch); + if (helper.source.indexOf("\\w") > -1 && isWordCharBasic(ch)) return true; + return helper.test(ch); + } + + function isEmpty (obj) { + for (var n in obj) if (obj.hasOwnProperty(n) && obj[n]) return false; + return true; + } + + // Extending unicode characters. A series of a non-extending char + + // any number of extending chars is treated as a single unit as far + // as editing and measuring is concerned. This is not fully correct, + // since some scripts/font/browsers also treat other configurations + // of code points as a group. + var extendingChars = /[\u0300-\u036f\u0483-\u0489\u0591-\u05bd\u05bf\u05c1\u05c2\u05c4\u05c5\u05c7\u0610-\u061a\u064b-\u065e\u0670\u06d6-\u06dc\u06de-\u06e4\u06e7\u06e8\u06ea-\u06ed\u0711\u0730-\u074a\u07a6-\u07b0\u07eb-\u07f3\u0816-\u0819\u081b-\u0823\u0825-\u0827\u0829-\u082d\u0900-\u0902\u093c\u0941-\u0948\u094d\u0951-\u0955\u0962\u0963\u0981\u09bc\u09be\u09c1-\u09c4\u09cd\u09d7\u09e2\u09e3\u0a01\u0a02\u0a3c\u0a41\u0a42\u0a47\u0a48\u0a4b-\u0a4d\u0a51\u0a70\u0a71\u0a75\u0a81\u0a82\u0abc\u0ac1-\u0ac5\u0ac7\u0ac8\u0acd\u0ae2\u0ae3\u0b01\u0b3c\u0b3e\u0b3f\u0b41-\u0b44\u0b4d\u0b56\u0b57\u0b62\u0b63\u0b82\u0bbe\u0bc0\u0bcd\u0bd7\u0c3e-\u0c40\u0c46-\u0c48\u0c4a-\u0c4d\u0c55\u0c56\u0c62\u0c63\u0cbc\u0cbf\u0cc2\u0cc6\u0ccc\u0ccd\u0cd5\u0cd6\u0ce2\u0ce3\u0d3e\u0d41-\u0d44\u0d4d\u0d57\u0d62\u0d63\u0dca\u0dcf\u0dd2-\u0dd4\u0dd6\u0ddf\u0e31\u0e34-\u0e3a\u0e47-\u0e4e\u0eb1\u0eb4-\u0eb9\u0ebb\u0ebc\u0ec8-\u0ecd\u0f18\u0f19\u0f35\u0f37\u0f39\u0f71-\u0f7e\u0f80-\u0f84\u0f86\u0f87\u0f90-\u0f97\u0f99-\u0fbc\u0fc6\u102d-\u1030\u1032-\u1037\u1039\u103a\u103d\u103e\u1058\u1059\u105e-\u1060\u1071-\u1074\u1082\u1085\u1086\u108d\u109d\u135f\u1712-\u1714\u1732-\u1734\u1752\u1753\u1772\u1773\u17b7-\u17bd\u17c6\u17c9-\u17d3\u17dd\u180b-\u180d\u18a9\u1920-\u1922\u1927\u1928\u1932\u1939-\u193b\u1a17\u1a18\u1a56\u1a58-\u1a5e\u1a60\u1a62\u1a65-\u1a6c\u1a73-\u1a7c\u1a7f\u1b00-\u1b03\u1b34\u1b36-\u1b3a\u1b3c\u1b42\u1b6b-\u1b73\u1b80\u1b81\u1ba2-\u1ba5\u1ba8\u1ba9\u1c2c-\u1c33\u1c36\u1c37\u1cd0-\u1cd2\u1cd4-\u1ce0\u1ce2-\u1ce8\u1ced\u1dc0-\u1de6\u1dfd-\u1dff\u200c\u200d\u20d0-\u20f0\u2cef-\u2cf1\u2de0-\u2dff\u302a-\u302f\u3099\u309a\ua66f-\ua672\ua67c\ua67d\ua6f0\ua6f1\ua802\ua806\ua80b\ua825\ua826\ua8c4\ua8e0-\ua8f1\ua926-\ua92d\ua947-\ua951\ua980-\ua982\ua9b3\ua9b6-\ua9b9\ua9bc\uaa29-\uaa2e\uaa31\uaa32\uaa35\uaa36\uaa43\uaa4c\uaab0\uaab2-\uaab4\uaab7\uaab8\uaabe\uaabf\uaac1\uabe5\uabe8\uabed\udc00-\udfff\ufb1e\ufe00-\ufe0f\ufe20-\ufe26\uff9e\uff9f]/; + function isExtendingChar (ch) { return ch.charCodeAt(0) >= 768 && extendingChars.test(ch); } + + // DOM UTILITIES + + function elt (tag, content, className, style) { + var e = document.createElement(tag); + if (className) e.className = className; + if (style) e.style.cssText = style; + if (typeof content === "string") e.appendChild(document.createTextNode(content)); + else if (content) for (var i = 0; i < content.length; ++i) e.appendChild(content[i]); + return e; + } + + var range; + if (document.createRange) { + range = function (node, start, end, endNode) { + var r = document.createRange(); + r.setEnd(endNode || node, end); + r.setStart(node, start); + return r; + }; + } else { + range = function (node, start, end) { + var r = document.body.createTextRange(); + try { r.moveToElementText(node.parentNode); } catch(e) { return r; } + r.collapse(true); + r.moveEnd("character", end); + r.moveStart("character", start); + return r; + }; + } + + function removeChildren (e) { + for (var count = e.childNodes.length; count > 0; --count) {e.removeChild(e.firstChild);} + return e; + } + + function removeChildrenAndAdd (parent, e) { + return removeChildren(parent).appendChild(e); + } + + var contains = CodeMirror.contains = function (parent, child) { + if (child.nodeType == 3) // Android browser always returns false when child is a textnode + {child = child.parentNode;} + if (parent.contains) {return parent.contains(child);} + do { + if (child.nodeType == 11) child = child.host; + if (child == parent) return true; + } while (child = child.parentNode); + }; + + function activeElt () { return document.activeElement; } + // Older versions of IE throws unspecified error when touching + // document.activeElement in some cases (during loading, in iframe) + if (ie && ie_version < 11) { + activeElt = function () { + try { return document.activeElement; } catch(e) { return document.body; } + }; + } + + function classTest (cls) { return new RegExp("(^|\\s)" + cls + "(?:$|\\s)\\s*"); } + var rmClass = CodeMirror.rmClass = function (node, cls) { + var current = node.className; + var match = classTest(cls).exec(current); + if (match) { + var after = current.slice(match.index + match[0].length); + node.className = current.slice(0, match.index) + (after ? match[1] + after : ""); + } + }; + var addClass = CodeMirror.addClass = function (node, cls) { + var current = node.className; + if (!classTest(cls).test(current)) node.className += (current ? " " : "") + cls; + }; + function joinClasses (a, b) { + var as = a.split(" "); + for (var i = 0; i < as.length; i++) {if (as[i] && !classTest(as[i]).test(b)) b += " " + as[i];} + return b; + } + + // WINDOW-WIDE EVENTS + + // These must be handled carefully, because naively registering a + // handler for each editor will cause the editors to never be + // garbage collected. + + function forEachCodeMirror (f) { + if (!document.body.getElementsByClassName) return; + var byClass = document.body.getElementsByClassName("CodeMirror"); + for (var i = 0; i < byClass.length; i++) { + var cm = byClass[i].CodeMirror; + if (cm) f(cm); + } + } + + var globalsRegistered = false; + function ensureGlobalHandlers () { + if (globalsRegistered) return; + registerGlobalHandlers(); + globalsRegistered = true; + } + function registerGlobalHandlers () { // When the window resizes, we need to refresh active editors. - var resizeTimer; - on(window, "resize", function() { - if (resizeTimer == null) resizeTimer = setTimeout(function() { - resizeTimer = null; - forEachCodeMirror(onResize); - }, 100); - }); - // When the window loses focus, we want to show the editor as blurred - on(window, "blur", function() { - forEachCodeMirror(onBlur); - }); - } + var resizeTimer; + on(window, "resize", function () { + if (resizeTimer == null) { + resizeTimer = setTimeout(function () { + resizeTimer = null; + forEachCodeMirror(onResize); + }, 100); + } + }); + // When the window loses focus, we want to show the editor as blurred + on(window, "blur", function () { + forEachCodeMirror(onBlur); + }); + } - // FEATURE DETECTION + // FEATURE DETECTION - // Detect drag-and-drop - var dragAndDrop = function() { + // Detect drag-and-drop + var dragAndDrop = function () { // There is *some* kind of drag-and-drop support in IE6-8, but I // couldn't get it to work yet. - if (ie && ie_version < 9) return false; - var div = elt('div'); - return "draggable" in div || "dragDrop" in div; - }(); - - var zwspSupported; - function zeroWidthElement(measure) { - if (zwspSupported == null) { - var test = elt("span", "\u200b"); - removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); - if (measure.firstChild.offsetHeight != 0) - zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8); - } - var node = zwspSupported ? elt("span", "\u200b") : - elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); - node.setAttribute("cm-text", ""); - return node; - } - - // Feature-detect IE's crummy client rect reporting for bidi text - var badBidiRects; - function hasBadBidiRects(measure) { - if (badBidiRects != null) return badBidiRects; - var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); - var r0 = range(txt, 0, 1).getBoundingClientRect(); - if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) - var r1 = range(txt, 1, 2).getBoundingClientRect(); - return badBidiRects = (r1.right - r0.right < 3); - } - - // See if "".split is the broken IE version, if so, provide an - // alternative way to split lines. - var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function(string) { - var pos = 0, result = [], l = string.length; - while (pos <= l) { - var nl = string.indexOf("\n", pos); - if (nl == -1) nl = string.length; - var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); - var rt = line.indexOf("\r"); - if (rt != -1) { - result.push(line.slice(0, rt)); - pos += rt + 1; - } else { - result.push(line); - pos = nl + 1; - } - } - return result; - } : function(string){return string.split(/\r\n?|\n/);}; - - var hasSelection = window.getSelection ? function(te) { - try { return te.selectionStart != te.selectionEnd; } - catch(e) { return false; } - } : function(te) { - try {var range = te.ownerDocument.selection.createRange();} - catch(e) {} - if (!range || range.parentElement() != te) return false; - return range.compareEndPoints("StartToEnd", range) != 0; - }; - - var hasCopyEvent = (function() { - var e = elt("div"); - if ("oncopy" in e) return true; - e.setAttribute("oncopy", "return;"); - return typeof e.oncopy == "function"; - })(); - - var badZoomedRects = null; - function hasBadZoomedRects(measure) { - if (badZoomedRects != null) return badZoomedRects; - var node = removeChildrenAndAdd(measure, elt("span", "x")); - var normal = node.getBoundingClientRect(); - var fromRange = range(node, 0, 1).getBoundingClientRect(); - return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; - } - - // KEY NAMES - - var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", - 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", - 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", - 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", - 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", - 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", - 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; - CodeMirror.keyNames = keyNames; - (function() { + if (ie && ie_version < 9) return false; + var div = elt("div"); + return "draggable" in div || "dragDrop" in div; + }(); + + var zwspSupported; + function zeroWidthElement (measure) { + if (zwspSupported == null) { + var test = elt("span", "\u200b"); + removeChildrenAndAdd(measure, elt("span", [test, document.createTextNode("x")])); + if (measure.firstChild.offsetHeight != 0) {zwspSupported = test.offsetWidth <= 1 && test.offsetHeight > 2 && !(ie && ie_version < 8);} + } + var node = zwspSupported ? elt("span", "\u200b") : + elt("span", "\u00a0", null, "display: inline-block; width: 1px; margin-right: -1px"); + node.setAttribute("cm-text", ""); + return node; + } + + // Feature-detect IE's crummy client rect reporting for bidi text + var badBidiRects; + function hasBadBidiRects (measure) { + if (badBidiRects != null) return badBidiRects; + var txt = removeChildrenAndAdd(measure, document.createTextNode("A\u062eA")); + var r0 = range(txt, 0, 1).getBoundingClientRect(); + if (!r0 || r0.left == r0.right) return false; // Safari returns null in some cases (#2780) + var r1 = range(txt, 1, 2).getBoundingClientRect(); + return badBidiRects = (r1.right - r0.right < 3); + } + + // See if "".split is the broken IE version, if so, provide an + // alternative way to split lines. + var splitLines = CodeMirror.splitLines = "\n\nb".split(/\n/).length != 3 ? function (string) { + var pos = 0, result = [], l = string.length; + while (pos <= l) { + var nl = string.indexOf("\n", pos); + if (nl == -1) nl = string.length; + var line = string.slice(pos, string.charAt(nl - 1) == "\r" ? nl - 1 : nl); + var rt = line.indexOf("\r"); + if (rt != -1) { + result.push(line.slice(0, rt)); + pos += rt + 1; + } else { + result.push(line); + pos = nl + 1; + } + } + return result; + } : function (string) {return string.split(/\r\n?|\n/);}; + + var hasSelection = window.getSelection ? function (te) { + try { return te.selectionStart != te.selectionEnd; } catch(e) { return false; } + } : function (te) { + try {var range = te.ownerDocument.selection.createRange();} catch(e) {} + if (!range || range.parentElement() != te) return false; + return range.compareEndPoints("StartToEnd", range) != 0; + }; + + var hasCopyEvent = (function () { + var e = elt("div"); + if ("oncopy" in e) return true; + e.setAttribute("oncopy", "return;"); + return typeof e.oncopy === "function"; + })(); + + var badZoomedRects = null; + function hasBadZoomedRects (measure) { + if (badZoomedRects != null) return badZoomedRects; + var node = removeChildrenAndAdd(measure, elt("span", "x")); + var normal = node.getBoundingClientRect(); + var fromRange = range(node, 0, 1).getBoundingClientRect(); + return badZoomedRects = Math.abs(normal.left - fromRange.left) > 1; + } + + // KEY NAMES + + var keyNames = {3: "Enter", 8: "Backspace", 9: "Tab", 13: "Enter", 16: "Shift", 17: "Ctrl", 18: "Alt", + 19: "Pause", 20: "CapsLock", 27: "Esc", 32: "Space", 33: "PageUp", 34: "PageDown", 35: "End", + 36: "Home", 37: "Left", 38: "Up", 39: "Right", 40: "Down", 44: "PrintScrn", 45: "Insert", + 46: "Delete", 59: ";", 61: "=", 91: "Mod", 92: "Mod", 93: "Mod", 107: "=", 109: "-", 127: "Delete", + 173: "-", 186: ";", 187: "=", 188: ",", 189: "-", 190: ".", 191: "/", 192: "`", 219: "[", 220: "\\", + 221: "]", 222: "'", 63232: "Up", 63233: "Down", 63234: "Left", 63235: "Right", 63272: "Delete", + 63273: "Home", 63275: "End", 63276: "PageUp", 63277: "PageDown", 63302: "Insert"}; + CodeMirror.keyNames = keyNames; + (function () { // Number keys - for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); - // Alphabetic keys - for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); - // Function keys - for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; - })(); - - // BIDI HELPERS - - function iterateBidiSections(order, from, to, f) { - if (!order) return f(from, to, "ltr"); - var found = false; - for (var i = 0; i < order.length; ++i) { - var part = order[i]; - if (part.from < to && part.to > from || from == to && part.to == from) { - f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); - found = true; - } - } - if (!found) f(from, to, "ltr"); - } - - function bidiLeft(part) { return part.level % 2 ? part.to : part.from; } - function bidiRight(part) { return part.level % 2 ? part.from : part.to; } - - function lineLeft(line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } - function lineRight(line) { - var order = getOrder(line); - if (!order) return line.text.length; - return bidiRight(lst(order)); - } - - function lineStart(cm, lineN) { - var line = getLine(cm.doc, lineN); - var visual = visualLine(line); - if (visual != line) lineN = lineNo(visual); - var order = getOrder(visual); - var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); - return Pos(lineN, ch); - } - function lineEnd(cm, lineN) { - var merged, line = getLine(cm.doc, lineN); - while (merged = collapsedSpanAtEnd(line)) { - line = merged.find(1, true).line; - lineN = null; - } - var order = getOrder(line); - var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); - return Pos(lineN == null ? lineNo(line) : lineN, ch); - } - function lineStartSmart(cm, pos) { - var start = lineStart(cm, pos.line); - var line = getLine(cm.doc, start.line); - var order = getOrder(line); - if (!order || order[0].level == 0) { - var firstNonWS = Math.max(0, line.text.search(/\S/)); - var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; - return Pos(start.line, inWS ? 0 : firstNonWS); - } - return start; - } - - function compareBidiLevel(order, a, b) { - var linedir = order[0].level; - if (a == linedir) return true; - if (b == linedir) return false; - return a < b; - } - var bidiOther; - function getBidiPartAt(order, pos) { - bidiOther = null; - for (var i = 0, found; i < order.length; ++i) { - var cur = order[i]; - if (cur.from < pos && cur.to > pos) return i; - if ((cur.from == pos || cur.to == pos)) { - if (found == null) { - found = i; - } else if (compareBidiLevel(order, cur.level, order[found].level)) { - if (cur.from != cur.to) bidiOther = found; - return i; - } else { - if (cur.from != cur.to) bidiOther = i; - return found; - } - } - } - return found; - } - - function moveInLine(line, pos, dir, byUnit) { - if (!byUnit) return pos + dir; - do pos += dir; - while (pos > 0 && isExtendingChar(line.text.charAt(pos))); - return pos; - } - - // This is needed in order to move 'visually' through bi-directional - // text -- i.e., pressing left should make the cursor go left, even - // when in RTL text. The tricky part is the 'jumps', where RTL and - // LTR text touch each other. This often requires the cursor offset - // to move more than one unit, in order to visually move one unit. - function moveVisually(line, start, dir, byUnit) { - var bidi = getOrder(line); - if (!bidi) return moveLogically(line, start, dir, byUnit); - var pos = getBidiPartAt(bidi, start), part = bidi[pos]; - var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); - - for (;;) { - if (target > part.from && target < part.to) return target; - if (target == part.from || target == part.to) { - if (getBidiPartAt(bidi, target) == pos) return target; - part = bidi[pos += dir]; - return (dir > 0) == part.level % 2 ? part.to : part.from; - } else { - part = bidi[pos += dir]; - if (!part) return null; - if ((dir > 0) == part.level % 2) - target = moveInLine(line, part.to, -1, byUnit); - else - target = moveInLine(line, part.from, 1, byUnit); - } - } - } - - function moveLogically(line, start, dir, byUnit) { - var target = start + dir; - if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; - return target < 0 || target > line.text.length ? null : target; - } - - // Bidirectional ordering algorithm - // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm - // that this (partially) implements. - - // One-char codes used for character types: - // L (L): Left-to-Right - // R (R): Right-to-Left - // r (AL): Right-to-Left Arabic - // 1 (EN): European Number - // + (ES): European Number Separator - // % (ET): European Number Terminator - // n (AN): Arabic Number - // , (CS): Common Number Separator - // m (NSM): Non-Spacing Mark - // b (BN): Boundary Neutral - // s (B): Paragraph Separator - // t (S): Segment Separator - // w (WS): Whitespace - // N (ON): Other Neutrals - - // Returns null if characters are ordered as they appear - // (left-to-right), or an array of sections ({from, to, level} - // objects) in the order in which they occur visually. - var bidiOrdering = (function() { + for (var i = 0; i < 10; i++) keyNames[i + 48] = keyNames[i + 96] = String(i); + // Alphabetic keys + for (var i = 65; i <= 90; i++) keyNames[i] = String.fromCharCode(i); + // Function keys + for (var i = 1; i <= 12; i++) keyNames[i + 111] = keyNames[i + 63235] = "F" + i; + })(); + + // BIDI HELPERS + + function iterateBidiSections (order, from, to, f) { + if (!order) return f(from, to, "ltr"); + var found = false; + for (var i = 0; i < order.length; ++i) { + var part = order[i]; + if (part.from < to && part.to > from || from == to && part.to == from) { + f(Math.max(part.from, from), Math.min(part.to, to), part.level == 1 ? "rtl" : "ltr"); + found = true; + } + } + if (!found) f(from, to, "ltr"); + } + + function bidiLeft (part) { return part.level % 2 ? part.to : part.from; } + function bidiRight (part) { return part.level % 2 ? part.from : part.to; } + + function lineLeft (line) { var order = getOrder(line); return order ? bidiLeft(order[0]) : 0; } + function lineRight (line) { + var order = getOrder(line); + if (!order) return line.text.length; + return bidiRight(lst(order)); + } + + function lineStart (cm, lineN) { + var line = getLine(cm.doc, lineN); + var visual = visualLine(line); + if (visual != line) lineN = lineNo(visual); + var order = getOrder(visual); + var ch = !order ? 0 : order[0].level % 2 ? lineRight(visual) : lineLeft(visual); + return Pos(lineN, ch); + } + function lineEnd (cm, lineN) { + var merged, line = getLine(cm.doc, lineN); + while (merged = collapsedSpanAtEnd(line)) { + line = merged.find(1, true).line; + lineN = null; + } + var order = getOrder(line); + var ch = !order ? line.text.length : order[0].level % 2 ? lineLeft(line) : lineRight(line); + return Pos(lineN == null ? lineNo(line) : lineN, ch); + } + function lineStartSmart (cm, pos) { + var start = lineStart(cm, pos.line); + var line = getLine(cm.doc, start.line); + var order = getOrder(line); + if (!order || order[0].level == 0) { + var firstNonWS = Math.max(0, line.text.search(/\S/)); + var inWS = pos.line == start.line && pos.ch <= firstNonWS && pos.ch; + return Pos(start.line, inWS ? 0 : firstNonWS); + } + return start; + } + + function compareBidiLevel (order, a, b) { + var linedir = order[0].level; + if (a == linedir) return true; + if (b == linedir) return false; + return a < b; + } + var bidiOther; + function getBidiPartAt (order, pos) { + bidiOther = null; + for (var i = 0, found; i < order.length; ++i) { + var cur = order[i]; + if (cur.from < pos && cur.to > pos) return i; + if ((cur.from == pos || cur.to == pos)) { + if (found == null) { + found = i; + } else if (compareBidiLevel(order, cur.level, order[found].level)) { + if (cur.from != cur.to) bidiOther = found; + return i; + } else { + if (cur.from != cur.to) bidiOther = i; + return found; + } + } + } + return found; + } + + function moveInLine (line, pos, dir, byUnit) { + if (!byUnit) return pos + dir; + do pos += dir; + while (pos > 0 && isExtendingChar(line.text.charAt(pos))); + return pos; + } + + // This is needed in order to move 'visually' through bi-directional + // text -- i.e., pressing left should make the cursor go left, even + // when in RTL text. The tricky part is the 'jumps', where RTL and + // LTR text touch each other. This often requires the cursor offset + // to move more than one unit, in order to visually move one unit. + function moveVisually (line, start, dir, byUnit) { + var bidi = getOrder(line); + if (!bidi) return moveLogically(line, start, dir, byUnit); + var pos = getBidiPartAt(bidi, start), part = bidi[pos]; + var target = moveInLine(line, start, part.level % 2 ? -dir : dir, byUnit); + + for (;;) { + if (target > part.from && target < part.to) return target; + if (target == part.from || target == part.to) { + if (getBidiPartAt(bidi, target) == pos) return target; + part = bidi[pos += dir]; + return (dir > 0) == part.level % 2 ? part.to : part.from; + } + part = bidi[pos += dir]; + if (!part) return null; + if ((dir > 0) == part.level % 2) {target = moveInLine(line, part.to, -1, byUnit);} else {target = moveInLine(line, part.from, 1, byUnit);} + + } + } + + function moveLogically (line, start, dir, byUnit) { + var target = start + dir; + if (byUnit) while (target > 0 && isExtendingChar(line.text.charAt(target))) target += dir; + return target < 0 || target > line.text.length ? null : target; + } + + // Bidirectional ordering algorithm + // See http://unicode.org/reports/tr9/tr9-13.html for the algorithm + // that this (partially) implements. + + // One-char codes used for character types: + // L (L): Left-to-Right + // R (R): Right-to-Left + // r (AL): Right-to-Left Arabic + // 1 (EN): European Number + // + (ES): European Number Separator + // % (ET): European Number Terminator + // n (AN): Arabic Number + // , (CS): Common Number Separator + // m (NSM): Non-Spacing Mark + // b (BN): Boundary Neutral + // s (B): Paragraph Separator + // t (S): Segment Separator + // w (WS): Whitespace + // N (ON): Other Neutrals + + // Returns null if characters are ordered as they appear + // (left-to-right), or an array of sections ({from, to, level} + // objects) in the order in which they occur visually. + var bidiOrdering = (function () { // Character types for codepoints 0 to 0xff - var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; - // Character types for codepoints 0x600 to 0x6ff - var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; - function charType(code) { - if (code <= 0xf7) return lowTypes.charAt(code); - else if (0x590 <= code && code <= 0x5f4) return "R"; - else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); - else if (0x6ee <= code && code <= 0x8ac) return "r"; - else if (0x2000 <= code && code <= 0x200b) return "w"; - else if (code == 0x200c) return "b"; - else return "L"; - } - - var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; - var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; - // Browsers seem to always treat the boundaries of block elements as being L. - var outerType = "L"; - - function BidiSpan(level, from, to) { - this.level = level; - this.from = from; this.to = to; - } - - return function(str) { - if (!bidiRE.test(str)) return false; - var len = str.length, types = []; - for (var i = 0, type; i < len; ++i) - types.push(type = charType(str.charCodeAt(i))); - - // W1. Examine each non-spacing mark (NSM) in the level run, and - // change the type of the NSM to the type of the previous - // character. If the NSM is at the start of the level run, it will - // get the type of sor. - for (var i = 0, prev = outerType; i < len; ++i) { - var type = types[i]; - if (type == "m") types[i] = prev; - else prev = type; - } - - // W2. Search backwards from each instance of a European number - // until the first strong type (R, L, AL, or sor) is found. If an - // AL is found, change the type of the European number to Arabic - // number. - // W3. Change all ALs to R. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (type == "1" && cur == "r") types[i] = "n"; - else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } - } - - // W4. A single European separator between two European numbers - // changes to a European number. A single common separator between - // two numbers of the same type changes to that type. - for (var i = 1, prev = types[0]; i < len - 1; ++i) { - var type = types[i]; - if (type == "+" && prev == "1" && types[i+1] == "1") types[i] = "1"; - else if (type == "," && prev == types[i+1] && + var lowTypes = "bbbbbbbbbtstwsbbbbbbbbbbbbbbssstwNN%%%NNNNNN,N,N1111111111NNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNNNLLLLLLLLLLLLLLLLLLLLLLLLLLNNNNbbbbbbsbbbbbbbbbbbbbbbbbbbbbbbbbb,N%%%%NNNNLNNNNN%%11NLNNN1LNNNNNLLLLLLLLLLLLLLLLLLLLLLLNLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLLN"; + // Character types for codepoints 0x600 to 0x6ff + var arabicTypes = "rrrrrrrrrrrr,rNNmmmmmmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmrrrrrrrnnnnnnnnnn%nnrrrmrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrrmmmmmmmmmmmmmmmmmmmNmmmm"; + function charType (code) { + if (code <= 0xf7) return lowTypes.charAt(code); + else if (0x590 <= code && code <= 0x5f4) return "R"; + else if (0x600 <= code && code <= 0x6ed) return arabicTypes.charAt(code - 0x600); + else if (0x6ee <= code && code <= 0x8ac) return "r"; + else if (0x2000 <= code && code <= 0x200b) return "w"; + else if (code == 0x200c) return "b"; + return "L"; + } + + var bidiRE = /[\u0590-\u05f4\u0600-\u06ff\u0700-\u08ac]/; + var isNeutral = /[stwN]/, isStrong = /[LRr]/, countsAsLeft = /[Lb1n]/, countsAsNum = /[1n]/; + // Browsers seem to always treat the boundaries of block elements as being L. + var outerType = "L"; + + function BidiSpan (level, from, to) { + this.level = level; + this.from = from; this.to = to; + } + + return function (str) { + if (!bidiRE.test(str)) return false; + var len = str.length, types = []; + for (var i = 0, type; i < len; ++i) {types.push(type = charType(str.charCodeAt(i)));} + + // W1. Examine each non-spacing mark (NSM) in the level run, and + // change the type of the NSM to the type of the previous + // character. If the NSM is at the start of the level run, it will + // get the type of sor. + for (var i = 0, prev = outerType; i < len; ++i) { + var type = types[i]; + if (type == "m") types[i] = prev; + else prev = type; + } + + // W2. Search backwards from each instance of a European number + // until the first strong type (R, L, AL, or sor) is found. If an + // AL is found, change the type of the European number to Arabic + // number. + // W3. Change all ALs to R. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (type == "1" && cur == "r") types[i] = "n"; + else if (isStrong.test(type)) { cur = type; if (type == "r") types[i] = "R"; } + } + + // W4. A single European separator between two European numbers + // changes to a European number. A single common separator between + // two numbers of the same type changes to that type. + for (var i = 1, prev = types[0]; i < len - 1; ++i) { + var type = types[i]; + if (type == "+" && prev == "1" && types[i + 1] == "1") types[i] = "1"; + else if (type == "," && prev == types[i + 1] && (prev == "1" || prev == "n")) types[i] = prev; - prev = type; - } - - // W5. A sequence of European terminators adjacent to European - // numbers changes to all European numbers. - // W6. Otherwise, separators and terminators change to Other - // Neutral. - for (var i = 0; i < len; ++i) { - var type = types[i]; - if (type == ",") types[i] = "N"; - else if (type == "%") { - for (var end = i + 1; end < len && types[end] == "%"; ++end) {} - var replace = (i && types[i-1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // W7. Search backwards from each instance of a European number - // until the first strong type (R, L, or sor) is found. If an L is - // found, then change the type of the European number to L. - for (var i = 0, cur = outerType; i < len; ++i) { - var type = types[i]; - if (cur == "L" && type == "1") types[i] = "L"; - else if (isStrong.test(type)) cur = type; - } - - // N1. A sequence of neutrals takes the direction of the - // surrounding strong text if the text on both sides has the same - // direction. European and Arabic numbers act as if they were R in - // terms of their influence on neutrals. Start-of-level-run (sor) - // and end-of-level-run (eor) are used at level run boundaries. - // N2. Any remaining neutrals take the embedding direction. - for (var i = 0; i < len; ++i) { - if (isNeutral.test(types[i])) { - for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} - var before = (i ? types[i-1] : outerType) == "L"; - var after = (end < len ? types[end] : outerType) == "L"; - var replace = before || after ? "L" : "R"; - for (var j = i; j < end; ++j) types[j] = replace; - i = end - 1; - } - } - - // Here we depart from the documented algorithm, in order to avoid - // building up an actual levels array. Since there are only three - // levels (0, 1, 2) in an implementation that doesn't take - // explicit embedding into account, we can build up the order on - // the fly, without following the level-based algorithm. - var order = [], m; - for (var i = 0; i < len;) { - if (countsAsLeft.test(types[i])) { - var start = i; - for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} - order.push(new BidiSpan(0, start, i)); - } else { - var pos = i, at = order.length; - for (++i; i < len && types[i] != "L"; ++i) {} - for (var j = pos; j < i;) { - if (countsAsNum.test(types[j])) { - if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); - var nstart = j; - for (++j; j < i && countsAsNum.test(types[j]); ++j) {} - order.splice(at, 0, new BidiSpan(2, nstart, j)); - pos = j; - } else ++j; - } - if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); - } - } - if (order[0].level == 1 && (m = str.match(/^\s+/))) { - order[0].from = m[0].length; - order.unshift(new BidiSpan(0, 0, m[0].length)); - } - if (lst(order).level == 1 && (m = str.match(/\s+$/))) { - lst(order).to -= m[0].length; - order.push(new BidiSpan(0, len - m[0].length, len)); - } - if (order[0].level == 2) - order.unshift(new BidiSpan(1, order[0].to, order[0].to)); - if (order[0].level != lst(order).level) - order.push(new BidiSpan(order[0].level, len, len)); - - return order; - }; - })(); + prev = type; + } + + // W5. A sequence of European terminators adjacent to European + // numbers changes to all European numbers. + // W6. Otherwise, separators and terminators change to Other + // Neutral. + for (var i = 0; i < len; ++i) { + var type = types[i]; + if (type == ",") types[i] = "N"; + else if (type == "%") { + for (var end = i + 1; end < len && types[end] == "%"; ++end) {} + var replace = (i && types[i - 1] == "!") || (end < len && types[end] == "1") ? "1" : "N"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // W7. Search backwards from each instance of a European number + // until the first strong type (R, L, or sor) is found. If an L is + // found, then change the type of the European number to L. + for (var i = 0, cur = outerType; i < len; ++i) { + var type = types[i]; + if (cur == "L" && type == "1") types[i] = "L"; + else if (isStrong.test(type)) cur = type; + } + + // N1. A sequence of neutrals takes the direction of the + // surrounding strong text if the text on both sides has the same + // direction. European and Arabic numbers act as if they were R in + // terms of their influence on neutrals. Start-of-level-run (sor) + // and end-of-level-run (eor) are used at level run boundaries. + // N2. Any remaining neutrals take the embedding direction. + for (var i = 0; i < len; ++i) { + if (isNeutral.test(types[i])) { + for (var end = i + 1; end < len && isNeutral.test(types[end]); ++end) {} + var before = (i ? types[i - 1] : outerType) == "L"; + var after = (end < len ? types[end] : outerType) == "L"; + var replace = before || after ? "L" : "R"; + for (var j = i; j < end; ++j) types[j] = replace; + i = end - 1; + } + } + + // Here we depart from the documented algorithm, in order to avoid + // building up an actual levels array. Since there are only three + // levels (0, 1, 2) in an implementation that doesn't take + // explicit embedding into account, we can build up the order on + // the fly, without following the level-based algorithm. + var order = [], m; + for (var i = 0; i < len;) { + if (countsAsLeft.test(types[i])) { + var start = i; + for (++i; i < len && countsAsLeft.test(types[i]); ++i) {} + order.push(new BidiSpan(0, start, i)); + } else { + var pos = i, at = order.length; + for (++i; i < len && types[i] != "L"; ++i) {} + for (var j = pos; j < i;) { + if (countsAsNum.test(types[j])) { + if (pos < j) order.splice(at, 0, new BidiSpan(1, pos, j)); + var nstart = j; + for (++j; j < i && countsAsNum.test(types[j]); ++j) {} + order.splice(at, 0, new BidiSpan(2, nstart, j)); + pos = j; + } else ++j; + } + if (pos < i) order.splice(at, 0, new BidiSpan(1, pos, i)); + } + } + if (order[0].level == 1 && (m = str.match(/^\s+/))) { + order[0].from = m[0].length; + order.unshift(new BidiSpan(0, 0, m[0].length)); + } + if (lst(order).level == 1 && (m = str.match(/\s+$/))) { + lst(order).to -= m[0].length; + order.push(new BidiSpan(0, len - m[0].length, len)); + } + if (order[0].level == 2) {order.unshift(new BidiSpan(1, order[0].to, order[0].to));} + if (order[0].level != lst(order).level) {order.push(new BidiSpan(order[0].level, len, len));} + + return order; + }; + })(); - // THE END + // THE END - CodeMirror.version = "5.4.1"; + CodeMirror.version = "5.4.1"; - return CodeMirror; + return CodeMirror; }); \ No newline at end of file diff --git a/src/base/formula/codemirror/formula-hint.js b/src/base/formula/codemirror/formula-hint.js index a83d58323..e18a0c8d1 100644 --- a/src/base/formula/codemirror/formula-hint.js +++ b/src/base/formula/codemirror/formula-hint.js @@ -3,11 +3,11 @@ })(function (CodeMirror) { var Pos = CodeMirror.Pos; - function forEach(arr, f) { + function forEach (arr, f) { for (var i = 0, e = arr.length; i < e; ++i) f(arr[i]); } - function arrayContains(arr, item) { + function arrayContains (arr, item) { if (!Array.prototype.indexOf) { var i = arr.length; while (i--) { @@ -20,7 +20,7 @@ return arr.indexOf(item) != -1; } - function scriptHint(editor, keywords, getToken, options) { + function scriptHint (editor, keywords, getToken, options) { // Find the token at the cursor var cur = editor.getCursor(), token = getToken(editor, cur); if (/\b(?:string)\b/.test(token.type)) { @@ -54,25 +54,25 @@ }; } - function getFormulaKeywords() { + function getFormulaKeywords () { return BI.FormulaCollections; } - function formulaHint(editor, options) { + function formulaHint (editor, options) { return scriptHint(editor, getFormulaKeywords(), function (e, cur) { return e.getTokenAt(cur); }, options); - }; + } CodeMirror.registerHelper("hint", "formula", formulaHint); - function getCompletions(token, context, keywords, options) { + function getCompletions (token, context, keywords, options) { var found = [], start = token.string; if (!start) { return found; } - function maybeAdd(str) { + function maybeAdd (str) { if (str.lastIndexOf(start, 0) == 0 && !arrayContains(found, str)) { found.push(str); } diff --git a/src/base/formula/codemirror/formula-mode.js b/src/base/formula/codemirror/formula-mode.js index 1f017806a..2a10c2b72 100644 --- a/src/base/formula/codemirror/formula-mode.js +++ b/src/base/formula/codemirror/formula-mode.js @@ -3,44 +3,44 @@ })(function (CodeMirror) { "use strict"; - CodeMirror.defineMode('formula', function () { - function wordObj(words) { + CodeMirror.defineMode("formula", function () { + function wordObj (words) { var o = {}; for (var i = 0, e = words.length; i < e; ++i) o[words[i]] = true; return o; } - var atoms = wordObj(['false', 'true']); + var atoms = wordObj(["false", "true"]); var keywords = wordObj(BI.FormulaCollections); - function tokenBase(stream, state) { + function tokenBase (stream, state) { if (stream.eatSpace()) { return null; } var ch = stream.next(); - if (ch === '"' || ch === '\'') { + if (ch === "\"" || ch === "'") { nextUntilUnescaped(stream, ch); return "string"; } - if (ch === '\u200b') { + if (ch === "\u200b") { nextUntilUnescaped(stream, ch); return "field"; } if (/[\[\],\(\)]/.test(ch)) { - return 'bracket'; + return "bracket"; } // richie:暂时不需要解析操作符号 - //if (/[+\-*\/=<>!&|]/.test(ch)) { + // if (/[+\-*\/=<>!&|]/.test(ch)) { // return 'operator'; - //} - //if (/\d|\d./.test(ch)) { + // } + // if (/\d|\d./.test(ch)) { // stream.eatWhile(/\d|\./); // if (stream.eol() || !/\w/.test(stream.peek())) { // return 'number'; // } - //} + // } @@ -55,7 +55,7 @@ return null; } - function nextUntilUnescaped(stream, end) { + function nextUntilUnescaped (stream, end) { var escaped = false, next; while ((next = stream.next()) != null) { if (next === end && !escaped) { @@ -66,7 +66,7 @@ return escaped; } - function tokenize(stream, state) { + function tokenize (stream, state) { return (state.tokens[0] || tokenBase)(stream, state); } diff --git a/src/base/formula/codemirror/show-hint.js b/src/base/formula/codemirror/show-hint.js index 1605e03d0..a1c25e7dc 100644 --- a/src/base/formula/codemirror/show-hint.js +++ b/src/base/formula/codemirror/show-hint.js @@ -31,7 +31,7 @@ completion.update(true); }); - function Completion(cm, options) { + function Completion (cm, options) { this.cm = cm; this.options = this.buildOptions(options); this.widget = null; @@ -47,8 +47,8 @@ } var requestAnimationFrame = window.requestAnimationFrame || function (fn) { - return setTimeout(fn, 1000 / 60); - }; + return setTimeout(fn, 1000 / 60); + }; var cancelAnimationFrame = window.cancelAnimationFrame || clearTimeout; Completion.prototype = { @@ -73,16 +73,16 @@ else { this.cm.replaceRange(getText(completion), completion.from || data.from, completion.to || data.to, "complete"); - if(completion.isKeyword === true){ - }else{ - var to = this.cm.getCursor(); - this.cm.markText(completion.from || data.from, to, {className: "#function", atomic: true}); - this.cm.replaceSelection("() "); - to = this.cm.getCursor(); - to.ch = to.ch - 2; - this.cm.setCursor(to); - this.cm.focus(); - } + if(completion.isKeyword === true) { + }else{ + var to = this.cm.getCursor(); + this.cm.markText(completion.from || data.from, to, {className: "#function", atomic: true}); + this.cm.replaceSelection("() "); + to = this.cm.getCursor(); + to.ch = to.ch - 2; + this.cm.setCursor(to); + this.cm.focus(); + } } CodeMirror.signal(data, "pick", completion); this.close(); @@ -140,20 +140,22 @@ var editor = this.cm.options.hintOptions; var out = {}; for (var prop in defaultOptions) out[prop] = defaultOptions[prop]; - if (editor) for (var prop in editor) - if (editor[prop] !== undefined) out[prop] = editor[prop]; - if (options) for (var prop in options) - if (options[prop] !== undefined) out[prop] = options[prop]; + if (editor) { + for (var prop in editor) {if (editor[prop] !== undefined) out[prop] = editor[prop];} + } + if (options) { + for (var prop in options) {if (options[prop] !== undefined) out[prop] = options[prop];} + } return out; } }; - function getText(completion) { - if (typeof completion == "string") return completion; - else return completion.text; + function getText (completion) { + if (typeof completion === "string") return completion; + return completion.text; } - function buildKeyMap(completion, handle) { + function buildKeyMap (completion, handle) { var baseMap = { Up: function () { handle.moveFocus(-1); @@ -180,38 +182,40 @@ var custom = completion.options.customKeys; var ourMap = custom ? {} : baseMap; - function addBinding(key, val) { + function addBinding (key, val) { var bound; - if (typeof val != "string") + if (typeof val !== "string") { bound = function (cm) { return val(cm, handle); }; + } // This mechanism is deprecated - else if (baseMap.hasOwnProperty(val)) - bound = baseMap[val]; - else - bound = val; + else if (baseMap.hasOwnProperty(val)) {bound = baseMap[val];} else {bound = val;} ourMap[key] = bound; } - if (custom) - for (var key in custom) if (custom.hasOwnProperty(key)) - addBinding(key, custom[key]); + if (custom) { + for (var key in custom) { + if (custom.hasOwnProperty(key)) {addBinding(key, custom[key]);} + } + } var extra = completion.options.extraKeys; - if (extra) - for (var key in extra) if (extra.hasOwnProperty(key)) - addBinding(key, extra[key]); + if (extra) { + for (var key in extra) { + if (extra.hasOwnProperty(key)) {addBinding(key, extra[key]);} + } + } return ourMap; } - function getHintElement(hintsElement, el) { + function getHintElement (hintsElement, el) { while (el && el != hintsElement) { if (el.nodeName.toUpperCase() === "LI" && el.parentNode == hintsElement) return el; el = el.parentNode; } } - function Widget(completion, data) { + function Widget (completion, data) { this.completion = completion; this.data = data; this.picked = false; @@ -366,19 +370,13 @@ }, changeActive: function (i, avoidWrap) { - if (i >= this.data.list.length) - i = avoidWrap ? this.data.list.length - 1 : 0; - else if (i < 0) - i = avoidWrap ? 0 : this.data.list.length - 1; + if (i >= this.data.list.length) {i = avoidWrap ? this.data.list.length - 1 : 0;} else if (i < 0) {i = avoidWrap ? 0 : this.data.list.length - 1;} if (this.selectedHint == i) return; var node = this.hints.childNodes[this.selectedHint]; node.className = node.className.replace(" " + ACTIVE_HINT_ELEMENT_CLASS, ""); node = this.hints.childNodes[this.selectedHint = i]; node.className += " " + ACTIVE_HINT_ELEMENT_CLASS; - if (node.offsetTop < this.hints.scrollTop) - this.hints.scrollTop = node.offsetTop - 3; - else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) - this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3; + if (node.offsetTop < this.hints.scrollTop) {this.hints.scrollTop = node.offsetTop - 3;} else if (node.offsetTop + node.offsetHeight > this.hints.scrollTop + this.hints.clientHeight) {this.hints.scrollTop = node.offsetTop + node.offsetHeight - this.hints.clientHeight + 3;} CodeMirror.signal(this.data, "select", this.data.list[this.selectedHint], node); }, @@ -406,15 +404,16 @@ var found = []; for (var i = 0; i < options.words.length; i++) { var word = options.words[i]; - if (word.slice(0, token.string.length) == token.string) - found.push(word); + if (word.slice(0, token.string.length) == token.string) {found.push(word);} } - if (found.length) return { - list: found, - from: CodeMirror.Pos(cur.line, token.start), - to: CodeMirror.Pos(cur.line, token.end) - }; + if (found.length) { + return { + list: found, + from: CodeMirror.Pos(cur.line, token.start), + to: CodeMirror.Pos(cur.line, token.end) + }; + } }); CodeMirror.commands.autocomplete = CodeMirror.showHint; diff --git a/src/base/formula/config.js b/src/base/formula/config.js index 400ef5b0d..997c5b419 100644 --- a/src/base/formula/config.js +++ b/src/base/formula/config.js @@ -1,6 +1,6 @@ /** * Created by User on 2017/3/21. */ -BI.FormulaCollections = ["abs","ABS","acos","ACOS","acosh","ACOSH","add2array","ADD2ARRAY","and","AND","array","ARRAY","asin","ASIN","asinh","ASINH","atan","ATAN","atan2","ATAN2","atanh","ATANH","average","AVERAGE","bitnot","BITNOT","bitoperation","BITOPERATION","ceiling","CEILING","char","CHAR","circular","CIRCULAR","class","CLASS","cnmoney","CNMONEY","code","CODE","col","COL","colcount","COLCOUNT","colname","COLNAME","combin","COMBIN","concatenate","CONCATENATE","correl","CORREL","cos","COS","cosh","COSH","count","COUNT","crosslayertotal","CROSSLAYERTOTAL","date","DATE","datedelta","DATEDELTA","datedif","DATEDIF","dateinmonth","DATEINMONTH","dateinquarter","DATEINQUARTER","dateinweek","DATEINWEEK","dateinyear","DATEINYEAR","datesubdate","DATESUBDATE","datetime","DATETIME","datetonumber","DATETONUMBER","day","DAY","days360","DAYS360","daysofmonth","DAYSOFMONTH","daysofquarter","DAYSOFQUARTER","daysofyear","DAYSOFYEAR","dayvalue","DAYVALUE","decimal","DECIMAL","decode","DECODE","degrees","DEGREES","encode","ENCODE","endwith","ENDWITH","enmoney","ENMONEY","ennumber","ENNUMBER","eval","EVAL","even","EVEN","exact","EXACT","exp","EXP","fact","FACT","fields","FIELDS","filename","FILENAME","filesize","FILESIZE","filetype","FILETYPE","find","FIND","floor","FLOOR","format","FORMAT","getuserdepartments","GETUSERDEPARTMENTS","getuserjobtitles","GETUSERJOBTITLES","greparray","GREPARRAY","hierarchy","HIERARCHY","hour","HOUR","i18n","I18N","if","IF","inarray","INARRAY","index","INDEX","indexof","INDEXOF","indexofarray","INDEXOFARRAY","int","INT","isnull","ISNULL","joinarray","JOINARRAY","jvm","JVM","layertotal","LAYERTOTAL","left","LEFT","len","LEN","let","LET","ln","LN","log","LOG","log10","LOG10","lower","LOWER","lunar","LUNAR","map","MAP","maparray","MAPARRAY","max","MAX","median","MEDIAN","mid","MID","min","MIN","minute","MINUTE","mod","MOD","mom","MOM","month","MONTH","monthdelta","MONTHDELTA","now","NOW","numto","NUMTO","nvl","NVL","odd","ODD","or","OR","pi","PI","power","POWER","product","PRODUCT","promotion","PROMOTION","proper","PROPER","proportion","PROPORTION","radians","RADIANS","rand","RAND","randbetween","RANDBETWEEN","range","RANGE","rank","RANK","records","RECORDS","regexp","REGEXP","removearray","REMOVEARRAY","repeat","REPEAT","replace","REPLACE","reverse","REVERSE","reversearray","REVERSEARRAY","right","RIGHT","round","ROUND","round5","ROUND5","rounddown","ROUNDDOWN","roundup","ROUNDUP","row","ROW","rowcount","ROWCOUNT","second","SECOND","seq","SEQ","sign","SIGN","sin","SIN","sinh","SINH","slicearray","SLICEARRAY","sort","SORT","sortarray","SORTARRAY","split","SPLIT","sql","SQL","sqrt","SQRT","startwith","STARTWITH","stdev","STDEV","substitute","SUBSTITUTE","sum","SUM","sumsq","SUMSQ","switch","SWITCH","tabledatafields","TABLEDATAFIELDS","tabledatas","TABLEDATAS","tables","TABLES","tan","TAN","tanh","TANH","time","TIME","tobigdecimal","TOBIGDECIMAL","tobinary","TOBINARY","todate","TODATE","today","TODAY","todouble","TODOUBLE","tohex","TOHEX","toimage","TOIMAGE","tointeger","TOINTEGER","tooctal","TOOCTAL","totext","TOTEXT","treelayer","TREELAYER","trim","TRIM","trunc","TRUNC","uniquearray","UNIQUEARRAY","upper","UPPER","uuid","UUID","value","VALUE","webimage","WEBIMAGE","week","WEEK","weekdate","WEEKDATE","weekday","WEEKDAY","weightedaverage","WEIGHTEDAVERAGE","year","YEAR","yeardelta","YEARDELTA"]; +BI.FormulaCollections = ["abs", "ABS", "acos", "ACOS", "acosh", "ACOSH", "add2array", "ADD2ARRAY", "and", "AND", "array", "ARRAY", "asin", "ASIN", "asinh", "ASINH", "atan", "ATAN", "atan2", "ATAN2", "atanh", "ATANH", "average", "AVERAGE", "bitnot", "BITNOT", "bitoperation", "BITOPERATION", "ceiling", "CEILING", "char", "CHAR", "circular", "CIRCULAR", "class", "CLASS", "cnmoney", "CNMONEY", "code", "CODE", "col", "COL", "colcount", "COLCOUNT", "colname", "COLNAME", "combin", "COMBIN", "concatenate", "CONCATENATE", "correl", "CORREL", "cos", "COS", "cosh", "COSH", "count", "COUNT", "crosslayertotal", "CROSSLAYERTOTAL", "date", "DATE", "datedelta", "DATEDELTA", "datedif", "DATEDIF", "dateinmonth", "DATEINMONTH", "dateinquarter", "DATEINQUARTER", "dateinweek", "DATEINWEEK", "dateinyear", "DATEINYEAR", "datesubdate", "DATESUBDATE", "datetime", "DATETIME", "datetonumber", "DATETONUMBER", "day", "DAY", "days360", "DAYS360", "daysofmonth", "DAYSOFMONTH", "daysofquarter", "DAYSOFQUARTER", "daysofyear", "DAYSOFYEAR", "dayvalue", "DAYVALUE", "decimal", "DECIMAL", "decode", "DECODE", "degrees", "DEGREES", "encode", "ENCODE", "endwith", "ENDWITH", "enmoney", "ENMONEY", "ennumber", "ENNUMBER", "eval", "EVAL", "even", "EVEN", "exact", "EXACT", "exp", "EXP", "fact", "FACT", "fields", "FIELDS", "filename", "FILENAME", "filesize", "FILESIZE", "filetype", "FILETYPE", "find", "FIND", "floor", "FLOOR", "format", "FORMAT", "getuserdepartments", "GETUSERDEPARTMENTS", "getuserjobtitles", "GETUSERJOBTITLES", "greparray", "GREPARRAY", "hierarchy", "HIERARCHY", "hour", "HOUR", "i18n", "I18N", "if", "IF", "inarray", "INARRAY", "index", "INDEX", "indexof", "INDEXOF", "indexofarray", "INDEXOFARRAY", "int", "INT", "isnull", "ISNULL", "joinarray", "JOINARRAY", "jvm", "JVM", "layertotal", "LAYERTOTAL", "left", "LEFT", "len", "LEN", "let", "LET", "ln", "LN", "log", "LOG", "log10", "LOG10", "lower", "LOWER", "lunar", "LUNAR", "map", "MAP", "maparray", "MAPARRAY", "max", "MAX", "median", "MEDIAN", "mid", "MID", "min", "MIN", "minute", "MINUTE", "mod", "MOD", "mom", "MOM", "month", "MONTH", "monthdelta", "MONTHDELTA", "now", "NOW", "numto", "NUMTO", "nvl", "NVL", "odd", "ODD", "or", "OR", "pi", "PI", "power", "POWER", "product", "PRODUCT", "promotion", "PROMOTION", "proper", "PROPER", "proportion", "PROPORTION", "radians", "RADIANS", "rand", "RAND", "randbetween", "RANDBETWEEN", "range", "RANGE", "rank", "RANK", "records", "RECORDS", "regexp", "REGEXP", "removearray", "REMOVEARRAY", "repeat", "REPEAT", "replace", "REPLACE", "reverse", "REVERSE", "reversearray", "REVERSEARRAY", "right", "RIGHT", "round", "ROUND", "round5", "ROUND5", "rounddown", "ROUNDDOWN", "roundup", "ROUNDUP", "row", "ROW", "rowcount", "ROWCOUNT", "second", "SECOND", "seq", "SEQ", "sign", "SIGN", "sin", "SIN", "sinh", "SINH", "slicearray", "SLICEARRAY", "sort", "SORT", "sortarray", "SORTARRAY", "split", "SPLIT", "sql", "SQL", "sqrt", "SQRT", "startwith", "STARTWITH", "stdev", "STDEV", "substitute", "SUBSTITUTE", "sum", "SUM", "sumsq", "SUMSQ", "switch", "SWITCH", "tabledatafields", "TABLEDATAFIELDS", "tabledatas", "TABLEDATAS", "tables", "TABLES", "tan", "TAN", "tanh", "TANH", "time", "TIME", "tobigdecimal", "TOBIGDECIMAL", "tobinary", "TOBINARY", "todate", "TODATE", "today", "TODAY", "todouble", "TODOUBLE", "tohex", "TOHEX", "toimage", "TOIMAGE", "tointeger", "TOINTEGER", "tooctal", "TOOCTAL", "totext", "TOTEXT", "treelayer", "TREELAYER", "trim", "TRIM", "trunc", "TRUNC", "uniquearray", "UNIQUEARRAY", "upper", "UPPER", "uuid", "UUID", "value", "VALUE", "webimage", "WEBIMAGE", "week", "WEEK", "weekdate", "WEEKDATE", "weekday", "WEEKDAY", "weightedaverage", "WEIGHTEDAVERAGE", "year", "YEAR", "yeardelta", "YEARDELTA"]; -BI.FormulaJson = [{"def":"MONTH:(serial_number)返回日期中的月。月是介于1和12之间的一个数。\nSerial_number:含有所求的月的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nMONTH(\"2000/1/1\")等于1。\nMONTH(\"2006/05/05\")等于5。\nMONTH(\"1997/04/20\")等于4。\nMONTH(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nMONTH(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nMONTH(\"1997-04-20\", \"yyyy-MM-dd\")等于4。\nMONTH(35796)等于1。","name":"MONTH","type":"DATETIME"},{"def":"ROWCOUNT(tableData)返回tableData的行数。\ntableData:TableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是tableData的行数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nROWCOUNT(\"ds1\")等于20。","name":"ROWCOUNT","type":"REPORT"},{"def":"RAND(): 返回均匀分布的随机数。每计算一次工作表,函数都会返回一个新的随机数值。\n备注:\n 要生成一个位于a和b之间的随机数,可以使用以下的公式: C=RAND()*(b-a)+a。\n 如果要使一个随机产生的数值不随单元格的重计算而改变,可以在编辑框中输入=RAND()并保持编辑状态,然后按F9,将公式永久性地改为随机数。\n示例:\n假如需要生成一个大于等于0,小于60的随机数,使用公式: =RAND()*60。\n假如需要生成一个大于等于0,小于19的随机数,使用公式: =RAND()*19。\n假如需要生成一个大于等于0,小于50的随机数,使用公式: =RAND()*50。","name":"RAND","type":"MATH"},{"def":"GETUSERDEPARTMENTS():返回角色部门\n示例:\nGETUSERDEPARTMENTS():返回角色所有部门,若多个部门则数组\nGETUSERDEPARTMENTS(3,2):返回角色该部门的第三层和第二层名字,\n若多个部门则返回数组,若没有第三层则只显示第二层","name":"GETUSERDEPARTMENTS","type":"OTHER"},{"def":"FORMAT(object,format) : 返回object的format格式。\nobject 需要被格式化对象,可以是String,数字,Object(常用的有Date, Time)。\nformat 格式化的样式。\n示例\nFORMAT(1234.5, \"#,##0.00\") => 1234.50\nFORMAT(1234.5, \"#,##0\") => 1234\nFORMAT(1234.5, \"¥#,##0.00\") => ¥1234.50\nFORMAT(1.5, \"0%\") => 150%\nFORMAT(1.5, \"0.000%\") => 150.000%\nFORMAT(6789, \"##0.0E0\") => 6.789E3\nFORMAT(6789, \"0.00E00\") => 6.79E03\nFORMAT(date(2007,1,1), \"EEEEE, MMMMM dd, yyyy\") => 星期一,一月 01,2007\nFORMAT(date(2007,1,13), \"MM/dd/yyyy\") => 01/13/2007\nFORMAT(date(2007,1,13), \"M-d-yy\") => 1-13-07\nFORMAT(time(16,23,56), \"h:mm:ss a\") => 4:23:56 下午","name":"FORMAT","type":"TEXT"},{"def":"TRIM(text): 清除文本中所有空格,单词间的单个空格除外,也可用于带有不规则空格的文本。\nText:需要清除空格的文本。\n示例:\nTRIM(\" Monthly Report\")等于Monthly Report。","name":"TRIM","type":"TEXT"},{"def":"SQRT(number): 返回一个正数的平方根。\nNumber:要求其平方根的任一正数。\n备注:\nNumber必须是一个正数,否则函数返回错误信息*NUM!。\n示例:\nSQRT(64)等于8。\nSQRT(-64)返回*NUM!。","name":"SQRT","type":"MATH"},{"def":"DAYSOFYEAR(year):返回某年包含的天数。\n示例:\nDAYSOFYEAR(2008)等于365,等价于DAYSOFYEAR(\"2008-01-01\")。","name":"DAYSOFYEAR","type":"DATETIME"},{"def":"RANK(number,ref,order): 返回一个数在一个数组中的秩。(如果把这个数组排序,该数的秩即为它在数组中的序号。)\nNumber 所求秩的数。(可以是Boolean型,true=1,false=0)\nRef 可以是数组,引用,或一系列数,非实数的值被忽略处理(接受Boolean型,true=1,false=0)。\nOrder 指定求秩的参数,非零为升序,零为降序\n\n备注\n1. RANK对重复的数返回相同的秩,但重复的数影响后面的数的秩,比如,在一组升序排列的整数中,如果5出现了2次,并且秩为3,那么6的秩为5 (没有数的秩是4).\n\n示例\nA1:A5 = 6, 4.5, 4.5, 2, 4\nRANK(A1,A1:A5,1) 即 6 的秩为 5.\n\nRANK(3,1,2,\"go\",3,4,1) = 3, \"go\"被忽略。","name":"RANK","type":"OTHER"},{"def":"ODD(number):返回对指定数值进行舍入后的奇数。\nnumber:是要舍入求奇的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是奇数,则不须进行任何舍入处理。\n示例:\nODD(1.5) 等于 3\nODD(3) 等于 3\nODD(2) 等于 3\nODD(-1) 等于 -1","name":"ODD","type":"MATH"},{"def":"COLCOUNT(tableData):返回tableData中列的个数。\ntableData:tableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是第一个查找到的tableData中列数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nCOLCOUNT(\"ds1\")等于6。\n","name":"COLCOUNT","type":"REPORT"},{"def":"ENDWITH(str1,str2):判断字符串str1是否以str2结束。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nENDWITH(\"FineReport\",\"Report\")等于true。\nENDWITH(\"FineReport\",\"Fine\")等于false。\nENDWITH(\"FineReport\",\"report\")等于false。","name":"ENDWITH","type":"TEXT"},{"def":"LOG10(number):返回以 10 为底的对数。\nnumber: 用于常用对数计算的正实数。\n示例:\nLOG10(86) 等于 1.934498451\nLOG10(10) 等于 1\nLOG10(1E5) 等于 5\n","name":"LOG10","type":"MATH"},{"def":"MAPARRAY(array, fn):把一个数组中的项目转换到另一个数组中。\narray (Array): 要转换的数组 \nfn (Function): 处理数组项目的函数 \n示例:\nMAPARRAY([3,4,2,3,6,8,7], item != 3)等于[false,true,true,false,true,true,true].","name":"MAPARRAY","type":"ARRAY"},{"def":"FLOOR(number): 将参数number沿绝对值减小的方向去尾舍入。\nNumber:待舍入的数值。\n示例:\nFLOOR(-2.5)等于-2。\nFLOOR(2.5)等于2。\n","name":"FLOOR","type":"MATH"},{"def":"NUMTO(number,bool)或NUMTO(number):返回number的中文表示。其中bool用于选择中文表示的方式,当没有bool时采用默认方式显示。\n示例:NUMTO(2345,true)等于二三四五。\n示例:NUMTO(2345,false)等于二千三百四十五。\n示例:NUMTO(2345)等于二千三百四十五。","name":"NUMTO","type":"TEXT"},{"def":"ATANH(number): 返回数字的反双曲正切值,该函数的参数值即为反双曲正切值的双曲正切值。\nNumber:指介于-1~1之间的任意实数。\n备注:\n 指定的number必须介于-1~1之间(不包括-1,1)。\n ATANH(TANH(number))=number,例如,ATANH(TANH(8))=8。\n示例:\nATANH(-0.5)等于-0.549306144。\nATANH(0)等于0。\nATANH(0.7)等于0.867300528。","name":"ATANH","type":"MATH"},{"def":"YEAR:(serial_number)返回日期中的年。Year是介于1900和9999之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nYEAR(\"2000/1/1\")等于2000。\nYEAR(\"2006/05/05\")等于2006。\nYEAR(\"1997/04/20\")等于1997。\nYEAR(\"2000-1-1\", \"yyyy-MM-dd\")等于2000。\nYEAR(\"2006-05-05\", \"yyyy-MM-dd\")等于2006。\nYEAR(\"1997-04-20\", \"yyyy-MM-dd\")等于1997。\nYEAR(35796)等于1998。","name":"YEAR","type":"DATETIME"},{"def":"SLICEARRAY(array, start, end):返回数组从第start个到第end个元素(包括第end个元素)。\n示例:\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3, 6)返回[4, 5, 1, 5].\n当不使用end参数时,返回从start开始到数组结束之间的元素。\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3)返回[4, 5, 1, 5, 7].","name":"SLICEARRAY","type":"ARRAY"},{"def":"","name":"DECODE","type":"OTHER"},{"def":"ENMONEY(value):将给定的BigDemical类型的数字转换成英文金额字符串。\n示例:\nENMONEY(23.49)等于TWENTY THREE AND CENTS FORTY NINE","name":"ENMONEY","type":"TEXT"},{"def":"IF(boolean,number1/string1,number2/string2):判断函数,boolean为true时返回第二个参数,为false时返回第三个。\nboolean: 用于判断的布尔值,true或者false。\nnumber1/string1: 第一个参数,如果boolean为ture,返回这个值。\nnumber2/string2: 第二个参数,如果boolean为false,返回这个值。\n示例:\nIF(true,2,8)等于2\nIF(false,\"first\",\"second\")等于second\nIF(true,\"first\",7)等于first","name":"IF","type":"LOGIC"},{"def":"DATEINWEEK(date, number):函数返回在某一个星期当中第几天的日期。\n示例:\ndateInWeek(\"2008-08-28\", 2)等于2008-08-26。\ndateInWeek(\"2008-08-28\", -1)等于2008-08-31。\n如果最后一个参数为-1,返回该日期所在星期的最后一天\n","name":"DATEINWEEK","type":"DATETIME"},{"def":"MONTHDELTA(date,delta):返回指定日期date后delta个月的日期。\n示例:\nMONTHDELTA(\"2008-08-08\", 4)等于2008-12-08。","name":"MONTHDELTA","type":"DATETIME"},{"def":"FIELDS(connectionName,tableName):返回tableName这个表中的所有字段名。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么FIELDS(\"BASE\",\"task\")等于[name,start,end].","name":"FIELDS","type":"REPORT"},{"def":"DATEDIF(start_date,end_date,unit):返回两个指定日期间的天数、月数或年数。\nStart_date:代表所指定时间段的初始日期。\nEnd_date:代表所指定时间段的终止日期。\nUnit:函数返回信息的类型。\n若unit=“Y”,则DATEDIF返回指定时间段的年差数。\n若unit=“M”,则DATEDIF返回指定时间段的月差数。\n若unit=“D”,则DATEDIF返回指定时间段的日差数。\n若unit=“MD”,则DATEDIF忽略年和月,返回指定时间段的日差数。\n若unit=“YM”,则DATEDIF忽略年和日,返回指定时间段的月差数。\n若unit=“YD”,则DATEDIF忽略年,返回指定时间段的日差数。\n示例:\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"Y\")等于3,即在2001年2月28日与2004年3月20日之间有3个整年。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"M\")等于37,即在2001年2月28日与2004年3月20日之间有36个整月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"D\")等于1116,即在2001年2月28日与2004年3月20日之间有1116个整天。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"MD\")等于8,即忽略月和年后,2001年2月28日与2004年3月20日的差为8天。\nDATEDIF(\"2001/1/28\",\"2004/3/20\",\"YM\")等于2,即忽略日和年后,2001年1月28日与2004年3月20日的差为2个月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"YD\")等于21,即忽略年后,2001年2月28日与2004年3月20日的差为21天。","name":"DATEDIF","type":"DATETIME"},{"def":"TOIMAGE(path):显示指定路径下的图片。此处默认开启了图片缓存功能以加速报表的生成.\n如不需要缓存,请在参数后面追加值FALSE,例如:TOIMAGE(\"D:/fr.png\",false).\n如需要指定图片大小,拉伸显示, 则需要添加参数,TOIMAGE(patch, true, width, height).\n示例:=toimage(\"d:/1.jpg\", true, \"50%\", 300), 第三个参数为指定宽度, 第四个参数为指定高度.\n如果参数为整数, 则直接写数字, 如果为百分比, 则需要加上引号, 如\"300%\"","name":"TOIMAGE","type":"OTHER"},{"def":"LEFT(text,num_chars): 根据指定的字符数返回文本串中的第一个或前几个字符。\nText:包含需要选取字符的文本串或单元格引用。\nNum_chars:指定返回的字符串长度。\n备注:\n Num_chars的值必须等于或大于0。\n 如果num_chars大于整个文本的长度,LEFT函数将返回所有的文本。\n 如果省略num_chars,则默认值为1。\n示例:\nLEFT(\"Fine software\",8)等于“Fine sof”。\nLEFT(\"Fine software\")等于“F”。\n如果单元格A3中含有“China”,则LEFT(A3,2)等于“Ch”。","name":"LEFT","type":"TEXT"},{"def":"SUBSTITUTE(text,old_text,new_text,instance_num): 用new_text替换文本串中的old_text。\nText:需要被替换字符的文本,或含有文本的单元格引用。\nOld_text:需要被替换的部分文本。\nNew_text:用于替换old_text的文本。\nInstance_num:指定用new_text来替换第几次出现的old_text。如果指定了instance_num,则只有指定位置上的old_text被替换,否则文字串中出现的所有old_text都被new_text替换。\n备注:\n 如果需要替换文本串中的指定文本,则使用SUBSTITUTE函数;如果需要替换文本串中指定位置上的任意文本,则使用REPLACE函数。\n示例:\nSUBSTITUTE(\"data base\",\"base\",\"model\")等于“data model”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",1)等于“July 18, 2000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\")等于“July 18, 1000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",2)等于“July 28, 1000”。 ","name":"SUBSTITUTE","type":"TEXT"},{"def":"LOG(number,base): 按指定的任意底数,返回数值的对数。\nNumber:需要求对数的正实数。\nBase:对数的底数。如果省略底数,默认值为10。\n示例:\nLOG(16,2)等于4。\nLOG(10)等于1。\nLOG(24,3)等于2.892789261。","name":"LOG","type":"MATH"},{"def":"SORTARRAY(array):返回数组array排过序的数组。\n示例:\nSORTARRAY([3, 4, 4, 5, 1, 5, 7])返回[1, 3, 4, 4, 5, 5, 7].\n注意:数组array的元素类型必须一样,并且要可比较。","name":"SORTARRAY","type":"ARRAY"},{"def":"DATEDELTA(date, deltadays):返回一个日期??date后deltadays的日期。\ndeltaDays可以为正值,负值,零。\n示例:\nDATEDELTA(\"2008-08-08\", -10)等于2008-07-29。\nDATEDELTA(\"2008-08-08\", 10)等于2008-08-18。","name":"DATEDELTA","type":"DATETIME"},{"def":"MID(text,start_num,num_chars): 返回文本串中从指定位置开始的一定数目的字符,该数目由用户指定。\nText:包含要提取字符的文本串。\nStart_num:文本中需要提取字符的起始位置。文本中第一个字符的start_num为1,依此类推。\nNum_chars:返回字符的长度。\n备注:\n 如果start_num大于文本长度,MID函数返回“”(空文本)。\n 如果start_num小于文本长度,并且start_num加上num_chars大于文本长度,MID函数将从start_num指定的起始字符直至文本末的所有字符。\n 如果start_num小于1,MID函数返回错误信息*VALUE!。\n 如果num_chars是负数,MID函数返回错误信息*VALUE!。\n示例:\nMID(\"Finemore software\",10,8)返回“software”。\nMID(\"Finemore software\",30,5)返回“”(空文本)。\nMID(\"Finemore software\",0,8)返回*VALUE!。\nMID(\"Finemore software\",5,-1)返回*VALUE!。","name":"MID","type":"TEXT"},{"def":"ATAN2(x_num,y_num): 返回x、y坐标的反正切值。返回角度为x轴与过(x_num,y_num)与坐标原点(0,0)的一条直线形成的角度。该角度以弧度显示。\nX_num:指定点的x坐标。\nY_num:指定点的y坐标。\n备注:\n 正值表示从x轴开始以逆时针方式所得的角度;负值表示从x轴开始以顺时针方式所得的角度。\na > 0,b > 0 or a > 0, b < 0时,公式直接成立;\na < 0,b > 0, ATAN2(a,b)=PI()-ABS(ATAN(b/a))\na < 0,b < 0, ATAN2(a,b)=ABS(ATAN(b/a))-PI()\n 当x_num与y_num都为0时,ATAN2返回错误信息*DIV/0!。\n 用角度制显示返回数值时,把返回数值乘以180/PI()。\n 返回值以弧度表示(返回值大于-pi且小于等于pi)。\n示例:\nATAN2(-2,2)等于2.356194490192345(弧度制的3*pi/4)。\nATAN2(2,2)等于0.785398163(弧度制的pi/4)。\nATAN2(-2,2)*180/PI()等于135(角度制)。","name":"ATAN2","type":"MATH"},{"def":"SUM(number1,number2,…): 求一个指定单元格区域中所有数字之和。\nNumber1,number2,…:1到30个参数或指定单元格区域中所有数字。\n备注:\n 函数将直接键入参数中的数值、逻辑值及文本表达式计算在内。\n 若参数是数组或引用,则只有数组或单元格引用中的数值进行计算。\n示例:\nSUM(70,80)等于150。\nSUM(\"70\",80,TRUE)等于151,逻辑值“TRUE”作为1来计算;“FALSE”作为0计算;文本“70”作为70来计算。","name":"SUM","type":"MATH"},{"def":"EXACT(text1,text2): 检测两组文本是否相同。如果完全相同,EXACT函数返回TRUE;否则,返回FALSE。EXACT函数可以区分大小写,但忽略格式的不同。同时也可以利用EXACT函数来检测输入文档的文字。\nText1:需要比较的第一组文本。\nText2:需要比较的第二组文本。\n示例:\nEXACT(\"Spreadsheet\",\"Spreadsheet\")等于TRUE。\nEXACT(\"Spreadsheet\",\"S preadsheet\")等于FALSE。\nEXACT(\"Spreadsheet\",\"spreadsheet\")等于FALSE。","name":"EXACT","type":"TEXT"},{"def":"TOINTEGER(text): 将文本转换成Integer对象。\nText:需要转换的文本。\n示例:\nTOINTEGER(\"123\")等于 new Integer(123)。","name":"TOINTEGER","type":"TEXT"},{"def":"ACOSH(number): 返回给定数值的反双曲余弦。\nNumber:返回值的双曲余弦。\n备注:\n 参数number的值必须大于或等于1。\n ACOSH(COSH(number))=number。\n示例:\nACOSH(1)等于0。\nACOSH(8)等于2.768659383。\nACOSH(5.5)等于2.389526435。","name":"ACOSH","type":"MATH"},{"def":"weekdate(year,month,weekOfMonth,dayOfWeek): 返回指定年月的指定周的周几的具体日期。\n示例:\nweekdate(2009,10,2,1)\n返回的是2009年的10月的第二个周的第一天即星期天的日期,返回的是2009-10-04\n最后一个参数dayOfWeek为-1时,表示这个周的最后一天\n示例:\nweekdate(2009,12,1,-1)\n返回的是2009年的12月的第一个周的最后一天即星期六的日期,返回的是2009-12-05\n","name":"WEEKDATE","type":"DATETIME"},{"def":"MIN(number1,number2,…): 返回参数列表中的最小值。\nNumber1,number2,…:1到30个需要找出最小值的参数。\n备注:\n 若参数中没有数字,函数MIN将返回0。\n 参数应为数字、空白单元格、逻辑值或是表示数值的文本串。如果参数是错误值时,MIN将返回错误信息。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n示例:\n如果B1:B4包含3,6,9,12,则:\nMIN(B1:B4)等于3。\nMIN(B1:B4,0)等于0。","name":"MIN","type":"MATH"},{"def":"STARTWITH(str1,str2):判断字符串str1是否以str2开始。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nSTARTWITH(\"FineReport\",\"Fine\")等于true。\nSTARTWITH(\"FineReport\",\"Report\")等于false。\nSTARTWITH(\"FineReport\",\"fine\")等于false。","name":"STARTWITH","type":"TEXT"},{"def":"COMBIN(number,number_chosen): 返回若干个指定对象的组合数。该函数与数学表达式为Cnk功能相同。\nNumber或数学表达式中的“n”指对象总数。\nNumber_chosen或数学表达式中的“k”指在对象总数中某一组合的数量。\n备注:\n Number必须是正整数,number_chosen必须是非负整数。\n 如果number和number_chosen小于0或number小于number_chosen,函数返回错误信息*NUM!。\n 对象组合是对象的子集。与排列不同的是,组合不涉及对象内部的先后顺序,而顺序对排列是非常重要的。\n 假设number=n,number_chosen=k,则: COMBIN(n,k)=Cnk=n!/(k!(n-k)!)。\n示例:\nCOMBIN(5,6)等于*NUM!。\nCOMBIN(5,2)等于10。","name":"COMBIN","type":"MATH"},{"def":"EVEN(number):返回沿绝对值增大方向取整后最接近的偶数。使用该函数可以处理那些成对出现的对象。\nnumber:所要取整的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是偶数,则不须进行任何舍入处理。\n示例:\nEVEN(1.5) 等于 2\nEVEN(3) 等于 4\nEVEN(2) 等于 2\nEVEN(-1) 等于 -2","name":"EVEN","type":"MATH"},{"def":"COUNT(value1,value2,…): 计算数组或数据区域中所含项的个数。\nValue1,value2,…:可包含任何类型数据的参数。","name":"COUNT","type":"MATH"},{"def":"INDEXOFARRAY(array, index):返回数组array的第index个元素。\n示例:\nINDEXOFARRAY([\"第一个\", \"第二个\", \"第三个\"], 2)返回\"第二个\"。","name":"INDEXOFARRAY","type":"ARRAY"},{"def":"MAP(object, string, int, int):四个参数分别是索引值,数据集的名字,索引值所在列序号,返回值所在列序号。\n提醒:后两个参数也可以写列名代替。\n根据数据集的名字,找到对应的数据集,找到其中索引列的值为key所对应的返回值。\n数据集的查找方式是依次从报表数据集找到服务器数据集。\n索引列序号与返回值序列号的初始值为1示例:\nMAP(1001, \"employee\", 1, 2)返回employee数据集,第1列中值为1001那条记录中第2列的值。\nMAP(1001, \"employee\", \"name\", \"address\")返回employee数据集,name列中值为1001那条记录中address列的值。","name":"MAP","type":"REPORT"},{"def":"SEQ(): 返回数值,在整个报表执行过程中,返回该函数被第几次执行了。\n示例:\nSEQ()在第一次执行时,结果为1。\nSEQ()在第二次执行时,结果为2。","name":"SEQ","type":"OTHER"},{"def":"i18n为本软件内置的国际化公式,可以对一些常用的词语进行国际化.\n示例:i18n('File'), 则会在中文语言环境下显示为: 文件, 而在英文语言环境下显示为: File","name":"I18N","type":"REPORT"},{"def":"层次坐标简写, 等同于=A1[A1:-1], 若需=B1[A1:-1]则HIERARCHY(A1, B1).\n若为横向, 偏移量为-2, 则写成HIERARCHY(A1, B1, -2, false), 等同于=B1[;A1:-1].\n公式中最后一个参数表示横纵向, 默认不传递, 表示纵向扩展, 若横向扩展, 则需要加上最后一个参数FALSE来区分. ","name":"HIERARCHY","type":"HA"},{"def":"","name":"ENCODE","type":"OTHER"},{"def":"DATEINMONTH(date, number):函数返回在某一个月当中第几天的日期。\n示例:\nDATEINMONTH(\"2008-08-08\", 20) 等于2008-08-20。\nDATEINMONTH(\"2008-08-08\", -1) 等于2008-08-31。","name":"DATEINMONTH","type":"DATETIME"},{"def":"TOOCTAL(int): 将一个十进制整型数转换成八进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOOCTAL(10)等于 \"12\"。\nTOOCTAL(20)等于 \"24\"。","name":"TOOCTAL","type":"MATH"},{"def":"REPEAT(text,number_times): 根据指定的次数重复显示文本。REPEAT函数可用来显示同一字符串,并对单元格进行填充。\nText:需要重复显示的文本或包含文本的单元格引用。\nNumber_times:指定文本重复的次数,且为正数。如果number_times为0,REPEAT函数将返回“”(空文本)。如果number_times不是整数,将被取整。REPEAT函数的最终结果通常不大于32767个字符。\n备注:\n 该函数可被用于在工作表中创建简单的直方图。\n示例:\nREPEAT(\"$\",4)等于“$$$$”。\n如果单元格B10的内容为“你好”,REPEAT(B10,3)等于“你好你好你好”。","name":"REPEAT","type":"TEXT"},{"def":"GREPARRAY(array,fn):函数(返回true或者false)是条件,过滤此数组,最后形成一个新数组。\n示例:\nGREPARRAY([3,4,2,3,6,8,7], item != 3)等于[4,2,6,8,7].\n","name":"GREPARRAY","type":"ARRAY"},{"def":"MAX(number1,number2,…): 返回参数列表中的最大值。\nNumber1,number2,…:1到30个需要找出最大值的参数。\n备注:\n 参数可以是数字、空白单元格、逻辑值或数字的文本表达式。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n 如果参数中没有任何数字,MAX将返回0。\n示例:\nMAX(0.1,0,1.2)等于1.2。","name":"MAX","type":"MATH"},{"def":"CHAR(number): 根据指定数字返回对应的字符。CHAR函数可将计算机其他类型的数字代码转换为字符。\nNumber:用于指定字符的数字,介于1~65535之间(包括1和65535)。\n示例:\nCHAR(88)等于“X”。\nCHAR(45)等于“-”。","name":"CHAR","type":"TEXT"},{"def":"TRUNC(number,num_digits):将数字的小数部分截去,返回整数。\nnumber:需要截尾取整的数字。\nnum_digits:用于指定取整精度的数字。\n示例:\nTRUNC(8.9) 等于 8\nTRUNC(-8.9) 等于 -8\nTRUNC(PI()) 等于 3\n","name":"TRUNC","type":"MATH"},{"def":"FACT(number):返回数的阶乘,一个数的阶乘等于 1*2*3*...*该数。\nnumber:要计算其阶乘的非负数。如果输入的 number 不是整数,则截尾取整。\n示例:\nFACT(1) 等于 1\nFACT(1.9) 等于 FACT(1) 等于 1\nFACT(0) 等于 1\nFACT(5) 等于 1*2*3*4*5 等于 120\n","name":"FACT","type":"MATH"},{"def":"STDEV(array1): 计算数据系列的标准偏差(与Excel的同名函数作用相同)。\n\n示例:\nSTDEV([1,2,3])=1。\n","name":"STDEV","type":"OTHER"},{"def":"SPLIT(String1,String2):返回由String2分割String1组成的字符串数组。\nString1:以双引号表示的字符串。\nString2:以双引号表示的分隔符。例如逗号\",\"\n示例:\nSPLIT(\"hello,world,yes\",\",\") = [\"hello\",\"world\",\"yes\"]。\nSPLIT(\"this is very good\",\" \") = [\"this\",\"is\",\"very\",\"good\"]。\n备注:\n如果只有一个参数,则返回一个错误。\n如果有多个参数,则只有前两个起作用。","name":"SPLIT","type":"TEXT"},{"def":"INARRAY(co, array):返回co在数组array中的位置,如果co不在array中,则返回0.\n示例:\nString[] arr = {\"a\",\"b\",\"c\",\"d\"}\n那么INARRAY(\"b\", arr)等于2.","name":"INARRAY","type":"ARRAY"},{"def":"REVERSEARRAY(array):返回数组array的倒序数组。\n示例:\nREVERSEARRAY([\"第一个\", \"第二个\", \"第三个\"])返回[\"第三个\", \"第二个\", \"第一个\"].","name":"REVERSEARRAY","type":"ARRAY"},{"def":"RANDBETWEEN(value1,value2):返回value1和value2之间的一个随机整数。\n示例:\nRANDBETWEEN(12.333, 13.233)只会返回13。\nRANDBETWEEN(11.2, 13.3)有可能返回12或者13。","name":"RANDBETWEEN","type":"MATH"},{"def":"UPPER(text): 将文本中所有的字符转化为大写。\nText:需要转化为大写字符的文本,或是包含文本的单元格引用。\n示例:\nUPPER(\"notes\")等于“NOTES”。\n如果单元格E5的值为“Examples”,则UPPER(E5)等于“EXAMPLES”。","name":"UPPER","type":"TEXT"},{"def":"ABS(number): 返回指定数字的绝对值。绝对值是指没有正负符号的数值。\nNumber:需要求出绝对值的任意实数。\n示例:\nABS(-1.5)等于1.5。\nABS(0)等于0。\nABS(2.5)等于2.5。","name":"ABS","type":"MATH"},{"def":"RIGHT(text,num_chars): 根据指定的字符数从右开始返回文本串中的最后一个或几个字符。\nText:包含需要提取字符的文本串或单元格引用。\nNum_chars:指定RIGHT函数从文本串中提取的字符数。Num_chars不能小于0。如果num_chars大于文本串长度,RIGHT函数将返回整个文本。如果不指定num_chars,则默认值为1。\n示例:\nRIGHT(\"It is interesting\",6)等于“esting”。\nRIGHT(\"Share Holder\")等于“r”。\nRIGHT(\"Huge sale\",4)等于“sale”。","name":"RIGHT","type":"TEXT"},{"def":"MEDIAN(array1): 返回数据系列的中值(与Excel的同名函数作用相同)。\n\n示例:\nMEDIAN([1,2,3])=2。\n","name":"MEDIAN","type":"OTHER"},{"def":"TABLEDATAFIELDS(tableData):返回tableData中所有的字段名。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的列名组成的数组。\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nTABLEDATAFIELDS(\"ds1\")等于\nCUSTOMERID,CUSTOMERAME,CITY,COUNTRY,TEL,DISTRICT。","name":"TABLEDATAFIELDS","type":"REPORT"},{"def":"占比公式, =PROPORTION(A1)等同于=A1/sum(A1[!0])","name":"PROPORTION","type":"HA"},{"def":"COL()返回当前单元格的列号,必须使用于条件属性中\n示例:\n如果当前单元格是A5,在A5中写入\"=col()\"则返回1。\n如果当前单元格是C6,在C6中写入\"=col()\"则返回3。","name":"COL","type":"REPORT"},{"def":"TOHEX(int): 将一个十进制整型数转换成十六进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOHEX(15)等于 \"f\"。\nTOHEX(20)等于 \"14\"。","name":"TOHEX","type":"MATH"},{"def":"COS(number): 返回一个角度的余弦值。\nNumber:以弧度表示的需要求余弦值的角度。\n备注:\n 要把一个角度转换成弧度值,将角度乘于PI()/180。\n COS(n*2*PI()+number)=COS(number)(其中n为整数,number从-pi到pi)。\n示例:\nCOS(0.5)等于0.877582562。\nCOS(30*PI()/180)等于0.866025404。","name":"COS","type":"MATH"},{"def":"跨层累计, =CROSSLAYERTOTAL(A1, B1, C1, D1)等同于=IF(&B1 >1, D1[B1:-1] + C1, D1[A1:-1,B1:!-1] + C1), 如需横向, 则传递第五个参数false","name":"CROSSLAYERTOTAL","type":"HA"},{"def":"POWER(number,power): 返回指定数字的乘幂。\nNumber:底数,可以为任意实数。\nPower:指数。参数number按照该指数次幂乘方。\n备注:\n 可以使用符号“^”代替POWER,如: POWER(5,2)等于5^2。\n示例:\nPOWER(6,2)等于36。\nPOWER(14,5)等于537824。\nPOWER(4,2/3)等于2.519842100。\nPOWER(3,-2.3)等于0.079913677。","name":"POWER","type":"MATH"},{"def":"DAYS360(start_date,end_date,method):按照一年 360 天的算法(每个月以 30 天计,一年共计 12 个月),\n返回两日期间相差的天数,这在会计计算中将会用到。如果财务系统是基于一年 12 个月,每月 30 天,\n可用此函数帮助计算支付款项。\nStart_date 和 end_date :是用于计算期间天数的起止日期。\nMethod : 它指定了在计算中是采用欧洲方法还是美国方法。\nMethod 定义 :\nFALSE或忽略 美国方法 (NASD)。如果起始日期是一个月的 31 号,则等于同月的 30 号。如果终止日期是一个月的\n31号,并且起始日期早于 30 号,则终止日期等于下一个月的 1 号,否则,终止日期等于本月的 30 号。\nTRUE 欧洲方法。无论是起始日期还是终止日期为一个月的 31 号,都将等于本月的 30 号。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAYS360(\"1998/1/30\", \"1998/2/1\") 等于 1","name":"DAYS360","type":"DATETIME"},{"def":"filetype(file)获取文件的类型。\n当file为单文件时,返回文件类型字符串,当file为多文件时,返回文件类型的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.txt },则filetype(B2)返回值为[“doc”, “xls”, “txt”]。","name":"FILETYPE","type":"OTHER"},{"def":"ADDARRAY(array, insertArray, start):在数组第start个位置插入insertArray中的所有元素,再返回该数组。\n示例:\nADDARRAY([3, 4, 1, 5, 7], [23, 43, 22], 3)返回[3, 4, 23, 43, 22, 1, 5, 7].\nADDARRAY([3, 4, 1, 5, 7], \"测试\", 3)返回[3, 4, \"测试\", 1, 5, 7].\n注意:如果start为小于1的数或者不写start参数,则默认从数组的第一位开始插入数组元素。","name":"ADD2ARRAY","type":"ARRAY"},{"def":"BITNOT(int):将一个十进制整数进行二进制取反运算。\nint:需要进行转换的十进制数。\n示例:\nBITNOT(3)等于-4。\nBITNOT(12)等于-13。","name":"BITNOT","type":"LOGIC"},{"def":"TABLEAS(connectionName):返回名为connectionName的数据库中的所有表名。\n示例:\n假设在FRDemo这个数据库中,有3个表:a,b,c;\n那么TABLES(\"FRDemo\")等于[a,b,c].","name":"TABLES","type":"REPORT"},{"def":"SUMSQ(number1,number2, ...):返回所有参数的平方和。\nnumber1, number2, ...:为 1 到 30 个需要求平方和的参数,也可以使用数组或对数组的引用来代替以逗号分隔的参数。\n示例:\nSUMSQ(3, 4) 等于 25\n","name":"SUMSQ","type":"MATH"},{"def":"RECORDS(connection, table,field):返回数据库表table中字段名field下的所有元素。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么RECORDS(\"BASE\",\"task\",\"end\")等于[2009,2012].\n\nRECORDS(connection, table,field,row)返回table中field字段下的第row行的记录,field可以为列名也可以为列号。\n RECORDS(\"BASE\",\"task\",\"end\",2)等于2012.\n RECORDS(\"BASE\",\"task\",2,2)等于2009.","name":"RECORDS","type":"REPORT"},{"def":"","name":"TOBIGDECIMAL","type":"DELETE"},{"def":"TODOUBLE(text): 将文本转换成Double对象。\nText:需要转换的文本。\n示例:\nTODOUBLE(\"123.21\")等于 new Double(123.21)。","name":"TODOUBLE","type":"TEXT"},{"def":"TODATE()函数可以将各种日期形式的参数转换为日期类型。\n它有三种参数的形式:\n1 参数是一个日期型的参数,那么直接将这个参数返回。\n示例:\nTODATE(DATE(2007,12,12))返回2007年12月12日组成的日期。\n2 参数是以从1970年1月1日0时0分0秒开始的毫秒数,返回对应的时间。\n示例:\nTODATE(1023542354746)返回2002年6月8日。\n3 参数是日期格式的文本,那么返回这个文本对应的日期。\n示例:\nTODATE(\"2007/10/15\")返回2007年10月5日组成的日期。\nTODATE(\"2007-6-8\")返回2007年6月8日组成的日期。\n4 有两个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式。\n示例:\nTODATE(\"1/15/07\",\"mm/dd/yy\")返回07年1月15日组成的日期。\n特别的,\"yyyyMMdd\"是用来解析形如“20081230”之类的日期格式的。比如TODATE(\"20110830\",\"yyyyMMdd\")返回11年08月30日组成的日期\n5 有三个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式,第三个参数为解析日期的语言,如:zh(中文),en(英文)。\n示例:\nTODATE(\"星期三 1/15/07\",\"EEE mm/dd/yy\", \"zh\")返回07年1月15日组成的日期,使用“zh(中文)”才能够正常解析“星期三”这个字符串。","name":"TODATE","type":"DATETIME"},{"def":"PROPER(text): 将文本中的第一个字母和所有非字母字符后的第一个字母转化成大写,其他字母变为小写。\nText:需要转化为文本的公式、由双引号引用的文本串或是单元格引用。\n示例:\nPROPER(\"Finemore Integrated Office\")等于“Finemore Integrated Office”。\nPROPER(\"100 percent\")等于“100 Percent”。\nPROPER(\"SpreaDSheEt\")等于“Spreadsheet”。","name":"PROPER","type":"TEXT"},{"def":"DAY:(serial_number)返回日期中的日。DAY是介于1和31之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAY(\"2000/1/1\")等于1。\nDAY(\"2006/05/05\")等于5。\nDAY(\"1997/04/20\")等于20。\nDAY(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nDAY(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nDAY(\"1997-04-20\", \"yyyy-MM-dd\")等于20。\nDAY(35796)等于1。","name":"DAY","type":"DATETIME"},{"def":"LUNAR(year,day,month): 返回当前日期对应的农历时间。\nyear,month,day:分别对应年月日。\n示例:\n如果需要查询2011年7月21日对应的农历时间,则只需输入LUNAR(2011,7,21)结果将显示为:辛卯年六月廿一\n同样,如输入LUNAR(2001,7,21),则显示:辛巳年六月初一 。本公式支持的时间段为1900-2100年。","name":"LUNAR","type":"DATETIME"},{"def":"TABLEDATAS():返回报表数据集和服务器数据集名字。\n示例:\n服务器数据集有:ds1,ds2,ds3;报表数据集有dsr1,dsr2.\nTABLEDATAS()等于[dsr1,dsr2,ds1,ds2,ds3].\n而TABLEDATAS(0)返回服务器数据集名字;TABLEDATAS(1)返回报表数据集名字;\nTABLEDATAS(0)等于[ds1,ds2,ds3];TABLEDATAS(1)等于[dsr1,dsr2].","name":"TABLEDATAS","type":"REPORT"},{"def":"TAN(number): 返回指定角度的正切值。\nNumber:待求正切值的角度,以弧度表示。如果参数是以度为单位的,乘以Pi()/180后转换为弧度。\n示例:\nTAN(0.8)等于1.029638557。\nTAN(45*Pi()/180)等于1。","name":"TAN","type":"MATH"},{"def":"","name":"JVM","type":"DELETE"},{"def":"LN(number):返回一个数的自然对数。自然对数以常数项 e(2.71828182845904)为底。\nnumber:是用于计算其自然对数的正实数。\n示例:\nLN(86) 等于 4.45437\nLN(2.7182818) 等于 1\nLN(EXP(3)) 等于 3\nEXP(LN(4)) 等于 4\n","name":"LN","type":"MATH"},{"def":"ARRAY(arg1,arg2...):返回一个由arg1,arg2,...组成的数组.\narg1,arg2,...:字符串或者数字.\n示例:\nARRAY(\"hello\") = [\"hello\"].\nARRAY(\"hello\",\"world\") = [\"hello\",\"world\"].\nARRAY(\"hello\",98) = [\"hello\",98].\nARRAY(67,98) = [67,98].","name":"ARRAY","type":"ARRAY"},{"def":"TOBINARY(int): 将一个十进制整型数转换成二进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOBINARY(10)等于 \"1010\"。\nTOBINARY(20)等于 \"10100\"。","name":"TOBINARY","type":"MATH"},{"def":"NVL(value1,value2,value3,...):在所有参数中返回第一个不是null的值value1:可以为任意数,也可以为null。\nvalue2:可以为任意数,也可以为null。\n当字符串长度为0时, 返回也为null\n示例:\nNVL(12,20)等于12。\nNVL(null,12)等于12。\nNVL(null,null)等于null。\nNVL(20,null)等于20。\nNVL(null,null,10)等于10。","name":"NVL","type":"OTHER"},{"def":"CORREL(array1,array2): 求两个相同长度数据系列的相关系数(与Excel的同名函数作用相同)。\n如果数组或引用参数包含文本、逻辑值或空白单元格,则这些值将被忽略;但包含零值的单元格将计算在内。\n函数计算结果出现负数表示负相关。相关系数的取值范围是[-1,1]之间的数。相关系数的绝对值越大,表示误差越小。 Array1 和 Array2 的数据点的个数必须相同,例如:\nCORREL([1,2,3],[2,4,6])=1。\n","name":"CORREL","type":"OTHER"},{"def":"COLNAME(tableData,colIndex)返回的是tableData中列序号colIndex的列名。\ntableData:表示TableData的名字,字符串形式。\ncolIndex:表示列序号。\n备注:\n TableData先从私有数据源中查找,再从公有数据源中查找。\n示例:\nCOLNAME(\"Check\",3)等于AcceName。\nCOLNAME(\"country\",4)等于Area。","name":"COLNAME","type":"REPORT"},{"def":"DECIMAL(number): 返回number的大数类型,常用于精确计算。","name":"DECIMAL","type":"MATH"},{"def":"CLASS(object):返回object对象的所属的类。","name":"CLASS","type":"OTHER"},{"def":"VALUE(tableData,col,row)返回tableData中列号为col的值, 行号为row。\ntableData:tableData的名字,字符串形式的。\nrow:行号。\ncol:列号。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的行数。\n示例:\nVALUE(\"country\",5,3)等于South America。\nVALUE(\"Simple\",8,3)等于jonnason。\n示例:VALUE(\"country\",5,\"大陆\")等于South America。\n\nVALUE(tableData,col)返回tableData中列号为col的一列值。\nVALUE(tableData,targetCol, orgCol, element)返回tableData中第targetCol列中的元素,这些元素对应的第orgCol列的值为element。\n示例:\ntableData : co\n国家 省份\n\n中国 江苏\n中国 浙江\n中国 北京\n美国 纽约\n美国 新泽西\nVALUE(\"co\",2, 1, \"中国\")等于[\"江苏\", \"浙江\", \"北京\"]。\n特别说明:列号也可以写为列名。\nVALUE(tableData,targetCol, orgCol, element, idx)返回VALUE(tableData,targetCol, orgCol, element)数组的第idx个值。\n特别说明:idx的值小于0时,会取数组的第一个值,idx的值大于数组长度时,会取数组的最后一个值。\n","name":"VALUE","type":"REPORT"},{"def":"JOINARRAY(array,sepa):返回一个由sepa作为分隔符的字符串.\narray:[arg1,arg2...]格式的数组;\nsepa:分隔符。\n示例:\nJOINARRAY([1,2],\";\") = [1;2].\nJOINARRAY([hello,world],\"-\") = [hello-world].","name":"JOINARRAY","type":"ARRAY"},{"def":"DATETONUMBER(date):返回自 1970 年 1 月 1 日 00:00:00 GMT 经过的毫秒数。\n示例:\nDATETONUMBER(\"2008-08-08\")等于1218124800000。","name":"DATETONUMBER","type":"DATETIME"},{"def":"INDEXOF(str1,index):返回字符串str1在index位置上的字符。\n备注:\n index是从0开始计数的。\n示例:\nINDEXOF(\"FineReport\",0)等于'F'。\nINDEXOF(\"FineReport\",2)等于'n'。\nINDEXOF(\"FineReport\",9)等于't'。\n\nINDEXOF(array, index):返回数组在index位置上的元素。\n备注:\n index是从1开始计数的。\n示例:\nString[] array = {\"a\", \"b\", \"c\"}\nINDEXOF(array, 1)等于\"a\".\n","name":"INDEXOF","type":"TEXT"},{"def":"PRODUCT(number1,number2, ...):将所有以参数形式给出的数字相乘,并返回乘积值。\nnumber1, number2, ...:为 1 到 30 个需要相乘的数字参数。\n示例:\nPRODUCT(3,4) 等于 12\nPRODUCT(3,4,5) 等于 60\n\n","name":"PRODUCT","type":"MATH"},{"def":"ACOS(number): 返回指定数值的反余弦值。反余弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的余弦值。\n备注:\n 函数的参数必须在-1和1之间,包括-1和1。\n 返回的角度值在0和Pi之间。\n 如果要把返回的角度用度数来表示,用180/PI()乘返回值即可。\n示例:\nACOS(1)等于0(弧度)。\nACOS(0.5)等于1.047197551(Pi/3弧度)。\nACOS(0.5)*180/PI()等于60(度)。","name":"ACOS","type":"MATH"},{"def":"FIND(find_text,within_text,start_num):从指定的索引(start_num)处开始,返回第一次出现的指定子字符串(find_text)在此字符串(within_text)中的索引。\nFind_text:需要查找的文本或包含文本的单元格引用。\nWithin_text:包含需要查找文本的文本或单元格引用。\nStart_num:指定进行查找字符的索引位置。within_text里的索引从1开始。如果省略start_num,则假设值为1。\n备注:\n 如果find_text不在within_text中,FIND函数返回值为0。\n 如果start_num不大于0,FIND函数返回错误信息*VALUE!。\n 如果start_num大于within_text的长度,FIND函数返回值为0。\n 如果find_text是空白文本,FIND函数将在搜索串中匹配第一个字符(即编号为start_num或1的字符)。\n示例:\nFIND(\"I\",\"Information\")等于1。\nFIND(\"i\",\"Information\")等于9。\nFIND(\"o\",\"Information\",2)等于4。\nFIND(\"o\",\"Information\",12)等于0。\nFIND(\"o\",\"Information\",-1)等于*VALUE!。","name":"FIND","type":"TEXT"},{"def":"MINUTE(serial_number):返回某一指定时间的分钟数,其值是介于0与59之间的一个整数。\nserial_number:包含所求分钟数的时间。\n示例:\nMINUTE(\"15:36:25\")等于36。\nMINUTE(\"15:36:25\", \"HH:mm:ss\")等于36。","name":"MINUTE","type":"DATETIME"},{"def":"SIGN(number):返回数字的符号。当数字为正数时返回 1,为零时返回 0,为负数时返回 -1。\nNumber:为任意实数。\n示例:\nSIGN(10) 等于 1\nSIGN(4-4) 等于 0\nSIGN(-0.00001) 等于 -1\n","name":"SIGN","type":"MATH"},{"def":"INDEX(key,val1,val2,...):返回key在val1,val2,...所组成的序列中的位置,不存在于序列中则返回参数的个数.\n备注:\n key和valn可以是任意类型\n示例:\nINDEX(2,2)等于1。\nINDEX(2,1,2)等于2。\nINDEX(2,4,5,6)等于4。\nINDEX(\"b\",\"b\",\"o\",\"y\")等于1。","name":"INDEX","type":"OTHER"},{"def":"REVERSE(value):返回与value相反的逻辑值。\n示例:\nREVERSE(true)等于false。","name":"REVERSE","type":"LOGIC"},{"def":"REPLACE(text, texttoreplace, replacetext):根据指定字符串,用其他文本来代替原始文本中的内容。\ntext:需要被替换部分字符的文本或单元格引用。\ntexttoreplace:指定的字符串或正则表达式。\nreplacetext:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"abcd\", \"a\", \"re\")等于\"rebcd\"。\nREPLACE(\"a**d\", \"**d\", \"rose\")等于\"arose\"。\nREPLACE(old_text,start_num,num_chars,new_text): 根据指定的字符数,用其他文本串来替换某个文本串中的部分内容。\nOld_text:需要被替换部分字符的文本或单元格引用。\nStart_num:需要用new_text来替换old_text中字符的起始位置。\nNum_chars:需要用new_text来替换old_text中字符的个数。\nNew_text:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"0123456789\",5,4,\"*\")等于“0123*89”。\nREPLACE(\"1980\",3,2,\"99\")等于“1999”。","name":"REPLACE","type":"TEXT"},{"def":"UUID():返回随机的UUID。\n示例:UUID()返回36位随机机器数。\n UUID(32)返回32位随机机器数。","name":"UUID","type":"OTHER"},{"def":"DATESUBDATE(date1, date2, op):返回两个日期之间的时间差。\nop表示返回的时间单位:\n\"s\",以秒为单位。\n\"m\",以分钟为单位。\n\"h\",以小时为单位。\n\"d\",以天为单位。\n\"w\",以周为单位。\n示例:\nDATESUBDATE(\"2008-08-08\", \"2008-06-06\",\"h\")等于1512。","name":"DATESUBDATE","type":"DATETIME"},{"def":"CONCATENATE(text1,text2,...): 将数个字符串合并成一个字符串。\nText1,text2,...:需要合并成单个文本的文本项,可以是字符,数字或是单元格引用。\n示例:\nCONCATENATE(\"Average \",\"Price\")等于“Average Price”。\nCONCATENATE(\"1\",\"2\")等于12。","name":"CONCATENATE","type":"TEXT"},{"def":"filesize(file)获取文件的大小,单位为Kb。\n当file为单文件时,返回文件大小,当file为多文件时,返回文件大小的数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了两个大小分别为100字节和10240字节的文件,则filename(B2)返回值为[0.098, 10.0]。","name":"FILESIZE","type":"OTHER"},{"def":"DAYSOFMONTH(date):返回从1900年1月后某年某月包含的天数。\n示例:\nDAYSOFMONTH(\"1900-02-01\")等于28。\nDAYSOFMONTH(\"2008/04/04\")等于30。","name":"DAYSOFMONTH","type":"DATETIME"},{"def":"DATEINQUARTER(date, number): 函数返回在某一个季度当中第几天的日期。\n示例:\nDATEINQUARTER(\"2009-05-05\", 20)等于 2009-04-20。","name":"DATEINQUARTER","type":"DATETIME"},{"def":"逐层累计, =LAYERTOTAL(B1, C1, D1)等同于=D1[B1:-1] + C1, 如需横向, 则传递第四个参数false.如LAYERTOTAL(B1, C1, D1, false)","name":"LAYERTOTAL","type":"HA"},{"def":"CNMONEY(number,unit)返回人民币大写。\nnumber:需要转换的数值型的数。\nunit:单位,\"s\",\"b\",\"q\",\"w\",\"sw\",\"bw\",\"qw\",\"y\",\"sy\",\"by\",\"qy\",\"wy\"分别代表“拾”,“佰”,“仟”,“万”,“拾万”,“佰万”,“仟万”,“亿”,“拾亿”,“佰亿”,“仟亿”,“万亿”。\n备注:\n 单位可以为空,如果为空,则直接将number转换为人民币大写,否则先将number与单位的进制相乘,然后再将相乘的结果转换为人民币大写。\n示例:\nCNMONEY(1200)等于壹仟贰佰圆整。\nCNMONEY(12.5,\"w\")等于壹拾贰万伍仟圆整。\nCNMONEY(56.3478,\"bw\")等于伍仟陆佰叁拾肆万柒仟捌佰圆整。\nCNMONEY(3.4567,\"y\")等于叁亿肆仟伍佰陆拾柒万圆整。","name":"CNMONEY","type":"TEXT"},{"def":"DAYVALUE(date):返回1900年至 date日期所经历的天数。\n示例:\nDAYVALUE(\"2008/08/08\")等于39668。","name":"DAYVALUE","type":"DATETIME"},{"def":"SQL(connectionName,sql,columnIndex,rowIndex)返回通过sql语句从connectionName中获得数据表的第columnIndex列第rowIndex行所对应的元素。\nconnectionName:数据库库的名字,字符串形式;\nsql:SQL语句,字符串形式;\ncolumnIndex:列序号,整形;\nrowIndex:行序号,整形。\n备注:行序号可以不写,这样返回值为数据列。\n示例:\n以我们提供的数据源HSQL为例\nSQL(\"HSQL\",\"SELECT * FROM CUSTOMER\",2,2)等于王先生。","name":"SQL","type":"REPORT"},{"def":"DATE(year,month,day): 返回一个表示某一特定日期的系列数。\nYear:代表年,可为一到四位数。\nMonth:代表月份。\n若1 month 12,则函数把参数值作为月。\n若month>12,则函数从年的一月份开始往上累加。例如: DATE(2000,25,2)等于2002年1月2日的系列数。\nDay:代表日。\n若日期小于等于某指定月的天数,则函数将此参数值作为日。\n若日期大于某指定月的天数,则函数从指定月份的第一天开始往上累加。若日期大于两个或多个月的总天数,则函数把减去两个月或多个月的余数加到第三或第四个月上,依此类推。例如:DATE(2000,3,35)等于2000年4月4日的系列数。\n备注:\n 若需要处理公式中日期的一部分,如年或月等,则可用此公式。\n 若年,月和日是函数而不是函数中的常量,则此公式最能体现其作用。\n示例:\nDATE(1978, 9, 19) 等于1978-09-19.\nDATE(1211, 12, 1) 等于1211-12-01. ","name":"DATE","type":"DATETIME"},{"def":"BITOPERATIOIN(int,int,op) 位运算,返回两个整数根据op进行位运算后的结果。\nint:十进制整数。\nop:位运算操作符,支持\"&\"(与),\"|\"(或),\"^\"(异或),\"<<\"(左移),\">>\"(右移)。\n示例:\nBITOPERATION(4,2,\"&\")表示4与2进行\"与\"运算,结果等于0。\nBITOPERATION(4,2,\"|\")表示4与2进行\"或\"运算,结果等于6。\nBITOPERATION(4,2,\"^\")表示4与2进行\"异或\"运算,结果等于6。\nBITOPERATION(4,2,\"<<\")表示4按位左移2位,结果等于16。\nBITOPERATION(4,2,\">>\")表示4按位右移2位,结果等于1。\nBITOPERATION(4,2,\"^~\")表示4与2进行\"同或\"运算,结果为-7。","name":"BITOPERATION","type":"LOGIC"},{"def":"LOWER(text): 将所有的大写字母转化为小写字母。\nText:需要转化为小写字母的文本串。LOWER函数不转化文本串中非字母的字符。\n示例:\nLOWER(\"A.M.10:30\")等于“a.m.10:30”。\nLOWER(\"China\")等于“china”。","name":"LOWER","type":"TEXT"},{"def":"CEILING(number): 将参数number沿绝对值增大的方向,舍入为最接近的整数\nNumber:指待舍入的数值。\nCEILING(-2.5)等于-3。\nCEILING(0.5)等于1。","name":"CEILING","type":"MATH"},{"def":"SINH(number):返回某一数字的双曲正弦值。\nnumber:为任意实数。\n示例:\nSINH(1) 等于 1.175201194\nSINH(-1) 等于 -1.175201194","name":"SINH","type":"MATH"},{"def":"AND(logical1,logical2,…): 当所有参数的值为真时,返回TRUE;当任意参数的值为假时,返回FALSE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nAND(1+7=8,5+7=12)等于TRUE。\nAND(1+7=8,5+7=11)等于FALSE。\n如果单元格A1到A4的值分别为TRUE、TRUE、FALSE和TRUE,则:\nAND(A1:A4)等于FALSE。\n如果单元格A5的值在0~50之间,则: AND(0 $A1}) + 1, 默认升序排列, 如需要降序, 则传递参数false,\n =SORT(A1, false)等同于=COUNT(A1[!0]{A1 < $A1}) + 1.","name":"SORT","type":"HA"},{"def":"SIN(number): 计算给定角度的正弦值。\nNumber:待求正弦值的以弧度表示的角度。\n备注:\n 如果参数的单位是度,将其乘以PI()/180即可转换成弧度。\n示例:\nSIN(10)等于-0.5440211108893698。\nSIN(45*PI()/180)等于0.707106781。","name":"SIN","type":"MATH"},{"def":"switch(表达式, 值1, 结果1, 值2, 结果2, ...)\n如果表达式的结果是值1,整个函数返回结果1\n如果表达式的结果是值2,整个函数返回结果2\n如果表达式的结果是值3,整个函数返回结果3\n等等\n","name":"SWITCH","type":"LOGIC"},{"def":"ROW()返回当前单元格的行号,必须使用于条件属性中\n示例:\n如果当前单元格为A5,在A5中写入\"=ROW()\"则返回5。\n如果当前单元格为B8,在B8中写入\"=ROW()\"则返回8。","name":"ROW","type":"REPORT"},{"def":"EVAL(exp)返回表达式exp计算后的结果。\nexp:一个表达式形式字符串。\n备注:\n 只要EVAL中的参数exp最终可以转化成一表达式形式的字符串,比如\"sum(2,4)\",\"2+7\"等等,那么它就可以被计算。\nEVAL(\"2+5\")等于7。\nEVAL(\"count(2,3)\")等于2。\nEVAL(\"sum\"+\"(2,3,5)\")等于10。\nEVAL(IF(true, \"sum\", \"count\") + \"(1,2,3,4)\")等于10。\nEVAL(IF(false, \"sum\", \"count\") + \"(1,2,3,4)\")等于4。","name":"EVAL","type":"OTHER"},{"def":"ATAN(number): 计算指定数值的反正切值。指定数值是返回角度的正切值,返回角度以弧度形式表示。\nNumber:返回角度的正切。\n备注:\n 返回角度在-pi/2到pi/2之间。\n 如果返回角度等于-pi/2或pi/2,ATAN将返回错误信息*NUM!。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nATAN(-1)等于-0.785398163(-pi/4弧度)。\nATAN(0)等于0(弧度)。\nATAN(2)*180/PI()等于63.43494882(度)。","name":"ATAN","type":"MATH"},{"def":"RANGE(from,to,step)函数表示从整数from开始,以step为每一步的大小,直到整数to的一个数字序列。\n例如:\nRANGE(1,5,1)表示从1开始,直到5(包括5),每一步大小为1,那么它返回一个数字序列为[1,2,3,4,5]。\nRANGE(-1,6,2)表示从-1开始,直到6(包括6),每一步大小为2,那么它返回一个数字序列为[-1,1,3,5]。\n备注:RANGE函数有三种参数形式:\n1 RANGE(to),默认的from为1,step为1,例如:\n RANGE(4)返回[1,2,3,4]。\n RANGE(-5)返回[]。\n2 RANGE(from,to),默认的step为1,例如:\n RANGE(-1,3)返回[-1,0,1,2,3]。\n RANGE(0,5)返回[0,1,2,3,4,5]。\n3 RANGE(from,to,step),三个参数的情况参照上面的注释,例如:\n RANGE(6,-1,-2)返回[6,4,2,0]。\n RANGE(4,1,1)返回[]。","name":"RANGE","type":"ARRAY"},{"def":"TANH(number):返回某一数字的双曲正切值。\nnumber:为任意实数。\n双曲正切的计算公式如下:\n示例:\nTANH(-2) 等于 -0.96403\nTANH(0) 等于 0\nTANH(0.5) 等于 0.462117\n","name":"TANH","type":"MATH"},{"def":"ROUNDDOWN(number,num_digits):靠近零值,向下(绝对值减小的方向)舍入数字。\nnumber:为需要向下舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDDOWN 和函数 ROUND 功能相似,不同之处在于函数 ROUNDDOWN 总是向下舍入数字。\n示例:\nROUNDDOWN(3.2, 0) 等于 3\nROUNDDOWN(76.9,0) 等于 76\nROUNDDOWN(3.14159, 3) 等于 3.141\nROUNDDOWN(-3.14159, 1) 等于 -3.1\nROUNDDOWN(31415.92654, -2) 等于 31,400\n","name":"ROUNDDOWN","type":"MATH"},{"def":"循环引用, =CIRCULAR(A1, B1, C1, D1)等同于=IF(&A1 = 1, 0, B1[A1:-1] + C1[A1:-1] – D1[A1:-1]),如需横向, 则传递第五个参数false","name":"CIRCULAR","type":"HA"},{"def":"HOUR(serial_number):返回某一指定时间的小时数。函数指定HOUR为0(0:00)到23(23:00)之间的一个整数。\nSerial_number:包含所求小时的时间。\n示例:\nHOUR(\"11:32:40\")等于11。\nHOUR(\"11:32:40\", \"HH:mm:ss\")等于11。","name":"HOUR","type":"DATETIME"},{"def":"ROUND(number,num_digits):返回某个数字按指定位数舍入后的数字。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND(2.15, 1) 等于 2.2\nROUND(2.149, 1) 等于 2.1\nROUND(-1.475, 2) 等于 -1.48\nROUND(21.5, -1) 等于 20\n因浮点数存在精度计算丢失问题, 导致计算结果里可能带上9999, 0000这些, \n因此加入第三个参数来控制是否需要去除9999. true表示需要过滤9999, 0000这些数据.","name":"ROUND","type":"MATH"},{"def":"YEARDELTA(date, delta):返回指定日期后delta年的日期。\n示例:\nYEARDELTA(\"2008-10-10\",10)等于2018-10-10。","name":"YEARDELTA","type":"DATETIME"},{"def":"DATEINYEAR(date, number):函数返回在一年当中第几天的日期。\n示例:\nDATEINYEAR(2008,100)等于2008-04-09,等价于DATEINYEAR(\"2008-08-08\",100),也返回2008-04-09.\nDATEINYEAR(2008,-1)等于2008-12-31,等价于DATEINYEAR(\"2008-08-08\",-1),也返回2008-12-31.","name":"DATEINYEAR","type":"DATETIME"},{"def":"WEIGHTEDAVERAGE(A1:A4,B1:B4): 返回指定数据的加权平均值。\n加权平均数是不同比重数据的平均数,加权平均数就是把原始数据按照合理的比例来计算。\nA1:A4,B1:B4:用于计算平均值的参数,A1~A4为数据,B1~B4为权值。\n示例:\n如果A1:A4为10,9,8,7,B1:B4为0.2,0.1,0.3,0.4则:\nWEIGHTEDAVERAGE(A1:A4,B1:B4)等于8.1。","name":"WEIGHTEDAVERAGE","type":"MATH"},{"def":"ASIN(number): 返回指定数值的反正弦值。反正弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的正弦值。\n备注:\n 指定数值必须在-1到1之间(含1与-1)。\n 返回角度在-pi/2到pi/2之间(含-pi/2与pi/2)。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nASIN(0.5)等于0.523598776(pi/6弧度)。\nASIN(1)等于1.570796327(pi/2弧度)。\nASIN(0.5)*180/PI()等于30(度)。","name":"ASIN","type":"MATH"},{"def":"INT(number): 返回数字下舍入(数值减小的方向)后最接近的整数值。\nNumber:需要下舍入为整数的实数。\n示例:\nINT(4.8)等于4。\nINT(-4.8)等于-5。\nINT(4.3)等于4。\nINT(-4.3)等于-5。\n公式INT(A1)将返回A1单元格中的一个正实数的整数数部分。","name":"INT","type":"MATH"},{"def":"GETUSERJOBTITLES():返回角色职务\n示例:\nGETUSERDEPARTMENTS():返回角色所有职务,若多个部门职务则返回职务数组","name":"GETUSERJOBTITLES","type":"OTHER"},{"def":"REGEXP(str, pattern):字符串str是否与正则表达式pattern相匹配。\n示例:\nREGEXP(\"aaaaac\",\"a*c\")等于true。\nREGEXP(\"abc\",\"a*c\")等于false。\n\nREGEXP(str, pattern, intNumber):字符串str是否与具有给定模式 intNumber的正则表达式pattern相匹配。\n示例:\nCASE_INSENSITIVE = 0 启用不区分大小写的匹配。 默认情况下,不区分大小写的匹配假定仅匹配 US-ASCII 字符集中的字符。可以通过指 定 UNICODE_CASE 标志连同此标志来启用 Unicode 感知的、不区分大小写的匹配。 \nMULTILINE = 1 启用多行模式。\nDOTALL = 2 启用 dotall 模式。在 dotall 模式中,表达式 . 可以匹配任何字符,包括行结束符。默认情况下,此表达式不匹配行 结束符。\nUNICODE_CASE = 3 启用 Unicode 感知的大小写折叠。指定此标志后,由 CASE_INSENSITIVE 标志启用时,不区分大小写的匹配将以 符合 Unicode Standard 的方式完成。\nCANON_EQ = 4 启用规范等价。 指定此标志后,当且仅当其完整规范分解匹配时,两个字符才可视为匹配。\nUNIX_LINES = 5 启用 Unix 行模式。 在此模式中,.、^ 和 $ 的行为中仅识别 '\\n' 行结束符。\nLITERAL = 6 启用模式的字面值解析。 指定此标志后,指定模式的输入字符串就会作为字面值字符序列来对待。输入序列中的 元字符或转义序列不具有任何特殊意义。 标志 CASE_INSENSITIVE 和 UNICODE_CASE 在与此标志一起使用时将 对匹配产生影响。其他标志都变得多余了。\nCOMMENTS = 7 模式中允许空白和注释。 此模式将忽略空白和在结束行之前以 # 开头的嵌入式注释。\n \nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 3)等于true。\nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 1)等于false。\n\n","name":"REGEXP","type":"TEXT"},{"def":"DAYSOFQUARTER(date): 返回从1900年1月后某年某季度的天数。\n示例:\nDAYSOFQUARTER(\"2009-02-01\")等于90。\nDAYSOFQUARTER(\"2009/05/05\")等于91。","name":"DAYSOFQUARTER","type":"DATETIME"},{"def":"AVERAGE(number1,number2,…,countstring): 返回指定数据的平均值。\nNumber1,number2…:用于计算平均值的参数; countString:文字、逻辑值是否参与计数。\n备注:\n 参数必须是数字,或是含有数字的名称,数组或引用。\n 如果数组或引用参数中含有文字,逻辑值,默认参与计数,countString为false则不参与计数;\n 空单元格始终不参与计数,但是,单元格中的零值参与。\n示例:\n如果A1:A6被命名为“ages”,分别等于10,23,文字,29,33及25,则:\nAVERAGE(A1:A6)等于20。\nAVERAGE(A1:A6, false)等于24。\nAVERAGE(ages)等于20。\n如果还有一个年龄为27的,求所有年龄的平均值为: AVERAGE(A1:A6,27)等于21。","name":"AVERAGE","type":"MATH"},{"def":"RADIANS(angle): 将角度转换成弧度。\nAngle:需要转换为弧度的角度。\n示例:\nRADIANS(90)等于1.570796327(π/2弧度)。","name":"RADIANS","type":"MATH"},{"def":"REMOVEARRAY(array, start, deleteCount):从数组array中删除从第start个元素开始的deleteCount个数组元素,并返回删除后的数组。\n示例:\nREMOVEARRAY([3, 4, 4, 2, 6, 7, 87], 4, 2)返回[3, 4, 4, 7, 87].\n","name":"REMOVEARRAY","type":"ARRAY"},{"def":"WEBIMAGE(path):在web页面上显示指定路径下的图片。","name":"WEBIMAGE","type":"OTHER"},{"def":"WEEK(serial_num):返回一个代表一年中的第几周的数字。\nSerial_num:表示输入的日期。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nWEEK(\"2010/1/1\")等于52。\nWEEK(\"2010/1/6\")等于1。\nWEEK(35796)等于1。","name":"WEEK","type":"DATETIME"},{"def":"filename(file)获取文件的文件名。\n当file为单文件时,返回文件名字符串,当file为多文件时,返回文件名的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.cpt },则filename(B2)返回值为[“A.doc”, “C.xls”, “B.cpt”]。","name":"FILENAME","type":"OTHER"},{"def":"COSH(number): 返回一个数值的双曲线余弦值。\nNumber:需要求其双曲线余弦值的一个实数。\n备注:\n 双曲线余弦值计算公式为: ,其中e是自然对数的底,e=2.71828182845904。\n示例:\nCOSH(3)等于10.06766200。\nCOSH(5)等于74.20994852。\nCOSH(6)等于201.7156361。","name":"COSH","type":"MATH"},{"def":"WEEKDAY(Serial_number):获取日期并返回星期数。返回值为介于0到6之间的某一整数,分别代表星期中的某一天(从星期日到星期六)。\nSerial_number:输入的日期\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n举例:\nWEEKDAY(\"2005/9/10\")等于6(星期六)。\nWEEKDAY(\"2005/9/11\")等于0(星期日)。\nWEEKDAY(35796)等于4(星期四)。\n","name":"WEEKDAY","type":"DATETIME"},{"def":"OR(logical1,logical2,…): 当所有参数的值为假时,返回FALSE;当任意参数的值为真时,返回TRUE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nOR(1+7=9,5+7=11)等于FALSE。\nOR(1+7=8,5+7=11)等于TRUE。","name":"OR","type":"LOGIC"},{"def":"MOD(number,divisor):返回两数相除的余数。结果的正负号与除数相同。\nnumber:为被除数。\ndivisor:为除数。\n示例:\nMOD(3, 2) 等于 1\nMOD(-3, 2) 等于 1\nMOD(3, -2) 等于 -1\nMOD(-3, -2) 等于 -1\n","name":"MOD","type":"MATH"},{"def":"TODAY():获取当前日期。\n示例:\n如果系统日期是2005年9月10日\n则TODAY()等于2005-9-10。","name":"TODAY","type":"DATETIME"},{"def":"ROUNDUP(number,num_digits):远离零值,向上(绝对值增大的方向)舍入数字。\nnumber:为需要向上舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDUP 和函数 ROUND 功能相似,不同之处在于函数 ROUNDUP 总是向上舍入数字。\n示例:\nROUNDUP(3.2,0) 等于 4\nROUNDUP(76.9,0) 等于 77\nROUNDUP(3.14159, 3) 等于 3.142\nROUNDUP(-3.14159, 1) 等于 -3.2\nROUNDUP(31415.92654, -2) 等于 31,500\n\n","name":"ROUNDUP","type":"MATH"},{"def":"ROUND5(number,num_digits):这个是四舍五入,奇进偶不进。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND5(2.125, 2) 等于 2.12\nROUND5(2.135, 2) 等于 2.14\n","name":"ROUND5","type":"MATH"},{"def":"TIME(hour,minute,second): 返回代表指定时间的小数。介于0:00:00(12:00:00 A.M.)与23:59:59(11:59:59 P.M.)之间的时间可返回0到0.99999999之间的对应数值。\nHour:介于0到23之间的数。\nMinute:介于0到59之间的数。\nSecond:介于0到59之间的数。\n示例:\nTIME(14,40,0)等于2:40 PM。\nTIME(19,43,24)等于7:43 PM。","name":"TIME","type":"DATETIME"},{"def":"环比公式, =MOM(A1, B1)等同于=IF(&A1 > 1, B1 / B1[A1:-1],0), 其中如果需要指定偏移量x, 则传递第三个参数x, 第四个参数表示横纵向.\n如=MOM(A1, B1, -2, false)等同于=IF(&A1 > 1, B1 / B1[;A1:-2], 0)","name":"MOM","type":"HA"},{"def":"ASINH(number): 返回指定数值的反双曲正弦值。反双曲正弦值的双曲正弦等于指定数值。即: ASINH(SINH(number))=number。\nNumber:任意实数。\n示例:\nASINH(-5)等于-2.312438341。\nASINH(8)等于2.776472281。\nASINH(16)等于3.466711038。","name":"ASINH","type":"MATH"},{"def":"EENNUMBER(value):将给定的BigDecimal类型的数字(100以内)取整后转化成英文金额的字符串。\n示例:\nENNUMBER(23.49)等于TWENTY THREE。\n注:若出现结果为空,需要将数字强制转换为BigDecimal类型,例如:ENNUMBER(TOBIGDECIMAL(80))","name":"ENNUMBER","type":"TEXT"},{"def":"CODE(text): 计算文本串中第一个字符的数字代码。返回的代码对应于计算机使用的字符集。\nText:需要计算第一个字符代码的文本或单元格引用。\n示例:\nCODE(\"S\")等于83。\nCODE(\"Spreadsheet\")等于83。","name":"CODE","type":"TEXT"},{"def":"DEGREES(angle): 将弧度转化为度。\nangle:待转换的弧度角。\n示例:\nDEGREES(PI()/2)等于90。\nDEGREES(3.1415926)等于179.9999969。","name":"DEGREES","type":"MATH"},{"def":"LEN(args): 返回文本串中的字符数或者数组的长度。\n需要注意的是:参数args为文本串时,空格也计为字符。\n参数args为数组时,直接返回数组长度。\n示例:\nLEN(\"Evermore software\")等于17。\nLEN(\" \")等于1。\nLEN(['a','b'])等于2。\n","name":"LEN","type":"TEXT"},{"def":"DATETIME():获取当前日期和时间。\n示例:\n如果系统时间是2005年9月10日 15点18分38秒\n则DATETIME()等于2005-9-10 15:18:36。","name":"DATETIME","type":"DELETE"},{"def":"UNIQUEARRAY(array):去掉数组array中的重复元素。\n示例:\nUNIQUEARRAY([14, 2, 3, 4, 3, 2, 5, 6, 2, 7, 9, 12, 3])返回[14, 2, 3, 4, 5, 6, 7, 9, 12].","name":"UNIQUEARRAY","type":"ARRAY"},{"def":"PROMOTION(value1,value2):返回value2在value1上提升的比例。\n示例:\nPROMOTION(12, 14)等于0.166666666,即提升了16.6666666%.\nPROMOTION(-12, 14)等于2.166666666,即提升了216.6666666%.","name":"PROMOTION","type":"MATH"},{"def":"PI(number): 是一个数学常量函数,当number为空时,函数返回精确到15位的数值3.141592653589793;当参数不为空时,number表示PI的倍数。\n示例:\nSIN(PI()/2)等于1。\n计算圆的面积的公式: S=PI()*(r^2),其中S为圆的面积,R为圆的半径。\nPI(3)等于9.42477796076938。","name":"PI","type":"MATH"},{"def":"ISNULL(object):判断对象中所有的值是否全部都是NULL或者为空字符串。","name":"ISNULL","type":"OTHER"},{"def":"LET(变量名,变量值,变量名,变量值,..., 表达式):局部变量赋值函数,参数的个数N必须为奇数, 最后一个是表达式,前面是N-1(偶数)为局部变量赋值对。\n变量名: 必须是合法的变量名,以字母开头,可以包括字母,数字和下划线\n表达式: 根据前面的N-1个参数赋值后计算出来的结果,这些变量赋值只在这个表达式内部有效\n示例:\nLET(a, 5,b, 6, a+b)等于11\n","name":"LET","type":"OTHER"},{"def":"SECOND(serial_number):返回某一指定时间的秒数,其值是介于0与59之间的一个整数。\nSerial_number:包含所求秒数的时间。\n示例:\nSECOND(\"15:36:25\")等于25。\nSECOND(\"15:36:25\", \"HH:mm:ss\")等于25。","name":"SECOND","type":"DATETIME"},{"def":"EXP(number): 返回e的n次幂。常数e为自然对数的底数,等于2.71828182845904。\nNumber:为任意实数,作为常数e的指数。\n备注:\n 如果要返回其他常数作为底数的幂,可以使用指数运算符(^)。例如: 在4^2中,4是底数,而2是指数。\n EXP函数与LN函数互为反函数。\n示例:\nEXP(0)等于1。\nEXP(3)等于20.08553692。\nEXP(LN(2))等于2。","name":"EXP","type":"MATH"},{"def":"treelayer(TreeObject, Int, Boolean, String):\n返回tree对象第n层的值,并且可以设置返回值类型及分隔符。\nTreeObject:tree对象,如$tree。\nInt:想要获得层级的数值,最上层为1,第二层为2,依此类推,若无则返回最底层\n。Boolean:返回值类型为字符串还是数组,默认false,返回数组;为true时返回字符串。\nString:当Boolean为true返回字符串时的分隔符,以双引号表示,默认为逗号\",\",如\";\"。\n示例:\n假设$tree勾选的值为中国-江苏-南京,中国-浙江-杭州,则treelayer($tree, true, ”\\’,\\’”):返回”’,’”分割的所选中节点字符串”南京’,’杭州”treelayer($tree, 2):以数组形式返回第二层[“江苏”,”浙江”]。treelayer($tree, 2, true, ”\\’,\\’”):返回”’,’”分割的字符串江苏’,’浙江。","name":"TREELAYER","type":"OTHER"},{"def":"读取配置文件","name":"TOTEXT","type":"DELETE"}]; +BI.FormulaJson = [{def: "MONTH:(serial_number)返回日期中的月。月是介于1和12之间的一个数。\nSerial_number:含有所求的月的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nMONTH(\"2000/1/1\")等于1。\nMONTH(\"2006/05/05\")等于5。\nMONTH(\"1997/04/20\")等于4。\nMONTH(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nMONTH(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nMONTH(\"1997-04-20\", \"yyyy-MM-dd\")等于4。\nMONTH(35796)等于1。", name: "MONTH", type: "DATETIME"}, {def: "ROWCOUNT(tableData)返回tableData的行数。\ntableData:TableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是tableData的行数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nROWCOUNT(\"ds1\")等于20。", name: "ROWCOUNT", type: "REPORT"}, {def: "RAND(): 返回均匀分布的随机数。每计算一次工作表,函数都会返回一个新的随机数值。\n备注:\n 要生成一个位于a和b之间的随机数,可以使用以下的公式: C=RAND()*(b-a)+a。\n 如果要使一个随机产生的数值不随单元格的重计算而改变,可以在编辑框中输入=RAND()并保持编辑状态,然后按F9,将公式永久性地改为随机数。\n示例:\n假如需要生成一个大于等于0,小于60的随机数,使用公式: =RAND()*60。\n假如需要生成一个大于等于0,小于19的随机数,使用公式: =RAND()*19。\n假如需要生成一个大于等于0,小于50的随机数,使用公式: =RAND()*50。", name: "RAND", type: "MATH"}, {def: "GETUSERDEPARTMENTS():返回角色部门\n示例:\nGETUSERDEPARTMENTS():返回角色所有部门,若多个部门则数组\nGETUSERDEPARTMENTS(3,2):返回角色该部门的第三层和第二层名字,\n若多个部门则返回数组,若没有第三层则只显示第二层", name: "GETUSERDEPARTMENTS", type: "OTHER"}, {def: "FORMAT(object,format) : 返回object的format格式。\nobject 需要被格式化对象,可以是String,数字,Object(常用的有Date, Time)。\nformat 格式化的样式。\n示例\nFORMAT(1234.5, \"#,##0.00\") => 1234.50\nFORMAT(1234.5, \"#,##0\") => 1234\nFORMAT(1234.5, \"¥#,##0.00\") => ¥1234.50\nFORMAT(1.5, \"0%\") => 150%\nFORMAT(1.5, \"0.000%\") => 150.000%\nFORMAT(6789, \"##0.0E0\") => 6.789E3\nFORMAT(6789, \"0.00E00\") => 6.79E03\nFORMAT(date(2007,1,1), \"EEEEE, MMMMM dd, yyyy\") => 星期一,一月 01,2007\nFORMAT(date(2007,1,13), \"MM/dd/yyyy\") => 01/13/2007\nFORMAT(date(2007,1,13), \"M-d-yy\") => 1-13-07\nFORMAT(time(16,23,56), \"h:mm:ss a\") => 4:23:56 下午", name: "FORMAT", type: "TEXT"}, {def: "TRIM(text): 清除文本中所有空格,单词间的单个空格除外,也可用于带有不规则空格的文本。\nText:需要清除空格的文本。\n示例:\nTRIM(\" Monthly Report\")等于Monthly Report。", name: "TRIM", type: "TEXT"}, {def: "SQRT(number): 返回一个正数的平方根。\nNumber:要求其平方根的任一正数。\n备注:\nNumber必须是一个正数,否则函数返回错误信息*NUM!。\n示例:\nSQRT(64)等于8。\nSQRT(-64)返回*NUM!。", name: "SQRT", type: "MATH"}, {def: "DAYSOFYEAR(year):返回某年包含的天数。\n示例:\nDAYSOFYEAR(2008)等于365,等价于DAYSOFYEAR(\"2008-01-01\")。", name: "DAYSOFYEAR", type: "DATETIME"}, {def: "RANK(number,ref,order): 返回一个数在一个数组中的秩。(如果把这个数组排序,该数的秩即为它在数组中的序号。)\nNumber 所求秩的数。(可以是Boolean型,true=1,false=0)\nRef 可以是数组,引用,或一系列数,非实数的值被忽略处理(接受Boolean型,true=1,false=0)。\nOrder 指定求秩的参数,非零为升序,零为降序\n\n备注\n1. RANK对重复的数返回相同的秩,但重复的数影响后面的数的秩,比如,在一组升序排列的整数中,如果5出现了2次,并且秩为3,那么6的秩为5 (没有数的秩是4).\n\n示例\nA1:A5 = 6, 4.5, 4.5, 2, 4\nRANK(A1,A1:A5,1) 即 6 的秩为 5.\n\nRANK(3,1,2,\"go\",3,4,1) = 3, \"go\"被忽略。", name: "RANK", type: "OTHER"}, {def: "ODD(number):返回对指定数值进行舍入后的奇数。\nnumber:是要舍入求奇的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是奇数,则不须进行任何舍入处理。\n示例:\nODD(1.5) 等于 3\nODD(3) 等于 3\nODD(2) 等于 3\nODD(-1) 等于 -1", name: "ODD", type: "MATH"}, {def: "COLCOUNT(tableData):返回tableData中列的个数。\ntableData:tableData的名字,字符串形式的。\n备注:\n 先从私有数据源中查找,然后再从公有数据源中查找,返回的是第一个查找到的tableData中列数。\n示例:\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nCOLCOUNT(\"ds1\")等于6。\n", name: "COLCOUNT", type: "REPORT"}, {def: "ENDWITH(str1,str2):判断字符串str1是否以str2结束。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nENDWITH(\"FineReport\",\"Report\")等于true。\nENDWITH(\"FineReport\",\"Fine\")等于false。\nENDWITH(\"FineReport\",\"report\")等于false。", name: "ENDWITH", type: "TEXT"}, {def: "LOG10(number):返回以 10 为底的对数。\nnumber: 用于常用对数计算的正实数。\n示例:\nLOG10(86) 等于 1.934498451\nLOG10(10) 等于 1\nLOG10(1E5) 等于 5\n", name: "LOG10", type: "MATH"}, {def: "MAPARRAY(array, fn):把一个数组中的项目转换到另一个数组中。\narray (Array): 要转换的数组 \nfn (Function): 处理数组项目的函数 \n示例:\nMAPARRAY([3,4,2,3,6,8,7], item != 3)等于[false,true,true,false,true,true,true].", name: "MAPARRAY", type: "ARRAY"}, {def: "FLOOR(number): 将参数number沿绝对值减小的方向去尾舍入。\nNumber:待舍入的数值。\n示例:\nFLOOR(-2.5)等于-2。\nFLOOR(2.5)等于2。\n", name: "FLOOR", type: "MATH"}, {def: "NUMTO(number,bool)或NUMTO(number):返回number的中文表示。其中bool用于选择中文表示的方式,当没有bool时采用默认方式显示。\n示例:NUMTO(2345,true)等于二三四五。\n示例:NUMTO(2345,false)等于二千三百四十五。\n示例:NUMTO(2345)等于二千三百四十五。", name: "NUMTO", type: "TEXT"}, {def: "ATANH(number): 返回数字的反双曲正切值,该函数的参数值即为反双曲正切值的双曲正切值。\nNumber:指介于-1~1之间的任意实数。\n备注:\n 指定的number必须介于-1~1之间(不包括-1,1)。\n ATANH(TANH(number))=number,例如,ATANH(TANH(8))=8。\n示例:\nATANH(-0.5)等于-0.549306144。\nATANH(0)等于0。\nATANH(0.7)等于0.867300528。", name: "ATANH", type: "MATH"}, {def: "YEAR:(serial_number)返回日期中的年。Year是介于1900和9999之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nYEAR(\"2000/1/1\")等于2000。\nYEAR(\"2006/05/05\")等于2006。\nYEAR(\"1997/04/20\")等于1997。\nYEAR(\"2000-1-1\", \"yyyy-MM-dd\")等于2000。\nYEAR(\"2006-05-05\", \"yyyy-MM-dd\")等于2006。\nYEAR(\"1997-04-20\", \"yyyy-MM-dd\")等于1997。\nYEAR(35796)等于1998。", name: "YEAR", type: "DATETIME"}, {def: "SLICEARRAY(array, start, end):返回数组从第start个到第end个元素(包括第end个元素)。\n示例:\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3, 6)返回[4, 5, 1, 5].\n当不使用end参数时,返回从start开始到数组结束之间的元素。\nSLICEARRAY([3, 4, 4, 5, 1, 5, 7], 3)返回[4, 5, 1, 5, 7].", name: "SLICEARRAY", type: "ARRAY"}, {def: "", name: "DECODE", type: "OTHER"}, {def: "ENMONEY(value):将给定的BigDemical类型的数字转换成英文金额字符串。\n示例:\nENMONEY(23.49)等于TWENTY THREE AND CENTS FORTY NINE", name: "ENMONEY", type: "TEXT"}, {def: "IF(boolean,number1/string1,number2/string2):判断函数,boolean为true时返回第二个参数,为false时返回第三个。\nboolean: 用于判断的布尔值,true或者false。\nnumber1/string1: 第一个参数,如果boolean为ture,返回这个值。\nnumber2/string2: 第二个参数,如果boolean为false,返回这个值。\n示例:\nIF(true,2,8)等于2\nIF(false,\"first\",\"second\")等于second\nIF(true,\"first\",7)等于first", name: "IF", type: "LOGIC"}, {def: "DATEINWEEK(date, number):函数返回在某一个星期当中第几天的日期。\n示例:\ndateInWeek(\"2008-08-28\", 2)等于2008-08-26。\ndateInWeek(\"2008-08-28\", -1)等于2008-08-31。\n如果最后一个参数为-1,返回该日期所在星期的最后一天\n", name: "DATEINWEEK", type: "DATETIME"}, {def: "MONTHDELTA(date,delta):返回指定日期date后delta个月的日期。\n示例:\nMONTHDELTA(\"2008-08-08\", 4)等于2008-12-08。", name: "MONTHDELTA", type: "DATETIME"}, {def: "FIELDS(connectionName,tableName):返回tableName这个表中的所有字段名。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么FIELDS(\"BASE\",\"task\")等于[name,start,end].", name: "FIELDS", type: "REPORT"}, {def: "DATEDIF(start_date,end_date,unit):返回两个指定日期间的天数、月数或年数。\nStart_date:代表所指定时间段的初始日期。\nEnd_date:代表所指定时间段的终止日期。\nUnit:函数返回信息的类型。\n若unit=“Y”,则DATEDIF返回指定时间段的年差数。\n若unit=“M”,则DATEDIF返回指定时间段的月差数。\n若unit=“D”,则DATEDIF返回指定时间段的日差数。\n若unit=“MD”,则DATEDIF忽略年和月,返回指定时间段的日差数。\n若unit=“YM”,则DATEDIF忽略年和日,返回指定时间段的月差数。\n若unit=“YD”,则DATEDIF忽略年,返回指定时间段的日差数。\n示例:\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"Y\")等于3,即在2001年2月28日与2004年3月20日之间有3个整年。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"M\")等于37,即在2001年2月28日与2004年3月20日之间有36个整月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"D\")等于1116,即在2001年2月28日与2004年3月20日之间有1116个整天。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"MD\")等于8,即忽略月和年后,2001年2月28日与2004年3月20日的差为8天。\nDATEDIF(\"2001/1/28\",\"2004/3/20\",\"YM\")等于2,即忽略日和年后,2001年1月28日与2004年3月20日的差为2个月。\nDATEDIF(\"2001/2/28\",\"2004/3/20\",\"YD\")等于21,即忽略年后,2001年2月28日与2004年3月20日的差为21天。", name: "DATEDIF", type: "DATETIME"}, {def: "TOIMAGE(path):显示指定路径下的图片。此处默认开启了图片缓存功能以加速报表的生成.\n如不需要缓存,请在参数后面追加值FALSE,例如:TOIMAGE(\"D:/fr.png\",false).\n如需要指定图片大小,拉伸显示, 则需要添加参数,TOIMAGE(patch, true, width, height).\n示例:=toimage(\"d:/1.jpg\", true, \"50%\", 300), 第三个参数为指定宽度, 第四个参数为指定高度.\n如果参数为整数, 则直接写数字, 如果为百分比, 则需要加上引号, 如\"300%\"", name: "TOIMAGE", type: "OTHER"}, {def: "LEFT(text,num_chars): 根据指定的字符数返回文本串中的第一个或前几个字符。\nText:包含需要选取字符的文本串或单元格引用。\nNum_chars:指定返回的字符串长度。\n备注:\n Num_chars的值必须等于或大于0。\n 如果num_chars大于整个文本的长度,LEFT函数将返回所有的文本。\n 如果省略num_chars,则默认值为1。\n示例:\nLEFT(\"Fine software\",8)等于“Fine sof”。\nLEFT(\"Fine software\")等于“F”。\n如果单元格A3中含有“China”,则LEFT(A3,2)等于“Ch”。", name: "LEFT", type: "TEXT"}, {def: "SUBSTITUTE(text,old_text,new_text,instance_num): 用new_text替换文本串中的old_text。\nText:需要被替换字符的文本,或含有文本的单元格引用。\nOld_text:需要被替换的部分文本。\nNew_text:用于替换old_text的文本。\nInstance_num:指定用new_text来替换第几次出现的old_text。如果指定了instance_num,则只有指定位置上的old_text被替换,否则文字串中出现的所有old_text都被new_text替换。\n备注:\n 如果需要替换文本串中的指定文本,则使用SUBSTITUTE函数;如果需要替换文本串中指定位置上的任意文本,则使用REPLACE函数。\n示例:\nSUBSTITUTE(\"data base\",\"base\",\"model\")等于“data model”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",1)等于“July 18, 2000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\")等于“July 18, 1000”。\nSUBSTITUTE(\"July 28, 2000\",\"2\",\"1\",2)等于“July 28, 1000”。 ", name: "SUBSTITUTE", type: "TEXT"}, {def: "LOG(number,base): 按指定的任意底数,返回数值的对数。\nNumber:需要求对数的正实数。\nBase:对数的底数。如果省略底数,默认值为10。\n示例:\nLOG(16,2)等于4。\nLOG(10)等于1。\nLOG(24,3)等于2.892789261。", name: "LOG", type: "MATH"}, {def: "SORTARRAY(array):返回数组array排过序的数组。\n示例:\nSORTARRAY([3, 4, 4, 5, 1, 5, 7])返回[1, 3, 4, 4, 5, 5, 7].\n注意:数组array的元素类型必须一样,并且要可比较。", name: "SORTARRAY", type: "ARRAY"}, {def: "DATEDELTA(date, deltadays):返回一个日期??date后deltadays的日期。\ndeltaDays可以为正值,负值,零。\n示例:\nDATEDELTA(\"2008-08-08\", -10)等于2008-07-29。\nDATEDELTA(\"2008-08-08\", 10)等于2008-08-18。", name: "DATEDELTA", type: "DATETIME"}, {def: "MID(text,start_num,num_chars): 返回文本串中从指定位置开始的一定数目的字符,该数目由用户指定。\nText:包含要提取字符的文本串。\nStart_num:文本中需要提取字符的起始位置。文本中第一个字符的start_num为1,依此类推。\nNum_chars:返回字符的长度。\n备注:\n 如果start_num大于文本长度,MID函数返回“”(空文本)。\n 如果start_num小于文本长度,并且start_num加上num_chars大于文本长度,MID函数将从start_num指定的起始字符直至文本末的所有字符。\n 如果start_num小于1,MID函数返回错误信息*VALUE!。\n 如果num_chars是负数,MID函数返回错误信息*VALUE!。\n示例:\nMID(\"Finemore software\",10,8)返回“software”。\nMID(\"Finemore software\",30,5)返回“”(空文本)。\nMID(\"Finemore software\",0,8)返回*VALUE!。\nMID(\"Finemore software\",5,-1)返回*VALUE!。", name: "MID", type: "TEXT"}, {def: "ATAN2(x_num,y_num): 返回x、y坐标的反正切值。返回角度为x轴与过(x_num,y_num)与坐标原点(0,0)的一条直线形成的角度。该角度以弧度显示。\nX_num:指定点的x坐标。\nY_num:指定点的y坐标。\n备注:\n 正值表示从x轴开始以逆时针方式所得的角度;负值表示从x轴开始以顺时针方式所得的角度。\na > 0,b > 0 or a > 0, b < 0时,公式直接成立;\na < 0,b > 0, ATAN2(a,b)=PI()-ABS(ATAN(b/a))\na < 0,b < 0, ATAN2(a,b)=ABS(ATAN(b/a))-PI()\n 当x_num与y_num都为0时,ATAN2返回错误信息*DIV/0!。\n 用角度制显示返回数值时,把返回数值乘以180/PI()。\n 返回值以弧度表示(返回值大于-pi且小于等于pi)。\n示例:\nATAN2(-2,2)等于2.356194490192345(弧度制的3*pi/4)。\nATAN2(2,2)等于0.785398163(弧度制的pi/4)。\nATAN2(-2,2)*180/PI()等于135(角度制)。", name: "ATAN2", type: "MATH"}, {def: "SUM(number1,number2,…): 求一个指定单元格区域中所有数字之和。\nNumber1,number2,…:1到30个参数或指定单元格区域中所有数字。\n备注:\n 函数将直接键入参数中的数值、逻辑值及文本表达式计算在内。\n 若参数是数组或引用,则只有数组或单元格引用中的数值进行计算。\n示例:\nSUM(70,80)等于150。\nSUM(\"70\",80,TRUE)等于151,逻辑值“TRUE”作为1来计算;“FALSE”作为0计算;文本“70”作为70来计算。", name: "SUM", type: "MATH"}, {def: "EXACT(text1,text2): 检测两组文本是否相同。如果完全相同,EXACT函数返回TRUE;否则,返回FALSE。EXACT函数可以区分大小写,但忽略格式的不同。同时也可以利用EXACT函数来检测输入文档的文字。\nText1:需要比较的第一组文本。\nText2:需要比较的第二组文本。\n示例:\nEXACT(\"Spreadsheet\",\"Spreadsheet\")等于TRUE。\nEXACT(\"Spreadsheet\",\"S preadsheet\")等于FALSE。\nEXACT(\"Spreadsheet\",\"spreadsheet\")等于FALSE。", name: "EXACT", type: "TEXT"}, {def: "TOINTEGER(text): 将文本转换成Integer对象。\nText:需要转换的文本。\n示例:\nTOINTEGER(\"123\")等于 new Integer(123)。", name: "TOINTEGER", type: "TEXT"}, {def: "ACOSH(number): 返回给定数值的反双曲余弦。\nNumber:返回值的双曲余弦。\n备注:\n 参数number的值必须大于或等于1。\n ACOSH(COSH(number))=number。\n示例:\nACOSH(1)等于0。\nACOSH(8)等于2.768659383。\nACOSH(5.5)等于2.389526435。", name: "ACOSH", type: "MATH"}, {def: "weekdate(year,month,weekOfMonth,dayOfWeek): 返回指定年月的指定周的周几的具体日期。\n示例:\nweekdate(2009,10,2,1)\n返回的是2009年的10月的第二个周的第一天即星期天的日期,返回的是2009-10-04\n最后一个参数dayOfWeek为-1时,表示这个周的最后一天\n示例:\nweekdate(2009,12,1,-1)\n返回的是2009年的12月的第一个周的最后一天即星期六的日期,返回的是2009-12-05\n", name: "WEEKDATE", type: "DATETIME"}, {def: "MIN(number1,number2,…): 返回参数列表中的最小值。\nNumber1,number2,…:1到30个需要找出最小值的参数。\n备注:\n 若参数中没有数字,函数MIN将返回0。\n 参数应为数字、空白单元格、逻辑值或是表示数值的文本串。如果参数是错误值时,MIN将返回错误信息。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n示例:\n如果B1:B4包含3,6,9,12,则:\nMIN(B1:B4)等于3。\nMIN(B1:B4,0)等于0。", name: "MIN", type: "MATH"}, {def: "STARTWITH(str1,str2):判断字符串str1是否以str2开始。\n备注:\n str1和str2都是大小写敏感的。\n示例:\nSTARTWITH(\"FineReport\",\"Fine\")等于true。\nSTARTWITH(\"FineReport\",\"Report\")等于false。\nSTARTWITH(\"FineReport\",\"fine\")等于false。", name: "STARTWITH", type: "TEXT"}, {def: "COMBIN(number,number_chosen): 返回若干个指定对象的组合数。该函数与数学表达式为Cnk功能相同。\nNumber或数学表达式中的“n”指对象总数。\nNumber_chosen或数学表达式中的“k”指在对象总数中某一组合的数量。\n备注:\n Number必须是正整数,number_chosen必须是非负整数。\n 如果number和number_chosen小于0或number小于number_chosen,函数返回错误信息*NUM!。\n 对象组合是对象的子集。与排列不同的是,组合不涉及对象内部的先后顺序,而顺序对排列是非常重要的。\n 假设number=n,number_chosen=k,则: COMBIN(n,k)=Cnk=n!/(k!(n-k)!)。\n示例:\nCOMBIN(5,6)等于*NUM!。\nCOMBIN(5,2)等于10。", name: "COMBIN", type: "MATH"}, {def: "EVEN(number):返回沿绝对值增大方向取整后最接近的偶数。使用该函数可以处理那些成对出现的对象。\nnumber:所要取整的数值。\n不论正负号如何,数值都朝着远离 0 的方向舍入。如果 number 恰好是偶数,则不须进行任何舍入处理。\n示例:\nEVEN(1.5) 等于 2\nEVEN(3) 等于 4\nEVEN(2) 等于 2\nEVEN(-1) 等于 -2", name: "EVEN", type: "MATH"}, {def: "COUNT(value1,value2,…): 计算数组或数据区域中所含项的个数。\nValue1,value2,…:可包含任何类型数据的参数。", name: "COUNT", type: "MATH"}, {def: "INDEXOFARRAY(array, index):返回数组array的第index个元素。\n示例:\nINDEXOFARRAY([\"第一个\", \"第二个\", \"第三个\"], 2)返回\"第二个\"。", name: "INDEXOFARRAY", type: "ARRAY"}, {def: "MAP(object, string, int, int):四个参数分别是索引值,数据集的名字,索引值所在列序号,返回值所在列序号。\n提醒:后两个参数也可以写列名代替。\n根据数据集的名字,找到对应的数据集,找到其中索引列的值为key所对应的返回值。\n数据集的查找方式是依次从报表数据集找到服务器数据集。\n索引列序号与返回值序列号的初始值为1示例:\nMAP(1001, \"employee\", 1, 2)返回employee数据集,第1列中值为1001那条记录中第2列的值。\nMAP(1001, \"employee\", \"name\", \"address\")返回employee数据集,name列中值为1001那条记录中address列的值。", name: "MAP", type: "REPORT"}, {def: "SEQ(): 返回数值,在整个报表执行过程中,返回该函数被第几次执行了。\n示例:\nSEQ()在第一次执行时,结果为1。\nSEQ()在第二次执行时,结果为2。", name: "SEQ", type: "OTHER"}, {def: "i18n为本软件内置的国际化公式,可以对一些常用的词语进行国际化.\n示例:i18n('File'), 则会在中文语言环境下显示为: 文件, 而在英文语言环境下显示为: File", name: "I18N", type: "REPORT"}, {def: "层次坐标简写, 等同于=A1[A1:-1], 若需=B1[A1:-1]则HIERARCHY(A1, B1).\n若为横向, 偏移量为-2, 则写成HIERARCHY(A1, B1, -2, false), 等同于=B1[;A1:-1].\n公式中最后一个参数表示横纵向, 默认不传递, 表示纵向扩展, 若横向扩展, 则需要加上最后一个参数FALSE来区分. ", name: "HIERARCHY", type: "HA"}, {def: "", name: "ENCODE", type: "OTHER"}, {def: "DATEINMONTH(date, number):函数返回在某一个月当中第几天的日期。\n示例:\nDATEINMONTH(\"2008-08-08\", 20) 等于2008-08-20。\nDATEINMONTH(\"2008-08-08\", -1) 等于2008-08-31。", name: "DATEINMONTH", type: "DATETIME"}, {def: "TOOCTAL(int): 将一个十进制整型数转换成八进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOOCTAL(10)等于 \"12\"。\nTOOCTAL(20)等于 \"24\"。", name: "TOOCTAL", type: "MATH"}, {def: "REPEAT(text,number_times): 根据指定的次数重复显示文本。REPEAT函数可用来显示同一字符串,并对单元格进行填充。\nText:需要重复显示的文本或包含文本的单元格引用。\nNumber_times:指定文本重复的次数,且为正数。如果number_times为0,REPEAT函数将返回“”(空文本)。如果number_times不是整数,将被取整。REPEAT函数的最终结果通常不大于32767个字符。\n备注:\n 该函数可被用于在工作表中创建简单的直方图。\n示例:\nREPEAT(\"$\",4)等于“$$$$”。\n如果单元格B10的内容为“你好”,REPEAT(B10,3)等于“你好你好你好”。", name: "REPEAT", type: "TEXT"}, {def: "GREPARRAY(array,fn):函数(返回true或者false)是条件,过滤此数组,最后形成一个新数组。\n示例:\nGREPARRAY([3,4,2,3,6,8,7], item != 3)等于[4,2,6,8,7].\n", name: "GREPARRAY", type: "ARRAY"}, {def: "MAX(number1,number2,…): 返回参数列表中的最大值。\nNumber1,number2,…:1到30个需要找出最大值的参数。\n备注:\n 参数可以是数字、空白单元格、逻辑值或数字的文本表达式。\n 如果数组或引用参数中包含可解析文本值,逻辑值,零值或空白单元格,这些值都将参与计算,而不可解析的文本值忽略不计。\n 如果参数中没有任何数字,MAX将返回0。\n示例:\nMAX(0.1,0,1.2)等于1.2。", name: "MAX", type: "MATH"}, {def: "CHAR(number): 根据指定数字返回对应的字符。CHAR函数可将计算机其他类型的数字代码转换为字符。\nNumber:用于指定字符的数字,介于1~65535之间(包括1和65535)。\n示例:\nCHAR(88)等于“X”。\nCHAR(45)等于“-”。", name: "CHAR", type: "TEXT"}, {def: "TRUNC(number,num_digits):将数字的小数部分截去,返回整数。\nnumber:需要截尾取整的数字。\nnum_digits:用于指定取整精度的数字。\n示例:\nTRUNC(8.9) 等于 8\nTRUNC(-8.9) 等于 -8\nTRUNC(PI()) 等于 3\n", name: "TRUNC", type: "MATH"}, {def: "FACT(number):返回数的阶乘,一个数的阶乘等于 1*2*3*...*该数。\nnumber:要计算其阶乘的非负数。如果输入的 number 不是整数,则截尾取整。\n示例:\nFACT(1) 等于 1\nFACT(1.9) 等于 FACT(1) 等于 1\nFACT(0) 等于 1\nFACT(5) 等于 1*2*3*4*5 等于 120\n", name: "FACT", type: "MATH"}, {def: "STDEV(array1): 计算数据系列的标准偏差(与Excel的同名函数作用相同)。\n\n示例:\nSTDEV([1,2,3])=1。\n", name: "STDEV", type: "OTHER"}, {def: "SPLIT(String1,String2):返回由String2分割String1组成的字符串数组。\nString1:以双引号表示的字符串。\nString2:以双引号表示的分隔符。例如逗号\",\"\n示例:\nSPLIT(\"hello,world,yes\",\",\") = [\"hello\",\"world\",\"yes\"]。\nSPLIT(\"this is very good\",\" \") = [\"this\",\"is\",\"very\",\"good\"]。\n备注:\n如果只有一个参数,则返回一个错误。\n如果有多个参数,则只有前两个起作用。", name: "SPLIT", type: "TEXT"}, {def: "INARRAY(co, array):返回co在数组array中的位置,如果co不在array中,则返回0.\n示例:\nString[] arr = {\"a\",\"b\",\"c\",\"d\"}\n那么INARRAY(\"b\", arr)等于2.", name: "INARRAY", type: "ARRAY"}, {def: "REVERSEARRAY(array):返回数组array的倒序数组。\n示例:\nREVERSEARRAY([\"第一个\", \"第二个\", \"第三个\"])返回[\"第三个\", \"第二个\", \"第一个\"].", name: "REVERSEARRAY", type: "ARRAY"}, {def: "RANDBETWEEN(value1,value2):返回value1和value2之间的一个随机整数。\n示例:\nRANDBETWEEN(12.333, 13.233)只会返回13。\nRANDBETWEEN(11.2, 13.3)有可能返回12或者13。", name: "RANDBETWEEN", type: "MATH"}, {def: "UPPER(text): 将文本中所有的字符转化为大写。\nText:需要转化为大写字符的文本,或是包含文本的单元格引用。\n示例:\nUPPER(\"notes\")等于“NOTES”。\n如果单元格E5的值为“Examples”,则UPPER(E5)等于“EXAMPLES”。", name: "UPPER", type: "TEXT"}, {def: "ABS(number): 返回指定数字的绝对值。绝对值是指没有正负符号的数值。\nNumber:需要求出绝对值的任意实数。\n示例:\nABS(-1.5)等于1.5。\nABS(0)等于0。\nABS(2.5)等于2.5。", name: "ABS", type: "MATH"}, {def: "RIGHT(text,num_chars): 根据指定的字符数从右开始返回文本串中的最后一个或几个字符。\nText:包含需要提取字符的文本串或单元格引用。\nNum_chars:指定RIGHT函数从文本串中提取的字符数。Num_chars不能小于0。如果num_chars大于文本串长度,RIGHT函数将返回整个文本。如果不指定num_chars,则默认值为1。\n示例:\nRIGHT(\"It is interesting\",6)等于“esting”。\nRIGHT(\"Share Holder\")等于“r”。\nRIGHT(\"Huge sale\",4)等于“sale”。", name: "RIGHT", type: "TEXT"}, {def: "MEDIAN(array1): 返回数据系列的中值(与Excel的同名函数作用相同)。\n\n示例:\nMEDIAN([1,2,3])=2。\n", name: "MEDIAN", type: "OTHER"}, {def: "TABLEDATAFIELDS(tableData):返回tableData中所有的字段名。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的列名组成的数组。\n以我们提供的数据源FRDemo为例\n新建数据集ds1:SELECT * FROM [CUSTOMER]\nTABLEDATAFIELDS(\"ds1\")等于\nCUSTOMERID,CUSTOMERAME,CITY,COUNTRY,TEL,DISTRICT。", name: "TABLEDATAFIELDS", type: "REPORT"}, {def: "占比公式, =PROPORTION(A1)等同于=A1/sum(A1[!0])", name: "PROPORTION", type: "HA"}, {def: "COL()返回当前单元格的列号,必须使用于条件属性中\n示例:\n如果当前单元格是A5,在A5中写入\"=col()\"则返回1。\n如果当前单元格是C6,在C6中写入\"=col()\"则返回3。", name: "COL", type: "REPORT"}, {def: "TOHEX(int): 将一个十进制整型数转换成十六进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOHEX(15)等于 \"f\"。\nTOHEX(20)等于 \"14\"。", name: "TOHEX", type: "MATH"}, {def: "COS(number): 返回一个角度的余弦值。\nNumber:以弧度表示的需要求余弦值的角度。\n备注:\n 要把一个角度转换成弧度值,将角度乘于PI()/180。\n COS(n*2*PI()+number)=COS(number)(其中n为整数,number从-pi到pi)。\n示例:\nCOS(0.5)等于0.877582562。\nCOS(30*PI()/180)等于0.866025404。", name: "COS", type: "MATH"}, {def: "跨层累计, =CROSSLAYERTOTAL(A1, B1, C1, D1)等同于=IF(&B1 >1, D1[B1:-1] + C1, D1[A1:-1,B1:!-1] + C1), 如需横向, 则传递第五个参数false", name: "CROSSLAYERTOTAL", type: "HA"}, {def: "POWER(number,power): 返回指定数字的乘幂。\nNumber:底数,可以为任意实数。\nPower:指数。参数number按照该指数次幂乘方。\n备注:\n 可以使用符号“^”代替POWER,如: POWER(5,2)等于5^2。\n示例:\nPOWER(6,2)等于36。\nPOWER(14,5)等于537824。\nPOWER(4,2/3)等于2.519842100。\nPOWER(3,-2.3)等于0.079913677。", name: "POWER", type: "MATH"}, {def: "DAYS360(start_date,end_date,method):按照一年 360 天的算法(每个月以 30 天计,一年共计 12 个月),\n返回两日期间相差的天数,这在会计计算中将会用到。如果财务系统是基于一年 12 个月,每月 30 天,\n可用此函数帮助计算支付款项。\nStart_date 和 end_date :是用于计算期间天数的起止日期。\nMethod : 它指定了在计算中是采用欧洲方法还是美国方法。\nMethod 定义 :\nFALSE或忽略 美国方法 (NASD)。如果起始日期是一个月的 31 号,则等于同月的 30 号。如果终止日期是一个月的\n31号,并且起始日期早于 30 号,则终止日期等于下一个月的 1 号,否则,终止日期等于本月的 30 号。\nTRUE 欧洲方法。无论是起始日期还是终止日期为一个月的 31 号,都将等于本月的 30 号。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAYS360(\"1998/1/30\", \"1998/2/1\") 等于 1", name: "DAYS360", type: "DATETIME"}, {def: "filetype(file)获取文件的类型。\n当file为单文件时,返回文件类型字符串,当file为多文件时,返回文件类型的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.txt },则filetype(B2)返回值为[“doc”, “xls”, “txt”]。", name: "FILETYPE", type: "OTHER"}, {def: "ADDARRAY(array, insertArray, start):在数组第start个位置插入insertArray中的所有元素,再返回该数组。\n示例:\nADDARRAY([3, 4, 1, 5, 7], [23, 43, 22], 3)返回[3, 4, 23, 43, 22, 1, 5, 7].\nADDARRAY([3, 4, 1, 5, 7], \"测试\", 3)返回[3, 4, \"测试\", 1, 5, 7].\n注意:如果start为小于1的数或者不写start参数,则默认从数组的第一位开始插入数组元素。", name: "ADD2ARRAY", type: "ARRAY"}, {def: "BITNOT(int):将一个十进制整数进行二进制取反运算。\nint:需要进行转换的十进制数。\n示例:\nBITNOT(3)等于-4。\nBITNOT(12)等于-13。", name: "BITNOT", type: "LOGIC"}, {def: "TABLEAS(connectionName):返回名为connectionName的数据库中的所有表名。\n示例:\n假设在FRDemo这个数据库中,有3个表:a,b,c;\n那么TABLES(\"FRDemo\")等于[a,b,c].", name: "TABLES", type: "REPORT"}, {def: "SUMSQ(number1,number2, ...):返回所有参数的平方和。\nnumber1, number2, ...:为 1 到 30 个需要求平方和的参数,也可以使用数组或对数组的引用来代替以逗号分隔的参数。\n示例:\nSUMSQ(3, 4) 等于 25\n", name: "SUMSQ", type: "MATH"}, {def: "RECORDS(connection, table,field):返回数据库表table中字段名field下的所有元素。\n示例:\n数据库BASE中有个名叫task的表的内容如下:\nname start end\na 2008 2009\nb 2009 2012\n那么RECORDS(\"BASE\",\"task\",\"end\")等于[2009,2012].\n\nRECORDS(connection, table,field,row)返回table中field字段下的第row行的记录,field可以为列名也可以为列号。\n RECORDS(\"BASE\",\"task\",\"end\",2)等于2012.\n RECORDS(\"BASE\",\"task\",2,2)等于2009.", name: "RECORDS", type: "REPORT"}, {def: "", name: "TOBIGDECIMAL", type: "DELETE"}, {def: "TODOUBLE(text): 将文本转换成Double对象。\nText:需要转换的文本。\n示例:\nTODOUBLE(\"123.21\")等于 new Double(123.21)。", name: "TODOUBLE", type: "TEXT"}, {def: "TODATE()函数可以将各种日期形式的参数转换为日期类型。\n它有三种参数的形式:\n1 参数是一个日期型的参数,那么直接将这个参数返回。\n示例:\nTODATE(DATE(2007,12,12))返回2007年12月12日组成的日期。\n2 参数是以从1970年1月1日0时0分0秒开始的毫秒数,返回对应的时间。\n示例:\nTODATE(1023542354746)返回2002年6月8日。\n3 参数是日期格式的文本,那么返回这个文本对应的日期。\n示例:\nTODATE(\"2007/10/15\")返回2007年10月5日组成的日期。\nTODATE(\"2007-6-8\")返回2007年6月8日组成的日期。\n4 有两个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式。\n示例:\nTODATE(\"1/15/07\",\"mm/dd/yy\")返回07年1月15日组成的日期。\n特别的,\"yyyyMMdd\"是用来解析形如“20081230”之类的日期格式的。比如TODATE(\"20110830\",\"yyyyMMdd\")返回11年08月30日组成的日期\n5 有三个参数,第一个参数是一个日期格式的文本,第二个参数是用来解析日期的格式,第三个参数为解析日期的语言,如:zh(中文),en(英文)。\n示例:\nTODATE(\"星期三 1/15/07\",\"EEE mm/dd/yy\", \"zh\")返回07年1月15日组成的日期,使用“zh(中文)”才能够正常解析“星期三”这个字符串。", name: "TODATE", type: "DATETIME"}, {def: "PROPER(text): 将文本中的第一个字母和所有非字母字符后的第一个字母转化成大写,其他字母变为小写。\nText:需要转化为文本的公式、由双引号引用的文本串或是单元格引用。\n示例:\nPROPER(\"Finemore Integrated Office\")等于“Finemore Integrated Office”。\nPROPER(\"100 percent\")等于“100 Percent”。\nPROPER(\"SpreaDSheEt\")等于“Spreadsheet”。", name: "PROPER", type: "TEXT"}, {def: "DAY:(serial_number)返回日期中的日。DAY是介于1和31之间的一个数。\nSerial_number:含有所求的年的日期.\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nDAY(\"2000/1/1\")等于1。\nDAY(\"2006/05/05\")等于5。\nDAY(\"1997/04/20\")等于20。\nDAY(\"2000-1-1\", \"yyyy-MM-dd\")等于1。\nDAY(\"2006-05-05\", \"yyyy-MM-dd\")等于5。\nDAY(\"1997-04-20\", \"yyyy-MM-dd\")等于20。\nDAY(35796)等于1。", name: "DAY", type: "DATETIME"}, {def: "LUNAR(year,day,month): 返回当前日期对应的农历时间。\nyear,month,day:分别对应年月日。\n示例:\n如果需要查询2011年7月21日对应的农历时间,则只需输入LUNAR(2011,7,21)结果将显示为:辛卯年六月廿一\n同样,如输入LUNAR(2001,7,21),则显示:辛巳年六月初一 。本公式支持的时间段为1900-2100年。", name: "LUNAR", type: "DATETIME"}, {def: "TABLEDATAS():返回报表数据集和服务器数据集名字。\n示例:\n服务器数据集有:ds1,ds2,ds3;报表数据集有dsr1,dsr2.\nTABLEDATAS()等于[dsr1,dsr2,ds1,ds2,ds3].\n而TABLEDATAS(0)返回服务器数据集名字;TABLEDATAS(1)返回报表数据集名字;\nTABLEDATAS(0)等于[ds1,ds2,ds3];TABLEDATAS(1)等于[dsr1,dsr2].", name: "TABLEDATAS", type: "REPORT"}, {def: "TAN(number): 返回指定角度的正切值。\nNumber:待求正切值的角度,以弧度表示。如果参数是以度为单位的,乘以Pi()/180后转换为弧度。\n示例:\nTAN(0.8)等于1.029638557。\nTAN(45*Pi()/180)等于1。", name: "TAN", type: "MATH"}, {def: "", name: "JVM", type: "DELETE"}, {def: "LN(number):返回一个数的自然对数。自然对数以常数项 e(2.71828182845904)为底。\nnumber:是用于计算其自然对数的正实数。\n示例:\nLN(86) 等于 4.45437\nLN(2.7182818) 等于 1\nLN(EXP(3)) 等于 3\nEXP(LN(4)) 等于 4\n", name: "LN", type: "MATH"}, {def: "ARRAY(arg1,arg2...):返回一个由arg1,arg2,...组成的数组.\narg1,arg2,...:字符串或者数字.\n示例:\nARRAY(\"hello\") = [\"hello\"].\nARRAY(\"hello\",\"world\") = [\"hello\",\"world\"].\nARRAY(\"hello\",98) = [\"hello\",98].\nARRAY(67,98) = [67,98].", name: "ARRAY", type: "ARRAY"}, {def: "TOBINARY(int): 将一个十进制整型数转换成二进制表示的字符串。\nint:表示需要进行转换的十进制整数。\n示例:\nTOBINARY(10)等于 \"1010\"。\nTOBINARY(20)等于 \"10100\"。", name: "TOBINARY", type: "MATH"}, {def: "NVL(value1,value2,value3,...):在所有参数中返回第一个不是null的值value1:可以为任意数,也可以为null。\nvalue2:可以为任意数,也可以为null。\n当字符串长度为0时, 返回也为null\n示例:\nNVL(12,20)等于12。\nNVL(null,12)等于12。\nNVL(null,null)等于null。\nNVL(20,null)等于20。\nNVL(null,null,10)等于10。", name: "NVL", type: "OTHER"}, {def: "CORREL(array1,array2): 求两个相同长度数据系列的相关系数(与Excel的同名函数作用相同)。\n如果数组或引用参数包含文本、逻辑值或空白单元格,则这些值将被忽略;但包含零值的单元格将计算在内。\n函数计算结果出现负数表示负相关。相关系数的取值范围是[-1,1]之间的数。相关系数的绝对值越大,表示误差越小。 Array1 和 Array2 的数据点的个数必须相同,例如:\nCORREL([1,2,3],[2,4,6])=1。\n", name: "CORREL", type: "OTHER"}, {def: "COLNAME(tableData,colIndex)返回的是tableData中列序号colIndex的列名。\ntableData:表示TableData的名字,字符串形式。\ncolIndex:表示列序号。\n备注:\n TableData先从私有数据源中查找,再从公有数据源中查找。\n示例:\nCOLNAME(\"Check\",3)等于AcceName。\nCOLNAME(\"country\",4)等于Area。", name: "COLNAME", type: "REPORT"}, {def: "DECIMAL(number): 返回number的大数类型,常用于精确计算。", name: "DECIMAL", type: "MATH"}, {def: "CLASS(object):返回object对象的所属的类。", name: "CLASS", type: "OTHER"}, {def: "VALUE(tableData,col,row)返回tableData中列号为col的值, 行号为row。\ntableData:tableData的名字,字符串形式的。\nrow:行号。\ncol:列号。\n备注:\n 先从报表数据集中查找,然后再从服务器数据集中查找,返回的是tableData的行数。\n示例:\nVALUE(\"country\",5,3)等于South America。\nVALUE(\"Simple\",8,3)等于jonnason。\n示例:VALUE(\"country\",5,\"大陆\")等于South America。\n\nVALUE(tableData,col)返回tableData中列号为col的一列值。\nVALUE(tableData,targetCol, orgCol, element)返回tableData中第targetCol列中的元素,这些元素对应的第orgCol列的值为element。\n示例:\ntableData : co\n国家 省份\n\n中国 江苏\n中国 浙江\n中国 北京\n美国 纽约\n美国 新泽西\nVALUE(\"co\",2, 1, \"中国\")等于[\"江苏\", \"浙江\", \"北京\"]。\n特别说明:列号也可以写为列名。\nVALUE(tableData,targetCol, orgCol, element, idx)返回VALUE(tableData,targetCol, orgCol, element)数组的第idx个值。\n特别说明:idx的值小于0时,会取数组的第一个值,idx的值大于数组长度时,会取数组的最后一个值。\n", name: "VALUE", type: "REPORT"}, {def: "JOINARRAY(array,sepa):返回一个由sepa作为分隔符的字符串.\narray:[arg1,arg2...]格式的数组;\nsepa:分隔符。\n示例:\nJOINARRAY([1,2],\";\") = [1;2].\nJOINARRAY([hello,world],\"-\") = [hello-world].", name: "JOINARRAY", type: "ARRAY"}, {def: "DATETONUMBER(date):返回自 1970 年 1 月 1 日 00:00:00 GMT 经过的毫秒数。\n示例:\nDATETONUMBER(\"2008-08-08\")等于1218124800000。", name: "DATETONUMBER", type: "DATETIME"}, {def: "INDEXOF(str1,index):返回字符串str1在index位置上的字符。\n备注:\n index是从0开始计数的。\n示例:\nINDEXOF(\"FineReport\",0)等于'F'。\nINDEXOF(\"FineReport\",2)等于'n'。\nINDEXOF(\"FineReport\",9)等于't'。\n\nINDEXOF(array, index):返回数组在index位置上的元素。\n备注:\n index是从1开始计数的。\n示例:\nString[] array = {\"a\", \"b\", \"c\"}\nINDEXOF(array, 1)等于\"a\".\n", name: "INDEXOF", type: "TEXT"}, {def: "PRODUCT(number1,number2, ...):将所有以参数形式给出的数字相乘,并返回乘积值。\nnumber1, number2, ...:为 1 到 30 个需要相乘的数字参数。\n示例:\nPRODUCT(3,4) 等于 12\nPRODUCT(3,4,5) 等于 60\n\n", name: "PRODUCT", type: "MATH"}, {def: "ACOS(number): 返回指定数值的反余弦值。反余弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的余弦值。\n备注:\n 函数的参数必须在-1和1之间,包括-1和1。\n 返回的角度值在0和Pi之间。\n 如果要把返回的角度用度数来表示,用180/PI()乘返回值即可。\n示例:\nACOS(1)等于0(弧度)。\nACOS(0.5)等于1.047197551(Pi/3弧度)。\nACOS(0.5)*180/PI()等于60(度)。", name: "ACOS", type: "MATH"}, {def: "FIND(find_text,within_text,start_num):从指定的索引(start_num)处开始,返回第一次出现的指定子字符串(find_text)在此字符串(within_text)中的索引。\nFind_text:需要查找的文本或包含文本的单元格引用。\nWithin_text:包含需要查找文本的文本或单元格引用。\nStart_num:指定进行查找字符的索引位置。within_text里的索引从1开始。如果省略start_num,则假设值为1。\n备注:\n 如果find_text不在within_text中,FIND函数返回值为0。\n 如果start_num不大于0,FIND函数返回错误信息*VALUE!。\n 如果start_num大于within_text的长度,FIND函数返回值为0。\n 如果find_text是空白文本,FIND函数将在搜索串中匹配第一个字符(即编号为start_num或1的字符)。\n示例:\nFIND(\"I\",\"Information\")等于1。\nFIND(\"i\",\"Information\")等于9。\nFIND(\"o\",\"Information\",2)等于4。\nFIND(\"o\",\"Information\",12)等于0。\nFIND(\"o\",\"Information\",-1)等于*VALUE!。", name: "FIND", type: "TEXT"}, {def: "MINUTE(serial_number):返回某一指定时间的分钟数,其值是介于0与59之间的一个整数。\nserial_number:包含所求分钟数的时间。\n示例:\nMINUTE(\"15:36:25\")等于36。\nMINUTE(\"15:36:25\", \"HH:mm:ss\")等于36。", name: "MINUTE", type: "DATETIME"}, {def: "SIGN(number):返回数字的符号。当数字为正数时返回 1,为零时返回 0,为负数时返回 -1。\nNumber:为任意实数。\n示例:\nSIGN(10) 等于 1\nSIGN(4-4) 等于 0\nSIGN(-0.00001) 等于 -1\n", name: "SIGN", type: "MATH"}, {def: "INDEX(key,val1,val2,...):返回key在val1,val2,...所组成的序列中的位置,不存在于序列中则返回参数的个数.\n备注:\n key和valn可以是任意类型\n示例:\nINDEX(2,2)等于1。\nINDEX(2,1,2)等于2。\nINDEX(2,4,5,6)等于4。\nINDEX(\"b\",\"b\",\"o\",\"y\")等于1。", name: "INDEX", type: "OTHER"}, {def: "REVERSE(value):返回与value相反的逻辑值。\n示例:\nREVERSE(true)等于false。", name: "REVERSE", type: "LOGIC"}, {def: "REPLACE(text, texttoreplace, replacetext):根据指定字符串,用其他文本来代替原始文本中的内容。\ntext:需要被替换部分字符的文本或单元格引用。\ntexttoreplace:指定的字符串或正则表达式。\nreplacetext:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"abcd\", \"a\", \"re\")等于\"rebcd\"。\nREPLACE(\"a**d\", \"**d\", \"rose\")等于\"arose\"。\nREPLACE(old_text,start_num,num_chars,new_text): 根据指定的字符数,用其他文本串来替换某个文本串中的部分内容。\nOld_text:需要被替换部分字符的文本或单元格引用。\nStart_num:需要用new_text来替换old_text中字符的起始位置。\nNum_chars:需要用new_text来替换old_text中字符的个数。\nNew_text:需要替换部分旧文本的文本。\n示例:\nREPLACE(\"0123456789\",5,4,\"*\")等于“0123*89”。\nREPLACE(\"1980\",3,2,\"99\")等于“1999”。", name: "REPLACE", type: "TEXT"}, {def: "UUID():返回随机的UUID。\n示例:UUID()返回36位随机机器数。\n UUID(32)返回32位随机机器数。", name: "UUID", type: "OTHER"}, {def: "DATESUBDATE(date1, date2, op):返回两个日期之间的时间差。\nop表示返回的时间单位:\n\"s\",以秒为单位。\n\"m\",以分钟为单位。\n\"h\",以小时为单位。\n\"d\",以天为单位。\n\"w\",以周为单位。\n示例:\nDATESUBDATE(\"2008-08-08\", \"2008-06-06\",\"h\")等于1512。", name: "DATESUBDATE", type: "DATETIME"}, {def: "CONCATENATE(text1,text2,...): 将数个字符串合并成一个字符串。\nText1,text2,...:需要合并成单个文本的文本项,可以是字符,数字或是单元格引用。\n示例:\nCONCATENATE(\"Average \",\"Price\")等于“Average Price”。\nCONCATENATE(\"1\",\"2\")等于12。", name: "CONCATENATE", type: "TEXT"}, {def: "filesize(file)获取文件的大小,单位为Kb。\n当file为单文件时,返回文件大小,当file为多文件时,返回文件大小的数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了两个大小分别为100字节和10240字节的文件,则filename(B2)返回值为[0.098, 10.0]。", name: "FILESIZE", type: "OTHER"}, {def: "DAYSOFMONTH(date):返回从1900年1月后某年某月包含的天数。\n示例:\nDAYSOFMONTH(\"1900-02-01\")等于28。\nDAYSOFMONTH(\"2008/04/04\")等于30。", name: "DAYSOFMONTH", type: "DATETIME"}, {def: "DATEINQUARTER(date, number): 函数返回在某一个季度当中第几天的日期。\n示例:\nDATEINQUARTER(\"2009-05-05\", 20)等于 2009-04-20。", name: "DATEINQUARTER", type: "DATETIME"}, {def: "逐层累计, =LAYERTOTAL(B1, C1, D1)等同于=D1[B1:-1] + C1, 如需横向, 则传递第四个参数false.如LAYERTOTAL(B1, C1, D1, false)", name: "LAYERTOTAL", type: "HA"}, {def: "CNMONEY(number,unit)返回人民币大写。\nnumber:需要转换的数值型的数。\nunit:单位,\"s\",\"b\",\"q\",\"w\",\"sw\",\"bw\",\"qw\",\"y\",\"sy\",\"by\",\"qy\",\"wy\"分别代表“拾”,“佰”,“仟”,“万”,“拾万”,“佰万”,“仟万”,“亿”,“拾亿”,“佰亿”,“仟亿”,“万亿”。\n备注:\n 单位可以为空,如果为空,则直接将number转换为人民币大写,否则先将number与单位的进制相乘,然后再将相乘的结果转换为人民币大写。\n示例:\nCNMONEY(1200)等于壹仟贰佰圆整。\nCNMONEY(12.5,\"w\")等于壹拾贰万伍仟圆整。\nCNMONEY(56.3478,\"bw\")等于伍仟陆佰叁拾肆万柒仟捌佰圆整。\nCNMONEY(3.4567,\"y\")等于叁亿肆仟伍佰陆拾柒万圆整。", name: "CNMONEY", type: "TEXT"}, {def: "DAYVALUE(date):返回1900年至 date日期所经历的天数。\n示例:\nDAYVALUE(\"2008/08/08\")等于39668。", name: "DAYVALUE", type: "DATETIME"}, {def: "SQL(connectionName,sql,columnIndex,rowIndex)返回通过sql语句从connectionName中获得数据表的第columnIndex列第rowIndex行所对应的元素。\nconnectionName:数据库库的名字,字符串形式;\nsql:SQL语句,字符串形式;\ncolumnIndex:列序号,整形;\nrowIndex:行序号,整形。\n备注:行序号可以不写,这样返回值为数据列。\n示例:\n以我们提供的数据源HSQL为例\nSQL(\"HSQL\",\"SELECT * FROM CUSTOMER\",2,2)等于王先生。", name: "SQL", type: "REPORT"}, {def: "DATE(year,month,day): 返回一个表示某一特定日期的系列数。\nYear:代表年,可为一到四位数。\nMonth:代表月份。\n若1 month 12,则函数把参数值作为月。\n若month>12,则函数从年的一月份开始往上累加。例如: DATE(2000,25,2)等于2002年1月2日的系列数。\nDay:代表日。\n若日期小于等于某指定月的天数,则函数将此参数值作为日。\n若日期大于某指定月的天数,则函数从指定月份的第一天开始往上累加。若日期大于两个或多个月的总天数,则函数把减去两个月或多个月的余数加到第三或第四个月上,依此类推。例如:DATE(2000,3,35)等于2000年4月4日的系列数。\n备注:\n 若需要处理公式中日期的一部分,如年或月等,则可用此公式。\n 若年,月和日是函数而不是函数中的常量,则此公式最能体现其作用。\n示例:\nDATE(1978, 9, 19) 等于1978-09-19.\nDATE(1211, 12, 1) 等于1211-12-01. ", name: "DATE", type: "DATETIME"}, {def: "BITOPERATIOIN(int,int,op) 位运算,返回两个整数根据op进行位运算后的结果。\nint:十进制整数。\nop:位运算操作符,支持\"&\"(与),\"|\"(或),\"^\"(异或),\"<<\"(左移),\">>\"(右移)。\n示例:\nBITOPERATION(4,2,\"&\")表示4与2进行\"与\"运算,结果等于0。\nBITOPERATION(4,2,\"|\")表示4与2进行\"或\"运算,结果等于6。\nBITOPERATION(4,2,\"^\")表示4与2进行\"异或\"运算,结果等于6。\nBITOPERATION(4,2,\"<<\")表示4按位左移2位,结果等于16。\nBITOPERATION(4,2,\">>\")表示4按位右移2位,结果等于1。\nBITOPERATION(4,2,\"^~\")表示4与2进行\"同或\"运算,结果为-7。", name: "BITOPERATION", type: "LOGIC"}, {def: "LOWER(text): 将所有的大写字母转化为小写字母。\nText:需要转化为小写字母的文本串。LOWER函数不转化文本串中非字母的字符。\n示例:\nLOWER(\"A.M.10:30\")等于“a.m.10:30”。\nLOWER(\"China\")等于“china”。", name: "LOWER", type: "TEXT"}, {def: "CEILING(number): 将参数number沿绝对值增大的方向,舍入为最接近的整数\nNumber:指待舍入的数值。\nCEILING(-2.5)等于-3。\nCEILING(0.5)等于1。", name: "CEILING", type: "MATH"}, {def: "SINH(number):返回某一数字的双曲正弦值。\nnumber:为任意实数。\n示例:\nSINH(1) 等于 1.175201194\nSINH(-1) 等于 -1.175201194", name: "SINH", type: "MATH"}, {def: "AND(logical1,logical2,…): 当所有参数的值为真时,返回TRUE;当任意参数的值为假时,返回FALSE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nAND(1+7=8,5+7=12)等于TRUE。\nAND(1+7=8,5+7=11)等于FALSE。\n如果单元格A1到A4的值分别为TRUE、TRUE、FALSE和TRUE,则:\nAND(A1:A4)等于FALSE。\n如果单元格A5的值在0~50之间,则: AND(0 $A1}) + 1, 默认升序排列, 如需要降序, 则传递参数false,\n =SORT(A1, false)等同于=COUNT(A1[!0]{A1 < $A1}) + 1.", name: "SORT", type: "HA"}, {def: "SIN(number): 计算给定角度的正弦值。\nNumber:待求正弦值的以弧度表示的角度。\n备注:\n 如果参数的单位是度,将其乘以PI()/180即可转换成弧度。\n示例:\nSIN(10)等于-0.5440211108893698。\nSIN(45*PI()/180)等于0.707106781。", name: "SIN", type: "MATH"}, {def: "switch(表达式, 值1, 结果1, 值2, 结果2, ...)\n如果表达式的结果是值1,整个函数返回结果1\n如果表达式的结果是值2,整个函数返回结果2\n如果表达式的结果是值3,整个函数返回结果3\n等等\n", name: "SWITCH", type: "LOGIC"}, {def: "ROW()返回当前单元格的行号,必须使用于条件属性中\n示例:\n如果当前单元格为A5,在A5中写入\"=ROW()\"则返回5。\n如果当前单元格为B8,在B8中写入\"=ROW()\"则返回8。", name: "ROW", type: "REPORT"}, {def: "EVAL(exp)返回表达式exp计算后的结果。\nexp:一个表达式形式字符串。\n备注:\n 只要EVAL中的参数exp最终可以转化成一表达式形式的字符串,比如\"sum(2,4)\",\"2+7\"等等,那么它就可以被计算。\nEVAL(\"2+5\")等于7。\nEVAL(\"count(2,3)\")等于2。\nEVAL(\"sum\"+\"(2,3,5)\")等于10。\nEVAL(IF(true, \"sum\", \"count\") + \"(1,2,3,4)\")等于10。\nEVAL(IF(false, \"sum\", \"count\") + \"(1,2,3,4)\")等于4。", name: "EVAL", type: "OTHER"}, {def: "ATAN(number): 计算指定数值的反正切值。指定数值是返回角度的正切值,返回角度以弧度形式表示。\nNumber:返回角度的正切。\n备注:\n 返回角度在-pi/2到pi/2之间。\n 如果返回角度等于-pi/2或pi/2,ATAN将返回错误信息*NUM!。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nATAN(-1)等于-0.785398163(-pi/4弧度)。\nATAN(0)等于0(弧度)。\nATAN(2)*180/PI()等于63.43494882(度)。", name: "ATAN", type: "MATH"}, {def: "RANGE(from,to,step)函数表示从整数from开始,以step为每一步的大小,直到整数to的一个数字序列。\n例如:\nRANGE(1,5,1)表示从1开始,直到5(包括5),每一步大小为1,那么它返回一个数字序列为[1,2,3,4,5]。\nRANGE(-1,6,2)表示从-1开始,直到6(包括6),每一步大小为2,那么它返回一个数字序列为[-1,1,3,5]。\n备注:RANGE函数有三种参数形式:\n1 RANGE(to),默认的from为1,step为1,例如:\n RANGE(4)返回[1,2,3,4]。\n RANGE(-5)返回[]。\n2 RANGE(from,to),默认的step为1,例如:\n RANGE(-1,3)返回[-1,0,1,2,3]。\n RANGE(0,5)返回[0,1,2,3,4,5]。\n3 RANGE(from,to,step),三个参数的情况参照上面的注释,例如:\n RANGE(6,-1,-2)返回[6,4,2,0]。\n RANGE(4,1,1)返回[]。", name: "RANGE", type: "ARRAY"}, {def: "TANH(number):返回某一数字的双曲正切值。\nnumber:为任意实数。\n双曲正切的计算公式如下:\n示例:\nTANH(-2) 等于 -0.96403\nTANH(0) 等于 0\nTANH(0.5) 等于 0.462117\n", name: "TANH", type: "MATH"}, {def: "ROUNDDOWN(number,num_digits):靠近零值,向下(绝对值减小的方向)舍入数字。\nnumber:为需要向下舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDDOWN 和函数 ROUND 功能相似,不同之处在于函数 ROUNDDOWN 总是向下舍入数字。\n示例:\nROUNDDOWN(3.2, 0) 等于 3\nROUNDDOWN(76.9,0) 等于 76\nROUNDDOWN(3.14159, 3) 等于 3.141\nROUNDDOWN(-3.14159, 1) 等于 -3.1\nROUNDDOWN(31415.92654, -2) 等于 31,400\n", name: "ROUNDDOWN", type: "MATH"}, {def: "循环引用, =CIRCULAR(A1, B1, C1, D1)等同于=IF(&A1 = 1, 0, B1[A1:-1] + C1[A1:-1] – D1[A1:-1]),如需横向, 则传递第五个参数false", name: "CIRCULAR", type: "HA"}, {def: "HOUR(serial_number):返回某一指定时间的小时数。函数指定HOUR为0(0:00)到23(23:00)之间的一个整数。\nSerial_number:包含所求小时的时间。\n示例:\nHOUR(\"11:32:40\")等于11。\nHOUR(\"11:32:40\", \"HH:mm:ss\")等于11。", name: "HOUR", type: "DATETIME"}, {def: "ROUND(number,num_digits):返回某个数字按指定位数舍入后的数字。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND(2.15, 1) 等于 2.2\nROUND(2.149, 1) 等于 2.1\nROUND(-1.475, 2) 等于 -1.48\nROUND(21.5, -1) 等于 20\n因浮点数存在精度计算丢失问题, 导致计算结果里可能带上9999, 0000这些, \n因此加入第三个参数来控制是否需要去除9999. true表示需要过滤9999, 0000这些数据.", name: "ROUND", type: "MATH"}, {def: "YEARDELTA(date, delta):返回指定日期后delta年的日期。\n示例:\nYEARDELTA(\"2008-10-10\",10)等于2018-10-10。", name: "YEARDELTA", type: "DATETIME"}, {def: "DATEINYEAR(date, number):函数返回在一年当中第几天的日期。\n示例:\nDATEINYEAR(2008,100)等于2008-04-09,等价于DATEINYEAR(\"2008-08-08\",100),也返回2008-04-09.\nDATEINYEAR(2008,-1)等于2008-12-31,等价于DATEINYEAR(\"2008-08-08\",-1),也返回2008-12-31.", name: "DATEINYEAR", type: "DATETIME"}, {def: "WEIGHTEDAVERAGE(A1:A4,B1:B4): 返回指定数据的加权平均值。\n加权平均数是不同比重数据的平均数,加权平均数就是把原始数据按照合理的比例来计算。\nA1:A4,B1:B4:用于计算平均值的参数,A1~A4为数据,B1~B4为权值。\n示例:\n如果A1:A4为10,9,8,7,B1:B4为0.2,0.1,0.3,0.4则:\nWEIGHTEDAVERAGE(A1:A4,B1:B4)等于8.1。", name: "WEIGHTEDAVERAGE", type: "MATH"}, {def: "ASIN(number): 返回指定数值的反正弦值。反正弦值为一个角度,返回角度以弧度形式表示。\nNumber:需要返回角度的正弦值。\n备注:\n 指定数值必须在-1到1之间(含1与-1)。\n 返回角度在-pi/2到pi/2之间(含-pi/2与pi/2)。\n 用角度形式返回数值时,返回数值乘以180/PI()。\n示例:\nASIN(0.5)等于0.523598776(pi/6弧度)。\nASIN(1)等于1.570796327(pi/2弧度)。\nASIN(0.5)*180/PI()等于30(度)。", name: "ASIN", type: "MATH"}, {def: "INT(number): 返回数字下舍入(数值减小的方向)后最接近的整数值。\nNumber:需要下舍入为整数的实数。\n示例:\nINT(4.8)等于4。\nINT(-4.8)等于-5。\nINT(4.3)等于4。\nINT(-4.3)等于-5。\n公式INT(A1)将返回A1单元格中的一个正实数的整数数部分。", name: "INT", type: "MATH"}, {def: "GETUSERJOBTITLES():返回角色职务\n示例:\nGETUSERDEPARTMENTS():返回角色所有职务,若多个部门职务则返回职务数组", name: "GETUSERJOBTITLES", type: "OTHER"}, {def: "REGEXP(str, pattern):字符串str是否与正则表达式pattern相匹配。\n示例:\nREGEXP(\"aaaaac\",\"a*c\")等于true。\nREGEXP(\"abc\",\"a*c\")等于false。\n\nREGEXP(str, pattern, intNumber):字符串str是否与具有给定模式 intNumber的正则表达式pattern相匹配。\n示例:\nCASE_INSENSITIVE = 0 启用不区分大小写的匹配。 默认情况下,不区分大小写的匹配假定仅匹配 US-ASCII 字符集中的字符。可以通过指 定 UNICODE_CASE 标志连同此标志来启用 Unicode 感知的、不区分大小写的匹配。 \nMULTILINE = 1 启用多行模式。\nDOTALL = 2 启用 dotall 模式。在 dotall 模式中,表达式 . 可以匹配任何字符,包括行结束符。默认情况下,此表达式不匹配行 结束符。\nUNICODE_CASE = 3 启用 Unicode 感知的大小写折叠。指定此标志后,由 CASE_INSENSITIVE 标志启用时,不区分大小写的匹配将以 符合 Unicode Standard 的方式完成。\nCANON_EQ = 4 启用规范等价。 指定此标志后,当且仅当其完整规范分解匹配时,两个字符才可视为匹配。\nUNIX_LINES = 5 启用 Unix 行模式。 在此模式中,.、^ 和 $ 的行为中仅识别 '\\n' 行结束符。\nLITERAL = 6 启用模式的字面值解析。 指定此标志后,指定模式的输入字符串就会作为字面值字符序列来对待。输入序列中的 元字符或转义序列不具有任何特殊意义。 标志 CASE_INSENSITIVE 和 UNICODE_CASE 在与此标志一起使用时将 对匹配产生影响。其他标志都变得多余了。\nCOMMENTS = 7 模式中允许空白和注释。 此模式将忽略空白和在结束行之前以 # 开头的嵌入式注释。\n \nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 3)等于true。\nREGEXP(\"Aaaaabbbbc\",\"a*b*c\", 1)等于false。\n\n", name: "REGEXP", type: "TEXT"}, {def: "DAYSOFQUARTER(date): 返回从1900年1月后某年某季度的天数。\n示例:\nDAYSOFQUARTER(\"2009-02-01\")等于90。\nDAYSOFQUARTER(\"2009/05/05\")等于91。", name: "DAYSOFQUARTER", type: "DATETIME"}, {def: "AVERAGE(number1,number2,…,countstring): 返回指定数据的平均值。\nNumber1,number2…:用于计算平均值的参数; countString:文字、逻辑值是否参与计数。\n备注:\n 参数必须是数字,或是含有数字的名称,数组或引用。\n 如果数组或引用参数中含有文字,逻辑值,默认参与计数,countString为false则不参与计数;\n 空单元格始终不参与计数,但是,单元格中的零值参与。\n示例:\n如果A1:A6被命名为“ages”,分别等于10,23,文字,29,33及25,则:\nAVERAGE(A1:A6)等于20。\nAVERAGE(A1:A6, false)等于24。\nAVERAGE(ages)等于20。\n如果还有一个年龄为27的,求所有年龄的平均值为: AVERAGE(A1:A6,27)等于21。", name: "AVERAGE", type: "MATH"}, {def: "RADIANS(angle): 将角度转换成弧度。\nAngle:需要转换为弧度的角度。\n示例:\nRADIANS(90)等于1.570796327(π/2弧度)。", name: "RADIANS", type: "MATH"}, {def: "REMOVEARRAY(array, start, deleteCount):从数组array中删除从第start个元素开始的deleteCount个数组元素,并返回删除后的数组。\n示例:\nREMOVEARRAY([3, 4, 4, 2, 6, 7, 87], 4, 2)返回[3, 4, 4, 7, 87].\n", name: "REMOVEARRAY", type: "ARRAY"}, {def: "WEBIMAGE(path):在web页面上显示指定路径下的图片。", name: "WEBIMAGE", type: "OTHER"}, {def: "WEEK(serial_num):返回一个代表一年中的第几周的数字。\nSerial_num:表示输入的日期。\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n示例:\nWEEK(\"2010/1/1\")等于52。\nWEEK(\"2010/1/6\")等于1。\nWEEK(35796)等于1。", name: "WEEK", type: "DATETIME"}, {def: "filename(file)获取文件的文件名。\n当file为单文件时,返回文件名字符串,当file为多文件时,返回文件名的字符串数组。\n如果file不为文件类型,则返回错误信息。\n示例:\n假设文件控件在B2单元格,而B2单元格依次上传了三个不同类型文件{A.doc, C.xls ,B.cpt },则filename(B2)返回值为[“A.doc”, “C.xls”, “B.cpt”]。", name: "FILENAME", type: "OTHER"}, {def: "COSH(number): 返回一个数值的双曲线余弦值。\nNumber:需要求其双曲线余弦值的一个实数。\n备注:\n 双曲线余弦值计算公式为: ,其中e是自然对数的底,e=2.71828182845904。\n示例:\nCOSH(3)等于10.06766200。\nCOSH(5)等于74.20994852。\nCOSH(6)等于201.7156361。", name: "COSH", type: "MATH"}, {def: "WEEKDAY(Serial_number):获取日期并返回星期数。返回值为介于0到6之间的某一整数,分别代表星期中的某一天(从星期日到星期六)。\nSerial_number:输入的日期\n备注:\nFineReport将日期保存为系列数,一个系列数代表一个与之匹配的日期,以方便用户对日期进行数值式计算。\n在1900年日期系统中,FineReport电子表格将1900年1月1日保存为系列数2,将1900年1月2日保存为系列数3,\n将1900年1月3日保存为系列数4……依此类推。如在1900年日期系统,1998年1月1日存为系列数35796。\n举例:\nWEEKDAY(\"2005/9/10\")等于6(星期六)。\nWEEKDAY(\"2005/9/11\")等于0(星期日)。\nWEEKDAY(35796)等于4(星期四)。\n", name: "WEEKDAY", type: "DATETIME"}, {def: "OR(logical1,logical2,…): 当所有参数的值为假时,返回FALSE;当任意参数的值为真时,返回TRUE。\nLogical1,logical2,…:指1到30个需要检验TRUE或FALSE的条件值。\n备注:\n 参数必须是逻辑值,或是含有逻辑值的数组或引用。\n 如果数组或引用中含有文本或空的单元格,则忽略其值。\n 如果在指定的单元格区域中没有逻辑值,AND函数将返回错误信息*NAME?。\n示例:\nOR(1+7=9,5+7=11)等于FALSE。\nOR(1+7=8,5+7=11)等于TRUE。", name: "OR", type: "LOGIC"}, {def: "MOD(number,divisor):返回两数相除的余数。结果的正负号与除数相同。\nnumber:为被除数。\ndivisor:为除数。\n示例:\nMOD(3, 2) 等于 1\nMOD(-3, 2) 等于 1\nMOD(3, -2) 等于 -1\nMOD(-3, -2) 等于 -1\n", name: "MOD", type: "MATH"}, {def: "TODAY():获取当前日期。\n示例:\n如果系统日期是2005年9月10日\n则TODAY()等于2005-9-10。", name: "TODAY", type: "DATETIME"}, {def: "ROUNDUP(number,num_digits):远离零值,向上(绝对值增大的方向)舍入数字。\nnumber:为需要向上舍入的任意实数。\nnum_digits:舍入后的数字的位数。\n函数 ROUNDUP 和函数 ROUND 功能相似,不同之处在于函数 ROUNDUP 总是向上舍入数字。\n示例:\nROUNDUP(3.2,0) 等于 4\nROUNDUP(76.9,0) 等于 77\nROUNDUP(3.14159, 3) 等于 3.142\nROUNDUP(-3.14159, 1) 等于 -3.2\nROUNDUP(31415.92654, -2) 等于 31,500\n\n", name: "ROUNDUP", type: "MATH"}, {def: "ROUND5(number,num_digits):这个是四舍五入,奇进偶不进。\nnumber:需要进行舍入的数字。\nnum_digits:指定的位数,按此位数进行舍入。\n如果 num_digits 大于 0,则舍入到指定的小数位。\n如果 num_digits 等于 0,则舍入到最接近的整数。\n如果 num_digits 小于 0,则在小数点左侧进行舍入。\n示例:\nROUND5(2.125, 2) 等于 2.12\nROUND5(2.135, 2) 等于 2.14\n", name: "ROUND5", type: "MATH"}, {def: "TIME(hour,minute,second): 返回代表指定时间的小数。介于0:00:00(12:00:00 A.M.)与23:59:59(11:59:59 P.M.)之间的时间可返回0到0.99999999之间的对应数值。\nHour:介于0到23之间的数。\nMinute:介于0到59之间的数。\nSecond:介于0到59之间的数。\n示例:\nTIME(14,40,0)等于2:40 PM。\nTIME(19,43,24)等于7:43 PM。", name: "TIME", type: "DATETIME"}, {def: "环比公式, =MOM(A1, B1)等同于=IF(&A1 > 1, B1 / B1[A1:-1],0), 其中如果需要指定偏移量x, 则传递第三个参数x, 第四个参数表示横纵向.\n如=MOM(A1, B1, -2, false)等同于=IF(&A1 > 1, B1 / B1[;A1:-2], 0)", name: "MOM", type: "HA"}, {def: "ASINH(number): 返回指定数值的反双曲正弦值。反双曲正弦值的双曲正弦等于指定数值。即: ASINH(SINH(number))=number。\nNumber:任意实数。\n示例:\nASINH(-5)等于-2.312438341。\nASINH(8)等于2.776472281。\nASINH(16)等于3.466711038。", name: "ASINH", type: "MATH"}, {def: "EENNUMBER(value):将给定的BigDecimal类型的数字(100以内)取整后转化成英文金额的字符串。\n示例:\nENNUMBER(23.49)等于TWENTY THREE。\n注:若出现结果为空,需要将数字强制转换为BigDecimal类型,例如:ENNUMBER(TOBIGDECIMAL(80))", name: "ENNUMBER", type: "TEXT"}, {def: "CODE(text): 计算文本串中第一个字符的数字代码。返回的代码对应于计算机使用的字符集。\nText:需要计算第一个字符代码的文本或单元格引用。\n示例:\nCODE(\"S\")等于83。\nCODE(\"Spreadsheet\")等于83。", name: "CODE", type: "TEXT"}, {def: "DEGREES(angle): 将弧度转化为度。\nangle:待转换的弧度角。\n示例:\nDEGREES(PI()/2)等于90。\nDEGREES(3.1415926)等于179.9999969。", name: "DEGREES", type: "MATH"}, {def: "LEN(args): 返回文本串中的字符数或者数组的长度。\n需要注意的是:参数args为文本串时,空格也计为字符。\n参数args为数组时,直接返回数组长度。\n示例:\nLEN(\"Evermore software\")等于17。\nLEN(\" \")等于1。\nLEN(['a','b'])等于2。\n", name: "LEN", type: "TEXT"}, {def: "DATETIME():获取当前日期和时间。\n示例:\n如果系统时间是2005年9月10日 15点18分38秒\n则DATETIME()等于2005-9-10 15:18:36。", name: "DATETIME", type: "DELETE"}, {def: "UNIQUEARRAY(array):去掉数组array中的重复元素。\n示例:\nUNIQUEARRAY([14, 2, 3, 4, 3, 2, 5, 6, 2, 7, 9, 12, 3])返回[14, 2, 3, 4, 5, 6, 7, 9, 12].", name: "UNIQUEARRAY", type: "ARRAY"}, {def: "PROMOTION(value1,value2):返回value2在value1上提升的比例。\n示例:\nPROMOTION(12, 14)等于0.166666666,即提升了16.6666666%.\nPROMOTION(-12, 14)等于2.166666666,即提升了216.6666666%.", name: "PROMOTION", type: "MATH"}, {def: "PI(number): 是一个数学常量函数,当number为空时,函数返回精确到15位的数值3.141592653589793;当参数不为空时,number表示PI的倍数。\n示例:\nSIN(PI()/2)等于1。\n计算圆的面积的公式: S=PI()*(r^2),其中S为圆的面积,R为圆的半径。\nPI(3)等于9.42477796076938。", name: "PI", type: "MATH"}, {def: "ISNULL(object):判断对象中所有的值是否全部都是NULL或者为空字符串。", name: "ISNULL", type: "OTHER"}, {def: "LET(变量名,变量值,变量名,变量值,..., 表达式):局部变量赋值函数,参数的个数N必须为奇数, 最后一个是表达式,前面是N-1(偶数)为局部变量赋值对。\n变量名: 必须是合法的变量名,以字母开头,可以包括字母,数字和下划线\n表达式: 根据前面的N-1个参数赋值后计算出来的结果,这些变量赋值只在这个表达式内部有效\n示例:\nLET(a, 5,b, 6, a+b)等于11\n", name: "LET", type: "OTHER"}, {def: "SECOND(serial_number):返回某一指定时间的秒数,其值是介于0与59之间的一个整数。\nSerial_number:包含所求秒数的时间。\n示例:\nSECOND(\"15:36:25\")等于25。\nSECOND(\"15:36:25\", \"HH:mm:ss\")等于25。", name: "SECOND", type: "DATETIME"}, {def: "EXP(number): 返回e的n次幂。常数e为自然对数的底数,等于2.71828182845904。\nNumber:为任意实数,作为常数e的指数。\n备注:\n 如果要返回其他常数作为底数的幂,可以使用指数运算符(^)。例如: 在4^2中,4是底数,而2是指数。\n EXP函数与LN函数互为反函数。\n示例:\nEXP(0)等于1。\nEXP(3)等于20.08553692。\nEXP(LN(2))等于2。", name: "EXP", type: "MATH"}, {def: "treelayer(TreeObject, Int, Boolean, String):\n返回tree对象第n层的值,并且可以设置返回值类型及分隔符。\nTreeObject:tree对象,如$tree。\nInt:想要获得层级的数值,最上层为1,第二层为2,依此类推,若无则返回最底层\n。Boolean:返回值类型为字符串还是数组,默认false,返回数组;为true时返回字符串。\nString:当Boolean为true返回字符串时的分隔符,以双引号表示,默认为逗号\",\",如\";\"。\n示例:\n假设$tree勾选的值为中国-江苏-南京,中国-浙江-杭州,则treelayer($tree, true, ”\\’,\\’”):返回”’,’”分割的所选中节点字符串”南京’,’杭州”treelayer($tree, 2):以数组形式返回第二层[“江苏”,”浙江”]。treelayer($tree, 2, true, ”\\’,\\’”):返回”’,’”分割的字符串江苏’,’浙江。", name: "TREELAYER", type: "OTHER"}, {def: "读取配置文件", name: "TOTEXT", type: "DELETE"}]; diff --git a/src/base/formula/formulaeditor.js b/src/base/formula/formulaeditor.js index 64eb67f98..bf678856b 100644 --- a/src/base/formula/formulaeditor.js +++ b/src/base/formula/formulaeditor.js @@ -6,9 +6,9 @@ BI.FormulaEditor = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.FormulaEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-formula-editor bi-card', - watermark: '', - value: '', + baseCls: "bi-formula-editor bi-card", + watermark: "", + value: "", fieldTextValueMap: {}, showHint: true, lineHeight: 2 @@ -21,8 +21,8 @@ BI.FormulaEditor = BI.inherit(BI.Single, { textWrapping: true, lineWrapping: true, lineNumbers: false, - mode: 'formula', - //解决插入字段由括号或其他特殊字符包围时分裂的bug + mode: "formula", + // 解决插入字段由括号或其他特殊字符包围时分裂的bug specialChars: /[\u0000-\u001f\u007f\u00ad\u200c-\u200f\u2028\u2029\ufeff]/ }); o.lineHeight === 1 ? this.element.addClass("codemirror-low-line-height") : this.element.addClass("codemirror-high-line-height"); @@ -32,7 +32,7 @@ BI.FormulaEditor = BI.inherit(BI.Single, { CodeMirror.showHint(cm, CodeMirror.formulaHint, {completeSingle: false}); } BI.nextTick(function () { - self.fireEvent(BI.FormulaEditor.EVENT_CHANGE) + self.fireEvent(BI.FormulaEditor.EVENT_CHANGE); }); }); @@ -114,10 +114,10 @@ BI.FormulaEditor = BI.inherit(BI.Single, { */ insertField: function (field) { var from = this.editor.getCursor(); - //解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 - this.editor.replaceSelection('\u200b' + field + '\u200b'); + // 解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 + this.editor.replaceSelection("\u200b" + field + "\u200b"); var to = this.editor.getCursor(); - this.editor.markText(from, to, {className: 'fieldName', atomic: true, startStyle: "start", endStyle: "end"}); + this.editor.markText(from, to, {className: "fieldName", atomic: true, startStyle: "start", endStyle: "end"}); this.editor.replaceSelection(" "); this.editor.focus(); }, @@ -166,7 +166,7 @@ BI.FormulaEditor = BI.inherit(BI.Single, { _.forEach(line.markedSpans, function (i, ms) { switch (i.marker.className) { case "fieldName": - //因为插入字段的时候首尾加了不可见字符,所以首尾缩进一个字符 + // 因为插入字段的时候首尾加了不可见字符,所以首尾缩进一个字符 var dId = fieldMap[value.substr(i.from + 1, i.to - i.from - 2)]; if (!fields.contains(dId)) { fields.push(dId); diff --git a/src/base/foundation/message.js b/src/base/foundation/message.js index e22ab89c6..e4a406034 100644 --- a/src/base/foundation/message.js +++ b/src/base/foundation/message.js @@ -43,28 +43,28 @@ $.extend(BI, { BI.delay(function () { toast.element.slideUp(500, function () { toast.destroy(); - }) - }, 5000) - }) + }); + }, 5000); + }); }, _show: function (hasCancel, title, message, callback) { - $mask = $('
    ').css({ - position: 'absolute', - 'zIndex': BI.zIndex_tip - 2, + $mask = $("
    ").css({ + position: "absolute", + zIndex: BI.zIndex_tip - 2, top: 0, left: 0, right: 0, bottom: 0, opacity: 0.5 - }).appendTo('body'); - $pop = $('
    ').css({ - position: 'absolute', - 'zIndex': BI.zIndex_tip - 1, + }).appendTo("body"); + $pop = $("
    ").css({ + position: "absolute", + zIndex: BI.zIndex_tip - 1, top: 0, left: 0, right: 0, bottom: 0 - }).appendTo('body'); + }).appendTo("body"); var close = function () { messageShow.destroy(); $mask.remove(); @@ -73,10 +73,10 @@ $.extend(BI, { if (hasCancel === true) { controlItems.push({ el: { - type: 'bi.button', + type: "bi.button", text: BI.i18nText("BI-Basic_Cancel"), height: 30, - level: 'ignore', + level: "ignore", handler: function () { close(); if (BI.isFunction(callback)) { @@ -88,7 +88,7 @@ $.extend(BI, { } controlItems.push({ el: { - type: 'bi.button', + type: "bi.button", text: BI.i18nText("BI-Basic_OK"), height: 30, handler: function () { @@ -101,31 +101,31 @@ $.extend(BI, { }); var conf = { element: $pop, - type: 'bi.center_adapt', + type: "bi.center_adapt", items: [ { - type: 'bi.border', - cls: 'bi-message-content bi-card', + type: "bi.border", + cls: "bi-message-content bi-card", items: { - 'north': { + north: { el: { - type: 'bi.border', - cls: 'bi-message-title bi-background', + type: "bi.border", + cls: "bi-message-title bi-background", items: { center: { el: { - type: 'bi.label', + type: "bi.label", text: title || BI.i18nText("BI-Basic_Prompt"), - textAlign: 'left', + textAlign: "left", hgap: 20, height: 50 } }, east: { el: { - type: 'bi.icon_button', - cls: 'bi-message-close close-font', -// height: 50, + type: "bi.icon_button", + cls: "bi-message-close close-font", + // height: 50, handler: function () { close(); } @@ -136,7 +136,7 @@ $.extend(BI, { }, height: 50 }, - 'center': { + center: { el: { type: "bi.text", cls: "bi-message-text", @@ -147,12 +147,12 @@ $.extend(BI, { text: message } }, - 'south': { + south: { el: { type: "bi.absolute", items: [{ el: { - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", hgap: 5, items: controlItems }, diff --git a/src/base/grid/grid.js b/src/base/grid/grid.js index a0334ce39..d51b6e51e 100644 --- a/src/base/grid/grid.js +++ b/src/base/grid/grid.js @@ -15,8 +15,8 @@ BI.GridView = BI.inherit(BI.Widget, { overflowY: true, overscanColumnCount: 0, overscanRowCount: 0, - rowHeightGetter: BI.emptyFn, //number类型或function类型 - columnWidthGetter: BI.emptyFn, //number类型或function类型 + rowHeightGetter: BI.emptyFn, // number类型或function类型 + columnWidthGetter: BI.emptyFn, // number类型或function类型 // estimatedColumnSize: 100, //columnWidthGetter为function时必设 // estimatedRowSize: 30, //rowHeightGetter为function时必设 scrollLeft: 0, @@ -73,7 +73,7 @@ BI.GridView = BI.inherit(BI.Widget, { return { overscanStartIndex: Math.max(0, startIndex - overscanCellsCount), overscanStopIndex: Math.min(cellCount - 1, stopIndex + overscanCellsCount) - } + }; }, _calculateChildrenToRender: function () { @@ -98,7 +98,7 @@ BI.GridView = BI.inherit(BI.Widget, { this._renderedRowStartIndex = visibleRowIndices.start; this._renderedRowStopIndex = visibleRowIndices.stop; - var overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex) + var overscanColumnIndices = this._getOverscanIndices(this.columnCount, overscanColumnCount, this._renderedColumnStartIndex, this._renderedColumnStopIndex); var overscanRowIndices = this._getOverscanIndices(this.rowCount, overscanRowCount, this._renderedRowStartIndex, this._renderedRowStopIndex); @@ -107,7 +107,7 @@ BI.GridView = BI.inherit(BI.Widget, { var rowStartIndex = overscanRowIndices.overscanStartIndex; var rowStopIndex = overscanRowIndices.overscanStopIndex; - //算区间size + // 算区间size var minRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStartIndex); var minColumnDatum = this._columnSizeAndPositionManager.getSizeAndPositionOfCell(columnStartIndex); var maxRowDatum = this._rowSizeAndPositionManager.getSizeAndPositionOfCell(rowStopIndex); @@ -116,7 +116,7 @@ BI.GridView = BI.inherit(BI.Widget, { var left = minColumnDatum.offset + horizontalOffsetAdjustment; var bottom = maxRowDatum.offset + verticalOffsetAdjustment + maxRowDatum.size; var right = maxColumnDatum.offset + horizontalOffsetAdjustment + maxColumnDatum.size; - //如果滚动的区间并没有超出渲染的范围 + // 如果滚动的区间并没有超出渲染的范围 if (top >= this.renderRange.minY && bottom <= this.renderRange.maxY && left >= this.renderRange.minX && right <= this.renderRange.maxX) { return; } @@ -180,7 +180,7 @@ BI.GridView = BI.inherit(BI.Widget, { count++; } } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (self.renderedKeys[i]) { @@ -199,15 +199,15 @@ BI.GridView = BI.inherit(BI.Widget, { deleteArray.push(key[2]); }); BI.each(deleteArray, function (i, index) { - //性能优化,不调用destroy方法防止触发destroy事件 + // 性能优化,不调用destroy方法防止触发destroy事件 self.renderedCells[index].el._destroy(); }); var addedItems = []; BI.each(addSet, function (index, key) { - addedItems.push(renderedCells[key[2]]) + addedItems.push(renderedCells[key[2]]); }); this.container.addItems(addedItems); - //拦截父子级关系 + // 拦截父子级关系 this.container._children = renderedWidgets; this.container.attr("items", renderedCells); this.renderedCells = renderedCells; @@ -249,7 +249,7 @@ BI.GridView = BI.inherit(BI.Widget, { this._rowSizeAndPositionManager = new BI.ScalingCellSizeAndPositionManager(this.rowCount, o.rowHeightGetter, o.estimatedRowSize); this._calculateChildrenToRender(); - //元素未挂载时不能设置scrollTop + // 元素未挂载时不能设置scrollTop try { this.element.scrollTop(o.scrollTop); this.element.scrollLeft(o.scrollLeft); @@ -280,11 +280,11 @@ BI.GridView = BI.inherit(BI.Widget, { }, setColumnCount: function (columnCount) { - this.options.columnCount = columnCount + this.options.columnCount = columnCount; }, setRowCount: function (rowCount) { - this.options.rowCount = rowCount + this.options.rowCount = rowCount; }, setOverflowX: function (b) { @@ -292,7 +292,7 @@ BI.GridView = BI.inherit(BI.Widget, { if (this.options.overflowX !== !!b) { this.options.overflowX = !!b; BI.nextTick(function () { - self.element.css({overflowX: !!b ? "auto" : "hidden"}); + self.element.css({overflowX: b ? "auto" : "hidden"}); }); } }, @@ -302,7 +302,7 @@ BI.GridView = BI.inherit(BI.Widget, { if (this.options.overflowY !== !!b) { this.options.overflowY = !!b; BI.nextTick(function () { - self.element.css({overflowY: !!b ? "auto" : "hidden"}); + self.element.css({overflowY: b ? "auto" : "hidden"}); }); } }, @@ -331,7 +331,7 @@ BI.GridView = BI.inherit(BI.Widget, { this.options.estimatedRowSize = height; }, - //重新计算children + // 重新计算children _reRange: function () { this.renderRange = {}; }, @@ -360,4 +360,4 @@ BI.GridView = BI.inherit(BI.Widget, { } }); BI.GridView.EVENT_SCROLL = "EVENT_SCROLL"; -BI.shortcut('bi.grid_view', BI.GridView); \ No newline at end of file +BI.shortcut("bi.grid_view", BI.GridView); \ No newline at end of file diff --git a/src/base/layer/layer.floatbox.js b/src/base/layer/layer.floatbox.js index b7c284bdf..dde869b3e 100644 --- a/src/base/layer/layer.floatbox.js +++ b/src/base/layer/layer.floatbox.js @@ -9,7 +9,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { baseCls: "bi-float-box bi-card", width: 600, height: 500 - }) + }); }, _init: function () { BI.FloatBox.superclass._init.apply(this, arguments); @@ -35,19 +35,19 @@ BI.FloatBox = BI.inherit(BI.Widget, { if (ui.position.top < 0) { ui.position.top = 0; } - //BI-12134 没有什么特别好的方法 + // BI-12134 没有什么特别好的方法 BI.Resizers._resize(); } }); this._south = BI.createWidget(); BI.createWidget({ - type: 'bi.border', + type: "bi.border", element: this, items: { - 'north': { + north: { el: { - type: 'bi.border', - cls: 'bi-message-title bi-background', + type: "bi.border", + cls: "bi-message-title bi-background", items: { center: { el: { @@ -63,8 +63,8 @@ BI.FloatBox = BI.inherit(BI.Widget, { }, east: { el: { - type: 'bi.icon_button', - cls: 'bi-message-close close-font', + type: "bi.icon_button", + cls: "bi-message-close close-font", height: 50, handler: function () { self.currentSectionProvider.close(); @@ -76,7 +76,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { }, height: 50 }, - 'center': { + center: { el: { type: "bi.absolute", items: [{ @@ -88,7 +88,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { }] } }, - 'south': { + south: { el: { type: "bi.absolute", items: [{ @@ -102,7 +102,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { height: 60 } } - }) + }); }, populate: function (sectionProvider) { @@ -116,7 +116,7 @@ BI.FloatBox = BI.inherit(BI.Widget, { sectionProvider.rebuildSouth(this._south); sectionProvider.on(BI.PopoverSection.EVENT_CLOSE, function () { self.close(); - }) + }); }, show: function () { diff --git a/src/base/layer/layer.popup.js b/src/base/layer/layer.popup.js index 2d683d3d9..9a3722d31 100644 --- a/src/base/layer/layer.popup.js +++ b/src/base/layer/layer.popup.js @@ -7,9 +7,9 @@ BI.PopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.PopupView.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-popup-view", - maxWidth: 'auto', + maxWidth: "auto", minWidth: 100, - //maxHeight: 200, + // maxHeight: 200, minHeight: 25, lgap: 0, rgap: 0, @@ -17,16 +17,16 @@ BI.PopupView = BI.inherit(BI.Widget, { bgap: 0, vgap: 0, hgap: 0, - direction: BI.Direction.Top, //工具栏的方向 - stopEvent: false,//是否停止mousedown、mouseup事件 - stopPropagation: false, //是否停止mousedown、mouseup向上冒泡 + direction: BI.Direction.Top, // 工具栏的方向 + stopEvent: false, // 是否停止mousedown、mouseup事件 + stopPropagation: false, // 是否停止mousedown、mouseup向上冒泡 logic: { dynamic: true }, - tool: false, //自定义工具栏 - tabs: [], //导航栏 - buttons: [], //toolbar栏 + tool: false, // 自定义工具栏 + tabs: [], // 导航栏 + buttons: [], // toolbar栏 el: { type: "bi.button_group", @@ -37,28 +37,28 @@ BI.PopupView = BI.inherit(BI.Widget, { type: "bi.vertical" }] } - }) + }); }, _init: function () { BI.PopupView.superclass._init.apply(this, arguments); var self = this, o = this.options; var fn = function (e) { - e.stopPropagation(); - }, stop = function (e) { - e.stopEvent(); - return false; - }; + e.stopPropagation(); + }, stop = function (e) { + e.stopEvent(); + return false; + }; this.element.css({ "z-index": BI.zIndex_popup, "min-width": o.minWidth + "px", "max-width": o.maxWidth + "px" - }).bind({"click": fn}); + }).bind({click: fn}); this.element.bind("mousewheel", fn); - o.stopPropagation && this.element.bind({"mousedown": fn, "mouseup": fn, "mouseover": fn}); - o.stopEvent && this.element.bind({"mousedown": stop, "mouseup": stop, "mouseover": stop}); + o.stopPropagation && this.element.bind({mousedown: fn, mouseup: fn, mouseover: fn}); + o.stopEvent && this.element.bind({mousedown: stop, mouseup: stop, mouseover: stop}); this.tool = this._createTool(); this.tab = this._createTab(); this.view = this._createView(); @@ -103,7 +103,7 @@ BI.PopupView = BI.inherit(BI.Widget, { if (false === o.tool) { return; } - return BI.createWidget(o.tool) + return BI.createWidget(o.tool); }, _createTab: function () { @@ -116,7 +116,7 @@ BI.PopupView = BI.inherit(BI.Widget, { cls: "list-view-tab", height: 25, items: o.tabs - }) + }); }, _createToolBar: function () { @@ -134,7 +134,7 @@ BI.PopupView = BI.inherit(BI.Widget, { shadow: true, isShadowShowingOnSelected: true }) - }) + }); }, getView: function () { @@ -155,7 +155,7 @@ BI.PopupView = BI.inherit(BI.Widget, { tabHeight = this.tab ? (this.tab.attr("height") || 25) : 0, toolHeight = ((this.tool && this.tool.attr("height")) || 25) * ((this.tool && this.tool.isVisible()) ? 1 : 0); this.view.resetHeight ? this.view.resetHeight(h - tbHeight - tabHeight - toolHeight - 2) : - this.view.element.css({"max-height": (h - tbHeight - tabHeight - toolHeight - 2) + "px"}) + this.view.element.css({"max-height": (h - tbHeight - tabHeight - toolHeight - 2) + "px"}); }, setValue: function (selectedValues) { diff --git a/src/base/layer/layer.searcher.js b/src/base/layer/layer.searcher.js index 09dc6ff54..9e6073e39 100644 --- a/src/base/layer/layer.searcher.js +++ b/src/base/layer/layer.searcher.js @@ -14,7 +14,7 @@ BI.SearcherView = BI.inherit(BI.Pane, { tipText: BI.i18nText("BI-No_Select"), chooseType: BI.Selection.Single, - matcher: {//完全匹配的构造器 + matcher: {// 完全匹配的构造器 type: "bi.button_group", behaviors: { redmark: function () { @@ -38,7 +38,7 @@ BI.SearcherView = BI.inherit(BI.Pane, { type: "bi.vertical" }] } - }) + }); }, _init: function () { diff --git a/src/base/list/listview.js b/src/base/list/listview.js index b12ffb1d2..d6c4e7dbf 100644 --- a/src/base/list/listview.js +++ b/src/base/list/listview.js @@ -35,7 +35,7 @@ BI.ListView = BI.inherit(BI.Widget, { } }, o.el)], element: this - } + }; }, mounted: function () { @@ -106,5 +106,5 @@ BI.ListView = BI.inherit(BI.Widget, { this.restore(); } }); -BI.shortcut('bi.list_view', BI.ListView); +BI.shortcut("bi.list_view", BI.ListView); diff --git a/src/base/list/virtuallist.js b/src/base/list/virtuallist.js index fce34dbb7..928b5e1c1 100644 --- a/src/base/list/virtuallist.js +++ b/src/base/list/virtuallist.js @@ -44,7 +44,7 @@ BI.VirtualList = BI.inherit(BI.Widget, { } }], element: this - } + }; }, mounted: function () { @@ -175,5 +175,5 @@ BI.VirtualList = BI.inherit(BI.Widget, { this.restore(); } }); -BI.shortcut('bi.virtual_list', BI.VirtualList); +BI.shortcut("bi.virtual_list", BI.VirtualList); diff --git a/src/base/pager/pager.js b/src/base/pager/pager.js index 8c0a72936..3abbe7016 100644 --- a/src/base/pager/pager.js +++ b/src/base/pager/pager.js @@ -16,35 +16,35 @@ BI.Pager = BI.inherit(BI.Widget, { vgap: 0 }], - dynamicShow: true, //是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 - //dynamicShow为false时以下两个有用 - dynamicShowFirstLast: false,//是否动态显示首页、尾页 - dynamicShowPrevNext: false,//是否动态显示上一页、下一页 - pages: false, //总页数 + dynamicShow: true, // 是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 + // dynamicShow为false时以下两个有用 + dynamicShowFirstLast: false, // 是否动态显示首页、尾页 + dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 + pages: false, // 总页数 curr: function () { return 1; - }, //初始化当前页 - groups: 0, //连续显示分页数 - jump: BI.emptyFn, //分页的回调函数 + }, // 初始化当前页 + groups: 0, // 连续显示分页数 + jump: BI.emptyFn, // 分页的回调函数 - first: false, //是否显示首页 - last: false, //是否显示尾页 + first: false, // 是否显示首页 + last: false, // 是否显示尾页 prev: "上一页", next: "下一页", firstPage: 1, - lastPage: function () { //在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: function () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, - hasPrev: BI.emptyFn, //pages不可用时有效 - hasNext: BI.emptyFn //pages不可用时有效 - }) + hasPrev: BI.emptyFn, // pages不可用时有效 + hasNext: BI.emptyFn // pages不可用时有效 + }); }, _init: function () { BI.Pager.superclass._init.apply(this, arguments); var self = this; this.currPage = BI.result(this.options, "curr"); - //翻页太灵敏 + // 翻页太灵敏 // this._lock = false; // this._debouce = BI.debounce(function () { // self._lock = false; @@ -71,17 +71,17 @@ BI.Pager = BI.inherit(BI.Widget, { groups > pages && (groups = pages); } - //计算当前组 + // 计算当前组 dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); - //当前页非首页,则输出上一页 + // 当前页非首页,则输出上一页 if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) { if (BI.isKey(prev)) { view.push({ text: prev, value: "prev", disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) - }) + }); } else { view.push(BI.extend({ disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) @@ -89,7 +89,7 @@ BI.Pager = BI.inherit(BI.Widget, { } } - //当前组非首组,则输出首页 + // 当前组非首组,则输出首页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { view.push({ text: first, @@ -105,14 +105,14 @@ BI.Pager = BI.inherit(BI.Widget, { } } - //输出当前页组 + // 输出当前页组 dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; dict.end = dict.index > 1 ? (function () { var max = curr + (groups - dict.poor - 1); return max > pages ? pages : max; }()) : groups; - if (dict.end - dict.start < groups - 1) { //最后一组状态 + if (dict.end - dict.start < groups - 1) { // 最后一组状态 dict.start = dict.end - groups + 1; } var s = dict.start, e = dict.end; @@ -126,16 +126,16 @@ BI.Pager = BI.inherit(BI.Widget, { text: s, value: s, selected: true - }) + }); } else { view.push({ text: s, value: s - }) + }); } } - //总页数大于连续分页数,且当前组最大页小于总页,输出尾页 + // 总页数大于连续分页数,且当前组最大页小于总页,输出尾页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0) { view.push({ @@ -148,27 +148,27 @@ BI.Pager = BI.inherit(BI.Widget, { text: last, value: "last", disabled: !(pages > groups && dict.end < pages && groups !== 0) - }) + }); } - //当前页不为尾页时,输出下一页 + // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { if (BI.isKey(next)) { if (pages === false) { - return {text: next, value: "next", disabled: o.hasNext(curr) === false} + return {text: next, value: "next", disabled: o.hasNext(curr) === false}; } return (dict.flow && curr === pages) ? - {text: next, value: "next", disabled: true} + {text: next, value: "next", disabled: true} : - {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; - } else { - return BI.extend({ - disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) - }, next); + {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; } + return BI.extend({ + disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) + }, next); + }())); } diff --git a/src/base/pane.js b/src/base/pane.js index 1ef5b7f29..d540bf2e0 100644 --- a/src/base/pane.js +++ b/src/base/pane.js @@ -14,7 +14,7 @@ BI.Pane = BI.inherit(BI.Widget, { tipText: BI.i18nText("BI-No_Selected_Item"), overlap: true, onLoaded: BI.emptyFn - }) + }); }, _init: function () { @@ -44,7 +44,7 @@ BI.Pane = BI.inherit(BI.Widget, { if (o.overlap === true) { if (!BI.Layers.has(this.getName())) { BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", items: [{ el: { type: "bi.layout", @@ -72,7 +72,7 @@ BI.Pane = BI.inherit(BI.Widget, { right: 0, top: 0 }] - }) + }); } }, diff --git a/src/base/single/a/a.js b/src/base/single/a/a.js index d721337e1..03ef06616 100644 --- a/src/base/single/a/a.js +++ b/src/base/single/a/a.js @@ -15,7 +15,7 @@ BI.A = BI.inherit(BI.Text, { target: "_blank", el: null, element: "" - }) + }); }, _init: function () { var o = this.options; diff --git a/src/base/single/bar/bar.loading.js b/src/base/single/bar/bar.loading.js index 5479b81f0..bc79f5cbe 100644 --- a/src/base/single/bar/bar.loading.js +++ b/src/base/single/bar/bar.loading.js @@ -4,15 +4,15 @@ * @type {*|void|Object} */ BI.LoadingBar = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.LoadingBar.superclass._defaultConfig.apply(this, arguments); return BI.extend( conf, { - baseCls : (conf.baseCls ||"")+' bi-loading-bar bi-tips', + baseCls: (conf.baseCls || "") + " bi-loading-bar bi-tips", height: 30, handler: BI.emptyFn - }) + }); }, - _init : function() { + _init: function () { BI.LoadingBar.superclass._init.apply(this, arguments); var self = this; this.loaded = BI.createWidget({ @@ -21,25 +21,25 @@ BI.LoadingBar = BI.inherit(BI.Single, { text: BI.i18nText("BI-Load_More"), width: 120, handler: this.options.handler - }) - this.loaded.on(BI.Controller.EVENT_CHANGE, function(type){ + }); + this.loaded.on(BI.Controller.EVENT_CHANGE, function (type) { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); this.loading = BI.createWidget({ type: "bi.layout", width: this.options.height, - height:this.options.height, + height: this.options.height, cls: "loading-background cursor-default" - }) + }); var loaded = BI.createWidget({ type: "bi.center_adapt", items: [this.loaded] - }) + }); var loading = BI.createWidget({ type: "bi.center_adapt", items: [this.loading] - }) + }); this.cardLayout = BI.createWidget({ type: "bi.card", element: this, @@ -50,28 +50,28 @@ BI.LoadingBar = BI.inherit(BI.Single, { el: loading, cardName: "loading" }] - }) + }); this.invisible(); }, - _reset: function(){ + _reset: function () { this.visible(); this.loaded.setText(BI.i18nText("BI-Load_More")); this.loaded.enable(); }, - setLoaded: function(){ + setLoaded: function () { this._reset(); this.cardLayout.showCardByName("loaded"); }, - setEnd: function(){ + setEnd: function () { this.setLoaded(); this.loaded.setText(BI.i18nText("BI-No_More_Data")); this.loaded.disable(); }, - setLoading: function(){ + setLoading: function () { this._reset(); this.cardLayout.showCardByName("loading"); } diff --git a/src/base/single/button/button.basic.js b/src/base/single/button/button.basic.js index e438ca73e..6a7a408c7 100644 --- a/src/base/single/button/button.basic.js +++ b/src/base/single/button/button.basic.js @@ -15,16 +15,16 @@ BI.BasicButton = BI.inherit(BI.Single, { stopEvent: false, stopPropagation: false, selected: false, - once: false, //点击一次选中有效,再点无效 - forceSelected: false, //点击即选中, 选中了就不会被取消,与once的区别是forceSelected不影响事件的触发 - forceNotSelected: false, //无论怎么点击都不会被选中 - disableSelected: false, //使能选中 + once: false, // 点击一次选中有效,再点无效 + forceSelected: false, // 点击即选中, 选中了就不会被取消,与once的区别是forceSelected不影响事件的触发 + forceNotSelected: false, // 无论怎么点击都不会被选中 + disableSelected: false, // 使能选中 shadow: false, - isShadowShowingOnSelected: false, //选中状态下是否显示阴影 + isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 trigger: null, handler: BI.emptyFn - }) + }); }, _init: function () { BI.BasicButton.superclass._init.apply(this, arguments); @@ -195,10 +195,10 @@ BI.BasicButton = BI.inherit(BI.Single, { } }); - //之后的300ms点击无效 + // 之后的300ms点击无效 var onClick = BI.debounce(this._doClick, BI.EVENT_RESPONSE_TIME, true); - function ev(e) { + function ev (e) { if (o.stopEvent) { e.stopEvent(); } @@ -207,7 +207,7 @@ BI.BasicButton = BI.inherit(BI.Single, { } } - function clk(e) { + function clk (e) { ev(e); if (!self.isEnabled() || (self.isOnce() && self.isSelected())) { return; diff --git a/src/base/single/button/button.node.js b/src/base/single/button/button.node.js index fbc18a9f7..ce9bdc81e 100644 --- a/src/base/single/button/button.node.js +++ b/src/base/single/button/button.node.js @@ -7,47 +7,47 @@ * @abstract */ BI.NodeButton = BI.inherit(BI.BasicButton, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.NodeButton.superclass._defaultConfig.apply(this, arguments); return BI.extend( conf, { baseCls: (conf.baseCls || "") + " bi-node", open: false - }) + }); }, - _init:function() { + _init: function () { BI.NodeButton.superclass._init.apply(this, arguments); var self = this; - BI.nextTick(function(){ + BI.nextTick(function () { self.setOpened(self.isOpened()); - }) + }); }, - doClick: function(){ + doClick: function () { BI.NodeButton.superclass.doClick.apply(this, arguments); this.setOpened(!this.isOpened()); }, - isOnce: function(){ + isOnce: function () { return false; }, - isOpened: function(){ + isOpened: function () { return !!this.options.open; }, - setOpened: function(b){ + setOpened: function (b) { this.options.open = !!b; }, - triggerCollapse: function(){ + triggerCollapse: function () { if(this.isOpened()) { this.setOpened(false); this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.COLLAPSE, this.getValue(), this); } }, - triggerExpand: function(){ + triggerExpand: function () { if(!this.isOpened()) { this.setOpened(true); this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EXPAND, this.getValue(), this); diff --git a/src/base/single/button/buttons/button.icon.js b/src/base/single/button/buttons/button.icon.js index 1793df636..f41059b02 100644 --- a/src/base/single/button/buttons/button.icon.js +++ b/src/base/single/button/buttons/button.icon.js @@ -10,17 +10,17 @@ BI.IconButton = BI.inherit(BI.BasicButton, { baseCls: (conf.baseCls || "") + " bi-icon-button horizon-center", iconWidth: null, iconHeight: null - }) + }); }, _init: function () { BI.IconButton.superclass._init.apply(this, arguments); var o = this.options; this.element.css({ - textAlign: 'center' + textAlign: "center" }); this.icon = BI.createWidget({ - type: 'bi.icon', + type: "bi.icon", width: o.iconWidth, height: o.iconHeight }); @@ -30,11 +30,11 @@ BI.IconButton = BI.inherit(BI.BasicButton, { type: "bi.default", element: this, items: [this.icon] - }) + }); } else { BI.createWidget({ element: this, - type: 'bi.center_adapt', + type: "bi.center_adapt", items: [this.icon] }); } diff --git a/src/base/single/button/buttons/button.image.js b/src/base/single/button/buttons/button.image.js index 5e6467fe8..085e901a8 100644 --- a/src/base/single/button/buttons/button.image.js +++ b/src/base/single/button/buttons/button.image.js @@ -13,7 +13,7 @@ BI.ImageButton = BI.inherit(BI.BasicButton, { src: "", iconWidth: "100%", iconHeight: "100%" - }) + }); }, _init: function () { @@ -30,14 +30,14 @@ BI.ImageButton = BI.inherit(BI.BasicButton, { type: "bi.center_adapt", element: this, items: [this.image] - }) + }); } else { BI.createWidget({ type: "bi.adaptive", element: this, items: [this.image], scrollable: false - }) + }); } }, diff --git a/src/base/single/button/buttons/button.js b/src/base/single/button/buttons/button.js index f5450b38f..b6609d617 100644 --- a/src/base/single/button/buttons/button.js +++ b/src/base/single/button/buttons/button.js @@ -13,15 +13,15 @@ _defaultConfig: function (props) { var conf = BI.Button.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { - baseCls: (conf.baseCls || "") + ' bi-button', + baseCls: (conf.baseCls || "") + " bi-button", minWidth: (props.block === true || props.clear === true) ? 0 : 90, shadow: props.clear !== true, isShadowShowingOnSelected: true, readonly: true, iconClass: "", - level: 'common', - block: false, //是否块状显示,即不显示边框,没有最小宽度的限制 - clear: false, //是否去掉边框和背景 + level: "common", + block: false, // 是否块状显示,即不显示边框,没有最小宽度的限制 + clear: false, // 是否去掉边框和背景 textAlign: "center", whiteSpace: "nowrap", forceCenter: false, @@ -33,7 +33,7 @@ bgap: 0, lgap: 0, rgap: 0 - }) + }); }, _init: function () { @@ -68,7 +68,7 @@ type: "bi.horizontal", items: [this.icon, this.text] }] - }) + }); } else { this.text = BI.createWidget({ type: "bi.label", @@ -139,6 +139,6 @@ BI.Button.superclass.destroy.apply(this, arguments); } }); - BI.shortcut('bi.button', BI.Button); + BI.shortcut("bi.button", BI.Button); BI.Button.EVENT_CHANGE = "EVENT_CHANGE"; })(jQuery); \ No newline at end of file diff --git a/src/base/single/button/buttons/button.text.js b/src/base/single/button/buttons/button.text.js index 0b121fd87..2f8476fad 100644 --- a/src/base/single/button/buttons/button.text.js +++ b/src/base/single/button/buttons/button.text.js @@ -20,7 +20,7 @@ BI.TextButton = BI.inherit(BI.BasicButton, { rgap: 0, text: "", py: "" - }) + }); }, _init: function () { diff --git a/src/base/single/button/listitem/blankiconicontextitem.js b/src/base/single/button/listitem/blankiconicontextitem.js index affe804ac..90a74bc05 100644 --- a/src/base/single/button/listitem/blankiconicontextitem.js +++ b/src/base/single/button/listitem/blankiconicontextitem.js @@ -26,7 +26,7 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconIconTextItem.superclass._init.apply(this, arguments); @@ -35,7 +35,7 @@ BI.BlankIconIconTextItem = BI.inherit(BI.BasicButton, { type: "bi.layout", width: o.blankWidth, height: o.height - }) + }); this.text = BI.createWidget({ type: "bi.label", cls: "list-item-text", diff --git a/src/base/single/button/listitem/blankicontexticonitem.js b/src/base/single/button/listitem/blankicontexticonitem.js index 349a1f432..7d019e57f 100644 --- a/src/base/single/button/listitem/blankicontexticonitem.js +++ b/src/base/single/button/listitem/blankicontexticonitem.js @@ -27,7 +27,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconTextIconItem.superclass._init.apply(this, arguments); @@ -43,7 +43,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); var icon1 = BI.createWidget({ type: "bi.center_adapt", @@ -57,7 +57,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { height: o.iconHeight } }] - }) + }); BI.createWidget({ type: "bi.absolute", element: this, @@ -79,7 +79,7 @@ BI.BlankIconTextIconItem = BI.inherit(BI.BasicButton, { bottom: 0, right: 0 }] - }) + }); BI.createWidget(BI.extend({ element: this diff --git a/src/base/single/button/listitem/blankicontextitem.js b/src/base/single/button/listitem/blankicontextitem.js index ed890dc72..54d5e744b 100644 --- a/src/base/single/button/listitem/blankicontextitem.js +++ b/src/base/single/button/listitem/blankicontextitem.js @@ -25,7 +25,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.BlankIconTextItem.superclass._init.apply(this, arguments); @@ -33,7 +33,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { var blank = BI.createWidget({ type: "bi.layout", width: o.blankWidth - }) + }); this.text = BI.createWidget({ type: "bi.label", cls: "list-item-text", @@ -46,7 +46,7 @@ BI.BlankIconTextItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); this.icon = BI.createWidget({ type: "bi.center_adapt", width: c.commonWidth, diff --git a/src/base/single/button/listitem/icontexticonitem.js b/src/base/single/button/listitem/icontexticonitem.js index a267d789f..615472c59 100644 --- a/src/base/single/button/listitem/icontexticonitem.js +++ b/src/base/single/button/listitem/icontexticonitem.js @@ -26,7 +26,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextIconItem.superclass._init.apply(this, arguments); @@ -42,7 +42,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); var icon1 = BI.createWidget({ type: "bi.center_adapt", @@ -56,11 +56,11 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { height: o.iconHeight } }] - }) + }); var blank = BI.createWidget({ type: "bi.layout", width: c.commonWidth - }) + }); BI.createWidget({ type: "bi.absolute", element: this, @@ -81,7 +81,7 @@ BI.IconTextIconItem = BI.inherit(BI.BasicButton, { bottom: 0, right: 0 }] - }) + }); BI.createWidget(BI.extend({ element: this diff --git a/src/base/single/button/listitem/icontextitem.js b/src/base/single/button/listitem/icontextitem.js index 02004fa70..fab2afab6 100644 --- a/src/base/single/button/listitem/icontextitem.js +++ b/src/base/single/button/listitem/icontextitem.js @@ -24,7 +24,7 @@ BI.IconTextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextItem.superclass._init.apply(this, arguments); diff --git a/src/base/single/button/listitem/texticonitem.js b/src/base/single/button/listitem/texticonitem.js index 068a4ba5e..55bba2733 100644 --- a/src/base/single/button/listitem/texticonitem.js +++ b/src/base/single/button/listitem/texticonitem.js @@ -25,7 +25,7 @@ BI.TextIconItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextIconItem.superclass._init.apply(this, arguments); diff --git a/src/base/single/button/listitem/textitem.js b/src/base/single/button/listitem/textitem.js index d3599f770..d842e7a27 100644 --- a/src/base/single/button/listitem/textitem.js +++ b/src/base/single/button/listitem/textitem.js @@ -18,7 +18,7 @@ BI.TextItem = BI.inherit(BI.BasicButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextItem.superclass._init.apply(this, arguments); diff --git a/src/base/single/button/node/icontexticonnode.js b/src/base/single/button/node/icontexticonnode.js index 85d662a73..65cb89227 100644 --- a/src/base/single/button/node/icontexticonnode.js +++ b/src/base/single/button/node/icontexticonnode.js @@ -24,7 +24,7 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextIconNode.superclass._init.apply(this, arguments); @@ -40,7 +40,7 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); var icon1 = BI.createWidget({ type: "bi.center_adapt", @@ -54,12 +54,12 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { height: o.iconHeight } }] - }) + }); var blank = BI.createWidget({ type: "bi.layout", width: c.commonWidth, height: o.height - }) + }); BI.createWidget({ type: "bi.absolute", element: this, @@ -80,7 +80,7 @@ BI.IconTextIconNode = BI.inherit(BI.NodeButton, { bottom: 0, right: 0 }] - }) + }); BI.createWidget(BI.extend({ element: this diff --git a/src/base/single/button/node/icontextnode.js b/src/base/single/button/node/icontextnode.js index 408707618..7e4eb6349 100644 --- a/src/base/single/button/node/icontextnode.js +++ b/src/base/single/button/node/icontextnode.js @@ -23,7 +23,7 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.IconTextNode.superclass._init.apply(this, arguments); @@ -40,7 +40,7 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); this.icon = BI.createWidget({ type: "bi.center_adapt", width: c.commonWidth, @@ -52,7 +52,7 @@ BI.IconTextNode = BI.inherit(BI.NodeButton, { height: o.iconHeight } }] - }) + }); BI.createWidget(BI.extend({ element: this diff --git a/src/base/single/button/node/texticonnode.js b/src/base/single/button/node/texticonnode.js index a32fa4dc8..667d74e3f 100644 --- a/src/base/single/button/node/texticonnode.js +++ b/src/base/single/button/node/texticonnode.js @@ -22,7 +22,7 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextIconNode.superclass._init.apply(this, arguments); @@ -39,7 +39,7 @@ BI.TextIconNode = BI.inherit(BI.NodeButton, { value: o.value, keyword: o.keyword, height: o.height - }) + }); this.icon = BI.createWidget({ type: "bi.center_adapt", width: c.commonWidth, diff --git a/src/base/single/button/node/textnode.js b/src/base/single/button/node/textnode.js index d0fcc5c48..2c7cdbda0 100644 --- a/src/base/single/button/node/textnode.js +++ b/src/base/single/button/node/textnode.js @@ -17,7 +17,7 @@ BI.TextNode = BI.inherit(BI.NodeButton, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.TextNode.superclass._init.apply(this, arguments); diff --git a/src/base/single/editor/editor.code.js b/src/base/single/editor/editor.code.js index 6fff97d19..c7070d06b 100644 --- a/src/base/single/editor/editor.code.js +++ b/src/base/single/editor/editor.code.js @@ -7,12 +7,12 @@ BI.CodeEditor = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-code-editor', - value: '', + baseCls: "bi-code-editor", + value: "", watermark: "", lineHeight: 2, readOnly: false, - //参数显示值构造函数 + // 参数显示值构造函数 paramFormatter: function (v) { return v; } @@ -26,13 +26,13 @@ BI.CodeEditor = BI.inherit(BI.Single, { lineWrapping: true, lineNumbers: false, readOnly: o.readOnly, - //解决插入字段由括号或其他特殊字符包围时分裂的bug + // 解决插入字段由括号或其他特殊字符包围时分裂的bug specialChars: /[\u0000-\u001f\u007f\u00ad\u200c-\u200f\u2028\u2029\ufeff]/ }); o.lineHeight === 1 ? this.element.addClass("codemirror-low-line-height") : this.element.addClass("codemirror-high-line-height"); this.editor.on("change", function (cm, change) { BI.nextTick(function () { - self.fireEvent(BI.CodeEditor.EVENT_CHANGE) + self.fireEvent(BI.CodeEditor.EVENT_CHANGE); }); }); @@ -58,7 +58,7 @@ BI.CodeEditor = BI.inherit(BI.Single, { // self.editor.execCommand("goLineEnd"); // }); - //水印 + // 水印 this.watermark = BI.createWidget({ type: "bi.label", text: o.watermark, @@ -96,7 +96,7 @@ BI.CodeEditor = BI.inherit(BI.Single, { _setEnable: function (b) { BI.CodeEditor.superclass._setEnable.apply(this, arguments); - this.editor.setOption("readOnly", b === true ? false : "nocursor") + this.editor.setOption("readOnly", b === true ? false : "nocursor"); }, _checkWaterMark: function () { @@ -112,12 +112,12 @@ BI.CodeEditor = BI.inherit(BI.Single, { var value = param; param = this.options.paramFormatter(param); var from = this.editor.getCursor(); - //解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 - this.editor.replaceSelection('\u200b' + param + '\u200b'); + // 解决插入字段由括号或其他特殊字符包围时分裂的bug,在两端以不可见字符包裹一下 + this.editor.replaceSelection("\u200b" + param + "\u200b"); var to = this.editor.getCursor(); - var options = {className: 'param', atomic: true}; + var options = {className: "param", atomic: true}; if (BI.isNotNull(param.match(/^$/))) { - options.className = 'error-param'; + options.className = "error-param"; } options.value = value; this.editor.markText(from, to, options); @@ -134,16 +134,16 @@ BI.CodeEditor = BI.inherit(BI.Single, { return this.editor.getValue("\n", function (line) { var rawText = line.text, value = line.text, num = 0; value.text = rawText; - //根据插入位置不同,line.markedSpan可能是乱序的 + // 根据插入位置不同,line.markedSpan可能是乱序的 _.forEach(_.sortBy(line.markedSpans, "from"), function (i, ms) { switch (i.marker.className) { case "param": case "error-param": var fieldNameLength = i.to - i.from; value = value.substr(0, i.from + num) + "$\{" + i.marker.value + "\}" + value.substr(i.to + num, value.length); - //加上${}的偏移 + // 加上${}的偏移 num += 3; - //加上实际值和显示值的长度差的偏移 + // 加上实际值和显示值的长度差的偏移 num += (i.marker.value.length - fieldNameLength); break; } diff --git a/src/base/single/editor/editor.js b/src/base/single/editor/editor.js index c19b2b974..96d90c5a0 100644 --- a/src/base/single/editor/editor.js +++ b/src/base/single/editor/editor.js @@ -14,7 +14,7 @@ BI.Editor = BI.inherit(BI.Single, { rgap: 0, tgap: 0, bgap: 0, - //title,warningTitle这两个属性没用 + // title,warningTitle这两个属性没用 tipType: "warning", inputType: "text", validationChecker: BI.emptyFn, @@ -22,7 +22,7 @@ BI.Editor = BI.inherit(BI.Single, { allowBlank: false, watermark: "", errorText: "" - }) + }); }, _init: function () { @@ -38,12 +38,12 @@ BI.Editor = BI.inherit(BI.Single, { allowBlank: o.allowBlank })); this.editor.element.css({ - "width": "100%", - "height": "100%", - "border": "none", - "outline": "none", - "padding": "0", - "margin": "0" + width: "100%", + height: "100%", + border: "none", + outline: "none", + padding: "0", + margin: "0" }); if (BI.isKey(this.options.watermark)) { this.watermark = BI.createWidget({ diff --git a/src/base/single/editor/editor.multifile.js b/src/base/single/editor/editor.multifile.js index b004217ec..40aae20dc 100644 --- a/src/base/single/editor/editor.multifile.js +++ b/src/base/single/editor/editor.multifile.js @@ -12,10 +12,10 @@ BI.MultifileEditor = BI.inherit(BI.Single, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-multifile-editor", multiple: false, - maxSize: -1,//1024 * 1024 + maxSize: -1, // 1024 * 1024 accept: "", url: "" - }) + }); }, _init: function () { diff --git a/src/base/single/editor/editor.textarea.js b/src/base/single/editor/editor.textarea.js index faad35840..a3cacaace 100644 --- a/src/base/single/editor/editor.textarea.js +++ b/src/base/single/editor/editor.textarea.js @@ -7,8 +7,8 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.TextAreaEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-textarea-editor bi-card', - value: '' + baseCls: "bi-textarea-editor bi-card", + value: "" }); }, _init: function () { @@ -21,7 +21,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { height: "100%", cls: "bi-textarea textarea-editor-content display-block" }); - this.content.element.css({"resize": "none"}); + this.content.element.css({resize: "none"}); BI.createWidget({ type: "bi.absolute", element: this, @@ -92,7 +92,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { self.focus(); }); BI.createWidget({ - type: 'bi.absolute', + type: "bi.absolute", element: this, items: [{ el: this.watermark, @@ -100,7 +100,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { top: 0, right: 0 }] - }) + }); } else { this.watermark.setText(o.watermark); this.watermark.setValid(!o.invalid); @@ -144,7 +144,7 @@ BI.TextAreaEditor = BI.inherit(BI.Single, { this.element.css(style); this.content.element.css(BI.extend({}, style, { color: style.color || BI.DOM.getContrastColor(BI.DOM.isRGBColor(style.backgroundColor) ? BI.DOM.rgb2hex(style.backgroundColor) : style.backgroundColor) - })) + })); }, getStyle: function () { diff --git a/src/base/single/icon/icon.js b/src/base/single/icon/icon.js index 51804c51c..306921102 100644 --- a/src/base/single/icon/icon.js +++ b/src/base/single/icon/icon.js @@ -9,7 +9,7 @@ BI.Icon = BI.inherit(BI.Single, { return BI.extend(conf, { tagName: "i", baseCls: (conf.baseCls || "") + " x-icon b-font horizon-center display-block" - }) + }); }, _init: function () { BI.Icon.superclass._init.apply(this, arguments); diff --git a/src/base/single/iframe/iframe.js b/src/base/single/iframe/iframe.js index 141be9b13..8e0c8e539 100644 --- a/src/base/single/iframe/iframe.js +++ b/src/base/single/iframe/iframe.js @@ -12,7 +12,7 @@ BI.Iframe = BI.inherit(BI.Single, { src: "", width: "100%", height: "100%" - }) + }); }, _init: function () { @@ -40,11 +40,11 @@ BI.Iframe = BI.inherit(BI.Single, { }, getWidth: function () { - return this.options.width + return this.options.width; }, getHeight: function () { - return this.options.height + return this.options.height; } }); diff --git a/src/base/single/img/img.js b/src/base/single/img/img.js index 3cf9aee79..aa5054bc4 100644 --- a/src/base/single/img/img.js +++ b/src/base/single/img/img.js @@ -14,7 +14,7 @@ BI.Img = BI.inherit(BI.Single, { src: "", width: "100%", height: "100%" - }) + }); }, _init: function () { diff --git a/src/base/single/input/checkbox.js b/src/base/single/input/checkbox.js index 859340504..6ebbb9310 100644 --- a/src/base/single/input/checkbox.js +++ b/src/base/single/input/checkbox.js @@ -4,8 +4,8 @@ * @type {*|void|Object} */ BI.Checkbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.Checkbox.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.Checkbox.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-checkbox check-box-icon", selected: false, @@ -14,16 +14,16 @@ BI.Checkbox = BI.inherit(BI.IconButton, { height: 16, iconWidth: 16, iconHeight: 16 - }) + }); }, - _init : function() { + _init: function () { BI.Checkbox.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.Checkbox.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.Checkbox.EVENT_CHANGE); } } diff --git a/src/base/single/input/input.js b/src/base/single/input/input.js index e27f06c5a..a88499f2f 100644 --- a/src/base/single/input/input.js +++ b/src/base/single/input/input.js @@ -11,9 +11,9 @@ BI.Input = BI.inherit(BI.Single, { baseCls: (conf.baseCls || "") + " bi-input display-block", element: "", validationChecker: BI.emptyFn, - quitChecker: BI.emptyFn,//按确定键能否退出编辑 + quitChecker: BI.emptyFn, // 按确定键能否退出编辑 allowBlank: false - }) + }); }, _init: function () { @@ -40,8 +40,8 @@ BI.Input = BI.inherit(BI.Single, { } }) .on("input propertychange", function (e) { - //这个事件在input的属性发生改变的时候就会触发(class的变化也算) - if(BI.isNotNull(e.keyCode)){ + // 这个事件在input的属性发生改变的时候就会触发(class的变化也算) + if(BI.isNotNull(e.keyCode)) { inputEventValid = true; self._keydown_ = true; _keydown(e.keyCode); @@ -77,7 +77,7 @@ BI.Input = BI.inherit(BI.Single, { } else { blur(); } - function blur() { + function blur () { if (!self.isValid() && self.options.quitChecker.apply(self, [BI.trim(self.getValue())]) !== false) { self.element.val(self._lastValidValue ? self._lastValidValue : ""); self._checkValidationOnValueChange(); @@ -119,7 +119,7 @@ BI.Input = BI.inherit(BI.Single, { this.fireEvent(BI.Input.EVENT_START); } } - if (ctrlKey === true && keyCode === 86) {//ctrlKey+V + if (ctrlKey === true && keyCode === 86) {// ctrlKey+V this._valueChange(); } else { if (keyCode == BI.KeyCode.ENTER) { @@ -157,7 +157,7 @@ BI.Input = BI.inherit(BI.Single, { } }, - //初始状态 + // 初始状态 _defaultState: function () { if (this.getValue() == "") { this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.EMPTY, this.getValue(), this); diff --git a/src/base/single/input/radio.js b/src/base/single/input/radio.js index dcd26722c..04a04ad9c 100644 --- a/src/base/single/input/radio.js +++ b/src/base/single/input/radio.js @@ -4,8 +4,8 @@ * @type {*|void|Object} */ BI.Radio = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.Radio.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.Radio.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-radio radio-icon", selected: false, @@ -14,16 +14,16 @@ BI.Radio = BI.inherit(BI.IconButton, { height: 16, iconWidth: 16, iconHeight: 16 - }) + }); }, - _init : function() { + _init: function () { BI.Radio.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.Radio.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.Radio.EVENT_CHANGE); } } diff --git a/src/base/single/label/label.js b/src/base/single/label/label.js index bbb0deb48..d0eaf88dd 100644 --- a/src/base/single/label/label.js +++ b/src/base/single/label/label.js @@ -8,8 +8,8 @@ BI.Label = BI.inherit(BI.Single, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-label", textAlign: "center", - whiteSpace: "nowrap", //normal or nowrap - forceCenter: false, //是否无论如何都要居中, 不考虑超出边界的情况, 在未知宽度和高度时有效 + whiteSpace: "nowrap", // normal or nowrap + forceCenter: false, // 是否无论如何都要居中, 不考虑超出边界的情况, 在未知宽度和高度时有效 textWidth: null, textHeight: null, hgap: 0, @@ -21,7 +21,7 @@ BI.Label = BI.inherit(BI.Single, { text: "", py: "", keyword: "" - }) + }); }, _createJson: function () { @@ -226,7 +226,7 @@ BI.Label = BI.inherit(BI.Single, { type: "bi.layout", element: this.text, scrollable: o.whiteSpace === "normal" - }) + }); }, _createNotCenterEl: function () { @@ -344,7 +344,7 @@ BI.Label = BI.inherit(BI.Single, { return; } if (o.whiteSpace == "normal") { - this.text = BI.createWidget(json) + this.text = BI.createWidget(json); BI.createWidget({ type: "bi.vertical_adapt", scrollable: o.whiteSpace === "normal", @@ -424,7 +424,7 @@ BI.Label = BI.inherit(BI.Single, { type: "bi.layout", element: this.text, scrollable: o.whiteSpace === "normal" - }) + }); }, doRedMark: function () { @@ -453,7 +453,7 @@ BI.Label = BI.inherit(BI.Single, { }, setStyle: function (css) { - this.text.setStyle(css) + this.text.setStyle(css); }, setValue: function (v) { diff --git a/src/base/single/link/link.js b/src/base/single/link/link.js index ca6895d43..59ef99c21 100644 --- a/src/base/single/link/link.js +++ b/src/base/single/link/link.js @@ -4,19 +4,19 @@ * @extends BI.Text */ BI.Link = BI.inherit(BI.Label, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Link.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-link", href: "", target: "_blank" - }) + }); }, - _createJson: function(){ + _createJson: function () { var o = this.options; return { - type:"bi.a", + type: "bi.a", textAlign: o.textAlign, whiteSpace: o.whiteSpace, lineHeight: o.textHeight, @@ -29,7 +29,7 @@ BI.Link = BI.inherit(BI.Label, { }; }, - _init : function() { + _init: function () { BI.Link.superclass._init.apply(this, arguments); } }); diff --git a/src/base/single/single.js b/src/base/single/single.js index 8bf74ec1a..22f52ac6e 100644 --- a/src/base/single/single.js +++ b/src/base/single/single.js @@ -19,7 +19,7 @@ BI.Single = BI.inherit(BI.Widget, { warningTitle: null, tipType: null, // success或warning value: null - }) + }); }, _showToolTip: function (e, opt) { @@ -88,7 +88,7 @@ BI.Single = BI.inherit(BI.Widget, { }, disabledHover: function () { - //取消hover事件 + // 取消hover事件 if (BI.isNotNull(this.timeout)) { clearTimeout(this.timeout); } @@ -103,7 +103,7 @@ BI.Single = BI.inherit(BI.Widget, { this.items = items || []; }, - //opt: {container: '', belowMouse: false} + // opt: {container: '', belowMouse: false} setTitle: function (title, opt) { this.options.title = title; if (BI.isKey(title)) { diff --git a/src/base/single/text.js b/src/base/single/text.js index 019870bec..186aae317 100644 --- a/src/base/single/text.js +++ b/src/base/single/text.js @@ -11,7 +11,7 @@ BI.Text = BI.inherit(BI.Single, { textAlign: "left", whiteSpace: "normal", lineHeight: null, - handler: null,//如果传入handler,表示处理文字的点击事件,不是区域的 + handler: null, // 如果传入handler,表示处理文字的点击事件,不是区域的 hgap: 0, vgap: 0, lgap: 0, @@ -20,7 +20,7 @@ BI.Text = BI.inherit(BI.Single, { bgap: 0, text: "", py: "" - }) + }); }, _init: function () { @@ -29,37 +29,37 @@ BI.Text = BI.inherit(BI.Single, { if (o.hgap + o.lgap > 0) { this.element.css({ "padding-left": o.hgap + o.lgap + "px" - }) + }); } if (o.hgap + o.rgap > 0) { this.element.css({ "padding-right": o.hgap + o.rgap + "px" - }) + }); } if (o.vgap + o.tgap > 0) { this.element.css({ "padding-top": o.vgap + o.tgap + "px" - }) + }); } if (o.vgap + o.bgap > 0) { this.element.css({ "padding-bottom": o.vgap + o.bgap + "px" - }) + }); } if (BI.isNumber(o.height)) { - this.element.css({"lineHeight": o.height + "px"}); + this.element.css({lineHeight: o.height + "px"}); } if (BI.isNumber(o.lineHeight)) { - this.element.css({"lineHeight": o.lineHeight + "px"}); + this.element.css({lineHeight: o.lineHeight + "px"}); } this.element.css({ - "textAlign": o.textAlign, - "whiteSpace": o.whiteSpace + textAlign: o.textAlign, + whiteSpace: o.whiteSpace }); if (o.handler) { this.text = BI.createWidget({ type: "bi.layout", - tagName: 'span' + tagName: "span" }); this.text.element.click(function () { o.handler(self.getValue()); @@ -108,7 +108,7 @@ BI.Text = BI.inherit(BI.Single, { }, setStyle: function (css) { - this.text.element.css(css) + this.text.element.css(css); }, setText: function (text) { diff --git a/src/base/single/tip/tip.bubble.js b/src/base/single/tip/tip.bubble.js index 425578a00..ded1eaf6f 100644 --- a/src/base/single/tip/tip.bubble.js +++ b/src/base/single/tip/tip.bubble.js @@ -6,30 +6,30 @@ * @type {*|void|Object} */ BI.Bubble = BI.inherit(BI.Tip, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend(BI.Bubble.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-bubble", direction: "top", text: "", height: 35 - }) + }); }, - _init : function() { + _init: function () { BI.Bubble.superclass._init.apply(this, arguments); var fn = function (e) { e.stopPropagation(); e.stopEvent(); return false; }; - this.element.bind({"click": fn, "mousedown": fn, "mouseup": fn, "mouseover": fn, "mouseenter": fn, "mouseleave": fn, "mousemove": fn}); + this.element.bind({click: fn, mousedown: fn, mouseup: fn, mouseover: fn, mouseenter: fn, mouseleave: fn, mousemove: fn}); BI.createWidget({ type: "bi.left", element: this, items: [this["_" + this.options.direction]()] - }) + }); }, - _createBubbleText: function(){ + _createBubbleText: function () { return (this.text = BI.createWidget({ type: "bi.label", cls: "bubble-text", @@ -39,7 +39,7 @@ BI.Bubble = BI.inherit(BI.Tip, { })); }, - _top: function(){ + _top: function () { return BI.createWidget({ type: "bi.vertical", items: [{ @@ -51,10 +51,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, height: 3 }] - }) + }); }, - _bottom: function(){ + _bottom: function () { return BI.createWidget({ type: "bi.vertical", items: [{ @@ -66,10 +66,10 @@ BI.Bubble = BI.inherit(BI.Tip, { el: this._createBubbleText(), height: 30 }] - }) + }); }, - _left: function(){ + _left: function () { return BI.createWidget({ type: "bi.right", items: [{ @@ -81,10 +81,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, { el: this._createBubbleText() }] - }) + }); }, - _right: function(){ + _right: function () { return BI.createWidget({ type: "bi.left", items: [{ @@ -96,10 +96,10 @@ BI.Bubble = BI.inherit(BI.Tip, { }, { el: this._createBubbleText() }] - }) + }); }, - setText: function(text){ + setText: function (text) { this.text.setText(text); } }); diff --git a/src/base/single/tip/tip.js b/src/base/single/tip/tip.js index 01a1cf9f4..5ee0829ee 100644 --- a/src/base/single/tip/tip.js +++ b/src/base/single/tip/tip.js @@ -7,16 +7,16 @@ * @abstract */ BI.Tip = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Link.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-tip", zIndex: BI.zIndex_tip - }) + }); }, - _init : function() { + _init: function () { BI.Tip.superclass._init.apply(this, arguments); - this.element.css({"zIndex": this.options.zIndex}); + this.element.css({zIndex: this.options.zIndex}); } }); \ No newline at end of file diff --git a/src/base/single/tip/tip.toast.js b/src/base/single/tip/tip.toast.js index 1a0c45f00..f5f944cee 100644 --- a/src/base/single/tip/tip.toast.js +++ b/src/base/single/tip/tip.toast.js @@ -15,23 +15,23 @@ BI.Toast = BI.inherit(BI.Tip, { return BI.extend(BI.Toast.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-toast", text: "", - level: "success",//success或warning + level: "success", // success或warning height: 30 - }) + }); }, _init: function () { BI.Toast.superclass._init.apply(this, arguments); var o = this.options; this.element.css({ minWidth: this._const.minWidth + "px" - }) + }); this.element.addClass("toast-" + o.level); var fn = function (e) { e.stopPropagation(); e.stopEvent(); return false; }; - this.element.bind({"click": fn, "mousedown": fn, "mouseup": fn, "mouseover": fn, "mouseenter": fn, "mouseleave": fn, "mousemove": fn}); + this.element.bind({click: fn, mousedown: fn, mouseup: fn, mouseover: fn, mouseenter: fn, mouseleave: fn, mousemove: fn}); this.text = BI.createWidget({ type: "bi.label", @@ -39,10 +39,10 @@ BI.Toast = BI.inherit(BI.Tip, { text: o.text, height: 30, hgap: this._const.hgap - }) + }); }, - setWidth: function(width){ + setWidth: function (width) { this.element.width(width); }, diff --git a/src/base/single/tip/tip.tooltip.js b/src/base/single/tip/tip.tooltip.js index 64dd0c594..134d4afd7 100644 --- a/src/base/single/tip/tip.tooltip.js +++ b/src/base/single/tip/tip.tooltip.js @@ -14,11 +14,11 @@ BI.Tooltip = BI.inherit(BI.Tip, { return BI.extend(BI.Tooltip.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-tooltip", text: "", - level: "success",//success或warning + level: "success", // success或warning stopEvent: false, stopPropagation: false, height: 20 - }) + }); }, _init: function () { BI.Tooltip.superclass._init.apply(this, arguments); @@ -29,13 +29,13 @@ BI.Tooltip = BI.inherit(BI.Tip, { o.stopEvent && e.stopEvent(); }; this.element.bind({ - "click": fn, - "mousedown": fn, - "mouseup": fn, - "mouseover": fn, - "mouseenter": fn, - "mouseleave": fn, - "mousemove": fn + click: fn, + mousedown: fn, + mouseup: fn, + mouseover: fn, + mouseenter: fn, + mouseleave: fn, + mousemove: fn }); var texts = (o.text + "").split("\n"); @@ -51,9 +51,9 @@ BI.Tooltip = BI.inherit(BI.Tip, { whiteSpace: "normal", text: text, textHeight: 16 - } + }; }) - }) + }); } else { this.text = BI.createWidget({ type: "bi.label", diff --git a/src/base/single/trigger/trigger.js b/src/base/single/trigger/trigger.js index e78dbacee..fee7f867c 100644 --- a/src/base/single/trigger/trigger.js +++ b/src/base/single/trigger/trigger.js @@ -5,23 +5,23 @@ * @abstract */ BI.Trigger = BI.inherit(BI.Single, { - _defaultConfig: function() { + _defaultConfig: function () { var conf = BI.Trigger.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-trigger cursor-pointer", height: 24 - }) + }); }, - _init : function() { + _init: function () { BI.Trigger.superclass._init.apply(this, arguments); }, - setKey: function(){ + setKey: function () { }, - getKey: function(){ + getKey: function () { } }); \ No newline at end of file diff --git a/src/base/sql/codemirrior/sql-hint.js b/src/base/sql/codemirrior/sql-hint.js index a34ae5e5d..0b1e73ca0 100644 --- a/src/base/sql/codemirrior/sql-hint.js +++ b/src/base/sql/codemirrior/sql-hint.js @@ -1,312 +1,305 @@ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE -(function(mod) { - mod(CodeMirror); -})(function(CodeMirror) { - - var tables; - var defaultTable; - var keywords; - var identifierQuote; - var CONS = { - QUERY_DIV: ";", - ALIAS_KEYWORD: "AS" - }; - var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos; - - function isArray(val) { return Object.prototype.toString.call(val) == "[object Array]" } - - function getKeywords(editor) { - var mode = editor.doc.modeOption; - if (mode === "sql") mode = "text/x-sql"; - return CodeMirror.resolveMode(mode).keywords; - } - - function getIdentifierQuote(editor) { - var mode = editor.doc.modeOption; - if (mode === "sql") mode = "text/x-sql"; - return CodeMirror.resolveMode(mode).identifierQuote || "`"; - } - - function getText(item) { - return typeof item == "string" ? item : item.text; - } - - function wrapTable(name, value) { - if (isArray(value)) value = {columns: value} - if (!value.text) value.text = name - return value - } - - function parseTables(input) { - var result = {} - if (isArray(input)) { - for (var i = input.length - 1; i >= 0; i--) { - var item = input[i] - result[getText(item).toUpperCase()] = wrapTable(getText(item), item) - } - } else if (input) { - for (var name in input) - result[name.toUpperCase()] = wrapTable(name, input[name]) - } - return result - } - - function getTable(name) { - return tables[name.toUpperCase()] - } - - function shallowClone(object) { - var result = {}; - for (var key in object) if (object.hasOwnProperty(key)) - result[key] = object[key]; - return result; - } - - function match(string, word) { - if (BI.isNotEmptyString(string) && word.length !== string.length) { - var len = string.length; - var sub = getText(word).substr(0, len); - return string.toUpperCase() === sub.toUpperCase(); +(function (mod) { + mod(CodeMirror); +})(function (CodeMirror) { + + var tables; + var defaultTable; + var keywords; + var identifierQuote; + var CONS = { + QUERY_DIV: ";", + ALIAS_KEYWORD: "AS" + }; + var Pos = CodeMirror.Pos, cmpPos = CodeMirror.cmpPos; + + function isArray (val) { return Object.prototype.toString.call(val) == "[object Array]"; } + + function getKeywords (editor) { + var mode = editor.doc.modeOption; + if (mode === "sql") mode = "text/x-sql"; + return CodeMirror.resolveMode(mode).keywords; } - } - - function addMatches(result, search, wordlist, formatter) { - if (isArray(wordlist)) { - for (var i = 0; i < wordlist.length; i++) - if (match(search, wordlist[i])) result.push(formatter(wordlist[i], i)); - } else { - for (var word in wordlist) if (wordlist.hasOwnProperty(word)) { - var val = wordlist[word] - if (!val || val === true) - val = word - else - val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text - if (match(search, val)) result.push(formatter(val)) - } + + function getIdentifierQuote (editor) { + var mode = editor.doc.modeOption; + if (mode === "sql") mode = "text/x-sql"; + return CodeMirror.resolveMode(mode).identifierQuote || "`"; } - } - function cleanName(name) { - // Get rid name from identifierQuote and preceding dot(.) - if (name.charAt(0) == ".") { - name = name.substr(1); + function getText (item) { + return typeof item === "string" ? item : item.text; } - // replace doublicated identifierQuotes with single identifierQuotes - // and remove single identifierQuotes - var nameParts = name.split(identifierQuote+identifierQuote); - for (var i = 0; i < nameParts.length; i++) - nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote,"g"), ""); - return nameParts.join(identifierQuote); - } - - function insertIdentifierQuotes(name) { - var nameParts = getText(name).split("."); - for (var i = 0; i < nameParts.length; i++) - nameParts[i] = identifierQuote + - // doublicate identifierQuotes - nameParts[i].replace(new RegExp(identifierQuote,"g"), identifierQuote+identifierQuote) + - identifierQuote; - var escaped = nameParts.join("."); - if (typeof name == "string") return escaped; - name = shallowClone(name); - name.text = escaped; - return name; - } - - function nameCompletion(cur, token, result, editor) { - // Try to complete table, column names and return start position of completion - var useIdentifierQuotes = false; - var nameParts = []; - var start = token.start; - var cont = true; - while (cont) { - cont = (token.string.charAt(0) == "."); - useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote); - - start = token.start; - nameParts.unshift(cleanName(token.string)); - - token = editor.getTokenAt(Pos(cur.line, token.start)); - if (token.string == ".") { - cont = true; - token = editor.getTokenAt(Pos(cur.line, token.start)); - } + + function wrapTable (name, value) { + if (isArray(value)) value = {columns: value}; + if (!value.text) value.text = name; + return value; } - // Try to complete table names - var string = nameParts.join("."); - addMatches(result, string, tables, function(w) { - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); + function parseTables (input) { + var result = {}; + if (isArray(input)) { + for (var i = input.length - 1; i >= 0; i--) { + var item = input[i]; + result[getText(item).toUpperCase()] = wrapTable(getText(item), item); + } + } else if (input) { + for (var name in input) {result[name.toUpperCase()] = wrapTable(name, input[name]);} + } + return result; + } - // Try to complete columns from defaultTable - addMatches(result, string, defaultTable, function(w) { - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); + function getTable (name) { + return tables[name.toUpperCase()]; + } - // Try to complete columns - string = nameParts.pop(); - var table = nameParts.join("."); - - var alias = false; - var aliasTable = table; - // Check if table is available. If not, find table by Alias - if (!getTable(table)) { - var oldTable = table; - table = findTableByAlias(table, editor); - if (table !== oldTable) alias = true; + function shallowClone (object) { + var result = {}; + for (var key in object) { + if (object.hasOwnProperty(key)) {result[key] = object[key];} + } + return result; } - var columns = getTable(table); - if (columns && columns.columns) - columns = columns.columns; + function match (string, word) { + if (BI.isNotEmptyString(string) && word.length !== string.length) { + var len = string.length; + var sub = getText(word).substr(0, len); + return string.toUpperCase() === sub.toUpperCase(); + } + } - if (columns) { - addMatches(result, string, columns, function(w) { - var tableInsert = table; - if (alias == true) tableInsert = aliasTable; - if (typeof w == "string") { - w = tableInsert + "." + w; + function addMatches (result, search, wordlist, formatter) { + if (isArray(wordlist)) { + for (var i = 0; i < wordlist.length; i++) {if (match(search, wordlist[i])) result.push(formatter(wordlist[i], i));} } else { - w = shallowClone(w); - w.text = tableInsert + "." + w.text; + for (var word in wordlist) { + if (wordlist.hasOwnProperty(word)) { + var val = wordlist[word]; + if (!val || val === true) {val = word;} else {val = val.displayText ? {text: val.text, displayText: val.displayText} : val.text;} + if (match(search, val)) result.push(formatter(val)); + } + } } - return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; - }); } - return start; - } - - function eachWord(lineText, f) { - var words = lineText.split(/\s+/) - for (var i = 0; i < words.length; i++) - if (words[i]) f(words[i].replace(/[,;]/g, '')) - } - - function findTableByAlias(alias, editor) { - var doc = editor.doc; - var fullQuery = doc.getValue(); - var aliasUpperCase = alias.toUpperCase(); - var previousWord = ""; - var table = ""; - var separator = []; - var validRange = { - start: Pos(0, 0), - end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length) - }; - - //add separator - var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV); - while(indexOfSeparator != -1) { - separator.push(doc.posFromIndex(indexOfSeparator)); - indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator+1); - } - separator.unshift(Pos(0, 0)); - separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length)); - - //find valid range - var prevItem = null; - var current = editor.getCursor() - for (var i = 0; i < separator.length; i++) { - if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) { - validRange = {start: prevItem, end: separator[i]}; - break; - } - prevItem = separator[i]; + function cleanName (name) { + // Get rid name from identifierQuote and preceding dot(.) + if (name.charAt(0) == ".") { + name = name.substr(1); + } + // replace doublicated identifierQuotes with single identifierQuotes + // and remove single identifierQuotes + var nameParts = name.split(identifierQuote + identifierQuote); + for (var i = 0; i < nameParts.length; i++) {nameParts[i] = nameParts[i].replace(new RegExp(identifierQuote, "g"), "");} + return nameParts.join(identifierQuote); } - var query = doc.getRange(validRange.start, validRange.end, false); - - for (var i = 0; i < query.length; i++) { - var lineText = query[i]; - eachWord(lineText, function(word) { - var wordUpperCase = word.toUpperCase(); - if (wordUpperCase === aliasUpperCase && getTable(previousWord)) - table = previousWord; - if (wordUpperCase !== CONS.ALIAS_KEYWORD) - previousWord = word; - }); - if (table) break; + function insertIdentifierQuotes (name) { + var nameParts = getText(name).split("."); + for (var i = 0; i < nameParts.length; i++) { + nameParts[i] = identifierQuote + + // doublicate identifierQuotes + nameParts[i].replace(new RegExp(identifierQuote, "g"), identifierQuote + identifierQuote) + + identifierQuote; + } + var escaped = nameParts.join("."); + if (typeof name === "string") return escaped; + name = shallowClone(name); + name.text = escaped; + return name; } - return table; - } - - CodeMirror.registerHelper("hint", "sql", function(editor, options) { - tables = parseTables(options && options.tables) - var defaultTableName = options && options.defaultTable; - var disableKeywords = options && options.disableKeywords; - defaultTable = defaultTableName && getTable(defaultTableName); - keywords = getKeywords(editor); - var keywordsCount = BI.size(keywords); - var functions = []; - var desc = {}; - var cur = editor.getCursor(); - var token = editor.getTokenAt(cur); - BI.each(BI.FormulaCollections, function(idx, formula){ - if(formula.lastIndexOf(token.string, 0) == 0 && !BI.contains(functions, formula)){ - functions.push(formula); - } - }); - BI.each(BI.FormulaJson, function(idx, formula){ - desc[formula.name.toLowerCase()] = formula.def; - }); - keywords = BI.concat(BI.keys(keywords), functions); - identifierQuote = getIdentifierQuote(editor); - if (defaultTableName && !defaultTable) - defaultTable = findTableByAlias(defaultTableName, editor); + function nameCompletion (cur, token, result, editor) { + // Try to complete table, column names and return start position of completion + var useIdentifierQuotes = false; + var nameParts = []; + var start = token.start; + var cont = true; + while (cont) { + cont = (token.string.charAt(0) == "."); + useIdentifierQuotes = useIdentifierQuotes || (token.string.charAt(0) == identifierQuote); + + start = token.start; + nameParts.unshift(cleanName(token.string)); + + token = editor.getTokenAt(Pos(cur.line, token.start)); + if (token.string == ".") { + cont = true; + token = editor.getTokenAt(Pos(cur.line, token.start)); + } + } - defaultTable = defaultTable || []; + // Try to complete table names + var string = nameParts.join("."); + addMatches(result, string, tables, function (w) { + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + + // Try to complete columns from defaultTable + addMatches(result, string, defaultTable, function (w) { + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + + // Try to complete columns + string = nameParts.pop(); + var table = nameParts.join("."); + + var alias = false; + var aliasTable = table; + // Check if table is available. If not, find table by Alias + if (!getTable(table)) { + var oldTable = table; + table = findTableByAlias(table, editor); + if (table !== oldTable) alias = true; + } - if (defaultTable.columns) - defaultTable = defaultTable.columns; + var columns = getTable(table); + if (columns && columns.columns) {columns = columns.columns;} + + if (columns) { + addMatches(result, string, columns, function (w) { + var tableInsert = table; + if (alias == true) tableInsert = aliasTable; + if (typeof w === "string") { + w = tableInsert + "." + w; + } else { + w = shallowClone(w); + w.text = tableInsert + "." + w.text; + } + return useIdentifierQuotes ? insertIdentifierQuotes(w) : w; + }); + } - var result = []; - var start, end, search; - if (token.end > cur.ch) { - token.end = cur.ch; - token.string = token.string.slice(0, cur.ch - token.start); + return start; } - if (token.string.match(/^[.`"\w@]\w*$/)) { - search = token.string; - start = token.start; - end = token.end; - } else { - start = end = cur.ch; - search = ""; + function eachWord (lineText, f) { + var words = lineText.split(/\s+/); + for (var i = 0; i < words.length; i++) {if (words[i]) f(words[i].replace(/[,;]/g, ""));} } - if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) { - start = nameCompletion(cur, token, result, editor); - } else { - addMatches(result, search, tables, function(w) {return w}); - addMatches(result, search, defaultTable, function(w) {return w}); - if (!disableKeywords) - addMatches(result, search, keywords, function(w, i) { - var isKeyword = i < keywordsCount; - return { - isKeyword: isKeyword, - text: w - // description: desc[w] || "SQL关键字", - // className: isKeyword ? "sql-keyword" : "sql-fr-function", - // render: function (Element, self, data) { - // var label = BI.createWidget({ - // type: "bi.label", - // element: Element, - // text: data.displayText || getText(data) - // }); - // label.setTitle(data.description, { - // container: "body" - - // }); - // } - }; - }); + + function findTableByAlias (alias, editor) { + var doc = editor.doc; + var fullQuery = doc.getValue(); + var aliasUpperCase = alias.toUpperCase(); + var previousWord = ""; + var table = ""; + var separator = []; + var validRange = { + start: Pos(0, 0), + end: Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).length) + }; + + // add separator + var indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV); + while(indexOfSeparator != -1) { + separator.push(doc.posFromIndex(indexOfSeparator)); + indexOfSeparator = fullQuery.indexOf(CONS.QUERY_DIV, indexOfSeparator + 1); + } + separator.unshift(Pos(0, 0)); + separator.push(Pos(editor.lastLine(), editor.getLineHandle(editor.lastLine()).text.length)); + + // find valid range + var prevItem = null; + var current = editor.getCursor(); + for (var i = 0; i < separator.length; i++) { + if ((prevItem == null || cmpPos(current, prevItem) > 0) && cmpPos(current, separator[i]) <= 0) { + validRange = {start: prevItem, end: separator[i]}; + break; + } + prevItem = separator[i]; + } + + var query = doc.getRange(validRange.start, validRange.end, false); + + for (var i = 0; i < query.length; i++) { + var lineText = query[i]; + eachWord(lineText, function (word) { + var wordUpperCase = word.toUpperCase(); + if (wordUpperCase === aliasUpperCase && getTable(previousWord)) {table = previousWord;} + if (wordUpperCase !== CONS.ALIAS_KEYWORD) {previousWord = word;} + }); + if (table) break; + } + return table; } - return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)}; - }); + CodeMirror.registerHelper("hint", "sql", function (editor, options) { + tables = parseTables(options && options.tables); + var defaultTableName = options && options.defaultTable; + var disableKeywords = options && options.disableKeywords; + defaultTable = defaultTableName && getTable(defaultTableName); + keywords = getKeywords(editor); + var keywordsCount = BI.size(keywords); + var functions = []; + var desc = {}; + var cur = editor.getCursor(); + var token = editor.getTokenAt(cur); + BI.each(BI.FormulaCollections, function (idx, formula) { + if(formula.lastIndexOf(token.string, 0) == 0 && !BI.contains(functions, formula)) { + functions.push(formula); + } + }); + BI.each(BI.FormulaJson, function (idx, formula) { + desc[formula.name.toLowerCase()] = formula.def; + }); + keywords = BI.concat(BI.keys(keywords), functions); + identifierQuote = getIdentifierQuote(editor); + + if (defaultTableName && !defaultTable) {defaultTable = findTableByAlias(defaultTableName, editor);} + + defaultTable = defaultTable || []; + + if (defaultTable.columns) {defaultTable = defaultTable.columns;} + + var result = []; + var start, end, search; + if (token.end > cur.ch) { + token.end = cur.ch; + token.string = token.string.slice(0, cur.ch - token.start); + } + + if (token.string.match(/^[.`"\w@]\w*$/)) { + search = token.string; + start = token.start; + end = token.end; + } else { + start = end = cur.ch; + search = ""; + } + if (search.charAt(0) == "." || search.charAt(0) == identifierQuote) { + start = nameCompletion(cur, token, result, editor); + } else { + addMatches(result, search, tables, function (w) {return w;}); + addMatches(result, search, defaultTable, function (w) {return w;}); + if (!disableKeywords) { + addMatches(result, search, keywords, function (w, i) { + var isKeyword = i < keywordsCount; + return { + isKeyword: isKeyword, + text: w + // description: desc[w] || "SQL关键字", + // className: isKeyword ? "sql-keyword" : "sql-fr-function", + // render: function (Element, self, data) { + // var label = BI.createWidget({ + // type: "bi.label", + // element: Element, + // text: data.displayText || getText(data) + // }); + // label.setTitle(data.description, { + // container: "body" + + // }); + // } + }; + }); + } + } + + return {list: result, from: Pos(cur.line, start), to: Pos(cur.line, end)}; + }); }); diff --git a/src/base/sql/codemirrior/sql-mode.js b/src/base/sql/codemirrior/sql-mode.js index b19514434..a9f1fa6b6 100644 --- a/src/base/sql/codemirrior/sql-mode.js +++ b/src/base/sql/codemirrior/sql-mode.js @@ -1,288 +1,277 @@ // CodeMirror, copyright (c) by Marijn Haverbeke and others // Distributed under an MIT license: http://codemirror.net/LICENSE -(function(mod) { +(function (mod) { mod(CodeMirror); -})(function(CodeMirror) { +})(function (CodeMirror) { "use strict"; -CodeMirror.defineMode("sql", function(config, parserConfig) { - "use strict"; + CodeMirror.defineMode("sql", function (config, parserConfig) { + "use strict"; - var client = parserConfig.client || {}, - atoms = parserConfig.atoms || {"false": true, "true": true, "null": true}, - builtin = parserConfig.builtin || {}, - keywords = parserConfig.keywords || {}, - operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/, - support = parserConfig.support || {}, - hooks = parserConfig.hooks || {}, - dateSQL = parserConfig.dateSQL || {"date" : true, "time" : true, "timestamp" : true}, - functions = parserConfig.functions || {}; + var client = parserConfig.client || {}, + atoms = parserConfig.atoms || {false: true, true: true, null: true}, + builtin = parserConfig.builtin || {}, + keywords = parserConfig.keywords || {}, + operatorChars = parserConfig.operatorChars || /^[*+\-%<>!=&|~^]/, + support = parserConfig.support || {}, + hooks = parserConfig.hooks || {}, + dateSQL = parserConfig.dateSQL || {date: true, time: true, timestamp: true}, + functions = parserConfig.functions || {}; - function tokenBase(stream, state) { - var ch = stream.next(); + function tokenBase (stream, state) { + var ch = stream.next(); - // call hooks from the mime type - if (hooks[ch]) { - var result = hooks[ch](stream, state); - if (result !== false) return result; - } + // call hooks from the mime type + if (hooks[ch]) { + var result = hooks[ch](stream, state); + if (result !== false) return result; + } - if (support.hexNumber && + if (support.hexNumber && ((ch == "0" && stream.match(/^[xX][0-9a-fA-F]+/)) || (ch == "x" || ch == "X") && stream.match(/^'[0-9a-fA-F]+'/))) { - // hex - // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html - return "number"; - } else if (support.binaryNumber && + // hex + // ref: http://dev.mysql.com/doc/refman/5.5/en/hexadecimal-literals.html + return "number"; + } else if (support.binaryNumber && (((ch == "b" || ch == "B") && stream.match(/^'[01]+'/)) || (ch == "0" && stream.match(/^b[01]+/)))) { - // bitstring - // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html - return "number"; - } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { - // numbers - // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html - stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/); - support.decimallessFloat && stream.match(/^\.(?!\.)/); - return "number"; - } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { - // placeholders - return "variable-3"; - } else if (ch == "'" || (ch == '"' && support.doubleQuote)) { - // strings - // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html - state.tokenize = tokenLiteral(ch); - return state.tokenize(stream, state); - } else if ((((support.nCharCast && (ch == "n" || ch == "N")) + // bitstring + // ref: http://dev.mysql.com/doc/refman/5.5/en/bit-field-literals.html + return "number"; + } else if (ch.charCodeAt(0) > 47 && ch.charCodeAt(0) < 58) { + // numbers + // ref: http://dev.mysql.com/doc/refman/5.5/en/number-literals.html + stream.match(/^[0-9]*(\.[0-9]+)?([eE][-+]?[0-9]+)?/); + support.decimallessFloat && stream.match(/^\.(?!\.)/); + return "number"; + } else if (ch == "?" && (stream.eatSpace() || stream.eol() || stream.eat(";"))) { + // placeholders + return "variable-3"; + } else if (ch == "'" || (ch == "\"" && support.doubleQuote)) { + // strings + // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html + state.tokenize = tokenLiteral(ch); + return state.tokenize(stream, state); + } else if ((((support.nCharCast && (ch == "n" || ch == "N")) || (support.charsetCast && ch == "_" && stream.match(/[a-z][a-z0-9]*/i))) - && (stream.peek() == "'" || stream.peek() == '"'))) { - // charset casting: _utf8'str', N'str', n'str' - // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html - return "keyword"; - } else if (/^[\(\),\;\[\]]/.test(ch)) { - // no highlighting - return null; - } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { - // 1-line comment - stream.skipToEnd(); - return "comment"; - } else if ((support.commentHash && ch == "#") + && (stream.peek() == "'" || stream.peek() == "\""))) { + // charset casting: _utf8'str', N'str', n'str' + // ref: http://dev.mysql.com/doc/refman/5.5/en/string-literals.html + return "keyword"; + } else if (/^[\(\),\;\[\]]/.test(ch)) { + // no highlighting + return null; + } else if (support.commentSlashSlash && ch == "/" && stream.eat("/")) { + // 1-line comment + stream.skipToEnd(); + return "comment"; + } else if ((support.commentHash && ch == "#") || (ch == "-" && stream.eat("-") && (!support.commentSpaceRequired || stream.eat(" ")))) { - // 1-line comments - // ref: https://kb.askmonty.org/en/comment-syntax/ - stream.skipToEnd(); - return "comment"; - } else if (ch == "/" && stream.eat("*")) { - // multi-line comments - // ref: https://kb.askmonty.org/en/comment-syntax/ - state.tokenize = tokenComment(1); - return state.tokenize(stream, state); - } else if (ch == ".") { - // .1 for 0.1 - if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) - return "number"; - if (stream.match(/^\.+/)) - return null - // .table_name (ODBC) - // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html - if (support.ODBCdotTable && stream.match(/^[\w\d_]+/)) - return "variable-2"; - } else if (operatorChars.test(ch)) { - // operators - stream.eatWhile(operatorChars); - return null; - } else if (ch == '{' && + // 1-line comments + // ref: https://kb.askmonty.org/en/comment-syntax/ + stream.skipToEnd(); + return "comment"; + } else if (ch == "/" && stream.eat("*")) { + // multi-line comments + // ref: https://kb.askmonty.org/en/comment-syntax/ + state.tokenize = tokenComment(1); + return state.tokenize(stream, state); + } else if (ch == ".") { + // .1 for 0.1 + if (support.zerolessFloat && stream.match(/^(?:\d+(?:e[+-]?\d+)?)/i)) {return "number";} + if (stream.match(/^\.+/)) {return null;} + // .table_name (ODBC) + // // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html + if (support.ODBCdotTable && stream.match(/^[\w\d_]+/)) {return "variable-2";} + } else if (operatorChars.test(ch)) { + // operators + stream.eatWhile(operatorChars); + return null; + } else if (ch == "{" && (stream.match(/^( )*(d|D|t|T|ts|TS)( )*'[^']*'( )*}/) || stream.match(/^( )*(d|D|t|T|ts|TS)( )*"[^"]*"( )*}/))) { - // dates (weird ODBC syntax) - // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html - return "number"; - } else { - stream.eatWhile(/^[_\w\d]/); - var word = stream.current().toLowerCase(); - // dates (standard SQL syntax) - // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html - if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) - return "number"; - if (atoms.hasOwnProperty(word)) return "atom"; - if (builtin.hasOwnProperty(word)) return "builtin"; - if (functions.hasOwnProperty(word) && stream.peek() === '(') return "function"; - if (keywords.hasOwnProperty(word)) return "keyword"; - if (client.hasOwnProperty(word)) return "string-2"; - return null; - } - } + // dates (weird ODBC syntax) + // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html + return "number"; + } else { + stream.eatWhile(/^[_\w\d]/); + var word = stream.current().toLowerCase(); + // dates (standard SQL syntax) + // ref: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-literals.html + if (dateSQL.hasOwnProperty(word) && (stream.match(/^( )+'[^']*'/) || stream.match(/^( )+"[^"]*"/))) {return "number";} + if (atoms.hasOwnProperty(word)) return "atom"; + if (builtin.hasOwnProperty(word)) return "builtin"; + if (functions.hasOwnProperty(word) && stream.peek() === "(") return "function"; + if (keywords.hasOwnProperty(word)) return "keyword"; + if (client.hasOwnProperty(word)) return "string-2"; + return null; + } + } - // 'string', with char specified in quote escaped by '\' - function tokenLiteral(quote) { - return function(stream, state) { - var escaped = false, ch; - while ((ch = stream.next()) != null) { - if (ch == quote && !escaped) { - state.tokenize = tokenBase; - break; + // 'string', with char specified in quote escaped by '\' + function tokenLiteral (quote) { + return function (stream, state) { + var escaped = false, ch; + while ((ch = stream.next()) != null) { + if (ch == quote && !escaped) { + state.tokenize = tokenBase; + break; + } + escaped = !escaped && ch == "\\"; + } + return "string"; + }; + } + function tokenComment (depth) { + return function (stream, state) { + var m = stream.match(/^.*?(\/\*|\*\/)/); + if (!m) stream.skipToEnd(); + else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1); + else if (depth > 1) state.tokenize = tokenComment(depth - 1); + else state.tokenize = tokenBase; + return "comment"; + }; } - escaped = !escaped && ch == "\\"; - } - return "string"; - }; - } - function tokenComment(depth) { - return function(stream, state) { - var m = stream.match(/^.*?(\/\*|\*\/)/) - if (!m) stream.skipToEnd() - else if (m[1] == "/*") state.tokenize = tokenComment(depth + 1) - else if (depth > 1) state.tokenize = tokenComment(depth - 1) - else state.tokenize = tokenBase - return "comment" - } - } - function pushContext(stream, state, type) { - state.context = { - prev: state.context, - indent: stream.indentation(), - col: stream.column(), - type: type - }; - } + function pushContext (stream, state, type) { + state.context = { + prev: state.context, + indent: stream.indentation(), + col: stream.column(), + type: type + }; + } - function popContext(state) { - state.indent = state.context.indent; - state.context = state.context.prev; - } + function popContext (state) { + state.indent = state.context.indent; + state.context = state.context.prev; + } - return { - startState: function() { - return {tokenize: tokenBase, context: null}; - }, + return { + startState: function () { + return {tokenize: tokenBase, context: null}; + }, - token: function(stream, state) { - if (stream.sol()) { - if (state.context && state.context.align == null) - state.context.align = false; - } - if (state.tokenize == tokenBase && stream.eatSpace()) return null; + token: function (stream, state) { + if (stream.sol()) { + if (state.context && state.context.align == null) {state.context.align = false;} + } + if (state.tokenize == tokenBase && stream.eatSpace()) return null; - var style = state.tokenize(stream, state); - if (style == "comment") return style; + var style = state.tokenize(stream, state); + if (style == "comment") return style; - if (state.context && state.context.align == null) - state.context.align = true; + if (state.context && state.context.align == null) {state.context.align = true;} - var tok = stream.current(); - if (tok == "(") - pushContext(stream, state, ")"); - else if (tok == "[") - pushContext(stream, state, "]"); - else if (state.context && state.context.type == tok) - popContext(state); - return style; - }, + var tok = stream.current(); + if (tok == "(") {pushContext(stream, state, ")");} else if (tok == "[") {pushContext(stream, state, "]");} else if (state.context && state.context.type == tok) {popContext(state);} + return style; + }, - indent: function(state, textAfter) { - var cx = state.context; - if (!cx) return CodeMirror.Pass; - var closing = textAfter.charAt(0) == cx.type; - if (cx.align) return cx.col + (closing ? 0 : 1); - else return cx.indent + (closing ? 0 : config.indentUnit); - }, + indent: function (state, textAfter) { + var cx = state.context; + if (!cx) return CodeMirror.Pass; + var closing = textAfter.charAt(0) == cx.type; + if (cx.align) return cx.col + (closing ? 0 : 1); + return cx.indent + (closing ? 0 : config.indentUnit); + }, - blockCommentStart: "/*", - blockCommentEnd: "*/", - lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--" - }; -}); + blockCommentStart: "/*", + blockCommentEnd: "*/", + lineComment: support.commentSlashSlash ? "//" : support.commentHash ? "#" : "--" + }; + }); -(function() { - "use strict"; + (function () { + "use strict"; - // `identifier` - function hookIdentifier(stream) { - // MySQL/MariaDB identifiers - // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html - var ch; - while ((ch = stream.next()) != null) { - if (ch == "`" && !stream.eat("`")) return "variable-2"; - } - stream.backUp(stream.current().length - 1); - return stream.eatWhile(/\w/) ? "variable-2" : null; - } + // `identifier` + function hookIdentifier (stream) { + // MySQL/MariaDB identifiers + // ref: http://dev.mysql.com/doc/refman/5.6/en/identifier-qualifiers.html + var ch; + while ((ch = stream.next()) != null) { + if (ch == "`" && !stream.eat("`")) return "variable-2"; + } + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; + } - // "identifier" - function hookIdentifierDoublequote(stream) { - // Standard SQL /SQLite identifiers - // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier - // ref: http://sqlite.org/lang_keywords.html - var ch; - while ((ch = stream.next()) != null) { - if (ch == "\"" && !stream.eat("\"")) return "variable-2"; - } - stream.backUp(stream.current().length - 1); - return stream.eatWhile(/\w/) ? "variable-2" : null; - } + // "identifier" + function hookIdentifierDoublequote (stream) { + // Standard SQL /SQLite identifiers + // ref: http://web.archive.org/web/20160813185132/http://savage.net.au/SQL/sql-99.bnf.html#delimited%20identifier + // ref: http://sqlite.org/lang_keywords.html + var ch; + while ((ch = stream.next()) != null) { + if (ch == "\"" && !stream.eat("\"")) return "variable-2"; + } + stream.backUp(stream.current().length - 1); + return stream.eatWhile(/\w/) ? "variable-2" : null; + } - // variable token - function hookVar(stream) { - // variables - // @@prefix.varName @varName - // varName can be quoted with ` or ' or " - // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html - if (stream.eat("@")) { - stream.match(/^session\./); - stream.match(/^local\./); - stream.match(/^global\./); - } + // variable token + function hookVar (stream) { + // variables + // @@prefix.varName @varName + // varName can be quoted with ` or ' or " + // ref: http://dev.mysql.com/doc/refman/5.5/en/user-variables.html + if (stream.eat("@")) { + stream.match(/^session\./); + stream.match(/^local\./); + stream.match(/^global\./); + } - if (stream.eat("'")) { - stream.match(/^.*'/); - return "variable-2"; - } else if (stream.eat('"')) { - stream.match(/^.*"/); - return "variable-2"; - } else if (stream.eat("`")) { - stream.match(/^.*`/); - return "variable-2"; - } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { - return "variable-2"; - } - return null; - }; + if (stream.eat("'")) { + stream.match(/^.*'/); + return "variable-2"; + } else if (stream.eat("\"")) { + stream.match(/^.*"/); + return "variable-2"; + } else if (stream.eat("`")) { + stream.match(/^.*`/); + return "variable-2"; + } else if (stream.match(/^[0-9a-zA-Z$\.\_]+/)) { + return "variable-2"; + } + return null; + } - // short client keyword token - function hookClient(stream) { - // \N means NULL - // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html - if (stream.eat("N")) { - return "atom"; - } - // \g, etc - // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html - return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; - } + // short client keyword token + function hookClient (stream) { + // \N means NULL + // ref: http://dev.mysql.com/doc/refman/5.5/en/null-values.html + if (stream.eat("N")) { + return "atom"; + } + // \g, etc + // ref: http://dev.mysql.com/doc/refman/5.5/en/mysql-commands.html + return stream.match(/^[a-zA-Z.#!?]/) ? "variable-2" : null; + } - // these keywords are used by all SQL dialects (however, a mode can still overwrite it) - var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; + // these keywords are used by all SQL dialects (however, a mode can still overwrite it) + var sqlKeywords = "alter and as asc between by count create delete desc distinct drop from group having in insert into is join like not on or order select set table union update values where limit "; - // turn a space-separated list into an array - function set(str) { - var obj = {}, words = str.split(" "); - for (var i = 0; i < words.length; ++i) obj[words[i]] = true; - return obj; - } + // turn a space-separated list into an array + function set (str) { + var obj = {}, words = str.split(" "); + for (var i = 0; i < words.length; ++i) obj[words[i]] = true; + return obj; + } - // A generic SQL Mode. It's not a standard, it just try to support what is generally supported - CodeMirror.defineMIME("text/x-sql", { - name: "sql", - keywords: set(sqlKeywords + "begin"), - builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"), - atoms: set("false true null unknown"), - operatorChars: /^[*+\-%<>!=]/, - dateSQL: set("date time timestamp"), - support: set("ODBCdotTable doubleQuote binaryNumber hexNumber"), - functions: BI.makeObject(BI.FormulaCollections, true) - }); -}()); + // A generic SQL Mode. It's not a standard, it just try to support what is generally supported + CodeMirror.defineMIME("text/x-sql", { + name: "sql", + keywords: set(sqlKeywords + "begin"), + builtin: set("bool boolean bit blob enum long longblob longtext medium mediumblob mediumint mediumtext time timestamp tinyblob tinyint tinytext text bigint int int1 int2 int3 int4 int8 integer float float4 float8 double char varbinary varchar varcharacter precision real date datetime year unsigned signed decimal numeric"), + atoms: set("false true null unknown"), + operatorChars: /^[*+\-%<>!=]/, + dateSQL: set("date time timestamp"), + support: set("ODBCdotTable doubleQuote binaryNumber hexNumber"), + functions: BI.makeObject(BI.FormulaCollections, true) + }); + }()); }); diff --git a/src/base/sql/editor.sql.js b/src/base/sql/editor.sql.js index 3f8005d9c..c3b767509 100644 --- a/src/base/sql/editor.sql.js +++ b/src/base/sql/editor.sql.js @@ -4,8 +4,8 @@ BI.SQLEditor = BI.inherit(BI.Widget, { _defaultConfig: function () { return $.extend(BI.CodeEditor.superclass._defaultConfig.apply(), { - baseCls: 'bi-sql-editor', - value: '', + baseCls: "bi-sql-editor", + value: "", lineHeight: 2, showHint: true }); @@ -29,7 +29,7 @@ BI.SQLEditor = BI.inherit(BI.Widget, { }); } BI.nextTick(function () { - self.fireEvent(BI.FormulaEditor.EVENT_CHANGE) + self.fireEvent(BI.FormulaEditor.EVENT_CHANGE); }); }); @@ -42,7 +42,7 @@ BI.SQLEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.FormulaEditor.EVENT_BLUR); }); - //水印 + // 水印 this.watermark = BI.createWidget({ type: "bi.label", text: BI.i18nText("Please_Enter_SQL"), diff --git a/src/base/svg/raphael.js b/src/base/svg/raphael.js index 2bbc32437..e6e643992 100644 --- a/src/base/svg/raphael.js +++ b/src/base/svg/raphael.js @@ -18,7 +18,7 @@ // └────────────────────────────────────────────────────────────┘ \\ (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("eve", function() { + define("eve", function () { return factory(); }); } else if (typeof exports === "object") { @@ -26,7 +26,7 @@ } else { glob.eve = factory(); } -}(this, function(){ +}(this, function () { var version = "0.4.2", has = "hasOwnProperty", separator = /[\.\/]/, @@ -38,7 +38,7 @@ current_event, stop, events = {n: {}}, - /*\ + /* \ * eve [ method ] @@ -68,10 +68,12 @@ errors = []; current_event = name; stop = 0; - for (var i = 0, ii = listeners.length; i < ii; i++) if ("zIndex" in listeners[i]) { - indexed.push(listeners[i].zIndex); - if (listeners[i].zIndex < 0) { - queue[listeners[i].zIndex] = listeners[i]; + for (var i = 0, ii = listeners.length; i < ii; i++) { + if ("zIndex" in listeners[i]) { + indexed.push(listeners[i].zIndex); + if (listeners[i].zIndex < 0) { + queue[listeners[i].zIndex] = listeners[i]; + } } } indexed.sort(numsort); @@ -98,7 +100,7 @@ if (stop) { break; } - } while (l) + } while (l); } else { queue[l.zIndex] = l; } @@ -115,7 +117,7 @@ }; // Undocumented. Debug only. eve._events = events; - /*\ + /* \ * eve.listeners [ method ] @@ -159,7 +161,7 @@ return out; }; - /*\ + /* \ * eve.on [ method ] ** @@ -185,7 +187,7 @@ \*/ eve.on = function (name, f) { name = String(name); - if (typeof f != "function") { + if (typeof f !== "function") { return function () {}; } var names = name.split(separator), @@ -195,8 +197,10 @@ e = e.hasOwnProperty(names[i]) && e[names[i]] || (e[names[i]] = {n: {}}); } e.f = e.f || []; - for (i = 0, ii = e.f.length; i < ii; i++) if (e.f[i] == f) { - return fun; + for (i = 0, ii = e.f.length; i < ii; i++) { + if (e.f[i] == f) { + return fun; + } } e.f.push(f); return function (zIndex) { @@ -205,7 +209,7 @@ } }; }; - /*\ + /* \ * eve.f [ method ] ** @@ -227,7 +231,7 @@ eve.apply(null, [event, null].concat(attrs).concat([].slice.call(arguments, 0))); }; }; - /*\ + /* \ * eve.stop [ method ] ** @@ -236,7 +240,7 @@ eve.stop = function () { stop = 1; }; - /*\ + /* \ * eve.nt [ method ] ** @@ -256,7 +260,7 @@ } return current_event; }; - /*\ + /* \ * eve.nts [ method ] ** @@ -268,7 +272,7 @@ eve.nts = function () { return current_event.split(separator); }; - /*\ + /* \ * eve.off [ method ] ** @@ -280,7 +284,7 @@ - name (string) name of the event, dot (`.`) or slash (`/`) separated, with optional wildcards - f (function) event handler function \*/ - /*\ + /* \ * eve.unbind [ method ] ** @@ -306,8 +310,10 @@ splice.push(e[names[i]]); } } else { - for (key in e) if (e[has](key)) { - splice.push(e[key]); + for (key in e) { + if (e[has](key)) { + splice.push(e[key]); + } } } cur.splice.apply(cur, splice); @@ -318,31 +324,39 @@ while (e.n) { if (f) { if (e.f) { - for (j = 0, jj = e.f.length; j < jj; j++) if (e.f[j] == f) { - e.f.splice(j, 1); - break; + for (j = 0, jj = e.f.length; j < jj; j++) { + if (e.f[j] == f) { + e.f.splice(j, 1); + break; + } } !e.f.length && delete e.f; } - for (key in e.n) if (e.n[has](key) && e.n[key].f) { - var funcs = e.n[key].f; - for (j = 0, jj = funcs.length; j < jj; j++) if (funcs[j] == f) { - funcs.splice(j, 1); - break; + for (key in e.n) { + if (e.n[has](key) && e.n[key].f) { + var funcs = e.n[key].f; + for (j = 0, jj = funcs.length; j < jj; j++) { + if (funcs[j] == f) { + funcs.splice(j, 1); + break; + } + } + !funcs.length && delete e.n[key].f; } - !funcs.length && delete e.n[key].f; } } else { delete e.f; - for (key in e.n) if (e.n[has](key) && e.n[key].f) { - delete e.n[key].f; + for (key in e.n) { + if (e.n[has](key) && e.n[key].f) { + delete e.n[key].f; + } } } e = e.n; } } }; - /*\ + /* \ * eve.once [ method ] ** @@ -366,7 +380,7 @@ }; return eve.on(name, f2); }; - /*\ + /* \ * eve.version [ property (string) ] ** @@ -390,7 +404,7 @@ (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.core", ["eve"], function(eve) { + define("raphael.core", ["eve"], function (eve) { return factory(eve); }); } else if (typeof exports === "object") { @@ -399,7 +413,7 @@ glob.Raphael = factory(glob.eve); } }(this, function (eve) { - /*\ + /* \ * Raphael [ method ] ** @@ -449,22 +463,22 @@ | text: "Dump" | }]); \*/ - function R(first) { + function R (first) { if (R.is(first, "function")) { return loaded ? first() : eve.on("raphael.DOMload", first); } else if (R.is(first, array)) { return R._engine.create[apply](R, first.splice(0, 3 + R.is(first[0], nu))).add(first); - } else { - var args = Array.prototype.slice.call(arguments, 0); - if (R.is(args[args.length - 1], "function")) { - var f = args.pop(); - return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () { - f.call(R._engine.create[apply](R, args)); - }); - } else { - return R._engine.create[apply](R, arguments); - } } + var args = Array.prototype.slice.call(arguments, 0); + if (R.is(args[args.length - 1], "function")) { + var f = args.pop(); + return loaded ? f.call(R._engine.create[apply](R, args)) : eve.on("raphael.DOMload", function () { + f.call(R._engine.create[apply](R, args)); + }); + } + return R._engine.create[apply](R, arguments); + + } R.version = "2.1.4"; R.eve = eve; @@ -483,13 +497,13 @@ is: g.win.Raphael }, Paper = function () { - /*\ + /* \ * Paper.ca [ property (object) ] ** * Shortcut for @Paper.customAttributes \*/ - /*\ + /* \ * Paper.customAttributes [ property (object) ] ** @@ -521,7 +535,7 @@ appendChild = "appendChild", apply = "apply", concat = "concat", - supportsTouch = ('ontouchstart' in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, //taken from Modernizr touch test + supportsTouch = ("ontouchstart" in g.win) || g.win.DocumentTouch && g.doc instanceof DocumentTouch, // taken from Modernizr touch test E = "", S = " ", Str = String, @@ -549,7 +563,7 @@ push = "push", ISURL = R._ISURL = /^url\(['"]?(.+?)['"]?\)$/i, colourRegExp = /^\s*((#[a-f\d]{6})|(#[a-f\d]{3})|rgba?\(\s*([\d\.]+%?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+%?(?:\s*,\s*[\d\.]+%?)?)\s*\)|hsba?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\)|hsla?\(\s*([\d\.]+(?:deg|\xb0|%)?\s*,\s*[\d\.]+%?\s*,\s*[\d\.]+(?:%?\s*,\s*[\d\.]+)?)%?\s*\))\s*$/i, - isnan = {"NaN": 1, "Infinity": 1, "-Infinity": 1}, + isnan = {NaN: 1, Infinity: 1, "-Infinity": 1}, bezierrg = /^(?:cubic-)?bezier\(([^,]+),([^,]+),([^,]+),([^\)]+)\)/, round = math.round, setAttribute = "setAttribute", @@ -566,8 +580,8 @@ cy: 0, fill: "#fff", "fill-opacity": 1, - font: '10px "Arial"', - "font-family": '"Arial"', + font: "10px \"Arial\"", + "font-family": "\"Arial\"", "font-size": "10", "font-style": "normal", "font-weight": 400, @@ -673,12 +687,12 @@ var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); }, - set : function(el) { + set: function (el) { var bbox = el._getBBox(); return rectPath(bbox.x, bbox.y, bbox.width, bbox.height); } }, - /*\ + /* \ * Raphael.mapPath [ method ] ** @@ -707,7 +721,7 @@ }; R._g = g; - /*\ + /* \ * Raphael.type [ property (string) ] ** @@ -717,21 +731,21 @@ if (R.type == "VML") { var d = g.doc.createElement("div"), b; - d.innerHTML = ''; + d.innerHTML = ""; b = d.firstChild; b.style.behavior = "url(#default#VML)"; - if (!(b && typeof b.adj == "object")) { + if (!(b && typeof b.adj === "object")) { return (R.type = E); } d = null; } - /*\ + /* \ * Raphael.svg [ property (boolean) ] ** * `true` if browser supports SVG. \*/ - /*\ + /* \ * Raphael.vml [ property (boolean) ] ** @@ -739,7 +753,7 @@ \*/ R.svg = !(R.vml = R.type == "VML"); R._Paper = Paper; - /*\ + /* \ * Raphael.fn [ property (object) ] ** @@ -768,7 +782,7 @@ R.fn = paperproto = Paper.prototype = R.prototype; R._id = 0; R._oid = 0; - /*\ + /* \ * Raphael.is [ method ] ** @@ -787,24 +801,26 @@ return o instanceof Array; } return (type == "null" && o === null) || - (type == typeof o && o !== null) || + (type === typeof o && o !== null) || (type == "object" && o === Object(o)) || (type == "array" && Array.isArray && Array.isArray(o)) || objectToString.call(o).slice(8, -1).toLowerCase() == type; }; - function clone(obj) { - if (typeof obj == "function" || Object(obj) !== obj) { + function clone (obj) { + if (typeof obj === "function" || Object(obj) !== obj) { return obj; } var res = new obj.constructor; - for (var key in obj) if (obj[has](key)) { - res[key] = clone(obj[key]); + for (var key in obj) { + if (obj[has](key)) { + res[key] = clone(obj[key]); + } } return res; } - /*\ + /* \ * Raphael.angle [ method ] ** @@ -826,11 +842,11 @@ return 0; } return (180 + math.atan2(-y, -x) * 180 / PI + 360) % 360; - } else { - return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); } + return R.angle(x1, y1, x3, y3) - R.angle(x2, y2, x3, y3); + }; - /*\ + /* \ * Raphael.rad [ method ] ** @@ -842,7 +858,7 @@ R.rad = function (deg) { return deg % 360 * PI / 180; }; - /*\ + /* \ * Raphael.deg [ method ] ** @@ -852,9 +868,9 @@ = (number) angle in degrees. \*/ R.deg = function (rad) { - return Math.round ((rad * 180 / PI% 360)* 1000) / 1000; + return Math.round ((rad * 180 / PI % 360) * 1000) / 1000; }; - /*\ + /* \ * Raphael.snapTo [ method ] ** @@ -869,8 +885,10 @@ tolerance = R.is(tolerance, "finite") ? tolerance : 10; if (R.is(values, array)) { var i = values.length; - while (i--) if (abs(values[i] - value) <= tolerance) { - return values[i]; + while (i--) { + if (abs(values[i] - value) <= tolerance) { + return values[i]; + } } } else { values = +values; @@ -885,7 +903,7 @@ return value; }; - /*\ + /* \ * Raphael.createUUID [ method ] ** @@ -901,7 +919,7 @@ return v.toString(16); }); - /*\ + /* \ * Raphael.setWindow [ method ] ** @@ -997,7 +1015,7 @@ return rgb; }; - /*\ + /* \ * Raphael.color [ method ] ** @@ -1050,7 +1068,7 @@ clr.toString = rgbtoString; return clr; }; - /*\ + /* \ * Raphael.hsb2rgb [ method ] ** @@ -1087,7 +1105,7 @@ B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; - /*\ + /* \ * Raphael.hsl2rgb [ method ] ** @@ -1128,7 +1146,7 @@ B += [0, 0, X, C, C, X][h]; return packageRGB(R, G, B, o); }; - /*\ + /* \ * Raphael.rgb2hsb [ method ] ** @@ -1154,15 +1172,15 @@ V = mmax(r, g, b); C = V - mmin(r, g, b); H = (C == 0 ? null : - V == r ? (g - b) / C : - V == g ? (b - r) / C + 2 : + V == r ? (g - b) / C : + V == g ? (b - r) / C + 2 : (r - g) / C + 4 ); H = ((H + 360) % 6) * 60 / 360; S = C == 0 ? 0 : C / V; return {h: H, s: S, b: V, toString: hsbtoString}; }; - /*\ + /* \ * Raphael.rgb2hsl [ method ] ** @@ -1191,24 +1209,26 @@ H = (C == 0 ? null : M == r ? (g - b) / C : M == g ? (b - r) / C + 2 : - (r - g) / C + 4); + (r - g) / C + 4); H = ((H + 360) % 6) * 60 / 360; L = (M + m) / 2; S = (C == 0 ? 0 : L < .5 ? C / (2 * L) : - C / (2 - 2 * L)); + C / (2 - 2 * L)); return {h: H, s: S, l: L, toString: hsltoString}; }; R._path2string = function () { return this.join(",").replace(p2s, "$1"); }; - function repush(array, item) { - for (var i = 0, ii = array.length; i < ii; i++) if (array[i] === item) { - return array.push(array.splice(i, 1)[0]); + function repush (array, item) { + for (var i = 0, ii = array.length; i < ii; i++) { + if (array[i] === item) { + return array.push(array.splice(i, 1)[0]); + } } } - function cacher(f, scope, postprocessor) { - function newf() { + function cacher (f, scope, postprocessor) { + function newf () { var arg = Array.prototype.slice.call(arguments, 0), args = arg.join("\u2400"), cache = newf.cache = newf.cache || {}, @@ -1240,11 +1260,11 @@ img.src = src; }; - function clrToString() { + function clrToString () { return this.hex; } - /*\ + /* \ * Raphael.getRGB [ method ] ** @@ -1342,7 +1362,7 @@ } return {r: -1, g: -1, b: -1, hex: "none", error: 1, toString: clrToString}; }, R); - /*\ + /* \ * Raphael.hsb [ method ] ** @@ -1356,7 +1376,7 @@ R.hsb = cacher(function (h, s, b) { return R.hsb2rgb(h, s, b).hex; }); - /*\ + /* \ * Raphael.hsl [ method ] ** @@ -1370,7 +1390,7 @@ R.hsl = cacher(function (h, s, l) { return R.hsl2rgb(h, s, l).hex; }); - /*\ + /* \ * Raphael.rgb [ method ] ** @@ -1382,10 +1402,10 @@ = (string) hex representation of the colour. \*/ R.rgb = cacher(function (r, g, b) { - function round(x) { return (x + 0.5) | 0; } + function round (x) { return (x + 0.5) | 0; } return "#" + (16777216 | round(b) | (round(g) << 8) | (round(r) << 16)).toString(16).slice(1); }); - /*\ + /* \ * Raphael.getColor [ method ] ** @@ -1405,7 +1425,7 @@ } return rgb.hex; }; - /*\ + /* \ * Raphael.getColor.reset [ method ] ** @@ -1416,7 +1436,7 @@ }; // http://schepers.cc/getting-to-the-point - function catmullRom2bezier(crp, z) { + function catmullRom2bezier (crp, z) { var d = []; for (var i = 0, iLen = crp.length; iLen - 2 * !z > i; i += 2) { var p = [ @@ -1445,7 +1465,7 @@ (-p[0].x + 6 * p[1].x + p[2].x) / 6, (-p[0].y + 6 * p[1].y + p[2].y) / 6, (p[1].x + 6 * p[2].x - p[3].x) / 6, - (p[1].y + 6*p[2].y - p[3].y) / 6, + (p[1].y + 6 * p[2].y - p[3].y) / 6, p[2].x, p[2].y ]); @@ -1453,7 +1473,7 @@ return d; } - /*\ + /* \ * Raphael.parsePathString [ method ] ** @@ -1492,10 +1512,12 @@ } if (name == "r") { data.push([b][concat](params)); - } else while (params.length >= paramCounts[name]) { - data.push([b][concat](params.splice(0, paramCounts[name]))); - if (!paramCounts[name]) { - break; + } else { + while (params.length >= paramCounts[name]) { + data.push([b][concat](params.splice(0, paramCounts[name]))); + if (!paramCounts[name]) { + break; + } } } }); @@ -1504,7 +1526,7 @@ pth.arr = pathClone(data); return data; }; - /*\ + /* \ * Raphael.parseTransformString [ method ] ** @@ -1548,14 +1570,16 @@ }; } setTimeout(function () { - for (var key in p) if (p[has](key) && key != ps) { - p[key].sleep--; - !p[key].sleep && delete p[key]; + for (var key in p) { + if (p[has](key) && key != ps) { + p[key].sleep--; + !p[key].sleep && delete p[key]; + } } }); return p[ps]; }; - /*\ + /* \ * Raphael.findDotsAtSegment [ method ] ** @@ -1623,7 +1647,7 @@ alpha: alpha }; }; - /*\ + /* \ * Raphael.bezierBBox [ method ] ** @@ -1667,7 +1691,7 @@ height: bbox.max.y - bbox.min.y }; }; - /*\ + /* \ * Raphael.isPointInsideBBox [ method ] ** @@ -1683,7 +1707,7 @@ R.isPointInsideBBox = function (bbox, x, y) { return x >= bbox.x && x <= bbox.x2 && y >= bbox.y && y <= bbox.y2; }; - /*\ + /* \ * Raphael.isBBoxIntersect [ method ] ** @@ -1708,20 +1732,20 @@ || (bbox1.x < bbox2.x2 && bbox1.x > bbox2.x || bbox2.x < bbox1.x2 && bbox2.x > bbox1.x) && (bbox1.y < bbox2.y2 && bbox1.y > bbox2.y || bbox2.y < bbox1.y2 && bbox2.y > bbox1.y); }; - function base3(t, p1, p2, p3, p4) { + function base3 (t, p1, p2, p3, p4) { var t1 = -3 * p1 + 9 * p2 - 9 * p3 + 3 * p4, t2 = t * t1 + 6 * p1 - 12 * p2 + 6 * p3; return t * t2 - 3 * p1 + 3 * p2; } - function bezlen(x1, y1, x2, y2, x3, y3, x4, y4, z) { + function bezlen (x1, y1, x2, y2, x3, y3, x4, y4, z) { if (z == null) { z = 1; } z = z > 1 ? 1 : z < 0 ? 0 : z; var z2 = z / 2, n = 12, - Tvalues = [-0.1252,0.1252,-0.3678,0.3678,-0.5873,0.5873,-0.7699,0.7699,-0.9041,0.9041,-0.9816,0.9816], - Cvalues = [0.2491,0.2491,0.2335,0.2335,0.2032,0.2032,0.1601,0.1601,0.1069,0.1069,0.0472,0.0472], + Tvalues = [-0.1252, 0.1252, -0.3678, 0.3678, -0.5873, 0.5873, -0.7699, 0.7699, -0.9041, 0.9041, -0.9816, 0.9816], + Cvalues = [0.2491, 0.2491, 0.2335, 0.2335, 0.2032, 0.2032, 0.1601, 0.1601, 0.1069, 0.1069, 0.0472, 0.0472], sum = 0; for (var i = 0; i < n; i++) { var ct = z2 * Tvalues[i] + z2, @@ -1732,7 +1756,7 @@ } return z2 * sum; } - function getTatLen(x1, y1, x2, y2, x3, y3, x4, y4, ll) { + function getTatLen (x1, y1, x2, y2, x3, y3, x4, y4, ll) { if (ll < 0 || bezlen(x1, y1, x2, y2, x3, y3, x4, y4) < ll) { return; } @@ -1749,7 +1773,7 @@ } return t2; } - function intersect(x1, y1, x2, y2, x3, y3, x4, y4) { + function intersect (x1, y1, x2, y2, x3, y3, x4, y4) { if ( mmax(x1, x2) < mmin(x3, x4) || mmin(x1, x2) > mmax(x3, x4) || @@ -1783,13 +1807,13 @@ } return {x: px, y: py}; } - function inter(bez1, bez2) { + function inter (bez1, bez2) { return interHelper(bez1, bez2); } - function interCount(bez1, bez2) { + function interCount (bez1, bez2) { return interHelper(bez1, bez2, 1); } - function interHelper(bez1, bez2, justCount) { + function interHelper (bez1, bez2, justCount) { var bbox1 = R.bezierBBox(bez1), bbox2 = R.bezierBBox(bez2); if (!R.isBBoxIntersect(bbox1, bbox2)) { @@ -1844,7 +1868,7 @@ } return res; } - /*\ + /* \ * Raphael.pathIntersection [ method ] ** @@ -1874,7 +1898,7 @@ R.pathIntersectionNumber = function (path1, path2) { return interPathHelper(path1, path2, 1); }; - function interPathHelper(path1, path2, justCount) { + function interPathHelper (path1, path2, justCount) { path1 = R._path2curve(path1); path2 = R._path2curve(path2); var x1, y1, x2, y2, x1m, y1m, x2m, y2m, bez1, bez2, @@ -1927,7 +1951,7 @@ } return res; } - /*\ + /* \ * Raphael.isPointInsidePath [ method ] ** @@ -1950,7 +1974,7 @@ eve("raphael.log", null, "Rapha\xebl: you are calling to method \u201c" + methodname + "\u201d of removed object", methodname); }; }; - /*\ + /* \ * Raphael.pathBBox [ method ] ** @@ -2295,14 +2319,14 @@ m2[1] = 2 * m1[1] - m2[1]; if (recursive) { return [m2, m3, m4][concat](res); - } else { - res = [m2, m3, m4][concat](res).join()[split](","); - var newres = []; - for (var i = 0, ii = res.length; i < ii; i++) { - newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; - } - return newres; } + res = [m2, m3, m4][concat](res).join()[split](","); + var newres = []; + for (var i = 0, ii = res.length; i < ii; i++) { + newres[i] = i % 2 ? rotate(res[i - 1], res[i], rad).y : rotate(res[i], res[i + 1], rad).x; + } + return newres; + }, findDotAtSegment = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, t) { var t1 = 1 - t; @@ -2364,7 +2388,7 @@ attrs = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, attrs2 = {x: 0, y: 0, bx: 0, by: 0, X: 0, Y: 0, qx: null, qy: null}, processPath = function (path, d, pcom) { - var nx, ny, tq = {T:1, Q:1}; + var nx, ny, tq = {T: 1, Q: 1}; if (!path) { return ["C", d.x, d.y, d.x, d.y, d.x, d.y]; } @@ -2381,8 +2405,7 @@ if (pcom == "C" || pcom == "S") { // In "S" case we have to take into account, if the previous command is C/S. nx = d.x * 2 - d.bx; // And reflect the previous ny = d.y * 2 - d.by; // command's control point relative to the current point. - } - else { // or some else or nothing + } else { // or some else or nothing nx = d.x; ny = d.y; } @@ -2392,8 +2415,7 @@ if (pcom == "Q" || pcom == "T") { // In "T" case we have to take into account, if the previous command is Q/T. d.qx = d.x * 2 - d.qx; // And make a reflection similar d.qy = d.y * 2 - d.qy; // to case "S". - } - else { // or something else or nothing + } else { // or something else or nothing d.qx = d.x; d.qy = d.y; } @@ -2424,8 +2446,8 @@ pp[i].shift(); var pi = pp[i]; while (pi.length) { - pcoms1[i]="A"; // if created multiple C:s, their original seg is saved - p2 && (pcoms2[i]="A"); // the same as above + pcoms1[i] = "A"; // if created multiple C:s, their original seg is saved + p2 && (pcoms2[i] = "A"); // the same as above pp.splice(i++, 0, ["C"][concat](pi.splice(0, 6))); } pp.splice(i, 1); @@ -2452,7 +2474,7 @@ if (pfirst != "C") // C is not saved yet, because it may be result of conversion { pcoms1[i] = pfirst; // Save current path command - i && ( pcom = pcoms1[i-1]); // Get previous path command pcom + i && ( pcom = pcoms1[i - 1]); // Get previous path command pcom } p[i] = processPath(p[i], attrs, pcom); // Previous path command is inputted to processPath @@ -2464,14 +2486,13 @@ if (p2) { // the same procedures is done to p2 p2[i] && (pfirst = p2[i][0]); - if (pfirst != "C") - { + if (pfirst != "C") { pcoms2[i] = pfirst; - i && (pcom = pcoms2[i-1]); + i && (pcom = pcoms2[i - 1]); } p2[i] = processPath(p2[i], attrs2, pcom); - if (pcoms2[i]!="A" && pfirst=="C") pcoms2[i]="C"; + if (pcoms2[i] != "A" && pfirst == "C") pcoms2[i] = "C"; fixArc(p2, i); } @@ -2575,7 +2596,7 @@ el2.prev = el; el.next = el2; }, - /*\ + /* \ * Raphael.toMatrix [ method ] ** @@ -2600,7 +2621,7 @@ extractTransform(el, transform); return el.matrix; }, - /*\ + /* \ * Raphael.transformPath [ method ] ** @@ -2691,7 +2712,7 @@ } } - /*\ + /* \ * Element.matrix [ property (object) ] ** @@ -2719,16 +2740,16 @@ case "m": return [l, 1, 0, 0, 1, 0, 0]; case "r": if (item.length == 4) { return [l, 0, item[2], item[3]]; - } else { - return [l, 0]; } + return [l, 0]; + case "s": if (item.length == 5) { return [l, 1, 1, item[3], item[4]]; } else if (item.length == 3) { - return [l, 1, 1]; - } else { + return [l, 1, 1]; + } return [l, 1]; - } + } }, equaliseTransform = R._equaliseTransform = function (t1, t2) { @@ -2774,13 +2795,13 @@ width: container.style.pixelWidth || container.offsetWidth, height: container.style.pixelHeight || container.offsetHeight }; - } else { - return { - container: container, - width: y, - height: w - }; } + return { + container: container, + width: y, + height: w + }; + } return { container: 1, @@ -2790,7 +2811,7 @@ height: h }; }; - /*\ + /* \ * Raphael.pathToRelative [ method ] ** @@ -2803,7 +2824,7 @@ \*/ R.pathToRelative = pathToRelative; R._engine = {}; - /*\ + /* \ * Raphael.path2curve [ method ] ** @@ -2815,7 +2836,7 @@ = (array) array of segments. \*/ R.path2curve = path2curve; - /*\ + /* \ * Raphael.matrix [ method ] ** @@ -2834,7 +2855,7 @@ R.matrix = function (a, b, c, d, e, f) { return new Matrix(a, b, c, d, e, f); }; - function Matrix(a, b, c, d, e, f) { + function Matrix (a, b, c, d, e, f) { if (a != null) { this.a = +a; this.b = +b; @@ -2852,7 +2873,7 @@ } } (function (matrixproto) { - /*\ + /* \ * Matrix.add [ method ] ** @@ -2893,7 +2914,7 @@ this.e = out[0][2]; this.f = out[1][2]; }; - /*\ + /* \ * Matrix.invert [ method ] ** @@ -2905,7 +2926,7 @@ x = me.a * me.d - me.b * me.c; return new Matrix(me.d / x, -me.b / x, -me.c / x, me.a / x, (me.c * me.f - me.d * me.e) / x, (me.b * me.e - me.a * me.f) / x); }; - /*\ + /* \ * Matrix.clone [ method ] ** @@ -2915,7 +2936,7 @@ matrixproto.clone = function () { return new Matrix(this.a, this.b, this.c, this.d, this.e, this.f); }; - /*\ + /* \ * Matrix.translate [ method ] ** @@ -2927,7 +2948,7 @@ matrixproto.translate = function (x, y) { this.add(1, 0, 0, 1, x, y); }; - /*\ + /* \ * Matrix.scale [ method ] ** @@ -2944,7 +2965,7 @@ this.add(x, 0, 0, y, 0, 0); (cx || cy) && this.add(1, 0, 0, 1, -cx, -cy); }; - /*\ + /* \ * Matrix.rotate [ method ] ** @@ -2963,7 +2984,7 @@ this.add(cos, sin, -sin, cos, x, y); this.add(1, 0, 0, 1, -x, -y); }; - /*\ + /* \ * Matrix.x [ method ] ** @@ -2976,7 +2997,7 @@ matrixproto.x = function (x, y) { return x * this.a + y * this.c + this.e; }; - /*\ + /* \ * Matrix.y [ method ] ** @@ -2994,7 +3015,7 @@ }; matrixproto.toString = function () { return R.svg ? - "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : + "matrix(" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)].join() + ")" : [this.get(0), this.get(2), this.get(1), this.get(3), 0, 0].join(); }; matrixproto.toFilter = function () { @@ -3005,15 +3026,15 @@ matrixproto.offset = function () { return [this.e.toFixed(4), this.f.toFixed(4)]; }; - function norm(a) { + function norm (a) { return a[0] * a[0] + a[1] * a[1]; } - function normalize(a) { + function normalize (a) { var mag = math.sqrt(norm(a)); a[0] && (a[0] /= mag); a[1] && (a[1] /= mag); } - /*\ + /* \ * Matrix.split [ method ] ** @@ -3062,7 +3083,7 @@ out.noRotation = !+out.shear.toFixed(9) && !out.rotate; return out; }; - /*\ + /* \ * Matrix.toTransformString [ method ] ** @@ -3078,9 +3099,9 @@ return (s.dx || s.dy ? "t" + [s.dx, s.dy] : E) + (s.scalex != 1 || s.scaley != 1 ? "s" + [s.scalex, s.scaley, 0, 0] : E) + (s.rotate ? "r" + [s.rotate, 0, 0] : E); - } else { - return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; } + return "m" + [this.get(0), this.get(1), this.get(2), this.get(3), this.get(4), this.get(5)]; + }; })(Matrix.prototype); @@ -3137,8 +3158,7 @@ return function () { obj.removeEventListener(type, f, false); - if (supportsTouch && touchMap[type]) - obj.removeEventListener(touchMap[type], _f, false); + if (supportsTouch && touchMap[type]) {obj.removeEventListener(touchMap[type], _f, false);} return true; }; @@ -3216,7 +3236,7 @@ } drag = []; }, - /*\ + /* \ * Raphael.el [ property (object) ] ** @@ -3231,7 +3251,7 @@ | paper.circle(100, 100, 20).red(); \*/ elproto = R.el = {}; - /*\ + /* \ * Element.click [ method ] ** @@ -3240,7 +3260,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unclick [ method ] ** @@ -3250,7 +3270,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.dblclick [ method ] ** @@ -3259,7 +3279,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.undblclick [ method ] ** @@ -3269,7 +3289,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.mousedown [ method ] ** @@ -3278,7 +3298,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmousedown [ method ] ** @@ -3288,7 +3308,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.mousemove [ method ] ** @@ -3297,7 +3317,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmousemove [ method ] ** @@ -3307,7 +3327,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.mouseout [ method ] ** @@ -3316,7 +3336,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseout [ method ] ** @@ -3326,7 +3346,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.mouseover [ method ] ** @@ -3335,7 +3355,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseover [ method ] ** @@ -3345,7 +3365,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.mouseup [ method ] ** @@ -3354,7 +3374,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.unmouseup [ method ] ** @@ -3364,7 +3384,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.touchstart [ method ] ** @@ -3373,7 +3393,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchstart [ method ] ** @@ -3383,7 +3403,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.touchmove [ method ] ** @@ -3392,7 +3412,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchmove [ method ] ** @@ -3402,7 +3422,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.touchend [ method ] ** @@ -3411,7 +3431,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchend [ method ] ** @@ -3421,7 +3441,7 @@ = (object) @Element \*/ - /*\ + /* \ * Element.touchcancel [ method ] ** @@ -3430,7 +3450,7 @@ - handler (function) handler for the event = (object) @Element \*/ - /*\ + /* \ * Element.untouchcancel [ method ] ** @@ -3451,7 +3471,7 @@ R["un" + eventName] = elproto["un" + eventName] = function (fn) { var events = this.events || [], l = events.length; - while (l--){ + while (l--) { if (events[l].name == eventName && (R.is(fn, "undefined") || events[l].f == fn)) { events[l].unbind(); events.splice(l, 1); @@ -3463,7 +3483,7 @@ })(events[i]); } - /*\ + /* \ * Element.data [ method ] ** @@ -3495,8 +3515,10 @@ } if (arguments.length == 1) { if (R.is(key, "object")) { - for (var i in key) if (key[has](i)) { - this.data(i, key[i]); + for (var i in key) { + if (key[has](i)) { + this.data(i, key[i]); + } } return this; } @@ -3508,11 +3530,11 @@ return this; }; - elproto.datum = function(){ + elproto.datum = function () { return arguments.length == 0 ? this._bindData : ((this._bindData = arguments[0]), this); }; - /*\ + /* \ * Element.removeData [ method ] ** @@ -3530,7 +3552,7 @@ } return this; }; - /*\ + /* \ * Element.getData [ method ] ** @@ -3540,7 +3562,7 @@ elproto.getData = function () { return clone(eldata[this.id] || {}); }; - /*\ + /* \ * Element.hover [ method ] ** @@ -3555,7 +3577,7 @@ elproto.hover = function (f_in, f_out, scope_in, scope_out) { return this.mouseover(f_in, scope_in).mouseout(f_out, scope_out || scope_in); }; - /*\ + /* \ * Element.unhover [ method ] ** @@ -3569,7 +3591,7 @@ return this.unmouseover(f_in).unmouseout(f_out); }; var draggable = []; - /*\ + /* \ * Element.drag [ method ] ** @@ -3600,7 +3622,7 @@ = (object) @Element \*/ elproto.drag = function (onmove, onstart, onend, move_scope, start_scope, end_scope) { - function start(e) { + function start (e) { (e.originalEvent || e).preventDefault(); var x = e.clientX, y = e.clientY, @@ -3633,7 +3655,7 @@ this.mousedown(start); return this; }; - /*\ + /* \ * Element.onDragOver [ method ] ** @@ -3644,7 +3666,7 @@ elproto.onDragOver = function (f) { f ? eve.on("raphael.drag.over." + this.id, f) : eve.unbind("raphael.drag.over." + this.id); }; - /*\ + /* \ * Element.undrag [ method ] ** @@ -3652,15 +3674,17 @@ \*/ elproto.undrag = function () { var i = draggable.length; - while (i--) if (draggable[i].el == this) { - this.unmousedown(draggable[i].start); - draggable.splice(i, 1); - eve.unbind("raphael.drag.*." + this.id); + while (i--) { + if (draggable[i].el == this) { + this.unmousedown(draggable[i].start); + draggable.splice(i, 1); + eve.unbind("raphael.drag.*." + this.id); + } } !draggable.length && R.unmousemove(dragMove).unmouseup(dragUp); drag = []; }; - /*\ + /* \ * Paper.circle [ method ] ** @@ -3681,7 +3705,7 @@ this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.rect [ method ] * @@ -3707,7 +3731,7 @@ this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.ellipse [ method ] ** @@ -3729,7 +3753,7 @@ this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.path [ method ] ** @@ -3767,7 +3791,7 @@ this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.image [ method ] ** @@ -3790,7 +3814,7 @@ this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.text [ method ] ** @@ -3811,7 +3835,7 @@ this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Paper.set [ method ] ** @@ -3836,7 +3860,7 @@ out["type"] = "set"; return out; }; - /*\ + /* \ * Paper.setStart [ method ] ** @@ -3853,7 +3877,7 @@ paperproto.setStart = function (set) { this.__set__ = set || this.set(); }; - /*\ + /* \ * Paper.setFinish [ method ] ** @@ -3866,7 +3890,7 @@ delete this.__set__; return out; }; - /*\ + /* \ * Paper.getSize [ method ] ** @@ -3881,7 +3905,7 @@ height: container.offsetHeight }; }; - /*\ + /* \ * Paper.setSize [ method ] ** @@ -3895,7 +3919,7 @@ paperproto.setSize = function (width, height) { return R._engine.setSize.call(this, width, height); }; - /*\ + /* \ * Paper.setViewBox [ method ] ** @@ -3913,20 +3937,20 @@ paperproto.setViewBox = function (x, y, w, h, fit) { return R._engine.setViewBox.call(this, x, y, w, h, fit); }; - /*\ + /* \ * Paper.top [ property ] ** * Points to the topmost element on the paper \*/ - /*\ + /* \ * Paper.bottom [ property ] ** * Points to the bottom element on the paper \*/ paperproto.top = paperproto.bottom = null; - /*\ + /* \ * Paper.raphael [ property ] ** @@ -3946,7 +3970,7 @@ x: left }; }; - /*\ + /* \ * Paper.getElementByPoint [ method ] ** @@ -3986,7 +4010,7 @@ return target; }; - /*\ + /* \ * Paper.getElementsByBBox [ method ] ** @@ -4007,7 +4031,7 @@ return set; }; - /*\ + /* \ * Paper.getById [ method ] ** @@ -4028,7 +4052,7 @@ } return null; }; - /*\ + /* \ * Paper.forEach [ method ] ** @@ -4056,7 +4080,7 @@ } return this; }; - /*\ + /* \ * Paper.getElementsByPoint [ method ] ** @@ -4077,13 +4101,13 @@ }); return set; }; - function x_y() { + function x_y () { return this.x + S + this.y; } - function x_y_w_h() { + function x_y_w_h () { return this.x + S + this.y + S + this.width + " \xd7 " + this.height; } - /*\ + /* \ * Element.isPointInside [ method ] ** @@ -4097,12 +4121,12 @@ \*/ elproto.isPointInside = function (x, y) { var rp = this.realPath = getPath[this.type](this); - if (this.attr('transform') && this.attr('transform').length) { - rp = R.transformPath(rp, this.attr('transform')); + if (this.attr("transform") && this.attr("transform").length) { + rp = R.transformPath(rp, this.attr("transform")); } return R.isPointInsidePath(rp, x, y); }; - /*\ + /* \ * Element.getBBox [ method ] ** @@ -4146,7 +4170,7 @@ } return _.bbox; }; - /*\ + /* \ * Element.clone [ method ] ** @@ -4161,7 +4185,7 @@ this.__set__ && this.__set__.push(out); return out; }; - /*\ + /* \ * Element.glow [ method ] ** @@ -4216,9 +4240,9 @@ getPointAtSegmentLength = function (p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length) { if (length == null) { return bezlen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y); - } else { - return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); } + return R.findDotsAtSegment(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, getTatLen(p1x, p1y, c1x, c1y, c2x, c2y, p2x, p2y, length)); + }, getLengthFactory = function (istotal, subpath) { return function (path, length, onlystart) { @@ -4264,7 +4288,7 @@ var getTotalLength = getLengthFactory(1), getPointAtLength = getLengthFactory(), getSubpathsAtLength = getLengthFactory(0, 1); - /*\ + /* \ * Raphael.getTotalLength [ method ] ** @@ -4277,7 +4301,7 @@ = (number) length. \*/ R.getTotalLength = getTotalLength; - /*\ + /* \ * Raphael.getPointAtLength [ method ] ** @@ -4296,7 +4320,7 @@ o } \*/ R.getPointAtLength = getPointAtLength; - /*\ + /* \ * Raphael.getSubpath [ method ] ** @@ -4317,7 +4341,7 @@ var a = getSubpathsAtLength(path, to, 1); return from ? getSubpathsAtLength(a, from).end : a; }; - /*\ + /* \ * Element.getTotalLength [ method ] ** @@ -4336,7 +4360,7 @@ return getTotalLength(path); }; - /*\ + /* \ * Element.getPointAtLength [ method ] ** @@ -4361,7 +4385,7 @@ return getPointAtLength(path, length); }; - /*\ + /* \ * Element.getPath [ method ] ** @@ -4383,7 +4407,7 @@ return path; }; - /*\ + /* \ * Element.getSubpath [ method ] ** @@ -4404,7 +4428,7 @@ return R.getSubpath(path, from, to); }; - /*\ + /* \ * Raphael.easing_formulas [ property ] ** @@ -4527,65 +4551,67 @@ } if (time < ms) { var pos = easing(time / ms); - for (var attr in from) if (from[has](attr)) { - switch (availableAnimAttrs[attr]) { - case nu: - now = +from[attr] + pos * ms * diff[attr]; - break; - case "colour": - now = "rgb(" + [ + for (var attr in from) { + if (from[has](attr)) { + switch (availableAnimAttrs[attr]) { + case nu: + now = +from[attr] + pos * ms * diff[attr]; + break; + case "colour": + now = "rgb(" + [ upto255(round(from[attr].r + pos * ms * diff[attr].r)), upto255(round(from[attr].g + pos * ms * diff[attr].g)), upto255(round(from[attr].b + pos * ms * diff[attr].b)) ].join(",") + ")"; - break; - case "path": - now = []; - for (var i = 0, ii = from[attr].length; i < ii; i++) { - now[i] = [from[attr][i][0]]; - for (var j = 1, jj = from[attr][i].length; j < jj; j++) { - now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j]; - } - now[i] = now[i].join(S); - } - now = now.join(S); - break; - case "transform": - if (diff[attr].real) { + break; + case "path": now = []; - for (i = 0, ii = from[attr].length; i < ii; i++) { + for (var i = 0, ii = from[attr].length; i < ii; i++) { now[i] = [from[attr][i][0]]; - for (j = 1, jj = from[attr][i].length; j < jj; j++) { - now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; + for (var j = 1, jj = from[attr][i].length; j < jj; j++) { + now[i][j] = +from[attr][i][j] + pos * ms * diff[attr][i][j]; } + now[i] = now[i].join(S); } - } else { - var get = function (i) { - return +from[attr][i] + pos * ms * diff[attr][i]; - }; - // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; - now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; - } - break; - case "csv": - if (attr == "clip-rect") { + now = now.join(S); + break; + case "transform": + if (diff[attr].real) { + now = []; + for (i = 0, ii = from[attr].length; i < ii; i++) { + now[i] = [from[attr][i][0]]; + for (j = 1, jj = from[attr][i].length; j < jj; j++) { + now[i][j] = from[attr][i][j] + pos * ms * diff[attr][i][j]; + } + } + } else { + var get = function (i) { + return +from[attr][i] + pos * ms * diff[attr][i]; + }; + // now = [["r", get(2), 0, 0], ["t", get(3), get(4)], ["s", get(0), get(1), 0, 0]]; + now = [["m", get(0), get(1), get(2), get(3), get(4), get(5)]]; + } + break; + case "csv": + if (attr == "clip-rect") { + now = []; + i = 4; + while (i--) { + now[i] = +from[attr][i] + pos * ms * diff[attr][i]; + } + } + break; + default: + var from2 = [][concat](from[attr]); now = []; - i = 4; + i = that.paper.customAttributes[attr].length; while (i--) { - now[i] = +from[attr][i] + pos * ms * diff[attr][i]; + now[i] = +from2[i] + pos * ms * diff[attr][i]; } - } - break; - default: - var from2 = [][concat](from[attr]); - now = []; - i = that.paper.customAttributes[attr].length; - while (i--) { - now[i] = +from2[i] + pos * ms * diff[attr][i]; - } - break; + break; + } + set[attr] = now; } - set[attr] = now; } that.attr(set); (function (id, that, anim) { @@ -4594,8 +4620,8 @@ }); })(that.id, that, e.anim); } else { - (function(f, el, a) { - setTimeout(function() { + (function (f, el, a) { + setTimeout(function () { eve("raphael.anim.frame." + el.id, el, a); eve("raphael.anim.finish." + el.id, el, a); R.is(f, "function") && f.call(el); @@ -4604,8 +4630,10 @@ that.attr(to); animationElements.splice(l--, 1); if (e.repeat > 1 && !e.next) { - for (key in to) if (to[has](key)) { - init[key] = e.totalOrigin[key]; + for (key in to) { + if (to[has](key)) { + init[key] = e.totalOrigin[key]; + } } e.el.attr(init); runAnimation(e.anim, e.el, e.anim.percents[0], null, e.totalOrigin, e.repeat - 1); @@ -4620,7 +4648,7 @@ upto255 = function (color) { return color > 255 ? 255 : color < 0 ? 0 : color; }; - /*\ + /* \ * Element.animateWith [ method ] ** @@ -4663,21 +4691,21 @@ // status = element.status(anim); // return this.animate(a).status(a, status * anim.ms / a.ms); }; - function CubicBezierAtTime(t, p1x, p1y, p2x, p2y, duration) { + function CubicBezierAtTime (t, p1x, p1y, p2x, p2y, duration) { var cx = 3 * p1x, bx = 3 * (p2x - p1x) - cx, ax = 1 - cx - bx, cy = 3 * p1y, by = 3 * (p2y - p1y) - cy, ay = 1 - cy - by; - function sampleCurveX(t) { + function sampleCurveX (t) { return ((ax * t + bx) * t + cx) * t; } - function solve(x, epsilon) { + function solve (x, epsilon) { var t = solveCurveX(x, epsilon); return ((ay * t + by) * t + cy) * t; } - function solveCurveX(x, epsilon) { + function solveCurveX (x, epsilon) { var t0, t1, t2, x2, d2, i; for(t2 = x, i = 0; i < 8; i++) { x2 = sampleCurveX(t2) - x; @@ -4719,15 +4747,17 @@ f ? eve.on("raphael.anim.frame." + this.id, f) : eve.unbind("raphael.anim.frame." + this.id); return this; }; - function Animation(anim, ms) { + function Animation (anim, ms) { var percents = [], newAnim = {}; this.ms = ms; this.times = 1; if (anim) { - for (var attr in anim) if (anim[has](attr)) { - newAnim[toFloat(attr)] = anim[attr]; - percents.push(toFloat(attr)); + for (var attr in anim) { + if (anim[has](attr)) { + newAnim[toFloat(attr)] = anim[attr]; + percents.push(toFloat(attr)); + } } percents.sort(sortByNumber); } @@ -4735,7 +4765,7 @@ this.top = percents[percents.length - 1]; this.percents = percents; } - /*\ + /* \ * Animation.delay [ method ] ** @@ -4756,7 +4786,7 @@ a.del = +delay || 0; return a; }; - /*\ + /* \ * Animation.repeat [ method ] ** @@ -4774,7 +4804,7 @@ a.times = math.floor(mmax(times, 0)) || 1; return a; }; - function runAnimation(anim, element, percent, status, totalOrigin, times) { + function runAnimation (anim, element, percent, status, totalOrigin, times) { percent = toFloat(percent); var params, isInAnim, @@ -4820,76 +4850,77 @@ return; } if (!isInAnim) { - for (var attr in params) if (params[has](attr)) { - if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) { - from[attr] = element.attr(attr); - (from[attr] == null) && (from[attr] = availableAttrs[attr]); - to[attr] = params[attr]; - switch (availableAnimAttrs[attr]) { - case nu: - diff[attr] = (to[attr] - from[attr]) / ms; - break; - case "colour": - from[attr] = R.getRGB(from[attr]); - var toColour = R.getRGB(to[attr]); - diff[attr] = { - r: (toColour.r - from[attr].r) / ms, - g: (toColour.g - from[attr].g) / ms, - b: (toColour.b - from[attr].b) / ms - }; - break; - case "path": - var pathes = path2curve(from[attr], to[attr]), - toPath = pathes[1]; - from[attr] = pathes[0]; - diff[attr] = []; - for (i = 0, ii = from[attr].length; i < ii; i++) { - diff[attr][i] = [0]; - for (var j = 1, jj = from[attr][i].length; j < jj; j++) { - diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; - } - } - break; - case "transform": - var _ = element._, - eq = equaliseTransform(_[attr], to[attr]); - if (eq) { - from[attr] = eq.from; - to[attr] = eq.to; + for (var attr in params) { + if (params[has](attr)) { + if (availableAnimAttrs[has](attr) || element.paper.customAttributes[has](attr)) { + from[attr] = element.attr(attr); + (from[attr] == null) && (from[attr] = availableAttrs[attr]); + to[attr] = params[attr]; + switch (availableAnimAttrs[attr]) { + case nu: + diff[attr] = (to[attr] - from[attr]) / ms; + break; + case "colour": + from[attr] = R.getRGB(from[attr]); + var toColour = R.getRGB(to[attr]); + diff[attr] = { + r: (toColour.r - from[attr].r) / ms, + g: (toColour.g - from[attr].g) / ms, + b: (toColour.b - from[attr].b) / ms + }; + break; + case "path": + var pathes = path2curve(from[attr], to[attr]), + toPath = pathes[1]; + from[attr] = pathes[0]; diff[attr] = []; - diff[attr].real = true; for (i = 0, ii = from[attr].length; i < ii; i++) { - diff[attr][i] = [from[attr][i][0]]; - for (j = 1, jj = from[attr][i].length; j < jj; j++) { - diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; + diff[attr][i] = [0]; + for (var j = 1, jj = from[attr][i].length; j < jj; j++) { + diff[attr][i][j] = (toPath[i][j] - from[attr][i][j]) / ms; } } - } else { - var m = (element.matrix || new Matrix), - to2 = { - _: {transform: _.transform}, - getBBox: function () { - return element.getBBox(1); + break; + case "transform": + var _ = element._, + eq = equaliseTransform(_[attr], to[attr]); + if (eq) { + from[attr] = eq.from; + to[attr] = eq.to; + diff[attr] = []; + diff[attr].real = true; + for (i = 0, ii = from[attr].length; i < ii; i++) { + diff[attr][i] = [from[attr][i][0]]; + for (j = 1, jj = from[attr][i].length; j < jj; j++) { + diff[attr][i][j] = (to[attr][i][j] - from[attr][i][j]) / ms; } - }; - from[attr] = [ - m.a, - m.b, - m.c, - m.d, - m.e, - m.f - ]; - extractTransform(to2, to[attr]); - to[attr] = to2._.transform; - diff[attr] = [ - (to2.matrix.a - m.a) / ms, - (to2.matrix.b - m.b) / ms, - (to2.matrix.c - m.c) / ms, - (to2.matrix.d - m.d) / ms, - (to2.matrix.e - m.e) / ms, - (to2.matrix.f - m.f) / ms - ]; + } + } else { + var m = (element.matrix || new Matrix), + to2 = { + _: {transform: _.transform}, + getBBox: function () { + return element.getBBox(1); + } + }; + from[attr] = [ + m.a, + m.b, + m.c, + m.d, + m.e, + m.f + ]; + extractTransform(to2, to[attr]); + to[attr] = to2._.transform; + diff[attr] = [ + (to2.matrix.a - m.a) / ms, + (to2.matrix.b - m.b) / ms, + (to2.matrix.c - m.c) / ms, + (to2.matrix.d - m.d) / ms, + (to2.matrix.e - m.e) / ms, + (to2.matrix.f - m.f) / ms + ]; // from[attr] = [_.sx, _.sy, _.deg, _.dx, _.dy]; // var to2 = {_:{}, getBBox: function () { return element.getBBox(); }}; // extractTransform(to2, to[attr]); @@ -4900,30 +4931,31 @@ // (to2._.dx - _.dx) / ms, // (to2._.dy - _.dy) / ms // ]; - } - break; - case "csv": - var values = Str(params[attr])[split](separator), - from2 = Str(from[attr])[split](separator); - if (attr == "clip-rect") { - from[attr] = from2; + } + break; + case "csv": + var values = Str(params[attr])[split](separator), + from2 = Str(from[attr])[split](separator); + if (attr == "clip-rect") { + from[attr] = from2; + diff[attr] = []; + i = from2.length; + while (i--) { + diff[attr][i] = (values[i] - from[attr][i]) / ms; + } + } + to[attr] = values; + break; + default: + values = [][concat](params[attr]); + from2 = [][concat](from[attr]); diff[attr] = []; - i = from2.length; + i = element.paper.customAttributes[attr].length; while (i--) { - diff[attr][i] = (values[i] - from[attr][i]) / ms; + diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms; } - } - to[attr] = values; - break; - default: - values = [][concat](params[attr]); - from2 = [][concat](from[attr]); - diff[attr] = []; - i = element.paper.customAttributes[attr].length; - while (i--) { - diff[attr][i] = ((values[i] || 0) - (from2[i] || 0)) / ms; - } - break; + break; + } } } } @@ -4980,7 +5012,7 @@ } eve("raphael.anim.start." + element.id, element, anim); } - /*\ + /* \ * Raphael.animation [ method ] ** @@ -5009,33 +5041,35 @@ var p = {}, json, attr; - for (attr in params) if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { - json = true; - p[attr] = params[attr]; + for (attr in params) { + if (params[has](attr) && toFloat(attr) != attr && toFloat(attr) + "%" != attr) { + json = true; + p[attr] = params[attr]; + } } if (!json) { // if percent-like syntax is used and end-of-all animation callback used - if(callback){ + if(callback) { // find the last one var lastKey = 0; - for(var i in params){ + for(var i in params) { var percent = toInt(i); - if(params[has](i) && percent > lastKey){ + if(params[has](i) && percent > lastKey) { lastKey = percent; } } - lastKey += '%'; + lastKey += "%"; // if already defined callback in the last keyframe, skip !params[lastKey].callback && (params[lastKey].callback = callback); } return new Animation(params, ms); - } else { - easing && (p.easing = easing); - callback && (p.callback = callback); - return new Animation({100: p}, ms); } + easing && (p.easing = easing); + callback && (p.callback = callback); + return new Animation({100: p}, ms); + }; - /*\ + /* \ * Element.animate [ method ] ** @@ -5062,7 +5096,7 @@ runAnimation(anim, element, anim.percents[0], null, element.attr()); return element; }; - /*\ + /* \ * Element.setTime [ method ] ** @@ -5084,7 +5118,7 @@ } return this; }; - /*\ + /* \ * Element.status [ method ] ** @@ -5113,27 +5147,27 @@ if (value != null) { runAnimation(anim, this, -1, mmin(value, 1)); return this; - } else { - len = animationElements.length; - for (; i < len; i++) { - e = animationElements[i]; - if (e.el.id == this.id && (!anim || e.anim == anim)) { - if (anim) { - return e.status; - } - out.push({ - anim: e.anim, - status: e.status - }); + } + len = animationElements.length; + for (; i < len; i++) { + e = animationElements[i]; + if (e.el.id == this.id && (!anim || e.anim == anim)) { + if (anim) { + return e.status; } + out.push({ + anim: e.anim, + status: e.status + }); } - if (anim) { - return 0; - } - return out; } + if (anim) { + return 0; + } + return out; + }; - /*\ + /* \ * Element.pause [ method ] ** @@ -5146,14 +5180,16 @@ = (object) original element \*/ elproto.pause = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) { - animationElements[i].paused = true; + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + if (eve("raphael.anim.pause." + this.id, this, animationElements[i].anim) !== false) { + animationElements[i].paused = true; + } } } return this; }; - /*\ + /* \ * Element.resume [ method ] ** @@ -5166,16 +5202,18 @@ = (object) original element \*/ elproto.resume = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - var e = animationElements[i]; - if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { - delete e.paused; - this.status(e.anim, e.status); + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + var e = animationElements[i]; + if (eve("raphael.anim.resume." + this.id, this, e.anim) !== false) { + delete e.paused; + this.status(e.anim, e.status); + } } } return this; }; - /*\ + /* \ * Element.stop [ method ] ** @@ -5188,16 +5226,20 @@ = (object) original element \*/ elproto.stop = function (anim) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { - if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) { - animationElements.splice(i--, 1); + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.id == this.id && (!anim || animationElements[i].anim == anim)) { + if (eve("raphael.anim.stop." + this.id, this, animationElements[i].anim) !== false) { + animationElements.splice(i--, 1); + } } } return this; }; - function stopAnimation(paper) { - for (var i = 0; i < animationElements.length; i++) if (animationElements[i].el.paper == paper) { - animationElements.splice(i--, 1); + function stopAnimation (paper) { + for (var i = 0; i < animationElements.length; i++) { + if (animationElements[i].el.paper == paper) { + animationElements.splice(i--, 1); + } } } eve.on("raphael.remove", stopAnimation); @@ -5221,7 +5263,7 @@ } }, setproto = Set.prototype; - /*\ + /* \ * Set.push [ method ] ** @@ -5241,7 +5283,7 @@ } return this; }; - /*\ + /* \ * Set.pop [ method ] ** @@ -5252,7 +5294,7 @@ this.length && delete this[this.length--]; return this.items.pop(); }; - /*\ + /* \ * Set.forEach [ method ] ** @@ -5274,15 +5316,17 @@ } return this; }; - for (var method in elproto) if (elproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname][apply](el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname][apply](el, arg); + }); + }; + })(method); + } } setproto.attr = function (name, value) { if (name && R.is(name, array) && R.is(name[0], "object")) { @@ -5296,7 +5340,7 @@ } return this; }; - /*\ + /* \ * Set.clear [ method ] ** @@ -5307,7 +5351,7 @@ this.pop(); } }; - /*\ + /* \ * Set.splice [ method ] ** @@ -5346,7 +5390,7 @@ } return new Set(todel); }; - /*\ + /* \ * Set.exclude [ method ] ** @@ -5358,9 +5402,11 @@ = (boolean) `true` if object was found & removed from the set \*/ setproto.exclude = function (el) { - for (var i = 0, ii = this.length; i < ii; i++) if (this[i] == el) { - this.splice(i, 1); - return true; + for (var i = 0, ii = this.length; i < ii; i++) { + if (this[i] == el) { + this.splice(i, 1); + return true; + } } }; setproto.animate = function (params, ms, easing, callback) { @@ -5397,12 +5443,14 @@ y = [], x2 = [], y2 = []; - for (var i = this.items.length; i--;) if (!this.items[i].removed) { - var box = this.items[i].getBBox(); - x.push(box.x); - y.push(box.y); - x2.push(box.x + box.width); - y2.push(box.y + box.height); + for (var i = this.items.length; i--;) { + if (!this.items[i].removed) { + var box = this.items[i].getBBox(); + x.push(box.x); + y.push(box.y); + x2.push(box.x + box.width); + y2.push(box.y + box.height); + } } x = mmin[apply](0, x); y = mmin[apply](0, y); @@ -5428,12 +5476,12 @@ return "Rapha\xebl\u2018s set"; }; - setproto.glow = function(glowConfig) { + setproto.glow = function (glowConfig) { var ret = this.paper.set(); - this.forEach(function(shape, index){ + this.forEach(function (shape, index) { var g = shape.glow(glowConfig); - if(g != null){ - g.forEach(function(shape2, index2){ + if(g != null) { + g.forEach(function (shape2, index2) { ret.push(shape2); }); } @@ -5442,7 +5490,7 @@ }; - /*\ + /* \ * Set.isPointInside [ method ] ** @@ -5465,7 +5513,7 @@ return isPointInside; }; - /*\ + /* \ * Raphael.registerFont [ method ] ** @@ -5491,8 +5539,10 @@ glyphs: {} }, family = font.face["font-family"]; - for (var prop in font.face) if (font.face[has](prop)) { - fontcopy.face[prop] = font.face[prop]; + for (var prop in font.face) { + if (font.face[has](prop)) { + fontcopy.face[prop] = font.face[prop]; + } } if (this.fonts[family]) { this.fonts[family].push(fontcopy); @@ -5501,25 +5551,29 @@ } if (!font.svg) { fontcopy.face["units-per-em"] = toInt(font.face["units-per-em"], 10); - for (var glyph in font.glyphs) if (font.glyphs[has](glyph)) { - var path = font.glyphs[glyph]; - fontcopy.glyphs[glyph] = { - w: path.w, - k: {}, - d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) { - return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M"; - }) + "z" - }; - if (path.k) { - for (var k in path.k) if (path[has](k)) { - fontcopy.glyphs[glyph].k[k] = path.k[k]; + for (var glyph in font.glyphs) { + if (font.glyphs[has](glyph)) { + var path = font.glyphs[glyph]; + fontcopy.glyphs[glyph] = { + w: path.w, + k: {}, + d: path.d && "M" + path.d.replace(/[mlcxtrv]/g, function (command) { + return {l: "L", c: "C", x: "z", t: "m", r: "l", v: "c"}[command] || "M"; + }) + "z" + }; + if (path.k) { + for (var k in path.k) { + if (path[has](k)) { + fontcopy.glyphs[glyph].k[k] = path.k[k]; + } + } } } } } return font; }; - /*\ + /* \ * Paper.getFont [ method ] ** @@ -5545,10 +5599,12 @@ var font = R.fonts[family]; if (!font) { var name = new RegExp("(^|\\s)" + family.replace(/[^\w\d\s+!~.:_-]/g, E) + "(\\s|$)", "i"); - for (var fontName in R.fonts) if (R.fonts[has](fontName)) { - if (name.test(fontName)) { - font = R.fonts[fontName]; - break; + for (var fontName in R.fonts) { + if (R.fonts[has](fontName)) { + if (name.test(fontName)) { + font = R.fonts[fontName]; + break; + } } } } @@ -5563,7 +5619,7 @@ } return thefont; }; - /*\ + /* \ * Paper.print [ method ] ** @@ -5624,7 +5680,7 @@ }); }; - /*\ + /* \ * Paper.add [ method ] ** @@ -5666,7 +5722,7 @@ return res; }; - /*\ + /* \ * Raphael.format [ method ] ** @@ -5692,7 +5748,7 @@ })); return token || E; }; - /*\ + /* \ * Raphael.fullfill [ method ] ** @@ -5726,7 +5782,7 @@ if (name in res) { res = res[name]; } - typeof res == "function" && isFunc && (res = res()); + typeof res === "function" && isFunc && (res = res()); } }); res = (res == null || res == obj ? all : res) + ""; @@ -5738,7 +5794,7 @@ }); }; })(); - /*\ + /* \ * Raphael.ninja [ method ] ** @@ -5756,7 +5812,7 @@ oldRaphael.was ? (g.win.Raphael = oldRaphael.is) : delete Raphael; return R; }; - /*\ + /* \ * Raphael.st [ property (object) ] ** @@ -5784,14 +5840,14 @@ // Firefox <3.6 fix: http://webreflection.blogspot.com/2009/11/195-chars-to-help-lazy-loading.html (function (doc, loaded, f) { - if (doc.readyState == null && doc.addEventListener){ + if (doc.readyState == null && doc.addEventListener) { doc.addEventListener(loaded, f = function () { doc.removeEventListener(loaded, f, false); doc.readyState = "complete"; }, false); doc.readyState = "loading"; } - function isLoaded() { + function isLoaded () { (/in/).test(doc.readyState) ? setTimeout(isLoaded, 9) : R.eve("raphael.DOMload"); } isLoaded(); @@ -5812,7 +5868,7 @@ (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.svg", ["raphael.core"], function(raphael) { + define("raphael.svg", ["raphael.core"], function (raphael) { return factory(raphael); }); } else if (typeof exports === "object") { @@ -5820,7 +5876,7 @@ } else { factory(glob.Raphael); } -}(this, function(R) { +}(this, function (R) { if (R && !R.svg) { return; } @@ -5851,14 +5907,16 @@ }; var $ = function (el, attr) { if (attr) { - if (typeof el == "string") { + if (typeof el === "string") { el = $(el); } - for (var key in attr) if (attr[has](key)) { - if (key.substring(0, 6) == "xlink:") { - el.setAttributeNS(xlink, key.substring(6), Str(attr[key])); - } else { - el.setAttribute(key, Str(attr[key])); + for (var key in attr) { + if (attr[has](key)) { + if (key.substring(0, 6) == "xlink:") { + el.setAttributeNS(xlink, key.substring(6), Str(attr[key])); + } else { + el.setAttribute(key, Str(attr[key])); + } } } } else { @@ -6090,9 +6148,11 @@ delete o._.arrows[se + "Type"]; delete o._.arrows[se + "String"]; } - for (attr in markerCounter) if (markerCounter[has](attr) && !markerCounter[attr]) { - var item = R._g.doc.getElementById(attr); - item && item.parentNode.removeChild(item); + for (attr in markerCounter) { + if (markerCounter[has](attr) && !markerCounter[attr]) { + var item = R._g.doc.getElementById(attr); + item && item.parentNode.removeChild(item); + } } } }, @@ -6119,8 +6179,7 @@ dashes[i] = value[i] * width + ((i % 2) ? 1 : -1) * butt; } $(o.node, {"stroke-dasharray": dashes.join(",")}); - } - else { + } else { $(o.node, {"stroke-dasharray": "none"}); } }, @@ -6406,10 +6465,12 @@ } } else { tspans = node.getElementsByTagName("tspan"); - for (i = 0, ii = tspans.length; i < ii; i++) if (i) { - $(tspans[i], {dy: fontSize * leading, x: a.x}); - } else { - $(tspans[0], {dy: 0}); + for (i = 0, ii = tspans.length; i < ii; i++) { + if (i) { + $(tspans[i], {dy: fontSize * leading, x: a.x}); + } else { + $(tspans[0], {dy: 0}); + } } } $(node, {x: a.x, y: a.y}); @@ -6421,14 +6482,14 @@ getRealNode = function (node) { if (node.parentNode && node.parentNode.tagName.toLowerCase() === "a") { return node.parentNode; - } else { - return node; } + return node; + }, Element = function (node, svg) { var X = 0, Y = 0; - /*\ + /* \ * Element.node [ property (object) ] ** @@ -6443,7 +6504,7 @@ | }; \*/ this[0] = this.node = node; - /*\ + /* \ * Element.raphael [ property (object) ] ** @@ -6456,7 +6517,7 @@ | } \*/ node.raphael = true; - /*\ + /* \ * Element.id [ property (number) ] ** @@ -6467,7 +6528,7 @@ node.raphaelid = this.id; this.matrix = R.matrix(); this.realPath = null; - /*\ + /* \ * Element.paper [ property (object) ] ** @@ -6491,7 +6552,7 @@ dirty: 1 }; !svg.bottom && (svg.bottom = this); - /*\ + /* \ * Element.prev [ property (object) ] ** @@ -6500,7 +6561,7 @@ this.prev = svg.top; svg.top && (svg.top.next = this); svg.top = this; - /*\ + /* \ * Element.next [ property (object) ] ** @@ -6525,7 +6586,7 @@ }); return p; }; - /*\ + /* \ * Element.rotate [ method ] ** @@ -6558,7 +6619,7 @@ this.transform(this._.transform.concat([["r", deg, cx, cy]])); return this; }; - /*\ + /* \ * Element.scale [ method ] ** @@ -6594,7 +6655,7 @@ this.transform(this._.transform.concat([["s", sx, sy, cx, cy]])); return this; }; - /*\ + /* \ * Element.translate [ method ] ** @@ -6618,7 +6679,7 @@ this.transform(this._.transform.concat([["t", dx, dy]])); return this; }; - /*\ + /* \ * Element.transform [ method ] ** @@ -6673,7 +6734,7 @@ return this; }; - /*\ + /* \ * Element.hide [ method ] ** @@ -6684,7 +6745,7 @@ if(!this.removed) this.node.style.display = "none"; return this; }; - /*\ + /* \ * Element.show [ method ] ** @@ -6695,7 +6756,7 @@ if(!this.removed) this.node.style.display = ""; return this; }; - /*\ + /* \ * Element.remove [ method ] ** @@ -6720,7 +6781,7 @@ this.removeData(); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } this.removed = true; }; @@ -6733,7 +6794,7 @@ containerStyle; if (this.paper.canvas.parentElement) { containerStyle = this.paper.canvas.parentElement.style; - } //IE10+ can't find parentElement + } // IE10+ can't find parentElement else if (this.paper.canvas.parentNode) { containerStyle = this.paper.canvas.parentNode.style; } @@ -6752,17 +6813,17 @@ y: this.node.clientTop, width: this.node.clientWidth, height: this.node.clientHeight - } + }; } finally { bbox = bbox || {}; - if(canvasHidden){ + if(canvasHidden) { containerStyle.display = "none"; } } hide && this.hide(); return bbox; }; - /*\ + /* \ * Element.attr [ method ] ** @@ -6849,8 +6910,10 @@ } if (name == null) { var res = {}; - for (var a in this.attrs) if (this.attrs[has](a)) { - res[a] = this.attrs[a]; + for (var a in this.attrs) { + if (this.attrs[has](a)) { + res[a] = this.attrs[a]; + } } res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient; res.transform = this._.transform; @@ -6893,17 +6956,21 @@ for (var key in params) { eve("raphael.attr." + key + "." + this.id, this, params[key]); } - for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { - var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); - this.attrs[key] = params[key]; - for (var subkey in par) if (par[has](subkey)) { - params[subkey] = par[subkey]; + for (key in this.paper.customAttributes) { + if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { + var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); + this.attrs[key] = params[key]; + for (var subkey in par) { + if (par[has](subkey)) { + params[subkey] = par[subkey]; + } + } } } setFillAndStroke(this, params); return this; }; - /*\ + /* \ * Element.toFront [ method ] ** @@ -6920,7 +6987,7 @@ svg.top != this && R._tofront(this, svg); return this; }; - /*\ + /* \ * Element.toBack [ method ] ** @@ -6938,7 +7005,7 @@ var svg = this.paper; return this; }; - /*\ + /* \ * Element.insertAfter [ method ] ** @@ -6960,7 +7027,7 @@ R._insertafter(this, element, this.paper); return this; }; - /*\ + /* \ * Element.insertBefore [ method ] ** @@ -7144,7 +7211,7 @@ this._viewBox = [x, y, w, h, !!fit]; return this; }; - /*\ + /* \ * Paper.renderfix [ method ] ** @@ -7176,7 +7243,7 @@ } } }; - /*\ + /* \ * Paper.clear [ method ] ** @@ -7193,7 +7260,7 @@ c.appendChild(this.desc); c.appendChild(this.defs = $("defs")); }; - /*\ + /* \ * Paper.remove [ method ] ** @@ -7203,19 +7270,21 @@ eve("raphael.remove", this); this.canvas.parentNode && this.canvas.parentNode.removeChild(this.canvas); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } }; var setproto = R.st; - for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname].apply(el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method) && !setproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname].apply(el, arg); + }); + }; + })(method); + } } })); @@ -7231,7 +7300,7 @@ (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael.vml", ["raphael.core"], function(raphael) { + define("raphael.vml", ["raphael.core"], function (raphael) { return factory(raphael); }); } else if (typeof exports === "object") { @@ -7239,7 +7308,7 @@ } else { factory(glob.Raphael); } -}(this, function(R) { +}(this, function (R) { if (R && !R.vml) { return; } @@ -7392,8 +7461,10 @@ res = o; - for (var par in params) if (params[has](par)) { - a[par] = params[par]; + for (var par in params) { + if (params[has](par)) { + a[par] = params[par]; + } } if (newpath) { a.path = R._getPath[o.type](o); @@ -7448,7 +7519,7 @@ if (o.textpath) { var textpathStyle = o.textpath.style; params.font && (textpathStyle.font = params.font); - params["font-family"] && (textpathStyle.fontFamily = '"' + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + '"'); + params["font-family"] && (textpathStyle.fontFamily = "\"" + params["font-family"].split(",")[0].replace(/^['"]+|['"]+$/g, E) + "\""); params["font-size"] && (textpathStyle.fontSize = params["font-size"]); params["font-weight"] && (textpathStyle.fontWeight = params["font-weight"]); params["font-style"] && (textpathStyle.fontStyle = params["font-style"]); @@ -7581,9 +7652,11 @@ ("x" in params || "y" in params) && (res.path.v = R.format("m{0},{1}l{2},{1}", round(a.x * zoom), round(a.y * zoom), round(a.x * zoom) + 1)); var dirtyattrs = ["x", "y", "text", "font", "font-family", "font-weight", "font-style", "font-size"]; - for (var d = 0, dd = dirtyattrs.length; d < dd; d++) if (dirtyattrs[d] in params) { - res._.dirty = 1; - break; + for (var d = 0, dd = dirtyattrs.length; d < dd; d++) { + if (dirtyattrs[d] in params) { + res._.dirty = 1; + break; + } } // text-anchor emulation @@ -7813,12 +7886,11 @@ }; // Needed to fix the vml setViewBox issues elproto.auxGetBBox = R.el.getBBox; - elproto.getBBox = function(){ + elproto.getBBox = function () { var b = this.auxGetBBox(); - if (this.paper && this.paper._viewBoxShift) - { + if (this.paper && this.paper._viewBoxShift) { var c = {}; - var z = 1/this.paper._viewBoxShift.scale; + var z = 1 / this.paper._viewBoxShift.scale; c.x = b.x - this.paper._viewBoxShift.dx; c.x *= z; c.y = b.y - this.paper._viewBoxShift.dy; @@ -7852,7 +7924,7 @@ this.node.parentNode.removeChild(this.node); this.shape && this.shape.parentNode.removeChild(this.shape); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } this.removed = true; }; @@ -7862,8 +7934,10 @@ } if (name == null) { var res = {}; - for (var a in this.attrs) if (this.attrs[has](a)) { - res[a] = this.attrs[a]; + for (var a in this.attrs) { + if (this.attrs[has](a)) { + res[a] = this.attrs[a]; + } } res.gradient && res.fill == "none" && (res.fill = res.gradient) && delete res.gradient; res.transform = this._.transform; @@ -7904,11 +7978,15 @@ eve("raphael.attr." + key + "." + this.id, this, params[key]); } if (params) { - for (key in this.paper.customAttributes) if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { - var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); - this.attrs[key] = params[key]; - for (var subkey in par) if (par[has](subkey)) { - params[subkey] = par[subkey]; + for (key in this.paper.customAttributes) { + if (this.paper.customAttributes[has](key) && params[has](key) && R.is(this.paper.customAttributes[key], "function")) { + var par = this.paper.customAttributes[key].apply(this, [].concat(params[key])); + this.attrs[key] = params[key]; + for (var subkey in par) { + if (par[has](subkey)) { + params[subkey] = par[subkey]; + } + } } } // this.paper.canvas.style.display = "none"; @@ -8158,11 +8236,11 @@ try { !doc.namespaces.rvml && doc.namespaces.add("rvml", "urn:schemas-microsoft-com:vml"); createNode = function (tagName) { - return doc.createElement(''); + return doc.createElement(""); }; } catch (e) { createNode = function (tagName) { - return doc.createElement('<' + tagName + ' xmlns="urn:schemas-microsoft.com:vml" class="rvml">'); + return doc.createElement("<" + tagName + " xmlns=\"urn:schemas-microsoft.com:vml\" class=\"rvml\">"); }; } }; @@ -8222,21 +8300,23 @@ R.eve("raphael.remove", this); this.canvas.parentNode.removeChild(this.canvas); for (var i in this) { - this[i] = typeof this[i] == "function" ? R._removedFactory(i) : null; + this[i] = typeof this[i] === "function" ? R._removedFactory(i) : null; } return true; }; var setproto = R.st; - for (var method in elproto) if (elproto[has](method) && !setproto[has](method)) { - setproto[method] = (function (methodname) { - return function () { - var arg = arguments; - return this.forEach(function (el) { - el[methodname].apply(el, arg); - }); - }; - })(method); + for (var method in elproto) { + if (elproto[has](method) && !setproto[has](method)) { + setproto[method] = (function (methodname) { + return function () { + var arg = arguments; + return this.forEach(function (el) { + el[methodname].apply(el, arg); + }); + }; + })(method); + } } })); @@ -8251,7 +8331,7 @@ (function (glob, factory) { if (typeof define === "function" && define.amd) { - define("raphael", ["raphael.core", "raphael.svg", "raphael.vml"], function(Raphael) { + define("raphael", ["raphael.core", "raphael.svg", "raphael.vml"], function (Raphael) { return factory(Raphael); }); } else if (typeof exports === "object") { @@ -8262,7 +8342,7 @@ module.exports = factory(raphael); } else { - //glob.Raphael = factory(glob.Raphael); + // glob.Raphael = factory(glob.Raphael); } }(this, function (Raphael) { return Raphael.ninja(); diff --git a/src/base/svg/svg.js b/src/base/svg/svg.js index dd5a1fee2..24ec65861 100644 --- a/src/base/svg/svg.js +++ b/src/base/svg/svg.js @@ -10,7 +10,7 @@ BI.Svg = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Svg.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-svg" - }) + }); }, _init: function () { @@ -18,7 +18,7 @@ BI.Svg = BI.inherit(BI.Widget, { this.paper = Raphael(this.element[0]); this.element.css("overflow", "hidden"); - $(this.paper.canvas).width("100%").height("100%").css({"left": "0", "top": "0"}).appendTo(this.element); + $(this.paper.canvas).width("100%").height("100%").css({left: "0", top: "0"}).appendTo(this.element); this.top = this.paper.top; this.bottom = this.paper.bottom; diff --git a/src/base/table/native.scrollbar.js b/src/base/table/native.scrollbar.js index ac629be71..e535ace65 100644 --- a/src/base/table/native.scrollbar.js +++ b/src/base/table/native.scrollbar.js @@ -16,12 +16,12 @@ BI.NativeTableScrollbar = BI.inherit(BI.Widget, { defaultPosition: 0, position: 0, size: 0 - }) + }); }, render: function () { var self = this, o = this.options; - //把滚动台size改掉 + // 把滚动台size改掉 this.element.width(36); var throttle = BI.throttle(function () { @@ -40,7 +40,7 @@ BI.NativeTableScrollbar = BI.inherit(BI.Widget, { self.inner = _ref; } }] - } + }; }, mounted: function () { @@ -92,12 +92,12 @@ BI.NativeTableHorizontalScrollbar = BI.inherit(BI.Widget, { contentSize: 0, position: 0, size: 0 - }) + }); }, render: function () { var self = this, o = this.options; - //把滚动台size改掉 + // 把滚动台size改掉 this.element.height(36); var throttle = BI.throttle(function () { @@ -116,7 +116,7 @@ BI.NativeTableHorizontalScrollbar = BI.inherit(BI.Widget, { self.inner = _ref; } }] - } + }; }, setContentSize: function (contentSize) { diff --git a/src/base/table/table.cell.js b/src/base/table/table.cell.js index fa2ac3564..919385cc4 100644 --- a/src/base/table/table.cell.js +++ b/src/base/table/table.cell.js @@ -12,7 +12,7 @@ BI.TableCell = BI.inherit(BI.Widget, { baseCls: "bi-table-cell", textAlign: "left", text: "" - }) + }); }, _init: function () { @@ -26,7 +26,7 @@ BI.TableCell = BI.inherit(BI.Widget, { text: this.options.text, value: this.options.value, lgap: 5 - }) + }); } }); diff --git a/src/base/table/table.collection.cell.js b/src/base/table/table.collection.cell.js index 5c5105399..a9786e1e2 100644 --- a/src/base/table/table.collection.cell.js +++ b/src/base/table/table.collection.cell.js @@ -15,7 +15,7 @@ BI.CollectionTableCell = BI.inherit(BI.Widget, { _left: 0, _top: 0, cell: {} - }) + }); }, _init: function () { diff --git a/src/base/table/table.collection.js b/src/base/table/table.collection.js index 81d742dc6..098777692 100644 --- a/src/base/table/table.collection.js +++ b/src/base/table/table.collection.js @@ -272,7 +272,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { overflow: "scroll", overflowX: "scroll", overflowY: "scroll" - }) + }); }; this.topLeft.setWidth(otlw); @@ -330,7 +330,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { _digest: function () { var o = this.options; var freezeColLength = this._getFreezeColLength(); - //如果表头位置不够,取消表头冻结 + // 如果表头位置不够,取消表头冻结 if (this._getFreezeHeaderHeight() <= 0) { this.topLeftItems = []; this.topRightItems = []; @@ -420,7 +420,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { var isNeedMergeCol = o.mergeRule(cache[i][j], cache[i][j - 1]); if (isNeedMergeCol && isNeedMergeRow) { continue; - //mergeRow(i, j);//优先合并列 + // mergeRow(i, j);//优先合并列 } if (isNeedMergeCol) { mergeCol(i, j); @@ -445,7 +445,7 @@ BI.CollectionTable = BI.inherit(BI.Widget, { col: item.item._col, width: item.item._width, height: item.item._height - } + }; }); }, @@ -555,4 +555,4 @@ BI.CollectionTable = BI.inherit(BI.Widget, { this._restore(); } }); -BI.shortcut('bi.collection_table', BI.CollectionTable); \ No newline at end of file +BI.shortcut("bi.collection_table", BI.CollectionTable); \ No newline at end of file diff --git a/src/base/table/table.collection.quick.js b/src/base/table/table.collection.quick.js index ad8c014bd..43ac408ad 100644 --- a/src/base/table/table.collection.quick.js +++ b/src/base/table/table.collection.quick.js @@ -65,25 +65,25 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { _shouldHandleLeftX: function (delta) { if (delta > 0) { return this.bottomLeftCollection.getScrollLeft() < this.bottomLeftCollection.getMaxScrollLeft(); - } else { - return this.bottomLeftCollection.getScrollLeft() > 0; } + return this.bottomLeftCollection.getScrollLeft() > 0; + }, _shouldHandleRightX: function (delta) { if (delta > 0) { return this.bottomRightCollection.getScrollLeft() < this.bottomRightCollection.getMaxScrollLeft(); - } else { - return this.bottomRightCollection.getScrollLeft() > 0; } + return this.bottomRightCollection.getScrollLeft() > 0; + }, _shouldHandleY: function (delta) { if (delta > 0) { return this.bottomRightCollection.getScrollTop() < this.bottomRightCollection.getMaxScrollTop(); - } else { - return this.bottomRightCollection.getScrollTop() > 0; } + return this.bottomRightCollection.getScrollTop() > 0; + }, _onWheelLeft: function (deltaX, deltaY) { @@ -117,7 +117,7 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { _populateTable: function () { var self = this, o = this.options; var regionSize = this.getRegionSize(), totalLeftColumnSize = 0, totalRightColumnSize = 0, totalColumnSize = 0, - summaryColumnSizeArray = [] + summaryColumnSizeArray = []; BI.each(o.columnSize, function (i, size) { if (o.isNeedFreeze === true && o.freezeCols.contains(i)) { totalLeftColumnSize += size; @@ -188,4 +188,4 @@ BI.QuickCollectionTable = BI.inherit(BI.CollectionTable, { this.bottomRightCollection.populate(rightItems); } }); -BI.shortcut('bi.quick_collection_table', BI.QuickCollectionTable); \ No newline at end of file +BI.shortcut("bi.quick_collection_table", BI.QuickCollectionTable); \ No newline at end of file diff --git a/src/base/table/table.grid.cell.js b/src/base/table/table.grid.cell.js index eaccd5a2b..030d955a1 100644 --- a/src/base/table/table.grid.cell.js +++ b/src/base/table/table.grid.cell.js @@ -17,7 +17,7 @@ BI.GridTableCell = BI.inherit(BI.Widget, { _left: 0, _top: 0, cell: {} - }) + }); }, _init: function () { diff --git a/src/base/table/table.grid.js b/src/base/table/table.grid.js index c4444c1d6..a9e40bcf3 100644 --- a/src/base/table/table.grid.js +++ b/src/base/table/table.grid.js @@ -320,7 +320,7 @@ BI.GridTable = BI.inherit(BI.Widget, { overflow: "scroll", overflowX: "scroll", overflowY: "scroll" - }) + }); }; this.topLeft.setWidth(otlw); @@ -476,4 +476,4 @@ BI.GridTable = BI.inherit(BI.Widget, { this._restore(); } }); -BI.shortcut('bi.grid_table', BI.GridTable); \ No newline at end of file +BI.shortcut("bi.grid_table", BI.GridTable); \ No newline at end of file diff --git a/src/base/table/table.grid.quick.js b/src/base/table/table.grid.quick.js index daa1243fc..2206799e6 100644 --- a/src/base/table/table.grid.quick.js +++ b/src/base/table/table.grid.quick.js @@ -65,25 +65,25 @@ BI.QuickGridTable = BI.inherit(BI.GridTable, { _shouldHandleLeftX: function (delta) { if (delta > 0) { return this.bottomLeftGrid.getScrollLeft() < this.bottomLeftGrid.getMaxScrollLeft(); - } else { - return this.bottomLeftGrid.getScrollLeft() > 0; } + return this.bottomLeftGrid.getScrollLeft() > 0; + }, _shouldHandleRightX: function (delta) { if (delta > 0) { return this.bottomRightGrid.getScrollLeft() < this.bottomRightGrid.getMaxScrollLeft(); - } else { - return this.bottomRightGrid.getScrollLeft() > 0; } + return this.bottomRightGrid.getScrollLeft() > 0; + }, _shouldHandleY: function (delta) { if (delta > 0) { return this.bottomRightGrid.getScrollTop() < this.bottomRightGrid.getMaxScrollTop(); - } else { - return this.bottomRightGrid.getScrollTop() > 0; } + return this.bottomRightGrid.getScrollTop() > 0; + }, _onWheelLeft: function (deltaX, deltaY) { @@ -220,4 +220,4 @@ BI.QuickGridTable = BI.inherit(BI.GridTable, { this.bottomRightGrid.populate(rightItems); } }); -BI.shortcut('bi.quick_grid_table', BI.QuickGridTable); \ No newline at end of file +BI.shortcut("bi.quick_grid_table", BI.QuickGridTable); \ No newline at end of file diff --git a/src/base/table/table.grid.scrollbar.js b/src/base/table/table.grid.scrollbar.js index 7f1bcb384..cb5affb40 100644 --- a/src/base/table/table.grid.scrollbar.js +++ b/src/base/table/table.grid.scrollbar.js @@ -25,7 +25,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { orientation: "vertical", position: 0, size: 0 - }) + }); }, render: function () { @@ -50,7 +50,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { mounted: function () { var self = this, o = this.options; - var onWheel = o.orientation === 'horizontal' ? this._onWheelX : this._onWheelY; + var onWheel = o.orientation === "horizontal" ? this._onWheelX : this._onWheelY; this._wheelHandler = new BI.WheelHandler( BI.bind(onWheel, this), BI.bind(this._shouldHandleX, this), @@ -83,7 +83,7 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { }, _isHorizontal: function () { - return this.options.orientation === 'horizontal' + return this.options.orientation === "horizontal"; }, _getScale: function () { @@ -109,13 +109,13 @@ BI.GridTableScrollbar = BI.inherit(BI.Widget, { }, _shouldHandleX: function (delta) { - return this.options.orientation === 'horizontal' ? + return this.options.orientation === "horizontal" ? this._shouldHandleChange(delta) : false; }, _shouldHandleY: function (delta) { - return this.options.orientation !== 'horizontal' ? + return this.options.orientation !== "horizontal" ? this._shouldHandleChange(delta) : false; }, @@ -349,7 +349,7 @@ BI.GridTableHorizontalScrollbar = BI.inherit(BI.Widget, { contentSize: 0, position: 0, size: 0 - }) + }); }, _init: function () { diff --git a/src/base/table/table.header.cell.js b/src/base/table/table.header.cell.js index 559055567..c6dfe9081 100644 --- a/src/base/table/table.header.cell.js +++ b/src/base/table/table.header.cell.js @@ -11,7 +11,7 @@ BI.TableHeaderCell = BI.inherit(BI.Widget, { return BI.extend(BI.TableHeaderCell.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-table-header-cell", text: "" - }) + }); }, _init: function () { @@ -23,7 +23,7 @@ BI.TableHeaderCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); diff --git a/src/base/table/table.js b/src/base/table/table.js index f5347beaa..b516457a9 100644 --- a/src/base/table/table.js +++ b/src/base/table/table.js @@ -13,16 +13,16 @@ BI.Table = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.Table.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-table", - logic: { //冻结的页面布局逻辑 + logic: { // 冻结的页面布局逻辑 dynamic: false }, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 - mergeRule: function (row1, row2) { //合并规则, 默认相等时合并 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 + mergeRule: function (row1, row2) { // 合并规则, 默认相等时合并 return BI.isEqual(row1, row2); }, @@ -35,8 +35,8 @@ BI.Table = BI.inherit(BI.Widget, { header: [], footer: false, - items: [] //二维数组 - }) + items: [] // 二维数组 + }); }, _calculateWidth: function (width) { @@ -326,17 +326,17 @@ BI.Table = BI.inherit(BI.Widget, { var regionColumnSize = o.regionColumnSize; if (o.freezeCols.length === 0) { - regionColumnSize = isRight ? ['fill', 0] : [0, 'fill']; + regionColumnSize = isRight ? ["fill", 0] : [0, "fill"]; } else if (o.freezeCols.length >= o.columnSize.length) { - regionColumnSize = isRight ? [0, 'fill'] : ['fill', 0]; + regionColumnSize = isRight ? [0, "fill"] : ["fill", 0]; } this.partitions = BI.createWidget(BI.extend({ element: this }, BI.LogicFactory.createLogic("table", BI.extend({}, o.logic, { rows: 2, columns: 2, - columnSize: regionColumnSize || (isRight ? ['fill', leftWidth] : [leftWidth, 'fill']), - rowSize: [headerHeight, 'fill'], + columnSize: regionColumnSize || (isRight ? ["fill", leftWidth] : [leftWidth, "fill"]), + rowSize: [headerHeight, "fill"], items: [[{ el: this.topLeft }, { @@ -365,7 +365,7 @@ BI.Table = BI.inherit(BI.Widget, { scroll(this.scrollBottomRight.element, this.scrollTopRight.element, this.scrollBottomLeft.element); // scroll(this.scrollBottomLeft.element, this.scrollTopLeft.element, this.scrollBottomRight.element); - function scroll(scrollElement, scrollTopElement, otherElement) { + function scroll (scrollElement, scrollTopElement, otherElement) { scrollElement.scroll(function (e) { otherElement.scrollTop(scrollElement.scrollTop()); scrollTopElement.scrollLeft(scrollElement.scrollLeft()); @@ -442,10 +442,10 @@ BI.Table = BI.inherit(BI.Widget, { createOneEl(i, j); } }); - function mergeRow(i, j) { + function mergeRow (i, j) { var height = (preCol[j].attr("height") | 0) + rowSize + 1; preCol[j].attr("height", height).css("height", height); - //preCW[j].element.css("height", height); + // preCW[j].element.css("height", height); var rowspan = ((preCol[j].attr("rowspan") || 1) | 0) + 1; preCol[j].attr("rowspan", rowspan); preCol[j].__mergeRows.pushDistinct(i); @@ -453,7 +453,7 @@ BI.Table = BI.inherit(BI.Widget, { Ws[i][j] = preCW[j]; } - function mergeCol(i, j) { + function mergeCol (i, j) { if (columnSize[j]) { var width = preRow[i].attr("width") | 0; if (width > 1.05 && columnSize[j]) { @@ -462,7 +462,7 @@ BI.Table = BI.inherit(BI.Widget, { width--; } } else { - width = width + columnSize[j] + width = width + columnSize[j]; } width = self._calculateWidth(width); preRow[i].attr("width", width).css("width", width); @@ -475,14 +475,14 @@ BI.Table = BI.inherit(BI.Widget, { Ws[i][j] = preRW[i]; } - function createOneEl(r, c) { + function createOneEl (r, c) { var width = self._calculateWidth(columnSize[c]); if (width > 1.05 && c === columnSize.length - 1) { width--; } var height = self._calculateHeight(rowSize); var td = $("").attr("height", height) - .attr("width", width).css({"width": width, "height": height, "position": "relative"}) + .attr("width", width).css({width: width, height: height, position: "relative"}) .addClass((c & 1) === 0 ? "odd-col" : "even-col") .addClass(r === 0 ? "first-row" : "") .addClass(c === 0 ? "first-col" : "") @@ -653,12 +653,12 @@ BI.Table = BI.inherit(BI.Widget, { } else { (isRight ? left : right)[i].push(cell); } - }) + }); }); return { left: left, right: right - } + }; }, _table: function () { @@ -666,7 +666,7 @@ BI.Table = BI.inherit(BI.Widget, { type: "bi.layout", tagName: "table", cls: "table", - attribute: {"cellspacing": 0, "cellpadding": 0} + attribute: {cellspacing: 0, cellpadding: 0} }); }, @@ -820,7 +820,7 @@ BI.Table = BI.inherit(BI.Widget, { } }); } - }) + }); }; run(topleft); run(topright); @@ -1080,21 +1080,21 @@ BI.Table = BI.inherit(BI.Widget, { if (o.isNeedFreeze === true) { if (BI.size(this.bottomLeftBodyTds) > 0 || BI.size(this.bottomRightBodyTds) > 0) { if (!BI.any(this.bottomLeftBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.bottomLeftBodyTds[0], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.bottomLeftBodyTds[0]) - 1) { @@ -1104,21 +1104,21 @@ BI.Table = BI.inherit(BI.Widget, { }); } if (!BI.any(this.bottomRightBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.bottomRightBodyTds[0], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.bottomRightBodyTds[0]) - 1) { @@ -1130,21 +1130,21 @@ BI.Table = BI.inherit(BI.Widget, { return columnSize; } if (!BI.any(this.topLeftBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.topLeftBodyTds[BI.size(this.topLeftBodyTds) - 1], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.topLeftBodyTds[BI.size(self.topLeftBodyTds) - 1]) - 1) { @@ -1154,21 +1154,21 @@ BI.Table = BI.inherit(BI.Widget, { }); } if (!BI.any(this.topRightBodyTds, function (i, tds) { - if (!BI.any(tds, function (i, item) { - if (item.__mergeCols.length > 1) { - return true; - } - })) { - BI.each(tds, function (i, item) { - var width = item.width() / item.__mergeCols.length; - if (i == BI.size(tds) - 1) { - width++; - } - columnSize.push(width); - }); + if (!BI.any(tds, function (i, item) { + if (item.__mergeCols.length > 1) { return true; } })) { + BI.each(tds, function (i, item) { + var width = item.width() / item.__mergeCols.length; + if (i == BI.size(tds) - 1) { + width++; + } + columnSize.push(width); + }); + return true; + } + })) { BI.each(this.topRightBodyTds[BI.size(this.topRightBodyTds) - 1], function (i, item) { var width = item.width() / item.__mergeCols.length; if (i == BI.size(self.topRightBodyTds[BI.size(self.topRightBodyTds) - 1]) - 1) { @@ -1291,7 +1291,7 @@ BI.Table = BI.inherit(BI.Widget, { } }); } - }) + }); }; run(topleft); run(topright); @@ -1404,7 +1404,7 @@ BI.Table = BI.inherit(BI.Widget, { o.regionColumnSize = columnSize; if (o.freezeCols.length === 0) { if (o.isNeedFreeze) { - this.partitions.attr("columnSize", this._isRightFreeze() ? ['fill', 0] : [0, 'fill']); + this.partitions.attr("columnSize", this._isRightFreeze() ? ["fill", 0] : [0, "fill"]); this.partitions.resize(); } else { this.tableContainer.element.width(columnSize[0]); @@ -1418,7 +1418,7 @@ BI.Table = BI.inherit(BI.Widget, { } } else { if (o.isNeedFreeze) { - this.partitions.attr("columnSize", this._isRightFreeze() ? [0, 'fill'] : ['fill', 0]); + this.partitions.attr("columnSize", this._isRightFreeze() ? [0, "fill"] : ["fill", 0]); this.partitions.resize(); } else { this.tableContainer.element.width(columnSize[0]); @@ -1475,9 +1475,9 @@ BI.Table = BI.inherit(BI.Widget, { if (o.isNeedFreeze) { if (o.freezeCols.length < o.columnSize.length) { return [this.scrollTopRight.element[0].scrollHeight, this.scrollBottomRight.element[0].scrollHeight]; - } else { - return [this.scrollTopLeft.element[0].scrollHeight, this.scrollBottomLeft.element[0].scrollHeight]; } + return [this.scrollTopLeft.element[0].scrollHeight, this.scrollBottomLeft.element[0].scrollHeight]; + } return [this.scrollBottomRight.element[0].scrollHeight]; }, @@ -1570,14 +1570,14 @@ BI.Table = BI.inherit(BI.Widget, { topRight: this.topRightBodyItems, bottomLeft: this.bottomLeftBodyItems, bottomRight: this.bottomRightBodyItems - } - } else { - return { - header: this.headerItems, - body: this.bodyItems, - footer: this.footerItems - } + }; } + return { + header: this.headerItems, + body: this.bodyItems, + footer: this.footerItems + }; + }, populate: function (items, header) { diff --git a/src/base/table/table.resizable.cell.js b/src/base/table/table.resizable.cell.js index 434b3e276..22f08137a 100644 --- a/src/base/table/table.resizable.cell.js +++ b/src/base/table/table.resizable.cell.js @@ -17,7 +17,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { start: BI.emptyFn, resize: BI.emptyFn, stop: BI.emptyFn - }) + }); }, _init: function () { @@ -28,7 +28,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { var startDrag = false; var size = 0, offset = 0, defaultSize = o.width; - function optimizeSize(s) { + function optimizeSize (s) { var optSize = BI.clamp(s, o.minSize, o.maxSize || Number.MAX_VALUE); // if (o.suitableSize) { // if (Math.abs(o.suitableSize - optSize) < 5) { @@ -97,7 +97,7 @@ BI.ResizableTableCell = BI.inherit(BI.Widget, { top: 0, bottom: 0 }] - }) + }); }, setWidth: function (width) { diff --git a/src/base/table/table.resizable.js b/src/base/table/table.resizable.js index 4cf32a668..f97010209 100644 --- a/src/base/table/table.resizable.js +++ b/src/base/table/table.resizable.js @@ -18,7 +18,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { isResizeAdapt: false, headerRowSize: 25, rowSize: 25, - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, columnSize: [], @@ -28,7 +28,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { header: [], items: [], regionColumnSize: [] - }) + }); }, _init: function () { @@ -217,7 +217,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { self.resizer.setVisible(true); var height = o.headerRowSize + self._getRegionRowSize()[1]; self.resizer.setHeight(height); - //TODO 不知道为什么加入这段代码会使得列宽调整出问题 + // TODO 不知道为什么加入这段代码会使得列宽调整出问题 // if (o.minColumnSize[j]) { // if (size === o.minColumnSize[j]) { // self.resizer.element.addClass("suitable"); @@ -288,7 +288,7 @@ BI.ResizableTable = BI.inherit(BI.Widget, { setWidth: function (width) { BI.ResizableTable.superclass.setWidth.apply(this, arguments); - this.table.setWidth(width) + this.table.setWidth(width); }, setHeight: function (height) { diff --git a/src/base/tree/customtree.js b/src/base/tree/customtree.js index 96a692fe0..4698b7d18 100644 --- a/src/base/tree/customtree.js +++ b/src/base/tree/customtree.js @@ -27,7 +27,7 @@ BI.CustomTree = BI.inherit(BI.Widget, { type: "bi.vertical" }] } - }) + }); }, _init: function () { @@ -62,7 +62,7 @@ BI.CustomTree = BI.inherit(BI.Widget, { item.popup.expander = BI.deepClone(o.expander); item.items = item.popup.items = node.children; item.itemsCreator = item.popup.itemsCreator = function (op) { - if (BI.isNotNull(op.node)) {//从子节点传过来的itemsCreator直接向上传递 + if (BI.isNotNull(op.node)) {// 从子节点传过来的itemsCreator直接向上传递 return o.itemsCreator.apply(self, arguments); } var args = Array.prototype.slice.call(arguments, 0); @@ -78,7 +78,7 @@ BI.CustomTree = BI.inherit(BI.Widget, { return items; }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.tree = BI.createWidget(o.el, { @@ -97,10 +97,10 @@ BI.CustomTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.CustomTree.EVENT_CHANGE, val, obj); } - }) + }); }, - //生成树方法 + // 生成树方法 stroke: function (nodes) { this.populate.apply(this, arguments); }, diff --git a/src/base/tree/parttree.js b/src/base/tree/parttree.js index adc7088dc..8718b5efa 100644 --- a/src/base/tree/parttree.js +++ b/src/base/tree/parttree.js @@ -6,7 +6,7 @@ */ BI.PartTree = BI.inherit(BI.AsyncTree, { _defaultConfig: function () { - return BI.extend(BI.PartTree.superclass._defaultConfig.apply(this, arguments), {}) + return BI.extend(BI.PartTree.superclass._defaultConfig.apply(this, arguments), {}); }, _init: function () { @@ -44,7 +44,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { if (treeNode.checked === true) { BI.AsyncTree.superclass._selectTreeNode.apply(self, arguments); } else { - //如果选中的值中不存在该值不处理 + // 如果选中的值中不存在该值不处理 var t = this.options.paras.selectedValues; var p = parentValues.concat(name); for (var i = 0, len = p.length; i < len; i++) { @@ -72,19 +72,19 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { var hashMap = {}; var rootNoots = this.nodes.getNodes(); track(rootNoots); - function track(nodes) { + function track (nodes) { BI.each(nodes, function (i, node) { var checkState = node.getCheckStatus(); if (checkState.checked === false) { return true; } var parentValues = node.parentValues || self._getParentValues(node); - //把文字中的html去掉,其实就是把文字颜色去掉 + // 把文字中的html去掉,其实就是把文字颜色去掉 var values = parentValues.concat([self._getNodeValue(node)]); self._buildTree(hashMap, values); -// if(checkState.checked === true && checkState.half === false && nodes[i].flag === true){ -// continue; -// } + // if(checkState.checked === true && checkState.half === false && nodes[i].flag === true){ + // continue; + // } if (BI.isNotEmptyArray(node.children)) { track(node.children); return true; @@ -92,7 +92,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { if (checkState.half === true) { self._getHalfSelectedValues(hashMap, node); } - }) + }); } return hashMap; @@ -128,7 +128,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { self.fireEvent(BI.Events.AFTERINIT); }; - function callback(nodes) { + function callback (nodes) { if (self._stop === true) { return; } @@ -152,7 +152,7 @@ BI.PartTree = BI.inherit(BI.AsyncTree, { return result; }, - //生成树方法 + // 生成树方法 stroke: function (config) { var o = this.options; delete o.paras.keyword; diff --git a/src/base/tree/treeview.js b/src/base/tree/treeview.js index 435436c53..ece8ef0bc 100644 --- a/src/base/tree/treeview.js +++ b/src/base/tree/treeview.js @@ -10,7 +10,7 @@ BI.TreeView = BI.inherit(BI.Pane, { baseCls: "bi-tree", paras: {}, itemsCreator: BI.emptyFn - }) + }); }, _init: function () { BI.TreeView.superclass._init.apply(this, arguments); @@ -51,13 +51,13 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //选择节点触发方法 + // 选择节点触发方法 _selectTreeNode: function (treeId, treeNode) { this.fireEvent(BI.Controller.EVENT_CHANGE, BI.Events.CLICK, treeNode, this); this.fireEvent(BI.TreeView.EVENT_CHANGE, treeNode, this); }, - //配置属性 + // 配置属性 _configSetting: function () { var paras = this.options.paras; var self = this; @@ -99,11 +99,11 @@ BI.TreeView = BI.inherit(BI.Pane, { }; var className = "dark", perTime = 100; - function onClick(event, treeId, treeNode) { + function onClick (event, treeId, treeNode) { self.nodes.checkNode(treeNode, !treeNode.checked, true, true); } - function getUrl(treeId, treeNode) { + function getUrl (treeId, treeNode) { var parentNode = self._getParentValues(treeNode); treeNode.times = treeNode.times || 1; var param = "id=" + treeNode.id @@ -111,23 +111,23 @@ BI.TreeView = BI.inherit(BI.Pane, { + "&parentValues= " + window.encodeURIComponent(BI.jsonEncode(parentNode)) + "&checkState=" + window.encodeURIComponent(BI.jsonEncode(treeNode.getCheckStatus())); - return BI.servletURL + '?op=' + self.options.op + '&cmd=' + self.options.cmd + "&" + param; + return BI.servletURL + "?op=" + self.options.op + "&cmd=" + self.options.cmd + "&" + param; } - function beforeExpand(treeId, treeNode) { + function beforeExpand (treeId, treeNode) { if (!treeNode.isAjaxing) { if (!treeNode.children) { treeNode.times = 1; ajaxGetNodes(treeNode, "refresh"); } return true; - } else { - BI.Msg.toast("Please Wait。", "warning"); - return false; } + BI.Msg.toast("Please Wait。", "warning"); + return false; + } - function onAsyncSuccess(event, treeId, treeNode, msg) { + function onAsyncSuccess (event, treeId, treeNode, msg) { treeNode.halfCheck = false; if (!msg || msg.length === 0 || /^[\s,\S]*<\/html>$/gi.test(msg) || self._stop) { return; @@ -135,7 +135,7 @@ BI.TreeView = BI.inherit(BI.Pane, { var zTree = self.nodes; var totalCount = treeNode.count || 0; - //尝试去获取下一组节点,若获取值为空数组,表示获取完成 + // 尝试去获取下一组节点,若获取值为空数组,表示获取完成 // TODO by GUY if (treeNode.children.length > totalCount) { treeNode.count = treeNode.children.length; @@ -143,41 +143,41 @@ BI.TreeView = BI.inherit(BI.Pane, { ajaxGetNodes(treeNode); }, perTime); } else { - //treeNode.icon = ""; + // treeNode.icon = ""; zTree.updateNode(treeNode); zTree.selectNode(treeNode.children[0]); - //className = (className === "dark" ? "":"dark"); + // className = (className === "dark" ? "":"dark"); } } - function onAsyncError(event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { + function onAsyncError (event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) { var zTree = self.nodes; BI.Msg.toast("Error!", "warning"); - //treeNode.icon = ""; - //zTree.updateNode(treeNode); + // treeNode.icon = ""; + // zTree.updateNode(treeNode); } - function ajaxGetNodes(treeNode, reloadType) { + function ajaxGetNodes (treeNode, reloadType) { var zTree = self.nodes; if (reloadType == "refresh") { - //treeNode.icon = BI.servletURL +"?op=resource&resource=/com/fr/bi/web/css/base/third/ztree/img/loading.gif"; + // treeNode.icon = BI.servletURL +"?op=resource&resource=/com/fr/bi/web/css/base/third/ztree/img/loading.gif"; zTree.updateNode(treeNode); } zTree.reAsyncChildNodes(treeNode, reloadType, true); } - function beforeCheck(treeId, treeNode) { + function beforeCheck (treeId, treeNode) { treeNode.halfCheck = false; if (treeNode.checked === true) { - //将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy - //所有的半选状态都需要取消halfCheck=true的情况 - function track(children) { + // 将展开的节点halfCheck设为false,解决展开节点存在halfCheck=true的情况 guy + // 所有的半选状态都需要取消halfCheck=true的情况 + function track (children) { BI.each(children, function (i, ch) { if (ch.halfCheck === true) { ch.halfCheck = false; track(ch.children); } - }) + }); } track(treeNode.children); @@ -185,19 +185,19 @@ BI.TreeView = BI.inherit(BI.Pane, { var nodes = treeObj.getSelectedNodes(); $.each(nodes, function (index, node) { node.halfCheck = false; - }) + }); } } - function onCheck(event, treeId, treeNode) { + function onCheck (event, treeId, treeNode) { self._selectTreeNode(treeId, treeNode); } - function onExpand(event, treeId, treeNode) { + function onExpand (event, treeId, treeNode) { treeNode.halfCheck = false; } - function onCollapse(event, treeId, treeNode) { + function onCollapse (event, treeId, treeNode) { } return setting; @@ -214,19 +214,19 @@ BI.TreeView = BI.inherit(BI.Pane, { }, _getNodeValue: function (node) { - //去除标红 + // 去除标红 return node.value == null ? node.text.replace(/<[^>]+>/g, "").replaceAll(" ", " ") : node.value; }, - //获取半选框值 + // 获取半选框值 _getHalfSelectedValues: function (map, node) { var self = this; var checkState = node.getCheckStatus(); - //将未选的去掉 + // 将未选的去掉 if (checkState.checked === false && checkState.half === false) { return; } - //如果节点已展开,并且是半选 + // 如果节点已展开,并且是半选 if (BI.isNotEmptyArray(node.children) && checkState.half === true) { var children = node.children; BI.each(children, function (i, ch) { @@ -267,7 +267,7 @@ BI.TreeView = BI.inherit(BI.Pane, { cur[key] = value; }, - //构造树节点 + // 构造树节点 _buildTree: function (map, values) { var cur = map; BI.each(values, function (i, value) { @@ -275,16 +275,16 @@ BI.TreeView = BI.inherit(BI.Pane, { cur[value] = {}; } cur = cur[value]; - }) + }); }, - //获取选中的值 + // 获取选中的值 _getSelectedValues: function () { var self = this; var hashMap = {}; var rootNoots = this.nodes.getNodes(); track(rootNoots); - function track(nodes) { + function track (nodes) { BI.each(nodes, function (i, node) { var checkState = node.getCheckStatus(); if (checkState.checked === true || checkState.half === true) { @@ -296,19 +296,19 @@ BI.TreeView = BI.inherit(BI.Pane, { self._buildTree(hashMap, values); } } - }) + }); } return hashMap; }, - //处理节点 + // 处理节点 _dealWidthNodes: function (nodes) { var self = this, o = this.options; var ns = BI.Tree.arrayFormat(nodes); BI.each(ns, function (i, n) { n.title = n.title || n.text || n.value; - //处理标红 + // 处理标红 if (BI.isKey(o.paras.keyword)) { n.text = $("
    ").__textKeywordMarked__(n.text, o.paras.keyword, n.py).html(); } else { @@ -341,7 +341,7 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //生成树内部方法 + // 生成树内部方法 _initTree: function (setting) { var self = this, o = this.options; self.fireEvent(BI.Events.INIT); @@ -379,31 +379,31 @@ BI.TreeView = BI.inherit(BI.Pane, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes, setting) { var setting = setting || { - async: { - enable: false - }, - check: { - enable: false - }, - data: { - key: { - title: "title", - name: "text" - }, - simpleData: { - enable: true - } - }, - view: { - showIcon: false, - expandSpeed: "", - nameIsHTML: true + async: { + enable: false + }, + check: { + enable: false + }, + data: { + key: { + title: "title", + name: "text" }, - callback: {} - }; + simpleData: { + enable: true + } + }, + view: { + showIcon: false, + expandSpeed: "", + nameIsHTML: true + }, + callback: {} + }; this.nodes = $.fn.zTree.init(this.tree.element, setting, nodes); }, @@ -415,7 +415,7 @@ BI.TreeView = BI.inherit(BI.Pane, { this._stop = true; }, - //生成树方法 + // 生成树方法 stroke: function (config) { delete this.options.keyword; BI.extend(this.options.paras, config); @@ -435,7 +435,7 @@ BI.TreeView = BI.inherit(BI.Pane, { }, checkAll: function (checked) { - function setNode(children) { + function setNode (children) { BI.each(children, function (i, child) { child.halfCheck = false; setNode(child.children); @@ -453,7 +453,7 @@ BI.TreeView = BI.inherit(BI.Pane, { this.nodes && this.nodes.expandAll(flag); }, - //设置树节点的状态 + // 设置树节点的状态 setValue: function (value, param) { this.checkAll(false); this.updateValue(value, param); @@ -475,7 +475,7 @@ BI.TreeView = BI.inherit(BI.Pane, { BI.each(nodes, function (j, node) { BI.extend(node, {checked: true}, op); treeObj.updateNode(node); - }) + }); }); }, diff --git a/src/base/tree/ztree/jquery.ztree.core-3.5.js b/src/base/tree/ztree/jquery.ztree.core-3.5.js index ee05c22c8..45c260f87 100644 --- a/src/base/tree/ztree/jquery.ztree.core-3.5.js +++ b/src/base/tree/ztree/jquery.ztree.core-3.5.js @@ -10,1706 +10,1703 @@ * email: hunter.z@263.net * Date: 2015-06-18 */ -(function($){ - var settings = {}, roots = {}, caches = {}, - //default consts of core - _consts = { - className: { - BUTTON: "button", - LEVEL: "level", - ICO_LOADING: "ico_loading", - SWITCH: "switch" - }, - event: { - NODECREATED: "ztree_nodeCreated", - CLICK: "ztree_click", - EXPAND: "ztree_expand", - COLLAPSE: "ztree_collapse", - ASYNC_SUCCESS: "ztree_async_success", - ASYNC_ERROR: "ztree_async_error", - REMOVE: "ztree_remove", - SELECTED: "ztree_selected", - UNSELECTED: "ztree_unselected" - }, - id: { - A: "_a", - ICON: "_ico", - SPAN: "_span", - SWITCH: "_switch", - UL: "_ul" - }, - line: { - ROOT: "root", - ROOTS: "roots", - CENTER: "center", - BOTTOM: "bottom", - NOLINE: "noline", - LINE: "line" - }, - folder: { - OPEN: "open", - CLOSE: "close", - DOCU: "docu" - }, - node: { - CURSELECTED: "curSelectedNode" - } - }, - //default setting of core - _setting = { - treeId: "", - treeObj: null, - view: { - addDiyDom: null, - autoCancelSelected: true, - dblClickExpand: true, - expandSpeed: "fast", - fontCss: {}, - nameIsHTML: false, - selectedMulti: true, - showIcon: true, - showLine: true, - showTitle: true, - txtSelectedEnable: false - }, - data: { - key: { - children: "children", - name: "name", - title: "", - url: "url" - }, - simpleData: { - enable: false, - idKey: "id", - pIdKey: "pId", - rootPId: null - }, - keep: { - parent: false, - leaf: false - } - }, - async: { - enable: false, - contentType: "application/x-www-form-urlencoded", - type: "post", - dataType: "text", - url: "", - autoParam: [], - otherParam: [], - dataFilter: null - }, - callback: { - beforeAsync:null, - beforeClick:null, - beforeDblClick:null, - beforeRightClick:null, - beforeMouseDown:null, - beforeMouseUp:null, - beforeExpand:null, - beforeCollapse:null, - beforeRemove:null, +(function ($) { + var settings = {}, roots = {}, caches = {}, + // default consts of core + _consts = { + className: { + BUTTON: "button", + LEVEL: "level", + ICO_LOADING: "ico_loading", + SWITCH: "switch" + }, + event: { + NODECREATED: "ztree_nodeCreated", + CLICK: "ztree_click", + EXPAND: "ztree_expand", + COLLAPSE: "ztree_collapse", + ASYNC_SUCCESS: "ztree_async_success", + ASYNC_ERROR: "ztree_async_error", + REMOVE: "ztree_remove", + SELECTED: "ztree_selected", + UNSELECTED: "ztree_unselected" + }, + id: { + A: "_a", + ICON: "_ico", + SPAN: "_span", + SWITCH: "_switch", + UL: "_ul" + }, + line: { + ROOT: "root", + ROOTS: "roots", + CENTER: "center", + BOTTOM: "bottom", + NOLINE: "noline", + LINE: "line" + }, + folder: { + OPEN: "open", + CLOSE: "close", + DOCU: "docu" + }, + node: { + CURSELECTED: "curSelectedNode" + } + }, + // default setting of core + _setting = { + treeId: "", + treeObj: null, + view: { + addDiyDom: null, + autoCancelSelected: true, + dblClickExpand: true, + expandSpeed: "fast", + fontCss: {}, + nameIsHTML: false, + selectedMulti: true, + showIcon: true, + showLine: true, + showTitle: true, + txtSelectedEnable: false + }, + data: { + key: { + children: "children", + name: "name", + title: "", + url: "url" + }, + simpleData: { + enable: false, + idKey: "id", + pIdKey: "pId", + rootPId: null + }, + keep: { + parent: false, + leaf: false + } + }, + async: { + enable: false, + contentType: "application/x-www-form-urlencoded", + type: "post", + dataType: "text", + url: "", + autoParam: [], + otherParam: [], + dataFilter: null + }, + callback: { + beforeAsync: null, + beforeClick: null, + beforeDblClick: null, + beforeRightClick: null, + beforeMouseDown: null, + beforeMouseUp: null, + beforeExpand: null, + beforeCollapse: null, + beforeRemove: null, - onAsyncError:null, - onAsyncSuccess:null, - onNodeCreated:null, - onClick:null, - onDblClick:null, - onRightClick:null, - onMouseDown:null, - onMouseUp:null, - onExpand:null, - onCollapse:null, - onRemove:null - } - }, - //default root of core - //zTree use root to save full data - _initRoot = function (setting) { - var r = data.getRoot(setting); - if (!r) { - r = {}; - data.setRoot(setting, r); - } - r[setting.data.key.children] = []; - r.expandTriggerFlag = false; - r.curSelectedList = []; - r.noSelection = true; - r.createdNodes = []; - r.zId = 0; - r._ver = (new Date()).getTime(); - }, - //default cache of core - _initCache = function(setting) { - var c = data.getCache(setting); - if (!c) { - c = {}; - data.setCache(setting, c); - } - c.nodes = []; - c.doms = []; - }, - //default bindEvent of core - _bindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.bind(c.NODECREATED, function (event, treeId, node) { - tools.apply(setting.callback.onNodeCreated, [event, treeId, node]); - }); + onAsyncError: null, + onAsyncSuccess: null, + onNodeCreated: null, + onClick: null, + onDblClick: null, + onRightClick: null, + onMouseDown: null, + onMouseUp: null, + onExpand: null, + onCollapse: null, + onRemove: null + } + }, + // default root of core + // zTree use root to save full data + _initRoot = function (setting) { + var r = data.getRoot(setting); + if (!r) { + r = {}; + data.setRoot(setting, r); + } + r[setting.data.key.children] = []; + r.expandTriggerFlag = false; + r.curSelectedList = []; + r.noSelection = true; + r.createdNodes = []; + r.zId = 0; + r._ver = (new Date()).getTime(); + }, + // default cache of core + _initCache = function (setting) { + var c = data.getCache(setting); + if (!c) { + c = {}; + data.setCache(setting, c); + } + c.nodes = []; + c.doms = []; + }, + // default bindEvent of core + _bindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.bind(c.NODECREATED, function (event, treeId, node) { + tools.apply(setting.callback.onNodeCreated, [event, treeId, node]); + }); - o.bind(c.CLICK, function (event, srcEvent, treeId, node, clickFlag) { - tools.apply(setting.callback.onClick, [srcEvent, treeId, node, clickFlag]); - }); + o.bind(c.CLICK, function (event, srcEvent, treeId, node, clickFlag) { + tools.apply(setting.callback.onClick, [srcEvent, treeId, node, clickFlag]); + }); - o.bind(c.EXPAND, function (event, treeId, node) { - tools.apply(setting.callback.onExpand, [event, treeId, node]); - }); + o.bind(c.EXPAND, function (event, treeId, node) { + tools.apply(setting.callback.onExpand, [event, treeId, node]); + }); - o.bind(c.COLLAPSE, function (event, treeId, node) { - tools.apply(setting.callback.onCollapse, [event, treeId, node]); - }); + o.bind(c.COLLAPSE, function (event, treeId, node) { + tools.apply(setting.callback.onCollapse, [event, treeId, node]); + }); - o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) { - tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]); - }); + o.bind(c.ASYNC_SUCCESS, function (event, treeId, node, msg) { + tools.apply(setting.callback.onAsyncSuccess, [event, treeId, node, msg]); + }); - o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { - tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); - }); + o.bind(c.ASYNC_ERROR, function (event, treeId, node, XMLHttpRequest, textStatus, errorThrown) { + tools.apply(setting.callback.onAsyncError, [event, treeId, node, XMLHttpRequest, textStatus, errorThrown]); + }); - o.bind(c.REMOVE, function (event, treeId, treeNode) { - tools.apply(setting.callback.onRemove, [event, treeId, treeNode]); - }); + o.bind(c.REMOVE, function (event, treeId, treeNode) { + tools.apply(setting.callback.onRemove, [event, treeId, treeNode]); + }); - o.bind(c.SELECTED, function (event, srcEvent, treeId, node) { - tools.apply(setting.callback.onSelected, [srcEvent, treeId, node]); - }); - o.bind(c.UNSELECTED, function (event, srcEvent, treeId, node) { - tools.apply(setting.callback.onUnSelected, [srcEvent, treeId, node]); - }); - }, - _unbindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.unbind(c.NODECREATED) - .unbind(c.CLICK) - .unbind(c.EXPAND) - .unbind(c.COLLAPSE) - .unbind(c.ASYNC_SUCCESS) - .unbind(c.ASYNC_ERROR) - .unbind(c.REMOVE) - .unbind(c.SELECTED) - .unbind(c.UNSELECTED); - }, - //default event proxy of core - _eventProxy = function(event) { - var target = event.target, - setting = data.getSetting(event.data.treeId), - tId = "", node = null, - nodeEventType = "", treeEventType = "", - nodeEventCallback = null, treeEventCallback = null, - tmp = null; + o.bind(c.SELECTED, function (event, srcEvent, treeId, node) { + tools.apply(setting.callback.onSelected, [srcEvent, treeId, node]); + }); + o.bind(c.UNSELECTED, function (event, srcEvent, treeId, node) { + tools.apply(setting.callback.onUnSelected, [srcEvent, treeId, node]); + }); + }, + _unbindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.unbind(c.NODECREATED) + .unbind(c.CLICK) + .unbind(c.EXPAND) + .unbind(c.COLLAPSE) + .unbind(c.ASYNC_SUCCESS) + .unbind(c.ASYNC_ERROR) + .unbind(c.REMOVE) + .unbind(c.SELECTED) + .unbind(c.UNSELECTED); + }, + // default event proxy of core + _eventProxy = function (event) { + var target = event.target, + setting = data.getSetting(event.data.treeId), + tId = "", node = null, + nodeEventType = "", treeEventType = "", + nodeEventCallback = null, treeEventCallback = null, + tmp = null; - if (tools.eqs(event.type, "mousedown")) { - treeEventType = "mousedown"; - } else if (tools.eqs(event.type, "mouseup")) { - treeEventType = "mouseup"; - } else if (tools.eqs(event.type, "contextmenu")) { - treeEventType = "contextmenu"; - } else if (tools.eqs(event.type, "click")) { - if (tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.SWITCH) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "switchNode"; - } else { - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) { - tId = tools.getNodeMainDom(tmp).id; - nodeEventType = "clickNode"; - } - } - } else if (tools.eqs(event.type, "dblclick")) { - treeEventType = "dblclick"; - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) { - tId = tools.getNodeMainDom(tmp).id; - nodeEventType = "switchNode"; - } - } - if (treeEventType.length > 0 && tId.length == 0) { - tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+consts.id.A}]); - if (tmp) {tId = tools.getNodeMainDom(tmp).id;} - } - // event to node - if (tId.length>0) { - node = data.getNodeCache(setting, tId); - switch (nodeEventType) { - case "switchNode" : - if (!node.isParent) { - nodeEventType = ""; - } else if (tools.eqs(event.type, "click") + if (tools.eqs(event.type, "mousedown")) { + treeEventType = "mousedown"; + } else if (tools.eqs(event.type, "mouseup")) { + treeEventType = "mouseup"; + } else if (tools.eqs(event.type, "contextmenu")) { + treeEventType = "contextmenu"; + } else if (tools.eqs(event.type, "click")) { + if (tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.SWITCH) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "switchNode"; + } else { + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) { + tId = tools.getNodeMainDom(tmp).id; + nodeEventType = "clickNode"; + } + } + } else if (tools.eqs(event.type, "dblclick")) { + treeEventType = "dblclick"; + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) { + tId = tools.getNodeMainDom(tmp).id; + nodeEventType = "switchNode"; + } + } + if (treeEventType.length > 0 && tId.length == 0) { + tmp = tools.getMDom(setting, target, [{tagName: "a", attrName: "treeNode" + consts.id.A}]); + if (tmp) {tId = tools.getNodeMainDom(tmp).id;} + } + // event to node + if (tId.length > 0) { + node = data.getNodeCache(setting, tId); + switch (nodeEventType) { + case "switchNode" : + if (!node.isParent) { + nodeEventType = ""; + } else if (tools.eqs(event.type, "click") || (tools.eqs(event.type, "dblclick") && tools.apply(setting.view.dblClickExpand, [setting.treeId, node], setting.view.dblClickExpand))) { - nodeEventCallback = handler.onSwitchNode; - } else { - nodeEventType = ""; - } - break; - case "clickNode" : - nodeEventCallback = handler.onClickNode; - break; - } - } - // event to zTree - switch (treeEventType) { - case "mousedown" : - treeEventCallback = handler.onZTreeMousedown; - break; - case "mouseup" : - treeEventCallback = handler.onZTreeMouseup; - break; - case "dblclick" : - treeEventCallback = handler.onZTreeDblclick; - break; - case "contextmenu" : - treeEventCallback = handler.onZTreeContextmenu; - break; - } - var proxyResult = { - stop: false, - node: node, - nodeEventType: nodeEventType, - nodeEventCallback: nodeEventCallback, - treeEventType: treeEventType, - treeEventCallback: treeEventCallback - }; - return proxyResult - }, - //default init node of core - _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { - if (!n) return; - var r = data.getRoot(setting), - childKey = setting.data.key.children; - n.level = level; - n.tId = setting.treeId + "_" + (++r.zId); - n.parentTId = parentNode ? parentNode.tId : null; - n.open = (typeof n.open == "string") ? tools.eqs(n.open, "true") : !!n.open; - if (n[childKey] && n[childKey].length > 0) { - n.isParent = true; - n.zAsync = true; - } else { - n.isParent = (typeof n.isParent == "string") ? tools.eqs(n.isParent, "true") : !!n.isParent; - n.open = (n.isParent && !setting.async.enable) ? n.open : false; - n.zAsync = !n.isParent; - } - n.isFirstNode = isFirstNode; - n.isLastNode = isLastNode; - n.getParentNode = function() {return data.getNodeCache(setting, n.parentTId);}; - n.getPreNode = function() {return data.getPreNode(setting, n);}; - n.getNextNode = function() {return data.getNextNode(setting, n);}; - n.isAjaxing = false; - data.fixPIdKeyValue(setting, n); - }, - _init = { - bind: [_bindEvent], - unbind: [_unbindEvent], - caches: [_initCache], - nodes: [_initNode], - proxys: [_eventProxy], - roots: [_initRoot], - beforeA: [], - afterA: [], - innerBeforeA: [], - innerAfterA: [], - zTreeTools: [] - }, - //method of operate data - data = { - addNodeCache: function(setting, node) { - data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = node; - }, - getNodeCacheId: function(tId) { - return tId.substring(tId.lastIndexOf("_")+1); - }, - addAfterA: function(afterA) { - _init.afterA.push(afterA); - }, - addBeforeA: function(beforeA) { - _init.beforeA.push(beforeA); - }, - addInnerAfterA: function(innerAfterA) { - _init.innerAfterA.push(innerAfterA); - }, - addInnerBeforeA: function(innerBeforeA) { - _init.innerBeforeA.push(innerBeforeA); - }, - addInitBind: function(bindEvent) { - _init.bind.push(bindEvent); - }, - addInitUnBind: function(unbindEvent) { - _init.unbind.push(unbindEvent); - }, - addInitCache: function(initCache) { - _init.caches.push(initCache); - }, - addInitNode: function(initNode) { - _init.nodes.push(initNode); - }, - addInitProxy: function(initProxy, isFirst) { - if (!!isFirst) { - _init.proxys.splice(0,0,initProxy); - } else { - _init.proxys.push(initProxy); - } - }, - addInitRoot: function(initRoot) { - _init.roots.push(initRoot); - }, - addNodesData: function(setting, parentNode, nodes) { - var childKey = setting.data.key.children; - if (!parentNode[childKey]) parentNode[childKey] = []; - if (parentNode[childKey].length > 0) { - parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false; - view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]); - } - parentNode.isParent = true; - parentNode[childKey] = parentNode[childKey].concat(nodes); - }, - addSelectedNode: function(setting, node) { - var root = data.getRoot(setting); - if (!data.isSelectedNode(setting, node)) { - root.curSelectedList.push(node); - } - }, - addCreatedNode: function(setting, node) { - if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { - var root = data.getRoot(setting); - root.createdNodes.push(node); - } - }, - addZTreeTools: function(zTreeTools) { - _init.zTreeTools.push(zTreeTools); - }, - exSetting: function(s) { - $.extend(true, _setting, s); - }, - fixPIdKeyValue: function(setting, node) { - if (setting.data.simpleData.enable) { - node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; - } - }, - getAfterA: function(setting, node, array) { - for (var i=0, j=_init.afterA.length; i-1) { - result.push(nodes[i]); - } - result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value)); - } - return result; - }, - getNodesByFilter: function(setting, nodes, filter, isSingle, invokeParam) { - if (!nodes) return (isSingle ? null : []); - var childKey = setting.data.key.children, - result = isSingle ? null : []; - for (var i = 0, l = nodes.length; i < l; i++) { - if (tools.apply(filter, [nodes[i], invokeParam], false)) { - if (isSingle) {return nodes[i];} - result.push(nodes[i]); - } - var tmpResult = data.getNodesByFilter(setting, nodes[i][childKey], filter, isSingle, invokeParam); - if (isSingle && !!tmpResult) {return tmpResult;} - result = isSingle ? tmpResult : result.concat(tmpResult); - } - return result; - }, - getPreNode: function(setting, node) { - if (!node) return null; - var childKey = setting.data.key.children, - p = node.parentTId ? node.getParentNode() : data.getRoot(setting); - for (var i=0, l=p[childKey].length; i 0) { + n.isParent = true; + n.zAsync = true; + } else { + n.isParent = (typeof n.isParent === "string") ? tools.eqs(n.isParent, "true") : !!n.isParent; + n.open = (n.isParent && !setting.async.enable) ? n.open : false; + n.zAsync = !n.isParent; + } + n.isFirstNode = isFirstNode; + n.isLastNode = isLastNode; + n.getParentNode = function () {return data.getNodeCache(setting, n.parentTId);}; + n.getPreNode = function () {return data.getPreNode(setting, n);}; + n.getNextNode = function () {return data.getNextNode(setting, n);}; + n.isAjaxing = false; + data.fixPIdKeyValue(setting, n); + }, + _init = { + bind: [_bindEvent], + unbind: [_unbindEvent], + caches: [_initCache], + nodes: [_initNode], + proxys: [_eventProxy], + roots: [_initRoot], + beforeA: [], + afterA: [], + innerBeforeA: [], + innerAfterA: [], + zTreeTools: [] + }, + // method of operate data + data = { + addNodeCache: function (setting, node) { + data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = node; + }, + getNodeCacheId: function (tId) { + return tId.substring(tId.lastIndexOf("_") + 1); + }, + addAfterA: function (afterA) { + _init.afterA.push(afterA); + }, + addBeforeA: function (beforeA) { + _init.beforeA.push(beforeA); + }, + addInnerAfterA: function (innerAfterA) { + _init.innerAfterA.push(innerAfterA); + }, + addInnerBeforeA: function (innerBeforeA) { + _init.innerBeforeA.push(innerBeforeA); + }, + addInitBind: function (bindEvent) { + _init.bind.push(bindEvent); + }, + addInitUnBind: function (unbindEvent) { + _init.unbind.push(unbindEvent); + }, + addInitCache: function (initCache) { + _init.caches.push(initCache); + }, + addInitNode: function (initNode) { + _init.nodes.push(initNode); + }, + addInitProxy: function (initProxy, isFirst) { + if (isFirst) { + _init.proxys.splice(0, 0, initProxy); + } else { + _init.proxys.push(initProxy); + } + }, + addInitRoot: function (initRoot) { + _init.roots.push(initRoot); + }, + addNodesData: function (setting, parentNode, nodes) { + var childKey = setting.data.key.children; + if (!parentNode[childKey]) parentNode[childKey] = []; + if (parentNode[childKey].length > 0) { + parentNode[childKey][parentNode[childKey].length - 1].isLastNode = false; + view.setNodeLineIcos(setting, parentNode[childKey][parentNode[childKey].length - 1]); + } + parentNode.isParent = true; + parentNode[childKey] = parentNode[childKey].concat(nodes); + }, + addSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + if (!data.isSelectedNode(setting, node)) { + root.curSelectedList.push(node); + } + }, + addCreatedNode: function (setting, node) { + if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { + var root = data.getRoot(setting); + root.createdNodes.push(node); + } + }, + addZTreeTools: function (zTreeTools) { + _init.zTreeTools.push(zTreeTools); + }, + exSetting: function (s) { + $.extend(true, _setting, s); + }, + fixPIdKeyValue: function (setting, node) { + if (setting.data.simpleData.enable) { + node[setting.data.simpleData.pIdKey] = node.parentTId ? node.getParentNode()[setting.data.simpleData.idKey] : setting.data.simpleData.rootPId; + } + }, + getAfterA: function (setting, node, array) { + for (var i = 0, j = _init.afterA.length; i < j; i++) { + _init.afterA[i].apply(this, arguments); + } + }, + getBeforeA: function (setting, node, array) { + for (var i = 0, j = _init.beforeA.length; i < j; i++) { + _init.beforeA[i].apply(this, arguments); + } + }, + getInnerAfterA: function (setting, node, array) { + for (var i = 0, j = _init.innerAfterA.length; i < j; i++) { + _init.innerAfterA[i].apply(this, arguments); + } + }, + getInnerBeforeA: function (setting, node, array) { + for (var i = 0, j = _init.innerBeforeA.length; i < j; i++) { + _init.innerBeforeA[i].apply(this, arguments); + } + }, + getCache: function (setting) { + return caches[setting.treeId]; + }, + getNextNode: function (setting, node) { + if (!node) return null; + var childKey = setting.data.key.children, + p = node.parentTId ? node.getParentNode() : data.getRoot(setting); + for (var i = 0, l = p[childKey].length - 1; i <= l; i++) { + if (p[childKey][i] === node) { + return (i == l ? null : p[childKey][i + 1]); + } + } + return null; + }, + getNodeByParam: function (setting, nodes, key, value) { + if (!nodes || !key) return null; + var childKey = setting.data.key.children; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i][key] == value) { + return nodes[i]; + } + var tmp = data.getNodeByParam(setting, nodes[i][childKey], key, value); + if (tmp) return tmp; + } + return null; + }, + getNodeCache: function (setting, tId) { + if (!tId) return null; + var n = caches[setting.treeId].nodes[data.getNodeCacheId(tId)]; + return n ? n : null; + }, + getNodeName: function (setting, node) { + var nameKey = setting.data.key.name; + return "" + node[nameKey]; + }, + getNodeTitle: function (setting, node) { + var t = setting.data.key.title === "" ? setting.data.key.name : setting.data.key.title; + return "" + node[t]; + }, + getNodes: function (setting) { + return data.getRoot(setting)[setting.data.key.children]; + }, + getNodesByParam: function (setting, nodes, key, value) { + if (!nodes || !key) return []; + var childKey = setting.data.key.children, + result = []; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i][key] == value) { + result.push(nodes[i]); + } + result = result.concat(data.getNodesByParam(setting, nodes[i][childKey], key, value)); + } + return result; + }, + getNodesByParamFuzzy: function (setting, nodes, key, value) { + if (!nodes || !key) return []; + var childKey = setting.data.key.children, + result = []; + value = value.toLowerCase(); + for (var i = 0, l = nodes.length; i < l; i++) { + if (typeof nodes[i][key] === "string" && nodes[i][key].toLowerCase().indexOf(value) > -1) { + result.push(nodes[i]); + } + result = result.concat(data.getNodesByParamFuzzy(setting, nodes[i][childKey], key, value)); + } + return result; + }, + getNodesByFilter: function (setting, nodes, filter, isSingle, invokeParam) { + if (!nodes) return (isSingle ? null : []); + var childKey = setting.data.key.children, + result = isSingle ? null : []; + for (var i = 0, l = nodes.length; i < l; i++) { + if (tools.apply(filter, [nodes[i], invokeParam], false)) { + if (isSingle) {return nodes[i];} + result.push(nodes[i]); + } + var tmpResult = data.getNodesByFilter(setting, nodes[i][childKey], filter, isSingle, invokeParam); + if (isSingle && !!tmpResult) {return tmpResult;} + result = isSingle ? tmpResult : result.concat(tmpResult); + } + return result; + }, + getPreNode: function (setting, node) { + if (!node) return null; + var childKey = setting.data.key.children, + p = node.parentTId ? node.getParentNode() : data.getRoot(setting); + for (var i = 0, l = p[childKey].length; i < l; i++) { + if (p[childKey][i] === node) { + return (i == 0 ? null : p[childKey][i - 1]); + } + } + return null; + }, + getRoot: function (setting) { + return setting ? roots[setting.treeId] : null; + }, + getRoots: function () { + return roots; + }, + getSetting: function (treeId) { + return settings[treeId]; + }, + getSettings: function () { + return settings; + }, + getZTreeTools: function (treeId) { + var r = this.getRoot(this.getSetting(treeId)); + return r ? r.treeTools : null; + }, + initCache: function (setting) { + for (var i = 0, j = _init.caches.length; i < j; i++) { + _init.caches[i].apply(this, arguments); + } + }, + initNode: function (setting, level, node, parentNode, preNode, nextNode) { + for (var i = 0, j = _init.nodes.length; i < j; i++) { + _init.nodes[i].apply(this, arguments); + } + }, + initRoot: function (setting) { + for (var i = 0, j = _init.roots.length; i < j; i++) { + _init.roots[i].apply(this, arguments); + } + }, + isSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + for (var i = 0, j = root.curSelectedList.length; i < j; i++) { + if(node === root.curSelectedList[i]) return true; + } + return false; + }, + removeNodeCache: function (setting, node) { + var childKey = setting.data.key.children; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + arguments.callee(setting, node[childKey][i]); + } + } + data.getCache(setting).nodes[data.getNodeCacheId(node.tId)] = null; + }, + removeSelectedNode: function (setting, node) { + var root = data.getRoot(setting); + for (var i = 0, j = root.curSelectedList.length; i < j; i++) { + if(node === root.curSelectedList[i] || !data.getNodeCache(setting, root.curSelectedList[i].tId)) { + root.curSelectedList.splice(i, 1); + i--; j--; + } + } + }, + setCache: function (setting, cache) { + caches[setting.treeId] = cache; + }, + setRoot: function (setting, root) { + roots[setting.treeId] = root; + }, + setZTreeTools: function (setting, zTreeTools) { + for (var i = 0, j = _init.zTreeTools.length; i < j; i++) { + _init.zTreeTools[i].apply(this, arguments); + } + }, + transformToArrayFormat: function (setting, nodes) { + if (!nodes) return []; + var childKey = setting.data.key.children, + r = []; + if (tools.isArray(nodes)) { + for (var i = 0, l = nodes.length; i < l; i++) { + r.push(nodes[i]); + if (nodes[i][childKey]) {r = r.concat(data.transformToArrayFormat(setting, nodes[i][childKey]));} + } + } else { + r.push(nodes); + if (nodes[childKey]) {r = r.concat(data.transformToArrayFormat(setting, nodes[childKey]));} + } + return r; + }, + transformTozTreeFormat: function (setting, sNodes) { + var i, l, + key = setting.data.simpleData.idKey, + parentKey = setting.data.simpleData.pIdKey, + childKey = setting.data.key.children; + if (!key || key == "" || !sNodes) return []; - if (tools.isArray(sNodes)) { - var r = []; - var tmpMap = []; - for (i=0, l=sNodes.length; i 0))); - }, - clone: function (obj){ - if (obj === null) return null; - var o = tools.isArray(obj) ? [] : {}; - for(var i in obj){ - o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]); - } - return o; - }, - eqs: function(str1, str2) { - return str1.toLowerCase() === str2.toLowerCase(); - }, - isArray: function(arr) { - return Object.prototype.toString.apply(arr) === "[object Array]"; - }, - $: function(node, exp, setting) { - if (!!exp && typeof exp != "string") { - setting = exp; - exp = ""; - } - if (typeof node == "string") { - return $(node, setting ? setting.treeObj.get(0).ownerDocument : null); - } else { - return $("#" + node.tId + exp, setting ? setting.treeObj : null); - } - }, - getMDom: function (setting, curDom, targetExpr) { - if (!curDom) return null; - while (curDom && curDom.id !== setting.treeId) { - for (var i=0, l=targetExpr.length; curDom.tagName && i 0 ); - }, - uCanDo: function(setting, e) { - return true; - } - }, - //method of operate ztree dom - view = { - addNodes: function(setting, parentNode, newNodes, isSilent) { - if (setting.data.keep.leaf && parentNode && !parentNode.isParent) { - return; - } - if (!tools.isArray(newNodes)) { - newNodes = [newNodes]; - } - if (setting.data.simpleData.enable) { - newNodes = data.transformTozTreeFormat(setting, newNodes); - } - if (parentNode) { - var target_switchObj = $$(parentNode, consts.id.SWITCH, setting), - target_icoObj = $$(parentNode, consts.id.ICON, setting), - target_ulObj = $$(parentNode, consts.id.UL, setting); + if (tools.isArray(sNodes)) { + var r = []; + var tmpMap = []; + for (i = 0, l = sNodes.length; i < l; i++) { + tmpMap[sNodes[i][key]] = sNodes[i]; + } + for (i = 0, l = sNodes.length; i < l; i++) { + if (tmpMap[sNodes[i][parentKey]] && sNodes[i][key] != sNodes[i][parentKey]) { + if (!tmpMap[sNodes[i][parentKey]][childKey]) {tmpMap[sNodes[i][parentKey]][childKey] = [];} + tmpMap[sNodes[i][parentKey]][childKey].push(sNodes[i]); + } else { + r.push(sNodes[i]); + } + } + return r; + } + return [sNodes]; + + } + }, + // method of event proxy + event = { + bindEvent: function (setting) { + for (var i = 0, j = _init.bind.length; i < j; i++) { + _init.bind[i].apply(this, arguments); + } + }, + unbindEvent: function (setting) { + for (var i = 0, j = _init.unbind.length; i < j; i++) { + _init.unbind[i].apply(this, arguments); + } + }, + bindTree: function (setting) { + var eventParam = { + treeId: setting.treeId + }, + o = setting.treeObj; + if (!setting.view.txtSelectedEnable) { + // for can't select text + o.bind("selectstart", function (e) { + var node; + var n = e.originalEvent.srcElement.nodeName.toLowerCase(); + return (n === "input" || n === "textarea" ); + }).css({ + "-moz-user-select": "-moz-none" + }); + } + o.bind("click", eventParam, event.proxy); + o.bind("dblclick", eventParam, event.proxy); + o.bind("mouseover", eventParam, event.proxy); + o.bind("mouseout", eventParam, event.proxy); + o.bind("mousedown", eventParam, event.proxy); + o.bind("mouseup", eventParam, event.proxy); + o.bind("contextmenu", eventParam, event.proxy); + }, + unbindTree: function (setting) { + var o = setting.treeObj; + o.unbind("click", event.proxy) + .unbind("dblclick", event.proxy) + .unbind("mouseover", event.proxy) + .unbind("mouseout", event.proxy) + .unbind("mousedown", event.proxy) + .unbind("mouseup", event.proxy) + .unbind("contextmenu", event.proxy); + }, + doProxy: function (e) { + var results = []; + for (var i = 0, j = _init.proxys.length; i < j; i++) { + var proxyResult = _init.proxys[i].apply(this, arguments); + results.push(proxyResult); + if (proxyResult.stop) { + break; + } + } + return results; + }, + proxy: function (e) { + var setting = data.getSetting(e.data.treeId); + if (!tools.uCanDo(setting, e)) return true; + var results = event.doProxy(e), + r = true, x = false; + for (var i = 0, l = results.length; i < l; i++) { + var proxyResult = results[i]; + if (proxyResult.nodeEventCallback) { + x = true; + r = proxyResult.nodeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; + } + if (proxyResult.treeEventCallback) { + x = true; + r = proxyResult.treeEventCallback.apply(proxyResult, [e, proxyResult.node]) && r; + } + } + return r; + } + }, + // method of event handler + handler = { + onSwitchNode: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (node.open) { + if (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false) return true; + data.getRoot(setting).expandTriggerFlag = true; + view.switchNode(setting, node); + } else { + if (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false) return true; + data.getRoot(setting).expandTriggerFlag = true; + view.switchNode(setting, node); + } + return true; + }, + onClickNode: function (event, node) { + var setting = data.getSetting(event.data.treeId), + clickFlag = ( (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey)) && data.isSelectedNode(setting, node)) ? 0 : (setting.view.autoCancelSelected && (event.ctrlKey || event.metaKey) && setting.view.selectedMulti) ? 2 : 1; + if (tools.apply(setting.callback.beforeClick, [setting.treeId, node, clickFlag], true) == false) return true; + if (clickFlag === 0) { + view.cancelPreSelectedNode(setting, node); + } else { + view.selectNode(setting, node, clickFlag === 2); + } + setting.treeObj.trigger(consts.event.CLICK, [event, setting.treeId, node, clickFlag]); + return true; + }, + onZTreeMousedown: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeMouseDown, [setting.treeId, node], true)) { + tools.apply(setting.callback.onMouseDown, [event, setting.treeId, node]); + } + return true; + }, + onZTreeMouseup: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeMouseUp, [setting.treeId, node], true)) { + tools.apply(setting.callback.onMouseUp, [event, setting.treeId, node]); + } + return true; + }, + onZTreeDblclick: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeDblClick, [setting.treeId, node], true)) { + tools.apply(setting.callback.onDblClick, [event, setting.treeId, node]); + } + return true; + }, + onZTreeContextmenu: function (event, node) { + var setting = data.getSetting(event.data.treeId); + if (tools.apply(setting.callback.beforeRightClick, [setting.treeId, node], true)) { + tools.apply(setting.callback.onRightClick, [event, setting.treeId, node]); + } + return (typeof setting.callback.onRightClick) !== "function"; + } + }, + // method of tools for zTree + tools = { + apply: function (fun, param, defaultValue) { + if ((typeof fun) === "function") { + return fun.apply(zt, param ? param : []); + } + return defaultValue; + }, + canAsync: function (setting, node) { + var childKey = setting.data.key.children; + return (setting.async.enable && node && node.isParent && !(node.zAsync || (node[childKey] && node[childKey].length > 0))); + }, + clone: function (obj) { + if (obj === null) return null; + var o = tools.isArray(obj) ? [] : {}; + for(var i in obj) { + o[i] = (obj[i] instanceof Date) ? new Date(obj[i].getTime()) : (typeof obj[i] === "object" ? arguments.callee(obj[i]) : obj[i]); + } + return o; + }, + eqs: function (str1, str2) { + return str1.toLowerCase() === str2.toLowerCase(); + }, + isArray: function (arr) { + return Object.prototype.toString.apply(arr) === "[object Array]"; + }, + $: function (node, exp, setting) { + if (!!exp && typeof exp !== "string") { + setting = exp; + exp = ""; + } + if (typeof node === "string") { + return $(node, setting ? setting.treeObj.get(0).ownerDocument : null); + } + return $("#" + node.tId + exp, setting ? setting.treeObj : null); + + }, + getMDom: function (setting, curDom, targetExpr) { + if (!curDom) return null; + while (curDom && curDom.id !== setting.treeId) { + for (var i = 0, l = targetExpr.length; curDom.tagName && i < l; i++) { + if (tools.eqs(curDom.tagName, targetExpr[i].tagName) && curDom.getAttribute(targetExpr[i].attrName) !== null) { + return curDom; + } + } + curDom = curDom.parentNode; + } + return null; + }, + getNodeMainDom: function (target) { + return ($(target).parent("li").get(0) || $(target).parentsUntil("li").parent().get(0)); + }, + isChildOrSelf: function (dom, parentId) { + return ( $(dom).closest("#" + parentId).length > 0 ); + }, + uCanDo: function (setting, e) { + return true; + } + }, + // method of operate ztree dom + view = { + addNodes: function (setting, parentNode, newNodes, isSilent) { + if (setting.data.keep.leaf && parentNode && !parentNode.isParent) { + return; + } + if (!tools.isArray(newNodes)) { + newNodes = [newNodes]; + } + if (setting.data.simpleData.enable) { + newNodes = data.transformTozTreeFormat(setting, newNodes); + } + if (parentNode) { + var target_switchObj = $$(parentNode, consts.id.SWITCH, setting), + target_icoObj = $$(parentNode, consts.id.ICON, setting), + target_ulObj = $$(parentNode, consts.id.UL, setting); - if (!parentNode.open) { - view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE); - view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); - parentNode.open = false; - target_ulObj.css({ - "display": "none" - }); - } + if (!parentNode.open) { + view.replaceSwitchClass(parentNode, target_switchObj, consts.folder.CLOSE); + view.replaceIcoClass(parentNode, target_icoObj, consts.folder.CLOSE); + parentNode.open = false; + target_ulObj.css({ + display: "none" + }); + } - data.addNodesData(setting, parentNode, newNodes); - view.createNodes(setting, parentNode.level + 1, newNodes, parentNode); - if (!isSilent) { - view.expandCollapseParentNode(setting, parentNode, true); - } - } else { - data.addNodesData(setting, data.getRoot(setting), newNodes); - view.createNodes(setting, 0, newNodes, null); - } - }, - appendNodes: function(setting, level, nodes, parentNode, initFlag, openFlag) { - if (!nodes) return []; - var html = [], - childKey = setting.data.key.children; - for (var i = 0, l = nodes.length; i < l; i++) { - var node = nodes[i]; - if (initFlag) { - var tmpPNode = (parentNode) ? parentNode: data.getRoot(setting), - tmpPChild = tmpPNode[childKey], - isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)), - isLastNode = (i == (nodes.length - 1)); - data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); - data.addNodeCache(setting, node); - } + data.addNodesData(setting, parentNode, newNodes); + view.createNodes(setting, parentNode.level + 1, newNodes, parentNode); + if (!isSilent) { + view.expandCollapseParentNode(setting, parentNode, true); + } + } else { + data.addNodesData(setting, data.getRoot(setting), newNodes); + view.createNodes(setting, 0, newNodes, null); + } + }, + appendNodes: function (setting, level, nodes, parentNode, initFlag, openFlag) { + if (!nodes) return []; + var html = [], + childKey = setting.data.key.children; + for (var i = 0, l = nodes.length; i < l; i++) { + var node = nodes[i]; + if (initFlag) { + var tmpPNode = (parentNode) ? parentNode : data.getRoot(setting), + tmpPChild = tmpPNode[childKey], + isFirstNode = ((tmpPChild.length == nodes.length) && (i == 0)), + isLastNode = (i == (nodes.length - 1)); + data.initNode(setting, level, node, parentNode, isFirstNode, isLastNode, openFlag); + data.addNodeCache(setting, node); + } - var childHtml = []; - if (node[childKey] && node[childKey].length > 0) { - //make child html first, because checkType - childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open); - } - if (openFlag) { + var childHtml = []; + if (node[childKey] && node[childKey].length > 0) { + // make child html first, because checkType + childHtml = view.appendNodes(setting, level + 1, node[childKey], node, initFlag, openFlag && node.open); + } + if (openFlag) { - view.makeDOMNodeMainBefore(html, setting, node); - view.makeDOMNodeLine(html, setting, node); - data.getBeforeA(setting, node, html); - view.makeDOMNodeNameBefore(html, setting, node); - data.getInnerBeforeA(setting, node, html); - view.makeDOMNodeIcon(html, setting, node); - data.getInnerAfterA(setting, node, html); - view.makeDOMNodeNameAfter(html, setting, node); - data.getAfterA(setting, node, html); - if (node.isParent && node.open) { - view.makeUlHtml(setting, node, html, childHtml.join('')); - } - view.makeDOMNodeMainAfter(html, setting, node); - data.addCreatedNode(setting, node); - } - } - return html; - }, - appendParentULDom: function(setting, node) { - var html = [], - nObj = $$(node, setting); - if (!nObj.get(0) && !!node.parentTId) { - view.appendParentULDom(setting, node.getParentNode()); - nObj = $$(node, setting); - } - var ulObj = $$(node, consts.id.UL, setting); - if (ulObj.get(0)) { - ulObj.remove(); - } - var childKey = setting.data.key.children, - childHtml = view.appendNodes(setting, node.level+1, node[childKey], node, false, true); - view.makeUlHtml(setting, node, html, childHtml.join('')); - nObj.append(html.join('')); - }, - asyncNode: function(setting, node, isSilent, callback) { - var i, l; - if (node && !node.isParent) { - tools.apply(callback); - return false; - } else if (node && node.isAjaxing) { - return false; - } else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) { - tools.apply(callback); - return false; - } - if (node) { - node.isAjaxing = true; - var icoObj = $$(node, consts.id.ICON, setting); - icoObj.attr({"style":"", "class":consts.className.BUTTON + " " + consts.className.ICO_LOADING}); - } + view.makeDOMNodeMainBefore(html, setting, node); + view.makeDOMNodeLine(html, setting, node); + data.getBeforeA(setting, node, html); + view.makeDOMNodeNameBefore(html, setting, node); + data.getInnerBeforeA(setting, node, html); + view.makeDOMNodeIcon(html, setting, node); + data.getInnerAfterA(setting, node, html); + view.makeDOMNodeNameAfter(html, setting, node); + data.getAfterA(setting, node, html); + if (node.isParent && node.open) { + view.makeUlHtml(setting, node, html, childHtml.join("")); + } + view.makeDOMNodeMainAfter(html, setting, node); + data.addCreatedNode(setting, node); + } + } + return html; + }, + appendParentULDom: function (setting, node) { + var html = [], + nObj = $$(node, setting); + if (!nObj.get(0) && !!node.parentTId) { + view.appendParentULDom(setting, node.getParentNode()); + nObj = $$(node, setting); + } + var ulObj = $$(node, consts.id.UL, setting); + if (ulObj.get(0)) { + ulObj.remove(); + } + var childKey = setting.data.key.children, + childHtml = view.appendNodes(setting, node.level + 1, node[childKey], node, false, true); + view.makeUlHtml(setting, node, html, childHtml.join("")); + nObj.append(html.join("")); + }, + asyncNode: function (setting, node, isSilent, callback) { + var i, l; + if (node && !node.isParent) { + tools.apply(callback); + return false; + } else if (node && node.isAjaxing) { + return false; + } else if (tools.apply(setting.callback.beforeAsync, [setting.treeId, node], true) == false) { + tools.apply(callback); + return false; + } + if (node) { + node.isAjaxing = true; + var icoObj = $$(node, consts.id.ICON, setting); + icoObj.attr({style: "", class: consts.className.BUTTON + " " + consts.className.ICO_LOADING}); + } - var tmpParam = {}; - for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) { - var pKey = setting.async.autoParam[i].split("="), spKey = pKey; - if (pKey.length>1) { - spKey = pKey[1]; - pKey = pKey[0]; - } - tmpParam[spKey] = node[pKey]; - } - if (tools.isArray(setting.async.otherParam)) { - for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) { - tmpParam[setting.async.otherParam[i]] = setting.async.otherParam[i + 1]; - } - } else { - for (var p in setting.async.otherParam) { - tmpParam[p] = setting.async.otherParam[p]; - } - } + var tmpParam = {}; + for (i = 0, l = setting.async.autoParam.length; node && i < l; i++) { + var pKey = setting.async.autoParam[i].split("="), spKey = pKey; + if (pKey.length > 1) { + spKey = pKey[1]; + pKey = pKey[0]; + } + tmpParam[spKey] = node[pKey]; + } + if (tools.isArray(setting.async.otherParam)) { + for (i = 0, l = setting.async.otherParam.length; i < l; i += 2) { + tmpParam[setting.async.otherParam[i]] = setting.async.otherParam[i + 1]; + } + } else { + for (var p in setting.async.otherParam) { + tmpParam[p] = setting.async.otherParam[p]; + } + } - var _tmpV = data.getRoot(setting)._ver; - $.ajax({ - contentType: setting.async.contentType, - cache: false, - type: setting.async.type, - url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), - data: tmpParam, - dataType: setting.async.dataType, - success: function(msg) { - if (_tmpV != data.getRoot(setting)._ver) { - return; - } - var newNodes = []; - try { - if (!msg || msg.length == 0) { - newNodes = []; - } else if (typeof msg == "string") { - newNodes = eval("(" + msg + ")"); - } else { - newNodes = msg; - } - } catch(err) { - newNodes = msg; - } + var _tmpV = data.getRoot(setting)._ver; + $.ajax({ + contentType: setting.async.contentType, + cache: false, + type: setting.async.type, + url: tools.apply(setting.async.url, [setting.treeId, node], setting.async.url), + data: tmpParam, + dataType: setting.async.dataType, + success: function (msg) { + if (_tmpV != data.getRoot(setting)._ver) { + return; + } + var newNodes = []; + try { + if (!msg || msg.length == 0) { + newNodes = []; + } else if (typeof msg === "string") { + newNodes = eval("(" + msg + ")"); + } else { + newNodes = msg; + } + } catch(err) { + newNodes = msg; + } - if (node) { - node.isAjaxing = null; - node.zAsync = true; - } - view.setNodeLineIcos(setting, node); - if (newNodes && newNodes !== "") { - newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); - view.addNodes(setting, node, !!newNodes ? tools.clone(newNodes) : [], !!isSilent); - } else { - view.addNodes(setting, node, [], !!isSilent); - } - setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]); - tools.apply(callback); - }, - error: function(XMLHttpRequest, textStatus, errorThrown) { - if (_tmpV != data.getRoot(setting)._ver) { - return; - } - if (node) node.isAjaxing = null; - view.setNodeLineIcos(setting, node); - setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); - } - }); - return true; - }, - cancelPreSelectedNode: function (setting, node, excludeNode) { - var list = data.getRoot(setting).curSelectedList, - i, n; - for (i=list.length-1; i>=0; i--) { - n = list[i]; - if (node === n || (!node && (!excludeNode || excludeNode !== n))) { - $$(n, consts.id.A, setting).removeClass(consts.node.CURSELECTED); - if (node) { - data.removeSelectedNode(setting, node); - setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); - break; - } else { - list.splice(i, 1); - setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); - } - } - } - }, - createNodeCallback: function(setting) { - if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { - var root = data.getRoot(setting); - while (root.createdNodes.length>0) { - var node = root.createdNodes.shift(); - tools.apply(setting.view.addDiyDom, [setting.treeId, node]); - if (!!setting.callback.onNodeCreated) { - setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]); - } - } - } - }, - createNodes: function(setting, level, nodes, parentNode) { - if (!nodes || nodes.length == 0) return; - var root = data.getRoot(setting), - childKey = setting.data.key.children, - openFlag = !parentNode || parentNode.open || !!$$(parentNode[childKey][0], setting).get(0); - root.createdNodes = []; - var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag); - if (!parentNode) { - setting.treeObj.append(zTreeHtml.join('')); - } else { - var ulObj = $$(parentNode, consts.id.UL, setting); - if (ulObj.get(0)) { - ulObj.append(zTreeHtml.join('')); - } - } - view.createNodeCallback(setting); - }, - destroy: function(setting) { - if (!setting) return; - data.initCache(setting); - data.initRoot(setting); - event.unbindTree(setting); - event.unbindEvent(setting); - setting.treeObj.empty(); - delete settings[setting.treeId]; - }, - expandCollapseNode: function(setting, node, expandFlag, animateFlag, callback) { - var root = data.getRoot(setting), - childKey = setting.data.key.children; - if (!node) { - tools.apply(callback, []); - return; - } - if (root.expandTriggerFlag) { - var _callback = callback; - callback = function(){ - if (_callback) _callback(); - if (node.open) { - setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]); - } else { - setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]); - } - }; - root.expandTriggerFlag = false; - } - if (!node.open && node.isParent && ((!$$(node, consts.id.UL, setting).get(0)) || (node[childKey] && node[childKey].length>0 && !$$(node[childKey][0], setting).get(0)))) { - view.appendParentULDom(setting, node); - view.createNodeCallback(setting); - } - if (node.open == expandFlag) { - tools.apply(callback, []); - return; - } - var ulObj = $$(node, consts.id.UL, setting), - switchObj = $$(node, consts.id.SWITCH, setting), - icoObj = $$(node, consts.id.ICON, setting); + if (node) { + node.isAjaxing = null; + node.zAsync = true; + } + view.setNodeLineIcos(setting, node); + if (newNodes && newNodes !== "") { + newNodes = tools.apply(setting.async.dataFilter, [setting.treeId, node, newNodes], newNodes); + view.addNodes(setting, node, newNodes ? tools.clone(newNodes) : [], !!isSilent); + } else { + view.addNodes(setting, node, [], !!isSilent); + } + setting.treeObj.trigger(consts.event.ASYNC_SUCCESS, [setting.treeId, node, msg]); + tools.apply(callback); + }, + error: function (XMLHttpRequest, textStatus, errorThrown) { + if (_tmpV != data.getRoot(setting)._ver) { + return; + } + if (node) node.isAjaxing = null; + view.setNodeLineIcos(setting, node); + setting.treeObj.trigger(consts.event.ASYNC_ERROR, [setting.treeId, node, XMLHttpRequest, textStatus, errorThrown]); + } + }); + return true; + }, + cancelPreSelectedNode: function (setting, node, excludeNode) { + var list = data.getRoot(setting).curSelectedList, + i, n; + for (i = list.length - 1; i >= 0; i--) { + n = list[i]; + if (node === n || (!node && (!excludeNode || excludeNode !== n))) { + $$(n, consts.id.A, setting).removeClass(consts.node.CURSELECTED); + if (node) { + data.removeSelectedNode(setting, node); + setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); + break; + } else { + list.splice(i, 1); + setting.treeObj.trigger(consts.event.UNSELECTED, [event, setting.treeId, n]); + } + } + } + }, + createNodeCallback: function (setting) { + if (!!setting.callback.onNodeCreated || !!setting.view.addDiyDom) { + var root = data.getRoot(setting); + while (root.createdNodes.length > 0) { + var node = root.createdNodes.shift(); + tools.apply(setting.view.addDiyDom, [setting.treeId, node]); + if (setting.callback.onNodeCreated) { + setting.treeObj.trigger(consts.event.NODECREATED, [setting.treeId, node]); + } + } + } + }, + createNodes: function (setting, level, nodes, parentNode) { + if (!nodes || nodes.length == 0) return; + var root = data.getRoot(setting), + childKey = setting.data.key.children, + openFlag = !parentNode || parentNode.open || !!$$(parentNode[childKey][0], setting).get(0); + root.createdNodes = []; + var zTreeHtml = view.appendNodes(setting, level, nodes, parentNode, true, openFlag); + if (!parentNode) { + setting.treeObj.append(zTreeHtml.join("")); + } else { + var ulObj = $$(parentNode, consts.id.UL, setting); + if (ulObj.get(0)) { + ulObj.append(zTreeHtml.join("")); + } + } + view.createNodeCallback(setting); + }, + destroy: function (setting) { + if (!setting) return; + data.initCache(setting); + data.initRoot(setting); + event.unbindTree(setting); + event.unbindEvent(setting); + setting.treeObj.empty(); + delete settings[setting.treeId]; + }, + expandCollapseNode: function (setting, node, expandFlag, animateFlag, callback) { + var root = data.getRoot(setting), + childKey = setting.data.key.children; + if (!node) { + tools.apply(callback, []); + return; + } + if (root.expandTriggerFlag) { + var _callback = callback; + callback = function () { + if (_callback) _callback(); + if (node.open) { + setting.treeObj.trigger(consts.event.EXPAND, [setting.treeId, node]); + } else { + setting.treeObj.trigger(consts.event.COLLAPSE, [setting.treeId, node]); + } + }; + root.expandTriggerFlag = false; + } + if (!node.open && node.isParent && ((!$$(node, consts.id.UL, setting).get(0)) || (node[childKey] && node[childKey].length > 0 && !$$(node[childKey][0], setting).get(0)))) { + view.appendParentULDom(setting, node); + view.createNodeCallback(setting); + } + if (node.open == expandFlag) { + tools.apply(callback, []); + return; + } + var ulObj = $$(node, consts.id.UL, setting), + switchObj = $$(node, consts.id.SWITCH, setting), + icoObj = $$(node, consts.id.ICON, setting); - if (node.isParent) { - node.open = !node.open; - if (node.iconOpen && node.iconClose) { - icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); - } + if (node.isParent) { + node.open = !node.open; + if (node.iconOpen && node.iconClose) { + icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); + } - if (node.open) { - view.replaceSwitchClass(node, switchObj, consts.folder.OPEN); - view.replaceIcoClass(node, icoObj, consts.folder.OPEN); - if (animateFlag == false || setting.view.expandSpeed == "") { - ulObj.show(); - tools.apply(callback, []); - } else { - if (node[childKey] && node[childKey].length > 0) { - ulObj.slideDown(setting.view.expandSpeed, callback); - } else { - ulObj.show(); - tools.apply(callback, []); - } - } - } else { - view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); - view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); - if (animateFlag == false || setting.view.expandSpeed == "" || !(node[childKey] && node[childKey].length > 0)) { - ulObj.hide(); - tools.apply(callback, []); - } else { - ulObj.slideUp(setting.view.expandSpeed, callback); - } - } - } else { - tools.apply(callback, []); - } - }, - expandCollapseParentNode: function(setting, node, expandFlag, animateFlag, callback) { - if (!node) return; - if (!node.parentTId) { - view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback); - return; - } else { - view.expandCollapseNode(setting, node, expandFlag, animateFlag); - } - if (node.parentTId) { - view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback); - } - }, - expandCollapseSonNode: function(setting, node, expandFlag, animateFlag, callback) { - var root = data.getRoot(setting), - childKey = setting.data.key.children, - treeNodes = (node) ? node[childKey]: root[childKey], - selfAnimateSign = (node) ? false : animateFlag, - expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; - data.getRoot(setting).expandTriggerFlag = false; - if (treeNodes) { - for (var i = 0, l = treeNodes.length; i < l; i++) { - if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); - } - } - data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; - view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback ); - }, - isSelectedNode: function (setting, node) { - if (!node) { - return false; - } - var list = data.getRoot(setting).curSelectedList, - i; - for (i=list.length-1; i>=0; i--) { - if (node === list[i]) { - return true; - } - } - return false; - }, - makeDOMNodeIcon: function(html, setting, node) { - var nameStr = data.getNodeName(setting, node), - name = setting.view.nameIsHTML ? nameStr : nameStr.replace(/&/g,'&').replace(//g,'>'); - html.push("",name,""); - }, - makeDOMNodeLine: function(html, setting, node) { - html.push(""); - }, - makeDOMNodeMainAfter: function(html, setting, node) { - html.push("
  • "); - }, - makeDOMNodeMainBefore: function(html, setting, node) { - html.push("
  • "); - }, - makeDOMNodeNameAfter: function(html, setting, node) { - html.push(""); - }, - makeDOMNodeNameBefore: function(html, setting, node) { - var title = data.getNodeTitle(setting, node), - url = view.makeNodeUrl(setting, node), - fontcss = view.makeNodeFontCss(setting, node), - fontStyle = []; - for (var f in fontcss) { - fontStyle.push(f, ":", fontcss[f], ";"); - } - html.push(" 0) ? "href='" + url + "'" : ""), " target='",view.makeNodeTarget(node),"' style='", fontStyle.join(''), - "'"); - if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && title) {html.push("title='", title.replace(/'/g,"'").replace(//g,'>'),"'");} - html.push(">"); - }, - makeNodeFontCss: function(setting, node) { - var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); - return (fontCss && ((typeof fontCss) != "function")) ? fontCss : {}; - }, - makeNodeIcoClass: function(setting, node) { - var icoCss = ["ico"]; - if (!node.isAjaxing) { - icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0]; - if (node.isParent) { - icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); - } else { - icoCss.push(consts.folder.DOCU); - } - } - return consts.className.BUTTON + " " + icoCss.join('_'); - }, - makeNodeIcoStyle: function(setting, node) { - var icoStyle = []; - if (!node.isAjaxing) { - var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon; - if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); - if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { - icoStyle.push("width:0px;height:0px;"); - } - } - return icoStyle.join(''); - }, - makeNodeLineClass: function(setting, node) { - var lineClass = []; - if (setting.view.showLine) { - if (node.level == 0 && node.isFirstNode && node.isLastNode) { - lineClass.push(consts.line.ROOT); - } else if (node.level == 0 && node.isFirstNode) { - lineClass.push(consts.line.ROOTS); - } else if (node.isLastNode) { - lineClass.push(consts.line.BOTTOM); - } else { - lineClass.push(consts.line.CENTER); - } - } else { - lineClass.push(consts.line.NOLINE); - } - if (node.isParent) { - lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); - } else { - lineClass.push(consts.folder.DOCU); - } - return view.makeNodeLineClassEx(node) + lineClass.join('_'); - }, - makeNodeLineClassEx: function(node) { - return consts.className.BUTTON + " " + consts.className.LEVEL + node.level + " " + consts.className.SWITCH + " "; - }, - makeNodeTarget: function(node) { - return (node.target || "_blank"); - }, - makeNodeUrl: function(setting, node) { - var urlKey = setting.data.key.url; - return node[urlKey] ? node[urlKey] : null; - }, - makeUlHtml: function(setting, node, html, content) { - html.push("
      "); - html.push(content); - html.push("
    "); - }, - makeUlLineClass: function(setting, node) { - return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : ""); - }, - removeChildNodes: function(setting, node) { - if (!node) return; - var childKey = setting.data.key.children, - nodes = node[childKey]; - if (!nodes) return; + if (node.open) { + view.replaceSwitchClass(node, switchObj, consts.folder.OPEN); + view.replaceIcoClass(node, icoObj, consts.folder.OPEN); + if (animateFlag == false || setting.view.expandSpeed == "") { + ulObj.show(); + tools.apply(callback, []); + } else { + if (node[childKey] && node[childKey].length > 0) { + ulObj.slideDown(setting.view.expandSpeed, callback); + } else { + ulObj.show(); + tools.apply(callback, []); + } + } + } else { + view.replaceSwitchClass(node, switchObj, consts.folder.CLOSE); + view.replaceIcoClass(node, icoObj, consts.folder.CLOSE); + if (animateFlag == false || setting.view.expandSpeed == "" || !(node[childKey] && node[childKey].length > 0)) { + ulObj.hide(); + tools.apply(callback, []); + } else { + ulObj.slideUp(setting.view.expandSpeed, callback); + } + } + } else { + tools.apply(callback, []); + } + }, + expandCollapseParentNode: function (setting, node, expandFlag, animateFlag, callback) { + if (!node) return; + if (!node.parentTId) { + view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback); + return; + } + view.expandCollapseNode(setting, node, expandFlag, animateFlag); + + if (node.parentTId) { + view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, animateFlag, callback); + } + }, + expandCollapseSonNode: function (setting, node, expandFlag, animateFlag, callback) { + var root = data.getRoot(setting), + childKey = setting.data.key.children, + treeNodes = (node) ? node[childKey] : root[childKey], + selfAnimateSign = (node) ? false : animateFlag, + expandTriggerFlag = data.getRoot(setting).expandTriggerFlag; + data.getRoot(setting).expandTriggerFlag = false; + if (treeNodes) { + for (var i = 0, l = treeNodes.length; i < l; i++) { + if (treeNodes[i]) view.expandCollapseSonNode(setting, treeNodes[i], expandFlag, selfAnimateSign); + } + } + data.getRoot(setting).expandTriggerFlag = expandTriggerFlag; + view.expandCollapseNode(setting, node, expandFlag, animateFlag, callback ); + }, + isSelectedNode: function (setting, node) { + if (!node) { + return false; + } + var list = data.getRoot(setting).curSelectedList, + i; + for (i = list.length - 1; i >= 0; i--) { + if (node === list[i]) { + return true; + } + } + return false; + }, + makeDOMNodeIcon: function (html, setting, node) { + var nameStr = data.getNodeName(setting, node), + name = setting.view.nameIsHTML ? nameStr : nameStr.replace(/&/g, "&").replace(//g, ">"); + html.push("", name, ""); + }, + makeDOMNodeLine: function (html, setting, node) { + html.push(""); + }, + makeDOMNodeMainAfter: function (html, setting, node) { + html.push("
  • "); + }, + makeDOMNodeMainBefore: function (html, setting, node) { + html.push("
  • "); + }, + makeDOMNodeNameAfter: function (html, setting, node) { + html.push(""); + }, + makeDOMNodeNameBefore: function (html, setting, node) { + var title = data.getNodeTitle(setting, node), + url = view.makeNodeUrl(setting, node), + fontcss = view.makeNodeFontCss(setting, node), + fontStyle = []; + for (var f in fontcss) { + fontStyle.push(f, ":", fontcss[f], ";"); + } + html.push(" 0) ? "href='" + url + "'" : ""), " target='", view.makeNodeTarget(node), "' style='", fontStyle.join(""), + "'"); + if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle) && title) {html.push("title='", title.replace(/'/g, "'").replace(//g, ">"), "'");} + html.push(">"); + }, + makeNodeFontCss: function (setting, node) { + var fontCss = tools.apply(setting.view.fontCss, [setting.treeId, node], setting.view.fontCss); + return (fontCss && ((typeof fontCss) !== "function")) ? fontCss : {}; + }, + makeNodeIcoClass: function (setting, node) { + var icoCss = ["ico"]; + if (!node.isAjaxing) { + icoCss[0] = (node.iconSkin ? node.iconSkin + "_" : "") + icoCss[0]; + if (node.isParent) { + icoCss.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); + } else { + icoCss.push(consts.folder.DOCU); + } + } + return consts.className.BUTTON + " " + icoCss.join("_"); + }, + makeNodeIcoStyle: function (setting, node) { + var icoStyle = []; + if (!node.isAjaxing) { + var icon = (node.isParent && node.iconOpen && node.iconClose) ? (node.open ? node.iconOpen : node.iconClose) : node.icon; + if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;"); + if (setting.view.showIcon == false || !tools.apply(setting.view.showIcon, [setting.treeId, node], true)) { + icoStyle.push("width:0px;height:0px;"); + } + } + return icoStyle.join(""); + }, + makeNodeLineClass: function (setting, node) { + var lineClass = []; + if (setting.view.showLine) { + if (node.level == 0 && node.isFirstNode && node.isLastNode) { + lineClass.push(consts.line.ROOT); + } else if (node.level == 0 && node.isFirstNode) { + lineClass.push(consts.line.ROOTS); + } else if (node.isLastNode) { + lineClass.push(consts.line.BOTTOM); + } else { + lineClass.push(consts.line.CENTER); + } + } else { + lineClass.push(consts.line.NOLINE); + } + if (node.isParent) { + lineClass.push(node.open ? consts.folder.OPEN : consts.folder.CLOSE); + } else { + lineClass.push(consts.folder.DOCU); + } + return view.makeNodeLineClassEx(node) + lineClass.join("_"); + }, + makeNodeLineClassEx: function (node) { + return consts.className.BUTTON + " " + consts.className.LEVEL + node.level + " " + consts.className.SWITCH + " "; + }, + makeNodeTarget: function (node) { + return (node.target || "_blank"); + }, + makeNodeUrl: function (setting, node) { + var urlKey = setting.data.key.url; + return node[urlKey] ? node[urlKey] : null; + }, + makeUlHtml: function (setting, node, html, content) { + html.push("
      "); + html.push(content); + html.push("
    "); + }, + makeUlLineClass: function (setting, node) { + return ((setting.view.showLine && !node.isLastNode) ? consts.line.LINE : ""); + }, + removeChildNodes: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children, + nodes = node[childKey]; + if (!nodes) return; - for (var i = 0, l = nodes.length; i < l; i++) { - data.removeNodeCache(setting, nodes[i]); - } - data.removeSelectedNode(setting); - delete node[childKey]; + for (var i = 0, l = nodes.length; i < l; i++) { + data.removeNodeCache(setting, nodes[i]); + } + data.removeSelectedNode(setting); + delete node[childKey]; - if (!setting.data.keep.parent) { - node.isParent = false; - node.open = false; - var tmp_switchObj = $$(node, consts.id.SWITCH, setting), - tmp_icoObj = $$(node, consts.id.ICON, setting); - view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU); - view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU); - $$(node, consts.id.UL, setting).remove(); - } else { - $$(node, consts.id.UL, setting).empty(); - } - }, - setFirstNode: function(setting, parentNode) { - var childKey = setting.data.key.children, childLength = parentNode[childKey].length; - if ( childLength > 0) { - parentNode[childKey][0].isFirstNode = true; - } - }, - setLastNode: function(setting, parentNode) { - var childKey = setting.data.key.children, childLength = parentNode[childKey].length; - if ( childLength > 0) { - parentNode[childKey][childLength - 1].isLastNode = true; - } - }, - removeNode: function(setting, node) { - var root = data.getRoot(setting), - childKey = setting.data.key.children, - parentNode = (node.parentTId) ? node.getParentNode() : root; + if (!setting.data.keep.parent) { + node.isParent = false; + node.open = false; + var tmp_switchObj = $$(node, consts.id.SWITCH, setting), + tmp_icoObj = $$(node, consts.id.ICON, setting); + view.replaceSwitchClass(node, tmp_switchObj, consts.folder.DOCU); + view.replaceIcoClass(node, tmp_icoObj, consts.folder.DOCU); + $$(node, consts.id.UL, setting).remove(); + } else { + $$(node, consts.id.UL, setting).empty(); + } + }, + setFirstNode: function (setting, parentNode) { + var childKey = setting.data.key.children, childLength = parentNode[childKey].length; + if ( childLength > 0) { + parentNode[childKey][0].isFirstNode = true; + } + }, + setLastNode: function (setting, parentNode) { + var childKey = setting.data.key.children, childLength = parentNode[childKey].length; + if ( childLength > 0) { + parentNode[childKey][childLength - 1].isLastNode = true; + } + }, + removeNode: function (setting, node) { + var root = data.getRoot(setting), + childKey = setting.data.key.children, + parentNode = (node.parentTId) ? node.getParentNode() : root; - node.isFirstNode = false; - node.isLastNode = false; - node.getPreNode = function() {return null;}; - node.getNextNode = function() {return null;}; + node.isFirstNode = false; + node.isLastNode = false; + node.getPreNode = function () {return null;}; + node.getNextNode = function () {return null;}; - if (!data.getNodeCache(setting, node.tId)) { - return; - } + if (!data.getNodeCache(setting, node.tId)) { + return; + } - $$(node, setting).remove(); - data.removeNodeCache(setting, node); - data.removeSelectedNode(setting, node); + $$(node, setting).remove(); + data.removeNodeCache(setting, node); + data.removeSelectedNode(setting, node); - for (var i = 0, l = parentNode[childKey].length; i < l; i++) { - if (parentNode[childKey][i].tId == node.tId) { - parentNode[childKey].splice(i, 1); - break; - } - } - view.setFirstNode(setting, parentNode); - view.setLastNode(setting, parentNode); + for (var i = 0, l = parentNode[childKey].length; i < l; i++) { + if (parentNode[childKey][i].tId == node.tId) { + parentNode[childKey].splice(i, 1); + break; + } + } + view.setFirstNode(setting, parentNode); + view.setLastNode(setting, parentNode); - var tmp_ulObj,tmp_switchObj,tmp_icoObj, - childLength = parentNode[childKey].length; + var tmp_ulObj, tmp_switchObj, tmp_icoObj, + childLength = parentNode[childKey].length; - //repair nodes old parent - if (!setting.data.keep.parent && childLength == 0) { - //old parentNode has no child nodes - parentNode.isParent = false; - parentNode.open = false; - tmp_ulObj = $$(parentNode, consts.id.UL, setting); - tmp_switchObj = $$(parentNode, consts.id.SWITCH, setting); - tmp_icoObj = $$(parentNode, consts.id.ICON, setting); - view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU); - view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU); - tmp_ulObj.css("display", "none"); + // repair nodes old parent + if (!setting.data.keep.parent && childLength == 0) { + // old parentNode has no child nodes + parentNode.isParent = false; + parentNode.open = false; + tmp_ulObj = $$(parentNode, consts.id.UL, setting); + tmp_switchObj = $$(parentNode, consts.id.SWITCH, setting); + tmp_icoObj = $$(parentNode, consts.id.ICON, setting); + view.replaceSwitchClass(parentNode, tmp_switchObj, consts.folder.DOCU); + view.replaceIcoClass(parentNode, tmp_icoObj, consts.folder.DOCU); + tmp_ulObj.css("display", "none"); - } else if (setting.view.showLine && childLength > 0) { - //old parentNode has child nodes - var newLast = parentNode[childKey][childLength - 1]; - tmp_ulObj = $$(newLast, consts.id.UL, setting); - tmp_switchObj = $$(newLast, consts.id.SWITCH, setting); - tmp_icoObj = $$(newLast, consts.id.ICON, setting); - if (parentNode == root) { - if (parentNode[childKey].length == 1) { - //node was root, and ztree has only one root after move node - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT); - } else { - var tmp_first_switchObj = $$(parentNode[childKey][0], consts.id.SWITCH, setting); - view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS); - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); - } - } else { - view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); - } - tmp_ulObj.removeClass(consts.line.LINE); - } - }, - replaceIcoClass: function(node, obj, newName) { - if (!obj || node.isAjaxing) return; - var tmpName = obj.attr("class"); - if (tmpName == undefined) return; - var tmpList = tmpName.split("_"); - switch (newName) { - case consts.folder.OPEN: - case consts.folder.CLOSE: - case consts.folder.DOCU: - tmpList[tmpList.length-1] = newName; - break; - } - obj.attr("class", tmpList.join("_")); - }, - replaceSwitchClass: function(node, obj, newName) { - if (!obj) return; - var tmpName = obj.attr("class"); - if (tmpName == undefined) return; - var tmpList = tmpName.split("_"); - switch (newName) { - case consts.line.ROOT: - case consts.line.ROOTS: - case consts.line.CENTER: - case consts.line.BOTTOM: - case consts.line.NOLINE: - tmpList[0] = view.makeNodeLineClassEx(node) + newName; - break; - case consts.folder.OPEN: - case consts.folder.CLOSE: - case consts.folder.DOCU: - tmpList[1] = newName; - break; - } - obj.attr("class", tmpList.join("_")); - if (newName !== consts.folder.DOCU) { - obj.removeAttr("disabled"); - } else { - obj.attr("disabled", "disabled"); - } - }, - selectNode: function(setting, node, addFlag) { - if (!addFlag) { - view.cancelPreSelectedNode(setting, null, node); - } - $$(node, consts.id.A, setting).addClass(consts.node.CURSELECTED); - data.addSelectedNode(setting, node); - setting.treeObj.trigger(consts.event.SELECTED, [event, setting.treeId, node]); - }, - setNodeFontCss: function(setting, treeNode) { - var aObj = $$(treeNode, consts.id.A, setting), - fontCss = view.makeNodeFontCss(setting, treeNode); - if (fontCss) { - aObj.css(fontCss); - } - }, - setNodeLineIcos: function(setting, node) { - if (!node) return; - var switchObj = $$(node, consts.id.SWITCH, setting), - ulObj = $$(node, consts.id.UL, setting), - icoObj = $$(node, consts.id.ICON, setting), - ulLine = view.makeUlLineClass(setting, node); - if (ulLine.length==0) { - ulObj.removeClass(consts.line.LINE); - } else { - ulObj.addClass(ulLine); - } - switchObj.attr("class", view.makeNodeLineClass(setting, node)); - if (node.isParent) { - switchObj.removeAttr("disabled"); - } else { - switchObj.attr("disabled", "disabled"); - } - icoObj.removeAttr("style"); - icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); - icoObj.attr("class", view.makeNodeIcoClass(setting, node)); - }, - setNodeName: function(setting, node) { - var title = data.getNodeTitle(setting, node), - nObj = $$(node, consts.id.SPAN, setting); - nObj.empty(); - if (setting.view.nameIsHTML) { - nObj.html(data.getNodeName(setting, node)); - } else { - nObj.text(data.getNodeName(setting, node)); - } - if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle)) { - var aObj = $$(node, consts.id.A, setting); - aObj.attr("title", !title ? "" : title); - } - }, - setNodeTarget: function(setting, node) { - var aObj = $$(node, consts.id.A, setting); - aObj.attr("target", view.makeNodeTarget(node)); - }, - setNodeUrl: function(setting, node) { - var aObj = $$(node, consts.id.A, setting), - url = view.makeNodeUrl(setting, node); - if (url == null || url.length == 0) { - aObj.removeAttr("href"); - } else { - aObj.attr("href", url); - } - }, - switchNode: function(setting, node) { - if (node.open || !tools.canAsync(setting, node)) { - view.expandCollapseNode(setting, node, !node.open); - } else if (setting.async.enable) { - if (!view.asyncNode(setting, node)) { - view.expandCollapseNode(setting, node, !node.open); - return; - } - } else if (node) { - view.expandCollapseNode(setting, node, !node.open); - } - } - }; - // zTree defind - $.fn.zTree = { - consts : _consts, - _z : { - tools: tools, - view: view, - event: event, - data: data - }, - getZTreeObj: function(treeId) { - var o = data.getZTreeTools(treeId); - return o ? o : null; - }, - destroy: function(treeId) { - if (!!treeId && treeId.length > 0) { - view.destroy(data.getSetting(treeId)); - } else { - for(var s in settings) { - view.destroy(settings[s]); - } - } - }, - init: function(obj, zSetting, zNodes) { - var setting = tools.clone(_setting); - $.extend(true, setting, zSetting); - setting.treeId = obj.attr("id"); - setting.treeObj = obj; - setting.treeObj.empty(); - settings[setting.treeId] = setting; - //For some older browser,(e.g., ie6) - if(typeof document.body.style.maxHeight === "undefined") { - setting.view.expandSpeed = ""; - } - data.initRoot(setting); - var root = data.getRoot(setting), - childKey = setting.data.key.children; - zNodes = zNodes ? tools.clone(tools.isArray(zNodes)? zNodes : [zNodes]) : []; - if (setting.data.simpleData.enable) { - root[childKey] = data.transformTozTreeFormat(setting, zNodes); - } else { - root[childKey] = zNodes; - } + } else if (setting.view.showLine && childLength > 0) { + // old parentNode has child nodes + var newLast = parentNode[childKey][childLength - 1]; + tmp_ulObj = $$(newLast, consts.id.UL, setting); + tmp_switchObj = $$(newLast, consts.id.SWITCH, setting); + tmp_icoObj = $$(newLast, consts.id.ICON, setting); + if (parentNode == root) { + if (parentNode[childKey].length == 1) { + // node was root, and ztree has only one root after move node + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.ROOT); + } else { + var tmp_first_switchObj = $$(parentNode[childKey][0], consts.id.SWITCH, setting); + view.replaceSwitchClass(parentNode[childKey][0], tmp_first_switchObj, consts.line.ROOTS); + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); + } + } else { + view.replaceSwitchClass(newLast, tmp_switchObj, consts.line.BOTTOM); + } + tmp_ulObj.removeClass(consts.line.LINE); + } + }, + replaceIcoClass: function (node, obj, newName) { + if (!obj || node.isAjaxing) return; + var tmpName = obj.attr("class"); + if (tmpName == undefined) return; + var tmpList = tmpName.split("_"); + switch (newName) { + case consts.folder.OPEN: + case consts.folder.CLOSE: + case consts.folder.DOCU: + tmpList[tmpList.length - 1] = newName; + break; + } + obj.attr("class", tmpList.join("_")); + }, + replaceSwitchClass: function (node, obj, newName) { + if (!obj) return; + var tmpName = obj.attr("class"); + if (tmpName == undefined) return; + var tmpList = tmpName.split("_"); + switch (newName) { + case consts.line.ROOT: + case consts.line.ROOTS: + case consts.line.CENTER: + case consts.line.BOTTOM: + case consts.line.NOLINE: + tmpList[0] = view.makeNodeLineClassEx(node) + newName; + break; + case consts.folder.OPEN: + case consts.folder.CLOSE: + case consts.folder.DOCU: + tmpList[1] = newName; + break; + } + obj.attr("class", tmpList.join("_")); + if (newName !== consts.folder.DOCU) { + obj.removeAttr("disabled"); + } else { + obj.attr("disabled", "disabled"); + } + }, + selectNode: function (setting, node, addFlag) { + if (!addFlag) { + view.cancelPreSelectedNode(setting, null, node); + } + $$(node, consts.id.A, setting).addClass(consts.node.CURSELECTED); + data.addSelectedNode(setting, node); + setting.treeObj.trigger(consts.event.SELECTED, [event, setting.treeId, node]); + }, + setNodeFontCss: function (setting, treeNode) { + var aObj = $$(treeNode, consts.id.A, setting), + fontCss = view.makeNodeFontCss(setting, treeNode); + if (fontCss) { + aObj.css(fontCss); + } + }, + setNodeLineIcos: function (setting, node) { + if (!node) return; + var switchObj = $$(node, consts.id.SWITCH, setting), + ulObj = $$(node, consts.id.UL, setting), + icoObj = $$(node, consts.id.ICON, setting), + ulLine = view.makeUlLineClass(setting, node); + if (ulLine.length == 0) { + ulObj.removeClass(consts.line.LINE); + } else { + ulObj.addClass(ulLine); + } + switchObj.attr("class", view.makeNodeLineClass(setting, node)); + if (node.isParent) { + switchObj.removeAttr("disabled"); + } else { + switchObj.attr("disabled", "disabled"); + } + icoObj.removeAttr("style"); + icoObj.attr("style", view.makeNodeIcoStyle(setting, node)); + icoObj.attr("class", view.makeNodeIcoClass(setting, node)); + }, + setNodeName: function (setting, node) { + var title = data.getNodeTitle(setting, node), + nObj = $$(node, consts.id.SPAN, setting); + nObj.empty(); + if (setting.view.nameIsHTML) { + nObj.html(data.getNodeName(setting, node)); + } else { + nObj.text(data.getNodeName(setting, node)); + } + if (tools.apply(setting.view.showTitle, [setting.treeId, node], setting.view.showTitle)) { + var aObj = $$(node, consts.id.A, setting); + aObj.attr("title", !title ? "" : title); + } + }, + setNodeTarget: function (setting, node) { + var aObj = $$(node, consts.id.A, setting); + aObj.attr("target", view.makeNodeTarget(node)); + }, + setNodeUrl: function (setting, node) { + var aObj = $$(node, consts.id.A, setting), + url = view.makeNodeUrl(setting, node); + if (url == null || url.length == 0) { + aObj.removeAttr("href"); + } else { + aObj.attr("href", url); + } + }, + switchNode: function (setting, node) { + if (node.open || !tools.canAsync(setting, node)) { + view.expandCollapseNode(setting, node, !node.open); + } else if (setting.async.enable) { + if (!view.asyncNode(setting, node)) { + view.expandCollapseNode(setting, node, !node.open); + return; + } + } else if (node) { + view.expandCollapseNode(setting, node, !node.open); + } + } + }; + // zTree defind + $.fn.zTree = { + consts: _consts, + _z: { + tools: tools, + view: view, + event: event, + data: data + }, + getZTreeObj: function (treeId) { + var o = data.getZTreeTools(treeId); + return o ? o : null; + }, + destroy: function (treeId) { + if (!!treeId && treeId.length > 0) { + view.destroy(data.getSetting(treeId)); + } else { + for(var s in settings) { + view.destroy(settings[s]); + } + } + }, + init: function (obj, zSetting, zNodes) { + var setting = tools.clone(_setting); + $.extend(true, setting, zSetting); + setting.treeId = obj.attr("id"); + setting.treeObj = obj; + setting.treeObj.empty(); + settings[setting.treeId] = setting; + // For some older browser,(e.g., ie6) + if(typeof document.body.style.maxHeight === "undefined") { + setting.view.expandSpeed = ""; + } + data.initRoot(setting); + var root = data.getRoot(setting), + childKey = setting.data.key.children; + zNodes = zNodes ? tools.clone(tools.isArray(zNodes) ? zNodes : [zNodes]) : []; + if (setting.data.simpleData.enable) { + root[childKey] = data.transformTozTreeFormat(setting, zNodes); + } else { + root[childKey] = zNodes; + } - data.initCache(setting); - event.unbindTree(setting); - event.bindTree(setting); - event.unbindEvent(setting); - event.bindEvent(setting); + data.initCache(setting); + event.unbindTree(setting); + event.bindTree(setting); + event.unbindEvent(setting); + event.bindEvent(setting); - var zTreeTools = { - setting : setting, - addNodes : function(parentNode, newNodes, isSilent) { - if (!newNodes) return null; - if (!parentNode) parentNode = null; - if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null; - var xNewNodes = tools.clone(tools.isArray(newNodes)? newNodes: [newNodes]); - function addCallback() { - view.addNodes(setting, parentNode, xNewNodes, (isSilent==true)); - } + var zTreeTools = { + setting: setting, + addNodes: function (parentNode, newNodes, isSilent) { + if (!newNodes) return null; + if (!parentNode) parentNode = null; + if (parentNode && !parentNode.isParent && setting.data.keep.leaf) return null; + var xNewNodes = tools.clone(tools.isArray(newNodes) ? newNodes : [newNodes]); + function addCallback () { + view.addNodes(setting, parentNode, xNewNodes, (isSilent == true)); + } - if (tools.canAsync(setting, parentNode)) { - view.asyncNode(setting, parentNode, isSilent, addCallback); - } else { - addCallback(); - } - return xNewNodes; - }, - cancelSelectedNode : function(node) { - view.cancelPreSelectedNode(setting, node); - }, - destroy : function() { - view.destroy(setting); - }, - expandAll : function(expandFlag) { - expandFlag = !!expandFlag; - view.expandCollapseSonNode(setting, null, expandFlag, true); - return expandFlag; - }, - expandNode : function(node, expandFlag, sonSign, focus, callbackFlag) { - if (!node || !node.isParent) return null; - if (expandFlag !== true && expandFlag !== false) { - expandFlag = !node.open; - } - callbackFlag = !!callbackFlag; + if (tools.canAsync(setting, parentNode)) { + view.asyncNode(setting, parentNode, isSilent, addCallback); + } else { + addCallback(); + } + return xNewNodes; + }, + cancelSelectedNode: function (node) { + view.cancelPreSelectedNode(setting, node); + }, + destroy: function () { + view.destroy(setting); + }, + expandAll: function (expandFlag) { + expandFlag = !!expandFlag; + view.expandCollapseSonNode(setting, null, expandFlag, true); + return expandFlag; + }, + expandNode: function (node, expandFlag, sonSign, focus, callbackFlag) { + if (!node || !node.isParent) return null; + if (expandFlag !== true && expandFlag !== false) { + expandFlag = !node.open; + } + callbackFlag = !!callbackFlag; - if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) { - return null; - } else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) { - return null; - } - if (expandFlag && node.parentTId) { - view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, false); - } - if (expandFlag === node.open && !sonSign) { - return null; - } + if (callbackFlag && expandFlag && (tools.apply(setting.callback.beforeExpand, [setting.treeId, node], true) == false)) { + return null; + } else if (callbackFlag && !expandFlag && (tools.apply(setting.callback.beforeCollapse, [setting.treeId, node], true) == false)) { + return null; + } + if (expandFlag && node.parentTId) { + view.expandCollapseParentNode(setting, node.getParentNode(), expandFlag, false); + } + if (expandFlag === node.open && !sonSign) { + return null; + } - data.getRoot(setting).expandTriggerFlag = callbackFlag; - if (!tools.canAsync(setting, node) && sonSign) { - view.expandCollapseSonNode(setting, node, expandFlag, true, function() { - if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e){}} - }); - } else { - node.open = !expandFlag; - view.switchNode(this.setting, node); - if (focus !== false) {try{$$(node, setting).focus().blur();}catch(e){}} - } - return expandFlag; - }, - getNodes : function() { - return data.getNodes(setting); - }, - getNodeByParam : function(key, value, parentNode) { - if (!key) return null; - return data.getNodeByParam(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodeByTId : function(tId) { - return data.getNodeCache(setting, tId); - }, - getNodesByParam : function(key, value, parentNode) { - if (!key) return null; - return data.getNodesByParam(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodesByParamFuzzy : function(key, value, parentNode) { - if (!key) return null; - return data.getNodesByParamFuzzy(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), key, value); - }, - getNodesByFilter: function(filter, isSingle, parentNode, invokeParam) { - isSingle = !!isSingle; - if (!filter || (typeof filter != "function")) return (isSingle ? null : []); - return data.getNodesByFilter(setting, parentNode?parentNode[setting.data.key.children]:data.getNodes(setting), filter, isSingle, invokeParam); - }, - getNodeIndex : function(node) { - if (!node) return null; - var childKey = setting.data.key.children, - parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); - for (var i=0, l = parentNode[childKey].length; i < l; i++) { - if (parentNode[childKey][i] == node) return i; - } - return -1; - }, - getSelectedNodes : function() { - var r = [], list = data.getRoot(setting).curSelectedList; - for (var i=0, l=list.length; i 0) { - view.createNodes(setting, 0, root[childKey]); - } else if (setting.async.enable && setting.async.url && setting.async.url !== '') { - view.asyncNode(setting); - } - return zTreeTools; - } - }; + if (root[childKey] && root[childKey].length > 0) { + view.createNodes(setting, 0, root[childKey]); + } else if (setting.async.enable && setting.async.url && setting.async.url !== "") { + view.asyncNode(setting); + } + return zTreeTools; + } + }; - var zt = $.fn.zTree, - $$ = tools.$, - consts = zt.consts; + var zt = $.fn.zTree, + $$ = tools.$, + consts = zt.consts; })(jQuery); \ No newline at end of file diff --git a/src/base/tree/ztree/jquery.ztree.excheck-3.5.js b/src/base/tree/ztree/jquery.ztree.excheck-3.5.js index 1a2774bca..696bbfdaf 100644 --- a/src/base/tree/ztree/jquery.ztree.excheck-3.5.js +++ b/src/base/tree/ztree/jquery.ztree.excheck-3.5.js @@ -10,619 +10,619 @@ * email: hunter.z@263.net * Date: 2015-06-18 */ -(function($){ - //default consts of excheck - var _consts = { - event: { - CHECK: "ztree_check" - }, - id: { - CHECK: "_check" - }, - checkbox: { - STYLE: "checkbox", - DEFAULT: "chk", - DISABLED: "disable", - FALSE: "false", - TRUE: "true", - FULL: "full", - PART: "part", - FOCUS: "focus" - }, - radio: { - STYLE: "radio", - TYPE_ALL: "all", - TYPE_LEVEL: "level" - } - }, - //default setting of excheck - _setting = { - check: { - enable: false, - autoCheckTrigger: false, - chkStyle: _consts.checkbox.STYLE, - nocheckInherit: false, - chkDisabledInherit: false, - radioType: _consts.radio.TYPE_LEVEL, - chkboxType: { - "Y": "ps", - "N": "ps" - } - }, - data: { - key: { - checked: "checked" - } - }, - callback: { - beforeCheck:null, - onCheck:null - } - }, - //default root of excheck - _initRoot = function (setting) { - var r = data.getRoot(setting); - r.radioCheckedList = []; - }, - //default cache of excheck - _initCache = function(treeId) {}, - //default bind event of excheck - _bindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.bind(c.CHECK, function (event, srcEvent, treeId, node) { - event.srcEvent = srcEvent; - tools.apply(setting.callback.onCheck, [event, treeId, node]); - }); - }, - _unbindEvent = function(setting) { - var o = setting.treeObj, - c = consts.event; - o.unbind(c.CHECK); - }, - //default event proxy of excheck - _eventProxy = function(e) { - var target = e.target, - setting = data.getSetting(e.data.treeId), - tId = "", node = null, - nodeEventType = "", treeEventType = "", - nodeEventCallback = null, treeEventCallback = null; +(function ($) { + // default consts of excheck + var _consts = { + event: { + CHECK: "ztree_check" + }, + id: { + CHECK: "_check" + }, + checkbox: { + STYLE: "checkbox", + DEFAULT: "chk", + DISABLED: "disable", + FALSE: "false", + TRUE: "true", + FULL: "full", + PART: "part", + FOCUS: "focus" + }, + radio: { + STYLE: "radio", + TYPE_ALL: "all", + TYPE_LEVEL: "level" + } + }, + // default setting of excheck + _setting = { + check: { + enable: false, + autoCheckTrigger: false, + chkStyle: _consts.checkbox.STYLE, + nocheckInherit: false, + chkDisabledInherit: false, + radioType: _consts.radio.TYPE_LEVEL, + chkboxType: { + Y: "ps", + N: "ps" + } + }, + data: { + key: { + checked: "checked" + } + }, + callback: { + beforeCheck: null, + onCheck: null + } + }, + // default root of excheck + _initRoot = function (setting) { + var r = data.getRoot(setting); + r.radioCheckedList = []; + }, + // default cache of excheck + _initCache = function (treeId) {}, + // default bind event of excheck + _bindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.bind(c.CHECK, function (event, srcEvent, treeId, node) { + event.srcEvent = srcEvent; + tools.apply(setting.callback.onCheck, [event, treeId, node]); + }); + }, + _unbindEvent = function (setting) { + var o = setting.treeObj, + c = consts.event; + o.unbind(c.CHECK); + }, + // default event proxy of excheck + _eventProxy = function (e) { + var target = e.target, + setting = data.getSetting(e.data.treeId), + tId = "", node = null, + nodeEventType = "", treeEventType = "", + nodeEventCallback = null, treeEventCallback = null; - if (tools.eqs(e.type, "mouseover")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "mouseoverCheck"; - } - } else if (tools.eqs(e.type, "mouseout")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "mouseoutCheck"; - } - } else if (tools.eqs(e.type, "click")) { - if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode"+ consts.id.CHECK) !== null) { - tId = tools.getNodeMainDom(target).id; - nodeEventType = "checkNode"; - } - } - if (tId.length>0) { - node = data.getNodeCache(setting, tId); - switch (nodeEventType) { - case "checkNode" : - nodeEventCallback = _handler.onCheckNode; - break; - case "mouseoverCheck" : - nodeEventCallback = _handler.onMouseoverCheck; - break; - case "mouseoutCheck" : - nodeEventCallback = _handler.onMouseoutCheck; - break; - } - } - var proxyResult = { - stop: nodeEventType === "checkNode", - node: node, - nodeEventType: nodeEventType, - nodeEventCallback: nodeEventCallback, - treeEventType: treeEventType, - treeEventCallback: treeEventCallback - }; - return proxyResult - }, - //default init node of excheck - _initNode = function(setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { - if (!n) return; - var checkedKey = setting.data.key.checked; - if (typeof n[checkedKey] == "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); - n[checkedKey] = !!n[checkedKey]; - n.checkedOld = n[checkedKey]; - if (typeof n.nocheck == "string") n.nocheck = tools.eqs(n.nocheck, "true"); - n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); - if (typeof n.chkDisabled == "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); - n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); - if (typeof n.halfCheck == "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); - n.halfCheck = !!n.halfCheck; - n.check_Child_State = -1; - n.check_Focus = false; - n.getCheckStatus = function() {return data.getCheckStatus(setting, n);}; + if (tools.eqs(e.type, "mouseover")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "mouseoverCheck"; + } + } else if (tools.eqs(e.type, "mouseout")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "mouseoutCheck"; + } + } else if (tools.eqs(e.type, "click")) { + if (setting.check.enable && tools.eqs(target.tagName, "span") && target.getAttribute("treeNode" + consts.id.CHECK) !== null) { + tId = tools.getNodeMainDom(target).id; + nodeEventType = "checkNode"; + } + } + if (tId.length > 0) { + node = data.getNodeCache(setting, tId); + switch (nodeEventType) { + case "checkNode" : + nodeEventCallback = _handler.onCheckNode; + break; + case "mouseoverCheck" : + nodeEventCallback = _handler.onMouseoverCheck; + break; + case "mouseoutCheck" : + nodeEventCallback = _handler.onMouseoutCheck; + break; + } + } + var proxyResult = { + stop: nodeEventType === "checkNode", + node: node, + nodeEventType: nodeEventType, + nodeEventCallback: nodeEventCallback, + treeEventType: treeEventType, + treeEventCallback: treeEventCallback + }; + return proxyResult; + }, + // default init node of excheck + _initNode = function (setting, level, n, parentNode, isFirstNode, isLastNode, openFlag) { + if (!n) return; + var checkedKey = setting.data.key.checked; + if (typeof n[checkedKey] === "string") n[checkedKey] = tools.eqs(n[checkedKey], "true"); + n[checkedKey] = !!n[checkedKey]; + n.checkedOld = n[checkedKey]; + if (typeof n.nocheck === "string") n.nocheck = tools.eqs(n.nocheck, "true"); + n.nocheck = !!n.nocheck || (setting.check.nocheckInherit && parentNode && !!parentNode.nocheck); + if (typeof n.chkDisabled === "string") n.chkDisabled = tools.eqs(n.chkDisabled, "true"); + n.chkDisabled = !!n.chkDisabled || (setting.check.chkDisabledInherit && parentNode && !!parentNode.chkDisabled); + if (typeof n.halfCheck === "string") n.halfCheck = tools.eqs(n.halfCheck, "true"); + n.halfCheck = !!n.halfCheck; + n.check_Child_State = -1; + n.check_Focus = false; + n.getCheckStatus = function () {return data.getCheckStatus(setting, n);}; - if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey] ) { - var r = data.getRoot(setting); - r.radioCheckedList.push(n); - } - }, - //add dom for check - _beforeA = function(setting, node, html) { - var checkedKey = setting.data.key.checked; - if (setting.check.enable) { - data.makeChkFlag(setting, node); - html.push(""); - } - }, - //update zTreeObj, add method of check - _zTreeTools = function(setting, zTreeTools) { - zTreeTools.checkNode = function(node, checked, checkTypeFlag, callbackFlag) { - var checkedKey = this.setting.data.key.checked; - if (node.chkDisabled === true) return; - if (checked !== true && checked !== false) { - checked = !node[checkedKey]; - } - callbackFlag = !!callbackFlag; + if (setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL && n[checkedKey] ) { + var r = data.getRoot(setting); + r.radioCheckedList.push(n); + } + }, + // add dom for check + _beforeA = function (setting, node, html) { + var checkedKey = setting.data.key.checked; + if (setting.check.enable) { + data.makeChkFlag(setting, node); + html.push(""); + } + }, + // update zTreeObj, add method of check + _zTreeTools = function (setting, zTreeTools) { + zTreeTools.checkNode = function (node, checked, checkTypeFlag, callbackFlag) { + var checkedKey = this.setting.data.key.checked; + if (node.chkDisabled === true) return; + if (checked !== true && checked !== false) { + checked = !node[checkedKey]; + } + callbackFlag = !!callbackFlag; - if (node[checkedKey] === checked && !checkTypeFlag) { - return; - } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { - return; - } - if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { - node[checkedKey] = checked; - var checkObj = $$(node, consts.id.CHECK, this.setting); - if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); - view.setChkClass(this.setting, checkObj, node); - view.repairParentChkClassWithSelf(this.setting, node); - if (callbackFlag) { - this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); - } - } - } + if (node[checkedKey] === checked && !checkTypeFlag) { + return; + } else if (callbackFlag && tools.apply(this.setting.callback.beforeCheck, [this.setting.treeId, node], true) == false) { + return; + } + if (tools.uCanDo(this.setting) && this.setting.check.enable && node.nocheck !== true) { + node[checkedKey] = checked; + var checkObj = $$(node, consts.id.CHECK, this.setting); + if (checkTypeFlag || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); + view.setChkClass(this.setting, checkObj, node); + view.repairParentChkClassWithSelf(this.setting, node); + if (callbackFlag) { + this.setting.treeObj.trigger(consts.event.CHECK, [null, this.setting.treeId, node]); + } + } + }; - zTreeTools.checkAllNodes = function(checked) { - view.repairAllChk(this.setting, !!checked); - } + zTreeTools.checkAllNodes = function (checked) { + view.repairAllChk(this.setting, !!checked); + }; - zTreeTools.getCheckedNodes = function(checked) { - var childKey = this.setting.data.key.children; - checked = (checked !== false); - return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); - } + zTreeTools.getCheckedNodes = function (checked) { + var childKey = this.setting.data.key.children; + checked = (checked !== false); + return data.getTreeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey], checked); + }; - zTreeTools.getChangeCheckedNodes = function() { - var childKey = this.setting.data.key.children; - return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); - } + zTreeTools.getChangeCheckedNodes = function () { + var childKey = this.setting.data.key.children; + return data.getTreeChangeCheckedNodes(this.setting, data.getRoot(this.setting)[childKey]); + }; - zTreeTools.setChkDisabled = function(node, disabled, inheritParent, inheritChildren) { - disabled = !!disabled; - inheritParent = !!inheritParent; - inheritChildren = !!inheritChildren; - view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); - view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); - } + zTreeTools.setChkDisabled = function (node, disabled, inheritParent, inheritChildren) { + disabled = !!disabled; + inheritParent = !!inheritParent; + inheritChildren = !!inheritChildren; + view.repairSonChkDisabled(this.setting, node, disabled, inheritChildren); + view.repairParentChkDisabled(this.setting, node.getParentNode(), disabled, inheritParent); + }; - var _updateNode = zTreeTools.updateNode; - zTreeTools.updateNode = function(node, checkTypeFlag) { - if (_updateNode) _updateNode.apply(zTreeTools, arguments); - if (!node || !this.setting.check.enable) return; - var nObj = $$(node, this.setting); - if (nObj.get(0) && tools.uCanDo(this.setting)) { - var checkObj = $$(node, consts.id.CHECK, this.setting); - if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); - view.setChkClass(this.setting, checkObj, node); - view.repairParentChkClassWithSelf(this.setting, node); - } - } - }, - //method of operate data - _data = { - getRadioCheckedList: function(setting) { - var checkedList = data.getRoot(setting).radioCheckedList; - for (var i=0, j=checkedList.length; i -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) - }; - return r; - }, - getTreeCheckedNodes: function(setting, nodes, checked, results) { - if (!nodes) return []; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); - results = !results ? [] : results; - for (var i = 0, l = nodes.length; i < l; i++) { - if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { - results.push(nodes[i]); - if(onlyOne) { - break; - } - } - data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); - if(onlyOne && results.length > 0) { - break; - } - } - return results; - }, - getTreeChangeCheckedNodes: function(setting, nodes, results) { - if (!nodes) return []; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked; - results = !results ? [] : results; - for (var i = 0, l = nodes.length; i < l; i++) { - if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { - results.push(nodes[i]); - } - data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); - } - return results; - }, - makeChkFlag: function(setting, node) { - if (!node) return; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - chkFlag = -1; - if (node[childKey]) { - for (var i = 0, l = node[childKey].length; i < l; i++) { - var cNode = node[childKey][i]; - var tmp = -1; - if (setting.check.chkStyle == consts.radio.STYLE) { - if (cNode.nocheck === true || cNode.chkDisabled === true) { - tmp = cNode.check_Child_State; - } else if (cNode.halfCheck === true) { - tmp = 2; - } else if (cNode[checkedKey]) { - tmp = 2; - } else { - tmp = cNode.check_Child_State > 0 ? 2:0; - } - if (tmp == 2) { - chkFlag = 2; break; - } else if (tmp == 0){ - chkFlag = 0; - } - } else if (setting.check.chkStyle == consts.checkbox.STYLE) { - if (cNode.nocheck === true || cNode.chkDisabled === true) { - tmp = cNode.check_Child_State; - } else if (cNode.halfCheck === true) { - tmp = 1; - } else if (cNode[checkedKey] ) { - tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; - } else { - tmp = (cNode.check_Child_State > 0) ? 1 : 0; - } - if (tmp === 1) { - chkFlag = 1; break; - } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { - chkFlag = 1; break; - } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { - chkFlag = 1; break; - } else if (tmp > -1) { - chkFlag = tmp; - } - } - } - } - node.check_Child_State = chkFlag; - } - }, - //method of event proxy - _event = { + var _updateNode = zTreeTools.updateNode; + zTreeTools.updateNode = function (node, checkTypeFlag) { + if (_updateNode) _updateNode.apply(zTreeTools, arguments); + if (!node || !this.setting.check.enable) return; + var nObj = $$(node, this.setting); + if (nObj.get(0) && tools.uCanDo(this.setting)) { + var checkObj = $$(node, consts.id.CHECK, this.setting); + if (checkTypeFlag == true || this.setting.check.chkStyle === consts.radio.STYLE) view.checkNodeRelation(this.setting, node); + view.setChkClass(this.setting, checkObj, node); + view.repairParentChkClassWithSelf(this.setting, node); + } + }; + }, + // method of operate data + _data = { + getRadioCheckedList: function (setting) { + var checkedList = data.getRoot(setting).radioCheckedList; + for (var i = 0, j = checkedList.length; i < j; i++) { + if(!data.getNodeCache(setting, checkedList[i].tId)) { + checkedList.splice(i, 1); + i--; j--; + } + } + return checkedList; + }, + getCheckStatus: function (setting, node) { + if (!setting.check.enable || node.nocheck || node.chkDisabled) return null; + var checkedKey = setting.data.key.checked, + r = { + checked: node[checkedKey], + half: node.halfCheck ? node.halfCheck : (setting.check.chkStyle == consts.radio.STYLE ? (node.check_Child_State === 2) : (node[checkedKey] ? (node.check_Child_State > -1 && node.check_Child_State < 2) : (node.check_Child_State > 0))) + }; + return r; + }, + getTreeCheckedNodes: function (setting, nodes, checked, results) { + if (!nodes) return []; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + onlyOne = (checked && setting.check.chkStyle == consts.radio.STYLE && setting.check.radioType == consts.radio.TYPE_ALL); + results = !results ? [] : results; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] == checked) { + results.push(nodes[i]); + if(onlyOne) { + break; + } + } + data.getTreeCheckedNodes(setting, nodes[i][childKey], checked, results); + if(onlyOne && results.length > 0) { + break; + } + } + return results; + }, + getTreeChangeCheckedNodes: function (setting, nodes, results) { + if (!nodes) return []; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked; + results = !results ? [] : results; + for (var i = 0, l = nodes.length; i < l; i++) { + if (nodes[i].nocheck !== true && nodes[i].chkDisabled !== true && nodes[i][checkedKey] != nodes[i].checkedOld) { + results.push(nodes[i]); + } + data.getTreeChangeCheckedNodes(setting, nodes[i][childKey], results); + } + return results; + }, + makeChkFlag: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + chkFlag = -1; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + var cNode = node[childKey][i]; + var tmp = -1; + if (setting.check.chkStyle == consts.radio.STYLE) { + if (cNode.nocheck === true || cNode.chkDisabled === true) { + tmp = cNode.check_Child_State; + } else if (cNode.halfCheck === true) { + tmp = 2; + } else if (cNode[checkedKey]) { + tmp = 2; + } else { + tmp = cNode.check_Child_State > 0 ? 2 : 0; + } + if (tmp == 2) { + chkFlag = 2; break; + } else if (tmp == 0) { + chkFlag = 0; + } + } else if (setting.check.chkStyle == consts.checkbox.STYLE) { + if (cNode.nocheck === true || cNode.chkDisabled === true) { + tmp = cNode.check_Child_State; + } else if (cNode.halfCheck === true) { + tmp = 1; + } else if (cNode[checkedKey] ) { + tmp = (cNode.check_Child_State === -1 || cNode.check_Child_State === 2) ? 2 : 1; + } else { + tmp = (cNode.check_Child_State > 0) ? 1 : 0; + } + if (tmp === 1) { + chkFlag = 1; break; + } else if (tmp === 2 && chkFlag > -1 && i > 0 && tmp !== chkFlag) { + chkFlag = 1; break; + } else if (chkFlag === 2 && tmp > -1 && tmp < 2) { + chkFlag = 1; break; + } else if (tmp > -1) { + chkFlag = tmp; + } + } + } + } + node.check_Child_State = chkFlag; + } + }, + // method of event proxy + _event = { - }, - //method of event handler - _handler = { - onCheckNode: function (event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkedKey = setting.data.key.checked; - if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; - node[checkedKey] = !node[checkedKey]; - view.checkNodeRelation(setting, node); - var checkObj = $$(node, consts.id.CHECK, setting); - view.setChkClass(setting, checkObj, node); - view.repairParentChkClassWithSelf(setting, node); - setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); - return true; - }, - onMouseoverCheck: function(event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkObj = $$(node, consts.id.CHECK, setting); - node.check_Focus = true; - view.setChkClass(setting, checkObj, node); - return true; - }, - onMouseoutCheck: function(event, node) { - if (node.chkDisabled === true) return false; - var setting = data.getSetting(event.data.treeId), - checkObj = $$(node, consts.id.CHECK, setting); - node.check_Focus = false; - view.setChkClass(setting, checkObj, node); - return true; - } - }, - //method of tools for zTree - _tools = { + }, + // method of event handler + _handler = { + onCheckNode: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkedKey = setting.data.key.checked; + if (tools.apply(setting.callback.beforeCheck, [setting.treeId, node], true) == false) return true; + node[checkedKey] = !node[checkedKey]; + view.checkNodeRelation(setting, node); + var checkObj = $$(node, consts.id.CHECK, setting); + view.setChkClass(setting, checkObj, node); + view.repairParentChkClassWithSelf(setting, node); + setting.treeObj.trigger(consts.event.CHECK, [event, setting.treeId, node]); + return true; + }, + onMouseoverCheck: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkObj = $$(node, consts.id.CHECK, setting); + node.check_Focus = true; + view.setChkClass(setting, checkObj, node); + return true; + }, + onMouseoutCheck: function (event, node) { + if (node.chkDisabled === true) return false; + var setting = data.getSetting(event.data.treeId), + checkObj = $$(node, consts.id.CHECK, setting); + node.check_Focus = false; + view.setChkClass(setting, checkObj, node); + return true; + } + }, + // method of tools for zTree + _tools = { - }, - //method of operate ztree dom - _view = { - checkNodeRelation: function(setting, node) { - var pNode, i, l, - childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - r = consts.radio; - if (setting.check.chkStyle == r.STYLE) { - var checkedList = data.getRadioCheckedList(setting); - if (node[checkedKey]) { - if (setting.check.radioType == r.TYPE_ALL) { - for (i = checkedList.length-1; i >= 0; i--) { - pNode = checkedList[i]; - if (pNode[checkedKey] && pNode != node) { - pNode[checkedKey] = false; - checkedList.splice(i, 1); + }, + // method of operate ztree dom + _view = { + checkNodeRelation: function (setting, node) { + var pNode, i, l, + childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + r = consts.radio; + if (setting.check.chkStyle == r.STYLE) { + var checkedList = data.getRadioCheckedList(setting); + if (node[checkedKey]) { + if (setting.check.radioType == r.TYPE_ALL) { + for (i = checkedList.length - 1; i >= 0; i--) { + pNode = checkedList[i]; + if (pNode[checkedKey] && pNode != node) { + pNode[checkedKey] = false; + checkedList.splice(i, 1); - view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); - if (pNode.parentTId != node.parentTId) { - view.repairParentChkClassWithSelf(setting, pNode); - } - } - } - checkedList.push(node); - } else { - var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); - for (i = 0, l = parentNode[childKey].length; i < l; i++) { - pNode = parentNode[childKey][i]; - if (pNode[checkedKey] && pNode != node) { - pNode[checkedKey] = false; - view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); - } - } - } - } else if (setting.check.radioType == r.TYPE_ALL) { - for (i = 0, l = checkedList.length; i < l; i++) { - if (node == checkedList[i]) { - checkedList.splice(i, 1); - break; - } - } - } + view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); + if (pNode.parentTId != node.parentTId) { + view.repairParentChkClassWithSelf(setting, pNode); + } + } + } + checkedList.push(node); + } else { + var parentNode = (node.parentTId) ? node.getParentNode() : data.getRoot(setting); + for (i = 0, l = parentNode[childKey].length; i < l; i++) { + pNode = parentNode[childKey][i]; + if (pNode[checkedKey] && pNode != node) { + pNode[checkedKey] = false; + view.setChkClass(setting, $$(pNode, consts.id.CHECK, setting), pNode); + } + } + } + } else if (setting.check.radioType == r.TYPE_ALL) { + for (i = 0, l = checkedList.length; i < l; i++) { + if (node == checkedList[i]) { + checkedList.splice(i, 1); + break; + } + } + } - } else { - if (node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { - view.setSonNodeCheckBox(setting, node, true); - } - if (!node[checkedKey] && (!node[childKey] || node[childKey].length==0 || setting.check.chkboxType.N.indexOf("s") > -1)) { - view.setSonNodeCheckBox(setting, node, false); - } - if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { - view.setParentNodeCheckBox(setting, node, true); - } - if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { - view.setParentNodeCheckBox(setting, node, false); - } - } - }, - makeChkClass: function(setting, node) { - var checkedKey = setting.data.key.checked, - c = consts.checkbox, r = consts.radio, - fullStyle = ""; - if (node.chkDisabled === true) { - fullStyle = c.DISABLED; - } else if (node.halfCheck) { - fullStyle = c.PART; - } else if (setting.check.chkStyle == r.STYLE) { - fullStyle = (node.check_Child_State < 1)? c.FULL:c.PART; - } else { - fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL:c.PART) : ((node.check_Child_State < 1)? c.FULL:c.PART); - } - var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; - chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; - return consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; - }, - repairAllChk: function(setting, checked) { - if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { - var checkedKey = setting.data.key.checked, - childKey = setting.data.key.children, - root = data.getRoot(setting); - for (var i = 0, l = root[childKey].length; i 0) { - view.repairParentChkClass(setting, node[childKey][0]); - } else { - view.repairParentChkClass(setting, node); - } - }, - repairSonChkDisabled: function(setting, node, chkDisabled, inherit) { - if (!node) return; - var childKey = setting.data.key.children; - if (node.chkDisabled != chkDisabled) { - node.chkDisabled = chkDisabled; - } - view.repairChkClass(setting, node); - if (node[childKey] && inherit) { - for (var i = 0, l = node[childKey].length; i < l; i++) { - var sNode = node[childKey][i]; - view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); - } - } - }, - repairParentChkDisabled: function(setting, node, chkDisabled, inherit) { - if (!node) return; - if (node.chkDisabled != chkDisabled && inherit) { - node.chkDisabled = chkDisabled; - } - view.repairChkClass(setting, node); - view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); - }, - setChkClass: function(setting, obj, node) { - if (!obj) return; - if (node.nocheck === true) { - obj.hide(); - } else { - obj.show(); - } - obj.attr('class', view.makeChkClass(setting, node)); - }, - setParentNodeCheckBox: function(setting, node, value, srcNode) { - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - checkObj = $$(node, consts.id.CHECK, setting); - if (!srcNode) srcNode = node; - data.makeChkFlag(setting, node); - if (node.nocheck !== true && node.chkDisabled !== true) { - node[checkedKey] = value; - view.setChkClass(setting, checkObj, node); - if (setting.check.autoCheckTrigger && node != srcNode) { - setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); - } - } - if (node.parentTId) { - var pSign = true; - if (!value) { - var pNodes = node.getParentNode()[childKey]; - for (var i = 0, l = pNodes.length; i < l; i++) { - if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) + } else { + if (node[checkedKey] && (!node[childKey] || node[childKey].length == 0 || setting.check.chkboxType.Y.indexOf("s") > -1)) { + view.setSonNodeCheckBox(setting, node, true); + } + if (!node[checkedKey] && (!node[childKey] || node[childKey].length == 0 || setting.check.chkboxType.N.indexOf("s") > -1)) { + view.setSonNodeCheckBox(setting, node, false); + } + if (node[checkedKey] && setting.check.chkboxType.Y.indexOf("p") > -1) { + view.setParentNodeCheckBox(setting, node, true); + } + if (!node[checkedKey] && setting.check.chkboxType.N.indexOf("p") > -1) { + view.setParentNodeCheckBox(setting, node, false); + } + } + }, + makeChkClass: function (setting, node) { + var checkedKey = setting.data.key.checked, + c = consts.checkbox, r = consts.radio, + fullStyle = ""; + if (node.chkDisabled === true) { + fullStyle = c.DISABLED; + } else if (node.halfCheck) { + fullStyle = c.PART; + } else if (setting.check.chkStyle == r.STYLE) { + fullStyle = (node.check_Child_State < 1) ? c.FULL : c.PART; + } else { + fullStyle = node[checkedKey] ? ((node.check_Child_State === 2 || node.check_Child_State === -1) ? c.FULL : c.PART) : ((node.check_Child_State < 1) ? c.FULL : c.PART); + } + var chkName = setting.check.chkStyle + "_" + (node[checkedKey] ? c.TRUE : c.FALSE) + "_" + fullStyle; + chkName = (node.check_Focus && node.chkDisabled !== true) ? chkName + "_" + c.FOCUS : chkName; + return consts.className.BUTTON + " " + c.DEFAULT + " " + chkName; + }, + repairAllChk: function (setting, checked) { + if (setting.check.enable && setting.check.chkStyle === consts.checkbox.STYLE) { + var checkedKey = setting.data.key.checked, + childKey = setting.data.key.children, + root = data.getRoot(setting); + for (var i = 0, l = root[childKey].length; i < l; i++) { + var node = root[childKey][i]; + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = checked; + } + view.setSonNodeCheckBox(setting, node, checked); + } + } + }, + repairChkClass: function (setting, node) { + if (!node) return; + data.makeChkFlag(setting, node); + if (node.nocheck !== true) { + var checkObj = $$(node, consts.id.CHECK, setting); + view.setChkClass(setting, checkObj, node); + } + }, + repairParentChkClass: function (setting, node) { + if (!node || !node.parentTId) return; + var pNode = node.getParentNode(); + view.repairChkClass(setting, pNode); + view.repairParentChkClass(setting, pNode); + }, + repairParentChkClassWithSelf: function (setting, node) { + if (!node) return; + var childKey = setting.data.key.children; + if (node[childKey] && node[childKey].length > 0) { + view.repairParentChkClass(setting, node[childKey][0]); + } else { + view.repairParentChkClass(setting, node); + } + }, + repairSonChkDisabled: function (setting, node, chkDisabled, inherit) { + if (!node) return; + var childKey = setting.data.key.children; + if (node.chkDisabled != chkDisabled) { + node.chkDisabled = chkDisabled; + } + view.repairChkClass(setting, node); + if (node[childKey] && inherit) { + for (var i = 0, l = node[childKey].length; i < l; i++) { + var sNode = node[childKey][i]; + view.repairSonChkDisabled(setting, sNode, chkDisabled, inherit); + } + } + }, + repairParentChkDisabled: function (setting, node, chkDisabled, inherit) { + if (!node) return; + if (node.chkDisabled != chkDisabled && inherit) { + node.chkDisabled = chkDisabled; + } + view.repairChkClass(setting, node); + view.repairParentChkDisabled(setting, node.getParentNode(), chkDisabled, inherit); + }, + setChkClass: function (setting, obj, node) { + if (!obj) return; + if (node.nocheck === true) { + obj.hide(); + } else { + obj.show(); + } + obj.attr("class", view.makeChkClass(setting, node)); + }, + setParentNodeCheckBox: function (setting, node, value, srcNode) { + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + checkObj = $$(node, consts.id.CHECK, setting); + if (!srcNode) srcNode = node; + data.makeChkFlag(setting, node); + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = value; + view.setChkClass(setting, checkObj, node); + if (setting.check.autoCheckTrigger && node != srcNode) { + setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + } + } + if (node.parentTId) { + var pSign = true; + if (!value) { + var pNodes = node.getParentNode()[childKey]; + for (var i = 0, l = pNodes.length; i < l; i++) { + if ((pNodes[i].nocheck !== true && pNodes[i].chkDisabled !== true && pNodes[i][checkedKey]) || ((pNodes[i].nocheck === true || pNodes[i].chkDisabled === true) && pNodes[i].check_Child_State > 0)) { - pSign = false; - break; - } - } - } - if (pSign) { - view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); - } - } - }, - setSonNodeCheckBox: function(setting, node, value, srcNode) { - if (!node) return; - var childKey = setting.data.key.children, - checkedKey = setting.data.key.checked, - checkObj = $$(node, consts.id.CHECK, setting); - if (!srcNode) srcNode = node; + pSign = false; + break; + } + } + } + if (pSign) { + view.setParentNodeCheckBox(setting, node.getParentNode(), value, srcNode); + } + } + }, + setSonNodeCheckBox: function (setting, node, value, srcNode) { + if (!node) return; + var childKey = setting.data.key.children, + checkedKey = setting.data.key.checked, + checkObj = $$(node, consts.id.CHECK, setting); + if (!srcNode) srcNode = node; - var hasDisable = false; - if (node[childKey]) { - for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { - var sNode = node[childKey][i]; - view.setSonNodeCheckBox(setting, sNode, value, srcNode); - if (sNode.chkDisabled === true) hasDisable = true; - } - } + var hasDisable = false; + if (node[childKey]) { + for (var i = 0, l = node[childKey].length; i < l && node.chkDisabled !== true; i++) { + var sNode = node[childKey][i]; + view.setSonNodeCheckBox(setting, sNode, value, srcNode); + if (sNode.chkDisabled === true) hasDisable = true; + } + } - if (node != data.getRoot(setting) && node.chkDisabled !== true) { - if (hasDisable && node.nocheck !== true) { - data.makeChkFlag(setting, node); - } - if (node.nocheck !== true && node.chkDisabled !== true) { - node[checkedKey] = value; - if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; - } else { - node.check_Child_State = -1; - } - view.setChkClass(setting, checkObj, node); - if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { - setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); - } - } + if (node != data.getRoot(setting) && node.chkDisabled !== true) { + if (hasDisable && node.nocheck !== true) { + data.makeChkFlag(setting, node); + } + if (node.nocheck !== true && node.chkDisabled !== true) { + node[checkedKey] = value; + if (!hasDisable) node.check_Child_State = (node[childKey] && node[childKey].length > 0) ? (value ? 2 : 0) : -1; + } else { + node.check_Child_State = -1; + } + view.setChkClass(setting, checkObj, node); + if (setting.check.autoCheckTrigger && node != srcNode && node.nocheck !== true && node.chkDisabled !== true) { + setting.treeObj.trigger(consts.event.CHECK, [null, setting.treeId, node]); + } + } - } - }, + } + }, - _z = { - tools: _tools, - view: _view, - event: _event, - data: _data - }; - $.extend(true, $.fn.zTree.consts, _consts); - $.extend(true, $.fn.zTree._z, _z); + _z = { + tools: _tools, + view: _view, + event: _event, + data: _data + }; + $.extend(true, $.fn.zTree.consts, _consts); + $.extend(true, $.fn.zTree._z, _z); - var zt = $.fn.zTree, - tools = zt._z.tools, - consts = zt.consts, - view = zt._z.view, - data = zt._z.data, - event = zt._z.event, - $$ = tools.$; + var zt = $.fn.zTree, + tools = zt._z.tools, + consts = zt.consts, + view = zt._z.view, + data = zt._z.data, + event = zt._z.event, + $$ = tools.$; - data.exSetting(_setting); - data.addInitBind(_bindEvent); - data.addInitUnBind(_unbindEvent); - data.addInitCache(_initCache); - data.addInitNode(_initNode); - data.addInitProxy(_eventProxy, true); - data.addInitRoot(_initRoot); - data.addBeforeA(_beforeA); - data.addZTreeTools(_zTreeTools); + data.exSetting(_setting); + data.addInitBind(_bindEvent); + data.addInitUnBind(_unbindEvent); + data.addInitCache(_initCache); + data.addInitNode(_initNode); + data.addInitProxy(_eventProxy, true); + data.addInitRoot(_initRoot); + data.addBeforeA(_beforeA); + data.addZTreeTools(_zTreeTools); - var _createNodes = view.createNodes; - view.createNodes = function(setting, level, nodes, parentNode) { - if (_createNodes) _createNodes.apply(view, arguments); - if (!nodes) return; - view.repairParentChkClassWithSelf(setting, parentNode); - } - var _removeNode = view.removeNode; - view.removeNode = function(setting, node) { - var parentNode = node.getParentNode(); - if (_removeNode) _removeNode.apply(view, arguments); - if (!node || !parentNode) return; - view.repairChkClass(setting, parentNode); - view.repairParentChkClass(setting, parentNode); - } + var _createNodes = view.createNodes; + view.createNodes = function (setting, level, nodes, parentNode) { + if (_createNodes) _createNodes.apply(view, arguments); + if (!nodes) return; + view.repairParentChkClassWithSelf(setting, parentNode); + }; + var _removeNode = view.removeNode; + view.removeNode = function (setting, node) { + var parentNode = node.getParentNode(); + if (_removeNode) _removeNode.apply(view, arguments); + if (!node || !parentNode) return; + view.repairChkClass(setting, parentNode); + view.repairParentChkClass(setting, parentNode); + }; - var _appendNodes = view.appendNodes; - view.appendNodes = function(setting, level, nodes, parentNode, initFlag, openFlag) { - var html = ""; - if (_appendNodes) { - html = _appendNodes.apply(view, arguments); - } - if (parentNode) { - data.makeChkFlag(setting, parentNode); - } - return html; - } + var _appendNodes = view.appendNodes; + view.appendNodes = function (setting, level, nodes, parentNode, initFlag, openFlag) { + var html = ""; + if (_appendNodes) { + html = _appendNodes.apply(view, arguments); + } + if (parentNode) { + data.makeChkFlag(setting, parentNode); + } + return html; + }; })(jQuery); \ No newline at end of file diff --git a/src/case/button/icon/icon.change.js b/src/case/button/icon/icon.change.js index 69c050fdb..4f986e7f6 100644 --- a/src/case/button/icon/icon.change.js +++ b/src/case/button/icon/icon.change.js @@ -18,16 +18,16 @@ BI.IconChangeButton = BI.inherit(BI.Single, { stopEvent: false, stopPropagation: false, selected: false, - once: false, //点击一次选中有效,再点无效 - forceSelected: false, //点击即选中, 选中了就不会被取消 - forceNotSelected: false, //无论怎么点击都不会被选中 - disableSelected: false, //使能选中 + once: false, // 点击一次选中有效,再点无效 + forceSelected: false, // 点击即选中, 选中了就不会被取消 + forceNotSelected: false, // 无论怎么点击都不会被选中 + disableSelected: false, // 使能选中 shadow: false, - isShadowShowingOnSelected: false, //选中状态下是否显示阴影 + isShadowShowingOnSelected: false, // 选中状态下是否显示阴影 trigger: null, handler: BI.emptyFn - }) + }); }, _init: function () { diff --git a/src/case/button/icon/icon.half.js b/src/case/button/icon/icon.half.js index d5e8b9b7e..5c93f7585 100644 --- a/src/case/button/icon/icon.half.js +++ b/src/case/button/icon/icon.half.js @@ -4,8 +4,8 @@ * @type {*|void|Object} */ BI.HalfIconButton = BI.inherit(BI.IconButton, { - _defaultConfig: function() { - var conf = BI.HalfIconButton.superclass._defaultConfig.apply(this,arguments); + _defaultConfig: function () { + var conf = BI.HalfIconButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-half-icon-button check-half-select-icon", height: 16, @@ -13,16 +13,16 @@ BI.HalfIconButton = BI.inherit(BI.IconButton, { iconWidth: 16, iconHeight: 16, selected: false - }) + }); }, - _init : function() { + _init: function () { BI.HalfIconButton.superclass._init.apply(this, arguments); }, - doClick: function(){ + doClick: function () { BI.HalfIconButton.superclass.doClick.apply(this, arguments); - if(this.isValid()){ + if(this.isValid()) { this.fireEvent(BI.HalfIconButton.EVENT_CHANGE); } } diff --git a/src/case/button/item.multiselect.js b/src/case/button/item.multiselect.js index 5a6ac2042..52a7feb96 100644 --- a/src/case/button/item.multiselect.js +++ b/src/case/button/item.multiselect.js @@ -11,7 +11,7 @@ BI.MultiSelectItem = BI.inherit(BI.BasicButton, { logic: { dynamic: false } - }) + }); }, _init: function () { BI.MultiSelectItem.superclass._init.apply(this, arguments); diff --git a/src/case/button/item.singleselect.icontext.js b/src/case/button/item.singleselect.icontext.js index f3236f0f2..1a115e308 100644 --- a/src/case/button/item.singleselect.icontext.js +++ b/src/case/button/item.singleselect.icontext.js @@ -11,7 +11,7 @@ BI.SingleSelectIconTextItem = BI.inherit(BI.Single, { iconClass: "", hgap: 10, height: 25 - }) + }); }, _init: function () { BI.SingleSelectIconTextItem.superclass._init.apply(this, arguments); diff --git a/src/case/button/item.singleselect.js b/src/case/button/item.singleselect.js index a0f2f2726..77bf55597 100644 --- a/src/case/button/item.singleselect.js +++ b/src/case/button/item.singleselect.js @@ -10,7 +10,7 @@ BI.SingleSelectItem = BI.inherit(BI.BasicButton, { hgap: 10, height: 25, textAlign: "left" - }) + }); }, _init: function () { BI.SingleSelectItem.superclass._init.apply(this, arguments); diff --git a/src/case/button/item.singleselect.radio.js b/src/case/button/item.singleselect.radio.js index a43ad0e22..15e89a9da 100644 --- a/src/case/button/item.singleselect.radio.js +++ b/src/case/button/item.singleselect.radio.js @@ -12,7 +12,7 @@ BI.SingleSelectRadioItem = BI.inherit(BI.BasicButton, { }, hgap: 10, height: 25 - }) + }); }, _init: function () { BI.SingleSelectRadioItem.superclass._init.apply(this, arguments); diff --git a/src/case/button/node/node.first.plus.js b/src/case/button/node/node.first.plus.js index 8637d2cbe..8611252f6 100644 --- a/src/case/button/node/node.first.plus.js +++ b/src/case/button/node/node.first.plus.js @@ -16,7 +16,7 @@ BI.FirstPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.FirstPlusGroupNode.superclass._init.apply(this, arguments); diff --git a/src/case/button/node/node.icon.arrow.js b/src/case/button/node/node.icon.arrow.js index 3d3420161..192a747fd 100644 --- a/src/case/button/node/node.icon.arrow.js +++ b/src/case/button/node/node.icon.arrow.js @@ -21,7 +21,7 @@ BI.IconArrowNode = BI.inherit(BI.NodeButton, { iconHeight: 13, iconWidth: 13, iconCls: "" - }) + }); }, _init: function () { BI.IconArrowNode.superclass._init.apply(this, arguments); diff --git a/src/case/button/node/node.last.plus.js b/src/case/button/node/node.last.plus.js index 1e0c47d26..265bd6f84 100644 --- a/src/case/button/node/node.last.plus.js +++ b/src/case/button/node/node.last.plus.js @@ -16,7 +16,7 @@ BI.LastPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.LastPlusGroupNode.superclass._init.apply(this, arguments); diff --git a/src/case/button/node/node.mid.plus.js b/src/case/button/node/node.mid.plus.js index e78510def..ee33703b6 100644 --- a/src/case/button/node/node.mid.plus.js +++ b/src/case/button/node/node.mid.plus.js @@ -16,7 +16,7 @@ BI.MidPlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MidPlusGroupNode.superclass._init.apply(this, arguments); diff --git a/src/case/button/node/node.multilayer.icon.arrow.js b/src/case/button/node/node.multilayer.icon.arrow.js index 7f406ac68..ab63e01f9 100644 --- a/src/case/button/node/node.multilayer.icon.arrow.js +++ b/src/case/button/node/node.multilayer.icon.arrow.js @@ -3,7 +3,7 @@ BI.MultiLayerIconArrowNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerIconArrowNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-icon-arrow-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, @@ -11,7 +11,7 @@ BI.MultiLayerIconArrowNode = BI.inherit(BI.NodeButton, { iconHeight: 13, iconWidth: 13, iconCls: "" - }) + }); }, _init: function () { BI.MultiLayerIconArrowNode.superclass._init.apply(this, arguments); @@ -19,9 +19,9 @@ BI.MultiLayerIconArrowNode = BI.inherit(BI.NodeButton, { this.node = BI.createWidget({ type: "bi.icon_arrow_node", iconCls: o.iconCls, - //logic: { + // logic: { // dynamic: true - //}, + // }, id: o.id, pId: o.pId, open: o.open, @@ -44,7 +44,7 @@ BI.MultiLayerIconArrowNode = BI.inherit(BI.NodeButton, { type: "bi.layout", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -52,7 +52,7 @@ BI.MultiLayerIconArrowNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, isOnce: function () { diff --git a/src/case/button/node/node.plus.js b/src/case/button/node/node.plus.js index 7ccbb0433..df61dbe08 100644 --- a/src/case/button/node/node.plus.js +++ b/src/case/button/node/node.plus.js @@ -16,7 +16,7 @@ BI.PlusGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.PlusGroupNode.superclass._init.apply(this, arguments); diff --git a/src/case/button/node/node.triangle.js b/src/case/button/node/node.triangle.js index 932485a3b..d882ad7b4 100644 --- a/src/case/button/node/node.triangle.js +++ b/src/case/button/node/node.triangle.js @@ -16,7 +16,7 @@ BI.TriangleGroupNode = BI.inherit(BI.NodeButton, { pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.TriangleGroupNode.superclass._init.apply(this, arguments); @@ -74,7 +74,7 @@ BI.TriangleGroupNode = BI.inherit(BI.NodeButton, { this.checkbox.setSelected(v); }, - setText: function(text){ + setText: function (text) { BI.TriangleGroupNode.superclass.setText.apply(this, arguments); this.text.setText(text); } diff --git a/src/case/button/treeitem/item.first.treeleaf.js b/src/case/button/treeitem/item.first.treeleaf.js index 65e05b569..3e511764b 100644 --- a/src/case/button/treeitem/item.first.treeleaf.js +++ b/src/case/button/treeitem/item.first.treeleaf.js @@ -14,7 +14,7 @@ BI.FirstTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.FirstTreeLeafItem.superclass._init.apply(this, arguments); diff --git a/src/case/button/treeitem/item.icon.treeleaf.js b/src/case/button/treeitem/item.icon.treeleaf.js index bca64974f..12ca9b7f5 100644 --- a/src/case/button/treeitem/item.icon.treeleaf.js +++ b/src/case/button/treeitem/item.icon.treeleaf.js @@ -9,7 +9,7 @@ BI.IconTreeLeafItem = BI.inherit(BI.BasicButton, { iconWidth: 16, iconHeight: 16, iconCls: "" - }) + }); }, _init: function () { diff --git a/src/case/button/treeitem/item.last.treeleaf.js b/src/case/button/treeitem/item.last.treeleaf.js index 26be93942..2b5fca4ba 100644 --- a/src/case/button/treeitem/item.last.treeleaf.js +++ b/src/case/button/treeitem/item.last.treeleaf.js @@ -14,7 +14,7 @@ BI.LastTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.LastTreeLeafItem.superclass._init.apply(this, arguments); diff --git a/src/case/button/treeitem/item.mid.treeleaf.js b/src/case/button/treeitem/item.mid.treeleaf.js index 6210427f7..f804646f1 100644 --- a/src/case/button/treeitem/item.mid.treeleaf.js +++ b/src/case/button/treeitem/item.mid.treeleaf.js @@ -14,7 +14,7 @@ BI.MidTreeLeafItem = BI.inherit(BI.BasicButton, { pId: "", layer: 0, height: 25 - }) + }); }, _init: function () { BI.MidTreeLeafItem.superclass._init.apply(this, arguments); diff --git a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js index 02ffa959f..9fe8251a0 100644 --- a/src/case/button/treeitem/item.multilayer.icon.treeleaf.js +++ b/src/case/button/treeitem/item.multilayer.icon.treeleaf.js @@ -11,7 +11,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { iconCls: "", iconHeight: 14, iconWidth: 12 - }) + }); }, _init: function () { BI.MultiLayerIconTreeLeafItem.superclass._init.apply(this, arguments); @@ -32,7 +32,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { iconHeight: o.iconHeight }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -44,7 +44,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { type: "bi.layout", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -89,7 +89,7 @@ BI.MultiLayerIconTreeLeafItem = BI.inherit(BI.BasicButton, { this.item.setSelected(v); }, - getValue: function(){ + getValue: function () { return this.options.value; } }); diff --git a/src/case/button/treeitem/item.treetextleaf.js b/src/case/button/treeitem/item.treetextleaf.js index e2a93c765..6a1ede198 100644 --- a/src/case/button/treeitem/item.treetextleaf.js +++ b/src/case/button/treeitem/item.treetextleaf.js @@ -5,7 +5,7 @@ * @extends BI.BasicButton */ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend(BI.TreeTextLeafItem.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-tree-text-leaf-item bi-list-item-active", id: "", @@ -14,9 +14,9 @@ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { hgap: 0, lgap: 0, rgap: 0 - }) + }); }, - _init : function() { + _init: function () { BI.TreeTextLeafItem.superclass._init.apply(this, arguments); var self = this, o = this.options; this.text = BI.createWidget({ @@ -38,30 +38,30 @@ BI.TreeTextLeafItem = BI.inherit(BI.BasicButton, { items: [{ el: this.text }] - }) + }); }, - doRedMark: function(){ + doRedMark: function () { this.text.doRedMark.apply(this.text, arguments); }, - unRedMark: function(){ + unRedMark: function () { this.text.unRedMark.apply(this.text, arguments); }, - doHighLight: function(){ + doHighLight: function () { this.text.doHighLight.apply(this.text, arguments); }, - unHighLight: function(){ + unHighLight: function () { this.text.unHighLight.apply(this.text, arguments); }, - getId: function(){ + getId: function () { return this.options.id; }, - getPId: function(){ + getPId: function () { return this.options.pId; } }); diff --git a/src/case/calendar/calendar.js b/src/case/calendar/calendar.js index 8df9fd33c..7fe778a01 100644 --- a/src/case/calendar/calendar.js +++ b/src/case/calendar/calendar.js @@ -11,12 +11,12 @@ BI.Calendar = BI.inherit(BI.Widget, { logic: { dynamic: false }, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 year: 2015, - month: 7, //7表示八月 + month: 7, // 7表示八月 day: 25 - }) + }); }, _dateCreator: function (Y, M, D) { @@ -62,7 +62,7 @@ BI.Calendar = BI.inherit(BI.Widget, { } td.text = DD; items.push(td); - }) + }); return items; }, @@ -74,13 +74,13 @@ BI.Calendar = BI.inherit(BI.Widget, { type: "bi.label", height: 25, text: value - } - }) + }; + }); var title = BI.createWidget({ type: "bi.button_group", height: 25, items: items - }) + }); var days = this._dateCreator(o.year, o.month, o.day); items = []; items.push(days.slice(0, 7)); @@ -102,7 +102,7 @@ BI.Calendar = BI.inherit(BI.Widget, { height: 25, value: o.year + "-" + o.month + "-" + td.text, disabled: td.lastMonth || td.nextMonth || td.disabled - //selected: td.currentDay + // selected: td.currentDay }); }); }); @@ -119,7 +119,7 @@ BI.Calendar = BI.inherit(BI.Widget, { }); this.days.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }) + }); BI.createWidget(BI.extend({ element: this @@ -156,7 +156,7 @@ BI.Calendar = BI.inherit(BI.Widget, { year: date[0] | 0, month: date[1] | 0, day: date[2] | 0 - } + }; } }); @@ -168,22 +168,22 @@ BI.extend(BI.Calendar, { page += json.month - month; return page; }, - getDateJSONByPage: function(v){ + getDateJSONByPage: function (v) { var months = Date.getDate().getMonth(); var page = v; - //对当前page做偏移,使到当前年初 + // 对当前page做偏移,使到当前年初 page = page + months; var year = BI.parseInt(page / 12); - if(page < 0 && page % 12 !== 0){ + if(page < 0 && page % 12 !== 0) { year--; } var month = page >= 0 ? (page % 12) : ((12 + page % 12) % 12); return { year: Date.getDate().getFullYear() + year, month: month - } + }; } }); diff --git a/src/case/calendar/calendar.year.js b/src/case/calendar/calendar.year.js index 48e606080..8a20eb177 100644 --- a/src/case/calendar/calendar.year.js +++ b/src/case/calendar/calendar.year.js @@ -13,10 +13,10 @@ BI.YearCalendar = BI.inherit(BI.Widget, { logic: { dynamic: false }, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 year: null - }) + }); }, _yearCreator: function (Y) { @@ -41,7 +41,7 @@ BI.YearCalendar = BI.inherit(BI.Widget, { this.currentYear = Date.getDate().getFullYear(); var years = this._yearCreator(o.year || this.currentYear); - //纵向排列年 + // 纵向排列年 var len = years.length, tyears = BI.makeArray(len, ""); var map = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; BI.each(years, function (i, y) { @@ -119,11 +119,11 @@ BI.YearCalendar = BI.inherit(BI.Widget, { return this.years.getValue()[0]; } }); -//类方法 +// 类方法 BI.extend(BI.YearCalendar, { INTERVAL: 12, - //获取显示的第一年 + // 获取显示的第一年 getStartYear: function (year) { var cur = Date.getDate().getFullYear(); return year - ((year - cur + 3) % BI.YearCalendar.INTERVAL + 12) % BI.YearCalendar.INTERVAL; diff --git a/src/case/canvas/canvas.complex.js b/src/case/canvas/canvas.complex.js index 1073196cc..af8cd2a82 100644 --- a/src/case/canvas/canvas.complex.js +++ b/src/case/canvas/canvas.complex.js @@ -9,7 +9,7 @@ BI.ComplexCanvas = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.ComplexCanvas.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-complex-canvas" - }) + }); }, @@ -24,7 +24,7 @@ BI.ComplexCanvas = BI.inherit(BI.Widget, { }); }, - //绘制树枝节点 + // 绘制树枝节点 branch: function (x0, y0, x1, y1, x2, y2) { var self = this, args = [].slice.call(arguments); if (args.length <= 5) { diff --git a/src/case/checkbox/check.arrowtreegroupnode.js b/src/case/checkbox/check.arrowtreegroupnode.js index c48b4f4f1..2c884f84e 100644 --- a/src/case/checkbox/check.arrowtreegroupnode.js +++ b/src/case/checkbox/check.arrowtreegroupnode.js @@ -2,18 +2,18 @@ * Created by roy on 15/10/16. * 上箭头与下箭头切换的树节点 */ -BI.ArrowTreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{ - _defaultConfig:function(){ - return BI.extend(BI.ArrowTreeGroupNodeCheckbox.superclass._defaultConfig.apply(this,arguments),{ - extraCls:"bi-arrow-tree-group-node", +BI.ArrowTreeGroupNodeCheckbox = BI.inherit(BI.IconButton, { + _defaultConfig: function () { + return BI.extend(BI.ArrowTreeGroupNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { + extraCls: "bi-arrow-tree-group-node", iconWidth: 13, iconHeight: 13 }); }, - _init:function(){ - BI.ArrowTreeGroupNodeCheckbox.superclass._init.apply(this,arguments); + _init: function () { + BI.ArrowTreeGroupNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.ArrowTreeGroupNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.removeClass("column-next-page-h-font").addClass("column-pre-page-h-font"); @@ -22,4 +22,4 @@ BI.ArrowTreeGroupNodeCheckbox=BI.inherit(BI.IconButton,{ } } }); -BI.shortcut("bi.arrow_tree_group_node_checkbox",BI.ArrowTreeGroupNodeCheckbox); \ No newline at end of file +BI.shortcut("bi.arrow_tree_group_node_checkbox", BI.ArrowTreeGroupNodeCheckbox); \ No newline at end of file diff --git a/src/case/checkbox/check.checkingmarknode.js b/src/case/checkbox/check.checkingmarknode.js index 8264480af..1f1387d2b 100644 --- a/src/case/checkbox/check.checkingmarknode.js +++ b/src/case/checkbox/check.checkingmarknode.js @@ -4,21 +4,21 @@ * @extends BI.IconButton */ BI.CheckingMarkNode = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.CheckingMarkNode.superclass._defaultConfig.apply(this, arguments), { extraCls: "check-mark-font", iconWidth: 13, iconHeight: 13 }); }, - _init:function() { + _init: function () { BI.CheckingMarkNode.superclass._init.apply(this, arguments); this.setSelected(this.options.selected); }, - setSelected: function(v){ + setSelected: function (v) { BI.CheckingMarkNode.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("check-mark-font"); } else { this.element.removeClass("check-mark-font"); diff --git a/src/case/checkbox/check.first.treenode.js b/src/case/checkbox/check.first.treenode.js index 281e09554..f163a34ea 100644 --- a/src/case/checkbox/check.first.treenode.js +++ b/src/case/checkbox/check.first.treenode.js @@ -4,20 +4,20 @@ * @extends BI.IconButton */ BI.FirstTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.FirstTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type2", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.FirstTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.FirstTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type2"); } else { this.element.removeClass("tree-expand-icon-type2"); diff --git a/src/case/checkbox/check.last.treenode.js b/src/case/checkbox/check.last.treenode.js index 19eecd44e..2e14ba3f0 100644 --- a/src/case/checkbox/check.last.treenode.js +++ b/src/case/checkbox/check.last.treenode.js @@ -4,20 +4,20 @@ * @extends BI.IconButton */ BI.LastTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.LastTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type4", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.LastTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.LastTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type3"); } else { this.element.removeClass("tree-expand-icon-type3"); diff --git a/src/case/checkbox/check.mid.treenode.js b/src/case/checkbox/check.mid.treenode.js index da0876644..9084bd898 100644 --- a/src/case/checkbox/check.mid.treenode.js +++ b/src/case/checkbox/check.mid.treenode.js @@ -4,20 +4,20 @@ * @extends BI.IconButton */ BI.MidTreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.MidTreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type3", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.MidTreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.MidTreeNodeCheckbox.superclass.setSelected.apply(this, arguments); - if(v===true) { + if(v === true) { this.element.addClass("tree-expand-icon-type3"); } else { this.element.removeClass("tree-expand-icon-type3"); diff --git a/src/case/checkbox/check.treegroupnode.js b/src/case/checkbox/check.treegroupnode.js index 00cad265b..162e1c030 100644 --- a/src/case/checkbox/check.treegroupnode.js +++ b/src/case/checkbox/check.treegroupnode.js @@ -5,18 +5,18 @@ * @extends BI.IconButton */ BI.TreeGroupNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.TreeGroupNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-node-triangle-collapse-font", iconWidth: 13, iconHeight: 13 }); }, - _init:function() { + _init: function () { BI.TreeGroupNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.TreeGroupNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.removeClass("tree-node-triangle-collapse-font").addClass("tree-node-triangle-expand-font"); diff --git a/src/case/checkbox/check.treenode.js b/src/case/checkbox/check.treenode.js index fa84ca642..ccdee31b0 100644 --- a/src/case/checkbox/check.treenode.js +++ b/src/case/checkbox/check.treenode.js @@ -4,18 +4,18 @@ * @extends BI.IconButton */ BI.TreeNodeCheckbox = BI.inherit(BI.IconButton, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.TreeNodeCheckbox.superclass._defaultConfig.apply(this, arguments), { extraCls: "tree-collapse-icon-type1", iconWidth: 25, iconHeight: 25 }); }, - _init:function() { + _init: function () { BI.TreeNodeCheckbox.superclass._init.apply(this, arguments); }, - setSelected: function(v){ + setSelected: function (v) { BI.TreeNodeCheckbox.superclass.setSelected.apply(this, arguments); if(v) { this.element.addClass("tree-expand-icon-type1"); diff --git a/src/case/clipboard/clipboard.js b/src/case/clipboard/clipboard.js index fc699ebc7..32dc52252 100644 --- a/src/case/clipboard/clipboard.js +++ b/src/case/clipboard/clipboard.js @@ -1,52 +1,52 @@ -/*! +/* ! * clipboard.js v1.6.1 * https://zenorocha.github.io/clipboard.js * * Licensed MIT © Zeno Rocha */ -try {//IE8下会抛错 +try {// IE8下会抛错 (function (f) { if (typeof exports === "object" && typeof module !== "undefined") { - module.exports = f() + module.exports = f(); } else if (typeof define === "function" && define.amd) { - define([], f) + define([], f); } else { var g; if (typeof window !== "undefined") { - g = window + g = window; } else if (typeof global !== "undefined") { - g = global + g = global; } else if (typeof self !== "undefined") { - g = self + g = self; } else { - g = this + g = this; } - g.Clipboard = f() + g.Clipboard = f(); } })(function () { var define, module, exports; - return (function e(t, n, r) { - function s(o, u) { + return (function e (t, n, r) { + function s (o, u) { if (!n[o]) { if (!t[o]) { - var a = typeof require == "function" && require; + 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 + 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 s(n ? n : e); + }, l, l.exports, e, t, n, r); } - return n[o].exports + return n[o].exports; } - var i = typeof require == "function" && require; + var i = typeof require === "function" && require; for (var o = 0; o < r.length; o++)s(r[o]); - return s + return s; })({ 1: [function (require, module, exports) { var DOCUMENT_NODE_TYPE = 9; @@ -54,7 +54,7 @@ try {//IE8下会抛错 /** * A polyfill for Element.matches() */ - if (typeof Element !== 'undefined' && !Element.prototype.matches) { + if (typeof Element !== "undefined" && !Element.prototype.matches) { var proto = Element.prototype; proto.matches = proto.matchesSelector || @@ -71,7 +71,7 @@ try {//IE8下会抛错 * @param {String} selector * @return {Function} */ - function closest(element, selector) { + function closest (element, selector) { while (element && element.nodeType !== DOCUMENT_NODE_TYPE) { if (element.matches(selector)) return element; element = element.parentNode; @@ -81,7 +81,7 @@ try {//IE8下会抛错 module.exports = closest; }, {}], 2: [function (require, module, exports) { - var closest = require('./closest'); + var closest = require("./closest"); /** * Delegates event to a selector. @@ -93,7 +93,7 @@ try {//IE8下会抛错 * @param {Boolean} useCapture * @return {Object} */ - function delegate(element, selector, type, callback, useCapture) { + function delegate (element, selector, type, callback, useCapture) { var listenerFn = listener.apply(this, arguments); element.addEventListener(type, listenerFn, useCapture); @@ -102,7 +102,7 @@ try {//IE8下会抛错 destroy: function () { element.removeEventListener(type, listenerFn, useCapture); } - } + }; } /** @@ -114,14 +114,14 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Function} */ - function listener(element, selector, type, callback) { + function listener (element, selector, type, callback) { return function (e) { e.delegateTarget = closest(e.target, selector); if (e.delegateTarget) { callback.call(element, e); } - } + }; } module.exports = delegate; @@ -149,8 +149,8 @@ try {//IE8下会抛错 var type = Object.prototype.toString.call(value); return value !== undefined - && (type === '[object NodeList]' || type === '[object HTMLCollection]') - && ('length' in value) + && (type === "[object NodeList]" || type === "[object HTMLCollection]") + && ("length" in value) && (value.length === 0 || exports.node(value[0])); }; @@ -161,7 +161,7 @@ try {//IE8下会抛错 * @return {Boolean} */ exports.string = function (value) { - return typeof value === 'string' + return typeof value === "string" || value instanceof String; }; @@ -174,12 +174,12 @@ try {//IE8下会抛错 exports.fn = function (value) { var type = Object.prototype.toString.call(value); - return type === '[object Function]'; + return type === "[object Function]"; }; }, {}], 4: [function (require, module, exports) { - var is = require('./is'); - var delegate = require('delegate'); + var is = require("./is"); + var delegate = require("delegate"); /** * Validates all params and calls the right @@ -190,31 +190,29 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listen(target, type, callback) { + function listen (target, type, callback) { if (!target && !type && !callback) { - throw new Error('Missing required arguments'); + throw new Error("Missing required arguments"); } if (!is.string(type)) { - throw new TypeError('Second argument must be a String'); + throw new TypeError("Second argument must be a String"); } if (!is.fn(callback)) { - throw new TypeError('Third argument must be a Function'); + throw new TypeError("Third argument must be a Function"); } if (is.node(target)) { return listenNode(target, type, callback); - } - else if (is.nodeList(target)) { + } else if (is.nodeList(target)) { return listenNodeList(target, type, callback); - } - else if (is.string(target)) { + } else if (is.string(target)) { return listenSelector(target, type, callback); } - else { - throw new TypeError('First argument must be a String, HTMLElement, HTMLCollection, or NodeList'); - } + + throw new TypeError("First argument must be a String, HTMLElement, HTMLCollection, or NodeList"); + } /** @@ -226,14 +224,14 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenNode(node, type, callback) { + function listenNode (node, type, callback) { node.addEventListener(type, callback); return { destroy: function () { node.removeEventListener(type, callback); } - } + }; } /** @@ -245,7 +243,7 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenNodeList(nodeList, type, callback) { + function listenNodeList (nodeList, type, callback) { Array.prototype.forEach.call(nodeList, function (node) { node.addEventListener(type, callback); }); @@ -256,7 +254,7 @@ try {//IE8下会抛错 node.removeEventListener(type, callback); }); } - } + }; } /** @@ -268,39 +266,37 @@ try {//IE8下会抛错 * @param {Function} callback * @return {Object} */ - function listenSelector(selector, type, callback) { + function listenSelector (selector, type, callback) { return delegate(document.body, selector, type, callback); } module.exports = listen; - }, {"./is": 3, "delegate": 2}], 5: [function (require, module, exports) { - function select(element) { + }, {"./is": 3, delegate: 2}], 5: [function (require, module, exports) { + function select (element) { var selectedText; - if (element.nodeName === 'SELECT') { + if (element.nodeName === "SELECT") { element.focus(); selectedText = element.value; - } - else if (element.nodeName === 'INPUT' || element.nodeName === 'TEXTAREA') { - var isReadOnly = element.hasAttribute('readonly'); + } else if (element.nodeName === "INPUT" || element.nodeName === "TEXTAREA") { + var isReadOnly = element.hasAttribute("readonly"); if (!isReadOnly) { - element.setAttribute('readonly', ''); + element.setAttribute("readonly", ""); } element.select(); element.setSelectionRange(0, element.value.length); if (!isReadOnly) { - element.removeAttribute('readonly'); + element.removeAttribute("readonly"); } selectedText = element.value; - } - else { - if (element.hasAttribute('contenteditable')) { + } else { + if (element.hasAttribute("contenteditable")) { element.focus(); } @@ -320,7 +316,7 @@ try {//IE8下会抛错 module.exports = select; }, {}], 6: [function (require, module, exports) { - function E() { + function E () { // Keep this empty so it's easier to inherit from // (via https://github.com/lipsmack from https://github.com/scottcorgan/tiny-emitter/issues/3) } @@ -340,12 +336,12 @@ try {//IE8下会抛错 once: function (name, callback, ctx) { var self = this; - function listener() { + function listener () { self.off(name, listener); callback.apply(ctx, arguments); - }; + } - listener._ = callback + listener._ = callback; return this.on(name, listener, ctx); }, @@ -369,8 +365,7 @@ try {//IE8下会抛错 if (evts && callback) { for (var i = 0, len = evts.length; i < len; i++) { - if (evts[i].fn !== callback && evts[i].fn._ !== callback) - liveEvents.push(evts[i]); + if (evts[i].fn !== callback && evts[i].fn._ !== callback) {liveEvents.push(evts[i]);} } } @@ -391,9 +386,9 @@ try {//IE8下会抛错 }, {}], 7: [function (require, module, exports) { (function (global, factory) { if (typeof define === "function" && define.amd) { - define(['module', 'select'], factory); + define(["module", "select"], factory); } else if (typeof exports !== "undefined") { - factory(module, require('select')); + factory(module, require("select")); } else { var mod = { exports: {} @@ -402,13 +397,13 @@ try {//IE8下会抛错 global.clipboardAction = mod.exports; } })(this, function (module, _select) { - 'use strict'; + "use strict"; var _select2 = _interopRequireDefault(_select); - function _interopRequireDefault(obj) { + function _interopRequireDefault (obj) { return obj && obj.__esModule ? obj : { - "default": obj + default: obj }; } @@ -418,14 +413,14 @@ try {//IE8下会抛错 return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; }; - function _classCallCheck(instance, Constructor) { + function _classCallCheck (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { - function defineProperties(target, props) { + function defineProperties (target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; @@ -446,7 +441,7 @@ try {//IE8下会抛错 /** * @param {Object} options */ - function ClipboardAction(options) { + function ClipboardAction (options) { _classCallCheck(this, ClipboardAction); this.resolveOptions(options); @@ -460,8 +455,8 @@ try {//IE8下会抛错 _createClass(ClipboardAction, [{ - key: 'resolveOptions', - value: function resolveOptions() { + key: "resolveOptions", + value: function resolveOptions () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; this.action = options.action; @@ -470,11 +465,11 @@ try {//IE8下会抛错 this.text = options.text; this.trigger = options.trigger; - this.selectedText = ''; + this.selectedText = ""; } }, { - key: 'initSelection', - value: function initSelection() { + key: "initSelection", + value: function initSelection () { if (this.text) { this.selectFake(); } else if (this.target) { @@ -482,34 +477,34 @@ try {//IE8下会抛错 } } }, { - key: 'selectFake', - value: function selectFake() { + key: "selectFake", + value: function selectFake () { var _this = this; - var isRTL = document.documentElement.getAttribute('dir') == 'rtl'; + var isRTL = document.documentElement.getAttribute("dir") == "rtl"; this.removeFake(); this.fakeHandlerCallback = function () { return _this.removeFake(); }; - this.fakeHandler = document.body.addEventListener('click', this.fakeHandlerCallback) || true; + this.fakeHandler = document.body.addEventListener("click", this.fakeHandlerCallback) || true; - this.fakeElem = document.createElement('textarea'); + this.fakeElem = document.createElement("textarea"); // Prevent zooming on iOS - this.fakeElem.style.fontSize = '12pt'; + this.fakeElem.style.fontSize = "12pt"; // Reset box model - this.fakeElem.style.border = '0'; - this.fakeElem.style.padding = '0'; - this.fakeElem.style.margin = '0'; + this.fakeElem.style.border = "0"; + this.fakeElem.style.padding = "0"; + this.fakeElem.style.margin = "0"; // Move element out of screen horizontally - this.fakeElem.style.position = 'absolute'; - this.fakeElem.style[isRTL ? 'right' : 'left'] = '-9999px'; + this.fakeElem.style.position = "absolute"; + this.fakeElem.style[isRTL ? "right" : "left"] = "-9999px"; // Move element to the same position vertically var yPosition = window.pageYOffset || document.documentElement.scrollTop; - this.fakeElem.style.top = yPosition + 'px'; + this.fakeElem.style.top = yPosition + "px"; - this.fakeElem.setAttribute('readonly', ''); + this.fakeElem.setAttribute("readonly", ""); this.fakeElem.value = this.text; document.body.appendChild(this.fakeElem); @@ -518,10 +513,10 @@ try {//IE8下会抛错 this.copyText(); } }, { - key: 'removeFake', - value: function removeFake() { + key: "removeFake", + value: function removeFake () { if (this.fakeHandler) { - document.body.removeEventListener('click', this.fakeHandlerCallback); + document.body.removeEventListener("click", this.fakeHandlerCallback); this.fakeHandler = null; this.fakeHandlerCallback = null; } @@ -532,14 +527,14 @@ try {//IE8下会抛错 } } }, { - key: 'selectTarget', - value: function selectTarget() { + key: "selectTarget", + value: function selectTarget () { this.selectedText = (0, _select2["default"])(this.target); this.copyText(); } }, { - key: 'copyText', - value: function copyText() { + key: "copyText", + value: function copyText () { var succeeded = void 0; try { @@ -551,9 +546,9 @@ try {//IE8下会抛错 this.handleResult(succeeded); } }, { - key: 'handleResult', - value: function handleResult(succeeded) { - this.emitter.emit(succeeded ? 'success' : 'error', { + key: "handleResult", + value: function handleResult (succeeded) { + this.emitter.emit(succeeded ? "success" : "error", { action: this.action, text: this.selectedText, trigger: this.trigger, @@ -561,8 +556,8 @@ try {//IE8下会抛错 }); } }, { - key: 'clearSelection', - value: function clearSelection() { + key: "clearSelection", + value: function clearSelection () { if (this.target) { this.target.blur(); } @@ -570,44 +565,44 @@ try {//IE8下会抛错 window.getSelection().removeAllRanges(); } }, { - key: 'destroy', - value: function destroy() { + key: "destroy", + value: function destroy () { this.removeFake(); } }, { - key: 'action', - set: function set() { - var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : 'copy'; + key: "action", + set: function set () { + var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : "copy"; this._action = action; - if (this._action !== 'copy' && this._action !== 'cut') { - throw new Error('Invalid "action" value, use either "copy" or "cut"'); + if (this._action !== "copy" && this._action !== "cut") { + throw new Error("Invalid \"action\" value, use either \"copy\" or \"cut\""); } }, - get: function get() { + get: function get () { return this._action; } }, { - key: 'target', - set: function set(target) { + key: "target", + set: function set (target) { if (target !== undefined) { - if (target && (typeof target === 'undefined' ? 'undefined' : _typeof(target)) === 'object' && target.nodeType === 1) { - if (this.action === 'copy' && target.hasAttribute('disabled')) { - throw new Error('Invalid "target" attribute. Please use "readonly" instead of "disabled" attribute'); + if (target && (typeof target === "undefined" ? "undefined" : _typeof(target)) === "object" && target.nodeType === 1) { + if (this.action === "copy" && target.hasAttribute("disabled")) { + throw new Error("Invalid \"target\" attribute. Please use \"readonly\" instead of \"disabled\" attribute"); } - if (this.action === 'cut' && (target.hasAttribute('readonly') || target.hasAttribute('disabled'))) { - throw new Error('Invalid "target" attribute. You can\'t cut text from elements with "readonly" or "disabled" attributes'); + if (this.action === "cut" && (target.hasAttribute("readonly") || target.hasAttribute("disabled"))) { + throw new Error("Invalid \"target\" attribute. You can't cut text from elements with \"readonly\" or \"disabled\" attributes"); } this._target = target; } else { - throw new Error('Invalid "target" value, use a valid Element'); + throw new Error("Invalid \"target\" value, use a valid Element"); } } }, - get: function get() { + get: function get () { return this._target; } }]); @@ -618,12 +613,12 @@ try {//IE8下会抛错 module.exports = ClipboardAction; }); - }, {"select": 5}], 8: [function (require, module, exports) { + }, {select: 5}], 8: [function (require, module, exports) { (function (global, factory) { if (typeof define === "function" && define.amd) { - define(['module', './clipboard-action', 'tiny-emitter', 'good-listener'], factory); + define(["module", "./clipboard-action", "tiny-emitter", "good-listener"], factory); } else if (typeof exports !== "undefined") { - factory(module, require('./clipboard-action'), require('tiny-emitter'), require('good-listener')); + factory(module, require("./clipboard-action"), require("tiny-emitter"), require("good-listener")); } else { var mod = { exports: {} @@ -632,7 +627,7 @@ try {//IE8下会抛错 global.clipboard = mod.exports; } })(this, function (module, _clipboardAction, _tinyEmitter, _goodListener) { - 'use strict'; + "use strict"; var _clipboardAction2 = _interopRequireDefault(_clipboardAction); @@ -640,20 +635,20 @@ try {//IE8下会抛错 var _goodListener2 = _interopRequireDefault(_goodListener); - function _interopRequireDefault(obj) { + function _interopRequireDefault (obj) { return obj && obj.__esModule ? obj : { - "default": obj + default: obj }; } - function _classCallCheck(instance, Constructor) { + function _classCallCheck (instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError("Cannot call a class as a function"); } } var _createClass = function () { - function defineProperties(target, props) { + function defineProperties (target, props) { for (var i = 0; i < props.length; i++) { var descriptor = props[i]; descriptor.enumerable = descriptor.enumerable || false; @@ -670,7 +665,7 @@ try {//IE8下会抛错 }; }(); - function _possibleConstructorReturn(self, call) { + function _possibleConstructorReturn (self, call) { if (!self) { throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); } @@ -678,7 +673,7 @@ try {//IE8下会抛错 return call && (typeof call === "object" || typeof call === "function") ? call : self; } - function _inherits(subClass, superClass) { + function _inherits (subClass, superClass) { if (typeof superClass !== "function" && superClass !== null) { throw new TypeError("Super expression must either be null or a function, not " + typeof superClass); } @@ -701,7 +696,7 @@ try {//IE8下会抛错 * @param {String|HTMLElement|HTMLCollection|NodeList} trigger * @param {Object} options */ - function Clipboard(trigger, options) { + function Clipboard (trigger, options) { _classCallCheck(this, Clipboard); var _this = _possibleConstructorReturn(this, (Clipboard.__proto__ || Object.getPrototypeOf(Clipboard)).call(this)); @@ -719,26 +714,26 @@ try {//IE8下会抛错 _createClass(Clipboard, [{ - key: 'resolveOptions', - value: function resolveOptions() { + key: "resolveOptions", + value: function resolveOptions () { var options = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : {}; - this.action = typeof options.action === 'function' ? options.action : this.defaultAction; - this.target = typeof options.target === 'function' ? options.target : this.defaultTarget; - this.text = typeof options.text === 'function' ? options.text : this.defaultText; + this.action = typeof options.action === "function" ? options.action : this.defaultAction; + this.target = typeof options.target === "function" ? options.target : this.defaultTarget; + this.text = typeof options.text === "function" ? options.text : this.defaultText; } }, { - key: 'listenClick', - value: function listenClick(trigger) { + key: "listenClick", + value: function listenClick (trigger) { var _this2 = this; - this.listener = (0, _goodListener2["default"])(trigger, 'click', function (e) { + this.listener = (0, _goodListener2["default"])(trigger, "click", function (e) { return _this2.onClick(e); }); } }, { - key: 'onClick', - value: function onClick(e) { + key: "onClick", + value: function onClick (e) { var trigger = e.delegateTarget || e.currentTarget; if (this.clipboardAction) { @@ -754,27 +749,27 @@ try {//IE8下会抛错 }); } }, { - key: 'defaultAction', - value: function defaultAction(trigger) { - return getAttributeValue('action', trigger); + key: "defaultAction", + value: function defaultAction (trigger) { + return getAttributeValue("action", trigger); } }, { - key: 'defaultTarget', - value: function defaultTarget(trigger) { - var selector = getAttributeValue('target', trigger); + key: "defaultTarget", + value: function defaultTarget (trigger) { + var selector = getAttributeValue("target", trigger); if (selector) { return document.querySelector(selector); } } }, { - key: 'defaultText', - value: function defaultText(trigger) { - return getAttributeValue('text', trigger); + key: "defaultText", + value: function defaultText (trigger) { + return getAttributeValue("text", trigger); } }, { - key: 'destroy', - value: function destroy() { + key: "destroy", + value: function destroy () { this.listener.destroy(); if (this.clipboardAction) { @@ -783,11 +778,11 @@ try {//IE8下会抛错 } } }], [{ - key: 'isSupported', - value: function isSupported() { - var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ['copy', 'cut']; + key: "isSupported", + value: function isSupported () { + var action = arguments.length > 0 && arguments[0] !== undefined ? arguments[0] : ["copy", "cut"]; - var actions = typeof action === 'string' ? [action] : action; + var actions = typeof action === "string" ? [action] : action; var support = !!document.queryCommandSupported; actions.forEach(function (action) { @@ -806,8 +801,8 @@ try {//IE8下会抛错 * @param {String} suffix * @param {Element} element */ - function getAttributeValue(suffix, element) { - var attribute = 'data-clipboard-' + suffix; + function getAttributeValue (suffix, element) { + var attribute = "data-clipboard-" + suffix; if (!element.hasAttribute(attribute)) { return; @@ -820,7 +815,7 @@ try {//IE8下会抛错 }); }, {"./clipboard-action": 7, "good-listener": 4, "tiny-emitter": 6}] - }, {}, [8])(8) + }, {}, [8])(8); }); } catch (e) { /* @@ -839,11 +834,11 @@ try {//IE8下会抛错 $.fn.zclip = function (params) { - if (typeof params == "object" && !params.length) { + if (typeof params === "object" && !params.length) { var settings = $.extend({ - path: 'ZeroClipboard.swf', + path: "ZeroClipboard.swf", copy: null, beforeCopy: null, afterCopy: null, @@ -858,62 +853,62 @@ try {//IE8下会抛错 var o = $(this); - if (o.is(':visible') && (typeof settings.copy == 'string' || $.isFunction(settings.copy))) { + if (o.is(":visible") && (typeof settings.copy === "string" || $.isFunction(settings.copy))) { ZeroClipboard.setMoviePath(settings.path); var clip = new ZeroClipboard.Client(); if ($.isFunction(settings.copy)) { - o.bind('zClip_copy', settings.copy); + o.bind("zClip_copy", settings.copy); } if ($.isFunction(settings.beforeCopy)) { - o.bind('zClip_beforeCopy', settings.beforeCopy); + o.bind("zClip_beforeCopy", settings.beforeCopy); } if ($.isFunction(settings.afterCopy)) { - o.bind('zClip_afterCopy', settings.afterCopy); + o.bind("zClip_afterCopy", settings.afterCopy); } clip.setHandCursor(settings.setHandCursor); clip.setCSSEffects(settings.setCSSEffects); - clip.addEventListener('mouseOver', function (client) { - o.trigger('mouseenter'); + clip.addEventListener("mouseOver", function (client) { + o.trigger("mouseenter"); }); - clip.addEventListener('mouseOut', function (client) { - o.trigger('mouseleave'); + clip.addEventListener("mouseOut", function (client) { + o.trigger("mouseleave"); }); - clip.addEventListener('mouseDown', function (client) { + clip.addEventListener("mouseDown", function (client) { - o.trigger('mousedown'); + o.trigger("mousedown"); if (!$.isFunction(settings.copy)) { clip.setText(settings.copy); } else { - clip.setText(o.triggerHandler('zClip_copy')); + clip.setText(o.triggerHandler("zClip_copy")); } if ($.isFunction(settings.beforeCopy)) { - o.trigger('zClip_beforeCopy'); + o.trigger("zClip_beforeCopy"); } }); - clip.addEventListener('complete', function (client, text) { + clip.addEventListener("complete", function (client, text) { if ($.isFunction(settings.afterCopy)) { - o.trigger('zClip_afterCopy'); + o.trigger("zClip_afterCopy"); } else { if (text.length > 500) { text = text.substr(0, 500) + "...\n\n(" + (text.length - 500) + " characters not shown)"; } - o.removeClass('hover'); + o.removeClass("hover"); alert("Copied text to clipboard:\n\n " + text); } if (settings.clickAfter) { - o.trigger('click'); + o.trigger("click"); } }); @@ -921,7 +916,7 @@ try {//IE8下会抛错 clip.glue(o[0], o.parent()[0]); - $(window).bind('load resize', function () { + $(window).bind("load resize", function () { clip.reposition(); }); @@ -930,25 +925,25 @@ try {//IE8下会抛错 }); - } else if (typeof params == "string") { + } else if (typeof params === "string") { return this.each(function () { var o = $(this); params = params.toLowerCase(); - var zclipId = o.data('zclipId'); - var clipElm = $('#' + zclipId + '.zclip'); + var zclipId = o.data("zclipId"); + var clipElm = $("#" + zclipId + ".zclip"); if (params == "remove") { clipElm.remove(); - o.removeClass('active hover'); + o.removeClass("active hover"); } else if (params == "hide") { clipElm.hide(); - o.removeClass('active hover'); + o.removeClass("active hover"); } else if (params == "show") { @@ -960,38 +955,38 @@ try {//IE8下会抛错 } - } + }; })(jQuery); -// ZeroClipboard -// Simple Set Clipboard System -// Author: Joseph Huckaby + // ZeroClipboard + // Simple Set Clipboard System + // Author: Joseph Huckaby var ZeroClipboard = { version: "1.0.7", clients: {}, // registered upload clients on page, indexed by id - moviePath: 'ZeroClipboard.swf', + moviePath: "ZeroClipboard.swf", // URL to movie nextId: 1, // ID of next movie $: function (thingy) { // simple DOM lookup utility function - if (typeof(thingy) == 'string') thingy = document.getElementById(thingy); + if (typeof(thingy) === "string") thingy = document.getElementById(thingy); if (!thingy.addClass) { // extend element with a few useful methods thingy.hide = function () { - this.style.display = 'none'; + this.style.display = "none"; }; thingy.show = function () { - this.style.display = ''; + this.style.display = ""; }; thingy.addClass = function (name) { this.removeClass(name); - this.className += ' ' + name; + this.className += " " + name; }; thingy.removeClass = function (name) { var classes = this.className.split(/\s+/); @@ -1004,7 +999,7 @@ try {//IE8下会抛错 } if (idx > -1) { classes.splice(idx, 1); - this.className = classes.join(' '); + this.className = classes.join(" "); } return this; }; @@ -1056,7 +1051,7 @@ try {//IE8下会抛错 // unique ID this.id = ZeroClipboard.nextId++; - this.movieId = 'ZeroClipboardMovie_' + this.id; + this.movieId = "ZeroClipboardMovie_" + this.id; // register client with singleton to receive flash events ZeroClipboard.register(this.id, this); @@ -1074,7 +1069,7 @@ try {//IE8下会抛错 // whether movie is ready to receive events or not movie: null, // reference to movie object - clipText: '', + clipText: "", // text to copy to clipboard handCursorEnabled: true, // whether to show hand cursor, or default pointer cursor @@ -1093,29 +1088,29 @@ try {//IE8下会抛错 zIndex = parseInt(this.domElement.style.zIndex, 10) + 1; } - if (typeof(appendElem) == 'string') { + if (typeof(appendElem) === "string") { appendElem = ZeroClipboard.$(appendElem); - } else if (typeof(appendElem) == 'undefined') { - appendElem = document.getElementsByTagName('body')[0]; + } else if (typeof(appendElem) === "undefined") { + appendElem = document.getElementsByTagName("body")[0]; } // find X/Y position of domElement var box = ZeroClipboard.getDOMObjectPosition(this.domElement, appendElem); // create floating DIV above element - this.div = document.createElement('div'); + this.div = document.createElement("div"); this.div.className = "zclip"; this.div.id = "zclip-" + this.movieId; - $(this.domElement).data('zclipId', 'zclip-' + this.movieId); + $(this.domElement).data("zclipId", "zclip-" + this.movieId); var style = this.div.style; - style.position = 'absolute'; - style.left = '' + box.left + 'px'; - style.top = '' + box.top + 'px'; - style.width = '' + box.width + 'px'; - style.height = '' + box.height + 'px'; + style.position = "absolute"; + style.left = "" + box.left + "px"; + style.top = "" + box.top + "px"; + style.width = "" + box.width + "px"; + style.height = "" + box.height + "px"; style.zIndex = zIndex; - if (typeof(stylesToAdd) == 'object') { + if (typeof(stylesToAdd) === "object") { for (addedStyle in stylesToAdd) { style[addedStyle] = stylesToAdd[addedStyle]; } @@ -1129,16 +1124,16 @@ try {//IE8下会抛错 getHTML: function (width, height) { // return HTML for movie - var html = ''; - var flashvars = 'id=' + this.id + '&width=' + width + '&height=' + height; + var html = ""; + var flashvars = "id=" + this.id + "&width=" + width + "&height=" + height; if (navigator.userAgent.match(/MSIE/)) { // IE gets an OBJECT tag - var protocol = location.href.match(/^https/i) ? 'https://' : 'http://'; - html += ''; + var protocol = location.href.match(/^https/i) ? "https://" : "http://"; + html += ""; } else { // all other browsers get an EMBED tag - html += ''; + html += ""; } return html; }, @@ -1146,7 +1141,7 @@ try {//IE8下会抛错 hide: function () { // temporarily hide floater offscreen if (this.div) { - this.div.style.left = '-2000px'; + this.div.style.left = "-2000px"; } }, @@ -1159,13 +1154,13 @@ try {//IE8下会抛错 // destroy control and floater if (this.domElement && this.div) { this.hide(); - this.div.innerHTML = ''; + this.div.innerHTML = ""; - var body = document.getElementsByTagName('body')[0]; + var body = document.getElementsByTagName("body")[0]; try { body.removeChild(this.div); } catch (e) { - ; + } this.domElement = null; @@ -1184,8 +1179,8 @@ try {//IE8下会抛错 if (this.domElement && this.div) { var box = ZeroClipboard.getDOMObjectPosition(this.domElement); var style = this.div.style; - style.left = '' + box.left + 'px'; - style.top = '' + box.top + 'px'; + style.left = "" + box.left + "px"; + style.top = "" + box.top + "px"; } }, @@ -1200,7 +1195,7 @@ try {//IE8下会抛错 addEventListener: function (eventName, func) { // add user event listener for event // event types: load, queueStart, fileStart, fileComplete, queueComplete, progress, error, cancel - eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + eventName = eventName.toString().toLowerCase().replace(/^on/, ""); if (!this.handlers[eventName]) { this.handlers[eventName] = []; } @@ -1222,18 +1217,18 @@ try {//IE8下会抛错 receiveEvent: function (eventName, args) { // receive event from flash - eventName = eventName.toString().toLowerCase().replace(/^on/, ''); + eventName = eventName.toString().toLowerCase().replace(/^on/, ""); // special behavior for certain events switch (eventName) { - case 'load': + case "load": // movie claims it is ready, but in IE this isn't always the case... // bug fix: Cannot extend EMBED DOM elements in Firefox, must use traditional function this.movie = document.getElementById(this.movieId); if (!this.movie) { var self = this; setTimeout(function () { - self.receiveEvent('load', null); + self.receiveEvent("load", null); }, 1); return; } @@ -1242,7 +1237,7 @@ try {//IE8下会抛错 if (!this.ready && navigator.userAgent.match(/Firefox/) && navigator.userAgent.match(/Windows/)) { var self = this; setTimeout(function () { - self.receiveEvent('load', null); + self.receiveEvent("load", null); }, 100); this.ready = true; return; @@ -1259,11 +1254,11 @@ try {//IE8下会抛错 } break; - case 'mouseover': + case "mouseover": if (this.domElement && this.cssEffects) { - this.domElement.addClass('hover'); + this.domElement.addClass("hover"); if (this.recoverActive) { - this.domElement.addClass('active'); + this.domElement.addClass("active"); } @@ -1272,27 +1267,27 @@ try {//IE8下会抛错 break; - case 'mouseout': + case "mouseout": if (this.domElement && this.cssEffects) { this.recoverActive = false; - if (this.domElement.hasClass('active')) { - this.domElement.removeClass('active'); + if (this.domElement.hasClass("active")) { + this.domElement.removeClass("active"); this.recoverActive = true; } - this.domElement.removeClass('hover'); + this.domElement.removeClass("hover"); } break; - case 'mousedown': + case "mousedown": if (this.domElement && this.cssEffects) { - this.domElement.addClass('active'); + this.domElement.addClass("active"); } break; - case 'mouseup': + case "mouseup": if (this.domElement && this.cssEffects) { - this.domElement.removeClass('active'); + this.domElement.removeClass("active"); this.recoverActive = false; } break; @@ -1301,13 +1296,13 @@ try {//IE8下会抛错 for (var idx = 0, len = this.handlers[eventName].length; idx < len; idx++) { var func = this.handlers[eventName][idx]; - if (typeof(func) == 'function') { + if (typeof(func) === "function") { // actual function reference func(this, args); - } else if ((typeof(func) == 'object') && (func.length == 2)) { + } else if ((typeof(func) === "object") && (func.length == 2)) { // PHP style object + method, i.e. [myObject, 'myMethod'] func[0][func[1]](this, args); - } else if (typeof(func) == 'string') { + } else if (typeof(func) === "string") { // name of function window[func](this, args); } diff --git a/src/case/clipboard/index.js b/src/case/clipboard/index.js index 314cf2e5e..aee8bfa7b 100644 --- a/src/case/clipboard/index.js +++ b/src/case/clipboard/index.js @@ -10,7 +10,7 @@ BI.ClipBoard = BI.inherit(BI.BasicButton, { extraCls: "bi-clipboard", copy: BI.emptyFn, afterCopy: BI.emptyFn - }) + }); }, _init: function () { @@ -25,7 +25,7 @@ BI.ClipBoard = BI.inherit(BI.BasicButton, { return BI.isFunction(o.copy) ? o.copy() : o.copy; } }); - this.clipboard.on("success", o.afterCopy) + this.clipboard.on("success", o.afterCopy); } else { this.element.zclip({ path: BI.resourceURL + "/ZeroClipboard.swf", diff --git a/src/case/colorchooser/colorchooser.custom.js b/src/case/colorchooser/colorchooser.custom.js index 13a3313a3..b43d67804 100644 --- a/src/case/colorchooser/colorchooser.custom.js +++ b/src/case/colorchooser/colorchooser.custom.js @@ -12,7 +12,7 @@ BI.CustomColorChooser = BI.inherit(BI.Widget, { baseCls: "bi-custom-color-chooser", width: 227, height: 245 - }) + }); }, _init: function () { @@ -53,7 +53,7 @@ BI.CustomColorChooser = BI.inherit(BI.Widget, { }], height: 215 }] - }) + }); }, setValue: function (color) { diff --git a/src/case/colorchooser/colorchooser.js b/src/case/colorchooser/colorchooser.js index 4a1f018a0..6025e2631 100644 --- a/src/case/colorchooser/colorchooser.js +++ b/src/case/colorchooser/colorchooser.js @@ -11,7 +11,7 @@ BI.ColorChooser = BI.inherit(BI.Widget, { return BI.extend(BI.ColorChooser.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-color-chooser", el: {} - }) + }); }, _init: function () { @@ -63,7 +63,7 @@ BI.ColorChooser = BI.inherit(BI.Widget, { this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { self.fireEvent(BI.ColorChooser.EVENT_CHANGE, arguments); - }) + }); }, isViewVisible: function () { diff --git a/src/case/colorchooser/colorchooser.popup.js b/src/case/colorchooser/colorchooser.popup.js index 3f3e6504a..773e554cc 100644 --- a/src/case/colorchooser/colorchooser.popup.js +++ b/src/case/colorchooser/colorchooser.popup.js @@ -12,7 +12,7 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { baseCls: "bi-color-chooser-popup", width: 200, height: 145 - }) + }); }, _init: function () { @@ -160,7 +160,7 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { el: this.more, height: 20 }] - }) + }); }, setStoreColors: function (colors) { @@ -168,13 +168,13 @@ BI.ColorChooserPopup = BI.inherit(BI.Widget, { var items = BI.map(colors, function (i, color) { return { value: color - } + }; }); BI.count(colors.length, 8, function (i) { items.push({ value: "", disabled: true - }) + }); }); this.storeColors.populate([items]); } diff --git a/src/case/colorchooser/colorchooser.trigger.js b/src/case/colorchooser/colorchooser.trigger.js index 55213bc7f..c38b5ad72 100644 --- a/src/case/colorchooser/colorchooser.trigger.js +++ b/src/case/colorchooser/colorchooser.trigger.js @@ -12,7 +12,7 @@ BI.ColorChooserTrigger = BI.inherit(BI.Trigger, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-color-chooser-trigger", height: 30 - }) + }); }, _init: function () { @@ -55,7 +55,7 @@ BI.ColorChooserTrigger = BI.inherit(BI.Trigger, { if (color === "") { this.colorContainer.element.css("background-color", "").removeClass("trans-color-background").addClass("auto-color-background"); } else if (color === "transparent") { - this.colorContainer.element.css("background-color", "").removeClass("auto-color-background").addClass("trans-color-background") + this.colorContainer.element.css("background-color", "").removeClass("auto-color-background").addClass("trans-color-background"); } else { this.colorContainer.element.css({"background-color": color}).removeClass("auto-color-background").removeClass("trans-color-background"); } diff --git a/src/case/colorchooser/colorpicker/button/button.colorpicker.js b/src/case/colorchooser/colorpicker/button/button.colorpicker.js index 047d750c7..df5412c51 100644 --- a/src/case/colorchooser/colorpicker/button/button.colorpicker.js +++ b/src/case/colorchooser/colorpicker/button/button.colorpicker.js @@ -11,7 +11,7 @@ BI.ColorPickerButton = BI.inherit(BI.BasicButton, { var conf = BI.ColorPickerButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-color-picker-button bi-background bi-border-top bi-border-left" - }) + }); }, _init: function () { @@ -50,10 +50,10 @@ BI.ColorPickerButton = BI.inherit(BI.BasicButton, { setSelected: function (b) { BI.ColorPickerButton.superclass.setSelected.apply(this, arguments); - if (!!b) { + if (b) { this._createMask(); } - BI.Maskers[!!b ? "show" : "hide"](this.getName()); + BI.Maskers[b ? "show" : "hide"](this.getName()); } }); BI.ColorPickerButton.EVENT_CHANGE = "ColorPickerButton.EVENT_CHANGE"; diff --git a/src/case/colorchooser/colorpicker/colorpicker.js b/src/case/colorchooser/colorpicker/colorpicker.js index 1469ed3ac..44c7592c1 100644 --- a/src/case/colorchooser/colorpicker/colorpicker.js +++ b/src/case/colorchooser/colorpicker/colorpicker.js @@ -11,7 +11,7 @@ BI.ColorPicker = BI.inherit(BI.Widget, { return BI.extend(BI.ColorPicker.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-color-picker", items: null - }) + }); }, _items: [ @@ -165,11 +165,11 @@ BI.ColorPicker = BI.inherit(BI.Widget, { }); this.colors.on(BI.ButtonGroup.EVENT_CHANGE, function () { self.fireEvent(BI.ColorPicker.EVENT_CHANGE, arguments); - }) + }); }, - populate: function(items){ - var args =[].slice.call(arguments); + populate: function (items) { + var args = [].slice.call(arguments); args[0] = BI.createItems(items, { type: "bi.color_picker_button", once: false diff --git a/src/case/colorchooser/colorpicker/editor.colorpicker.js b/src/case/colorchooser/colorpicker/editor.colorpicker.js index 8b662c9ed..8b040df4a 100644 --- a/src/case/colorchooser/colorpicker/editor.colorpicker.js +++ b/src/case/colorchooser/colorpicker/editor.colorpicker.js @@ -12,7 +12,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { baseCls: "bi-color-picker-editor", // width: 200, height: 20 - }) + }); }, _init: function () { @@ -94,7 +94,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { element: this, items: [{ el: this.colorShow, - width: 'fill' + width: "fill" }, { el: RGB[0], lgap: 10, @@ -129,7 +129,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { }, width: 18 }] - }) + }); }, setValue: function (color) { @@ -163,7 +163,7 @@ BI.ColorPickerEditor = BI.inherit(BI.Widget, { r: this.R.getValue(), g: this.G.getValue(), b: this.B.getValue() - })) + })); } }); BI.ColorPickerEditor.EVENT_CHANGE = "ColorPickerEditor.EVENT_CHANGE"; diff --git a/src/case/colorchooser/farbtastic/farbtastic.js b/src/case/colorchooser/farbtastic/farbtastic.js index 347a04188..e4937eacc 100644 --- a/src/case/colorchooser/farbtastic/farbtastic.js +++ b/src/case/colorchooser/farbtastic/farbtastic.js @@ -12,7 +12,7 @@ BI.Farbtastic = BI.inherit(BI.Widget, { baseCls: "bi-farbtastic", width: 195, height: 195 - }) + }); }, _init: function () { diff --git a/src/case/colorchooser/farbtastic/jquery.farbtastic.js b/src/case/colorchooser/farbtastic/jquery.farbtastic.js index c523cfa00..008ae56e1 100644 --- a/src/case/colorchooser/farbtastic/jquery.farbtastic.js +++ b/src/case/colorchooser/farbtastic/jquery.farbtastic.js @@ -18,159 +18,157 @@ */ jQuery.fn.farbtastic = function (callback) { - $.farbtastic(this, callback); - return this; + $.farbtastic(this, callback); + return this; }; jQuery.farbtastic = function (container, callback) { - var container = $(container).get(0); - return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback)); -} + var container = $(container).get(0); + return container.farbtastic || (container.farbtastic = new jQuery._farbtastic(container, callback)); +}; jQuery._farbtastic = function (container, callback) { - // Store farbtastic object - var fb = this; - - // Insert markup - $(container).html('
    '); - var e = $('.farbtastic', container); - fb.wheel = $('.wheel', container).get(0); - // Dimensions - fb.radius = 84; - fb.square = 100; - fb.width = 194; - - // Fix background PNGs in IE6 - if (navigator.appVersion.match(/MSIE [0-6]\./)) { - $('*', e).each(function () { - if (this.currentStyle.backgroundImage != 'none') { - var image = this.currentStyle.backgroundImage; - image = this.currentStyle.backgroundImage.substring(5, image.length - 2); - $(this).css({ - 'backgroundImage': 'none', - 'filter': "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" + // Store farbtastic object + var fb = this; + + // Insert markup + $(container).html("
    "); + var e = $(".farbtastic", container); + fb.wheel = $(".wheel", container).get(0); + // Dimensions + fb.radius = 84; + fb.square = 100; + fb.width = 194; + + // Fix background PNGs in IE6 + if (navigator.appVersion.match(/MSIE [0-6]\./)) { + $("*", e).each(function () { + if (this.currentStyle.backgroundImage != "none") { + var image = this.currentStyle.backgroundImage; + image = this.currentStyle.backgroundImage.substring(5, image.length - 2); + $(this).css({ + backgroundImage: "none", + filter: "progid:DXImageTransform.Microsoft.AlphaImageLoader(enabled=true, sizingMethod=crop, src='" + image + "')" + }); + } }); - } - }); - } + } - /** + /** * Link to the given element(s) or callback. */ - fb.linkTo = function (callback) { + fb.linkTo = function (callback) { // Unbind previous nodes - if (typeof fb.callback == 'object') { - $(fb.callback).unbind('keyup', fb.updateValue); - } - - // Reset color - fb.color = null; + if (typeof fb.callback === "object") { + $(fb.callback).unbind("keyup", fb.updateValue); + } - // Bind callback or elements - if (typeof callback == 'function') { - fb.callback = callback; - } - else if (typeof callback == 'object' || typeof callback == 'string') { - fb.callback = $(callback); - fb.callback.bind('keyup', fb.updateValue); - if (fb.callback.get(0).value) { - fb.setColor(fb.callback.get(0).value); - } - } - return this; - } - fb.updateValue = function (event) { - if (this.value && this.value != fb.color) { - fb.setColor(this.value); - } - } + // Reset color + fb.color = null; + + // Bind callback or elements + if (typeof callback === "function") { + fb.callback = callback; + } else if (typeof callback === "object" || typeof callback === "string") { + fb.callback = $(callback); + fb.callback.bind("keyup", fb.updateValue); + if (fb.callback.get(0).value) { + fb.setColor(fb.callback.get(0).value); + } + } + return this; + }; + fb.updateValue = function (event) { + if (this.value && this.value != fb.color) { + fb.setColor(this.value); + } + }; - /** + /** * Change color with HTML syntax #123456 */ - fb.setColor = function (color) { - var unpack = fb.unpack(color); - if (fb.color != color && unpack) { - fb.color = color; - fb.rgb = unpack; - fb.hsl = fb.RGBToHSL(fb.rgb); - fb.updateDisplay(); - } - return this; - } + fb.setColor = function (color) { + var unpack = fb.unpack(color); + if (fb.color != color && unpack) { + fb.color = color; + fb.rgb = unpack; + fb.hsl = fb.RGBToHSL(fb.rgb); + fb.updateDisplay(); + } + return this; + }; - /** + /** * Change color with HSL triplet [0..1, 0..1, 0..1] */ - fb.setHSL = function (hsl) { - fb.hsl = hsl; - fb.rgb = fb.HSLToRGB(hsl); - fb.color = fb.pack(fb.rgb); - fb.updateDisplay(); - return this; - } + fb.setHSL = function (hsl) { + fb.hsl = hsl; + fb.rgb = fb.HSLToRGB(hsl); + fb.color = fb.pack(fb.rgb); + fb.updateDisplay(); + return this; + }; - ///////////////////////////////////////////////////// + // /////////////////////////////////////////////////// - /** + /** * Retrieve the coordinates of the given event relative to the center * of the widget. */ - fb.widgetCoords = function (event) { - var x, y; - var el = event.target || event.srcElement; - var reference = fb.wheel; - - if (typeof event.offsetX != 'undefined') { - // Use offset coordinates and find common offsetParent - var pos = { x: event.offsetX, y: event.offsetY }; - - // Send the coordinates upwards through the offsetParent chain. - var e = el; - while (e) { - e.mouseX = pos.x; - e.mouseY = pos.y; - pos.x += e.offsetLeft; - pos.y += e.offsetTop; - e = e.offsetParent; - } - - // Look for the coordinates starting from the wheel widget. - var e = reference; - var offset = { x: 0, y: 0 } - while (e) { - if (typeof e.mouseX != 'undefined') { - x = e.mouseX - offset.x; - y = e.mouseY - offset.y; - break; + fb.widgetCoords = function (event) { + var x, y; + var el = event.target || event.srcElement; + var reference = fb.wheel; + + if (typeof event.offsetX !== "undefined") { + // Use offset coordinates and find common offsetParent + var pos = { x: event.offsetX, y: event.offsetY }; + + // Send the coordinates upwards through the offsetParent chain. + var e = el; + while (e) { + e.mouseX = pos.x; + e.mouseY = pos.y; + pos.x += e.offsetLeft; + pos.y += e.offsetTop; + e = e.offsetParent; + } + + // Look for the coordinates starting from the wheel widget. + var e = reference; + var offset = { x: 0, y: 0 }; + while (e) { + if (typeof e.mouseX !== "undefined") { + x = e.mouseX - offset.x; + y = e.mouseY - offset.y; + break; + } + offset.x += e.offsetLeft; + offset.y += e.offsetTop; + e = e.offsetParent; + } + + // Reset stored coordinates + e = el; + while (e) { + e.mouseX = undefined; + e.mouseY = undefined; + e = e.offsetParent; + } + } else { + // Use absolute coordinates + var pos = fb.absolutePosition(reference); + x = (event.pageX || 0 * (event.clientX + $("html").get(0).scrollLeft)) - pos.x; + y = (event.pageY || 0 * (event.clientY + $("html").get(0).scrollTop)) - pos.y; } - offset.x += e.offsetLeft; - offset.y += e.offsetTop; - e = e.offsetParent; - } - - // Reset stored coordinates - e = el; - while (e) { - e.mouseX = undefined; - e.mouseY = undefined; - e = e.offsetParent; - } - } - else { - // Use absolute coordinates - var pos = fb.absolutePosition(reference); - x = (event.pageX || 0*(event.clientX + $('html').get(0).scrollLeft)) - pos.x; - y = (event.pageY || 0*(event.clientY + $('html').get(0).scrollTop)) - pos.y; - } - // Subtract distance to middle - return { x: x - fb.width / 2, y: y - fb.width / 2 }; - } + // Subtract distance to middle + return { x: x - fb.width / 2, y: y - fb.width / 2 }; + }; - /** + /** * Mousedown handler */ - fb.click = function (event) { + fb.click = function (event) { // Capture mouse // if (!document.dragging) { // $(document).bind('mousemove', fb.mousemove).bind('mouseup', fb.mouseup); @@ -178,168 +176,165 @@ jQuery._farbtastic = function (container, callback) { // } // Check which area is being dragged - var pos = fb.widgetCoords(event); - fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; + var pos = fb.widgetCoords(event); + fb.circleDrag = Math.max(Math.abs(pos.x), Math.abs(pos.y)) * 2 > fb.square; - // Process - fb.mousemove(event); - return false; - } + // Process + fb.mousemove(event); + return false; + }; - /** + /** * Mousemove handler */ - fb.mousemove = function (event) { + fb.mousemove = function (event) { // Get coordinates relative to color picker center - var pos = fb.widgetCoords(event); - - // Set new HSL parameters - if (fb.circleDrag) { - var hue = Math.atan2(pos.x, -pos.y) / 6.28; - if (hue < 0) hue += 1; - fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); - } - else { - var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); - var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); - fb.setHSL([fb.hsl[0], sat, lum]); - } - return false; - } + var pos = fb.widgetCoords(event); + + // Set new HSL parameters + if (fb.circleDrag) { + var hue = Math.atan2(pos.x, -pos.y) / 6.28; + if (hue < 0) hue += 1; + fb.setHSL([hue, fb.hsl[1], fb.hsl[2]]); + } else { + var sat = Math.max(0, Math.min(1, -(pos.x / fb.square) + .5)); + var lum = Math.max(0, Math.min(1, -(pos.y / fb.square) + .5)); + fb.setHSL([fb.hsl[0], sat, lum]); + } + return false; + }; - /** + /** * Mouseup handler */ - // fb.mouseup = function () { - // // Uncapture mouse - // $(document).unbind('mousemove', fb.mousemove); - // $(document).unbind('mouseup', fb.mouseup); - // document.dragging = false; - // } - - /** + // fb.mouseup = function () { + // // Uncapture mouse + // $(document).unbind('mousemove', fb.mousemove); + // $(document).unbind('mouseup', fb.mouseup); + // document.dragging = false; + // } + + /** * Update the markers and styles */ - fb.updateDisplay = function () { + fb.updateDisplay = function () { // Markers - var angle = fb.hsl[0] * 6.28; - $('.h-marker', e).css({ - left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + 'px', - top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + 'px' - }); - - $('.sl-marker', e).css({ - left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + 'px', - top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + 'px' - }); - - // Saturation/Luminance gradient - $('.color', e).css('backgroundColor', fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); - - // Linked elements or callback - if (typeof fb.callback == 'object') { - // Set background/foreground color - $(fb.callback).css({ - backgroundColor: fb.color, - color: fb.hsl[2] > 0.5 ? '#000' : '#fff' - }); - - // Change linked value - $(fb.callback).each(function() { - if (this.value && this.value != fb.color) { - this.value = fb.color; + var angle = fb.hsl[0] * 6.28; + $(".h-marker", e).css({ + left: Math.round(Math.sin(angle) * fb.radius + fb.width / 2) + "px", + top: Math.round(-Math.cos(angle) * fb.radius + fb.width / 2) + "px" + }); + + $(".sl-marker", e).css({ + left: Math.round(fb.square * (.5 - fb.hsl[1]) + fb.width / 2) + "px", + top: Math.round(fb.square * (.5 - fb.hsl[2]) + fb.width / 2) + "px" + }); + + // Saturation/Luminance gradient + $(".color", e).css("backgroundColor", fb.pack(fb.HSLToRGB([fb.hsl[0], 1, 0.5]))); + + // Linked elements or callback + if (typeof fb.callback === "object") { + // Set background/foreground color + $(fb.callback).css({ + backgroundColor: fb.color, + color: fb.hsl[2] > 0.5 ? "#000" : "#fff" + }); + + // Change linked value + $(fb.callback).each(function () { + if (this.value && this.value != fb.color) { + this.value = fb.color; + } + }); + } else if (typeof fb.callback === "function") { + fb.callback.call(fb, fb.color); } - }); - } - else if (typeof fb.callback == 'function') { - fb.callback.call(fb, fb.color); - } - } + }; - /** + /** * Get absolute position of element */ - fb.absolutePosition = function (el) { - var r = { x: el.offsetLeft, y: el.offsetTop }; - // Resolve relative to offsetParent - if (el.offsetParent) { - var tmp = fb.absolutePosition(el.offsetParent); - r.x += tmp.x; - r.y += tmp.y; - } - return r; - }; - - /* Various color utility functions */ - fb.pack = function (rgb) { - var r = Math.round(rgb[0] * 255); - var g = Math.round(rgb[1] * 255); - var b = Math.round(rgb[2] * 255); - return '#' + (r < 16 ? '0' : '') + r.toString(16) + - (g < 16 ? '0' : '') + g.toString(16) + - (b < 16 ? '0' : '') + b.toString(16); - } - - fb.unpack = function (color) { - if (color.length == 7) { - return [parseInt('0x' + color.substring(1, 3)) / 255, - parseInt('0x' + color.substring(3, 5)) / 255, - parseInt('0x' + color.substring(5, 7)) / 255]; - } - else if (color.length == 4) { - return [parseInt('0x' + color.substring(1, 2)) / 15, - parseInt('0x' + color.substring(2, 3)) / 15, - parseInt('0x' + color.substring(3, 4)) / 15]; - } - } - - fb.HSLToRGB = function (hsl) { - var m1, m2, r, g, b; - var h = hsl[0], s = hsl[1], l = hsl[2]; - m2 = (l <= 0.5) ? l * (s + 1) : l + s - l*s; - m1 = l * 2 - m2; - return [this.hueToRGB(m1, m2, h+0.33333), - this.hueToRGB(m1, m2, h), - this.hueToRGB(m1, m2, h-0.33333)]; - } - - fb.hueToRGB = function (m1, m2, h) { - h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); - if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; - if (h * 2 < 1) return m2; - if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; - return m1; - } - - fb.RGBToHSL = function (rgb) { - var min, max, delta, h, s, l; - var r = rgb[0], g = rgb[1], b = rgb[2]; - min = Math.min(r, Math.min(g, b)); - max = Math.max(r, Math.max(g, b)); - delta = max - min; - l = (min + max) / 2; - s = 0; - if (l > 0 && l < 1) { - s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); - } - h = 0; - if (delta > 0) { - if (max == r && max != g) h += (g - b) / delta; - if (max == g && max != b) h += (2 + (b - r) / delta); - if (max == b && max != r) h += (4 + (r - g) / delta); - h /= 6; - } - return [h, s, l]; - } + fb.absolutePosition = function (el) { + var r = { x: el.offsetLeft, y: el.offsetTop }; + // Resolve relative to offsetParent + if (el.offsetParent) { + var tmp = fb.absolutePosition(el.offsetParent); + r.x += tmp.x; + r.y += tmp.y; + } + return r; + }; + + /* Various color utility functions */ + fb.pack = function (rgb) { + var r = Math.round(rgb[0] * 255); + var g = Math.round(rgb[1] * 255); + var b = Math.round(rgb[2] * 255); + return "#" + (r < 16 ? "0" : "") + r.toString(16) + + (g < 16 ? "0" : "") + g.toString(16) + + (b < 16 ? "0" : "") + b.toString(16); + }; + + fb.unpack = function (color) { + if (color.length == 7) { + return [parseInt("0x" + color.substring(1, 3)) / 255, + parseInt("0x" + color.substring(3, 5)) / 255, + parseInt("0x" + color.substring(5, 7)) / 255]; + } else if (color.length == 4) { + return [parseInt("0x" + color.substring(1, 2)) / 15, + parseInt("0x" + color.substring(2, 3)) / 15, + parseInt("0x" + color.substring(3, 4)) / 15]; + } + }; + + fb.HSLToRGB = function (hsl) { + var m1, m2, r, g, b; + var h = hsl[0], s = hsl[1], l = hsl[2]; + m2 = (l <= 0.5) ? l * (s + 1) : l + s - l * s; + m1 = l * 2 - m2; + return [this.hueToRGB(m1, m2, h + 0.33333), + this.hueToRGB(m1, m2, h), + this.hueToRGB(m1, m2, h - 0.33333)]; + }; + + fb.hueToRGB = function (m1, m2, h) { + h = (h < 0) ? h + 1 : ((h > 1) ? h - 1 : h); + if (h * 6 < 1) return m1 + (m2 - m1) * h * 6; + if (h * 2 < 1) return m2; + if (h * 3 < 2) return m1 + (m2 - m1) * (0.66666 - h) * 6; + return m1; + }; + + fb.RGBToHSL = function (rgb) { + var min, max, delta, h, s, l; + var r = rgb[0], g = rgb[1], b = rgb[2]; + min = Math.min(r, Math.min(g, b)); + max = Math.max(r, Math.max(g, b)); + delta = max - min; + l = (min + max) / 2; + s = 0; + if (l > 0 && l < 1) { + s = delta / (l < 0.5 ? (2 * l) : (2 - 2 * l)); + } + h = 0; + if (delta > 0) { + if (max == r && max != g) h += (g - b) / delta; + if (max == g && max != b) h += (2 + (b - r) / delta); + if (max == b && max != r) h += (4 + (r - g) / delta); + h /= 6; + } + return [h, s, l]; + }; - // Install mousedown handler (the others are set on the document on-demand) - $('*', e).click(fb.click); + // Install mousedown handler (the others are set on the document on-demand) + $("*", e).click(fb.click); // Init color - fb.setColor('#000000'); + fb.setColor("#000000"); - // Set linked elements/callback - if (callback) { - fb.linkTo(callback); - } -} \ No newline at end of file + // Set linked elements/callback + if (callback) { + fb.linkTo(callback); + } +}; \ No newline at end of file diff --git a/src/case/combo/bubblecombo/combo.bubble.js b/src/case/combo/bubblecombo/combo.bubble.js index f5e836ada..553cb63ec 100644 --- a/src/case/combo/bubblecombo/combo.bubble.js +++ b/src/case/combo/bubblecombo/combo.bubble.js @@ -13,20 +13,20 @@ BI.BubbleCombo = BI.inherit(BI.Widget, { baseCls: "bi-bubble-combo", trigger: "click", toggle: true, - direction: "bottom", //top||bottom||left||right||top,left||top,right||bottom,left||bottom,right + direction: "bottom", // top||bottom||left||right||top,left||top,right||bottom,left||bottom,right isDefaultInit: false, destroyWhenHide: false, - isNeedAdjustHeight: true,//是否需要高度调整 + isNeedAdjustHeight: true, // 是否需要高度调整 isNeedAdjustWidth: true, stopPropagation: false, - adjustLength: 0,//调整的距离 + adjustLength: 0, // 调整的距离 // adjustXOffset: 0, // adjustYOffset: 10, hideChecker: BI.emptyFn, - offsetStyle: "left", //left,right,center + offsetStyle: "left", // left,right,center el: {}, popup: {} - }) + }); }, _init: function () { BI.BubbleCombo.superclass._init.apply(this, arguments); @@ -143,7 +143,7 @@ BI.BubbleCombo = BI.inherit(BI.Widget, { type: "bi.absolute", element: this, items: [pos] - }) + }); }, _createLeftTriangle: function () { diff --git a/src/case/combo/bubblecombo/popup.bubble.js b/src/case/combo/bubblecombo/popup.bubble.js index 5ab6352ba..ca729c76b 100644 --- a/src/case/combo/bubblecombo/popup.bubble.js +++ b/src/case/combo/bubblecombo/popup.bubble.js @@ -9,7 +9,7 @@ BI.BubblePopupView = BI.inherit(BI.PopupView, { var config = BI.BubblePopupView.superclass._defaultConfig.apply(this, arguments); return BI.extend(config, { baseCls: config.baseCls + " bi-bubble-popup-view" - }) + }); }, _init: function () { BI.BubblePopupView.superclass._init.apply(this, arguments); @@ -62,7 +62,7 @@ BI.BubblePopupView = BI.inherit(BI.PopupView, { type: "bi.absolute", element: this, items: [pos] - }) + }); }, hideLine: function () { @@ -83,7 +83,7 @@ BI.BubblePopupBarView = BI.inherit(BI.BubblePopupView, { return BI.extend(BI.BubblePopupBarView.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-bubble-bar-popup-view", buttons: [{value: BI.i18nText(BI.i18nText("BI-Basic_Sure"))}, {value: BI.i18nText("BI-Basic_Cancel"), level: "ignore"}] - }) + }); }, _init: function () { BI.BubblePopupBarView.superclass._init.apply(this, arguments); @@ -93,20 +93,20 @@ BI.BubblePopupBarView = BI.inherit(BI.BubblePopupView, { var items = []; BI.each(o.buttons.reverse(), function (i, buttonOpt) { - if(BI.isWidget(buttonOpt)){ + if(BI.isWidget(buttonOpt)) { items.push(buttonOpt); }else{ items.push(BI.extend({ - type: 'bi.button', + type: "bi.button", height: 30, handler: function (v) { self.fireEvent(BI.BubblePopupBarView.EVENT_CLICK_TOOLBAR_BUTTON, v); } - }, buttonOpt)) + }, buttonOpt)); } }); return BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", height: 40, hgap: 10, bgap: 10, diff --git a/src/case/combo/editoriconcheckcombo/combo.editoriconcheck.js b/src/case/combo/editoriconcheckcombo/combo.editoriconcheck.js index 6e3475310..9e6cb680d 100644 --- a/src/case/combo/editoriconcheckcombo/combo.editoriconcheck.js +++ b/src/case/combo/editoriconcheckcombo/combo.editoriconcheck.js @@ -13,7 +13,7 @@ BI.EditorIconCheckCombo = BI.inherit(BI.Widget, { allowBlank: true, watermark: "", errorText: "" - }) + }); }, _init: function () { diff --git a/src/case/combo/iconcombo/combo.icon.js b/src/case/combo/iconcombo/combo.icon.js index 96a022d58..8cbe5afaa 100644 --- a/src/case/combo/iconcombo/combo.icon.js +++ b/src/case/combo/iconcombo/combo.icon.js @@ -14,15 +14,15 @@ BI.IconCombo = BI.inherit(BI.Widget, { el: {}, popup: {}, minWidth: 100, - maxWidth: 'auto', + maxWidth: "auto", maxHeight: 300, direction: "bottom", - adjustLength: 3,//调整的距离 + adjustLength: 3, // 调整的距离 adjustXOffset: 0, adjustYOffset: 0, offsetStyle: "left", chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE - }) + }); }, _init: function () { diff --git a/src/case/combo/iconcombo/trigger.iconcombo.js b/src/case/combo/iconcombo/trigger.iconcombo.js index 6889424e4..d3bfb0c13 100644 --- a/src/case/combo/iconcombo/trigger.iconcombo.js +++ b/src/case/combo/iconcombo/trigger.iconcombo.js @@ -71,11 +71,11 @@ BI.IconComboTrigger = BI.inherit(BI.Trigger, { var iconClass = ""; v = BI.isArray(v) ? v[0] : v; if (BI.any(this.options.items, function (i, item) { - if (v === item.value) { - iconClass = item.iconClass; - return true; - } - })) { + if (v === item.value) { + iconClass = item.iconClass; + return true; + } + })) { this.button.setIcon(iconClass); this.button.setSelected(true); this.down.setSelected(true); diff --git a/src/case/combo/staticcombo/combo.static.js b/src/case/combo/staticcombo/combo.static.js index 824e68929..f0c196171 100644 --- a/src/case/combo/staticcombo/combo.static.js +++ b/src/case/combo/staticcombo/combo.static.js @@ -13,7 +13,7 @@ BI.StaticCombo = BI.inherit(BI.Widget, { el: {}, items: [], chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE - }) + }); }, _init: function () { diff --git a/src/case/combo/textvaluecheckcombo/combo.textvaluechecksmall.js b/src/case/combo/textvaluecheckcombo/combo.textvaluechecksmall.js index a5bcdcaa6..df7e15a7d 100644 --- a/src/case/combo/textvaluecheckcombo/combo.textvaluechecksmall.js +++ b/src/case/combo/textvaluecheckcombo/combo.textvaluechecksmall.js @@ -10,7 +10,7 @@ BI.SmallTextValueCheckCombo = BI.inherit(BI.Widget, { height: 24, chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, text: "" - }) + }); }, _init: function () { diff --git a/src/case/combo/textvaluecombo/combo.textvaluesmall.js b/src/case/combo/textvaluecombo/combo.textvaluesmall.js index 3a6c86057..d2bcd8bc0 100644 --- a/src/case/combo/textvaluecombo/combo.textvaluesmall.js +++ b/src/case/combo/textvaluecombo/combo.textvaluesmall.js @@ -12,7 +12,7 @@ BI.SmallTextValueCombo = BI.inherit(BI.Widget, { chooseType: BI.ButtonGroup.CHOOSE_TYPE_SINGLE, el: {}, text: "" - }) + }); }, _init: function () { diff --git a/src/case/combo/textvaluedownlistcombo/combo.textvaluedownlist.js b/src/case/combo/textvaluedownlistcombo/combo.textvaluedownlist.js index ded6b47e2..cc9391734 100644 --- a/src/case/combo/textvaluedownlistcombo/combo.textvaluedownlist.js +++ b/src/case/combo/textvaluedownlistcombo/combo.textvaluedownlist.js @@ -7,7 +7,7 @@ BI.TextValueDownListCombo = BI.inherit(BI.Widget, { return BI.extend(BI.TextValueDownListCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-text-value-down-list-combo", height: 30 - }) + }); }, _init: function () { @@ -49,7 +49,7 @@ BI.TextValueDownListCombo = BI.inherit(BI.Widget, { BI.each(BI.flatten(this.options.items), function (idx, item) { if (BI.has(item, "el")) { BI.each(item.children, function (id, it) { - self.valueMap[it.value] = {value: item.el.value, childValue: it.value} + self.valueMap[it.value] = {value: item.el.value, childValue: it.value}; }); } else { self.valueMap[item.value] = {value: item.value}; diff --git a/src/case/combo/textvaluedownlistcombo/trigger.textvaluedownlist.js b/src/case/combo/textvaluedownlistcombo/trigger.textvaluedownlist.js index 174f60f27..a498db359 100644 --- a/src/case/combo/textvaluedownlistcombo/trigger.textvaluedownlist.js +++ b/src/case/combo/textvaluedownlistcombo/trigger.textvaluedownlist.js @@ -27,12 +27,12 @@ BI.DownListSelectTextTrigger = BI.inherit(BI.Trigger, { }); }, - _formatItemArray: function(){ + _formatItemArray: function () { var sourceArray = BI.flatten(BI.deepClone(this.options.items)); var targetArray = []; - BI.each(sourceArray, function(idx, item){ - if(BI.has(item, "el")){ - BI.each(item.children, function(id, it){ + BI.each(sourceArray, function (idx, item) { + if(BI.has(item, "el")) { + BI.each(item.children, function (id, it) { it.text = item.el.text + "(" + it.text + ")"; }); targetArray = BI.concat(targetArray, item.children); diff --git a/src/case/editor/editor.clear.js b/src/case/editor/editor.clear.js index 121265b56..c784a862e 100644 --- a/src/case/editor/editor.clear.js +++ b/src/case/editor/editor.clear.js @@ -71,34 +71,34 @@ BI.ClearEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.ClearEditor.EVENT_KEY_DOWN, v); }); this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.ClearEditor.EVENT_SPACE) + self.fireEvent(BI.ClearEditor.EVENT_SPACE); }); this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.ClearEditor.EVENT_BACKSPACE) + self.fireEvent(BI.ClearEditor.EVENT_BACKSPACE); }); this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.ClearEditor.EVENT_VALID) + self.fireEvent(BI.ClearEditor.EVENT_VALID); }); this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.ClearEditor.EVENT_ERROR) + self.fireEvent(BI.ClearEditor.EVENT_ERROR); }); this.editor.on(BI.Editor.EVENT_ENTER, function () { self.fireEvent(BI.ClearEditor.EVENT_ENTER); }); this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.ClearEditor.EVENT_RESTRICT) + self.fireEvent(BI.ClearEditor.EVENT_RESTRICT); }); this.editor.on(BI.Editor.EVENT_EMPTY, function () { self._checkClear(); - self.fireEvent(BI.ClearEditor.EVENT_EMPTY) + self.fireEvent(BI.ClearEditor.EVENT_EMPTY); }); this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.ClearEditor.EVENT_REMOVE) + self.fireEvent(BI.ClearEditor.EVENT_REMOVE); }); this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.ClearEditor.EVENT_CONFIRM) + self.fireEvent(BI.ClearEditor.EVENT_CONFIRM); }); this.editor.on(BI.Editor.EVENT_START, function () { self.fireEvent(BI.ClearEditor.EVENT_START); diff --git a/src/case/editor/editor.shelter.js b/src/case/editor/editor.shelter.js index 86fe2179c..74e9008ba 100644 --- a/src/case/editor/editor.shelter.js +++ b/src/case/editor/editor.shelter.js @@ -22,7 +22,7 @@ BI.ShelterEditor = BI.inherit(BI.Widget, { errorText: "", height: 24, textAlign: "left" - }) + }); }, _init: function () { diff --git a/src/case/editor/editor.sign.initial.js b/src/case/editor/editor.sign.initial.js index 344634e45..629edd79a 100644 --- a/src/case/editor/editor.sign.initial.js +++ b/src/case/editor/editor.sign.initial.js @@ -20,7 +20,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { value: "", text: "", height: 24 - }) + }); }, _init: function () { @@ -59,7 +59,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignInitialEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignInitialEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ @@ -232,7 +232,7 @@ BI.SignInitialEditor = BI.inherit(BI.Widget, { return { value: this.editor.getValue(), text: this.options.text - } + }; }, getState: function () { diff --git a/src/case/editor/editor.sign.js b/src/case/editor/editor.sign.js index 094808c88..9c9585836 100644 --- a/src/case/editor/editor.sign.js +++ b/src/case/editor/editor.sign.js @@ -21,7 +21,7 @@ BI.SignEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { @@ -60,7 +60,7 @@ BI.SignEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ diff --git a/src/case/editor/editor.state.js b/src/case/editor/editor.state.js index ddd6e788a..c9aa8d289 100644 --- a/src/case/editor/editor.state.js +++ b/src/case/editor/editor.state.js @@ -21,7 +21,7 @@ BI.StateEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { diff --git a/src/case/editor/editor.state.simple.js b/src/case/editor/editor.state.simple.js index 792d04526..481b9e1b7 100644 --- a/src/case/editor/editor.state.simple.js +++ b/src/case/editor/editor.state.simple.js @@ -22,7 +22,7 @@ BI.SimpleStateEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { diff --git a/src/case/floatbox/floatboxsection.bar.js b/src/case/floatbox/floatboxsection.bar.js index e565b86c8..ea7a379c6 100644 --- a/src/case/floatbox/floatboxsection.bar.js +++ b/src/case/floatbox/floatboxsection.bar.js @@ -8,7 +8,7 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { _defaultConfig: function () { return BI.extend(BI.BarPopoverSection.superclass._defaultConfig.apply(this, arguments), { btns: [BI.i18nText(BI.i18nText("BI-Basic_Sure")), BI.i18nText(BI.i18nText("BI-Basic_Cancel"))] - }) + }); }, _init: function () { @@ -18,7 +18,7 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { rebuildSouth: function (south) { var self = this, o = this.options; this.sure = BI.createWidget({ - type: 'bi.button', + type: "bi.button", text: this.options.btns[0], warningTitle: o.warningTitle, height: 30, @@ -29,24 +29,24 @@ BI.BarPopoverSection = BI.inherit(BI.PopoverSection, { } }); this.cancel = BI.createWidget({ - type: 'bi.button', + type: "bi.button", text: this.options.btns[1], height: 30, value: 1, - level: 'ignore', + level: "ignore", handler: function (v) { self.close(v); } }); BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", element: south, lgap: 10, items: [this.cancel, this.sure] }); }, - setConfirmButtonEnable: function(v){ + setConfirmButtonEnable: function (v) { this.sure.setEnable(!!v); } }); \ No newline at end of file diff --git a/src/case/layer/layer.multipopup.js b/src/case/layer/layer.multipopup.js index 4f1ef1bf9..15834e60c 100644 --- a/src/case/layer/layer.multipopup.js +++ b/src/case/layer/layer.multipopup.js @@ -11,7 +11,7 @@ BI.MultiPopupView = BI.inherit(BI.PopupView, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-multi-list-view", buttons: [BI.i18nText("BI-Basic_Sure")] - }) + }); }, _init: function () { @@ -24,12 +24,12 @@ BI.MultiPopupView = BI.inherit(BI.PopupView, { return; } - var text = []; //构造[{text:content},……] + var text = []; // 构造[{text:content},……] BI.each(o.buttons, function (idx, item) { text.push({ text: item, value: idx - }) + }); }); this.buttongroup = BI.createWidget({ diff --git a/src/case/layer/layer.panel.js b/src/case/layer/layer.panel.js index bc7aa8357..878611741 100644 --- a/src/case/layer/layer.panel.js +++ b/src/case/layer/layer.panel.js @@ -11,7 +11,7 @@ BI.PopupPanel = BI.inherit(BI.MultiPopupView, { return BI.extend(conf, { baseCls: (conf.baseCls || "") + " bi-popup-panel", title: "" - }) + }); }, _init: function () { diff --git a/src/case/layer/pane.list.js b/src/case/layer/pane.list.js index 2e1782635..3988517b3 100644 --- a/src/case/layer/pane.list.js +++ b/src/case/layer/pane.list.js @@ -27,7 +27,7 @@ BI.ListPane = BI.inherit(BI.Pane, { el: { type: "bi.button_group" } - }) + }); }, _init: function () { BI.ListPane.superclass._init.apply(this, arguments); @@ -42,7 +42,7 @@ BI.ListPane = BI.inherit(BI.Pane, { if (op.times === 1) { self.empty(); BI.nextTick(function () { - self.loading() + self.loading(); }); } o.itemsCreator(op, function () { @@ -110,7 +110,7 @@ BI.ListPane = BI.inherit(BI.Pane, { populate: function (items) { var self = this, o = this.options; - if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {//接管loader的populate方法 + if (arguments.length === 0 && (BI.isFunction(this.button_group.attr("itemsCreator")))) {// 接管loader的populate方法 this.button_group.attr("itemsCreator").apply(this, [{times: 1}, function () { if (arguments.length === 0) { throw new Error("参数不能为空"); diff --git a/src/case/layer/panel.js b/src/case/layer/panel.js index 5e0f75190..885fec0ff 100644 --- a/src/case/layer/panel.js +++ b/src/case/layer/panel.js @@ -3,32 +3,32 @@ * @class BI.Panel * @extends BI.Widget */ -BI.Panel = BI.inherit(BI.Widget,{ - _defaultConfig : function(){ - return BI.extend(BI.Panel.superclass._defaultConfig.apply(this,arguments),{ +BI.Panel = BI.inherit(BI.Widget, { + _defaultConfig: function () { + return BI.extend(BI.Panel.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-panel bi-border", - title:"", - titleButtons:[], - el:{}, - logic:{ + title: "", + titleButtons: [], + el: {}, + logic: { dynamic: false } }); }, - _init:function(){ - BI.Panel.superclass._init.apply(this,arguments); + _init: function () { + BI.Panel.superclass._init.apply(this, arguments); var o = this.options; BI.createWidget(BI.extend({ element: this }, BI.LogicFactory.createLogic("vertical", BI.extend(o.logic, { items: BI.LogicFactory.createLogicItemsByDirection("top", this._createTitle() - ,this.options.el) + , this.options.el) })))); }, - _createTitle:function(){ + _createTitle: function () { var self = this, o = this.options; this.text = BI.createWidget({ type: "bi.label", @@ -38,19 +38,19 @@ BI.Panel = BI.inherit(BI.Widget,{ }); this.button_group = BI.createWidget({ - type:"bi.button_group", + type: "bi.button_group", items: o.titleButtons, layouts: [{ type: "bi.center_adapt", - lgap:10 + lgap: 10 }] }); - this.button_group.on(BI.Controller.EVENT_CHANGE, function(){ + this.button_group.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); - this.button_group.on(BI.ButtonGroup.EVENT_CHANGE, function(value, obj){ + this.button_group.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { self.fireEvent(BI.Panel.EVENT_CHANGE, value, obj); }); @@ -70,10 +70,10 @@ BI.Panel = BI.inherit(BI.Widget,{ }; }, - setTitle: function(title){ + setTitle: function (title) { this.text.setValue(title); } }); BI.Panel.EVENT_CHANGE = "Panel.EVENT_CHANGE"; -BI.shortcut("bi.panel",BI.Panel); \ No newline at end of file +BI.shortcut("bi.panel", BI.Panel); \ No newline at end of file diff --git a/src/case/list/list.select.js b/src/case/list/list.select.js index 6a44b884e..617f07c63 100644 --- a/src/case/list/list.select.js +++ b/src/case/list/list.select.js @@ -10,7 +10,7 @@ BI.SelectList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SelectList.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-select-list", - direction: BI.Direction.Top,//toolbar的位置 + direction: BI.Direction.Top, // toolbar的位置 logic: { dynamic: true }, @@ -24,13 +24,13 @@ BI.SelectList = BI.inherit(BI.Widget, { el: { type: "bi.list_pane" } - }) + }); }, _init: function () { BI.SelectList.superclass._init.apply(this, arguments); var self = this, o = this.options; - //全选 + // 全选 this.toolbar = BI.createWidget(o.toolbar); this.allSelected = false; this.toolbar.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { @@ -141,13 +141,13 @@ BI.SelectList = BI.inherit(BI.Widget, { value: this.list.getValue(), assist: this.list.getNotSelectedValue() }; - } else { - return { - type: BI.ButtonGroup.CHOOSE_TYPE_ALL, - value: this.list.getNotSelectedValue(), - assist: this.list.getValue() - }; } + return { + type: BI.ButtonGroup.CHOOSE_TYPE_ALL, + value: this.list.getNotSelectedValue(), + assist: this.list.getValue() + }; + }, empty: function () { @@ -169,7 +169,7 @@ BI.SelectList = BI.inherit(BI.Widget, { resetHeight: function (h) { var toolHeight = ( this.toolbar.element.outerHeight() || 25) * ( this.toolbar.isVisible() ? 1 : 0); this.list.resetHeight ? this.list.resetHeight(h - toolHeight) : - this.list.element.css({"max-height": h - toolHeight + "px"}) + this.list.element.css({"max-height": h - toolHeight + "px"}); }, setNotSelectedValue: function () { diff --git a/src/case/loader/loader.lazy.js b/src/case/loader/loader.lazy.js index 2f3d6859c..b1522d528 100644 --- a/src/case/loader/loader.lazy.js +++ b/src/case/loader/loader.lazy.js @@ -9,7 +9,7 @@ BI.LazyLoader = BI.inherit(BI.Widget, { return BI.extend(BI.LazyLoader.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-lazy-loader", el: {} - }) + }); }, _init: function () { @@ -19,7 +19,7 @@ BI.LazyLoader = BI.inherit(BI.Widget, { this.loader = BI.createWidget({ type: "bi.loader", element: this, - //下面是button_group的属性 + // 下面是button_group的属性 el: o.el, itemsCreator: function (options, populate) { @@ -31,8 +31,8 @@ BI.LazyLoader = BI.inherit(BI.Widget, { }); this.loader.on(BI.Loader.EVENT_CHANGE, function (obj) { - self.fireEvent(BI.LazyLoader.EVENT_CHANGE, obj) - }) + self.fireEvent(BI.LazyLoader.EVENT_CHANGE, obj); + }); }, _getNextItems: function (options) { var self = this, o = this.options; diff --git a/src/case/loader/loader.list.js b/src/case/loader/loader.list.js index b855c34a2..04c7292a9 100644 --- a/src/case/loader/loader.list.js +++ b/src/case/loader/loader.list.js @@ -10,9 +10,9 @@ BI.ListLoader = BI.inherit(BI.Widget, { return BI.extend(BI.ListLoader.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-list-loader", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -21,11 +21,11 @@ BI.ListLoader = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, next: {}, hasNext: BI.emptyFn - }) + }); }, _nextLoad: function () { @@ -69,7 +69,7 @@ BI.ListLoader = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self._nextLoad(); } - }) + }); } BI.createWidget({ @@ -94,7 +94,7 @@ BI.ListLoader = BI.inherit(BI.Widget, { return !!o.hasNext.apply(this, [{ times: this.times, count: this.count - }]) + }]); }, addItems: function (items) { diff --git a/src/case/loader/sort.list.js b/src/case/loader/sort.list.js index 05732f826..cc28610db 100644 --- a/src/case/loader/sort.list.js +++ b/src/case/loader/sort.list.js @@ -9,9 +9,9 @@ BI.SortList = BI.inherit(BI.Widget, { return BI.extend(BI.SortList.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-sort-list", - isDefaultInit: true,//是否默认初始化数据 + isDefaultInit: true, // 是否默认初始化数据 - //下面是button_group的属性 + // 下面是button_group的属性 el: { type: "bi.button_group" }, @@ -20,14 +20,14 @@ BI.SortList = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, onLoaded: BI.emptyFn, - //下面是分页信息 + // 下面是分页信息 count: false, next: {}, hasNext: BI.emptyFn - //containment: this.element, - //connectWith: ".bi-sort-list", - }) + // containment: this.element, + // connectWith: ".bi-sort-list", + }); }, _init: function () { @@ -74,7 +74,7 @@ BI.SortList = BI.inherit(BI.Widget, { "margin-right": $currentItem.css("margin-right"), "margin-top": $currentItem.css("margin-top"), "margin-bottom": $currentItem.css("margin-bottom"), - "margin": $currentItem.css("margin") + margin: $currentItem.css("margin") }); return holder.element; }, diff --git a/src/case/pager/pager.all.count.js b/src/case/pager/pager.all.count.js index 3edf00dfb..31e9063fe 100644 --- a/src/case/pager/pager.all.count.js +++ b/src/case/pager/pager.all.count.js @@ -8,10 +8,10 @@ BI.AllCountPager = BI.inherit(BI.Widget, { return BI.extend(BI.AllCountPager.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-all-count-pager", height: 30, - pages: 1, //必选项 - curr: 1, //初始化当前页, pages为数字时可用, - count: 1 //总行数 - }) + pages: 1, // 必选项 + curr: 1, // 初始化当前页, pages为数字时可用, + count: 1 // 总行数 + }); }, _init: function () { BI.AllCountPager.superclass._init.apply(this, arguments); @@ -117,7 +117,7 @@ BI.AllCountPager = BI.inherit(BI.Widget, { element: this, columnSize: ["", 35, 40, 36], items: [count, this.editor, this.allPages, this.pager] - }) + }); }, alwaysShowPager: true, diff --git a/src/case/pager/pager.direction.js b/src/case/pager/pager.direction.js index e9fad56b9..6dd6359b3 100644 --- a/src/case/pager/pager.direction.js +++ b/src/case/pager/pager.direction.js @@ -12,8 +12,8 @@ BI.DirectionPager = BI.inherit(BI.Widget, { baseCls: "bi-direction-pager", height: 30, horizontal: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -21,15 +21,15 @@ BI.DirectionPager = BI.inherit(BI.Widget, { lastPage: BI.emptyFn }, vertical: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, firstPage: 1, lastPage: BI.emptyFn } - }) + }); }, _init: function () { BI.DirectionPager.superclass._init.apply(this, arguments); diff --git a/src/case/pager/pager.js b/src/case/pager/pager.js index 15f460bf2..ed9b8dec7 100644 --- a/src/case/pager/pager.js +++ b/src/case/pager/pager.js @@ -16,35 +16,35 @@ BI.DetailPager = BI.inherit(BI.Widget, { vgap: 0 }], - dynamicShow: true, //是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 - //dynamicShow为false时以下两个有用 - dynamicShowFirstLast: false,//是否动态显示首页、尾页 - dynamicShowPrevNext: false,//是否动态显示上一页、下一页 - pages: false, //总页数 + dynamicShow: true, // 是否动态显示上一页、下一页、首页、尾页, 若为false,则指对其设置使能状态 + // dynamicShow为false时以下两个有用 + dynamicShowFirstLast: false, // 是否动态显示首页、尾页 + dynamicShowPrevNext: false, // 是否动态显示上一页、下一页 + pages: false, // 总页数 curr: function () { return 1; - }, //初始化当前页 - groups: 0, //连续显示分页数 - jump: BI.emptyFn, //分页的回调函数 + }, // 初始化当前页 + groups: 0, // 连续显示分页数 + jump: BI.emptyFn, // 分页的回调函数 - first: false, //是否显示首页 - last: false, //是否显示尾页 + first: false, // 是否显示首页 + last: false, // 是否显示尾页 prev: "上一页", next: "下一页", firstPage: 1, - lastPage: function () { //在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 + lastPage: function () { // 在万不得已时才会调用这个函数获取最后一页的页码, 主要作用于setValue方法 return 1; }, - hasPrev: BI.emptyFn, //pages不可用时有效 - hasNext: BI.emptyFn //pages不可用时有效 - }) + hasPrev: BI.emptyFn, // pages不可用时有效 + hasNext: BI.emptyFn // pages不可用时有效 + }); }, _init: function () { BI.DetailPager.superclass._init.apply(this, arguments); var self = this; this.currPage = BI.result(this.options, "curr"); - //翻页太灵敏 + // 翻页太灵敏 this._lock = false; this._debouce = BI.debounce(function () { self._lock = false; @@ -71,17 +71,17 @@ BI.DetailPager = BI.inherit(BI.Widget, { groups > pages && (groups = pages); } - //计算当前组 + // 计算当前组 dict.index = Math.ceil((curr + ((groups > 1 && groups !== pages) ? 1 : 0)) / (groups === 0 ? 1 : groups)); - //当前页非首页,则输出上一页 + // 当前页非首页,则输出上一页 if (((!o.dynamicShow && !o.dynamicShowPrevNext) || curr > 1) && prev !== false) { if (BI.isKey(prev)) { view.push({ text: prev, value: "prev", disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) - }) + }); } else { view.push(BI.extend({ disabled: pages === false ? o.hasPrev(curr) === false : !(curr > 1 && prev !== false) @@ -89,7 +89,7 @@ BI.DetailPager = BI.inherit(BI.Widget, { } } - //当前组非首组,则输出首页 + // 当前组非首组,则输出首页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (dict.index > 1 && groups !== 0)) && first) { view.push({ text: first, @@ -105,14 +105,14 @@ BI.DetailPager = BI.inherit(BI.Widget, { } } - //输出当前页组 + // 输出当前页组 dict.poor = Math.floor((groups - 1) / 2); dict.start = dict.index > 1 ? curr - dict.poor : 1; dict.end = dict.index > 1 ? (function () { var max = curr + (groups - dict.poor - 1); return max > pages ? pages : max; }()) : groups; - if (dict.end - dict.start < groups - 1) { //最后一组状态 + if (dict.end - dict.start < groups - 1) { // 最后一组状态 dict.start = dict.end - groups + 1; } var s = dict.start, e = dict.end; @@ -126,16 +126,16 @@ BI.DetailPager = BI.inherit(BI.Widget, { text: s, value: s, selected: true - }) + }); } else { view.push({ text: s, value: s - }) + }); } } - //总页数大于连续分页数,且当前组最大页小于总页,输出尾页 + // 总页数大于连续分页数,且当前组最大页小于总页,输出尾页 if (((!o.dynamicShow && !o.dynamicShowFirstLast) || (pages > groups && dict.end < pages && groups !== 0)) && last) { if (pages > groups && dict.end < pages && groups !== 0) { view.push({ @@ -148,27 +148,27 @@ BI.DetailPager = BI.inherit(BI.Widget, { text: last, value: "last", disabled: !(pages > groups && dict.end < pages && groups !== 0) - }) + }); } - //当前页不为尾页时,输出下一页 + // 当前页不为尾页时,输出下一页 dict.flow = !prev && groups === 0; if (((!o.dynamicShow && !o.dynamicShowPrevNext) && next) || (curr !== pages && next || dict.flow)) { view.push((function () { if (BI.isKey(next)) { if (pages === false) { - return {text: next, value: "next", disabled: o.hasNext(curr) === false} + return {text: next, value: "next", disabled: o.hasNext(curr) === false}; } return (dict.flow && curr === pages) ? - {text: next, value: "next", disabled: true} + {text: next, value: "next", disabled: true} : - {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; - } else { - return BI.extend({ - disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) - }, next); + {text: next, value: "next", disabled: !(curr !== pages && next || dict.flow)}; } + return BI.extend({ + disabled: pages === false ? o.hasNext(curr) === false : !(curr !== pages && next || dict.flow) + }, next); + }())); } diff --git a/src/case/richeditor/bar/action.richeditor.param.js b/src/case/richeditor/bar/action.richeditor.param.js index 4da1c1b0e..8fdd445c8 100644 --- a/src/case/richeditor/bar/action.richeditor.param.js +++ b/src/case/richeditor/bar/action.richeditor.param.js @@ -75,7 +75,7 @@ BI.RichEditorParamAction = BI.inherit(BI.RichEditorAction, { keydown: function (e) { var o = this.options; var sel = this._get$Sel(); - if (e.keyCode === 229) {//中文输入法 + if (e.keyCode === 229) {// 中文输入法 if (this._isParam(sel)) { this._addBlank(sel); e.stopEvent(); diff --git a/src/case/richeditor/niceditor/niceditor.js b/src/case/richeditor/niceditor/niceditor.js index 5d70636c3..1e93f1f8f 100644 --- a/src/case/richeditor/niceditor/niceditor.js +++ b/src/case/richeditor/niceditor/niceditor.js @@ -23,7 +23,7 @@ type: "bi.layout", height: 1 }, this.instance = this.addInstance()] - }) + }); }, addInstance: function () { @@ -56,7 +56,7 @@ // return false; } } while (t = t.parentNode); - this.fireEvent('blur', t); + this.fireEvent("blur", t); this.lastSelectedInstance = this.selectedInstance; this.selectedInstance = null; // return false; @@ -77,7 +77,7 @@ BI.NicEditor.EVENT_SELECTED = "selected"; BI.NicEditor.EVENT_BLUR = "blur"; BI.NicEditor.EVENT_KEYDOWN = "keydown"; - BI.shortcut('bi.nic_editor', BI.NicEditor); + BI.shortcut("bi.nic_editor", BI.NicEditor); var prefix = "niceditor-"; @@ -98,7 +98,7 @@ outline: "none" }).html(o.value); - this.element.css("maxHeight", (o.maxHeight) ? o.maxHeight + 'px' : null); + this.element.css("maxHeight", (o.maxHeight) ? o.maxHeight + "px" : null); this.e = BI.createWidget({ type: "bi.layout", @@ -124,12 +124,12 @@ // this.setContent("
    "); } this.instanceDoc = document.defaultView; - this.elm.element.on('mousedown', BI.bind(this.selected, this)); - this.elm.element.on('keydown', BI.bind(this.keyDown, this)); - this.elm.element.on('focus', BI.bind(this.selected, this)); - this.elm.element.on('blur', BI.bind(this.blur, this)); - this.elm.element.on('keyup', BI.bind(this.selected, this)); - this.ne.fireEvent('add'); + this.elm.element.on("mousedown", BI.bind(this.selected, this)); + this.elm.element.on("keydown", BI.bind(this.keyDown, this)); + this.elm.element.on("focus", BI.bind(this.selected, this)); + this.elm.element.on("blur", BI.bind(this.blur, this)); + this.elm.element.on("keyup", BI.bind(this.selected, this)); + this.ne.fireEvent("add"); }, disable: function () { @@ -175,9 +175,9 @@ } } return contain; - } else { - return (this.getSel().type == "Control") ? r.item(0) : r.parentElement(); } + return (this.getSel().type == "Control") ? r.item(0) : r.parentElement(); + }, saveRng: function () { @@ -199,7 +199,7 @@ } rng = document.selection.createRange(); - rng.moveStart('character', -el.innerText.length); + rng.moveStart("character", -el.innerText.length); var text = rng.text; for (var i = 0; i < el.innerText.length; i++) { if (el.innerText.substring(0, i + 1) == text.substring(text.length - i - 1, text.length)) { @@ -223,7 +223,7 @@ }, keyDown: function (e, t) { - this.ne.fireEvent('keydown', e); + this.ne.fireEvent("keydown", e); }, selected: function (e) { @@ -235,25 +235,25 @@ var selInstance = this.ne.selectedInstance; if (selInstance != this) { if (selInstance) { - this.ne.fireEvent('blur', e); + this.ne.fireEvent("blur", e); } this.ne.selectedInstance = this; - this.ne.fireEvent('focus', e); + this.ne.fireEvent("focus", e); } - this.ne.fireEvent('selected', e); + this.ne.fireEvent("selected", e); this.isFocused = true; - this.elm.element.addClass(prefix + 'selected'); + this.elm.element.addClass(prefix + "selected"); } // return false; }, blur: function () { this.isFocused = false; - this.elm.element.removeClass(prefix + 'selected'); + this.elm.element.removeClass(prefix + "selected"); }, saveContent: function () { - this.ne.fireEvent('save'); + this.ne.fireEvent("save"); this.e.element.value(this.getContent()); }, @@ -263,13 +263,13 @@ getContent: function () { this.content = this.getElm().element.html(); - this.ne.fireEvent('get'); + this.ne.fireEvent("get"); return this.content; }, setContent: function (e) { this.content = e; - this.ne.fireEvent('set'); + this.ne.fireEvent("set"); this.elm.element.html(this.content); }, diff --git a/src/case/richeditor/plugins/backgroundchooser/trigger.backgroundchooser.js b/src/case/richeditor/plugins/backgroundchooser/trigger.backgroundchooser.js index b997068ef..7b45df461 100644 --- a/src/case/richeditor/plugins/backgroundchooser/trigger.backgroundchooser.js +++ b/src/case/richeditor/plugins/backgroundchooser/trigger.backgroundchooser.js @@ -38,7 +38,7 @@ BI.RichEditorBackgroundChooserTrigger = BI.inherit(BI.Widget, { top: 7, left: 2 }] - }) + }); }, setValue: function (color) { @@ -49,4 +49,4 @@ BI.RichEditorBackgroundChooserTrigger = BI.inherit(BI.Widget, { return this.font.element.css("color"); } }); -BI.shortcut('bi.rich_editor_background_color_chooser_trigger', BI.RichEditorBackgroundChooserTrigger); \ No newline at end of file +BI.shortcut("bi.rich_editor_background_color_chooser_trigger", BI.RichEditorBackgroundChooserTrigger); \ No newline at end of file diff --git a/src/case/richeditor/plugins/button.align.center.js b/src/case/richeditor/plugins/button.align.center.js index 1cf3f1ad6..38ffc803f 100644 --- a/src/case/richeditor/plugins/button.align.center.js +++ b/src/case/richeditor/plugins/button.align.center.js @@ -35,4 +35,4 @@ BI.RichEditorAlignCenterButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_center_button", BI.RichEditorAlignCenterButton) \ No newline at end of file +BI.shortcut("bi.rich_editor_align_center_button", BI.RichEditorAlignCenterButton); \ No newline at end of file diff --git a/src/case/richeditor/plugins/button.align.left.js b/src/case/richeditor/plugins/button.align.left.js index 3d9fe660d..29c35845d 100644 --- a/src/case/richeditor/plugins/button.align.left.js +++ b/src/case/richeditor/plugins/button.align.left.js @@ -35,4 +35,4 @@ BI.RichEditorAlignLeftButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_left_button", BI.RichEditorAlignLeftButton) \ No newline at end of file +BI.shortcut("bi.rich_editor_align_left_button", BI.RichEditorAlignLeftButton); \ No newline at end of file diff --git a/src/case/richeditor/plugins/button.align.right.js b/src/case/richeditor/plugins/button.align.right.js index 2206db514..31f4f202b 100644 --- a/src/case/richeditor/plugins/button.align.right.js +++ b/src/case/richeditor/plugins/button.align.right.js @@ -35,4 +35,4 @@ BI.RichEditorAlignRightButton = BI.inherit(BI.RichEditorAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_align_right_button", BI.RichEditorAlignRightButton) \ No newline at end of file +BI.shortcut("bi.rich_editor_align_right_button", BI.RichEditorAlignRightButton); \ No newline at end of file diff --git a/src/case/richeditor/plugins/button.bold.js b/src/case/richeditor/plugins/button.bold.js index a6d931959..ac788559b 100644 --- a/src/case/richeditor/plugins/button.bold.js +++ b/src/case/richeditor/plugins/button.bold.js @@ -38,4 +38,4 @@ BI.RichEditorBoldButton = BI.inherit(BI.RichEditorAction, { this.bold.setSelected(false); } }); -BI.shortcut("bi.rich_editor_bold_button", BI.RichEditorBoldButton) \ No newline at end of file +BI.shortcut("bi.rich_editor_bold_button", BI.RichEditorBoldButton); \ No newline at end of file diff --git a/src/case/richeditor/plugins/button.italic.js b/src/case/richeditor/plugins/button.italic.js index a9a5f2ed1..a006dfa68 100644 --- a/src/case/richeditor/plugins/button.italic.js +++ b/src/case/richeditor/plugins/button.italic.js @@ -38,4 +38,4 @@ BI.RichEditorItalicButton = BI.inherit(BI.RichEditorAction, { this.italic.setSelected(false); } }); -BI.shortcut("bi.rich_editor_italic_button", BI.RichEditorItalicButton) \ No newline at end of file +BI.shortcut("bi.rich_editor_italic_button", BI.RichEditorItalicButton); \ No newline at end of file diff --git a/src/case/richeditor/plugins/button.param.js b/src/case/richeditor/plugins/button.param.js index 9b90ab2f7..875bf499f 100644 --- a/src/case/richeditor/plugins/button.param.js +++ b/src/case/richeditor/plugins/button.param.js @@ -25,7 +25,7 @@ BI.RichEditorParamButton = BI.inherit(BI.RichEditorParamAction, { width: 30 }); this.param.on(BI.Button.EVENT_CHANGE, function () { - self.addParam("参数") + self.addParam("参数"); }); }, activate: function () { @@ -34,4 +34,4 @@ BI.RichEditorParamButton = BI.inherit(BI.RichEditorParamAction, { deactivate: function () { } }); -BI.shortcut("bi.rich_editor_param_button", BI.RichEditorParamButton) \ No newline at end of file +BI.shortcut("bi.rich_editor_param_button", BI.RichEditorParamButton); \ No newline at end of file diff --git a/src/case/richeditor/plugins/button.underline.js b/src/case/richeditor/plugins/button.underline.js index d6fc0d5bb..21e60c5a8 100644 --- a/src/case/richeditor/plugins/button.underline.js +++ b/src/case/richeditor/plugins/button.underline.js @@ -38,4 +38,4 @@ BI.RichEditorUnderlineButton = BI.inherit(BI.RichEditorAction, { this.underline.setSelected(false); } }); -BI.shortcut("bi.rich_editor_underline_button", BI.RichEditorUnderlineButton) \ No newline at end of file +BI.shortcut("bi.rich_editor_underline_button", BI.RichEditorUnderlineButton); \ No newline at end of file diff --git a/src/case/richeditor/plugins/colorchooser/trigger.colorchooser.js b/src/case/richeditor/plugins/colorchooser/trigger.colorchooser.js index 298b9d852..1753c6391 100644 --- a/src/case/richeditor/plugins/colorchooser/trigger.colorchooser.js +++ b/src/case/richeditor/plugins/colorchooser/trigger.colorchooser.js @@ -38,7 +38,7 @@ BI.RichEditorColorChooserTrigger = BI.inherit(BI.Widget, { top: 7, left: 2 }] - }) + }); }, setValue: function (color) { @@ -49,4 +49,4 @@ BI.RichEditorColorChooserTrigger = BI.inherit(BI.Widget, { return this.font.element.css("color"); } }); -BI.shortcut('bi.rich_editor_color_chooser_trigger', BI.RichEditorColorChooserTrigger); \ No newline at end of file +BI.shortcut("bi.rich_editor_color_chooser_trigger", BI.RichEditorColorChooserTrigger); \ No newline at end of file diff --git a/src/case/richeditor/plugins/combo.colorchooser.js b/src/case/richeditor/plugins/combo.colorchooser.js index 773f32fea..cbee2f49c 100644 --- a/src/case/richeditor/plugins/combo.colorchooser.js +++ b/src/case/richeditor/plugins/combo.colorchooser.js @@ -44,4 +44,4 @@ BI.RichEditorColorChooser = BI.inherit(BI.RichEditorAction, { this.colorchooser.setValue(""); } }); -BI.shortcut('bi.rich_editor_color_chooser', BI.RichEditorColorChooser); \ No newline at end of file +BI.shortcut("bi.rich_editor_color_chooser", BI.RichEditorColorChooser); \ No newline at end of file diff --git a/src/case/richeditor/richeditor.js b/src/case/richeditor/richeditor.js index 1c495a8f4..d8a19f3de 100644 --- a/src/case/richeditor/richeditor.js +++ b/src/case/richeditor/richeditor.js @@ -58,4 +58,4 @@ BI.RichEditor = BI.inherit(BI.Widget, { } }); BI.RichEditor.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.rich_editor', BI.RichEditor); \ No newline at end of file +BI.shortcut("bi.rich_editor", BI.RichEditor); \ No newline at end of file diff --git a/src/case/segment/button.segment.js b/src/case/segment/button.segment.js index a90cef7c7..bd024ed07 100644 --- a/src/case/segment/button.segment.js +++ b/src/case/segment/button.segment.js @@ -10,19 +10,19 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { _defaultConfig: function () { var conf = BI.SegmentButton.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { - baseCls: (conf.baseCls || "") + ' bi-segment-button bi-list-item-active', + baseCls: (conf.baseCls || "") + " bi-segment-button bi-list-item-active", shadow: true, readonly: true, hgap: 5 - }) + }); }, _init: function () { BI.SegmentButton.superclass._init.apply(this, arguments); var opts = this.options, self = this; - //if (BI.isNumber(opts.height) && BI.isNull(opts.lineHeight)) { + // if (BI.isNumber(opts.height) && BI.isNull(opts.lineHeight)) { // this.element.css({lineHeight : (opts.height - 2) + 'px'}); - //} + // } this.text = BI.createWidget({ type: "bi.label", element: this, @@ -31,7 +31,7 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { text: opts.text, value: opts.value, hgap: opts.hgap - }) + }); }, setSelected: function () { @@ -47,4 +47,4 @@ BI.SegmentButton = BI.inherit(BI.BasicButton, { BI.SegmentButton.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.segment_button', BI.SegmentButton); \ No newline at end of file +BI.shortcut("bi.segment_button", BI.SegmentButton); \ No newline at end of file diff --git a/src/case/segment/segment.js b/src/case/segment/segment.js index 027de361f..74bf1d9ee 100644 --- a/src/case/segment/segment.js +++ b/src/case/segment/segment.js @@ -29,13 +29,13 @@ BI.Segment = BI.inherit(BI.Widget, { type: "bi.center" } ] - }) + }); this.buttonGroup.on(BI.Controller.EVENT_CHANGE, function () { - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments) + self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); this.buttonGroup.on(BI.ButtonGroup.EVENT_CHANGE, function (value, obj) { - self.fireEvent(BI.Segment.EVENT_CHANGE, value, obj) - }) + self.fireEvent(BI.Segment.EVENT_CHANGE, value, obj); + }); }, setValue: function (v) { @@ -51,4 +51,4 @@ BI.Segment = BI.inherit(BI.Widget, { } }); BI.Segment.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.segment', BI.Segment); \ No newline at end of file +BI.shortcut("bi.segment", BI.Segment); \ No newline at end of file diff --git a/src/case/table/table.adaptive.js b/src/case/table/table.adaptive.js index 447a9425f..1965e04c8 100644 --- a/src/case/table/table.adaptive.js +++ b/src/case/table/table.adaptive.js @@ -18,11 +18,11 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, isNeedResize: true, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -35,9 +35,9 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { regionColumnSize: [], header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -72,7 +72,7 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -139,7 +139,7 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { freezeCols: freezeCols, columnSize: columnSize, regionColumnSize: regionColumnSize - } + }; }, _populate: function () { @@ -225,4 +225,4 @@ BI.AdaptiveTable = BI.inherit(BI.Widget, { BI.AdaptiveTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.adaptive_table', BI.AdaptiveTable); \ No newline at end of file +BI.shortcut("bi.adaptive_table", BI.AdaptiveTable); \ No newline at end of file diff --git a/src/case/table/table.dynamicsummarylayertree.js b/src/case/table/table.dynamicsummarylayertree.js index 7377c8956..619026798 100644 --- a/src/case/table/table.dynamicsummarylayertree.js +++ b/src/case/table/table.dynamicsummarylayertree.js @@ -14,13 +14,13 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { el: { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -33,7 +33,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { regionColumnSize: [], - //行表头 + // 行表头 rowHeaderCreator: null, headerCellStyleGetter: BI.emptyFn, @@ -44,14 +44,14 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { footer: false, items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -73,16 +73,16 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { var deep = this._getHDeep(); if (deep <= 0) { newHeader.unshift(o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }); + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }); } else { newHeader[0] = o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }; + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }; } result.push(newHeader); } @@ -93,7 +93,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { var self = this, o = this.options; var result = []; - function track(node, layer) { + function track (node, layer) { node.type || (node.type = "bi.layer_tree_table_cell"); node.layer = layer; var next = [node]; @@ -120,7 +120,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { return o.summaryCellStyleGetter(true); } }].concat(node.values); - result.push(next) + result.push(next); } }); return BI.DynamicSummaryTreeTable.formatSummaryItems(result, header, o.crossItems, 1); @@ -188,7 +188,7 @@ BI.DynamicSummaryLayerTreeTable = BI.inherit(BI.Widget, { minColumnSize: this._formatColumns(minColumnSize, deep), maxColumnSize: this._formatColumns(maxColumnSize, deep), freezeCols: this._formatFreezeCols() - } + }; }, _init: function () { diff --git a/src/case/table/table.dynamicsummarytree.js b/src/case/table/table.dynamicsummarytree.js index a621fc098..a8933f2c1 100644 --- a/src/case/table/table.dynamicsummarytree.js +++ b/src/case/table/table.dynamicsummarytree.js @@ -14,13 +14,13 @@ BI.DynamicSummaryTreeTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -41,14 +41,14 @@ BI.DynamicSummaryTreeTable = BI.inherit(BI.Widget, { footer: false, items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -226,7 +226,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { formatHorizontalItems: function (nodes, deep, isCross, styleGetter) { var result = []; - function track(store, node) { + function track (store, node) { var next; if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { @@ -250,7 +250,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { text: BI.i18nText("BI-Summary_Values"), type: "bi.table_style_cell", styleGetter: function () { - return styleGetter(store === -1) + return styleGetter(store === -1); } }; for (var i = next.length; i < deep; i++) { @@ -297,7 +297,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { BI.each(nodes, function (i, node) { track(-1, node); }); - //填充空位 + // 填充空位 BI.each(result, function (i, line) { var last = BI.last(line); for (var j = line.length; j < deep; j++) { @@ -308,11 +308,11 @@ BI.extend(BI.DynamicSummaryTreeTable, { }, formatSummaryItems: function (items, header, crossItems, deep) { - //求纵向需要去除的列 + // 求纵向需要去除的列 var cols = []; var leaf = 0; - function track(node) { + function track (node) { if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { track(child); @@ -348,7 +348,7 @@ BI.extend(BI.DynamicSummaryTreeTable, { BI.each(items, function (i, node) { var nNode = node.slice(); BI.removeAt(nNode, cols); - nItems.push(nNode);; + nItems.push(nNode); }); header = nHeader; items = nItems; diff --git a/src/case/table/table.layertree.cell.js b/src/case/table/table.layertree.cell.js index 547660cb3..ce821b64e 100644 --- a/src/case/table/table.layertree.cell.js +++ b/src/case/table/table.layertree.cell.js @@ -9,7 +9,7 @@ BI.LayerTreeTableCell = BI.inherit(BI.Widget, { baseCls: "bi-layer-tree-table-cell", layer: 0, text: "" - }) + }); }, _init: function () { @@ -25,7 +25,7 @@ BI.LayerTreeTableCell = BI.inherit(BI.Widget, { value: o.value, lgap: 5 + 30 * o.layer, rgap: 5 - }) + }); } }); diff --git a/src/case/table/table.layertree.js b/src/case/table/table.layertree.js index 568f83240..9f8f2e4de 100644 --- a/src/case/table/table.layertree.js +++ b/src/case/table/table.layertree.js @@ -14,13 +14,13 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { type: "bi.resizable_table" }, - isNeedResize: false,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: false, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -42,14 +42,14 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { header: [], items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -71,16 +71,16 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { var deep = this._getHDeep(); if (deep <= 0) { newHeader.unshift(o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }); + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }); } else { newHeader[0] = o.rowHeaderCreator || { - type: "bi.table_style_cell", - text: BI.i18nText("BI-Row_Header"), - styleGetter: o.headerCellStyleGetter - }; + type: "bi.table_style_cell", + text: BI.i18nText("BI-Row_Header"), + styleGetter: o.headerCellStyleGetter + }; } result.push(newHeader); } @@ -91,7 +91,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { var self = this, o = this.options; var result = []; - function track(node, layer) { + function track (node, layer) { node.type || (node.type = "bi.layer_tree_table_cell"); node.layer = layer; var next = [node]; @@ -116,7 +116,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { return o.summaryCellStyleGetter(true); } }].concat(node.values); - result.push(next) + result.push(next); } }); return result; @@ -164,7 +164,7 @@ BI.LayerTreeTable = BI.inherit(BI.Widget, { minColumnSize: this._formatColumns(o.minColumnSize, deep), maxColumnSize: this._formatColumns(o.maxColumnSize, deep), freezeCols: this._formatFreezeCols() - } + }; }, _init: function () { diff --git a/src/case/table/table.style.cell.js b/src/case/table/table.style.cell.js index 25911fc26..37fcf0b68 100644 --- a/src/case/table/table.style.cell.js +++ b/src/case/table/table.style.cell.js @@ -43,4 +43,4 @@ BI.TableStyleCell = BI.inherit(BI.Single, { this._digestStyle(); } }); -BI.shortcut('bi.table_style_cell', BI.TableStyleCell); \ No newline at end of file +BI.shortcut("bi.table_style_cell", BI.TableStyleCell); \ No newline at end of file diff --git a/src/case/table/table.tree.js b/src/case/table/table.tree.js index 99e92b7c0..36fb4df75 100644 --- a/src/case/table/table.tree.js +++ b/src/case/table/table.tree.js @@ -13,12 +13,12 @@ BI.TableTree = BI.inherit(BI.Widget, { el: { type: "bi.resizable_table" }, - isNeedResize: true,//是否需要调整列宽 - isResizeAdapt: true,//是否需要在调整列宽或区域宽度的时候它们自适应变化 + isNeedResize: true, // 是否需要调整列宽 + isResizeAdapt: true, // 是否需要在调整列宽或区域宽度的时候它们自适应变化 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为tree时生效 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为tree时生效 - isNeedMerge: true,//是否需要合并单元格 + isNeedMerge: true, // 是否需要合并单元格 mergeCols: [], mergeRule: BI.emptyFn, @@ -37,14 +37,14 @@ BI.TableTree = BI.inherit(BI.Widget, { header: [], items: [], - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] - }) + }); }, _getVDeep: function () { - return this.options.crossHeader.length;//纵向深度 + return this.options.crossHeader.length;// 纵向深度 }, _getHDeep: function () { @@ -106,7 +106,7 @@ BI.TableTree = BI.inherit(BI.Widget, { return { header: header, items: items - } + }; }, setWidth: function (width) { @@ -215,7 +215,7 @@ BI.extend(BI.TableTree, { var self = this; var result = []; - function track(store, node) { + function track (store, node) { var next; if (BI.isArray(node.children)) { BI.each(node.children, function (index, child) { @@ -234,12 +234,12 @@ BI.extend(BI.TableTree, { } else { next = []; } - if (/**(store == -1 || node.children.length > 1) &&**/ BI.isNotEmptyArray(node.values)) { + if (/** (store == -1 || node.children.length > 1) &&**/ BI.isNotEmptyArray(node.values)) { var summary = { text: BI.i18nText("BI-Summary_Values"), type: "bi.table_style_cell", styleGetter: function () { - return styleGetter(store === -1) + return styleGetter(store === -1); } }; for (var i = next.length; i < deep; i++) { @@ -287,7 +287,7 @@ BI.extend(BI.TableTree, { BI.each(nodes, function (i, node) { track(-1, node); }); - //填充空位 + // 填充空位 BI.each(result, function (i, line) { var last = BI.last(line); for (var j = line.length; j < deep; j++) { @@ -303,7 +303,7 @@ BI.extend(BI.TableTree, { }, maxDeep: function (nodes) { - function track(deep, node) { + function track (deep, node) { var d = deep; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { diff --git a/src/case/toolbar/toolbar.multiselect.js b/src/case/toolbar/toolbar.multiselect.js index 156398c47..0c536148f 100644 --- a/src/case/toolbar/toolbar.multiselect.js +++ b/src/case/toolbar/toolbar.multiselect.js @@ -10,14 +10,14 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { return BI.extend(BI.MultiSelectBar.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-multi-select-bar", height: 25, - text: BI.i18nText('BI-Select_All'), + text: BI.i18nText("BI-Select_All"), isAllCheckedBySelectedValue: BI.emptyFn, - //手动控制选中 + // 手动控制选中 disableSelected: true, isHalfCheckedBySelectedValue: function (selectedValues) { return selectedValues.length > 0; } - }) + }); }, _init: function () { BI.MultiSelectBar.superclass._init.apply(this, arguments); @@ -76,7 +76,7 @@ BI.MultiSelectBar = BI.inherit(BI.BasicButton, { this.half.invisible(); }, - //自己手动控制选中 + // 自己手动控制选中 beforeClick: function () { var isHalf = this.isHalfSelected(), isSelected = this.isSelected(); if (isHalf === true) { diff --git a/src/case/tree/branchrelation.js b/src/case/tree/branchrelation.js index 535f68802..df1ba4eae 100644 --- a/src/case/tree/branchrelation.js +++ b/src/case/tree/branchrelation.js @@ -12,10 +12,10 @@ BI.BranchRelation = BI.inherit(BI.Widget, { baseCls: "bi-branch-relation-tree", items: [], - centerOffset: 0,//重心偏移量 + centerOffset: 0, // 重心偏移量 direction: BI.Direction.Bottom, align: BI.VerticalAlign.Top - }) + }); }, _init: function () { @@ -23,11 +23,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { this.populate(this.options.items); }, - //树分层 + // 树分层 _stratification: function () { var levels = []; this.tree.recursion(function (node, route) { - //node.isRoot = route.length <= 1; + // node.isRoot = route.length <= 1; node.leaf = node.isLeaf(); if (!levels[route.length - 1]) { levels[route.length - 1] = []; @@ -37,11 +37,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return levels; }, - //计算所有节点的叶子结点个数 + // 计算所有节点的叶子结点个数 _calculateLeaves: function () { var count = 0; - function track(node) { + function track (node) { var c = 0; if (node.isLeaf()) { return 1; @@ -57,7 +57,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return count; }, - //树平移 + // 树平移 _translate: function (levels) { var adjust = []; var maxLevel = levels.length; @@ -68,16 +68,16 @@ BI.BranchRelation = BI.inherit(BI.Widget, { BI.each(nodes, function (j, node) { if (node.isLeaf() && i < maxLevel - 1) { var newNode = new BI.Node(BI.UUID()); - //newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; + // newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; newNode.isNew = true; - //把node向下一层移 + // 把node向下一层移 var tar = 0; if (j > 0) { var c = nodes[j - 1].getLastChild(); tar = levels[i + 1].indexOf(c) + 1; } levels[i + 1].splice(tar, 0, node); - //新增一个临时树节点 + // 新增一个临时树节点 var index = node.parent.getChildIndex(node.id); node.parent.removeChildByIndex(index); node.parent.addChild(newNode, index); @@ -87,12 +87,12 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } else { adjust[i].push(node); } - }) + }); }); return adjust; }, - //树补白 + // 树补白 _fill: function (levels) { var adjust = []; var maxLevel = levels.length; @@ -107,23 +107,23 @@ BI.BranchRelation = BI.inherit(BI.Widget, { newNode.width = node.width; newNode.height = node.height; newNode.isNew = true; - //把node向下一层移 + // 把node向下一层移 var tar = 0; if (j > 0) { var c = nodes[j - 1].getLastChild(); tar = levels[i + 1].indexOf(c) + 1; } levels[i + 1].splice(tar, 0, newNode); - //新增一个临时树节点 + // 新增一个临时树节点 node.addChild(newNode); } adjust[i].push(node); - }) + }); }); return adjust; }, - //树调整 + // 树调整 _adjust: function (adjust) { while (true) { var isAllNeedAjust = false; @@ -147,7 +147,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { node.addChild(c); }); var newNode = new BI.Node(BI.UUID()); - //newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; + // newNode.isEmptyRoot = node.isRoot || node.isEmptyRoot; newNode.isNew = true; var index = node.parent.getChildIndex(node.id); node.parent.removeChildByIndex(index); @@ -156,11 +156,11 @@ BI.BranchRelation = BI.inherit(BI.Widget, { isAllNeedAjust = true; } } - }) + }); }); if (isAllNeedAjust === false) { break; - } else {//树重构 + } else {// 树重构 adjust = this._stratification(); } } @@ -171,7 +171,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var o = this.options; var width = 0; - function track1(node) { + function track1 (node) { var w = 0; if (node.isLeaf()) { return node.width; @@ -182,7 +182,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return w; } - function track2(node) { + function track2 (node) { var w = 0; if (node.isLeaf()) { return node.height; @@ -211,7 +211,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var o = this.options; var height = 0; - function track1(node) { + function track1 (node) { var h = 0; BI.each(node.getChildren(), function (i, child) { h = Math.max(h, track1(child)); @@ -219,7 +219,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { return h + (node.height || 0); } - function track2(node) { + function track2 (node) { var h = 0; BI.each(node.getChildren(), function (i, child) { h = Math.max(h, track2(child)); @@ -241,23 +241,23 @@ BI.BranchRelation = BI.inherit(BI.Widget, { var height = this._calculateHeight(); var levelCount = levels.length; var allLeavesCount = this._calculateLeaves(); - //计算坐标 + // 计算坐标 var xy = {}; var levelHeight = height / levelCount; BI.each(levels, function (i, nodes) { - //计算权重 + // 计算权重 var weights = []; BI.each(nodes, function (j, node) { weights[j] = (node.get("leaves") || 1) / allLeavesCount; }); BI.each(nodes, function (j, node) { - //求前j个元素的权重 + // 求前j个元素的权重 var weight = BI.sum(weights.slice(0, j)); - //求坐标 + // 求坐标 var x = weight * width + weights[j] * width / 2; var y = i * levelHeight + levelHeight / 2; xy[node.id] = {x: x, y: y}; - }) + }); }); return xy; }, @@ -286,7 +286,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Bottom: @@ -307,7 +307,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Left: @@ -328,7 +328,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; case BI.Direction.Right: @@ -349,7 +349,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } self.svg.path(path).attr("stroke", "#d4dadd"); } - }) + }); }); break; } @@ -361,14 +361,14 @@ BI.BranchRelation = BI.inherit(BI.Widget, { levels = levels.reverse(); } var xy = this._calculateXY(levels); - //画图 + // 画图 this._stroke(levels, xy); }, _isNeedAdjust: function () { var o = this.options; return o.direction === BI.Direction.Top && o.align === BI.VerticalAlign.Bottom || o.direction === BI.Direction.Bottom && o.align === BI.VerticalAlign.Top - || o.direction === BI.Direction.Left && o.align === BI.HorizontalAlign.Right || o.direction === BI.Direction.Right && o.align === BI.HorizontalAlign.Left + || o.direction === BI.Direction.Left && o.align === BI.HorizontalAlign.Right || o.direction === BI.Direction.Right && o.align === BI.HorizontalAlign.Left; }, setValue: function (value) { @@ -402,9 +402,9 @@ BI.BranchRelation = BI.inherit(BI.Widget, { } } return r; - } else { - return [sNodes]; } + return [sNodes]; + }, populate: function (items) { @@ -419,13 +419,13 @@ BI.BranchRelation = BI.inherit(BI.Widget, { type: "bi.svg" }); - //树分层 + // 树分层 var levels = this._stratification(); if (this._isNeedAdjust()) { - //树平移 + // 树平移 var adjust = this._translate(levels); - //树调整 + // 树调整 adjust = this._adjust(adjust); this._createBranches(adjust); @@ -464,7 +464,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { }] }, items: items - }] + }]; } else { items = [{ type: "bi.branch_tree", @@ -479,7 +479,7 @@ BI.BranchRelation = BI.inherit(BI.Widget, { }] }, items: items - }] + }]; } BI.createWidget({ type: "bi.adaptive", diff --git a/src/case/tree/expander/expander.branch.handstand.js b/src/case/tree/expander/expander.branch.handstand.js index 69595011e..425c02ed9 100644 --- a/src/case/tree/expander/expander.branch.handstand.js +++ b/src/case/tree/expander/expander.branch.handstand.js @@ -14,7 +14,7 @@ BI.HandStandBranchExpander = BI.inherit(BI.Widget, { }, el: {type: "bi.label"}, popup: {} - }) + }); }, _init: function () { diff --git a/src/case/tree/expander/expander.branch.js b/src/case/tree/expander/expander.branch.js index 5a70ade0a..5eff6614c 100644 --- a/src/case/tree/expander/expander.branch.js +++ b/src/case/tree/expander/expander.branch.js @@ -13,7 +13,7 @@ BI.BranchExpander = BI.inherit(BI.Widget, { }, el: {}, popup: {} - }) + }); }, _init: function () { diff --git a/src/case/tree/tree.branch.handstand.js b/src/case/tree/tree.branch.handstand.js index 0259daa40..7d8b6e28c 100644 --- a/src/case/tree/tree.branch.handstand.js +++ b/src/case/tree/tree.branch.handstand.js @@ -11,7 +11,7 @@ BI.HandStandBranchTree = BI.inherit(BI.Widget, { expander: {}, el: {}, items: [] - }) + }); }, _init: function () { BI.HandStandBranchTree.superclass._init.apply(this, arguments); @@ -35,10 +35,10 @@ BI.HandStandBranchTree = BI.inherit(BI.Widget, { }, o.el), items: this.options.items }); - this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function(){ + this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function () { self.fireEvent(BI.HandStandBranchTree.EVENT_CHANGE, arguments); }); - this.branchTree.on(BI.Controller.EVENT_CHANGE, function(){ + this.branchTree.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); }, diff --git a/src/case/tree/tree.branch.js b/src/case/tree/tree.branch.js index f1c5334db..f56540d24 100644 --- a/src/case/tree/tree.branch.js +++ b/src/case/tree/tree.branch.js @@ -11,7 +11,7 @@ BI.BranchTree = BI.inherit(BI.Widget, { expander: {}, el: {}, items: [] - }) + }); }, _init: function () { BI.BranchTree.superclass._init.apply(this, arguments); @@ -35,10 +35,10 @@ BI.BranchTree = BI.inherit(BI.Widget, { }, o.el), items: this.options.items }); - this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function(){ + this.branchTree.on(BI.CustomTree.EVENT_CHANGE, function () { self.fireEvent(BI.BranchTree.EVENT_CHANGE, arguments); }); - this.branchTree.on(BI.Controller.EVENT_CHANGE, function(){ + this.branchTree.on(BI.Controller.EVENT_CHANGE, function () { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); }, diff --git a/src/case/tree/tree.display.js b/src/case/tree/tree.display.js index 41cf91acf..175d5c06b 100644 --- a/src/case/tree/tree.display.js +++ b/src/case/tree/tree.display.js @@ -8,13 +8,13 @@ BI.DisplayTree = BI.inherit(BI.TreeView, { _defaultConfig: function () { return BI.extend(BI.DisplayTree.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-display-tree" - }) + }); }, _init: function () { BI.DisplayTree.superclass._init.apply(this, arguments); }, - //配置属性 + // 配置属性 _configSetting: function () { var setting = { view: { @@ -37,7 +37,7 @@ BI.DisplayTree = BI.inherit(BI.TreeView, { } }; - function beforeCollapse(treeId, treeNode) { + function beforeCollapse (treeId, treeNode) { return false; } diff --git a/src/case/tree/tree.level.js b/src/case/tree/tree.level.js index 3ca6a75dc..7698607a7 100644 --- a/src/case/tree/tree.level.js +++ b/src/case/tree/tree.level.js @@ -13,7 +13,7 @@ BI.LevelTree = BI.inherit(BI.Widget, { }, expander: {}, items: [] - }) + }); }, _init: function () { @@ -65,7 +65,7 @@ BI.LevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -95,10 +95,10 @@ BI.LevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.LevelTree.EVENT_CHANGE, arguments); } - }) + }); }, - //生成树方法 + // 生成树方法 stroke: function (nodes) { this.tree.stroke.apply(this.tree, arguments); }, diff --git a/src/case/tree/tree.simple.js b/src/case/tree/tree.simple.js index fc267b49d..0bf1346fe 100644 --- a/src/case/tree/tree.simple.js +++ b/src/case/tree/tree.simple.js @@ -11,7 +11,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { baseCls: "bi-simple-tree", itemsCreator: BI.emptyFn, items: null - }) + }); }, _init: function () { BI.SimpleTreeView.superclass._init.apply(this, arguments); @@ -92,7 +92,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { } else { track(node); } - }) + }); }; track(val); return result; @@ -111,7 +111,7 @@ BI.SimpleTreeView = BI.inherit(BI.Widget, { if (node.isLeaf()) { result.push(node.value); } - }) + }); } }); return result; diff --git a/src/case/trigger/trigger.editor.js b/src/case/trigger/trigger.editor.js index d25cb54b0..97fb48ce2 100644 --- a/src/case/trigger/trigger.editor.js +++ b/src/case/trigger/trigger.editor.js @@ -46,7 +46,7 @@ BI.EditorTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor diff --git a/src/case/trigger/trigger.icon.js b/src/case/trigger/trigger.icon.js index 0872514ae..dc3cbaae6 100644 --- a/src/case/trigger/trigger.icon.js +++ b/src/case/trigger/trigger.icon.js @@ -25,4 +25,4 @@ BI.IconTrigger = BI.inherit(BI.Trigger, { }); } }); -BI.shortcut('bi.icon_trigger', BI.IconTrigger); \ No newline at end of file +BI.shortcut("bi.icon_trigger", BI.IconTrigger); \ No newline at end of file diff --git a/src/case/trigger/trigger.icon.text.js b/src/case/trigger/trigger.icon.text.js index 3e972e5ce..0095c4325 100644 --- a/src/case/trigger/trigger.icon.text.js +++ b/src/case/trigger/trigger.icon.text.js @@ -36,7 +36,7 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", ref: function (_ref) { self.wrapper = _ref; }, @@ -51,12 +51,12 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { }, width: o.triggerWidth || o.height }, - { - el: this.text - }, { - el: this.trigerButton, - width: o.triggerWidth || o.height - } + { + el: this.text + }, { + el: this.trigerButton, + width: o.triggerWidth || o.height + } ] }); }, @@ -70,13 +70,13 @@ BI.IconTextTrigger = BI.inherit(BI.Trigger, { var o = this.options; this.icon.setIcon(iconCls); var iconItem = this.wrapper.attr("items")[0]; - if(BI.isNull(iconCls) || BI.isEmptyString(iconCls)){ - if(iconItem.width !== 0){ + if(BI.isNull(iconCls) || BI.isEmptyString(iconCls)) { + if(iconItem.width !== 0) { iconItem.width = 0; this.wrapper.resize(); } }else{ - if(iconItem.width !== (o.triggerWidth || o.height)){ + if(iconItem.width !== (o.triggerWidth || o.height)) { iconItem.width = (o.triggerWidth || o.height); this.wrapper.resize(); } diff --git a/src/case/trigger/trigger.text.js b/src/case/trigger/trigger.text.js index 44b4dd46f..290315ad4 100644 --- a/src/case/trigger/trigger.text.js +++ b/src/case/trigger/trigger.text.js @@ -37,7 +37,7 @@ BI.TextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.text diff --git a/src/case/trigger/trigger.text.small.js b/src/case/trigger/trigger.text.small.js index 754412d4a..cae070cfa 100644 --- a/src/case/trigger/trigger.text.small.js +++ b/src/case/trigger/trigger.text.small.js @@ -34,7 +34,7 @@ BI.SmallTextTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.text diff --git a/src/component/allvaluechooser/abstract.allvaluechooser.js b/src/component/allvaluechooser/abstract.allvaluechooser.js index 5183a27fa..067300476 100644 --- a/src/component/allvaluechooser/abstract.allvaluechooser.js +++ b/src/component/allvaluechooser/abstract.allvaluechooser.js @@ -45,7 +45,7 @@ BI.AbstractAllValueChooser = BI.inherit(BI.Widget, { } else { call(this.items); } - function call(items) { + function call (items) { var keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); @@ -54,7 +54,7 @@ BI.AbstractAllValueChooser = BI.inherit(BI.Widget, { var search = BI.Func.getSearchResult(items, kw); items = search.matched.concat(search.finded); }); - if (options.selectedValues) {//过滤 + if (options.selectedValues) {// 过滤 var filter = BI.makeObject(options.selectedValues, true); items = BI.filter(items, function (i, ob) { return !filter[ob.value]; diff --git a/src/component/allvaluechooser/combo.allvaluechooser.js b/src/component/allvaluechooser/combo.allvaluechooser.js index 908da7ec9..2e4e1ef4a 100644 --- a/src/component/allvaluechooser/combo.allvaluechooser.js +++ b/src/component/allvaluechooser/combo.allvaluechooser.js @@ -26,7 +26,7 @@ BI.AllValueChooserCombo = BI.inherit(BI.AbstractAllValueChooser, { this.items = o.items; } this.combo = BI.createWidget({ - type: 'bi.multi_select_combo', + type: "bi.multi_select_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -59,4 +59,4 @@ BI.AllValueChooserCombo = BI.inherit(BI.AbstractAllValueChooser, { } }); BI.AllValueChooserCombo.EVENT_CONFIRM = "AllValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.all_value_chooser_combo', BI.AllValueChooserCombo); \ No newline at end of file +BI.shortcut("bi.all_value_chooser_combo", BI.AllValueChooserCombo); \ No newline at end of file diff --git a/src/component/allvaluechooser/pane.allvaluechooser.js b/src/component/allvaluechooser/pane.allvaluechooser.js index 4d9a1f408..2ebc7972f 100644 --- a/src/component/allvaluechooser/pane.allvaluechooser.js +++ b/src/component/allvaluechooser/pane.allvaluechooser.js @@ -26,7 +26,7 @@ BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, { this.items = o.items; } this.list = BI.createWidget({ - type: 'bi.multi_select_list', + type: "bi.multi_select_list", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -59,4 +59,4 @@ BI.AllValueChooserPane = BI.inherit(BI.AbstractAllValueChooser, { } }); BI.AllValueChooserPane.EVENT_CHANGE = "AllValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.all_value_chooser_pane', BI.AllValueChooserPane); \ No newline at end of file +BI.shortcut("bi.all_value_chooser_pane", BI.AllValueChooserPane); \ No newline at end of file diff --git a/src/component/treevaluechooser/abstract.treevaluechooser.js b/src/component/treevaluechooser/abstract.treevaluechooser.js index d881febe3..208ada8d7 100644 --- a/src/component/treevaluechooser/abstract.treevaluechooser.js +++ b/src/component/treevaluechooser/abstract.treevaluechooser.js @@ -28,7 +28,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { } else { call(); } - function call() { + function call () { switch (options.type) { case BI.TreeView.REQ_TYPE_INIT_DATA: self._reqInitTreeNode(options, callback); @@ -65,7 +65,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { items: result }); - function doCheck(parentValues, node, selected) { + function doCheck (parentValues, node, selected) { if (selected == null || BI.isEmpty(selected)) { BI.each(node.getChildren(), function (i, child) { var newParents = BI.clone(parentValues); @@ -82,10 +82,10 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { newParents.push(node.value); createOneJson(node, node.parent && node.parent.id, getCount(selected[k], newParents)); doCheck(newParents, node, selected[k]); - }) + }); } - function getCount(jo, parentValues) { + function getCount (jo, parentValues) { if (jo == null) { return 0; } @@ -96,7 +96,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return BI.size(jo); } - function createOneJson(node, pId, llen) { + function createOneJson (node, pId, llen) { result.push({ id: node.id, pId: pId, @@ -123,15 +123,15 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { callback(selectedValues); - function dealWithSelectedValues(selectedValues) { + function dealWithSelectedValues (selectedValues) { var p = parentValues.concat(notSelectedValue); - //存储的值中存在这个值就把它删掉 - //例如选中了中国-江苏-南京, 取消中国或江苏或南京 + // 存储的值中存在这个值就把它删掉 + // 例如选中了中国-江苏-南京, 取消中国或江苏或南京 if (canFindKey(selectedValues, p)) { - //如果搜索的值在父亲链中 + // 如果搜索的值在父亲链中 if (isSearchValueInParent(p)) { - //例如选中了 中国-江苏, 搜索江苏, 取消江苏 - //例如选中了 中国-江苏, 搜索江苏, 取消中国 + // 例如选中了 中国-江苏, 搜索江苏, 取消江苏 + // 例如选中了 中国-江苏, 搜索江苏, 取消中国 self._deleteNode(selectedValues, p); } else { var searched = []; @@ -140,50 +140,50 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { BI.each(searched, function (i, arr) { var node = self._getNode(selectedValues, arr); if (node) { - //例如选中了 中国-江苏-南京,搜索南京,取消中国 + // 例如选中了 中国-江苏-南京,搜索南京,取消中国 self._deleteNode(selectedValues, arr); } else { - //例如选中了 中国-江苏,搜索南京,取消中国 + // 例如选中了 中国-江苏,搜索南京,取消中国 expandSelectedValue(selectedValues, arr, BI.last(arr)); } - }) + }); } } } - //存储的值中不存在这个值,但父亲节点是全选的情况 - //例如选中了中国-江苏,取消南京 - //important 选中了中国-江苏,取消了江苏,但是搜索的是南京 + // 存储的值中不存在这个值,但父亲节点是全选的情况 + // 例如选中了中国-江苏,取消南京 + // important 选中了中国-江苏,取消了江苏,但是搜索的是南京 if (isChild(selectedValues, p)) { var result = [], finded = false; - //如果parentValues中有匹配的值,说明搜索结果不在当前值下 + // 如果parentValues中有匹配的值,说明搜索结果不在当前值下 if (isSearchValueInParent(p)) { finded = true; } else { - //从当前值开始搜 + // 从当前值开始搜 finded = search(parentValues, notSelectedValue, result); p = parentValues; } if (finded === true) { - //去掉点击的节点之后的结果集 + // 去掉点击的节点之后的结果集 expandSelectedValue(selectedValues, p, notSelectedValue); - //添加去掉搜索的结果集 + // 添加去掉搜索的结果集 if (result.length > 0) { BI.each(result, function (i, strs) { self._buildTree(selectedValues, strs); - }) + }); } } } } - function expandSelectedValue(selectedValues, parents, notSelectedValue) { + function expandSelectedValue (selectedValues, parents, notSelectedValue) { var next = selectedValues; var childrenCount = []; var path = []; - //去掉点击的节点之后的结果集 + // 去掉点击的节点之后的结果集 BI.some(parents, function (i, v) { var t = next[v]; if (t == null) { @@ -195,7 +195,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { var expanded = self._getChildren(split); path.push(split); childrenCount.push(expanded.length); - //如果只有一个值且取消的就是这个值 + // 如果只有一个值且取消的就是这个值 if (i === parents.length - 1 && expanded.length === 1 && expanded[0] === notSelectedValue) { for (var j = childrenCount.length - 1; j >= 0; j--) { if (childrenCount[j] === 1) { @@ -224,7 +224,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { }); } - function search(parents, current, result, searched) { + function search (parents, current, result, searched) { var newParents = BI.clone(parents); newParents.push(current); if (self._isMatch(parents, current, keyword)) { @@ -254,7 +254,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return can; } - function isSearchValueInParent(parentValues) { + function isSearchValueInParent (parentValues) { for (var i = 0, len = parentValues.length; i < len; i++) { if (self._isMatch(parentValues.slice(0, parentValues.length - 1), parentValues[i], keyword)) { return true; @@ -263,7 +263,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return false; } - function canFindKey(selectedValues, parents) { + function canFindKey (selectedValues, parents) { var t = selectedValues; for (var i = 0; i < parents.length; i++) { var v = parents[i]; @@ -275,7 +275,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return true; } - function isChild(selectedValues, parents) { + function isChild (selectedValues, parents) { var t = selectedValues; for (var i = 0; i < parents.length; i++) { var v = parents[i]; @@ -311,7 +311,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { }); callback(jo); - function dealWithSelectedValues(selected, parents) { + function dealWithSelectedValues (selected, parents) { if (selected == null || BI.isEmpty(selected)) { return true; } @@ -331,7 +331,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return can && isAllSelected(selected, parents); } - function isAllSelected(selected, parents) { + function isAllSelected (selected, parents) { return BI.isEmpty(selected) || self._getChildCount(parents) === BI.size(selected); } }, @@ -348,10 +348,10 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { hasNext: output.length > self._const.perPage, items: result, lastSearchValue: BI.last(output) - }) + }); }); - function search() { + function search () { var children = self._getChildren([]); var start = children.length; if (lastSearchValue !== "") { @@ -381,7 +381,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return output; } - function nodeSearch(deep, parentValues, current, isAllSelect, result) { + function nodeSearch (deep, parentValues, current, isAllSelect, result) { if (self._isMatch(parentValues, current, keyword)) { var checked = isAllSelect || isSelected(parentValues, current); createOneJson(parentValues, current, false, checked, !isAllSelect && isHalf(parentValues, current), true, result); @@ -410,8 +410,8 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return [can, checked]; } - function createOneJson(parentValues, value, isOpen, checked, half, flag, result) { - var node = self._getTreeNode(parentValues, value) + function createOneJson (parentValues, value, isOpen, checked, half, flag, result) { + var node = self._getTreeNode(parentValues, value); result.push({ id: node.id, pId: node.pId, @@ -426,7 +426,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { }); } - function isHalf(parentValues, value) { + function isHalf (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return null; @@ -440,7 +440,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { }); } - function isAllSelected(parentValues, value) { + function isAllSelected (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return null; @@ -454,7 +454,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { }); } - function isSelected(parentValues, value) { + function isSelected (parentValues, value) { var find = findSelectedObj(parentValues); if (find == null) { return false; @@ -466,7 +466,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { }); } - function findSelectedObj(parentValues) { + function findSelectedObj (parentValues) { var find = selectedValues; if (find == null) { return null; @@ -505,7 +505,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { isParent: nodes[i].getChildrenLength() > 0, checked: state[0], halfCheck: state[1] - }) + }); } BI.nextTick(function () { callback({ @@ -514,7 +514,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { }); }); - function judgeState(parentValues, selected_value, checkState) { + function judgeState (parentValues, selected_value, checkState) { var checked = checkState.checked, half = checkState.half; if (parentValues.length > 0 && !checked) { return false; @@ -522,7 +522,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return (parentValues.length === 0 || (checked && half) && !BI.isEmpty(selected_value)); } - function dealWidthSelectedValue(parentValues, selectedValues) { + function dealWidthSelectedValue (parentValues, selectedValues) { var valueMap = {}; BI.each(parentValues, function (i, v) { selectedValues = selectedValues[v] || {}; @@ -547,11 +547,11 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { return valueMap; } - function getCheckState(current, parentValues, valueMap, checkState) { + function getCheckState (current, parentValues, valueMap, checkState) { var checked = checkState.checked, half = checkState.half; var tempCheck = false, halfCheck = false; if (BI.has(valueMap, current)) { - //可能是半选 + // 可能是半选 if (valueMap[current][0] === 1) { var values = BI.clone(parentValues); values.push(current); @@ -590,7 +590,7 @@ BI.AbstractTreeValueChooser = BI.inherit(BI.Widget, { var pNode = this._getNode(selectedValues, p); if (pNode != null && pNode[name]) { delete pNode[name]; - //递归删掉空父节点 + // 递归删掉空父节点 while (p.length > 0 && BI.isEmpty(pNode)) { name = p[p.length - 1]; p = p.slice(0, p.length - 1); diff --git a/src/component/treevaluechooser/combo.treevaluechooser.js b/src/component/treevaluechooser/combo.treevaluechooser.js index 5a7fa64ac..025094fa3 100644 --- a/src/component/treevaluechooser/combo.treevaluechooser.js +++ b/src/component/treevaluechooser/combo.treevaluechooser.js @@ -24,7 +24,7 @@ BI.TreeValueChooserCombo = BI.inherit(BI.AbstractTreeValueChooser, { this._initData(o.items); } this.combo = BI.createWidget({ - type: 'bi.multi_tree_combo', + type: "bi.multi_tree_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), width: o.width, @@ -49,4 +49,4 @@ BI.TreeValueChooserCombo = BI.inherit(BI.AbstractTreeValueChooser, { } }); BI.TreeValueChooserCombo.EVENT_CONFIRM = "TreeValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.tree_value_chooser_combo', BI.TreeValueChooserCombo); \ No newline at end of file +BI.shortcut("bi.tree_value_chooser_combo", BI.TreeValueChooserCombo); \ No newline at end of file diff --git a/src/component/treevaluechooser/pane.treevaluechooser.js b/src/component/treevaluechooser/pane.treevaluechooser.js index c0ebb8f32..457ee13ce 100644 --- a/src/component/treevaluechooser/pane.treevaluechooser.js +++ b/src/component/treevaluechooser/pane.treevaluechooser.js @@ -19,7 +19,7 @@ BI.TreeValueChooserPane = BI.inherit(BI.AbstractTreeValueChooser, { BI.TreeValueChooserPane.superclass._init.apply(this, arguments); var self = this, o = this.options; this.pane = BI.createWidget({ - type: 'bi.multi_select_tree', + type: "bi.multi_select_tree", element: this, itemsCreator: BI.bind(this._itemsCreator, this) }); @@ -50,4 +50,4 @@ BI.TreeValueChooserPane = BI.inherit(BI.AbstractTreeValueChooser, { } }); BI.TreeValueChooserPane.EVENT_CHANGE = "TreeValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.tree_value_chooser_pane', BI.TreeValueChooserPane); \ No newline at end of file +BI.shortcut("bi.tree_value_chooser_pane", BI.TreeValueChooserPane); \ No newline at end of file diff --git a/src/component/valuechooser/abstract.valuechooser.js b/src/component/valuechooser/abstract.valuechooser.js index 9b96e1ab5..d1af0431c 100644 --- a/src/component/valuechooser/abstract.valuechooser.js +++ b/src/component/valuechooser/abstract.valuechooser.js @@ -55,7 +55,7 @@ BI.AbstractValueChooser = BI.inherit(BI.Widget, { } else { call(this.items); } - function call(items) { + function call (items) { var keywords = (options.keywords || []).slice(); if (options.keyword) { keywords.push(options.keyword); @@ -64,7 +64,7 @@ BI.AbstractValueChooser = BI.inherit(BI.Widget, { var search = BI.Func.getSearchResult(items, kw); items = search.matched.concat(search.finded); }); - if (options.selectedValues) {//过滤 + if (options.selectedValues) {// 过滤 var filter = BI.makeObject(options.selectedValues, true); items = BI.filter(items, function (i, ob) { return !filter[ob.value]; diff --git a/src/component/valuechooser/combo.valuechooser.js b/src/component/valuechooser/combo.valuechooser.js index 2f88d2128..ad20c8098 100644 --- a/src/component/valuechooser/combo.valuechooser.js +++ b/src/component/valuechooser/combo.valuechooser.js @@ -26,7 +26,7 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { this.items = o.items; } this.combo = BI.createWidget({ - type: 'bi.multi_select_combo', + type: "bi.multi_select_combo", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this), @@ -48,7 +48,7 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { return { type: val.type, value: val.value - } + }; }, populate: function () { @@ -56,4 +56,4 @@ BI.ValueChooserCombo = BI.inherit(BI.AbstractValueChooser, { } }); BI.ValueChooserCombo.EVENT_CONFIRM = "ValueChooserCombo.EVENT_CONFIRM"; -BI.shortcut('bi.value_chooser_combo', BI.ValueChooserCombo); \ No newline at end of file +BI.shortcut("bi.value_chooser_combo", BI.ValueChooserCombo); \ No newline at end of file diff --git a/src/component/valuechooser/pane.valuechooser.js b/src/component/valuechooser/pane.valuechooser.js index 49c4aaf18..d23af6507 100644 --- a/src/component/valuechooser/pane.valuechooser.js +++ b/src/component/valuechooser/pane.valuechooser.js @@ -21,7 +21,7 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { BI.ValueChooserPane.superclass._init.apply(this, arguments); var self = this, o = this.options; this.list = BI.createWidget({ - type: 'bi.multi_select_list', + type: "bi.multi_select_list", element: this, itemsCreator: BI.bind(this._itemsCreator, this), valueFormatter: BI.bind(this._valueFormatter, this) @@ -45,7 +45,7 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { return { type: val.type, value: val.value - } + }; }, populate: function () { @@ -53,4 +53,4 @@ BI.ValueChooserPane = BI.inherit(BI.AbstractValueChooser, { } }); BI.ValueChooserPane.EVENT_CHANGE = "ValueChooserPane.EVENT_CHANGE"; -BI.shortcut('bi.value_chooser_pane', BI.ValueChooserPane); \ No newline at end of file +BI.shortcut("bi.value_chooser_pane", BI.ValueChooserPane); \ No newline at end of file diff --git a/src/config.js b/src/config.js index 07cb50f29..de637374c 100644 --- a/src/config.js +++ b/src/config.js @@ -1,96 +1,96 @@ -//工程配置 +// 工程配置 (function () { - //注册布局 + // 注册布局 var isSupportFlex = BI.isSupportCss3("flex"); BI.Plugin.registerWidget("bi.horizontal", function (ob) { if (isSupportFlex) { return BI.extend(ob, {type: "bi.flex_horizontal"}); - } else { - return ob; } + return ob; + }); BI.Plugin.registerWidget("bi.center_adapt", function (ob) { if (isSupportFlex && ob.items && ob.items.length <= 1) { - //有滚动条的情况下需要用到flex_wrapper_center布局 + // 有滚动条的情况下需要用到flex_wrapper_center布局 if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { - //不是IE用flex_wrapper_center布局 + // 不是IE用flex_wrapper_center布局 if (!BI.isIE()) { return BI.extend(ob, {type: "bi.flex_wrapper_center"}); } return ob; } return BI.extend(ob, {type: "bi.flex_center"}); - } else { - return ob; } + return ob; + }); BI.Plugin.registerWidget("bi.vertical_adapt", function (ob) { if (isSupportFlex) { - //有滚动条的情况下需要用到flex_wrapper_center布局 + // 有滚动条的情况下需要用到flex_wrapper_center布局 if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { - //不是IE用flex_wrapper_center布局 + // 不是IE用flex_wrapper_center布局 if (!BI.isIE()) { return BI.extend({}, ob, {type: "bi.flex_wrapper_vertical_center"}); } return ob; } return BI.extend(ob, {type: "bi.flex_vertical_center"}); - } else { - return ob; } + return ob; + }); BI.Plugin.registerWidget("bi.float_center_adapt", function (ob) { if (isSupportFlex) { - //有滚动条的情况下需要用到flex_wrapper_center布局 + // 有滚动条的情况下需要用到flex_wrapper_center布局 if (ob.scrollable === true || ob.scrollx === true || ob.scrolly === true) { - //不是IE用flex_wrapper_center布局 + // 不是IE用flex_wrapper_center布局 if (!BI.isIE()) { return BI.extend({}, ob, {type: "bi.flex_wrapper_center"}); } return ob; } return BI.extend(ob, {type: "bi.flex_center"}); - } else { - return ob; } + return ob; + }); - //注册滚动条 + // 注册滚动条 BI.Plugin.registerWidget("bi.grid_table_scrollbar", function (ob) { if (BI.isIE9Below()) { return BI.extend(ob, {type: "bi.native_table_scrollbar"}); - } else { - return ob; } + return ob; + }); BI.Plugin.registerWidget("bi.grid_table_horizontal_scrollbar", function (ob) { if (BI.isIE9Below()) { return BI.extend(ob, {type: "bi.native_table_horizontal_scrollbar"}); - } else { - return ob; } + return ob; + }); - //注册控件 + // 注册控件 BI.Plugin.registerWidget("bi.grid_table", function (ob) { - //非chrome下滚动条滑动效果不好,禁止掉 + // 非chrome下滚动条滑动效果不好,禁止掉 if (!(BI.isChrome() && BI.isWindows() && !BI.isEdge())) { return BI.extend(ob, {type: "bi.quick_grid_table"}); - } else { - return ob; } + return ob; + }); BI.Plugin.registerWidget("bi.collection_table", function (ob) { - //非chrome下滚动条滑动效果不好,禁止掉 + // 非chrome下滚动条滑动效果不好,禁止掉 if (!(BI.isChrome() && BI.isWindows() && !BI.isEdge())) { return BI.extend(ob, {type: "bi.quick_collection_table"}); - } else { - return ob; } + return ob; + }); - //IE8下滚动条用原生的 + // IE8下滚动条用原生的 $(function () { if (BI.isIE9Below()) { BI.GridTableScrollbar.SIZE = 18; } - }) + }); }()); \ No newline at end of file diff --git a/src/data/pool/pool.buffer.js b/src/data/pool/pool.buffer.js index 0dc70a243..a6d9b9509 100644 --- a/src/data/pool/pool.buffer.js +++ b/src/data/pool/pool.buffer.js @@ -2,10 +2,10 @@ * 缓冲池 * @type {{Buffer: {}}} */ -; + (function () { var Buffer = {}; - var MODE = false;//设置缓存模式为关闭 + var MODE = false;// 设置缓存模式为关闭 Data.BufferPool = { put: function (name, cache) { diff --git a/src/data/pool/pool.sharing.js b/src/data/pool/pool.sharing.js index 5bbb53331..614fc7997 100644 --- a/src/data/pool/pool.sharing.js +++ b/src/data/pool/pool.sharing.js @@ -2,7 +2,7 @@ * 共享池 * @type {{Shared: {}}} */ -; + (function () { var _Shared = {}; Data.SharingPool = { diff --git a/src/polyfill/array.js b/src/polyfill/array.js index 266f7b3f8..e3b248fc9 100644 --- a/src/polyfill/array.js +++ b/src/polyfill/array.js @@ -8,7 +8,7 @@ if (!Array.prototype.indexOf) { // 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'); + throw new TypeError("\"this\" is null or not defined"); } var o = Object(this); @@ -60,8 +60,8 @@ if (!Array.prototype.indexOf) { }; } if (!Array.prototype.lastIndexOf) { - Array.prototype.lastIndexOf = function (searchElement /*, fromIndex*/) { - 'use strict'; + Array.prototype.lastIndexOf = function (searchElement /* , fromIndex*/) { + "use strict"; if (this === void 0 || this === null) { throw new TypeError(); @@ -79,8 +79,7 @@ if (!Array.prototype.lastIndexOf) { n = Number(arguments[1]); if (n != n) { n = 0; - } - else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { + } else if (n != 0 && n != (1 / 0) && n != -(1 / 0)) { n = (n > 0 || -1) * Math.floor(Math.abs(n)); } } diff --git a/src/polyfill/console.js b/src/polyfill/console.js index a1c017c06..dc1414a00 100644 --- a/src/polyfill/console.js +++ b/src/polyfill/console.js @@ -2,11 +2,11 @@ * 特殊情况 * Created by wang on 15/6/23. */ -//解决console未定义问题 guy +// 解决console未定义问题 guy window.console = window.console || (function () { - var c = {}; - c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile + var c = {}; + c.log = c.warn = c.debug = c.info = c.error = c.time = c.dir = c.profile = c.clear = c.exception = c.trace = c.assert = function () { }; - return c; - })(); + return c; +})(); diff --git a/src/polyfill/set.js b/src/polyfill/set.js index 5bc42367d..f8f895d17 100644 --- a/src/polyfill/set.js +++ b/src/polyfill/set.js @@ -1,16 +1,16 @@ -if (typeof Set !== 'undefined' && Set.toString().match(/native code/)) { +if (typeof Set !== "undefined" && Set.toString().match(/native code/)) { } else { Set = function () { - this.set = {} + this.set = {}; }; Set.prototype.has = function (key) { return this.set[key] !== undefined; }; Set.prototype.add = function (key) { - this.set[key] = 1 + this.set[key] = 1; }; Set.prototype.clear = function () { - this.set = {} + this.set = {}; }; } \ No newline at end of file diff --git a/src/polyfill/sort.js b/src/polyfill/sort.js index c2581f68a..25ac409dc 100644 --- a/src/polyfill/sort.js +++ b/src/polyfill/sort.js @@ -1,11 +1,11 @@ -//修复ie9下sort方法的bug -;!function (window) { +// 修复ie9下sort方法的bug +!function (window) { var ua = window.navigator.userAgent.toLowerCase(), reg = /msie|applewebkit.+safari/; if (reg.test(ua)) { var _sort = Array.prototype.sort; Array.prototype.sort = function (fn) { - if (!!fn && typeof fn === 'function') { + if (!!fn && typeof fn === "function") { if (this.length < 2) { return this; } @@ -13,8 +13,8 @@ for (; i < l; i++) { for (j = i + 1; j < l; j++) { t = fn.call(this, this[i], this[j]); - r = (typeof t === 'number' ? t : - !!t ? 1 : 0) > 0; + r = (typeof t === "number" ? t : + t ? 1 : 0) > 0; if (r === true) { tmp = this[i]; this[i] = this[j]; @@ -23,9 +23,9 @@ } } return this; - } else { - return _sort.call(this); } + return _sort.call(this); + }; } }(window); \ No newline at end of file diff --git a/src/router/router.js b/src/router/router.js index 4ee73d096..7e90df0a9 100644 --- a/src/router/router.js +++ b/src/router/router.js @@ -1,10 +1,10 @@ -;(function(){ +(function () { var Events = { // Bind an event to a `callback` function. Passing `"all"` will bind // the callback to all events fired. on: function (name, callback, context) { - if (!eventsApi(this, 'on', name, [callback, context]) || !callback) return this; + if (!eventsApi(this, "on", name, [callback, context]) || !callback) return this; this._events || (this._events = {}); var events = this._events[name] || (this._events[name] = []); events.push({callback: callback, context: context, ctx: context || this}); @@ -14,7 +14,7 @@ // Bind an event to only be triggered a single time. After the first time // the callback is invoked, it will be removed. once: function (name, callback, context) { - if (!eventsApi(this, 'once', name, [callback, context]) || !callback) return this; + if (!eventsApi(this, "once", name, [callback, context]) || !callback) return this; var self = this; var once = _.once(function () { self.off(name, once); @@ -29,7 +29,7 @@ // callbacks for the event. If `name` is null, removes all bound // callbacks for all events. off: function (name, callback, context) { - if (!this._events || !eventsApi(this, 'off', name, [callback, context])) return this; + if (!this._events || !eventsApi(this, "off", name, [callback, context])) return this; // Remove all callbacks for all events. if (!name && !callback && !context) { @@ -86,7 +86,7 @@ trigger: function (name) { if (!this._events) return this; var args = slice.call(arguments, 1); - if (!eventsApi(this, 'trigger', name, args)) return this; + if (!eventsApi(this, "trigger", name, args)) return this; var events = this._events[name]; var allEvents = this._events.all; if (events) triggerEvents(events, args); @@ -103,15 +103,15 @@ // listening to. listenTo: function (obj, name, callback) { var listeningTo = this._listeningTo || (this._listeningTo = {}); - var id = obj._listenId || (obj._listenId = _.uniqueId('l')); + var id = obj._listenId || (obj._listenId = _.uniqueId("l")); listeningTo[id] = obj; - if (!callback && typeof name === 'object') callback = this; + if (!callback && typeof name === "object") callback = this; obj.on(name, callback, this); return this; }, listenToOnce: function (obj, name, callback) { - if (typeof name === 'object') { + if (typeof name === "object") { for (var event in name) this.listenToOnce(obj, event, name[event]); return this; } @@ -137,7 +137,7 @@ var listeningTo = this._listeningTo; if (!listeningTo) return this; var remove = !name && !callback; - if (!callback && typeof name === 'object') callback = this; + if (!callback && typeof name === "object") callback = this; if (obj) (listeningTo = {})[obj._listenId] = obj; for (var id in listeningTo) { obj = listeningTo[id]; @@ -159,7 +159,7 @@ if (!name) return true; // Handle event maps. - if (typeof name === 'object') { + if (typeof name === "object") { for (var key in name) { obj[action].apply(obj, [key, name[key]].concat(rest)); } @@ -239,16 +239,16 @@ if (!_.isRegExp(route)) route = this._routeToRegExp(route); if (_.isFunction(name)) { callback = name; - name = ''; + name = ""; } if (!callback) callback = this[name]; var router = this; BI.history.route(route, function (fragment) { var args = router._extractParameters(route, fragment); if (router.execute(callback, args, name) !== false) { - router.trigger.apply(router, ['route:' + name].concat(args)); - router.trigger('route', name, args); - BI.history.trigger('route', router, name, args); + router.trigger.apply(router, ["route:" + name].concat(args)); + router.trigger("route", name, args); + BI.history.trigger("route", router, name, args); } }); return this; @@ -271,7 +271,7 @@ // routes can be defined at the bottom of the route map. _bindRoutes: function () { if (!this.routes) return; - this.routes = _.result(this, 'routes'); + this.routes = _.result(this, "routes"); var route, routes = _.keys(this.routes); while ((route = routes.pop()) != null) { this.route(route, this.routes[route]); @@ -281,13 +281,13 @@ // Convert a route string into a regular expression, suitable for matching // against the current location hash. _routeToRegExp: function (route) { - route = route.replace(escapeRegExp, '\\$&') - .replace(optionalParam, '(?:$1)?') + route = route.replace(escapeRegExp, "\\$&") + .replace(optionalParam, "(?:$1)?") .replace(namedParam, function (match, optional) { - return optional ? match : '([^/?]+)'; + return optional ? match : "([^/?]+)"; }) - .replace(splatParam, '([^?]*?)'); - return new RegExp('^' + route + '(?:\\?([\\s\\S]*))?$'); + .replace(splatParam, "([^?]*?)"); + return new RegExp("^" + route + "(?:\\?([\\s\\S]*))?$"); }, // Given a route, and a URL fragment that it matches, return the array of @@ -314,10 +314,10 @@ // falls back to polling. var History = function () { this.handlers = []; - _.bindAll(this, 'checkUrl'); + _.bindAll(this, "checkUrl"); // Ensure that `History` can be used outside of the browser. - if (typeof window !== 'undefined') { + if (typeof window !== "undefined") { this.location = window.location; this.history = window.history; } @@ -344,22 +344,22 @@ // Are we at the app root? atRoot: function () { - var path = this.location.pathname.replace(/[^\/]$/, '$&/'); + var path = this.location.pathname.replace(/[^\/]$/, "$&/"); return path === this.root && !this.getSearch(); }, // In IE6, the hash fragment and search params are incorrect if the // fragment contains `?`. getSearch: function () { - var match = this.location.href.replace(/#.*/, '').match(/\?.+/); - return match ? match[0] : ''; + var match = this.location.href.replace(/#.*/, "").match(/\?.+/); + return match ? match[0] : ""; }, // Gets the true hash value. Cannot use location.hash directly due to bug // in Firefox where location.hash will always be decoded. getHash: function (window) { var match = (window || this).location.href.match(/#(.*)$/); - return match ? match[1] : ''; + return match ? match[1] : ""; }, // Get the pathname and search params, without the root. @@ -367,7 +367,7 @@ var path = decodeURI(this.location.pathname + this.getSearch()); var root = this.root.slice(0, -1); if (!path.indexOf(root)) path = path.slice(root.length); - return path.charAt(0) === '/' ? path.slice(1) : path; + return path.charAt(0) === "/" ? path.slice(1) : path; }, // Get the cross-browser normalized URL fragment from the path or hash. @@ -379,27 +379,27 @@ fragment = this.getHash(); } } - return fragment.replace(routeStripper, ''); + return fragment.replace(routeStripper, ""); }, // Start the hash change handling, returning `true` if the current URL matches // an existing route, and `false` otherwise. start: function (options) { - if (History.started) throw new Error('BI.history has already been started'); + if (History.started) throw new Error("BI.history has already been started"); History.started = true; // Figure out the initial configuration. Do we need an iframe? // Is pushState desired ... is it available? - this.options = _.extend({root: '/'}, this.options, options); + this.options = _.extend({root: "/"}, this.options, options); this.root = this.options.root; this._wantsHashChange = this.options.hashChange !== false; - this._hasHashChange = 'onhashchange' in window; + this._hasHashChange = "onhashchange" in window; this._wantsPushState = !!this.options.pushState; this._hasPushState = !!(this.options.pushState && this.history && this.history.pushState); this.fragment = this.getFragment(); // Normalize root to always include a leading and trailing slash. - this.root = ('/' + this.root + '/').replace(rootStripper, '/'); + this.root = ("/" + this.root + "/").replace(rootStripper, "/"); // Transition from hashChange to pushState or vice versa if both are // requested. @@ -408,8 +408,8 @@ // If we've started off with a route from a `pushState`-enabled // browser, but we're currently in a browser that doesn't support it... if (!this._hasPushState && !this.atRoot()) { - var root = this.root.slice(0, -1) || '/'; - this.location.replace(root + '#' + this.getPath()); + var root = this.root.slice(0, -1) || "/"; + this.location.replace(root + "#" + this.getPath()); // Return immediately as browser will do redirect to new url return true; @@ -425,28 +425,28 @@ // support the `hashchange` event, HTML5 history, or the user wants // `hashChange` but not `pushState`. if (!this._hasHashChange && this._wantsHashChange && (!this._wantsPushState || !this._hasPushState)) { - var iframe = document.createElement('iframe'); - iframe.src = 'javascript:0'; - iframe.style.display = 'none'; + var iframe = document.createElement("iframe"); + iframe.src = "javascript:0"; + iframe.style.display = "none"; iframe.tabIndex = -1; var body = document.body; // Using `appendChild` will throw on IE < 9 if the document is not ready. this.iframe = body.insertBefore(iframe, body.firstChild).contentWindow; this.iframe.document.open().close(); - this.iframe.location.hash = '#' + this.fragment; + this.iframe.location.hash = "#" + this.fragment; } // Add a cross-platform `addEventListener` shim for older browsers. var addEventListener = window.addEventListener || function (eventName, listener) { - return attachEvent('on' + eventName, listener); + return attachEvent("on" + eventName, listener); }; // Depending on whether we're using pushState or hashes, and whether // 'onhashchange' is supported, determine how we check the URL state. if (this._hasPushState) { - addEventListener('popstate', this.checkUrl, false); + addEventListener("popstate", this.checkUrl, false); } else if (this._wantsHashChange && this._hasHashChange && !this.iframe) { - addEventListener('hashchange', this.checkUrl, false); + addEventListener("hashchange", this.checkUrl, false); } else if (this._wantsHashChange) { this._checkUrlInterval = setInterval(this.checkUrl, this.interval); } @@ -459,14 +459,14 @@ stop: function () { // Add a cross-platform `removeEventListener` shim for older browsers. var removeEventListener = window.removeEventListener || function (eventName, listener) { - return detachEvent('on' + eventName, listener); + return detachEvent("on" + eventName, listener); }; // Remove window listeners. if (this._hasPushState) { - removeEventListener('popstate', this.checkUrl, false); + removeEventListener("popstate", this.checkUrl, false); } else if (this._wantsHashChange && this._hasHashChange && !this.iframe) { - removeEventListener('hashchange', this.checkUrl, false); + removeEventListener("hashchange", this.checkUrl, false); } // Clean up the iframe if necessary. @@ -527,24 +527,24 @@ if (!options || options === true) options = {trigger: !!options}; // Normalize the fragment. - fragment = this.getFragment(fragment || ''); + fragment = this.getFragment(fragment || ""); // Don't include a trailing slash on the root. var root = this.root; - if (fragment === '' || fragment.charAt(0) === '?') { - root = root.slice(0, -1) || '/'; + if (fragment === "" || fragment.charAt(0) === "?") { + root = root.slice(0, -1) || "/"; } var url = root + fragment; // Strip the hash and decode for matching. - fragment = decodeURI(fragment.replace(pathStripper, '')); + fragment = decodeURI(fragment.replace(pathStripper, "")); if (this.fragment === fragment) return; this.fragment = fragment; // If pushState is available, we use it to set the fragment as a real URL. if (this._hasPushState) { - this.history[options.replace ? 'replaceState' : 'pushState']({}, document.title, url); + this.history[options.replace ? "replaceState" : "pushState"]({}, document.title, url); // If hash changes haven't been explicitly disabled, update the hash // fragment to store history. @@ -570,11 +570,11 @@ // a new one to the browser history. _updateHash: function (location, fragment, replace) { if (replace) { - var href = location.href.replace(/(javascript:|#).*$/, ''); - location.replace(href + '#' + fragment); + var href = location.href.replace(/(javascript:|#).*$/, ""); + location.replace(href + "#" + fragment); } else { // Some browsers require that `hash` contains a leading #. - location.hash = '#' + fragment; + location.hash = "#" + fragment; } } diff --git a/src/third/jquery.mousewheel.js b/src/third/jquery.mousewheel.js index 597366353..517085768 100644 --- a/src/third/jquery.mousewheel.js +++ b/src/third/jquery.mousewheel.js @@ -1,4 +1,4 @@ -/*! +/* ! * jQuery Mousewheel 3.1.13 * * Copyright jQuery Foundation and other contributors @@ -7,10 +7,10 @@ */ (function (factory) { - if ( typeof define === 'function' && define.amd ) { + if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. - define(['../core/jquery'], factory); - } else if (typeof exports === 'object') { + define(["../core/jquery"], factory); + } else if (typeof exports === "object") { // Node/CommonJS style for Browserify module.exports = factory; } else { @@ -19,9 +19,9 @@ } }(function ($) { - var toFix = ['wheel', 'mousewheel', 'DOMMouseScroll', 'MozMousePixelScroll'], - toBind = ( 'onwheel' in document || document.documentMode >= 9 ) ? - ['wheel'] : ['mousewheel', 'DomMouseScroll', 'MozMousePixelScroll'], + var toFix = ["wheel", "mousewheel", "DOMMouseScroll", "MozMousePixelScroll"], + toBind = ( "onwheel" in document || document.documentMode >= 9 ) ? + ["wheel"] : ["mousewheel", "DomMouseScroll", "MozMousePixelScroll"], slice = Array.prototype.slice, nullLowestDeltaTimeout, lowestDelta; @@ -32,9 +32,9 @@ } var special = $.event.special.mousewheel = { - version: '3.1.12', + version: "3.1.12", - setup: function() { + setup: function () { if ( this.addEventListener ) { for ( var i = toBind.length; i; ) { this.addEventListener( toBind[--i], handler, false ); @@ -44,7 +44,7 @@ } }, - teardown: function() { + teardown: function () { if ( this.removeEventListener ) { for ( var i = toBind.length; i; ) { this.removeEventListener( toBind[--i], handler, false ); @@ -61,17 +61,17 @@ }; $.fn.extend({ - mousewheel: function(fn) { - return fn ? this.bind('mousewheel', fn) : this.trigger('mousewheel'); + mousewheel: function (fn) { + return fn ? this.bind("mousewheel", fn) : this.trigger("mousewheel"); }, - unmousewheel: function(fn) { - return this.unbind('mousewheel', fn); + unmousewheel: function (fn) { + return this.unbind("mousewheel", fn); } }); - function handler(event) { + function handler (event) { var orgEvent = event || window.event, args = slice.call(arguments, 1), delta = 0, @@ -81,16 +81,16 @@ offsetX = 0, offsetY = 0; event = $.event.fix(orgEvent); - event.type = 'mousewheel'; + event.type = "mousewheel"; // Old school scrollwheel delta - if ( 'detail' in orgEvent ) { deltaY = orgEvent.detail * -1; } - if ( 'wheelDelta' in orgEvent ) { deltaY = orgEvent.wheelDelta; } - if ( 'wheelDeltaY' in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } - if ( 'wheelDeltaX' in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } + if ( "detail" in orgEvent ) { deltaY = orgEvent.detail * -1; } + if ( "wheelDelta" in orgEvent ) { deltaY = orgEvent.wheelDelta; } + if ( "wheelDeltaY" in orgEvent ) { deltaY = orgEvent.wheelDeltaY; } + if ( "wheelDeltaX" in orgEvent ) { deltaX = orgEvent.wheelDeltaX * -1; } // Firefox < 17 horizontal scrolling related to DOMMouseScroll event - if ( 'axis' in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { + if ( "axis" in orgEvent && orgEvent.axis === orgEvent.HORIZONTAL_AXIS ) { deltaX = deltaY * -1; deltaY = 0; } @@ -99,11 +99,11 @@ delta = deltaY === 0 ? deltaX : deltaY; // New school wheel delta (wheel event) - if ( 'deltaY' in orgEvent ) { + if ( "deltaY" in orgEvent ) { deltaY = orgEvent.deltaY * -1; delta = deltaY; } - if ( 'deltaX' in orgEvent ) { + if ( "deltaX" in orgEvent ) { deltaX = orgEvent.deltaX; if ( deltaY === 0 ) { delta = deltaX * -1; } } @@ -149,9 +149,9 @@ } // Get a whole, normalized value for the deltas - delta = Math[ delta >= 1 ? 'floor' : 'ceil' ](delta / lowestDelta); - deltaX = Math[ deltaX >= 1 ? 'floor' : 'ceil' ](deltaX / lowestDelta); - deltaY = Math[ deltaY >= 1 ? 'floor' : 'ceil' ](deltaY / lowestDelta); + delta = Math[ delta >= 1 ? "floor" : "ceil" ](delta / lowestDelta); + deltaX = Math[ deltaX >= 1 ? "floor" : "ceil" ](deltaX / lowestDelta); + deltaY = Math[ deltaY >= 1 ? "floor" : "ceil" ](deltaY / lowestDelta); // Normalise offsetX and offsetY properties if ( special.settings.normalizeOffset && this.getBoundingClientRect ) { @@ -184,11 +184,11 @@ return ($.event.dispatch || $.event.handle).apply(this, args); } - function nullLowestDelta() { + function nullLowestDelta () { lowestDelta = null; } - function shouldAdjustOldDeltas(orgEvent, absDelta) { + function shouldAdjustOldDeltas (orgEvent, absDelta) { // If this is an older event and the delta is divisable by 120, // then we are assuming that the browser is treating this as an // older mouse wheel event and that we should divide the deltas @@ -196,7 +196,7 @@ // Side note, this actually impacts the reported scroll distance // in older browsers and can cause scrolling to be slower than native. // Turn this off by setting $.event.special.mousewheel.settings.adjustOldDeltas to false. - return special.settings.adjustOldDeltas && orgEvent.type === 'mousewheel' && absDelta % 120 === 0; + return special.settings.adjustOldDeltas && orgEvent.type === "mousewheel" && absDelta % 120 === 0; } })); \ No newline at end of file diff --git a/src/widget/adaptivearrangement/adaptivearrangement.js b/src/widget/adaptivearrangement/adaptivearrangement.js index 8a5b7fec4..53a18f002 100644 --- a/src/widget/adaptivearrangement/adaptivearrangement.js +++ b/src/widget/adaptivearrangement/adaptivearrangement.js @@ -70,7 +70,7 @@ BI.AdaptiveArrangement = BI.inherit(BI.Widget, { var self = this, o = this.options; item.element.css("zIndex", ++this.zIndex); item.element.mousedown(function () { - self._setSelect(item) + self._setSelect(item); }); }, @@ -296,4 +296,4 @@ BI.AdaptiveArrangement.EVENT_ELEMENT_RESIZE = "AdaptiveArrangement.EVENT_ELEMENT BI.AdaptiveArrangement.EVENT_ELEMENT_STOP_RESIZE = "AdaptiveArrangement.EVENT_ELEMENT_STOP_RESIZE"; BI.AdaptiveArrangement.EVENT_RESIZE = "AdaptiveArrangement.EVENT_RESIZE"; BI.AdaptiveArrangement.EVENT_SCROLL = "AdaptiveArrangement.EVENT_SCROLL"; -BI.shortcut('bi.adaptive_arrangement', BI.AdaptiveArrangement); \ No newline at end of file +BI.shortcut("bi.adaptive_arrangement", BI.AdaptiveArrangement); \ No newline at end of file diff --git a/src/widget/arrangement/arrangement.block.js b/src/widget/arrangement/arrangement.block.js index e28d7324b..6a234771d 100644 --- a/src/widget/arrangement/arrangement.block.js +++ b/src/widget/arrangement/arrangement.block.js @@ -13,4 +13,4 @@ BI.ArrangementBlock = BI.inherit(BI.Widget, { }); } }); -BI.shortcut('bi.arrangement_block', BI.ArrangementBlock); \ No newline at end of file +BI.shortcut("bi.arrangement_block", BI.ArrangementBlock); \ No newline at end of file diff --git a/src/widget/arrangement/arrangement.droppable.js b/src/widget/arrangement/arrangement.droppable.js index 13acb6f4e..84f9b4368 100644 --- a/src/widget/arrangement/arrangement.droppable.js +++ b/src/widget/arrangement/arrangement.droppable.js @@ -13,4 +13,4 @@ BI.ArrangementDroppable = BI.inherit(BI.Widget, { }); } }); -BI.shortcut('bi.arrangement_droppable', BI.ArrangementDroppable); \ No newline at end of file +BI.shortcut("bi.arrangement_droppable", BI.ArrangementDroppable); \ No newline at end of file diff --git a/src/widget/arrangement/arrangement.js b/src/widget/arrangement/arrangement.js index fc7d71d2f..4c9738bd8 100644 --- a/src/widget/arrangement/arrangement.js +++ b/src/widget/arrangement/arrangement.js @@ -62,7 +62,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { } }, - ////初始化操作//// + // //初始化操作//// _calculateRegions: function (items) { var self = this, o = this.options; this.regions = {}; @@ -92,7 +92,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return num1 >= num2 || this._isEqual(num1, num2); }, - //获取占有的最大Region + // 获取占有的最大Region _getRegionOccupied: function (regions) { var self = this, o = this.options; if (BI.size(regions || this.regions) <= 0) { @@ -101,7 +101,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: 0, width: 0, height: 0 - } + }; } var minLeft = BI.MAX, maxLeft = BI.MIN, minTop = BI.MAX, maxTop = BI.MIN; BI.each(regions || this.regions, function (id, region) { @@ -115,10 +115,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: minTop, width: maxLeft - minLeft, height: maxTop - minTop - } + }; }, - //两个区域的交叉面积 + // 两个区域的交叉面积 _getCrossArea: function (region1, region2) { if (region1.left <= region2.left) { if (region1.top <= region2.top) { @@ -156,7 +156,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return 0; }, - //是否有覆盖的组件 + // 是否有覆盖的组件 _isRegionOverlay: function (regions) { var reg = []; BI.each(regions || this.regions, function (id, region) { @@ -184,7 +184,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return false; }, - //布局是否是优良的 + // 布局是否是优良的 _isArrangeFine: function (regions) { switch (this.options.layoutType) { case BI.Arrangement.LAYOUT_TYPE.FREE: @@ -238,24 +238,24 @@ BI.Arrangement = BI.inherit(BI.Widget, { return clone; }, - //测试合法性 + // 测试合法性 _test: function (regions) { var self = this; return !BI.any(regions || this.regions, function (i, region) { if (BI.isNaN(region.width) || BI.isNaN(region.height) || region.width <= 21 || region.height <= 21) { return true; } - }) + }); }, _getScrollOffset: function () { return { left: this.container.element[0].scrollLeft, top: this.container.element[0].scrollTop - } + }; }, - ////操作//// + // //操作//// _createOneRegion: function (item) { var el = BI.createWidget(item.el); el.setVisible(true); @@ -266,7 +266,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { width: item.width, height: item.height, el: el - } + }; }, _applyRegion: function (regions) { @@ -346,10 +346,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { top: size.top, width: size.width, height: size.height - }) + }); }, - //Grid + // Grid _getOneWidthPortion: function () { return this.getClientWidth() / BI.Arrangement.PORTION; }, @@ -384,7 +384,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { y: topPortion, w: widthPortion, h: heightPortion - } + }; }, _getBlockPositionAndSize: function (position) { @@ -404,7 +404,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { BI.each(regions || this.regions, function (id, region) { result.push(BI.extend(self._getGridPositionAndSize(region), { i: region.id - })) + })); }); return result; }, @@ -457,10 +457,10 @@ BI.Arrangement = BI.inherit(BI.Widget, { } var movingUp = y && l.y > y; - if (typeof x === 'number') { + if (typeof x === "number") { l.x = x; } - if (typeof y === 'number') { + if (typeof y === "number") { l.y = y; } l.moved = true; @@ -490,7 +490,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return layout; - function getAllCollisions(layout, layoutItem) { + function getAllCollisions (layout, layoutItem) { return BI.filter(layout, function (i, l) { return self._collides(l, layoutItem); }); @@ -534,14 +534,14 @@ BI.Arrangement = BI.inherit(BI.Widget, { }, _moveElementAwayFromCollision: function (layout, collidesWith, - itemToMove, isUserAction) { + itemToMove, isUserAction) { if (isUserAction) { var fakeItem = { x: itemToMove.x, y: itemToMove.y, w: itemToMove.w, h: itemToMove.h, - i: '-1' + i: "-1" }; fakeItem.y = Math.max(collidesWith.y - itemToMove.h, 0); if (!this._getFirstCollision(layout, fakeItem)) { @@ -587,14 +587,14 @@ BI.Arrangement = BI.inherit(BI.Widget, { return out; - function getStatics(layout) { + function getStatics (layout) { return BI.filter(layout, function (i, l) { return l._static; }); } }, - ////公有方法//// + // //公有方法//// getRegionByName: function (name) { var obj = {}; obj[name] = this.regions[name]; @@ -633,7 +633,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { this.block.setVisible(false); }, - ////公有操作//// + // //公有操作//// setLayoutType: function (type) { var self = this, o = this.options; if (type !== o.layoutType) { @@ -658,7 +658,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { return { x: BI.parseFloat(BI.contentFormat((occupied.left + occupied.width) / width, "#.##;-#.##")), y: BI.parseFloat(BI.contentFormat((occupied.top + occupied.height) / height, "#.##;-#.##")) - } + }; }, addRegion: function (region, position) { @@ -877,7 +877,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { })); return function () { self.arrangement.setVisible(false); - } + }; }, scrollTo: function (scroll) { @@ -896,13 +896,13 @@ BI.Arrangement = BI.inherit(BI.Widget, { if (this._isArrangeFine()) { var width = this.getClientWidth(); var xRatio = (ratio.x || 1) * width / (occupied.left + occupied.width); - //var yRatio = ratio.y * height / (occupied.top + occupied.height); + // var yRatio = ratio.y * height / (occupied.top + occupied.height); var regions = this._cloneRegion(); BI.each(regions, function (i, region) { region.left = region.left * xRatio; - //region.top = region.top * yRatio; + // region.top = region.top * yRatio; region.width = region.width * xRatio; - //region.height = region.height * yRatio; + // region.height = region.height * yRatio; }); if (this._test(regions)) { this._modifyRegion(regions); @@ -924,7 +924,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { region.width = region.width * xRatio; region.top = region.top * yRatio; region.height = region.height * yRatio; - //做一下自适应布局到网格布局的兼容 + // 做一下自适应布局到网格布局的兼容 var perWidth = self._getOneWidthPortion(); var widthPortion = Math.round(region.width / perWidth); var leftPortion = Math.round(region.left / perWidth); @@ -999,7 +999,7 @@ BI.Arrangement = BI.inherit(BI.Widget, { } store[row][col] = region; }); - //非4的倍数 + // 非4的倍数 // if (count % 4 !== 0) { // var lasts = store[rows - 1]; // var perWidth = width / (count % 4); @@ -1055,4 +1055,4 @@ BI.extend(BI.Arrangement, { FREE: 1 } }); -BI.shortcut('bi.arrangement', BI.Arrangement); \ No newline at end of file +BI.shortcut("bi.arrangement", BI.Arrangement); \ No newline at end of file diff --git a/src/widget/date/calendar/combo.month.date.js b/src/widget/date/calendar/combo.month.date.js index 59ed76811..07466cba9 100644 --- a/src/widget/date/calendar/combo.month.date.js +++ b/src/widget/date/calendar/combo.month.date.js @@ -6,13 +6,13 @@ * @extends BI.Trigger */ BI.MonthDateCombo = BI.inherit(BI.Trigger, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.MonthDateCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-month-combo", height: 25 }); }, - _init: function() { + _init: function () { BI.MonthDateCombo.superclass._init.apply(this, arguments); var self = this, o = this.options; @@ -24,9 +24,9 @@ BI.MonthDateCombo = BI.inherit(BI.Trigger, { type: "bi.month_popup" }); - this.popup.on(BI.YearPopup.EVENT_CHANGE, function(){ + this.popup.on(BI.YearPopup.EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); - }) + }); this.combo = BI.createWidget({ @@ -41,21 +41,21 @@ BI.MonthDateCombo = BI.inherit(BI.Trigger, { stopPropagation: false, el: this.popup } - }) - this.combo.on(BI.Combo.EVENT_CHANGE, function(){ + }); + this.combo.on(BI.Combo.EVENT_CHANGE, function () { self.combo.hideView(); self.fireEvent(BI.MonthDateCombo.EVENT_CHANGE); }); }, - setValue: function(v){ + setValue: function (v) { this.trigger.setValue(v + 1); this.popup.setValue(v); }, - getValue: function(){ + getValue: function () { return this.popup.getValue(); } }); BI.MonthDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.month_date_combo', BI.MonthDateCombo); \ No newline at end of file +BI.shortcut("bi.month_date_combo", BI.MonthDateCombo); \ No newline at end of file diff --git a/src/widget/date/calendar/combo.year.date.js b/src/widget/date/calendar/combo.year.date.js index ff0e16a8c..e75df254f 100644 --- a/src/widget/date/calendar/combo.year.date.js +++ b/src/widget/date/calendar/combo.year.date.js @@ -6,15 +6,15 @@ * @extends BI.Trigger */ BI.YearDateCombo = BI.inherit(BI.Trigger, { - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.YearDateCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-combo", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 25 }); }, - _init: function() { + _init: function () { BI.YearDateCombo.superclass._init.apply(this, arguments); var self = this, o = this.options; @@ -28,11 +28,11 @@ BI.YearDateCombo = BI.inherit(BI.Trigger, { max: o.max }); - this.popup.on(BI.YearPopup.EVENT_CHANGE, function(){ + this.popup.on(BI.YearPopup.EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); self.combo.hideView(); self.fireEvent(BI.YearDateCombo.EVENT_CHANGE); - }) + }); this.combo = BI.createWidget({ @@ -47,20 +47,20 @@ BI.YearDateCombo = BI.inherit(BI.Trigger, { stopPropagation: false, el: this.popup } - }) - this.combo.on(BI.Combo.EVENT_CHANGE, function(){ + }); + this.combo.on(BI.Combo.EVENT_CHANGE, function () { self.fireEvent(BI.YearDateCombo.EVENT_CHANGE); - }) + }); }, - setValue: function(v){ + setValue: function (v) { this.trigger.setValue(v); this.popup.setValue(v); }, - getValue: function(){ + getValue: function () { return this.popup.getValue(); } }); BI.YearDateCombo.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.year_date_combo', BI.YearDateCombo); \ No newline at end of file +BI.shortcut("bi.year_date_combo", BI.YearDateCombo); \ No newline at end of file diff --git a/src/widget/date/calendar/picker.date.js b/src/widget/date/calendar/picker.date.js index 66545e4b5..18d42d901 100644 --- a/src/widget/date/calendar/picker.date.js +++ b/src/widget/date/calendar/picker.date.js @@ -9,9 +9,9 @@ BI.DatePicker = BI.inherit(BI.Widget, { return BI.extend(conf, { baseCls: "bi-date-picker bi-background", height: 25, - min: '1900-01-01', //最小日期 - max: '2099-12-31' //最大日期 - }) + min: "1900-01-01", // 最小日期 + max: "2099-12-31" // 最大日期 + }); }, _init: function () { @@ -30,12 +30,12 @@ BI.DatePicker = BI.inherit(BI.Widget, { self.setValue({ year: self.year.getValue() - 1, month: 11 - }) + }); } else { self.setValue({ year: self.year.getValue(), month: self.month.getValue() - 1 - }) + }); } self.fireEvent(BI.DatePicker.EVENT_CHANGE); self._checkLeftValid(); @@ -54,12 +54,12 @@ BI.DatePicker = BI.inherit(BI.Widget, { self.setValue({ year: self.year.getValue() + 1, month: 0 - }) + }); } else { self.setValue({ year: self.year.getValue(), month: self.month.getValue() + 1 - }) + }); } self.fireEvent(BI.DatePicker.EVENT_CHANGE); self._checkLeftValid(); @@ -77,7 +77,7 @@ BI.DatePicker = BI.inherit(BI.Widget, { month: self.month.getValue() }); self.fireEvent(BI.DatePicker.EVENT_CHANGE); - }) + }); this.month = BI.createWidget({ type: "bi.month_date_combo" }); @@ -106,11 +106,11 @@ BI.DatePicker = BI.inherit(BI.Widget, { el: this.right, width: 25 }] - }) + }); this.setValue({ year: this._year, month: this._month - }) + }); }, _checkLeftValid: function () { @@ -142,8 +142,8 @@ BI.DatePicker = BI.inherit(BI.Widget, { return { year: this.year.getValue(), month: this.month.getValue() - } + }; } }); -BI.DatePicker.EVENT_CHANGE = "EVENT_CHANGE" +BI.DatePicker.EVENT_CHANGE = "EVENT_CHANGE"; BI.shortcut("bi.date_picker", BI.DatePicker); \ No newline at end of file diff --git a/src/widget/date/calendar/popup.calendar.date.js b/src/widget/date/calendar/popup.calendar.date.js index fb7ac0854..99140a2ae 100644 --- a/src/widget/date/calendar/popup.calendar.date.js +++ b/src/widget/date/calendar/popup.calendar.date.js @@ -8,10 +8,10 @@ BI.DateCalendarPopup = BI.inherit(BI.Widget, { var conf = BI.DateCalendarPopup.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: "bi-date-calendar-popup", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 selectedTime: null - }) + }); }, _createNav: function (v) { @@ -27,7 +27,7 @@ BI.DateCalendarPopup = BI.inherit(BI.Widget, { month: date.month, day: this.selectedTime.day }); - return calendar + return calendar; }, _init: function () { diff --git a/src/widget/date/calendar/trigger.triangle.date.js b/src/widget/date/calendar/trigger.triangle.date.js index 76540d4c2..898199661 100644 --- a/src/widget/date/calendar/trigger.triangle.date.js +++ b/src/widget/date/calendar/trigger.triangle.date.js @@ -12,13 +12,13 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { iconHeight: 13 }, - _defaultConfig: function() { + _defaultConfig: function () { return BI.extend( BI.DateTriangleTrigger.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-date-triangle-trigger pull-down-ha-font cursor-pointer", height: 25 }); }, - _init: function() { + _init: function () { BI.DateTriangleTrigger.superclass._init.apply(this, arguments); var o = this.options, c = this._const; this.text = BI.createWidget({ @@ -28,7 +28,7 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { text: o.text, value: o.value, height: c.height - }) + }); this.icon = BI.createWidget({ type: "bi.icon", width: c.iconWidth, @@ -44,27 +44,27 @@ BI.DateTriangleTrigger = BI.inherit(BI.Trigger, { height: c.height, items: [this.text, this.icon] }] - }) + }); }, - setValue: function(v){ + setValue: function (v) { this.text.setValue(v); }, - getValue: function(){ + getValue: function () { return this.text.getValue(); }, - setText: function(v){ + setText: function (v) { this.text.setText(v); }, - getText: function(){ + getText: function () { return this.item.getText(); }, - getKey: function(){ + getKey: function () { } }); -BI.shortcut('bi.date_triangle_trigger', BI.DateTriangleTrigger); \ No newline at end of file +BI.shortcut("bi.date_triangle_trigger", BI.DateTriangleTrigger); \ No newline at end of file diff --git a/src/widget/date/combo.date.js b/src/widget/date/combo.date.js index f14a8fcfa..49243a03c 100644 --- a/src/widget/date/combo.date.js +++ b/src/widget/date/combo.date.js @@ -45,7 +45,7 @@ BI.DateCombo = BI.inherit(BI.Widget, { el: this.popup, stopPropagation: false } - }) + }); }, setValue: function (v) { @@ -57,4 +57,4 @@ BI.DateCombo = BI.inherit(BI.Widget, { return this.popup.getValue(); } }); -BI.shortcut('bi.date_combo', BI.DateCombo); \ No newline at end of file +BI.shortcut("bi.date_combo", BI.DateCombo); \ No newline at end of file diff --git a/src/widget/date/trigger.date.js b/src/widget/date/trigger.date.js index 413b2a72a..f9f2bd2d9 100644 --- a/src/widget/date/trigger.date.js +++ b/src/widget/date/trigger.date.js @@ -9,8 +9,8 @@ BI.DateTrigger = BI.inherit(BI.Trigger, { _defaultConfig: function () { return BI.extend(BI.DateTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-date-trigger", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24 }); }, @@ -24,10 +24,10 @@ BI.DateTrigger = BI.inherit(BI.Trigger, { var date = v.match(/\d+/g); self._autoAppend(v, date); return self._dateCheck(v) && Date.checkLegal(v) && self._checkVoid({ - year: date[0], - month: date[1], - day: date[2] - }); + year: date[0], + month: date[1], + day: date[2] + }); }, quitChecker: function () { return false; @@ -44,7 +44,7 @@ BI.DateTrigger = BI.inherit(BI.Trigger, { } }); this.editor.on(BI.SignEditor.EVENT_KEY_DOWN, function () { - self.fireEvent(BI.DateTrigger.EVENT_KEY_DOWN) + self.fireEvent(BI.DateTrigger.EVENT_KEY_DOWN); }); this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { self.fireEvent(BI.DateTrigger.EVENT_FOCUS); @@ -68,7 +68,7 @@ BI.DateTrigger = BI.inherit(BI.Trigger, { var date = value.split("-"); self.store_value = { type: BI.DateTrigger.MULTI_DATE_CALENDAR, - value:{ + value: { year: date[0] | 0, month: date[1] - 1, day: date[2] | 0 @@ -97,7 +97,7 @@ BI.DateTrigger = BI.inherit(BI.Trigger, { }, { el: this.editor }] - }) + }); }, _dateCheck: function (date) { return Date.parseDateTime(date, "%Y-%x-%d").print("%Y-%x-%d") == date || Date.parseDateTime(date, "%Y-%X-%d").print("%Y-%X-%d") == date || Date.parseDateTime(date, "%Y-%x-%e").print("%Y-%x-%e") == date || Date.parseDateTime(date, "%Y-%X-%e").print("%Y-%X-%e") == date; @@ -136,7 +136,7 @@ BI.DateTrigger = BI.inherit(BI.Trigger, { this.store_value = v; if (BI.isNotNull(v)) { type = v.type || BI.DateTrigger.MULTI_DATE_CALENDAR; value = v.value; - if(BI.isNull(value)){ + if(BI.isNull(value)) { value = v; } } diff --git a/src/widget/datepane/datepane.js b/src/widget/datepane/datepane.js index 5cd776432..c936d9dd1 100644 --- a/src/widget/datepane/datepane.js +++ b/src/widget/datepane/datepane.js @@ -6,10 +6,10 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { var conf = BI.DatePaneWidget.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { baseCls: "bi-date-pane", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 selectedTime: null - }) + }); }, _init: function () { BI.DatePaneWidget.superclass._init.apply(this, arguments); @@ -20,9 +20,9 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { this._month = this.today.getMonth(); this.selectedTime = o.selectedTime || { - year: this._year, - month: this._month - }; + year: this._year, + month: this._month + }; this.datePicker = BI.createWidget({ type: "bi.date_picker", @@ -83,7 +83,7 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { return { year: today.getFullYear(), month: today.getMonth() - } + }; }, _setCalenderValue: function (date) { @@ -105,7 +105,7 @@ BI.DatePaneWidget = BI.inherit(BI.Widget, { this.calendar.empty(); this._setCalenderValue(this._getNewCurrentDate()); } else { - this._setCalenderValue(timeOb) + this._setCalenderValue(timeOb); } }, diff --git a/src/widget/datetime/datetime.combo.js b/src/widget/datetime/datetime.combo.js index 0fdde56c1..b2d272255 100644 --- a/src/widget/datetime/datetime.combo.js +++ b/src/widget/datetime/datetime.combo.js @@ -12,7 +12,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { }, _defaultConfig: function () { return BI.extend(BI.DateTimeCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-date-time-combo bi-border', + baseCls: "bi-date-time-combo bi-border", width: 200, height: 24 }); @@ -30,7 +30,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { second: date.getSeconds() }; this.trigger = BI.createWidget({ - type: 'bi.date_time_trigger', + type: "bi.date_time_trigger", min: this.constants.DATE_MIN_VALUE, max: this.constants.DATE_MAX_VALUE }); @@ -58,7 +58,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { self.fireEvent(BI.DateTimeCombo.EVENT_CHANGE); }); this.combo = BI.createWidget({ - type: 'bi.combo', + type: "bi.combo", toggle: false, isNeedAdjustHeight: false, isNeedAdjustWidth: false, @@ -107,7 +107,7 @@ BI.DateTimeCombo = BI.inherit(BI.Single, { left: 0 }] }] - }) + }); }, setValue: function (v) { @@ -128,4 +128,4 @@ BI.DateTimeCombo.EVENT_CANCEL = "EVENT_CANCEL"; BI.DateTimeCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.DateTimeCombo.EVENT_CHANGE = "EVENT_CHANGE"; BI.DateTimeCombo.EVENT_BEFORE_POPUPVIEW = "BI.DateTimeCombo.EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.date_time_combo', BI.DateTimeCombo); +BI.shortcut("bi.date_time_combo", BI.DateTimeCombo); diff --git a/src/widget/datetime/datetime.popup.js b/src/widget/datetime/datetime.popup.js index 7f60aeb57..11678623a 100644 --- a/src/widget/datetime/datetime.popup.js +++ b/src/widget/datetime/datetime.popup.js @@ -4,7 +4,7 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.DateTimePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-date-time-popup', + baseCls: "bi-date-time-popup", width: 268, height: 290 }); @@ -13,9 +13,9 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { BI.DateTimePopup.superclass._init.apply(this, arguments); var self = this, opts = this.options; this.cancelButton = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", forceCenter: true, - cls: 'multidate-popup-button bi-border-top bi-border-right', + cls: "multidate-popup-button bi-border-top bi-border-right", shadow: true, text: BI.i18nText("BI-Basic_Cancel") }); @@ -26,7 +26,7 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { this.okButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'multidate-popup-button bi-border-top', + cls: "multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_OK") }); @@ -167,10 +167,10 @@ BI.DateTimePopup = BI.inherit(BI.Widget, { hour: this.hour.getValue(), minute: this.minute.getValue(), second: this.second.getValue() - } + }; } }); BI.DateTimePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; BI.DateTimePopup.BUTTON_CANCEL_EVENT_CHANGE = "BUTTON_CANCEL_EVENT_CHANGE"; BI.DateTimePopup.CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE"; -BI.shortcut('bi.date_time_popup', BI.DateTimePopup); +BI.shortcut("bi.date_time_popup", BI.DateTimePopup); diff --git a/src/widget/datetime/datetime.select.js b/src/widget/datetime/datetime.select.js index 4972c35e1..4f1b77b69 100644 --- a/src/widget/datetime/datetime.select.js +++ b/src/widget/datetime/datetime.select.js @@ -7,7 +7,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { baseCls: "bi-date-time-select bi-border", max: 23, min: 0 - }) + }); }, _init: function () { @@ -18,11 +18,11 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { value: this._alertInEditorValue(o.min), allowBlank: false, errorText: BI.i18nText("BI-Please_Input_Natural_Number"), - validationChecker: function(v){ + validationChecker: function (v) { return BI.isNaturalNumber(v); } }); - this.editor.on(BI.TextEditor.EVENT_CONFIRM, function(){ + this.editor.on(BI.TextEditor.EVENT_CONFIRM, function () { self._finetuning(0); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -30,7 +30,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { type: "bi.icon_button", cls: "column-pre-page-h-font top-button bi-border-left bi-border-bottom" }); - this.topBtn.on(BI.IconButton.EVENT_CHANGE, function(){ + this.topBtn.on(BI.IconButton.EVENT_CHANGE, function () { self._finetuning(1); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -38,7 +38,7 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { type: "bi.icon_button", cls: "column-next-page-h-font bottom-button bi-border-left" }); - this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function(){ + this.bottomBtn.on(BI.IconButton.EVENT_CHANGE, function () { self._finetuning(-1); self.fireEvent(BI.DateTimeSelect.EVENT_CONFIRM); }); @@ -66,28 +66,28 @@ BI.DateTimeSelect = BI.inherit(BI.Widget, { }); }, - _alertOutEditorValue: function(v){ - if (v > this.options.max){ + _alertOutEditorValue: function (v) { + if (v > this.options.max) { v = this.options.min; } - if (v < this.options.min){ - v = this.options.max + if (v < this.options.min) { + v = this.options.max; } return BI.parseInt(v); }, - _alertInEditorValue: function(v){ - if (v > this.options.max){ + _alertInEditorValue: function (v) { + if (v > this.options.max) { v = this.options.min; } - if (v < this.options.min){ + if (v < this.options.min) { v = this.options.max; } v = v < 10 ? "0" + v : v; return v; }, - _finetuning: function(add){ + _finetuning: function (add) { var v = BI.parseInt(this._alertOutEditorValue(this.editor.getValue())); this.editor.setValue(this._alertInEditorValue(v + add)); }, diff --git a/src/widget/datetime/datetime.trigger.js b/src/widget/datetime/datetime.trigger.js index d64445cf6..c6561c0ca 100644 --- a/src/widget/datetime/datetime.trigger.js +++ b/src/widget/datetime/datetime.trigger.js @@ -9,8 +9,8 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { _defaultConfig: function () { return BI.extend(BI.DateTimeTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-date-time-trigger", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24, width: 200 }); @@ -35,7 +35,7 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { }, { el: this.text }] - }) + }); }, _printTime: function (v) { @@ -45,11 +45,11 @@ BI.DateTimeTrigger = BI.inherit(BI.Trigger, { setValue: function (v) { var self = this; var value = v, dateStr; - if(BI.isNull(value)){ + if(BI.isNull(value)) { value = Date.getDate(); dateStr = value.print("%Y-%X-%d %H:%M:%S"); } else { - var date = Date.getDate(value.year,value.month,value.day,value.hour,value.minute,value.second); + var date = Date.getDate(value.year, value.month, value.day, value.hour, value.minute, value.second); dateStr = date.print("%Y-%X-%d %H:%M:%S"); } diff --git a/src/widget/directionpathchooser/directionpathchooser.js b/src/widget/directionpathchooser/directionpathchooser.js index 64a1aa330..2ffbd1f32 100644 --- a/src/widget/directionpathchooser/directionpathchooser.js +++ b/src/widget/directionpathchooser/directionpathchooser.js @@ -28,7 +28,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { items: o.items }); this.pathChooser.on(BI.PathChooser.EVENT_CHANGE, function (start, index) { - //self._unselectAllArrows(); + // self._unselectAllArrows(); self._setValue(start, index); self.fireEvent(BI.DirectionPathChooser.EVENT_CHANGE); }); @@ -48,7 +48,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { }, _drawOneArrow: function (dot, direction) { - //0,1,2,3 上右下左 + // 0,1,2,3 上右下左 var lineColor = this._const.lineColor; var selectLineColor = this._const.selectLineColor; var svg = this.pathChooser.svg; @@ -146,17 +146,17 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { } } }); - }) + }); }); - function getXoffsetByRegionIndex(regionIndex, diregion) { + function getXoffsetByRegionIndex (regionIndex, diregion) { if (diregion === -1) { return 100 * (regionIndex + 1) - 20; } return 100 * regionIndex + 20; } - function getYByXoffset(dots, xoffset) { + function getYByXoffset (dots, xoffset) { var finded = BI.find(dots, function (i, dot) { if (i > 0) { if (dots[i - 1].x < xoffset && dots[i].x > xoffset) { @@ -216,7 +216,7 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { if (array.length > 0) { result.push(array); } - //画这n条路径 + // 画这n条路径 BI.each(result, function (idx, path) { var start = path[0]; var index = BI.findIndex(routes[start], function (idx, p) { @@ -240,4 +240,4 @@ BI.DirectionPathChooser = BI.inherit(BI.Widget, { } }); BI.DirectionPathChooser.EVENT_CHANGE = "DirectionPathChooser.EVENT_CHANGE"; -BI.shortcut('bi.direction_path_chooser', BI.DirectionPathChooser); \ No newline at end of file +BI.shortcut("bi.direction_path_chooser", BI.DirectionPathChooser); \ No newline at end of file diff --git a/src/widget/downlist/combo.downlist.js b/src/widget/downlist/combo.downlist.js index 6b27576e8..89728a808 100644 --- a/src/widget/downlist/combo.downlist.js +++ b/src/widget/downlist/combo.downlist.js @@ -13,7 +13,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { trigger: "click", container: null, el: {} - }) + }); }, _init: function () { @@ -38,7 +38,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { this.downlistcombo = BI.createWidget({ element: this, - type: 'bi.combo', + type: "bi.combo", trigger: o.trigger, isNeedAdjustWidth: false, container: o.container, @@ -78,7 +78,7 @@ BI.DownListCombo = BI.inherit(BI.Widget, { this.popupview.setValue(v); }, getValue: function () { - return this.popupview.getValue() + return this.popupview.getValue(); } }); BI.DownListCombo.EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/widget/downlist/group.downlist.js b/src/widget/downlist/group.downlist.js index 9aa122d14..592a94038 100644 --- a/src/widget/downlist/group.downlist.js +++ b/src/widget/downlist/group.downlist.js @@ -13,7 +13,7 @@ BI.DownListGroup = BI.inherit(BI.Widget, { el: {} } ] - }) + }); }, _init: function () { BI.DownListGroup.superclass._init.apply(this, arguments); @@ -23,7 +23,7 @@ BI.DownListGroup = BI.inherit(BI.Widget, { element: this, type: "bi.button_tree", items: o.items, - chooseType: 0,//0单选,1多选 + chooseType: 0, // 0单选,1多选 layouts: [{ type: "bi.vertical", hgap: 0, @@ -35,16 +35,16 @@ BI.DownListGroup = BI.inherit(BI.Widget, { if(type === BI.Events.CLICK) { self.fireEvent(BI.DownListGroup.EVENT_CHANGE, arguments); } - }) + }); }, - getValue:function(){ + getValue: function () { return this.downlistgroup.getValue(); }, - setValue:function(v){ + setValue: function (v) { this.downlistgroup.setValue(v); } -}) +}); BI.DownListGroup.EVENT_CHANGE = "EVENT_CHANGE"; BI.shortcut("bi.down_list_group", BI.DownListGroup); \ No newline at end of file diff --git a/src/widget/downlist/item.downlist.js b/src/widget/downlist/item.downlist.js index 5f8ffeaff..cd1619dc7 100644 --- a/src/widget/downlist/item.downlist.js +++ b/src/widget/downlist/item.downlist.js @@ -15,7 +15,7 @@ BI.DownListItem = BI.inherit(BI.Single, { textVgap: 0, textLgap: 0, textRgap: 0 - }) + }); }, _init: function () { BI.DownListItem.superclass._init.apply(this, arguments); diff --git a/src/widget/downlist/item.downlistgroup.js b/src/widget/downlist/item.downlistgroup.js index 8d55da9f4..8e788f7a5 100644 --- a/src/widget/downlist/item.downlistgroup.js +++ b/src/widget/downlist/item.downlistgroup.js @@ -9,7 +9,7 @@ BI.DownListGroupItem = BI.inherit(BI.BasicButton, { // invalid: true, iconCls1: "dot-e-font", iconCls2: "pull-right-e-font" - }) + }); }, _init: function () { BI.DownListGroupItem.superclass._init.apply(this, arguments); @@ -65,7 +65,7 @@ BI.DownListGroupItem = BI.inherit(BI.BasicButton, { } }, function () { if (self.isEnabled()) { - self.dishover() + self.dishover(); } }); }, @@ -105,10 +105,10 @@ BI.DownListGroupItem = BI.inherit(BI.BasicButton, { if (BI.contains(o.childValues, value)) { self.icon1.setSelected(true); return true; - } else { - self.icon1.setSelected(false); } - }) + self.icon1.setSelected(false); + + }); } }); BI.DownListGroupItem.EVENT_CHANGE = "EVENT_CHANGE"; diff --git a/src/widget/downlist/popup.downlist.js b/src/widget/downlist/popup.downlist.js index adba7a1d8..089352b70 100644 --- a/src/widget/downlist/popup.downlist.js +++ b/src/widget/downlist/popup.downlist.js @@ -19,7 +19,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { baseCls: "bi-down-list-popup", items: [], chooseType: BI.Selection.Multi - }) + }); }, _init: function () { BI.DownListPopup.superclass._init.apply(this, arguments); @@ -46,7 +46,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { var changedValue = value; if (BI.isNotNull(self.childValueMap[value])) { changedValue = self.childValueMap[value]; - self.fireEvent(BI.DownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, self.fatherValueMap[value]) + self.fireEvent(BI.DownListPopup.EVENT_SON_VALUE_CHANGE, changedValue, self.fatherValueMap[value]); } else { self.fireEvent(BI.DownListPopup.EVENT_CHANGE, changedValue, object); } @@ -122,7 +122,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { self.childValueMap[self._createChildValue(fatherValue, childValue)] = childValue; child.value = self._createChildValue(fatherValue, childValue); item.el.childValues.push(child.value); - }) + }); } else { item.type = "bi.down_list_item"; item.title = item.title || item.text; @@ -130,7 +130,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { item.isNeedAdjustWidth = false; item.logic = { dynamic: true - } + }; } var el_done = {}; el_done.el = item; @@ -139,7 +139,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { if (self._isGroup(item_done.items)) { BI.each(item_done.items, function (i, item) { self.singleValues.push(item.el.value); - }) + }); } result.push(item_done); @@ -173,7 +173,7 @@ BI.DownListPopup = BI.inherit(BI.Pane, { }, _createChildValue: function (fatherValue, childValue) { - return fatherValue + "_" + childValue + return fatherValue + "_" + childValue; }, populate: function (items) { @@ -195,14 +195,14 @@ BI.DownListPopup = BI.inherit(BI.Pane, { var self = this; var valueArray = []; BI.each(valueItem, function (i, item) { - var value; - if (BI.isNotNull(item.childValue)) { - value = self._createChildValue(item.value, item.childValue); - } else { - value = item.value; - } - valueArray.push(value); + var value; + if (BI.isNotNull(item.childValue)) { + value = self._createChildValue(item.value, item.childValue); + } else { + value = item.value; } + valueArray.push(value); + } ); this.popup.setValue(valueArray); }, diff --git a/src/widget/editor/editor.search.js b/src/widget/editor/editor.search.js index b7f2cbaf4..00247bf07 100644 --- a/src/widget/editor/editor.search.js +++ b/src/widget/editor/editor.search.js @@ -82,34 +82,34 @@ BI.SearchEditor = BI.inherit(BI.Widget, { self.fireEvent(BI.SearchEditor.EVENT_KEY_DOWN, v); }); this.editor.on(BI.Editor.EVENT_SPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_SPACE) + self.fireEvent(BI.SearchEditor.EVENT_SPACE); }); this.editor.on(BI.Editor.EVENT_BACKSPACE, function () { - self.fireEvent(BI.SearchEditor.EVENT_BACKSPACE) + self.fireEvent(BI.SearchEditor.EVENT_BACKSPACE); }); this.editor.on(BI.Editor.EVENT_VALID, function () { - self.fireEvent(BI.SearchEditor.EVENT_VALID) + self.fireEvent(BI.SearchEditor.EVENT_VALID); }); this.editor.on(BI.Editor.EVENT_ERROR, function () { - self.fireEvent(BI.SearchEditor.EVENT_ERROR) + self.fireEvent(BI.SearchEditor.EVENT_ERROR); }); this.editor.on(BI.Editor.EVENT_ENTER, function () { self.fireEvent(BI.SearchEditor.EVENT_ENTER); }); this.editor.on(BI.Editor.EVENT_RESTRICT, function () { - self.fireEvent(BI.SearchEditor.EVENT_RESTRICT) + self.fireEvent(BI.SearchEditor.EVENT_RESTRICT); }); this.editor.on(BI.Editor.EVENT_EMPTY, function () { self._checkClear(); - self.fireEvent(BI.SearchEditor.EVENT_EMPTY) + self.fireEvent(BI.SearchEditor.EVENT_EMPTY); }); this.editor.on(BI.Editor.EVENT_REMOVE, function () { - self.fireEvent(BI.SearchEditor.EVENT_REMOVE) + self.fireEvent(BI.SearchEditor.EVENT_REMOVE); }); this.editor.on(BI.Editor.EVENT_CONFIRM, function () { - self.fireEvent(BI.SearchEditor.EVENT_CONFIRM) + self.fireEvent(BI.SearchEditor.EVENT_CONFIRM); }); this.editor.on(BI.Editor.EVENT_START, function () { self.fireEvent(BI.SearchEditor.EVENT_START); diff --git a/src/widget/editor/editor.text.js b/src/widget/editor/editor.text.js index 47d1f949c..5a3289dda 100644 --- a/src/widget/editor/editor.text.js +++ b/src/widget/editor/editor.text.js @@ -20,7 +20,7 @@ BI.TextEditor = BI.inherit(BI.Widget, { watermark: "", errorText: "", height: 24 - }) + }); }, _init: function () { diff --git a/src/widget/filemanager/buttongroup.filemanager.js b/src/widget/filemanager/buttongroup.filemanager.js index 831dd1bda..9765f52d7 100644 --- a/src/widget/filemanager/buttongroup.filemanager.js +++ b/src/widget/filemanager/buttongroup.filemanager.js @@ -11,7 +11,7 @@ BI.FileManagerButtonGroup = BI.inherit(BI.Widget, { return BI.extend(BI.FileManagerButtonGroup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-button_group", items: [] - }) + }); }, _init: function () { diff --git a/src/widget/filemanager/filemanager.js b/src/widget/filemanager/filemanager.js index ae5d2ade5..6923e72cf 100644 --- a/src/widget/filemanager/filemanager.js +++ b/src/widget/filemanager/filemanager.js @@ -12,7 +12,7 @@ BI.FileManager = BI.inherit(BI.Widget, { baseCls: "bi-file-manager", el: {}, items: [] - }) + }); }, _init: function () { @@ -27,7 +27,7 @@ BI.FileManager = BI.inherit(BI.Widget, { items: BI.deepClone(items) }); this.nav.on(BI.FileManagerNav.EVENT_CHANGE, function (value, obj) { - if (value == "-1") {//根节点 + if (value == "-1") {// 根节点 self.populate({children: self.tree.toJSON()}); } else { var node = self.tree.search(obj.attr("id")); diff --git a/src/widget/filemanager/items/item.file.filemanager.js b/src/widget/filemanager/items/item.file.filemanager.js index 989dae523..ab7316800 100644 --- a/src/widget/filemanager/items/item.file.filemanager.js +++ b/src/widget/filemanager/items/item.file.filemanager.js @@ -11,7 +11,7 @@ BI.FileManagerFileItem = BI.inherit(BI.Single, { return BI.extend(BI.FileManagerFileItem.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-file-item bi-list-item bi-border-bottom", height: 30 - }) + }); }, _init: function () { @@ -49,10 +49,10 @@ BI.FileManagerFileItem = BI.inherit(BI.Single, { value: o.value } }] - }) + }); }, - getAllLeaves: function(){ + getAllLeaves: function () { return [this.options.value]; }, diff --git a/src/widget/filemanager/items/item.folder.filemanager.js b/src/widget/filemanager/items/item.folder.filemanager.js index c993f4edd..d5a4029ac 100644 --- a/src/widget/filemanager/items/item.folder.filemanager.js +++ b/src/widget/filemanager/items/item.folder.filemanager.js @@ -11,7 +11,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { return BI.extend(BI.FileManagerFolderItem.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-file-manager-folder-item bi-list-item bi-border-bottom", height: 30 - }) + }); }, _init: function () { @@ -60,7 +60,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { }, { el: this.button }] - }) + }); }, setAllSelected: function (v) { @@ -70,7 +70,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { setHalfSelected: function (v) { this.checked.setHalfSelected(v); - if(!v){ + if(!v) { this.selectValue = []; } }, @@ -104,7 +104,7 @@ BI.FileManagerFolderItem = BI.inherit(BI.Single, { var res = []; this.tree.traverse(function (node) { if (node.isLeaf()) { - res.push(node.get("data").value) + res.push(node.get("data").value); } }); return res; diff --git a/src/widget/filemanager/list.filemanager.js b/src/widget/filemanager/list.filemanager.js index 681c2b14d..c3fedf2a4 100644 --- a/src/widget/filemanager/list.filemanager.js +++ b/src/widget/filemanager/list.filemanager.js @@ -12,7 +12,7 @@ BI.FileManagerList = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-list", el: {}, items: [] - }) + }); }, _init: function () { diff --git a/src/widget/filemanager/nav/button/button.nav.filemanager.js b/src/widget/filemanager/nav/button/button.nav.filemanager.js index 09eaa7d1a..7c5dc1488 100644 --- a/src/widget/filemanager/nav/button/button.nav.filemanager.js +++ b/src/widget/filemanager/nav/button/button.nav.filemanager.js @@ -16,7 +16,7 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-nav-button", selected: false, height: 40 - }) + }); }, _init: function () { @@ -45,8 +45,8 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { height: o.height }); var path = svg.path("M0,0L15,20L0,40").attr({ - "stroke": c.select_color, - "fill": o.selected ? c.select_color : c.normal_color + stroke: c.select_color, + fill: o.selected ? c.select_color : c.normal_color }); this.button.on(BI.TextButton.EVENT_CHANGE, function () { if (this.isSelected()) { @@ -69,7 +69,7 @@ BI.FileManagerNavButton = BI.inherit(BI.Widget, { top: 0, bottom: 0 }] - }) + }); }, isSelected: function () { diff --git a/src/widget/filemanager/nav/nav.filemanager.js b/src/widget/filemanager/nav/nav.filemanager.js index 2c7a43f1e..28b36aaab 100644 --- a/src/widget/filemanager/nav/nav.filemanager.js +++ b/src/widget/filemanager/nav/nav.filemanager.js @@ -12,7 +12,7 @@ BI.FileManagerNav = BI.inherit(BI.Widget, { baseCls: "bi-file-manager-nav bi-border-left", height: 40, items: [] - }) + }); }, _init: function () { @@ -86,7 +86,7 @@ BI.FileManagerNav = BI.inherit(BI.Widget, { return ids; }, - refreshTreeData: function(items){ + refreshTreeData: function (items) { this.tree.initTree(BI.Tree.transformToTreeFormat(items)); this.tree.getRoot().set("data", { text: BI.i18nText("BI-Created_By_Me"), diff --git a/src/widget/interactivearrangement/interactivearrangement.js b/src/widget/interactivearrangement/interactivearrangement.js index 2e9a43504..cdb791aa3 100644 --- a/src/widget/interactivearrangement/interactivearrangement.js +++ b/src/widget/interactivearrangement/interactivearrangement.js @@ -90,7 +90,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { top: top, middle: middle, bottom: bottom - } + }; }, _getRegionClientPosition: function (name) { @@ -102,7 +102,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { width: region.width, height: region.height, id: region.id - } + }; }, _vAlign: function (position, regions) { @@ -228,14 +228,14 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { _drawOneTag: function (start, end) { var s = BI.createWidget({ type: "bi.icon_button", - //invisible: true, + // invisible: true, width: 13, height: 13, cls: "drag-tag-font interactive-arrangement-dragtag-icon" }); var e = BI.createWidget({ type: "bi.icon_button", - //invisible: true, + // invisible: true, width: 13, height: 13, cls: "drag-tag-font interactive-arrangement-dragtag-icon" @@ -243,7 +243,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { if (this._isEqual(start.left, end.left)) { var line = BI.createWidget({ type: "bi.layout", - //invisible: true, + // invisible: true, cls: "interactive-arrangement-dragtag-line", width: 1, height: Math.abs(start.top - end.top) @@ -251,7 +251,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { } else { var line = BI.createWidget({ type: "bi.layout", - //invisible: true, + // invisible: true, cls: "interactive-arrangement-dragtag-line", height: 1, width: Math.abs(start.left - end.left) @@ -347,7 +347,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { return position; }, - //position不动 变size + // position不动 变size getSize: function (name, position, size) { var regions = this.getAllRegions(); var me; @@ -487,7 +487,7 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { return function () { callback(); self.stopDraw(); - } + }; }, scrollInterval: function () { @@ -549,4 +549,4 @@ BI.InteractiveArrangement = BI.inherit(BI.Widget, { }); BI.InteractiveArrangement.EVENT_RESIZE = "InteractiveArrangement.EVENT_RESIZE"; BI.InteractiveArrangement.EVENT_SCROLL = "InteractiveArrangement.EVENT_SCROLL"; -BI.shortcut('bi.interactive_arrangement', BI.InteractiveArrangement); \ No newline at end of file +BI.shortcut("bi.interactive_arrangement", BI.InteractiveArrangement); \ No newline at end of file diff --git a/src/widget/intervalslider/intervalslider.js b/src/widget/intervalslider/intervalslider.js index 124423059..8425bb380 100644 --- a/src/widget/intervalslider/intervalslider.js +++ b/src/widget/intervalslider/intervalslider.js @@ -17,7 +17,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { baseCls: "bi-interval-slider bi-slider-track", digit: false, unit: "" - }) + }); }, _init: function () { @@ -67,7 +67,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var v = BI.parseFloat(this.getValue()); self.valueOne = v; var percent = self._getPercentByValue(v); - var significantPercent = BI.parseFloat(percent.toFixed(1));//分成1000份 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 分成1000份 self._setLabelOnePosition(significantPercent); self._setSliderOnePosition(significantPercent); self._setBlueTrack(); @@ -132,10 +132,10 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }, - this._createLabelWrapper(), - this._createSliderWrapper() + this._createLabelWrapper(), + this._createSliderWrapper() ] - }) + }); }, _rePosBySizeAfterMove: function (size, isLeft) { @@ -145,7 +145,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var v = this._getValueByPercent(significantPercent); v = this._assertValue(v); v = o.digit === false ? v : v.toFixed(o.digit); - if(isLeft){ + if(isLeft) { this._setLabelOnePosition(significantPercent); this._setSliderOnePosition(significantPercent); this.labelOne.setValue(v); @@ -191,7 +191,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { self.fireEvent(BI.IntervalSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -199,7 +199,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -230,7 +230,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { top: 0, left: 0, width: "100%" - } + }; }, _createSliderWrapper: function () { @@ -259,7 +259,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { top: 20, left: 0, width: "100%" - } + }; }, _createTrackWrapper: function () { @@ -289,18 +289,18 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { var o = this.options; var valid = false; - //像90.这样的既不属于整数又不属于小数,是不合法的值 + // 像90.这样的既不属于整数又不属于小数,是不合法的值 var dotText = (v + "").split(".")[1]; if (BI.isEmptyString(dotText)) { }else{ if (BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max)) { - if(o.digit === false){ + if(o.digit === false) { valid = true; }else{ dotText = dotText || ""; @@ -316,43 +316,43 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { var labelTwoLeft = this.labelTwo.element[0].offsetLeft; if (labelOneLeft <= labelTwoLeft) { if ((labelTwoLeft - labelOneLeft) < 90) { - this.labelTwo.element.css({"top": 40}); + this.labelTwo.element.css({top: 40}); } else { - this.labelTwo.element.css({"top": 0}); + this.labelTwo.element.css({top: 0}); } } else { if ((labelOneLeft - labelTwoLeft) < 90) { - this.labelTwo.element.css({"top": 40}); + this.labelTwo.element.css({top: 40}); } else { - this.labelTwo.element.css({"top": 0}); + this.labelTwo.element.css({top: 0}); } } }, _setLabelOnePosition: function (percent) { - this.labelOne.element.css({"left": percent + "%"}); + this.labelOne.element.css({left: percent + "%"}); this._checkOverlap(); }, _setLabelTwoPosition: function (percent) { - this.labelTwo.element.css({"left": percent + "%"}); + this.labelTwo.element.css({left: percent + "%"}); this._checkOverlap(); }, _setSliderOnePosition: function (percent) { - this.sliderOne.element.css({"left": percent + "%"}); + this.sliderOne.element.css({left: percent + "%"}); }, _setSliderTwoPosition: function (percent) { - this.sliderTwo.element.css({"left": percent + "%"}); + this.sliderTwo.element.css({left: percent + "%"}); }, _setBlueTrackLeft: function (percent) { - this.blueTrack.element.css({"left": percent + "%"}); + this.blueTrack.element.css({left: percent + "%"}); }, _setBlueTrackWidth: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setBlueTrack: function () { @@ -389,21 +389,21 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, - //其中取max-min后保留4为有效数字后的值的小数位数为最终value的精度 - _getValueByPercent: function (percent) {//return (((max-min)*percent)/100+min) + // 其中取max-min后保留4为有效数字后的值的小数位数为最终value的精度 + _getValueByPercent: function (percent) {// return (((max-min)*percent)/100+min) var sub = this.calculation.accurateSubtraction(this.max, this.min); var mul = this.calculation.accurateMultiplication(sub, percent); var div = this.calculation.accurateDivisionTenExponent(mul, 2); - if(this.precision < 0){ + if(this.precision < 0) { var value = BI.parseFloat(this.calculation.accurateAddition(div, this.min)); var reduceValue = Math.round(this.calculation.accurateDivisionTenExponent(value, -this.precision)); return this.calculation.accurateMultiplication(reduceValue, Math.pow(10, -this.precision)); - }else{ - return BI.parseFloat(this.calculation.accurateAddition(div, this.min).toFixed(this.precision)); } + return BI.parseFloat(this.calculation.accurateAddition(div, this.min).toFixed(this.precision)); + }, _getPercentByValue: function (v) { @@ -416,31 +416,31 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { }, _getPrecision: function () { - //计算每一份值的精度(最大值和最小值的差值保留4为有效数字后的精度) - //如果差值的整数位数大于4,toPrecision(4)得到的是科学计数法123456 => 1.235e+5 - //返回非负值: 保留的小数位数 - //返回负值: 保留的10^n精度中的n + // 计算每一份值的精度(最大值和最小值的差值保留4为有效数字后的精度) + // 如果差值的整数位数大于4,toPrecision(4)得到的是科学计数法123456 => 1.235e+5 + // 返回非负值: 保留的小数位数 + // 返回负值: 保留的10^n精度中的n var sub = this.calculation.accurateSubtraction(this.max, this.min); var pre = sub.toPrecision(4); - //科学计数法 + // 科学计数法 var eIndex = pre.indexOf("e"); var arr = []; - if(eIndex > -1){ + if(eIndex > -1) { arr = pre.split("e"); var decimalPartLength = BI.size(arr[0].split(".")[1]); var sciencePartLength = BI.parseInt(arr[1].substring(1)); return decimalPartLength - sciencePartLength; - }else{ - arr = pre.split("."); - return arr.length > 1 ? arr[1].length : 0; } + arr = pre.split("."); + return arr.length > 1 ? arr[1].length : 0; + }, _assertValue: function (value) { - if(value <= this.min){ - return this.min + if(value <= this.min) { + return this.min; } - if(value >= this.max){ + if(value >= this.max) { return this.max; } return value; @@ -448,10 +448,10 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { getValue: function () { if (this.valueOne <= this.valueTwo) { - return {min: this.valueOne, max: this.valueTwo} - } else { - return {min: this.valueTwo, max: this.valueOne} + return {min: this.valueOne, max: this.valueTwo}; } + return {min: this.valueTwo, max: this.valueOne}; + }, setMinAndMax: function (v) { @@ -514,7 +514,7 @@ BI.IntervalSlider = BI.inherit(BI.Widget, { } else { this.labelOne.setValue(this.min); this.labelTwo.setValue(this.max); - this._setAllPosition(0, 100) + this._setAllPosition(0, 100); } } } diff --git a/src/widget/intervalslider/model.accuratecalculation.js b/src/widget/intervalslider/model.accuratecalculation.js index 6d50ad5f3..aa430dad1 100644 --- a/src/widget/intervalslider/model.accuratecalculation.js +++ b/src/widget/intervalslider/model.accuratecalculation.js @@ -7,7 +7,7 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.AccurateCalculationModel.superclass._defaultConfig.apply(this, arguments), { baseCls: "" - }) + }); }, _init: function () { @@ -28,16 +28,16 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { } var magnitudeDiff = stringNumber1.numDecimalLength - stringNumber2.numDecimalLength; if (magnitudeDiff > 0) { - var needAddZero = stringNumber2 + var needAddZero = stringNumber2; } else { var needAddZero = stringNumber1; magnitudeDiff = (0 - magnitudeDiff); } for (var i = 0; i < magnitudeDiff; i++) { if (needAddZero.numDecimal === "0" && i === 0) { - continue + continue; } - needAddZero.numDecimal += "0" + needAddZero.numDecimal += "0"; } }, @@ -53,25 +53,25 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var numDecimalLength = numStrArray[1].length; } return { - "numInteger": numInteger, - "numDecimal": numDecimal, - "numDecimalLength": numDecimalLength - } + numInteger: numInteger, + numDecimal: numDecimal, + numDecimalLength: numDecimalLength + }; }, - _accurateSubtraction: function (num1, num2) {//num1-num2 && num1>num2 + _accurateSubtraction: function (num1, num2) {// num1-num2 && num1>num2 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) - BI.parseInt(stringNumber2.numInteger); - //小数部分 + // 小数部分 this._formatDecimal(stringNumber1, stringNumber2); var decimalMaxLength = getDecimalMaxLength(stringNumber1, stringNumber2); if (BI.parseInt(stringNumber1.numDecimal) >= BI.parseInt(stringNumber2.numDecimal)) { var decimalResultTemp = (BI.parseInt(stringNumber1.numDecimal) - BI.parseInt(stringNumber2.numDecimal)).toString(); var decimalResult = addZero(decimalResultTemp, decimalMaxLength); - } else {//否则借位 + } else {// 否则借位 integerResult--; var borrow = this._getMagnitude(decimalMaxLength); var decimalResultTemp = (borrow + BI.parseInt(stringNumber1.numDecimal) - BI.parseInt(stringNumber2.numDecimal)).toString(); @@ -80,62 +80,62 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var result = integerResult + "." + decimalResult; return BI.parseFloat(result); - function getDecimalMaxLength(num1, num2) { + function getDecimalMaxLength (num1, num2) { if (num1.numDecimal.length >= num2.numDecimal.length) { - return num1.numDecimal.length + return num1.numDecimal.length; } - return num2.numDecimal.length + return num2.numDecimal.length; } - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, - _accurateAddition: function (num1, num2) {//加法结合律 + _accurateAddition: function (num1, num2) {// 加法结合律 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) + BI.parseInt(stringNumber2.numInteger); - //小数部分 + // 小数部分 this._formatDecimal(stringNumber1, stringNumber2); var decimalResult = (BI.parseInt(stringNumber1.numDecimal) + BI.parseInt(stringNumber2.numDecimal)).toString(); if (decimalResult !== "0") { if (decimalResult.length <= stringNumber1.numDecimal.length) { - decimalResult = addZero(decimalResult, stringNumber1.numDecimal.length) + decimalResult = addZero(decimalResult, stringNumber1.numDecimal.length); } else { - integerResult++;//进一 + integerResult++;// 进一 decimalResult = decimalResult.slice(1); } } var result = integerResult + "." + decimalResult; return BI.parseFloat(result); - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, - _accurateMultiplication: function (num1, num2) {//乘法分配律 + _accurateMultiplication: function (num1, num2) {// 乘法分配律 var stringNumber1 = this._stringNumberFactory(num1); var stringNumber2 = this._stringNumberFactory(num2); - //整数部分计算 + // 整数部分计算 var integerResult = BI.parseInt(stringNumber1.numInteger) * BI.parseInt(stringNumber2.numInteger); - //num1的小数和num2的整数 + // num1的小数和num2的整数 var dec1Int2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numDecimal) * BI.parseInt(stringNumber2.numInteger), stringNumber1.numDecimalLength); - //num1的整数和num2的小数 + // num1的整数和num2的小数 var int1dec2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numInteger) * BI.parseInt(stringNumber2.numDecimal), stringNumber2.numDecimalLength); - //小数*小数 + // 小数*小数 var dec1dec2 = this._accurateDivisionTenExponent(BI.parseInt(stringNumber1.numDecimal) * BI.parseInt(stringNumber2.numDecimal), (stringNumber1.numDecimalLength + stringNumber2.numDecimalLength)); return this._accurateAddition(this._accurateAddition(this._accurateAddition(integerResult, dec1Int2), int1dec2), dec1dec2); @@ -153,63 +153,63 @@ BI.AccurateCalculationModel = BI.inherit(BI.Widget, { var result = integerResult + "." + partDecimalResult + stringNumber.numDecimal; return BI.parseFloat(result); - function addZero(resultTemp, length) { + function addZero (resultTemp, length) { var diff = length - resultTemp.length; for (var i = 0; i < diff; i++) { resultTemp = "0" + resultTemp; } - return resultTemp + return resultTemp; } }, accurateSubtraction: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { if (num1 >= num2) { - return this._accurateSubtraction(num1, num2) + return this._accurateSubtraction(num1, num2); } - return -this._accurateSubtraction(num2, num1) + return -this._accurateSubtraction(num2, num1); } if (num1 >= 0 && num2 < 0) { - return this._accurateAddition(num1, -num2) + return this._accurateAddition(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return -this._accurateAddition(-num1, num2) + return -this._accurateAddition(-num1, num2); } if (num1 < 0 && num2 < 0) { if (num1 >= num2) { - return this._accurateSubtraction(-num2, -num1) + return this._accurateSubtraction(-num2, -num1); } - return this._accurateSubtraction(-num1, -num2) + return this._accurateSubtraction(-num1, -num2); } }, accurateAddition: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { - return this._accurateAddition(num1, num2) + return this._accurateAddition(num1, num2); } if (num1 >= 0 && num2 < 0) { - return this.accurateSubtraction(num1, -num2) + return this.accurateSubtraction(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return this.accurateSubtraction(num2, -num1) + return this.accurateSubtraction(num2, -num1); } if (num1 < 0 && num2 < 0) { - return -this._accurateAddition(-num1, -num2) + return -this._accurateAddition(-num1, -num2); } }, accurateMultiplication: function (num1, num2) { if (num1 >= 0 && num2 >= 0) { - return this._accurateMultiplication(num1, num2) + return this._accurateMultiplication(num1, num2); } if (num1 >= 0 && num2 < 0) { - return -this._accurateMultiplication(num1, -num2) + return -this._accurateMultiplication(num1, -num2); } if (num1 < 0 && num2 >= 0) { - return -this._accurateMultiplication(-num1, num2) + return -this._accurateMultiplication(-num1, num2); } if (num1 < 0 && num2 < 0) { - return this._accurateMultiplication(-num1, -num2) + return this._accurateMultiplication(-num1, -num2); } }, diff --git a/src/widget/month/combo.month.js b/src/widget/month/combo.month.js index 54fed691f..b284360d8 100644 --- a/src/widget/month/combo.month.js +++ b/src/widget/month/combo.month.js @@ -82,4 +82,4 @@ BI.MonthCombo = BI.inherit(BI.Widget, { BI.MonthCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.MonthCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.month_combo', BI.MonthCombo); \ No newline at end of file +BI.shortcut("bi.month_combo", BI.MonthCombo); \ No newline at end of file diff --git a/src/widget/month/popup.month.js b/src/widget/month/popup.month.js index 16373e113..6374c4a88 100644 --- a/src/widget/month/popup.month.js +++ b/src/widget/month/popup.month.js @@ -18,7 +18,7 @@ BI.MonthPopup = BI.inherit(BI.Widget, { BI.MonthPopup.superclass._init.apply(this, arguments); var self = this, o = this.options; - //纵向排列月 + // 纵向排列月 var month = [0, 6, 1, 7, 2, 8, 3, 9, 4, 10, 5, 11]; var items = []; items.push(month.slice(0, 2)); @@ -68,7 +68,7 @@ BI.MonthPopup = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MonthPopup.EVENT_CHANGE); } - }) + }); }, getValue: function () { diff --git a/src/widget/month/trigger.month.js b/src/widget/month/trigger.month.js index 8d0bb4c69..5f6c1992e 100644 --- a/src/widget/month/trigger.month.js +++ b/src/widget/month/trigger.month.js @@ -62,7 +62,7 @@ BI.MonthTrigger = BI.inherit(BI.Trigger, { }); BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor @@ -85,7 +85,7 @@ BI.MonthTrigger = BI.inherit(BI.Trigger, { }); }, setValue: function (v) { - if(BI.isNotNull(v)){ + if(BI.isNotNull(v)) { this.editor.setState(v + 1); this.editor.setValue(v + 1); this.editor.setTitle(v + 1); diff --git a/src/widget/multidate/abstract.multidate.datepane.js b/src/widget/multidate/abstract.multidate.datepane.js index 0f241fff8..0cfb77885 100644 --- a/src/widget/multidate/abstract.multidate.datepane.js +++ b/src/widget/multidate/abstract.multidate.datepane.js @@ -30,17 +30,17 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { var self = this, opts = this.options; this.label = BI.createWidget({ - type: 'bi.label', + type: "bi.label", height: this.constants.itemHeight, textAlign: "left", text: BI.i18nText("BI-Multi_Date_Relative_Current_Time"), - cls: 'bi-multidate-inner-label bi-tips' + cls: "bi-multidate-inner-label bi-tips" }); this.radioGroup = BI.createWidget({ type: "bi.button_group", chooseType: 0, items: BI.createItems(this.dateConfig(), { - type: 'bi.multidate_segment', + type: "bi.multidate_segment", height: this.constants.itemHeight }), layouts: [{ @@ -59,10 +59,10 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { }); BI.createWidget({ element: this, - type: 'bi.center_adapt', + type: "bi.center_adapt", lgap: this.constants.lgap, items: [{ - type: 'bi.vertical', + type: "bi.vertical", items: [this.label, this.radioGroup] }] }); @@ -74,7 +74,7 @@ BI.MultiDateCard = BI.inherit(BI.Widget, { return { type: type, value: value - } + }; }, _isTypeAvaliable: function (type) { diff --git a/src/widget/multidate/multidate.combo.js b/src/widget/multidate/multidate.combo.js index 905cdaff3..0288856b6 100644 --- a/src/widget/multidate/multidate.combo.js +++ b/src/widget/multidate/multidate.combo.js @@ -14,7 +14,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { }, _defaultConfig: function () { return BI.extend(BI.MultiDateCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-combo bi-border', + baseCls: "bi-multidate-combo bi-border", height: 24 }); }, @@ -25,7 +25,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { var date = Date.getDate(); this.storeValue = null; this.trigger = BI.createWidget({ - type: 'bi.date_trigger', + type: "bi.date_trigger", min: this.constants.DATE_MIN_VALUE, max: this.constants.DATE_MAX_VALUE }); @@ -106,11 +106,11 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.popup.on(BI.MultiDatePopup.CALENDAR_EVENT_CHANGE, function () { self.setValue(self.popup.getValue()); self.combo.hideView(); - //self.fireEvent(BI.MultiDateCombo.EVENT_CHANGE); + // self.fireEvent(BI.MultiDateCombo.EVENT_CHANGE); self.fireEvent(BI.MultiDateCombo.EVENT_CONFIRM); }); this.combo = BI.createWidget({ - type: 'bi.combo', + type: "bi.combo", toggle: false, isNeedAdjustHeight: false, isNeedAdjustWidth: false, @@ -174,13 +174,13 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { ref: function (_ref) { self.comboWrapper = _ref; } - }) + }); }, _checkDynamicValue: function (v) { var type = null; if (BI.isNotNull(v)) { - type = v.type + type = v.type; } switch (type) { case BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV: @@ -216,7 +216,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.storeValue = v; this.popup.setValue(v); this.trigger.setValue(v); - this._checkDynamicValue(v) + this._checkDynamicValue(v); }, getValue: function () { return this.storeValue; @@ -228,7 +228,7 @@ BI.MultiDateCombo = BI.inherit(BI.Single, { this.combo.hideView(); } }); -BI.shortcut('bi.multidate_combo', BI.MultiDateCombo); +BI.shortcut("bi.multidate_combo", BI.MultiDateCombo); BI.MultiDateCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.MultiDateCombo.EVENT_FOCUS = "EVENT_FOCUS"; diff --git a/src/widget/multidate/multidate.day.js b/src/widget/multidate/multidate.day.js index 8ca22055e..403679c72 100644 --- a/src/widget/multidate/multidate.day.js +++ b/src/widget/multidate/multidate.day.js @@ -8,7 +8,7 @@ BI.DayCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.DayCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-daycard' + baseCls: "bi-multidate-daycard" }); }, @@ -23,21 +23,21 @@ BI.DayCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Day_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Day_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY, - text: BI.i18nText("BI-Multi_Date_Today") - }]; + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Day_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_AFTER + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_TODAY, + text: BI.i18nText("BI-Multi_Date_Today") + }]; }, defaultSelectedItem: function () { - return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV + return BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_DAY_PREV; } }); BI.DayCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.daycard', BI.DayCard); +BI.shortcut("bi.daycard", BI.DayCard); diff --git a/src/widget/multidate/multidate.month.js b/src/widget/multidate/multidate.month.js index c4428fde2..731f43b70 100644 --- a/src/widget/multidate/multidate.month.js +++ b/src/widget/multidate/multidate.month.js @@ -7,7 +7,7 @@ BI.MonthCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.MonthCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-monthcard' + baseCls: "bi-multidate-monthcard" }); }, @@ -22,21 +22,21 @@ BI.MonthCard = BI.inherit(BI.MultiDateCard, { value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_PREV, text: BI.i18nText("BI-Multi_Date_Month_Prev") }, - { - isEditorExist: true, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER, - text: BI.i18nText("BI-Multi_Date_Month_Next") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Month_Begin") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Month_End") - }]; + { + isEditorExist: true, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_AFTER, + text: BI.i18nText("BI-Multi_Date_Month_Next") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_BEGIN, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Month_Begin") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_MONTH_END, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Month_End") + }]; }, defaultSelectedItem: function () { @@ -44,4 +44,4 @@ BI.MonthCard = BI.inherit(BI.MultiDateCard, { } }); BI.MonthCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.monthcard', BI.MonthCard); +BI.shortcut("bi.monthcard", BI.MonthCard); diff --git a/src/widget/multidate/multidate.popup.js b/src/widget/multidate/multidate.popup.js index 0a1d7bf30..d4d8e5015 100644 --- a/src/widget/multidate/multidate.popup.js +++ b/src/widget/multidate/multidate.popup.js @@ -23,7 +23,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { }, _defaultConfig: function () { return BI.extend(BI.MultiDatePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-popup', + baseCls: "bi-multidate-popup", width: 268, height: 260 }); @@ -33,9 +33,9 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { var self = this, opts = this.options; this.storeValue = ""; this.textButton = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-label bi-border-left bi-border-right bi-border-top', + cls: "bi-multidate-popup-label bi-border-left bi-border-right bi-border-top", shadow: true, text: BI.i18nText("BI-Multi_Date_Today") }); @@ -45,7 +45,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { this.clearButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-button bi-border-top', + cls: "bi-multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_Clear") }); @@ -55,7 +55,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { this.okButton = BI.createWidget({ type: "bi.text_button", forceCenter: true, - cls: 'bi-multidate-popup-button bi-border-top', + cls: "bi-multidate-popup-button bi-border-top", shadow: true, text: BI.i18nText("BI-Basic_OK") }); @@ -63,7 +63,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { self.fireEvent(BI.MultiDatePopup.BUTTON_OK_EVENT_CHANGE); }); this.dateTab = BI.createWidget({ - type: 'bi.tab', + type: "bi.tab", tab: { cls: "bi-multidate-popup-tab bi-border-bottom", height: this.constants.tabHeight, @@ -90,10 +90,10 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { width: this.constants.tabWidth, textAlign: "center", height: this.constants.itemHeight, - cls: 'bi-multidate-popup-item bi-list-item-active' + cls: "bi-multidate-popup-item bi-list-item-active" }), layouts: [{ - type: 'bi.left' + type: "bi.left" }] }, cardCreator: function (v) { @@ -118,7 +118,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.year; case BI.MultiDateCombo.MULTI_DATE_QUARTER_CARD: self.quarter = BI.createWidget({ - type: 'bi.quartercard' + type: "bi.quartercard" }); self.quarter.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.quarter, v); @@ -126,7 +126,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.quarter; case BI.MultiDateCombo.MULTI_DATE_MONTH_CARD: self.month = BI.createWidget({ - type: 'bi.monthcard' + type: "bi.monthcard" }); self.month.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.month, v); @@ -134,7 +134,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.month; case BI.MultiDateCombo.MULTI_DATE_WEEK_CARD: self.week = BI.createWidget({ - type: 'bi.weekcard' + type: "bi.weekcard" }); self.week.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.week, v); @@ -142,7 +142,7 @@ BI.MultiDatePopup = BI.inherit(BI.Widget, { return self.week; case BI.MultiDateCombo.MULTI_DATE_DAY_CARD: self.day = BI.createWidget({ - type: 'bi.daycard' + type: "bi.daycard" }); self.day.on(BI.MultiDateCard.EVENT_CHANGE, function (v) { self._setInnerValue(self.day, v); @@ -314,4 +314,4 @@ BI.MultiDatePopup.BUTTON_OK_EVENT_CHANGE = "BUTTON_OK_EVENT_CHANGE"; BI.MultiDatePopup.BUTTON_lABEL_EVENT_CHANGE = "BUTTON_lABEL_EVENT_CHANGE"; BI.MultiDatePopup.BUTTON_CLEAR_EVENT_CHANGE = "BUTTON_CLEAR_EVENT_CHANGE"; BI.MultiDatePopup.CALENDAR_EVENT_CHANGE = "CALENDAR_EVENT_CHANGE"; -BI.shortcut('bi.multidate_popup', BI.MultiDatePopup); +BI.shortcut("bi.multidate_popup", BI.MultiDatePopup); diff --git a/src/widget/multidate/multidate.quarter.js b/src/widget/multidate/multidate.quarter.js index 7a8a1fa2f..ab137edeb 100644 --- a/src/widget/multidate/multidate.quarter.js +++ b/src/widget/multidate/multidate.quarter.js @@ -8,7 +8,7 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.QuarterCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-quartercard' + baseCls: "bi-multidate-quartercard" }); }, @@ -23,21 +23,21 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { isEditorExist: true, text: BI.i18nText("BI-Multi_Date_Quarter_Prev") }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER, - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Quarter_Next") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Quarter_Begin") - }, - { - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END, - isEditorExist: false, - text: BI.i18nText("BI-Multi_Date_Quarter_End") - }] + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_AFTER, + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Quarter_Next") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_BEGIN, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Quarter_Begin") + }, + { + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_QUARTER_END, + isEditorExist: false, + text: BI.i18nText("BI-Multi_Date_Quarter_End") + }]; }, defaultSelectedItem: function () { @@ -45,4 +45,4 @@ BI.QuarterCard = BI.inherit(BI.MultiDateCard, { } }); BI.QuarterCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.quartercard', BI.QuarterCard); +BI.shortcut("bi.quartercard", BI.QuarterCard); diff --git a/src/widget/multidate/multidate.segment.js b/src/widget/multidate/multidate.segment.js index 277987027..0021b9a1b 100644 --- a/src/widget/multidate/multidate.segment.js +++ b/src/widget/multidate/multidate.segment.js @@ -15,7 +15,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { _defaultConfig: function () { return $.extend(BI.MultiDateSegment.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-segment', + baseCls: "bi-multidate-segment", text: "", height: 30, isEditorExist: true, @@ -35,13 +35,13 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); }); this.textEditor = BI.createWidget({ - type: 'bi.text_editor', + type: "bi.text_editor", value: this.constants.defaultEditorValue, title: function () { return self.textEditor.getValue(); }, tipType: "success", - cls: 'bi-multidate-editor', + cls: "bi-multidate-editor", width: this.constants.textWidth, height: this.constants.itemHeight }); @@ -51,7 +51,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { this.text = BI.createWidget({ type: "bi.label", textAlign: "left", - cls: 'bi-multidate-normal-label', + cls: "bi-multidate-normal-label", text: opts.text, height: this.constants.itemHeight }); @@ -61,7 +61,7 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { if (this.options.isEditorExist === true) { return BI.createWidget({ element: this, - type: 'bi.left', + type: "bi.left", items: [{ el: { type: "bi.center_adapt", @@ -70,23 +70,23 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { }, lgap: 0 }, - { - el: { - type: "bi.center_adapt", - items: [this.textEditor], - widgetName: 'textEditor' - }, - lgap: this.constants.maxGap + { + el: { + type: "bi.center_adapt", + items: [this.textEditor], + widgetName: "textEditor" }, - { - el: this.text, - lgap: this.constants.minGap - }] + lgap: this.constants.maxGap + }, + { + el: this.text, + lgap: this.constants.minGap + }] }); } return BI.createWidget({ element: this, - type: 'bi.left', + type: "bi.left", items: [{ el: { type: "bi.center_adapt", @@ -95,11 +95,11 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { }, lgap: 0 }, - { - el: this.text, - lgap: this.constants.maxGap - }] - }) + { + el: this.text, + lgap: this.constants.maxGap + }] + }); }, setSelected: function (v) { if (BI.isNotNull(this.radio)) { @@ -124,4 +124,4 @@ BI.MultiDateSegment = BI.inherit(BI.Single, { } }); BI.MultiDateSegment.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multidate_segment', BI.MultiDateSegment); \ No newline at end of file +BI.shortcut("bi.multidate_segment", BI.MultiDateSegment); \ No newline at end of file diff --git a/src/widget/multidate/multidate.week.js b/src/widget/multidate/multidate.week.js index 0a5265479..9eb6708c8 100644 --- a/src/widget/multidate/multidate.week.js +++ b/src/widget/multidate/multidate.week.js @@ -7,7 +7,7 @@ BI.WeekCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.WeekCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-weekcard' + baseCls: "bi-multidate-weekcard" }); }, @@ -22,11 +22,11 @@ BI.WeekCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Week_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Week_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER - }]; + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Week_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_WEEK_AFTER + }]; }, defaultSelectedItem: function () { @@ -34,4 +34,4 @@ BI.WeekCard = BI.inherit(BI.MultiDateCard, { } }); BI.WeekCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.weekcard', BI.WeekCard); +BI.shortcut("bi.weekcard", BI.WeekCard); diff --git a/src/widget/multidate/multidate.year.js b/src/widget/multidate/multidate.year.js index b1af65add..272db0e7c 100644 --- a/src/widget/multidate/multidate.year.js +++ b/src/widget/multidate/multidate.year.js @@ -7,7 +7,7 @@ BI.YearCard = BI.inherit(BI.MultiDateCard, { _defaultConfig: function () { return $.extend(BI.YearCard.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multidate-yearcard' + baseCls: "bi-multidate-yearcard" }); }, @@ -22,21 +22,21 @@ BI.YearCard = BI.inherit(BI.MultiDateCard, { text: BI.i18nText("BI-Multi_Date_Year_Prev"), value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_PREV }, - { - isEditorExist: true, - text: BI.i18nText("BI-Multi_Date_Year_Next"), - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN, - text: BI.i18nText("BI-Multi_Date_Year_Begin") - }, - { - isEditorExist: false, - value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END, - text: BI.i18nText("BI-Multi_Date_Year_End") - }] + { + isEditorExist: true, + text: BI.i18nText("BI-Multi_Date_Year_Next"), + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_AFTER + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_BEGIN, + text: BI.i18nText("BI-Multi_Date_Year_Begin") + }, + { + isEditorExist: false, + value: BI.MultiDateCombo.DATE_TYPE.MULTI_DATE_YEAR_END, + text: BI.i18nText("BI-Multi_Date_Year_End") + }]; }, defaultSelectedItem: function () { @@ -44,4 +44,4 @@ BI.YearCard = BI.inherit(BI.MultiDateCard, { } }); BI.YearCard.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.yearcard', BI.YearCard); +BI.shortcut("bi.yearcard", BI.YearCard); diff --git a/src/widget/multilayerselecttree/multilayerselecttree.leveltree.js b/src/widget/multilayerselecttree/multilayerselecttree.leveltree.js index 30a5ec2de..4c15b4959 100644 --- a/src/widget/multilayerselecttree/multilayerselecttree.leveltree.js +++ b/src/widget/multilayerselecttree/multilayerselecttree.leveltree.js @@ -11,7 +11,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { isDefaultInit: false, items: [], itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -63,7 +63,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -96,7 +96,7 @@ BI.MultiLayerSelectLevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MultiLayerSelectLevelTree.EVENT_CHANGE, arguments); } - }) + }); }, populate: function (nodes) { diff --git a/src/widget/multilayerselecttree/multilayerselecttree.popup.js b/src/widget/multilayerselecttree/multilayerselecttree.popup.js index 6bc234843..c70f783bb 100644 --- a/src/widget/multilayerselecttree/multilayerselecttree.popup.js +++ b/src/widget/multilayerselecttree/multilayerselecttree.popup.js @@ -23,7 +23,7 @@ BI.MultiLayerSelectTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.multilayer_select_level_tree', + type: "bi.multilayer_select_level_tree", isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator diff --git a/src/widget/multilayerselecttree/node/node.first.plus.js b/src/widget/multilayerselecttree/node/node.first.plus.js index 467290106..858f69919 100644 --- a/src/widget/multilayerselecttree/node/node.first.plus.js +++ b/src/widget/multilayerselecttree/node/node.first.plus.js @@ -10,13 +10,13 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-first-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -49,7 +49,7 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -57,7 +57,7 @@ BI.MultiLayerSelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, isOnce: function () { diff --git a/src/widget/multilayerselecttree/node/node.last.plus.js b/src/widget/multilayerselecttree/node/node.last.plus.js index 035ddd5e4..92909603d 100644 --- a/src/widget/multilayerselecttree/node/node.last.plus.js +++ b/src/widget/multilayerselecttree/node/node.last.plus.js @@ -10,13 +10,13 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-last-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -49,7 +49,7 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -57,7 +57,7 @@ BI.MultiLayerSelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { diff --git a/src/widget/multilayerselecttree/node/node.mid.plus.js b/src/widget/multilayerselecttree/node/node.mid.plus.js index 2dcde5142..9d16a7692 100644 --- a/src/widget/multilayerselecttree/node/node.mid.plus.js +++ b/src/widget/multilayerselecttree/node/node.mid.plus.js @@ -10,13 +10,13 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-select-tree-mid-plus-group-node bi-list-item-active", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSelectTreeMidPlusGroupNode.superclass._init.apply(this, arguments); @@ -49,7 +49,7 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -57,7 +57,7 @@ BI.MultiLayerSelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { diff --git a/src/widget/multilayersingletree/multilayersingletree.leveltree.js b/src/widget/multilayersingletree/multilayersingletree.leveltree.js index 057b41d2f..34be01704 100644 --- a/src/widget/multilayersingletree/multilayersingletree.leveltree.js +++ b/src/widget/multilayersingletree/multilayersingletree.leveltree.js @@ -11,7 +11,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { isDefaultInit: false, items: [], itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -63,7 +63,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { }); }, - //构造树结构, + // 构造树结构, initTree: function (nodes) { var self = this, o = this.options; this.empty(); @@ -82,8 +82,8 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { items: this._formatItems(BI.Tree.transformToTreeFormat(nodes), 0), itemsCreator: function (op, callback) { o.itemsCreator(op, function (items) { - callback(BI.Tree.transformToTreeFormat(items), 0) - }) + callback(BI.Tree.transformToTreeFormat(items), 0); + }); }, el: { @@ -99,7 +99,7 @@ BI.MultiLayerSingleLevelTree = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MultiLayerSingleLevelTree.EVENT_CHANGE, v); } - }) + }); }, populate: function (nodes) { diff --git a/src/widget/multilayersingletree/multilayersingletree.popup.js b/src/widget/multilayersingletree/multilayersingletree.popup.js index e1d6a4748..9c09aed39 100644 --- a/src/widget/multilayersingletree/multilayersingletree.popup.js +++ b/src/widget/multilayersingletree/multilayersingletree.popup.js @@ -23,7 +23,7 @@ BI.MultiLayerSingleTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.multilayer_single_level_tree', + type: "bi.multilayer_single_level_tree", isDefaultInit: o.isDefaultInit, items: o.items, itemsCreator: o.itemsCreator diff --git a/src/widget/multilayersingletree/node/node.first.plus.js b/src/widget/multilayersingletree/node/node.first.plus.js index 4e6255a50..f103812e7 100644 --- a/src/widget/multilayersingletree/node/node.first.plus.js +++ b/src/widget/multilayersingletree/node/node.first.plus.js @@ -10,12 +10,12 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-first-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); @@ -36,7 +36,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -49,7 +49,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -57,7 +57,7 @@ BI.MultiLayerSingleTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { diff --git a/src/widget/multilayersingletree/node/node.last.plus.js b/src/widget/multilayersingletree/node/node.last.plus.js index 085254a61..1141b1294 100644 --- a/src/widget/multilayersingletree/node/node.last.plus.js +++ b/src/widget/multilayersingletree/node/node.last.plus.js @@ -10,12 +10,12 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-last-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -36,7 +36,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -49,7 +49,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -57,7 +57,7 @@ BI.MultiLayerSingleTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { diff --git a/src/widget/multilayersingletree/node/node.mid.plus.js b/src/widget/multilayersingletree/node/node.mid.plus.js index a540a0e26..10894408d 100644 --- a/src/widget/multilayersingletree/node/node.mid.plus.js +++ b/src/widget/multilayersingletree/node/node.mid.plus.js @@ -10,12 +10,12 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { var conf = BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-multilayer-single-tree-mid-plus-group-node bi-list-item", - layer: 0,//第几层级 + layer: 0, // 第几层级 id: "", pId: "", open: false, height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeMidPlusGroupNode.superclass._init.apply(this, arguments); @@ -36,7 +36,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { py: o.py }); this.node.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -49,7 +49,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.node); BI.createWidget({ @@ -57,7 +57,7 @@ BI.MultiLayerSingleTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { diff --git a/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js index 82c6915d4..259def250 100644 --- a/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js +++ b/src/widget/multilayersingletree/treeitem/item.first.treeleaf.js @@ -15,7 +15,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeFirstTreeLeafItem.superclass._init.apply(this, arguments); @@ -35,7 +35,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -48,7 +48,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -56,7 +56,7 @@ BI.MultiLayerSingleTreeFirstTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { diff --git a/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js index bece33468..558906b09 100644 --- a/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js +++ b/src/widget/multilayersingletree/treeitem/item.last.treeleaf.js @@ -15,7 +15,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeLastTreeLeafItem.superclass._init.apply(this, arguments); @@ -35,7 +35,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -48,7 +48,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -56,7 +56,7 @@ BI.MultiLayerSingleTreeLastTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { diff --git a/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js b/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js index b6ec9bf9b..03d13faf7 100644 --- a/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js +++ b/src/widget/multilayersingletree/treeitem/item.mid.treeleaf.js @@ -15,7 +15,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { id: "", pId: "", height: 25 - }) + }); }, _init: function () { BI.MultiLayerSingleTreeMidTreeLeafItem.superclass._init.apply(this, arguments); @@ -35,7 +35,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { py: o.py }); this.item.on(BI.Controller.EVENT_CHANGE, function (type) { - if (type === BI.Events.CLICK) {//本身实现click功能 + if (type === BI.Events.CLICK) {// 本身实现click功能 return; } self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); @@ -48,7 +48,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { cls: "base-line-conn-background", width: 13, height: o.height - }) + }); }); items.push(this.item); BI.createWidget({ @@ -56,7 +56,7 @@ BI.MultiLayerSingleTreeMidTreeLeafItem = BI.inherit(BI.BasicButton, { element: this, columnSize: BI.makeArray(o.layer, 13), items: [items] - }) + }); }, doRedMark: function () { diff --git a/src/widget/multiselect/check/multiselect.check.pane.js b/src/widget/multiselect/check/multiselect.check.pane.js index 582f8a844..0abdb024c 100644 --- a/src/widget/multiselect/check/multiselect.check.pane.js +++ b/src/widget/multiselect/check/multiselect.check.pane.js @@ -28,7 +28,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { this.storeValue = {}; this.display = BI.createWidget({ - type: 'bi.display_selected_list', + type: "bi.display_selected_list", items: opts.items, itemsCreator: function (op, callback) { op = BI.extend(op || {}, { @@ -42,7 +42,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { text: txt, value: v, title: txt - } + }; }) }); return; @@ -52,9 +52,9 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }); this.continueSelect = BI.createWidget({ - type: 'bi.text_button', - text: BI.i18nText('BI-Continue_Select'), - cls: 'multi-select-check-selected bi-high-light' + type: "bi.text_button", + text: BI.i18nText("BI-Continue_Select"), + cls: "multi-select-check-selected bi-high-light" }); this.continueSelect.on(BI.TextButton.EVENT_CHANGE, function () { @@ -62,18 +62,18 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }); BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", element: this, items: [{ height: this.constants.height, el: { - type: 'bi.left', - cls: 'multi-select-continue-select', + type: "bi.left", + cls: "multi-select-continue-select", items: [ { el: { type: "bi.label", - text: BI.i18nText('BI-Selected_Data') + text: BI.i18nText("BI-Selected_Data") }, lgap: this.constants.lgap, tgap: this.constants.tgap @@ -85,7 +85,7 @@ BI.MultiSelectCheckPane = BI.inherit(BI.Widget, { }] } }, { - height: 'fill', + height: "fill", el: this.display }] }); diff --git a/src/widget/multiselect/check/multiselect.display.js b/src/widget/multiselect/check/multiselect.display.js index 5f00924af..d5ecf7fad 100644 --- a/src/widget/multiselect/check/multiselect.display.js +++ b/src/widget/multiselect/check/multiselect.display.js @@ -49,7 +49,7 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { opts.itemsCreator(options, function (ob) { self.hasNext = !!ob.hasNext; callback(self._createItems(ob.items)); - }) + }); }, hasNext: function () { return self.hasNext; @@ -59,8 +59,8 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { _createItems: function (items) { return BI.createItems(items, { - type: 'bi.icon_text_item', - cls: 'cursor-default check-font display-list-item bi-tips', + type: "bi.icon_text_item", + cls: "cursor-default check-font display-list-item bi-tips", once: true, invalid: true, selected: true, @@ -84,4 +84,4 @@ BI.DisplaySelectedList = BI.inherit(BI.Pane, { } }); -BI.shortcut('bi.display_selected_list', BI.DisplaySelectedList); \ No newline at end of file +BI.shortcut("bi.display_selected_list", BI.DisplaySelectedList); \ No newline at end of file diff --git a/src/widget/multiselect/multiselect..insert.combo.js b/src/widget/multiselect/multiselect..insert.combo.js index 23f3258c0..9e53c1b7d 100644 --- a/src/widget/multiselect/multiselect..insert.combo.js +++ b/src/widget/multiselect/multiselect..insert.combo.js @@ -7,7 +7,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiSelectInsertCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-insert-combo', + baseCls: "bi-multi-select-insert-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -24,7 +24,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { self.trigger.getCounter().setButtonChecked(self.storeValue); }; this.storeValue = {}; - //标记正在请求数据 + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -43,7 +43,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(BI.deepClone(self.getValue())); } callback.apply(self, arguments); @@ -65,7 +65,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { type: BI.Selection.Multi, value: [keyword] }, function () { - //如果在不选的状态下直接把该值添加进来 + // 如果在不选的状态下直接把该值添加进来 if (self.storeValue.type === BI.Selection.Multi) { self.storeValue.value.pushDistinct(keyword); } @@ -74,7 +74,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); // } }); this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -121,7 +121,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_select_popup_view', + type: "bi.multi_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -168,10 +168,10 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -209,7 +209,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -239,7 +239,7 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -285,14 +285,14 @@ BI.MultiSelectInsertCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { var self = this, o = this.options; adjust(); callback(); - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.MultiSelectInsertCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -354,4 +354,4 @@ BI.extend(BI.MultiSelectInsertCombo, { BI.MultiSelectInsertCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.multi_select_insert_combo', BI.MultiSelectInsertCombo); \ No newline at end of file +BI.shortcut("bi.multi_select_insert_combo", BI.MultiSelectInsertCombo); \ No newline at end of file diff --git a/src/widget/multiselect/multiselect.combo.js b/src/widget/multiselect/multiselect.combo.js index 9f410c4cd..8ba8d45bb 100644 --- a/src/widget/multiselect/multiselect.combo.js +++ b/src/widget/multiselect/multiselect.combo.js @@ -7,7 +7,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-combo', + baseCls: "bi-multi-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -24,7 +24,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { self.trigger.getCounter().setButtonChecked(self.storeValue); }; this.storeValue = {}; - //标记正在请求数据 + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -43,7 +43,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(BI.deepClone(self.getValue())); } callback.apply(self, arguments); @@ -70,7 +70,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.MultiSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -117,7 +117,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_select_popup_view', + type: "bi.multi_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -164,10 +164,10 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -205,7 +205,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -235,7 +235,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -281,7 +281,7 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -300,17 +300,17 @@ BI.MultiSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.storeValue.type === BI.Selection.All && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.Multi, value: [] - } + }; } else if (self.storeValue.type === BI.Selection.Multi && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.All, value: [] - } + }; } if (self.wants2Quit === true) { self.fireEvent(BI.MultiSelectCombo.EVENT_CONFIRM); @@ -374,4 +374,4 @@ BI.extend(BI.MultiSelectCombo, { BI.MultiSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.multi_select_combo', BI.MultiSelectCombo); \ No newline at end of file +BI.shortcut("bi.multi_select_combo", BI.MultiSelectCombo); \ No newline at end of file diff --git a/src/widget/multiselect/multiselect.loader.js b/src/widget/multiselect/multiselect.loader.js index febe15800..5d152540e 100644 --- a/src/widget/multiselect/multiselect.loader.js +++ b/src/widget/multiselect/multiselect.loader.js @@ -8,7 +8,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-loader', + baseCls: "bi-multi-select-loader", logic: { dynamic: true }, @@ -70,7 +70,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: self.storeValue.type === BI.Selection.Multi - } + }; }); if (BI.isKey(self._startValue) && !self.storeValue.value.contains(self._startValue)) { var txt = opts.valueFormatter(startValue) || startValue; @@ -79,7 +79,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { value: startValue, title: txt, selected: true - }) + }); } firstItems = self._createItems(json); } @@ -109,7 +109,7 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { logic: this.options.logic, height: 25, selected: this.isAllSelected() - }) + }); }, _scrollToTop: function () { @@ -165,4 +165,4 @@ BI.MultiSelectLoader = BI.inherit(BI.Widget, { }); BI.MultiSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_loader', BI.MultiSelectLoader); \ No newline at end of file +BI.shortcut("bi.multi_select_loader", BI.MultiSelectLoader); \ No newline at end of file diff --git a/src/widget/multiselect/multiselect.popup.view.js b/src/widget/multiselect/multiselect.popup.view.js index cfbd6aca1..b1137d1db 100644 --- a/src/widget/multiselect/multiselect.popup.view.js +++ b/src/widget/multiselect/multiselect.popup.view.js @@ -7,8 +7,8 @@ BI.MultiSelectPopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectPopupView.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-popup-view', - maxWidth: 'auto', + baseCls: "bi-multi-select-popup-view", + maxWidth: "auto", minWidth: 135, maxHeight: 400, valueFormatter: BI.emptyFn, @@ -35,7 +35,7 @@ BI.MultiSelectPopupView = BI.inherit(BI.Widget, { minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.loader }); @@ -88,4 +88,4 @@ BI.MultiSelectPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; BI.MultiSelectPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.shortcut('bi.multi_select_popup_view', BI.MultiSelectPopupView); \ No newline at end of file +BI.shortcut("bi.multi_select_popup_view", BI.MultiSelectPopupView); \ No newline at end of file diff --git a/src/widget/multiselect/multiselect.trigger.js b/src/widget/multiselect/multiselect.trigger.js index 0da496a64..455502610 100644 --- a/src/widget/multiselect/multiselect.trigger.js +++ b/src/widget/multiselect/multiselect.trigger.js @@ -59,7 +59,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { self.fireEvent(BI.MultiSelectTrigger.EVENT_CHANGE, arguments); }); this.numberCounter = BI.createWidget(o.switcher, { - type: 'bi.multi_select_check_selected_switcher', + type: "bi.multi_select_check_selected_switcher", valueFormatter: o.valueFormatter, itemsCreator: o.itemsCreator, adapter: o.adapter, @@ -73,7 +73,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapNumberCounter = BI.createWidget({ - type: 'bi.right_vertical_adapt', + type: "bi.right_vertical_adapt", hgap: 4, items: [{ el: this.numberCounter @@ -81,12 +81,12 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: wrapNumberCounter, width: 0 @@ -97,7 +97,7 @@ BI.MultiSelectTrigger = BI.inherit(BI.Trigger, { }); this.numberCounter.on(BI.Events.VIEW, function (b) { - BI.nextTick(function () {//自动调整宽度 + BI.nextTick(function () {// 自动调整宽度 wrapper.attr("items")[1].width = (b === true ? self.numberCounter.element.outerWidth() + 8 : 0); wrapper.resize(); }); @@ -151,4 +151,4 @@ BI.MultiSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.MultiSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.MultiSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.multi_select_trigger', BI.MultiSelectTrigger); \ No newline at end of file +BI.shortcut("bi.multi_select_trigger", BI.MultiSelectTrigger); \ No newline at end of file diff --git a/src/widget/multiselect/search/multiselect.search.loader.js b/src/widget/multiselect/search/multiselect.search.loader.js index 8c6caba90..5b1d919b5 100644 --- a/src/widget/multiselect/search/multiselect.search.loader.js +++ b/src/widget/multiselect/search/multiselect.search.loader.js @@ -8,7 +8,7 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-search-loader', + baseCls: "bi-multi-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -87,7 +87,7 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: this.isAllSelected() - }) + }); }, isAllSelected: function () { @@ -114,12 +114,12 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: src.type === BI.Selection.All - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = BI.deepClone(v); this.button_group.setValue(v); }, @@ -150,4 +150,4 @@ BI.MultiSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.MultiSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_search_loader', BI.MultiSelectSearchLoader); \ No newline at end of file +BI.shortcut("bi.multi_select_search_loader", BI.MultiSelectSearchLoader); \ No newline at end of file diff --git a/src/widget/multiselect/search/multiselect.search.pane.js b/src/widget/multiselect/search/multiselect.search.pane.js index 7acca0600..47ea910a9 100644 --- a/src/widget/multiselect/search/multiselect.search.pane.js +++ b/src/widget/multiselect/search/multiselect.search.pane.js @@ -29,8 +29,8 @@ BI.MultiSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'multi-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "multi-select-toolbar", height: this.constants.height }); diff --git a/src/widget/multiselect/trigger/button.checkselected.js b/src/widget/multiselect/trigger/button.checkselected.js index 718f75c46..f75840d3b 100644 --- a/src/widget/multiselect/trigger/button.checkselected.js +++ b/src/widget/multiselect/trigger/button.checkselected.js @@ -7,12 +7,12 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiSelectCheckSelectedButton.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-check-selected-button bi-high-light', + baseCls: "bi-multi-select-check-selected-button bi-high-light", itemsCreator: BI.emptyFn }); }, @@ -21,11 +21,11 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { BI.MultiSelectCheckSelectedButton.superclass._init.apply(this, arguments); var self = this; this.numberCounter = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", element: this, hgap: 4, text: "0", - textAlign: 'center', + textAlign: "center", textHeight: 15 }); this.numberCounter.on(BI.Controller.EVENT_CHANGE, function () { @@ -55,17 +55,17 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { type: BI.MultiSelectCombo.REQ_GET_DATA_LENGTH }, function (res) { var length = res.count - ob.value.length; - BI.nextTick(function(){ + BI.nextTick(function () { self.numberCounter.setText(length); self.setVisible(length > 0); }); }); return; } - BI.nextTick(function(){ + BI.nextTick(function () { self.numberCounter.setText(ob.value.length); self.setVisible(ob.value.length > 0); - }) + }); }, getValue: function () { @@ -74,4 +74,4 @@ BI.MultiSelectCheckSelectedButton = BI.inherit(BI.Single, { }); BI.MultiSelectCheckSelectedButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_select_check_selected_button', BI.MultiSelectCheckSelectedButton); \ No newline at end of file +BI.shortcut("bi.multi_select_check_selected_button", BI.MultiSelectCheckSelectedButton); \ No newline at end of file diff --git a/src/widget/multiselect/trigger/editor.multiselect.js b/src/widget/multiselect/trigger/editor.multiselect.js index 368509fa4..ec7f4c1e0 100644 --- a/src/widget/multiselect/trigger/editor.multiselect.js +++ b/src/widget/multiselect/trigger/editor.multiselect.js @@ -7,12 +7,12 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiSelectEditor.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-editor', + baseCls: "bi-multi-select-editor", el: {} }); }, @@ -21,10 +21,10 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { BI.MultiSelectEditor.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.state_editor', + type: "bi.state_editor", element: this, height: o.height, - watermark: BI.i18nText('BI-Basic_Search'), + watermark: BI.i18nText("BI-Basic_Search"), allowBlank: true }); @@ -60,16 +60,16 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { var v = this.editor.getState(); if (BI.isArray(v) && v.length > 0) { return v[v.length - 1]; - } else { - return ""; } + return ""; + }, getKeywords: function () { var val = this.editor.getLastValidValue(); var keywords = val.match(/[\S]+/g); if (BI.isEndWithBlank(val)) { - return keywords.concat([' ']); + return keywords.concat([" "]); } return keywords; }, @@ -79,4 +79,4 @@ BI.MultiSelectEditor = BI.inherit(BI.Widget, { } }); BI.MultiSelectEditor.EVENT_PAUSE = "MultiSelectEditor.EVENT_PAUSE"; -BI.shortcut('bi.multi_select_editor', BI.MultiSelectEditor); \ No newline at end of file +BI.shortcut("bi.multi_select_editor", BI.MultiSelectEditor); \ No newline at end of file diff --git a/src/widget/multiselect/trigger/searcher.multiselect.js b/src/widget/multiselect/trigger/searcher.multiselect.js index 150f63bae..3a410c46e 100644 --- a/src/widget/multiselect/trigger/searcher.multiselect.js +++ b/src/widget/multiselect/trigger/searcher.multiselect.js @@ -8,7 +8,7 @@ BI.MultiSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-searcher', + baseCls: "bi-multi-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -22,7 +22,7 @@ BI.MultiSelectSearcher = BI.inherit(BI.Widget, { BI.MultiSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.multi_select_editor', + type: "bi.multi_select_editor", height: o.height }); @@ -165,4 +165,4 @@ BI.MultiSelectSearcher.EVENT_START = "EVENT_START"; BI.MultiSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.MultiSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.MultiSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.multi_select_searcher', BI.MultiSelectSearcher); \ No newline at end of file +BI.shortcut("bi.multi_select_searcher", BI.MultiSelectSearcher); \ No newline at end of file diff --git a/src/widget/multiselect/trigger/switcher.checkselected.js b/src/widget/multiselect/trigger/switcher.checkselected.js index 011cd3794..5f1ec59bf 100644 --- a/src/widget/multiselect/trigger/switcher.checkselected.js +++ b/src/widget/multiselect/trigger/switcher.checkselected.js @@ -8,7 +8,7 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectCheckSelectedSwitcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-check-selected-switcher', + baseCls: "bi-multi-select-check-selected-switcher", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, el: {}, @@ -81,7 +81,7 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { }, setButtonChecked: function (v) { - this.button.setValue(v) + this.button.setValue(v); }, getValue: function () { @@ -95,4 +95,4 @@ BI.MultiSelectCheckSelectedSwitcher = BI.inherit(BI.Widget, { BI.MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE = "MultiSelectCheckSelectedSwitcher.EVENT_TRIGGER_CHANGE"; BI.MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW = "MultiSelectCheckSelectedSwitcher.EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.multi_select_check_selected_switcher', BI.MultiSelectCheckSelectedSwitcher); \ No newline at end of file +BI.shortcut("bi.multi_select_check_selected_switcher", BI.MultiSelectCheckSelectedSwitcher); \ No newline at end of file diff --git a/src/widget/multiselectlist/multiselectlist.insert.js b/src/widget/multiselectlist/multiselectlist.insert.js index 06772aab5..b1be66863 100644 --- a/src/widget/multiselectlist/multiselectlist.insert.js +++ b/src/widget/multiselectlist/multiselectlist.insert.js @@ -4,10 +4,10 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectInsertList.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-insert-list', + baseCls: "bi-multi-select-insert-list", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn - }) + }); }, _init: function () { BI.MultiSelectInsertList.superclass._init.apply(this, arguments); @@ -33,8 +33,8 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }); this.adapter.on(BI.MultiSelectLoader.EVENT_CHANGE, function () { self.storeValue = this.getValue(); - assertShowValue(); - self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); + assertShowValue(); + self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); }); this.searcherPane = BI.createWidget({ @@ -76,7 +76,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { self._showAdapter(); self._setStartValue(""); self.adapter.setValue(self.storeValue); - //需要刷新回到初始界面,否则搜索的结果不能放在最前面 + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 self.adapter.populate(); } }, { @@ -89,7 +89,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { value: [keyword] }, function () { if (self.storeValue.type === BI.Selection.Multi) { - self.storeValue.value.pushDistinct(keyword) + self.storeValue.value.pushDistinct(keyword); } self._showAdapter(); self.adapter.setValue(self.storeValue); @@ -98,10 +98,10 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { self.adapter.populate(); self._setStartValue(""); self.fireEvent(BI.MultiSelectInsertList.EVENT_CHANGE); - }) + }); } else { if (self.storeValue.type === BI.Selection.Multi) { - self.storeValue.value.pushDistinct(keyword) + self.storeValue.value.pushDistinct(keyword); } self._showAdapter(); self.adapter.setValue(self.storeValue); @@ -170,7 +170,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, _showAdapter: function () { @@ -206,12 +206,12 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }, function (ob) { self._allData = BI.pluck(ob.items, "value"); digest(self._allData); - }) + }); } else { - digest(this._allData) + digest(this._allData); } - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -256,7 +256,7 @@ BI.MultiSelectInsertList = BI.inherit(BI.Widget, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); callback(); - }) + }); }, _join: function (res, callback) { diff --git a/src/widget/multiselectlist/multiselectlist.js b/src/widget/multiselectlist/multiselectlist.js index 01fcad3fb..bfb9361cc 100644 --- a/src/widget/multiselectlist/multiselectlist.js +++ b/src/widget/multiselectlist/multiselectlist.js @@ -4,10 +4,10 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectList.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-list', + baseCls: "bi-multi-select-list", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn - }) + }); }, _init: function () { BI.MultiSelectList.superclass._init.apply(this, arguments); @@ -78,7 +78,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { self._showAdapter(); self._setStartValue(""); self.adapter.setValue(self.storeValue); - //需要刷新回到初始界面,否则搜索的结果不能放在最前面 + // 需要刷新回到初始界面,否则搜索的结果不能放在最前面 self.adapter.populate(); } }, { @@ -97,7 +97,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { self.adapter.populate(); self._setStartValue(""); self.fireEvent(BI.MultiSelectList.EVENT_CHANGE); - }) + }); } } }, { @@ -159,7 +159,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, _showAdapter: function () { @@ -195,12 +195,12 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { }, function (ob) { self._allData = BI.pluck(ob.items, "value"); digest(self._allData); - }) + }); } else { - digest(this._allData) + digest(this._allData); } - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -245,7 +245,7 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -263,17 +263,17 @@ BI.MultiSelectList = BI.inherit(BI.Widget, { callback(); } - function adjust() { + function adjust () { if (self.storeValue.type === BI.Selection.All && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.Multi, value: [] - } + }; } else if (self.storeValue.type === BI.Selection.Multi && self.storeValue.value.length >= self._count) { self.storeValue = { type: BI.Selection.All, value: [] - } + }; } } }, diff --git a/src/widget/multiselecttree/multiselecttree.js b/src/widget/multiselecttree/multiselecttree.js index 3b3e4ef5a..a52e0c5a5 100644 --- a/src/widget/multiselecttree/multiselecttree.js +++ b/src/widget/multiselecttree/multiselecttree.js @@ -4,9 +4,9 @@ BI.MultiSelectTree = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiSelectTree.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-select-tree', + baseCls: "bi-multi-select-tree", itemsCreator: BI.emptyFn - }) + }); }, _init: function () { @@ -28,7 +28,7 @@ BI.MultiSelectTree = BI.inherit(BI.Widget, { self.fireEvent(BI.MultiSelectTree.EVENT_CHANGE); }); - //搜索中的时候用的是parttree,同adapter中的synctree不一样 + // 搜索中的时候用的是parttree,同adapter中的synctree不一样 this.searcherPane = BI.createWidget({ type: "bi.multi_tree_search_pane", cls: "bi-border-left bi-border-right bi-border-bottom", @@ -111,7 +111,7 @@ BI.MultiSelectTree = BI.inherit(BI.Widget, { left: 0, right: 0 }] - }) + }); }, diff --git a/src/widget/multiselecttree/multiselecttree.popup.js b/src/widget/multiselecttree/multiselecttree.popup.js index b6e3e55a2..fe635f157 100644 --- a/src/widget/multiselecttree/multiselecttree.popup.js +++ b/src/widget/multiselecttree/multiselecttree.popup.js @@ -17,10 +17,10 @@ BI.MultiSelectTreePopup = BI.inherit(BI.Widget, { itemsCreator: o.itemsCreator }); this.popup.on(BI.TreeView.EVENT_AFTERINIT, function () { - self.fireEvent(BI.MultiSelectTreePopup.EVENT_AFTER_INIT) + self.fireEvent(BI.MultiSelectTreePopup.EVENT_AFTER_INIT); }); this.popup.on(BI.TreeView.EVENT_CHANGE, function () { - self.fireEvent(BI.MultiSelectTreePopup.EVENT_CHANGE) + self.fireEvent(BI.MultiSelectTreePopup.EVENT_CHANGE); }); }, diff --git a/src/widget/multitree/check/multi.tree.check.pane.js b/src/widget/multitree/check/multi.tree.check.pane.js index cd85c949c..57efc414c 100644 --- a/src/widget/multitree/check/multi.tree.check.pane.js +++ b/src/widget/multitree/check/multi.tree.check.pane.js @@ -26,9 +26,9 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { this.selectedValues = {}; var continueSelect = BI.createWidget({ - type: 'bi.text_button', - text: BI.i18nText('BI-Continue_Select'), - cls: 'multi-tree-check-selected' + type: "bi.text_button", + text: BI.i18nText("BI-Continue_Select"), + cls: "multi-tree-check-selected" }); continueSelect.on(BI.TextButton.EVENT_CHANGE, function () { opts.onClickContinueSelect(); @@ -38,13 +38,13 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { }); var backToPopup = BI.createWidget({ - type: 'bi.left', - cls: 'multi-tree-continue-select', + type: "bi.left", + cls: "multi-tree-continue-select", items: [ { el: { type: "bi.label", - text: BI.i18nText('BI-Selected_Data') + text: BI.i18nText("BI-Selected_Data") }, lgap: this.constants.lgap, tgap: this.constants.tgap @@ -78,13 +78,13 @@ BI.MultiTreeCheckPane = BI.inherit(BI.Pane, { }); BI.createWidget({ - type: 'bi.vtape', + type: "bi.vtape", element: this, items: [{ height: this.constants.height, el: backToPopup }, { - height: 'fill', + height: "fill", el: this.display }] }); diff --git a/src/widget/multitree/multi.tree.combo.js b/src/widget/multitree/multi.tree.combo.js index 8f6abbe2b..35befb8c7 100644 --- a/src/widget/multitree/multi.tree.combo.js +++ b/src/widget/multitree/multi.tree.combo.js @@ -17,7 +17,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.MultiTreeCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-combo', + baseCls: "bi-multi-tree-combo", itemsCreator: BI.emptyFn, height: 25 }); @@ -60,7 +60,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.multi_tree_popup_view', + type: "bi.multi_tree_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -113,7 +113,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { this.storeValue = {value: {}}; var change = false; - var clear = false; //标识当前是否点击了清空 + var clear = false; // 标识当前是否点击了清空 var isSearching = function () { return self.trigger.getSearcher().isSearching(); @@ -137,7 +137,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { }); }); - function showCounter() { + function showCounter () { if (isSearching()) { self.storeValue = {value: self.trigger.getValue()}; } else if (isPopupView()) { @@ -233,7 +233,7 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -259,4 +259,4 @@ BI.MultiTreeCombo = BI.inherit(BI.Single, { BI.MultiTreeCombo.EVENT_CONFIRM = "MultiTreeCombo.EVENT_CONFIRM"; -BI.shortcut('bi.multi_tree_combo', BI.MultiTreeCombo); \ No newline at end of file +BI.shortcut("bi.multi_tree_combo", BI.MultiTreeCombo); \ No newline at end of file diff --git a/src/widget/multitree/multi.tree.popup.js b/src/widget/multitree/multi.tree.popup.js index 349779d23..2ba7d906a 100644 --- a/src/widget/multitree/multi.tree.popup.js +++ b/src/widget/multitree/multi.tree.popup.js @@ -7,8 +7,8 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { _defaultConfig: function () { return BI.extend(BI.MultiTreePopup.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-popup', - maxWidth: 'auto', + baseCls: "bi-multi-tree-popup", + maxWidth: "auto", minWidth: 100, maxHeight: 400, onLoaded: BI.emptyFn @@ -25,7 +25,7 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { this.tree = BI.createWidget({ type: "bi.async_tree", height: 400, - cls:"popup-view-tree", + cls: "popup-view-tree", itemsCreator: opts.itemsCreator, onLoaded: opts.onLoaded }); @@ -37,7 +37,7 @@ BI.MultiTreePopup = BI.inherit(BI.Pane, { maxWidth: opts.maxWidth, minWidth: opts.minWidth, maxHeight: opts.maxHeight, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.tree }); @@ -94,4 +94,4 @@ BI.MultiTreePopup.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; BI.MultiTreePopup.EVENT_AFTERINIT = "EVENT_AFTERINIT"; -BI.shortcut('bi.multi_tree_popup_view', BI.MultiTreePopup); \ No newline at end of file +BI.shortcut("bi.multi_tree_popup_view", BI.MultiTreePopup); \ No newline at end of file diff --git a/src/widget/multitree/trigger/multi.tree.button.checkselected.js b/src/widget/multitree/trigger/multi.tree.button.checkselected.js index 993d1602e..e535f8b03 100644 --- a/src/widget/multitree/trigger/multi.tree.button.checkselected.js +++ b/src/widget/multitree/trigger/multi.tree.button.checkselected.js @@ -7,12 +7,12 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.MultiTreeCheckSelectedButton.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-check-selected-button', + baseCls: "bi-multi-tree-check-selected-button", itemsCreator: BI.emptyFn }); }, @@ -21,20 +21,20 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { BI.MultiTreeCheckSelectedButton.superclass._init.apply(this, arguments); var self = this; this.indicator = BI.createWidget({ - type: 'bi.icon_button', - cls: 'check-font trigger-check-selected', + type: "bi.icon_button", + cls: "check-font trigger-check-selected", width: 15, height: 15, stopPropagation: true }); this.checkSelected = BI.createWidget({ - type: 'bi.text_button', + type: "bi.text_button", cls: "trigger-check-selected", invisible: true, hgap: 4, text: this._const.checkSelected, - textAlign: 'center', + textAlign: "center", textHeight: 15 }); this.checkSelected.on(BI.Controller.EVENT_CHANGE, function () { @@ -49,7 +49,7 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { type: "bi.horizontal", element: this, items: [this.indicator, this.checkSelected] - }) + }); this.element.hover(function () { self.indicator.setVisible(false); @@ -68,4 +68,4 @@ BI.MultiTreeCheckSelectedButton = BI.inherit(BI.Single, { }); BI.MultiTreeCheckSelectedButton.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.multi_tree_check_selected_button', BI.MultiTreeCheckSelectedButton); \ No newline at end of file +BI.shortcut("bi.multi_tree_check_selected_button", BI.MultiTreeCheckSelectedButton); \ No newline at end of file diff --git a/src/widget/multitree/trigger/searcher.multi.tree.js b/src/widget/multitree/trigger/searcher.multi.tree.js index f958f519e..f17c38c8c 100644 --- a/src/widget/multitree/trigger/searcher.multi.tree.js +++ b/src/widget/multitree/trigger/searcher.multi.tree.js @@ -8,7 +8,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.MultiTreeSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-multi-tree-searcher', + baseCls: "bi-multi-tree-searcher", itemsCreator: BI.emptyFn, popup: {}, @@ -21,7 +21,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { BI.MultiTreeSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget({ - type: 'bi.multi_select_editor', + type: "bi.multi_select_editor", height: o.height, el: { type: "bi.simple_state_editor", @@ -116,7 +116,7 @@ BI.MultiTreeSearcher = BI.inherit(BI.Widget, { this.editor.setState(text); } - function getChildrenNode(ob) { + function getChildrenNode (ob) { var text = ""; var index = 0, size = BI.size(ob); BI.each(ob, function (name, children) { @@ -151,4 +151,4 @@ BI.MultiTreeSearcher.EVENT_CHANGE = "EVENT_CHANGE"; BI.MultiTreeSearcher.EVENT_START = "EVENT_START"; BI.MultiTreeSearcher.EVENT_STOP = "EVENT_STOP"; BI.MultiTreeSearcher.EVENT_PAUSE = "EVENT_PAUSE"; -BI.shortcut('bi.multi_tree_searcher', BI.MultiTreeSearcher); \ No newline at end of file +BI.shortcut("bi.multi_tree_searcher", BI.MultiTreeSearcher); \ No newline at end of file diff --git a/src/widget/numbereditor/number.editor.js b/src/widget/numbereditor/number.editor.js index 6a1034952..121d4b84b 100644 --- a/src/widget/numbereditor/number.editor.js +++ b/src/widget/numbereditor/number.editor.js @@ -16,7 +16,7 @@ BI.NumberEditor = BI.inherit(BI.Widget, { allowBlank: false, errorText: "", step: 1 - }) + }); }, _init: function () { @@ -80,7 +80,7 @@ BI.NumberEditor = BI.inherit(BI.Widget, { }); }, - //微调 + // 微调 _finetuning: function (add) { var v = BI.parseFloat(this.getValue()); this.setValue(v.add(add)); diff --git a/src/widget/numberinterval/numberinterval.js b/src/widget/numberinterval/numberinterval.js index dff3b594a..568bf447e 100644 --- a/src/widget/numberinterval/numberinterval.js +++ b/src/widget/numberinterval/numberinterval.js @@ -1,5 +1,5 @@ -//小于号的值为:0,小于等于号的值为:1 -//closeMIn:最小值的符号,closeMax:最大值的符号 +// 小于号的值为:0,小于等于号的值为:1 +// closeMIn:最小值的符号,closeMax:最大值的符号 /** * Created by roy on 15/9/17. * @@ -20,16 +20,16 @@ BI.NumberInterval = BI.inherit(BI.Single, { numTip: "" }, _defaultConfig: function () { - var conf = BI.NumberInterval.superclass._defaultConfig.apply(this, arguments) + var conf = BI.NumberInterval.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-number-interval", height: 25, validation: "valid" - }) + }); }, _init: function () { var self = this, c = this.constants, o = this.options; - BI.NumberInterval.superclass._init.apply(this, arguments) + BI.NumberInterval.superclass._init.apply(this, arguments); this.smallEditor = BI.createWidget({ type: "bi.editor", height: o.height - 2, @@ -104,21 +104,21 @@ BI.NumberInterval = BI.inherit(BI.Single, { }] }); - //this.smallCombo = BI.createWidget({ + // this.smallCombo = BI.createWidget({ // type: "bi.number_interval_combo", // cls: "number-interval-small-combo", // height: o.height, // value: o.closemin ? 1 : 0, // offsetStyle: "left" - //}); + // }); // - //this.bigCombo = BI.createWidget({ + // this.bigCombo = BI.createWidget({ // type: "bi.number_interval_combo", // cls: "number-interval-big-combo", // height: o.height, // value: o.closemax ? 1 : 0, // offsetStyle: "left" - //}); + // }); this.smallCombo = BI.createWidget({ type: "bi.icon_combo", cls: "number-interval-small-combo bi-border", @@ -248,42 +248,42 @@ BI.NumberInterval = BI.inherit(BI.Single, { self.element.removeClass("number-error"); o.validation = "invalid"; return c.typeError; - } else { - if (BI.isEmptyString(self.smallEditor.getValue()) || BI.isEmptyString(self.bigEditor.getValue())) { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } else { - var smallValue = parseFloat(self.smallEditor.getValue()), bigValue = parseFloat(self.bigEditor.getValue()), - bigComboValue = self.bigCombo.getValue(), smallComboValue = self.smallCombo.getValue(); - if (bigComboValue[0] === c.less_equal && smallComboValue[0] === c.less_equal) { - if (smallValue > bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.numberError; - } else { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } - } else { - if (smallValue > bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.numberError; - } else if (smallValue === bigValue) { - self.element.addClass("number-error"); - o.validation = "invalid"; - return c.signalError; - } else { - self.element.removeClass("number-error"); - o.validation = "valid"; - return ""; - } - } + } + if (BI.isEmptyString(self.smallEditor.getValue()) || BI.isEmptyString(self.bigEditor.getValue())) { + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + } + var smallValue = parseFloat(self.smallEditor.getValue()), bigValue = parseFloat(self.bigEditor.getValue()), + bigComboValue = self.bigCombo.getValue(), smallComboValue = self.smallCombo.getValue(); + if (bigComboValue[0] === c.less_equal && smallComboValue[0] === c.less_equal) { + if (smallValue > bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.numberError; } - + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + } + if (smallValue > bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.numberError; + } else if (smallValue === bigValue) { + self.element.addClass("number-error"); + o.validation = "invalid"; + return c.signalError; + } + self.element.removeClass("number-error"); + o.validation = "valid"; + return ""; + + + + + }, _setTitle: function (v) { @@ -314,10 +314,10 @@ BI.NumberInterval = BI.inherit(BI.Single, { }); break; default : - return + return; } - }) + }); }, _setBlurEvent: function (w) { var c = this.constants, self = this; @@ -338,18 +338,18 @@ BI.NumberInterval = BI.inherit(BI.Single, { default: self._setTitle(""); } - }) + }); }, _setErrorEvent: function (w) { - var c = this.constants, self = this + var c = this.constants, self = this; w.on(BI.Editor.EVENT_ERROR, function () { self._checkValidation(); BI.Bubbles.show(c.typeError, BI.i18nText("BI-Numerical_Interval_Input_Data"), self, { offsetStyle: "center" }); self.fireEvent(BI.NumberInterval.EVENT_ERROR); - }) + }); }, @@ -372,7 +372,7 @@ BI.NumberInterval = BI.inherit(BI.Single, { default: self.fireEvent(BI.NumberInterval.EVENT_VALID); } - }) + }); }, @@ -422,7 +422,7 @@ BI.NumberInterval = BI.inherit(BI.Single, { self.fireEvent(BI.NumberInterval.EVENT_CHANGE); self.fireEvent(BI.NumberInterval.EVENT_VALID); } - }) + }); }, isStateValid: function () { @@ -455,12 +455,12 @@ BI.NumberInterval = BI.inherit(BI.Single, { this.bigTip.setVisible(false); }, - setNumTip: function(numTip) { + setNumTip: function (numTip) { this.smallTip.setText(numTip); this.bigTip.setText(numTip); }, - getNumTip: function() { + getNumTip: function () { return this.smallTip.getText(); }, @@ -485,18 +485,18 @@ BI.NumberInterval = BI.inherit(BI.Single, { if (!BI.isNull(data.closemin)) { if (data.closemin === true) { - combo_value = 1 + combo_value = 1; } else { - combo_value = 0 + combo_value = 0; } self.smallCombo.setValue(combo_value); } if (!BI.isNull(data.closemax)) { if (data.closemax === true) { - combo_value = 1 + combo_value = 1; } else { - combo_value = 0 + combo_value = 0; } self.bigCombo.setValue(combo_value); } @@ -508,15 +508,15 @@ BI.NumberInterval = BI.inherit(BI.Single, { value.min = self.smallEditor.getValue(); value.max = self.bigEditor.getValue(); if (minComboValue[0] === 0) { - value.closemin = false + value.closemin = false; } else { - value.closemin = true + value.closemin = true; } if (maxComboValue[0] === 0) { - value.closemax = false + value.closemax = false; } else { - value.closemax = true + value.closemax = true; } return value; } diff --git a/src/widget/pagetable/pagetable.cell.js b/src/widget/pagetable/pagetable.cell.js index c90c400cc..ea50da922 100644 --- a/src/widget/pagetable/pagetable.cell.js +++ b/src/widget/pagetable/pagetable.cell.js @@ -12,7 +12,7 @@ BI.PageTableCell = BI.inherit(BI.Widget, { baseCls: "bi-page-table-cell", text: "", title: "" - }) + }); }, _init: function () { diff --git a/src/widget/pagetable/pagetable.js b/src/widget/pagetable/pagetable.js index a609728f5..06cde7b14 100644 --- a/src/widget/pagetable/pagetable.js +++ b/src/widget/pagetable/pagetable.js @@ -20,8 +20,8 @@ BI.PageTable = BI.inherit(BI.Widget, { }, pager: { horizontal: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -29,8 +29,8 @@ BI.PageTable = BI.inherit(BI.Widget, { lastPage: BI.emptyFn }, vertical: { - pages: false, //总页数 - curr: 1, //初始化当前页, pages为数字时可用 + pages: false, // 总页数 + curr: 1, // 初始化当前页, pages为数字时可用 hasPrev: BI.emptyFn, hasNext: BI.emptyFn, @@ -41,11 +41,11 @@ BI.PageTable = BI.inherit(BI.Widget, { itemsCreator: BI.emptyFn, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -61,9 +61,9 @@ BI.PageTable = BI.inherit(BI.Widget, { sequenceCellStyleGetter: BI.emptyFn, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -104,7 +104,7 @@ BI.PageTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -156,7 +156,7 @@ BI.PageTable = BI.inherit(BI.Widget, { right: 0, bottom: 0 }] - }) + }); }, setHPage: function (v) { @@ -275,4 +275,4 @@ BI.PageTable = BI.inherit(BI.Widget, { BI.PageTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.page_table', BI.PageTable); \ No newline at end of file +BI.shortcut("bi.page_table", BI.PageTable); \ No newline at end of file diff --git a/src/widget/pathchooser/pathchooser.js b/src/widget/pathchooser/pathchooser.js index 176c1cffa..3ea956ad5 100644 --- a/src/widget/pathchooser/pathchooser.js +++ b/src/widget/pathchooser/pathchooser.js @@ -16,7 +16,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return BI.extend(BI.PathChooser.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-path-chooser", items: [] - }) + }); }, _init: function () { @@ -30,7 +30,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return { type: "bi.path_region", title: self.texts[region] || region - } + }; })); this.regionMap = {}; BI.each(regions, function (i, region) { @@ -123,7 +123,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { left: x - 6.5, top: y - 6.5 }] - }) + }); }, _drawLine: function (start, lines) { @@ -135,7 +135,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { this.pathes[start] = []; } var startRegionIndex = this.getRegionIndexById(start); - //start所在的位置,然后接着往下画其他的路径 + // start所在的位置,然后接着往下画其他的路径 var offset = this.regions[startRegionIndex].getIndexByValue(start); BI.each(lines, function (i, line) { self.pathes[start][i] = []; @@ -154,14 +154,14 @@ BI.PathChooser = BI.inherit(BI.Widget, { self.pathes[start][i].push({ x: sleft - 50, y: stop - }) + }); } else if (idx === 0) { radioStartX = sleft + 50; path += "M" + sleft + "," + stop; self.pathes[start][i].push({ x: sleft, y: stop - }) + }); } else { radioStartX = sleft + 50; path += "M" + sleft + "," + 47.5 + "L" + (sleft + 50) + "," + 47.5 + "L" + (sleft + 50) + "," + stop; @@ -204,13 +204,13 @@ BI.PathChooser = BI.inherit(BI.Widget, { var graph = self.svg.path(path) .attr({ stroke: idx === 0 ? self._const.selectLineColor : self._const.lineColor, - 'stroke-dasharray': '-' + "stroke-dasharray": "-" }); self.lines[start].push(graph); if (lines.length > 1) { self.lines[start][0].toFront(); } - //第一个元素无论有多少个都要显示radio + // 第一个元素无论有多少个都要显示radio if (BI.contains(self.start, start)) { self.lines[self.regions[0].getValueByIndex(0)][0].toFront(); } @@ -237,7 +237,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { self.regionIndexes[k].push(regionIndex); } }); - }) + }); }); BI.each(routes, function (k, route) { self._drawLine(k, route); @@ -305,16 +305,16 @@ BI.PathChooser = BI.inherit(BI.Widget, { if (parent.getChildIndex(item.value) === -1) { tree.addNode(parent, node); } - }) + }); }); - //算出区域列表 + // 算出区域列表 tree.traverse(function (node) { BI.each(node.getChildren(), function (i, child) { if (BI.contains(regions, child.get("region"))) { var index1 = BI.indexOf(regions, node.get("region")); var index2 = BI.indexOf(regions, child.get("region")); - //交换区域 + // 交换区域 if (index1 > index2) { var t = regions[index2]; for (var j = index2; j < index1; j++) { @@ -329,14 +329,14 @@ BI.PathChooser = BI.inherit(BI.Widget, { }); this._createRegions(regions); - //算出节点 + // 算出节点 BI.each(branches, function (k, branch) { if (branch < max) { delete branches[k]; } }); - //过滤节点 + // 过滤节点 var nodes = []; var n = tree.getRoot(); while (n && n.getChildrenLength() === 1) { @@ -354,7 +354,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { } }); - //填充节点 + // 填充节点 var routes = {}; var s, e; for (var i = 0, len = nodes.length; i < len + 1; i++) { @@ -395,7 +395,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { return true; } } - }) + }); }); } this.routes = routes; @@ -460,7 +460,7 @@ BI.PathChooser = BI.inherit(BI.Widget, { if (array.length > 0) { result.push(array); } - //画这n条路径 + // 画这n条路径 BI.each(result, function (idx, path) { var start = path[0]; var index = BI.findIndex(self.routes[start], function (idx, p) { diff --git a/src/widget/pathchooser/pathregion.js b/src/widget/pathchooser/pathregion.js index 0fa33978b..0409ab0db 100644 --- a/src/widget/pathchooser/pathregion.js +++ b/src/widget/pathchooser/pathregion.js @@ -12,7 +12,7 @@ BI.PathRegion = BI.inherit(BI.Widget, { baseCls: "bi-path-region bi-background", width: 80, title: "" - }) + }); }, _init: function () { @@ -33,7 +33,7 @@ BI.PathRegion = BI.inherit(BI.Widget, { bgap: 5, hgap: 10, items: [title] - }) + }); }, hasItem: function (val) { diff --git a/src/widget/previewtable/previewtable.cell.js b/src/widget/previewtable/previewtable.cell.js index cc906530d..90436cbe2 100644 --- a/src/widget/previewtable/previewtable.cell.js +++ b/src/widget/previewtable/previewtable.cell.js @@ -26,7 +26,7 @@ BI.PreviewTableCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); -BI.shortcut('bi.preview_table_cell', BI.PreviewTableCell); \ No newline at end of file +BI.shortcut("bi.preview_table_cell", BI.PreviewTableCell); \ No newline at end of file diff --git a/src/widget/previewtable/previewtable.header.cell.js b/src/widget/previewtable/previewtable.header.cell.js index 18c257097..91df54862 100644 --- a/src/widget/previewtable/previewtable.header.cell.js +++ b/src/widget/previewtable/previewtable.header.cell.js @@ -26,7 +26,7 @@ BI.PreviewTableHeaderCell = BI.inherit(BI.Widget, { height: this.options.height, text: this.options.text, value: this.options.value - }) + }); } }); -BI.shortcut('bi.preview_table_header_cell', BI.PreviewTableHeaderCell); \ No newline at end of file +BI.shortcut("bi.preview_table_header_cell", BI.PreviewTableHeaderCell); \ No newline at end of file diff --git a/src/widget/previewtable/previewtable.js b/src/widget/previewtable/previewtable.js index 8e8bf5ba0..eb73d438d 100644 --- a/src/widget/previewtable/previewtable.js +++ b/src/widget/previewtable/previewtable.js @@ -62,11 +62,11 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }); }, - //是否有自适应调节的列,即列宽为"" + // 是否有自适应调节的列,即列宽为"" _hasAdaptCol: function (columnSize) { return BI.any(columnSize, function (i, size) { return size === ""; - }) + }); }, _isPercentage: function (columnSize) { @@ -76,7 +76,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { _adjustColumns: function () { var self = this, o = this.options; if (o.isNeedFreeze === true) { - //如果存在百分比的情况 + // 如果存在百分比的情况 if (this._isPercentage(o.columnSize)) { if (this._hasAdaptCol(o.columnSize)) { var findCols = [], remain = 0; @@ -113,7 +113,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { this.table.setColumnSize(isRight ? (notFreezeSize.concat(freezeSize)) : (freezeSize.concat(notFreezeSize))); } } else { - //如果存在自适应宽度的列或者是百分比计算的列,需要将整个表宽设为100% + // 如果存在自适应宽度的列或者是百分比计算的列,需要将整个表宽设为100% if (this._hasAdaptCol(o.columnSize) || this._isPercentage(o.columnSize)) { this.table.setRegionColumnSize(["100%"]); } @@ -157,11 +157,11 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }, getScrollRegionColumnSize: function () { - return this.table.getScrollRegionColumnSize() + return this.table.getScrollRegionColumnSize(); }, getScrollRegionRowSize: function () { - return this.table.getScrollRegionRowSize() + return this.table.getScrollRegionRowSize(); }, hasVerticalScroll: function () { @@ -173,7 +173,7 @@ BI.PreviewTable = BI.inherit(BI.Widget, { }, setLeftHorizontalScroll: function (scrollLeft) { - return this.table.setLeftHorizontalScroll(scrollLeft) + return this.table.setLeftHorizontalScroll(scrollLeft); }, setRightHorizontalScroll: function (scrollLeft) { @@ -201,4 +201,4 @@ BI.PreviewTable = BI.inherit(BI.Widget, { } }); BI.PreviewTable.EVENT_CHANGE = "PreviewTable.EVENT_CHANGE"; -BI.shortcut('bi.preview_table', BI.PreviewTable); \ No newline at end of file +BI.shortcut("bi.preview_table", BI.PreviewTable); \ No newline at end of file diff --git a/src/widget/quarter/combo.quarter.js b/src/widget/quarter/combo.quarter.js index eec309f80..93194ea5e 100644 --- a/src/widget/quarter/combo.quarter.js +++ b/src/widget/quarter/combo.quarter.js @@ -82,4 +82,4 @@ BI.QuarterCombo = BI.inherit(BI.Widget, { BI.QuarterCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.QuarterCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.quarter_combo', BI.QuarterCombo); \ No newline at end of file +BI.shortcut("bi.quarter_combo", BI.QuarterCombo); \ No newline at end of file diff --git a/src/widget/quarter/popup.quarter.js b/src/widget/quarter/popup.quarter.js index 4fedb4e6a..6babfe41b 100644 --- a/src/widget/quarter/popup.quarter.js +++ b/src/widget/quarter/popup.quarter.js @@ -58,7 +58,7 @@ BI.QuarterPopup = BI.inherit(BI.Widget, { if (type === BI.Events.CLICK) { self.fireEvent(BI.MonthPopup.EVENT_CHANGE); } - }) + }); }, getValue: function () { diff --git a/src/widget/quarter/trigger.quarter.js b/src/widget/quarter/trigger.quarter.js index 1429f56f4..d1f66375b 100644 --- a/src/widget/quarter/trigger.quarter.js +++ b/src/widget/quarter/trigger.quarter.js @@ -64,7 +64,7 @@ BI.QuarterTrigger = BI.inherit(BI.Trigger, { BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor diff --git a/src/widget/relationview/relationview.item.js b/src/widget/relationview/relationview.item.js index 88d435536..2a9f037ed 100644 --- a/src/widget/relationview/relationview.item.js +++ b/src/widget/relationview/relationview.item.js @@ -57,4 +57,4 @@ BI.RelationViewItem = BI.inherit(BI.BasicButton, { this.element[b ? "addClass" : "removeClass"]("active"); } }); -BI.shortcut('bi.relation_view_item', BI.RelationViewItem); \ No newline at end of file +BI.shortcut("bi.relation_view_item", BI.RelationViewItem); \ No newline at end of file diff --git a/src/widget/relationview/relationview.js b/src/widget/relationview/relationview.js index 1d30a4498..58bce3244 100644 --- a/src/widget/relationview/relationview.js +++ b/src/widget/relationview/relationview.js @@ -32,7 +32,7 @@ BI.RelationView = BI.inherit(BI.Widget, { widths[j] = BI.MIN; } widths[j] = Math.max(widths[j], obj.getWidth()); - }) + }); }); return widths; }, @@ -42,7 +42,7 @@ BI.RelationView = BI.inherit(BI.Widget, { BI.each(this.views, function (i, items) { BI.each(items, function (j, obj) { heights[i] = Math.max(heights[i], obj.getHeight()); - }) + }); }); return heights; }, @@ -73,7 +73,7 @@ BI.RelationView = BI.inherit(BI.Widget, { }); }, - previewRelationTables: function(relationTables, show) { + previewRelationTables: function (relationTables, show) { if (!show) { BI.each(this.storeViews, function (i, view) { view.toggleRegion(true); @@ -110,7 +110,7 @@ BI.RelationView = BI.inherit(BI.Widget, { type: "bi.svg" }); - //算出所有的区域和关联 + // 算出所有的区域和关联 var regions = this.regions = {}, relations = this.relations = {}; BI.each(items, function (i, item) { var pr = item.primary.region, fr = item.foreign && item.foreign.region; @@ -134,7 +134,7 @@ BI.RelationView = BI.inherit(BI.Widget, { } pr && fr && relations[pr][fr].push(item); }); - //求拓扑 + // 求拓扑 var topology = []; var rs = BI.clone(regions), store = {}; while (!BI.isEmpty(rs)) { @@ -150,7 +150,7 @@ BI.RelationView = BI.inherit(BI.Widget, { delete rs[k]; }); } - //构建视图 + // 构建视图 var views = this.views = {}, storeViews = this.storeViews = {}, indexes = this.indexes = {}; var verticals = []; BI.each(topology, function (i, items) { @@ -187,16 +187,16 @@ BI.RelationView = BI.inherit(BI.Widget, { verticals.push({ type: "bi.horizontal", items: horizontal - }) + }); }); - //求每一行的高度 + // 求每一行的高度 var heights = this._calculateHeights(); - //求每一列的宽度 + // 求每一列的宽度 var widths = this._calculateWidths(); - //求相对宽度和高度 + // 求相对宽度和高度 var offsetWidths = [0], offsetHeights = [0]; BI.each(heights, function (i, h) { if (i === 0) { @@ -211,8 +211,8 @@ BI.RelationView = BI.inherit(BI.Widget, { offsetWidths[i] = offsetWidths[i - 1] + widths[i - 1]; }); - //画线 - var lines = this.lines = {};//缓存所有的线 + // 画线 + var lines = this.lines = {};// 缓存所有的线 BI.each(relations, function (start, rs) { BI.each(rs, function (end, relation) { var startIndex = indexes[start], endIndex = indexes[end]; @@ -276,7 +276,7 @@ BI.RelationView = BI.inherit(BI.Widget, { } path += "M" + si.x + "," + si.y + "L" + ei.x + "," + ei.y; var line = lines[start][end] = self.svg.path(path) - .attr({"stroke": c.lineColor, "stroke-width": "2"}) + .attr({stroke: c.lineColor, "stroke-width": "2"}) .hover(function () { line.attr("stroke", c.selectLineColor).toFront(); storeViews[start].setValue(relation[0].primary.value); @@ -316,4 +316,4 @@ BI.RelationView = BI.inherit(BI.Widget, { }); BI.RelationView.EVENT_CHANGE = "RelationView.EVENT_CHANGE"; BI.RelationView.EVENT_PREVIEW = "EVENT_PREVIEW"; -BI.shortcut('bi.relation_view', BI.RelationView); \ No newline at end of file +BI.shortcut("bi.relation_view", BI.RelationView); \ No newline at end of file diff --git a/src/widget/relationview/relationview.region.container.js b/src/widget/relationview/relationview.region.container.js index a0d8c7dc5..cdbdf69b1 100644 --- a/src/widget/relationview/relationview.region.container.js +++ b/src/widget/relationview/relationview.region.container.js @@ -55,7 +55,7 @@ BI.RelationViewRegionContainer = BI.inherit(BI.Widget, { return this.region.getHeight(); }, - //获取上方开始划线的位置 + // 获取上方开始划线的位置 getTopLeftPosition: function () { return this.region.getTopLeftPosition(); }, @@ -84,7 +84,7 @@ BI.RelationViewRegionContainer = BI.inherit(BI.Widget, { v === true ? this.region.element.fadeIn() : this.region.element.fadeOut(); }, - setPreviewSelected: function(v) { + setPreviewSelected: function (v) { this.region.setPreviewSelected(v); } }); diff --git a/src/widget/relationview/relationview.region.js b/src/widget/relationview/relationview.region.js index f84937a46..f85f9f555 100644 --- a/src/widget/relationview/relationview.region.js +++ b/src/widget/relationview/relationview.region.js @@ -42,11 +42,11 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { value: o.value, textAlign: "left" }); - //title放body上 + // title放body上 if (BI.isKey(o.header)) { this.title.setTitle(o.header, { container: "body" - }) + }); } this.button_group = BI.createWidget({ @@ -71,7 +71,7 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { }], hgap: 25, vgap: 20 - }) + }); }, _createItems: function (items) { @@ -87,7 +87,7 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { self.setValue([]); self.fireEvent(BI.RelationViewRegion.EVENT_HOVER_OUT, item.value); } - }) + }); }); }, @@ -107,51 +107,51 @@ BI.RelationViewRegion = BI.inherit(BI.BasicButton, { return this.button_group.getAllButtons().length * 25 + 25 + 2 * 20 + 3; }, - //获取上方开始划线的位置 + // 获取上方开始划线的位置 getTopLeftPosition: function () { return { x: 25 + 10, y: 20 - } + }; }, getTopRightPosition: function () { return { x: this.getWidth() - 25 - 10, y: 20 - } + }; }, getBottomPosition: function () { return { x: 25 + 10, y: this.getHeight() - 20 - } + }; }, getLeftPosition: function () { return { x: 25, y: 20 + 10 - } + }; }, getRightPosition: function () { return { x: this.getWidth() - 25, y: 20 + 10 - } + }; }, setValue: function (v) { this.button_group.setValue(v); }, - setPreviewSelected: function(v) { + setPreviewSelected: function (v) { this.preview.setSelected(v); } }); BI.RelationViewRegion.EVENT_HOVER_IN = "RelationViewRegion.EVENT_HOVER_IN"; BI.RelationViewRegion.EVENT_HOVER_OUT = "RelationViewRegion.EVENT_HOVER_OUT"; BI.RelationViewRegion.EVENT_PREVIEW = "RelationViewRegion.EVENT_PREVIEW"; -BI.shortcut('bi.relation_view_region', BI.RelationViewRegion); \ No newline at end of file +BI.shortcut("bi.relation_view_region", BI.RelationViewRegion); \ No newline at end of file diff --git a/src/widget/responsivetable/responsivetable.js b/src/widget/responsivetable/responsivetable.js index c6817113d..eb9329b7b 100644 --- a/src/widget/responsivetable/responsivetable.js +++ b/src/widget/responsivetable/responsivetable.js @@ -14,12 +14,12 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.ResponisveTable.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-responsive-table", - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 - mergeRule: function (row1, row2) { //合并规则, 默认相等时合并 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 + mergeRule: function (row1, row2) { // 合并规则, 默认相等时合并 return BI.isEqual(row1, row2); }, @@ -32,9 +32,9 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { header: [], footer: false, - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -65,7 +65,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { header: o.header, footer: o.footer, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -87,7 +87,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { self.fireEvent(BI.Table.EVENT_TABLE_BEFORE_REGION_RESIZE, arguments); }); this.table.on(BI.Table.EVENT_TABLE_REGION_RESIZE, function () { - //important:在冻结并自适应列宽的情况下要随时变更表头宽度 + // important:在冻结并自适应列宽的情况下要随时变更表头宽度 if (o.isNeedResize === true && self._isAdaptiveColumn()) { self._resizeHeader(); } @@ -117,7 +117,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { if (o.isNeedFreeze === true) { var regionColumnSize = this.table.getRegionColumnSize(); var maxWidth = this.table.element.width(); - if (!regionColumnSize[0] || (regionColumnSize[0] === 'fill') || regionColumnSize[0] > maxWidth || regionColumnSize[1] > maxWidth) { + if (!regionColumnSize[0] || (regionColumnSize[0] === "fill") || regionColumnSize[0] > maxWidth || regionColumnSize[1] > maxWidth) { var freezeCols = o.freezeCols; if (freezeCols.length === 0) { this.table.setRegionColumnSize([0, "fill"]); @@ -146,7 +146,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { columnSizeRight.push(size); } }); - //因为有边框,所以加上数组长度的参数调整 + // 因为有边框,所以加上数组长度的参数调整 var sumLeft = BI.sum(columnSizeLeft) + columnSizeLeft.length, sumRight = BI.sum(columnSizeRight) + columnSizeRight.length; return { @@ -154,7 +154,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { sumRight: sumRight, left: columnSizeLeft, right: columnSizeRight - } + }; } return { size: columnSize, @@ -169,7 +169,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { _resizeHeader: function () { var self = this, o = this.options; if (o.isNeedFreeze === true) { - //若是当前处于自适应调节阶段 + // 若是当前处于自适应调节阶段 if (this._isAdaptiveColumn()) { var columnSize = this.table.getCalculateColumnSize(); this.table.setHeaderColumnSize(columnSize); @@ -188,10 +188,10 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { block = self._getBlockSize(); if (columnSizeLeft[columnSizeLeft.length - 1] < block.left[block.left.length - 1]) { - columnSizeLeft[columnSizeLeft.length - 1] = block.left[block.left.length - 1] + columnSizeLeft[columnSizeLeft.length - 1] = block.left[block.left.length - 1]; } if (columnSizeRight[columnSizeRight.length - 1] < block.right[block.right.length - 1]) { - columnSizeRight[columnSizeRight.length - 1] = block.right[block.right.length - 1] + columnSizeRight[columnSizeRight.length - 1] = block.right[block.right.length - 1]; } self.table.setColumnSize(columnSizeLeft.concat(columnSizeRight)); @@ -211,7 +211,7 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { block = this._getBlockSize(); if (size[size.length - 1] < block.size[block.size.length - 1]) { - size[size.length - 1] = block.size[block.size.length - 1] + size[size.length - 1] = block.size[block.size.length - 1]; } this.table.setColumnSize(size); } @@ -359,4 +359,4 @@ BI.ResponisveTable = BI.inherit(BI.Widget, { } } }); -BI.shortcut('bi.responsive_table', BI.ResponisveTable); \ No newline at end of file +BI.shortcut("bi.responsive_table", BI.ResponisveTable); \ No newline at end of file diff --git a/src/widget/selecttree/nodes/node.first.plus.js b/src/widget/selecttree/nodes/node.first.plus.js index bf230e04b..9cc5e3a88 100644 --- a/src/widget/selecttree/nodes/node.first.plus.js +++ b/src/widget/selecttree/nodes/node.first.plus.js @@ -17,7 +17,7 @@ BI.SelectTreeFirstPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeFirstPlusGroupNode.superclass._init.apply(this, arguments); diff --git a/src/widget/selecttree/nodes/node.last.plus.js b/src/widget/selecttree/nodes/node.last.plus.js index 213b3f9f0..ed3e4f51f 100644 --- a/src/widget/selecttree/nodes/node.last.plus.js +++ b/src/widget/selecttree/nodes/node.last.plus.js @@ -17,7 +17,7 @@ BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeLastPlusGroupNode.superclass._init.apply(this, arguments); @@ -25,7 +25,7 @@ BI.SelectTreeLastPlusGroupNode = BI.inherit(BI.NodeButton, { this.checkbox = BI.createWidget({ type: "bi.last_tree_node_checkbox", stopPropagation: true - }) + }); this.text = BI.createWidget({ type: "bi.label", textAlign: "left", diff --git a/src/widget/selecttree/nodes/node.mid.plus.js b/src/widget/selecttree/nodes/node.mid.plus.js index 0e0dbdd5b..9c0736319 100644 --- a/src/widget/selecttree/nodes/node.mid.plus.js +++ b/src/widget/selecttree/nodes/node.mid.plus.js @@ -17,7 +17,7 @@ BI.SelectTreeMidPlusGroupNode = BI.inherit(BI.NodeButton, { readonly: true, open: false, height: 25 - }) + }); }, _init: function () { BI.SelectTreeMidPlusGroupNode.superclass._init.apply(this, arguments); diff --git a/src/widget/selecttree/selecttree.popup.js b/src/widget/selecttree/selecttree.popup.js index 13a8b5926..b0933756b 100644 --- a/src/widget/selecttree/selecttree.popup.js +++ b/src/widget/selecttree/selecttree.popup.js @@ -52,7 +52,7 @@ BI.SelectTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.level_tree', + type: "bi.level_tree", expander: { type: "bi.select_tree_expander", isDefaultInit: true diff --git a/src/widget/sequencetable/dynamicnumber.sequencetable.js b/src/widget/sequencetable/dynamicnumber.sequencetable.js index b124eee5e..7d1ad1f69 100644 --- a/src/widget/sequencetable/dynamicnumber.sequencetable.js +++ b/src/widget/sequencetable/dynamicnumber.sequencetable.js @@ -21,7 +21,7 @@ BI.SequenceTableDynamicNumber = BI.inherit(BI.SequenceTableTreeNumber, { var result = []; var count = this._getStart(nodes); - function getLeafCount(node) { + function getLeafCount (node) { var cnt = 0; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { @@ -68,4 +68,4 @@ BI.SequenceTableDynamicNumber = BI.inherit(BI.SequenceTableTreeNumber, { return result; } }); -BI.shortcut('bi.sequence_table_dynamic_number', BI.SequenceTableDynamicNumber); \ No newline at end of file +BI.shortcut("bi.sequence_table_dynamic_number", BI.SequenceTableDynamicNumber); \ No newline at end of file diff --git a/src/widget/sequencetable/listnumber.sequencetable.js b/src/widget/sequencetable/listnumber.sequencetable.js index 94e288233..942e4daf6 100644 --- a/src/widget/sequencetable/listnumber.sequencetable.js +++ b/src/widget/sequencetable/listnumber.sequencetable.js @@ -11,16 +11,16 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { baseCls: "bi-sequence-table-list-number", isNeedFreeze: false, scrollTop: 0, - startSequence: 1,//开始的序号 + startSequence: 1, // 开始的序号 headerRowSize: 25, rowSize: 25, sequenceHeaderCreator: null, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [], @@ -141,7 +141,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { styleGetter: function (index) { return function () { return o.sequenceCellStyleGetter(self.start + i - 1); - } + }; }(cnt) })); renderedCells.push({ @@ -154,7 +154,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { renderedKeys.push(this.start + i); } - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (BI.deepContains(self.renderedKeys, key)) { @@ -177,7 +177,7 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { }); var addedItems = []; BI.each(addSet, function (index) { - addedItems.push(renderedCells[index]) + addedItems.push(renderedCells[index]); }); BI.createWidget({ type: "bi.absolute", @@ -241,4 +241,4 @@ BI.SequenceTableListNumber = BI.inherit(BI.Widget, { this._populate(); } }); -BI.shortcut('bi.sequence_table_list_number', BI.SequenceTableListNumber); \ No newline at end of file +BI.shortcut("bi.sequence_table_list_number", BI.SequenceTableListNumber); \ No newline at end of file diff --git a/src/widget/sequencetable/sequencetable.js b/src/widget/sequencetable/sequencetable.js index 1b6380042..5b197052b 100644 --- a/src/widget/sequencetable/sequencetable.js +++ b/src/widget/sequencetable/sequencetable.js @@ -19,11 +19,11 @@ BI.SequenceTable = BI.inherit(BI.Widget, { isNeedResize: true, isResizeAdapt: false, - isNeedFreeze: false,//是否需要冻结单元格 - freezeCols: [], //冻结的列号,从0开始,isNeedFreeze为true时生效 + isNeedFreeze: false, // 是否需要冻结单元格 + freezeCols: [], // 冻结的列号,从0开始,isNeedFreeze为true时生效 - isNeedMerge: false,//是否需要合并单元格 - mergeCols: [], //合并的单元格列号 + isNeedMerge: false, // 是否需要合并单元格 + mergeCols: [], // 合并的单元格列号 mergeRule: BI.emptyFn, columnSize: [], @@ -39,14 +39,14 @@ BI.SequenceTable = BI.inherit(BI.Widget, { sequenceCellStyleGetter: BI.emptyFn, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [], showSequence: false, - startSequence: 1//开始的序号 + startSequence: 1// 开始的序号 }); }, @@ -100,7 +100,7 @@ BI.SequenceTable = BI.inherit(BI.Widget, { header: o.header, items: o.items, - //交叉表头 + // 交叉表头 crossHeader: o.crossHeader, crossItems: o.crossItems }); @@ -250,4 +250,4 @@ BI.SequenceTable = BI.inherit(BI.Widget, { BI.SequenceTable.superclass.destroy.apply(this, arguments); } }); -BI.shortcut('bi.sequence_table', BI.SequenceTable); \ No newline at end of file +BI.shortcut("bi.sequence_table", BI.SequenceTable); \ No newline at end of file diff --git a/src/widget/sequencetable/treenumber.sequencetable.js b/src/widget/sequencetable/treenumber.sequencetable.js index 057a5e6c2..efe15c5fd 100644 --- a/src/widget/sequencetable/treenumber.sequencetable.js +++ b/src/widget/sequencetable/treenumber.sequencetable.js @@ -10,7 +10,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { return BI.extend(BI.SequenceTableTreeNumber.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-sequence-table-tree-number", isNeedFreeze: false, - startSequence: 1,//开始的序号 + startSequence: 1, // 开始的序号 scrollTop: 0, headerRowSize: 25, rowSize: 25, @@ -18,9 +18,9 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { sequenceHeaderCreator: null, header: [], - items: [], //二维数组 + items: [], // 二维数组 - //交叉表头 + // 交叉表头 crossHeader: [], crossItems: [] }); @@ -65,7 +65,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { el: this.scrollContainer }] }); - //缓存第一行对应的序号 + // 缓存第一行对应的序号 this.start = this.options.startSequence; this.cache = {}; this._nextState(); @@ -78,8 +78,8 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { var start = this.start; var cnt = this.start; - function track(node) { - //如果已经有缓存了就不改计数了,复杂表会出现这种情况 + function track (node) { + // 如果已经有缓存了就不改计数了,复杂表会出现这种情况 self.cache[node.text || node.value] || (self.cache[node.text || node.value] = cnt); cnt++; } @@ -92,7 +92,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { start = cnt = self.cache[child.text || child.value]; } } - track(child) + track(child); }); } }); @@ -123,13 +123,13 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { var result = []; var count = this._getStart(nodes); - function getLeafCount(node) { + function getLeafCount (node) { var cnt = 0; if (BI.isNotEmptyArray(node.children)) { BI.each(node.children, function (index, child) { cnt += getLeafCount(child); }); - if (/**node.children.length > 1 && **/BI.isNotEmptyArray(node.values)) { + if (/** node.children.length > 1 && **/BI.isNotEmptyArray(node.values)) { cnt++; } } else { @@ -290,7 +290,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { } : function (key) { return function () { return o.sequenceCellStyleGetter(key); - } + }; }(numbers[key].index) }, numbers[key])); renderedCells.push({ @@ -302,7 +302,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { } }); - //已存在的, 需要添加的和需要删除的 + // 已存在的, 需要添加的和需要删除的 var existSet = {}, addSet = {}, deleteArray = []; BI.each(renderedKeys, function (i, key) { if (BI.deepContains(self.renderedKeys, key)) { @@ -325,7 +325,7 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { }); var addedItems = []; BI.each(addSet, function (index) { - addedItems.push(renderedCells[index]) + addedItems.push(renderedCells[index]); }); BI.createWidget({ type: "bi.absolute", @@ -417,4 +417,4 @@ BI.SequenceTableTreeNumber = BI.inherit(BI.Widget, { this._populate(); } }); -BI.shortcut('bi.sequence_table_tree_number', BI.SequenceTableTreeNumber); \ No newline at end of file +BI.shortcut("bi.sequence_table_tree_number", BI.SequenceTableTreeNumber); \ No newline at end of file diff --git a/src/widget/singleselect/search/singleselect.search.loader.js b/src/widget/singleselect/search/singleselect.search.loader.js index 9c3ea9fad..0e687c32b 100644 --- a/src/widget/singleselect/search/singleselect.search.loader.js +++ b/src/widget/singleselect/search/singleselect.search.loader.js @@ -8,7 +8,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-search-loader', + baseCls: "bi-single-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -65,7 +65,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -95,7 +95,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: false - }) + }); }, _filterValues: function (src) { @@ -118,12 +118,12 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: false - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = v; this.button_group.setValue(v); }, @@ -154,4 +154,4 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_search_loader', BI.SingleSelectSearchLoader); \ No newline at end of file +BI.shortcut("bi.single_select_search_loader", BI.SingleSelectSearchLoader); \ No newline at end of file diff --git a/src/widget/singleselect/search/singleselect.search.pane.js b/src/widget/singleselect/search/singleselect.search.pane.js index 8cf9e4ce4..60e9ad29a 100644 --- a/src/widget/singleselect/search/singleselect.search.pane.js +++ b/src/widget/singleselect/search/singleselect.search.pane.js @@ -29,8 +29,8 @@ BI.SingleSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'single-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "single-select-toolbar", height: this.constants.height }); diff --git a/src/widget/singleselect/singleselect.combo.js b/src/widget/singleselect/singleselect.combo.js index 625de8372..d6c629797 100644 --- a/src/widget/singleselect/singleselect.combo.js +++ b/src/widget/singleselect/singleselect.combo.js @@ -7,7 +7,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-combo', + baseCls: "bi-single-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -22,8 +22,8 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { BI.isKey(self._startValue) && (self.storeValue = self._startValue); self.trigger.getSearcher().setState(self.storeValue); }; - this.storeValue = ''; - //标记正在请求数据 + this.storeValue = ""; + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -42,7 +42,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(self.getValue()); } callback.apply(self, arguments); @@ -69,7 +69,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -106,7 +106,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.single_select_popup_view', + type: "bi.single_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -152,10 +152,10 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -192,7 +192,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -201,7 +201,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, _makeMap: function (values) { @@ -220,7 +220,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -266,7 +266,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -285,7 +285,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -326,7 +326,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); }, @@ -348,4 +348,4 @@ BI.extend(BI.SingleSelectCombo, { BI.SingleSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.single_select_combo', BI.SingleSelectCombo); \ No newline at end of file +BI.shortcut("bi.single_select_combo", BI.SingleSelectCombo); \ No newline at end of file diff --git a/src/widget/singleselect/singleselect.list.js b/src/widget/singleselect/singleselect.list.js index b246f07bb..a1423a33e 100644 --- a/src/widget/singleselect/singleselect.list.js +++ b/src/widget/singleselect/singleselect.list.js @@ -7,127 +7,127 @@ */ BI.SingleSelectList = BI.inherit(BI.Widget, { - _defaultConfig: function () { - return BI.extend(BI.SingleSelectList.superclass._defaultConfig.apply(this, arguments), { - baseCls: "bi-select-list", - direction: BI.Direction.Top,//toolbar的位置 - logic: { - dynamic: true - }, - items: [], - itemsCreator: BI.emptyFn, - hasNext: BI.emptyFn, - onLoaded: BI.emptyFn, - el: { - type: "bi.list_pane" - } - }) - }, - _init: function () { - BI.SingleSelectList.superclass._init.apply(this, arguments); - var self = this, o = this.options; - - this.list = BI.createWidget(o.el, { - type: "bi.list_pane", - items: o.items, - itemsCreator: function (op, callback) { - o.itemsCreator(op, function (items) { - callback.apply(self, arguments); - }); - }, - onLoaded: o.onLoaded, - hasNext: o.hasNext - }); - - this.list.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { - if (type === BI.Events.CLICK) { - self.fireEvent(BI.SingleSelectList.EVENT_CHANGE, value, obj); - } - self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); - }); + _defaultConfig: function () { + return BI.extend(BI.SingleSelectList.superclass._defaultConfig.apply(this, arguments), { + baseCls: "bi-select-list", + direction: BI.Direction.Top, // toolbar的位置 + logic: { + dynamic: true + }, + items: [], + itemsCreator: BI.emptyFn, + hasNext: BI.emptyFn, + onLoaded: BI.emptyFn, + el: { + type: "bi.list_pane" + } + }); + }, + _init: function () { + BI.SingleSelectList.superclass._init.apply(this, arguments); + var self = this, o = this.options; + + this.list = BI.createWidget(o.el, { + type: "bi.list_pane", + items: o.items, + itemsCreator: function (op, callback) { + o.itemsCreator(op, function (items) { + callback.apply(self, arguments); + }); + }, + onLoaded: o.onLoaded, + hasNext: o.hasNext + }); + + this.list.on(BI.Controller.EVENT_CHANGE, function (type, value, obj) { + if (type === BI.Events.CLICK) { + self.fireEvent(BI.SingleSelectList.EVENT_CHANGE, value, obj); + } + self.fireEvent(BI.Controller.EVENT_CHANGE, arguments); + }); - BI.createWidget(BI.extend({ - element: this - }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ - scrolly: true - }, o.logic, { - items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.list) - })))); - - }, - - hasPrev: function () { - return this.list.hasPrev(); - }, - - hasNext: function () { - return this.list.hasNext(); - }, - - prependItems: function (items) { - this.list.prependItems.apply(this.list, arguments); - }, - - addItems: function (items) { - this.list.addItems.apply(this.list, arguments); - }, - - setValue: function (v) { - this.list.setValue([v]); - }, - - getValue: function () { - return this.list.getValue()[0]; - }, - - empty: function () { - this.list.empty(); - }, - - populate: function (items) { - this.list.populate.apply(this.list, arguments); - }, - - resetHeight: function (h) { - this.list.resetHeight ? this.list.resetHeight(h) : - this.list.element.css({"max-height": h + "px"}) - }, - - setNotSelectedValue: function () { - this.list.setNotSelectedValue.apply(this.list, arguments); - }, - - getNotSelectedValue: function () { - return this.list.getNotSelectedValue(); - }, - - getAllButtons: function () { - return this.list.getAllButtons(); - }, - - getAllLeaves: function () { - return this.list.getAllLeaves(); - }, - - getSelectedButtons: function () { - return this.list.getSelectedButtons(); - }, - - getNotSelectedButtons: function () { - return this.list.getNotSelectedButtons(); - }, - - getIndexByValue: function (value) { - return this.list.getIndexByValue(value); - }, - - getNodeById: function (id) { - return this.list.getNodeById(id); - }, - - getNodeByValue: function (value) { - return this.list.getNodeByValue(value); - } - }); - BI.SingleSelectList.EVENT_CHANGE = "EVENT_CHANGE"; - BI.shortcut("bi.single_select_list", BI.SingleSelectList); \ No newline at end of file + BI.createWidget(BI.extend({ + element: this + }, BI.LogicFactory.createLogic(BI.LogicFactory.createLogicTypeByDirection(o.direction), BI.extend({ + scrolly: true + }, o.logic, { + items: BI.LogicFactory.createLogicItemsByDirection(o.direction, this.list) + })))); + + }, + + hasPrev: function () { + return this.list.hasPrev(); + }, + + hasNext: function () { + return this.list.hasNext(); + }, + + prependItems: function (items) { + this.list.prependItems.apply(this.list, arguments); + }, + + addItems: function (items) { + this.list.addItems.apply(this.list, arguments); + }, + + setValue: function (v) { + this.list.setValue([v]); + }, + + getValue: function () { + return this.list.getValue()[0]; + }, + + empty: function () { + this.list.empty(); + }, + + populate: function (items) { + this.list.populate.apply(this.list, arguments); + }, + + resetHeight: function (h) { + this.list.resetHeight ? this.list.resetHeight(h) : + this.list.element.css({"max-height": h + "px"}); + }, + + setNotSelectedValue: function () { + this.list.setNotSelectedValue.apply(this.list, arguments); + }, + + getNotSelectedValue: function () { + return this.list.getNotSelectedValue(); + }, + + getAllButtons: function () { + return this.list.getAllButtons(); + }, + + getAllLeaves: function () { + return this.list.getAllLeaves(); + }, + + getSelectedButtons: function () { + return this.list.getSelectedButtons(); + }, + + getNotSelectedButtons: function () { + return this.list.getNotSelectedButtons(); + }, + + getIndexByValue: function (value) { + return this.list.getIndexByValue(value); + }, + + getNodeById: function (id) { + return this.list.getNodeById(id); + }, + + getNodeByValue: function (value) { + return this.list.getNodeByValue(value); + } +}); +BI.SingleSelectList.EVENT_CHANGE = "EVENT_CHANGE"; +BI.shortcut("bi.single_select_list", BI.SingleSelectList); \ No newline at end of file diff --git a/src/widget/singleselect/singleselect.loader.js b/src/widget/singleselect/singleselect.loader.js index 1d2fe6c53..fe8f6505b 100644 --- a/src/widget/singleselect/singleselect.loader.js +++ b/src/widget/singleselect/singleselect.loader.js @@ -8,7 +8,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-loader', + baseCls: "bi-single-select-loader", logic: { dynamic: true }, @@ -69,7 +69,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -99,7 +99,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { logic: this.options.logic, height: 25, selected: false - }) + }); }, _scrollToTop: function () { @@ -110,7 +110,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, setStartValue: function (v) { @@ -118,7 +118,7 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.button_group.setValue(this.storeValue); }, @@ -149,4 +149,4 @@ BI.SingleSelectLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_loader', BI.SingleSelectLoader); \ No newline at end of file +BI.shortcut("bi.single_select_loader", BI.SingleSelectLoader); \ No newline at end of file diff --git a/src/widget/singleselect/singleselect.popup.view.js b/src/widget/singleselect/singleselect.popup.view.js index 93a9d2d47..aed3afa29 100644 --- a/src/widget/singleselect/singleselect.popup.view.js +++ b/src/widget/singleselect/singleselect.popup.view.js @@ -7,8 +7,8 @@ BI.SingleSelectPopupView = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectPopupView.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-popup-view', - maxWidth: 'auto', + baseCls: "bi-single-select-popup-view", + maxWidth: "auto", minWidth: 135, maxHeight: 400, valueFormatter: BI.emptyFn, @@ -35,7 +35,7 @@ BI.SingleSelectPopupView = BI.inherit(BI.Widget, { minWidth: opts.minWidth, maxHeight: opts.maxHeight, element: this, - buttons: [BI.i18nText('BI-Basic_Clears'), BI.i18nText('BI-Basic_Sure')], + buttons: [BI.i18nText("BI-Basic_Clears"), BI.i18nText("BI-Basic_Sure")], el: this.loader }); @@ -84,4 +84,4 @@ BI.SingleSelectPopupView.EVENT_CLICK_CONFIRM = "EVENT_CLICK_CONFIRM"; BI.SingleSelectPopupView.EVENT_CLICK_CLEAR = "EVENT_CLICK_CLEAR"; -BI.shortcut('bi.single_select_popup_view', BI.SingleSelectPopupView); \ No newline at end of file +BI.shortcut("bi.single_select_popup_view", BI.SingleSelectPopupView); \ No newline at end of file diff --git a/src/widget/singleselect/singleselect.trigger.js b/src/widget/singleselect/singleselect.trigger.js index 757375949..420568256 100644 --- a/src/widget/singleselect/singleselect.trigger.js +++ b/src/widget/singleselect/singleselect.trigger.js @@ -60,12 +60,12 @@ BI.SingleSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: BI.createWidget(), width: 30 @@ -107,4 +107,4 @@ BI.SingleSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.single_select_trigger', BI.SingleSelectTrigger); \ No newline at end of file +BI.shortcut("bi.single_select_trigger", BI.SingleSelectTrigger); \ No newline at end of file diff --git a/src/widget/singleselect/trigger/editor.singleselect.js b/src/widget/singleselect/trigger/editor.singleselect.js index 8766495a7..9e26f6455 100644 --- a/src/widget/singleselect/trigger/editor.singleselect.js +++ b/src/widget/singleselect/trigger/editor.singleselect.js @@ -7,12 +7,12 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { _const: { - checkSelected: BI.i18nText('BI-Check_Selected') + checkSelected: BI.i18nText("BI-Check_Selected") }, _defaultConfig: function () { return BI.extend(BI.SingleSelectEditor.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-editor', + baseCls: "bi-single-select-editor", el: {} }); }, @@ -21,10 +21,10 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { BI.SingleSelectEditor.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.state_editor', + type: "bi.state_editor", element: this, height: o.height, - watermark: BI.i18nText('BI-Basic_Search'), + watermark: BI.i18nText("BI-Basic_Search"), allowBlank: true }); @@ -60,16 +60,16 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { var v = this.editor.getState(); if (BI.isArray(v) && v.length > 0) { return v[v.length - 1]; - } else { - return ""; } + return ""; + }, getKeywords: function () { var val = this.editor.getLastValidValue(); var keywords = val.match(/[\S]+/g); if (BI.isEndWithBlank(val)) { - return keywords.concat([' ']); + return keywords.concat([" "]); } return keywords; }, @@ -79,4 +79,4 @@ BI.SingleSelectEditor = BI.inherit(BI.Widget, { } }); BI.SingleSelectEditor.EVENT_PAUSE = "SingleSelectEditor.EVENT_PAUSE"; -BI.shortcut('bi.single_select_editor', BI.SingleSelectEditor); \ No newline at end of file +BI.shortcut("bi.single_select_editor", BI.SingleSelectEditor); \ No newline at end of file diff --git a/src/widget/singleselect/trigger/searcher.singleselect.js b/src/widget/singleselect/trigger/searcher.singleselect.js index df2e33908..6a900c64e 100644 --- a/src/widget/singleselect/trigger/searcher.singleselect.js +++ b/src/widget/singleselect/trigger/searcher.singleselect.js @@ -8,7 +8,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-searcher', + baseCls: "bi-single-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -22,7 +22,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { BI.SingleSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.single_select_editor', + type: "bi.single_select_editor", height: o.height }); @@ -104,11 +104,11 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { setState: function (v) { var o = this.options; - v || (v = ''); - if (v === '') { + v || (v = ""); + if (v === "") { this.editor.setState(BI.Selection.None); } else { - this.editor.setState(o.valueFormatter(v + "") || (v + '')); + this.editor.setState(o.valueFormatter(v + "") || (v + "")); } }, @@ -136,4 +136,4 @@ BI.SingleSelectSearcher.EVENT_START = "EVENT_START"; BI.SingleSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.SingleSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.single_select_searcher', BI.SingleSelectSearcher); \ No newline at end of file +BI.shortcut("bi.single_select_searcher", BI.SingleSelectSearcher); \ No newline at end of file diff --git a/src/widget/singleselectaddsearch/search/singleselect.search.loader.js b/src/widget/singleselectaddsearch/search/singleselect.search.loader.js index 7556a7c5c..3feebc758 100644 --- a/src/widget/singleselectaddsearch/search/singleselect.search.loader.js +++ b/src/widget/singleselectaddsearch/search/singleselect.search.loader.js @@ -8,7 +8,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearchLoader.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-search-loader', + baseCls: "bi-single-select-search-loader", itemsCreator: BI.emptyFn, keywordGetter: BI.emptyFn, valueFormatter: BI.emptyFn @@ -65,7 +65,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { value: v, title: txt, selected: false - } + }; }); firstItems = self._createItems(json); } @@ -112,7 +112,7 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }, height: 25, selected: false - }) + }); }, _filterValues: function (src) { @@ -135,12 +135,12 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { title: v.text, value: v.value, selected: false - } - }) + }; + }); }, setValue: function (v) { - //暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 + // 暂存的值一定是新的值,不然v改掉后,storeValue也跟着改了 this.storeValue = v; this.button_group.setValue(v); }, @@ -171,4 +171,4 @@ BI.SingleSelectSearchLoader = BI.inherit(BI.Widget, { }); BI.SingleSelectSearchLoader.EVENT_CHANGE = "EVENT_CHANGE"; -BI.shortcut('bi.single_select_search_add_loader', BI.SingleSelectSearchLoader); \ No newline at end of file +BI.shortcut("bi.single_select_search_add_loader", BI.SingleSelectSearchLoader); \ No newline at end of file diff --git a/src/widget/singleselectaddsearch/search/singleselect.search.pane.js b/src/widget/singleselectaddsearch/search/singleselect.search.pane.js index ecc8f92eb..ad306f561 100644 --- a/src/widget/singleselectaddsearch/search/singleselect.search.pane.js +++ b/src/widget/singleselectaddsearch/search/singleselect.search.pane.js @@ -29,8 +29,8 @@ BI.SingleSelectSearchPane = BI.inherit(BI.Widget, { this.tooltipClick = BI.createWidget({ type: "bi.label", invisible: true, - text: BI.i18nText('BI-Click_Blank_To_Select'), - cls: 'single-select-toolbar', + text: BI.i18nText("BI-Click_Blank_To_Select"), + cls: "single-select-toolbar", height: this.constants.height }); diff --git a/src/widget/singleselectaddsearch/singleselect.combo.js b/src/widget/singleselectaddsearch/singleselect.combo.js index e752f1c07..4858f43a2 100644 --- a/src/widget/singleselectaddsearch/singleselect.combo.js +++ b/src/widget/singleselectaddsearch/singleselect.combo.js @@ -7,7 +7,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { _defaultConfig: function () { return BI.extend(BI.SingleSelectCombo.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-combo', + baseCls: "bi-single-select-combo", itemsCreator: BI.emptyFn, valueFormatter: BI.emptyFn, height: 28 @@ -22,8 +22,8 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { BI.isKey(self._startValue) && (self.storeValue = self._startValue); self.trigger.getSearcher().setState(self.storeValue); }; - this.storeValue = ''; - //标记正在请求数据 + this.storeValue = ""; + // 标记正在请求数据 this.requesting = false; this.trigger = BI.createWidget({ @@ -42,7 +42,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { itemsCreator: function (op, callback) { o.itemsCreator(op, function (res) { if (op.times === 1 && BI.isNotNull(op.keywords)) { - //预防trigger内部把当前的storeValue改掉 + // 预防trigger内部把当前的storeValue改掉 self.trigger.setValue(self.getValue()); } callback.apply(self, arguments); @@ -69,7 +69,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { assertShowValue(); self.populate(); self._setStartValue(""); - }) + }); } }); this.trigger.on(BI.SingleSelectTrigger.EVENT_SEARCHING, function (keywords) { @@ -106,7 +106,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { el: this.trigger, adjustLength: 1, popup: { - type: 'bi.single_select_popup_view', + type: "bi.single_select_popup_view", ref: function () { self.popup = this; self.trigger.setAdapter(this); @@ -152,10 +152,10 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { self.populate(); }); }); - //当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 + // 当退出的时候如果还在处理请求,则等请求结束后再对外发确定事件 this.wants2Quit = false; this.combo.on(BI.Combo.EVENT_AFTER_HIDEVIEW, function () { - //important:关闭弹出时又可能没有退出编辑状态 + // important:关闭弹出时又可能没有退出编辑状态 self.trigger.stopEditing(); if (self.requesting === true) { self.wants2Quit = true; @@ -192,7 +192,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { top: 0, bottom: 0 }] - }) + }); }, _defaultState: function () { @@ -201,7 +201,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, _assertValue: function (val) { - val || (val = ''); + val || (val = ""); }, _makeMap: function (values) { @@ -220,7 +220,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { digest(values); }); - function digest(items) { + function digest (items) { var selectedMap = self._makeMap(items); BI.each(keywords, function (i, val) { if (BI.isNotNull(selectedMap[val])) { @@ -266,7 +266,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }); self.storeValue.value = newItems.concat(BI.values(selectedMap)); self._adjust(callback); - }) + }); }, _adjust: function (callback) { @@ -285,7 +285,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { } - function adjust() { + function adjust () { if (self.wants2Quit === true) { self.fireEvent(BI.SingleSelectCombo.EVENT_CONFIRM); self.wants2Quit = false; @@ -326,7 +326,7 @@ BI.SingleSelectCombo = BI.inherit(BI.Single, { }, setValue: function (v) { - this.storeValue = v || ''; + this.storeValue = v || ""; this._assertValue(this.storeValue); this.combo.setValue(this.storeValue); }, @@ -348,4 +348,4 @@ BI.extend(BI.SingleSelectCombo, { BI.SingleSelectCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; -BI.shortcut('bi.single_select_add_combo', BI.SingleSelectCombo); \ No newline at end of file +BI.shortcut("bi.single_select_add_combo", BI.SingleSelectCombo); \ No newline at end of file diff --git a/src/widget/singleselectaddsearch/singleselect.trigger.js b/src/widget/singleselectaddsearch/singleselect.trigger.js index 09cb914c4..ee55ed671 100644 --- a/src/widget/singleselectaddsearch/singleselect.trigger.js +++ b/src/widget/singleselectaddsearch/singleselect.trigger.js @@ -60,12 +60,12 @@ BI.SingleSelectTrigger = BI.inherit(BI.Trigger, { }); var wrapper = BI.createWidget({ - type: 'bi.htape', + type: "bi.htape", element: this, items: [ { el: this.searcher, - width: 'fill' + width: "fill" }, { el: BI.createWidget(), width: 30 @@ -107,4 +107,4 @@ BI.SingleSelectTrigger.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectTrigger.EVENT_SEARCHING = "EVENT_SEARCHING"; BI.SingleSelectTrigger.EVENT_BEFORE_COUNTER_POPUPVIEW = "EVENT_BEFORE_COUNTER_POPUPVIEW"; -BI.shortcut('bi.single_select_add_trigger', BI.SingleSelectTrigger); \ No newline at end of file +BI.shortcut("bi.single_select_add_trigger", BI.SingleSelectTrigger); \ No newline at end of file diff --git a/src/widget/singleselectaddsearch/trigger/searcher.singleselect.js b/src/widget/singleselectaddsearch/trigger/searcher.singleselect.js index 162bcd802..c09babc6a 100644 --- a/src/widget/singleselectaddsearch/trigger/searcher.singleselect.js +++ b/src/widget/singleselectaddsearch/trigger/searcher.singleselect.js @@ -8,7 +8,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { _defaultConfig: function () { return BI.extend(BI.SingleSelectSearcher.superclass._defaultConfig.apply(this, arguments), { - baseCls: 'bi-single-select-searcher', + baseCls: "bi-single-select-searcher", itemsCreator: BI.emptyFn, el: {}, popup: {}, @@ -22,7 +22,7 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { BI.SingleSelectSearcher.superclass._init.apply(this, arguments); var self = this, o = this.options; this.editor = BI.createWidget(o.el, { - type: 'bi.single_select_editor', + type: "bi.single_select_editor", height: o.height }); @@ -104,11 +104,11 @@ BI.SingleSelectSearcher = BI.inherit(BI.Widget, { setState: function (v) { var o = this.options; - v || (v = ''); - if (v === '') { + v || (v = ""); + if (v === "") { this.editor.setState(BI.Selection.None); } else { - this.editor.setState(o.valueFormatter(v + "") || (v + '')); + this.editor.setState(o.valueFormatter(v + "") || (v + "")); } }, @@ -136,4 +136,4 @@ BI.SingleSelectSearcher.EVENT_START = "EVENT_START"; BI.SingleSelectSearcher.EVENT_STOP = "EVENT_STOP"; BI.SingleSelectSearcher.EVENT_PAUSE = "EVENT_PAUSE"; BI.SingleSelectSearcher.EVENT_SEARCHING = "EVENT_SEARCHING"; -BI.shortcut('bi.single_select_add_searcher', BI.SingleSelectSearcher); \ No newline at end of file +BI.shortcut("bi.single_select_add_searcher", BI.SingleSelectSearcher); \ No newline at end of file diff --git a/src/widget/singleslider/button/editor.sign.text.js b/src/widget/singleslider/button/editor.sign.text.js index ceef43810..9d7661741 100644 --- a/src/widget/singleslider/button/editor.sign.text.js +++ b/src/widget/singleslider/button/editor.sign.text.js @@ -19,7 +19,7 @@ BI.SignTextEditor = BI.inherit(BI.Widget, { errorText: "", text: "", height: 24 - }) + }); }, _init: function () { @@ -58,7 +58,7 @@ BI.SignTextEditor = BI.inherit(BI.Widget, { }); this.text.on(BI.TextButton.EVENT_CHANGE, function () { BI.nextTick(function () { - self.fireEvent(BI.SignTextEditor.EVENT_CLICK_LABEL) + self.fireEvent(BI.SignTextEditor.EVENT_CLICK_LABEL); }); }); BI.createWidget({ diff --git a/src/widget/singleslider/singleslider.js b/src/widget/singleslider/singleslider.js index 92e455ffc..09305431e 100644 --- a/src/widget/singleslider/singleslider.js +++ b/src/widget/singleslider/singleslider.js @@ -56,13 +56,13 @@ BI.SingleSlider = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -138,7 +138,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _draggable: function (widget) { @@ -152,7 +152,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setLabelPosition(significantPercent); self._setSliderPosition(significantPercent); @@ -178,7 +178,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -186,7 +186,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -218,14 +218,14 @@ BI.SingleSlider = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { var o = this.options; var valid = false; if (BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max)) { - if(o.digit === false){ + if(o.digit === false) { valid = true; }else{ var dotText = (v + "").split(".")[1] || ""; @@ -236,15 +236,15 @@ BI.SingleSlider = BI.inherit(BI.Widget, { }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setLabelPosition: function (percent) { - this.label.element.css({"left": percent + "%"}); + this.label.element.css({left: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -259,7 +259,7 @@ BI.SingleSlider = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { diff --git a/src/widget/singleslider/singleslider.label.js b/src/widget/singleslider/singleslider.label.js index d963cb794..a1f171faa 100644 --- a/src/widget/singleslider/singleslider.label.js +++ b/src/widget/singleslider/singleslider.label.js @@ -57,13 +57,13 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -120,7 +120,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _draggable: function (widget) { @@ -134,7 +134,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setLabelPosition(significantPercent); self._setSliderPosition(significantPercent); @@ -160,7 +160,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSliderLabel.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -168,7 +168,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -200,23 +200,23 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - }) + }); }, _checkValidation: function (v) { - return BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max) + return BI.isNumeric(v) && !(BI.isNull(v) || v < this.min || v > this.max); }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setLabelPosition: function (percent) { - this.label.element.css({"left": percent + "%"}); + this.label.element.css({left: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -231,7 +231,7 @@ BI.SingleSliderLabel = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { diff --git a/src/widget/singleslider/singleslider.normal.js b/src/widget/singleslider/singleslider.normal.js index 26aaced4b..448b7e486 100644 --- a/src/widget/singleslider/singleslider.normal.js +++ b/src/widget/singleslider/singleslider.normal.js @@ -45,13 +45,13 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { var trackLength = self.track.element[0].scrollWidth; var percent = 0; if (offset < 0) { - percent = 0 + percent = 0; } if (offset > 0 && offset < (trackLength - c.SLIDER_WIDTH)) { percent = offset * 100 / self._getGrayTrackLength(); } if (offset > (trackLength - c.SLIDER_WIDTH)) { - percent = 100 + percent = 100; } var significantPercent = BI.parseFloat(percent.toFixed(1)); self._setAllPosition(significantPercent); @@ -87,7 +87,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { left: 0, width: "100%" }] - } + }; }, _draggable: function (widget) { @@ -101,7 +101,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { size = optimizeSize(defaultSize + offset); widget.element.addClass("dragging"); var percent = size * 100 / (self._getGrayTrackLength()); - var significantPercent = BI.parseFloat(percent.toFixed(1));//直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 + var significantPercent = BI.parseFloat(percent.toFixed(1));// 直接对计算出来的百分数保留到小数点后一位,相当于分成了1000份。 self._setBlueTrack(significantPercent); self._setSliderPosition(significantPercent); var v = self._getValueByPercent(significantPercent); @@ -125,7 +125,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { self.fireEvent(BI.SingleSlider.EVENT_CHANGE); }, document); widget.element.on("mousedown", function (event) { - if(!widget.isEnabled()){ + if(!widget.isEnabled()) { return; } defaultSize = this.offsetLeft; @@ -133,7 +133,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { mouseMoveTracker.captureMouseMoves(event); }); - function optimizeSize(s) { + function optimizeSize (s) { return BI.clamp(s, 0, self._getGrayTrackLength()); } }, @@ -184,19 +184,19 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { ref: function (ref) { self.track = ref; } - } + }; }, _checkValidation: function (v) { - return !(BI.isNull(v) || v < this.min || v > this.max) + return !(BI.isNull(v) || v < this.min || v > this.max); }, _setBlueTrack: function (percent) { - this.blueTrack.element.css({"width": percent + "%"}); + this.blueTrack.element.css({width: percent + "%"}); }, _setSliderPosition: function (percent) { - this.slider.element.css({"left": percent + "%"}); + this.slider.element.css({left: percent + "%"}); }, _setAllPosition: function (percent) { @@ -209,7 +209,7 @@ BI.SingleSliderNormal = BI.inherit(BI.Widget, { }, _getGrayTrackLength: function () { - return this.grayTrack.element[0].scrollWidth + return this.grayTrack.element[0].scrollWidth; }, _getValueByPercent: function (percent) { diff --git a/src/widget/singletree/singletree.popup.js b/src/widget/singletree/singletree.popup.js index 00ac75322..acc4c49b7 100644 --- a/src/widget/singletree/singletree.popup.js +++ b/src/widget/singletree/singletree.popup.js @@ -19,7 +19,7 @@ BI.SingleTreePopup = BI.inherit(BI.Pane, { var self = this, o = this.options; this.tree = BI.createWidget({ - type: 'bi.level_tree', + type: "bi.level_tree", expander: { isDefaultInit: true }, diff --git a/src/widget/switchtree/switchtree.js b/src/widget/switchtree/switchtree.js index 34a816700..6e74ee0ff 100644 --- a/src/widget/switchtree/switchtree.js +++ b/src/widget/switchtree/switchtree.js @@ -51,8 +51,8 @@ BI.SwitchTree = BI.inherit(BI.Widget, { } }, - _removeIsParent: function(items) { - BI.each(items, function(i, item) { + _removeIsParent: function (items) { + BI.each(items, function (i, item) { BI.isNotNull(item.isParent) && delete item.isParent; }); return items; @@ -108,4 +108,4 @@ BI.SwitchTree.SelectType = { SingleSelect: BI.Selection.Single, MultiSelect: BI.Selection.Multi }; -BI.shortcut('bi.switch_tree', BI.SwitchTree); +BI.shortcut("bi.switch_tree", BI.SwitchTree); diff --git a/src/widget/timeinterval/timeinterval.js b/src/widget/timeinterval/timeinterval.js index e79fe3cbd..514efbd23 100644 --- a/src/widget/timeinterval/timeinterval.js +++ b/src/widget/timeinterval/timeinterval.js @@ -15,7 +15,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { var conf = BI.TimeInterval.superclass._defaultConfig.apply(this, arguments); return BI.extend(conf, { extraCls: "bi-time-interval" - }) + }); }, _init: function () { var self = this; @@ -24,7 +24,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { this.left = this._createCombo(); this.right = this._createCombo(); this.label = BI.createWidget({ - type: 'bi.label', + type: "bi.label", height: this.constants.height, width: this.constants.width, text: "-" @@ -66,7 +66,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { _createCombo: function () { var self = this; var combo = BI.createWidget({ - type: 'bi.multidate_combo' + type: "bi.multidate_combo" }); combo.on(BI.MultiDateCombo.EVENT_ERROR, function () { self._clearTitle(); @@ -74,7 +74,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { self.fireEvent(BI.TimeInterval.EVENT_ERROR); }); - combo.on(BI.MultiDateCombo.EVENT_VALID, function(){ + combo.on(BI.MultiDateCombo.EVENT_VALID, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -90,7 +90,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { } }); - combo.on(BI.MultiDateCombo.EVENT_FOCUS, function(){ + combo.on(BI.MultiDateCombo.EVENT_FOCUS, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -110,7 +110,7 @@ BI.TimeInterval = BI.inherit(BI.Single, { self.left.hidePopupView(); self.right.hidePopupView(); }); - //combo.on(BI.MultiDateCombo.EVENT_CHANGE, function () { + // combo.on(BI.MultiDateCombo.EVENT_CHANGE, function () { // BI.Bubbles.hide("error"); // var smallDate = self.left.getKey(), bigDate = self.right.getKey(); // if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -124,9 +124,9 @@ BI.TimeInterval = BI.inherit(BI.Single, { // self._clearTitle(); // self.element.removeClass(self.constants.timeErrorCls); // } - //}); + // }); - combo.on(BI.MultiDateCombo.EVENT_CONFIRM, function(){ + combo.on(BI.MultiDateCombo.EVENT_CONFIRM, function () { BI.Bubbles.hide("error"); var smallDate = self.left.getKey(), bigDate = self.right.getKey(); if (self._check(smallDate, bigDate) && self._compare(smallDate, bigDate)) { @@ -150,14 +150,14 @@ BI.TimeInterval = BI.inherit(BI.Single, { _check: function (smallDate, bigDate) { var smallObj = smallDate.match(/\d+/g), bigObj = bigDate.match(/\d+/g); return this._dateCheck(smallDate) && Date.checkLegal(smallDate) && this._checkVoid({ - year: smallObj[0], - month: smallObj[1], - day: smallObj[2] - }) && this._dateCheck(bigDate) && Date.checkLegal(bigDate) && this._checkVoid({ - year: bigObj[0], - month: bigObj[1], - day: bigObj[2] - }); + year: smallObj[0], + month: smallObj[1], + day: smallObj[2] + }) && this._dateCheck(bigDate) && Date.checkLegal(bigDate) && this._checkVoid({ + year: bigObj[0], + month: bigObj[1], + day: bigObj[2] + }); }, _compare: function (smallDate, bigDate) { smallDate = Date.parseDateTime(smallDate, "%Y-%X-%d").print("%Y-%X-%d"); diff --git a/src/widget/year/combo.year.js b/src/widget/year/combo.year.js index 61d325334..4cbb21fb9 100644 --- a/src/widget/year/combo.year.js +++ b/src/widget/year/combo.year.js @@ -10,8 +10,8 @@ BI.YearCombo = BI.inherit(BI.Widget, { return BI.extend(BI.YearCombo.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-combo", behaviors: {}, - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 25 }); }, @@ -100,4 +100,4 @@ BI.YearCombo = BI.inherit(BI.Widget, { }); BI.YearCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_combo', BI.YearCombo); \ No newline at end of file +BI.shortcut("bi.year_combo", BI.YearCombo); \ No newline at end of file diff --git a/src/widget/year/popup.year.js b/src/widget/year/popup.year.js index a17c4e133..cc2e7b45e 100644 --- a/src/widget/year/popup.year.js +++ b/src/widget/year/popup.year.js @@ -11,8 +11,8 @@ BI.YearPopup = BI.inherit(BI.Widget, { return BI.extend(BI.YearPopup.superclass._defaultConfig.apply(this, arguments), { baseCls: "bi-year-popup", behaviors: {}, - min: '1900-01-01', //最小日期 - max: '2099-12-31' //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31" // 最大日期 }); }, diff --git a/src/widget/year/trigger.year.js b/src/widget/year/trigger.year.js index a337964c0..3fd21fe05 100644 --- a/src/widget/year/trigger.year.js +++ b/src/widget/year/trigger.year.js @@ -16,8 +16,8 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { _defaultConfig: function () { return BI.extend(BI.YearTrigger.superclass._defaultConfig.apply(this, arguments), { extraCls: "bi-year-trigger bi-border", - min: '1900-01-01', //最小日期 - max: '2099-12-31', //最大日期 + min: "1900-01-01", // 最小日期 + max: "2099-12-31", // 最大日期 height: 24 }); }, @@ -38,7 +38,7 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { vgap: c.vgap, allowBlank: true, errorText: c.errorText - }) + }); this.editor.on(BI.SignEditor.EVENT_FOCUS, function () { self.fireEvent(BI.YearTrigger.EVENT_FOCUS); }); @@ -66,7 +66,7 @@ BI.YearTrigger = BI.inherit(BI.Trigger, { }); BI.createWidget({ element: this, - type: 'bi.htape', + type: "bi.htape", items: [ { el: this.editor diff --git a/src/widget/yearmonth/combo.yearmonth.js b/src/widget/yearmonth/combo.yearmonth.js index 5780cc57d..ff1ba3b32 100644 --- a/src/widget/yearmonth/combo.yearmonth.js +++ b/src/widget/yearmonth/combo.yearmonth.js @@ -65,4 +65,4 @@ BI.YearMonthCombo = BI.inherit(BI.Widget, { }); BI.YearMonthCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearMonthCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_month_combo', BI.YearMonthCombo); \ No newline at end of file +BI.shortcut("bi.year_month_combo", BI.YearMonthCombo); \ No newline at end of file diff --git a/src/widget/yearquarter/combo.yearquarter.js b/src/widget/yearquarter/combo.yearquarter.js index 4671edb1c..a23f63c21 100644 --- a/src/widget/yearquarter/combo.yearquarter.js +++ b/src/widget/yearquarter/combo.yearquarter.js @@ -65,4 +65,4 @@ BI.YearQuarterCombo = BI.inherit(BI.Widget, { }); BI.YearQuarterCombo.EVENT_CONFIRM = "EVENT_CONFIRM"; BI.YearQuarterCombo.EVENT_BEFORE_POPUPVIEW = "EVENT_BEFORE_POPUPVIEW"; -BI.shortcut('bi.year_quarter_combo', BI.YearQuarterCombo); \ No newline at end of file +BI.shortcut("bi.year_quarter_combo", BI.YearQuarterCombo); \ No newline at end of file