How to use tree method in Kiwi

Best Python code snippet using Kiwi_python

jquery.ztree-2.6.js

Source:jquery.ztree-2.6.js Github

copy

Full Screen

1/*2 * JQuery zTree 2.63 * http://code.google.com/p/jquerytree/4 *5 * Copyright (c) 2010 Hunter.z (baby666.cn)6 *7 * Licensed same as jquery - under the terms of either the MIT License or the GPL Version 2 License8 * http://www.opensource.org/licenses/mit-license.php9 * http://www.gnu.org/licenses/gpl.html10 *11 * email: hunter.z@263.net12 * Date: 2011-06-0113 */1415(function($) {1617 var ZTREE_NODECREATED = "ZTREE_NODECREATED";18 var ZTREE_CLICK = "ZTREE_CLICK";19 var ZTREE_CHANGE = "ZTREE_CHANGE";20 var ZTREE_RENAME = "ZTREE_RENAME";21 var ZTREE_REMOVE = "ZTREE_REMOVE";22 var ZTREE_DRAG = "ZTREE_DRAG";23 var ZTREE_DROP = "ZTREE_DROP";24 var ZTREE_EXPAND = "ZTREE_EXPAND";25 var ZTREE_COLLAPSE = "ZTREE_COLLAPSE";26 var ZTREE_ASYNC_SUCCESS = "ZTREE_ASYNC_SUCCESS";27 var ZTREE_ASYNC_ERROR = "ZTREE_ASYNC_ERROR";2829 var IDMark_Switch = "_switch";30 var IDMark_Icon = "_ico";31 var IDMark_Span = "_span";32 var IDMark_Input = "_input";33 var IDMark_Check = "_check";34 var IDMark_Edit = "_edit";35 var IDMark_Remove = "_remove";36 var IDMark_Ul = "_ul";37 var IDMark_A = "_a";3839 var LineMark_Root = "root";40 var LineMark_Roots = "roots";41 var LineMark_Center = "center";42 var LineMark_Bottom = "bottom";43 var LineMark_NoLine = "noLine";44 var LineMark_Line = "line";4546 var FolderMark_Open = "open";47 var FolderMark_Close = "close";48 var FolderMark_Docu = "docu";4950 var Class_CurSelectedNode = "curSelectedNode";51 var Class_CurSelectedNode_Edit = "curSelectedNode_Edit";52 var Class_TmpTargetTree = "tmpTargetTree";53 var Class_TmpTargetNode = "tmpTargetNode";54 55 var Check_Style_Box = "checkbox";56 var Check_Style_Radio = "radio";57 var CheckBox_Default = "chk";58 var CheckBox_False = "false";59 var CheckBox_True = "true";60 var CheckBox_Full = "full";61 var CheckBox_Part = "part";62 var CheckBox_Focus = "focus";63 var Radio_Type_All = "all";64 var Radio_Type_Level = "level";65 66 var MoveType_Inner = "inner";67 var MoveType_Before = "before";68 var MoveType_After = "after";69 var MinMoveSize = "5";7071 var settings = new Array();72 var zTreeId = 0;73 var zTreeNodeCache = [];7475 //zTree构造函数76 $.fn.zTree = function(zTreeSetting, zTreeNodes) {7778 var setting = {79 //Tree 唯一标识,主UL的ID80 treeObjId: "",81 treeObj: null,82 //是否显示CheckBox83 checkable: false,84 //是否在编辑状态85 editable: false,86 //编辑状态是否显示修改按钮87 edit_renameBtn:true,88 //编辑状态是否显示删除节点按钮89 edit_removeBtn:true,90 //是否显示树的线91 showLine: true,92 //是否显示图标93 showIcon: true,94 //是否锁定父节点状态95 keepParent: false,96 //是否锁定叶子节点状态97 keepLeaf: false,98 //当前被选择的TreeNode99 curTreeNode: null,100 //当前正被编辑的TreeNode101 curEditTreeNode: null,102 //是否处于拖拽期间 0: not Drag; 1: doing Drag103 dragStatus: 0,104 dragNodeShowBefore: false,105 //拖拽操作控制 move or copy106 dragCopy: false,107 dragMove: true,108 //选择CheckBox 或 Radio109 checkStyle: Check_Style_Box,110 //checkBox点击后影响父子节点设置(checkStyle=Check_Style_Radio时无效) 111 checkType: {112 "Y": "ps",113 "N": "ps"114 },115 //radio 最大个数限制类型,每一级节点限制 或 整棵Tree的全部节点限制(checkStyle=Check_Style_Box时无效)116 checkRadioType:Radio_Type_Level,117 //checkRadioType = Radio_Type_All 时,保存被选择节点的堆栈118 checkRadioCheckedList:[],119 //是否异步获取节点数据120 async: false,121 //获取节点数据的URL地址122 asyncUrl: "",123 //获取节点数据时,必须的数据名称,例如:id、name124 asyncParam: [],125 //其它参数126 asyncParamOther: [],127 //异步加载获取数据,针对数据进行预处理的函数128 asyncDataFilter: null,129 //简单Array数组转换为JSON嵌套数据参数130 isSimpleData: false,131 treeNodeKey: "",132 treeNodeParentKey: "",133 rootPID: null,134 //用户自定义名称列135 nameCol: "name",136 //用户自定义子节点列137 nodesCol: "nodes", 138 //用户自定义checked列139 checkedCol: "checked", 140 //折叠、展开特效速度141 expandSpeed: "fast",142 //折叠、展开Trigger开关143 expandTriggerFlag:false,144 //hover 增加按钮接口145 addHoverDom:null,146 //hover 删除按钮接口147 removeHoverDom:null,148 //永久自定义显示控件方法149 addDiyDom:null,150 //字体个性化样式接口151 fontCss:{},152 153 root: {154 isRoot: true,155 nodes: []156 },157 //event Function158 callback: {159 beforeAsync:null,160 beforeClick:null,161 beforeRightClick:null,162 beforeMouseDown:null,163 beforeMouseUp:null,164 beforeChange:null,165 beforeDrag:null,166 beforeDrop:null,167 beforeRename:null,168 beforeRemove:null,169 beforeExpand:null,170 beforeCollapse:null,171 confirmDragOpen:null,172 confirmRename:null,173 174 nodeCreated:null,175 click:null,176 rightClick:null,177 mouseDown:null,178 mouseUp:null,179 change:null,180 drag:null,181 drop:null,182 rename:null,183 remove:null,184 expand:null,185 collapse:null,186 asyncConfirmData:null,187 asyncSuccess:null,188 asyncError:null189 } 190 };191192 if (zTreeSetting) {193 var tmp_checkType = zTreeSetting.checkType;194 zTreeSetting.checkType = undefined;195 var tmp_callback = zTreeSetting.callback;196 zTreeSetting.callback = undefined;197 var tmp_root = zTreeSetting.root;198 zTreeSetting.root = undefined;199 200 $.extend(setting, zTreeSetting);201 202 zTreeSetting.checkType = tmp_checkType; 203 $.extend(true, setting.checkType, tmp_checkType);204 zTreeSetting.callback = tmp_callback; 205 $.extend(setting.callback, tmp_callback);206 zTreeSetting.root = tmp_root; 207 $.extend(setting.root, tmp_root);208 }209210 setting.treeObjId = this.attr("id");211 setting.treeObj = this;212 setting.root.tId = -1;213 setting.root.name = "ZTREE ROOT";214 setting.root.isRoot = true;215 setting.checkRadioCheckedList = [];216 setting.curTreeNode = null;217 setting.curEditTreeNode = null;218 setting.dragNodeShowBefore = false;219 setting.dragStatus = 0;220 setting.expandTriggerFlag = false;221 if (!setting.root[setting.nodesCol]) setting.root[setting.nodesCol]= [];222223 if (zTreeNodes) {224 setting.root[setting.nodesCol] = zTreeNodes;225 }226 if (setting.isSimpleData) {227 setting.root[setting.nodesCol] = transformTozTreeFormat(setting, setting.root[setting.nodesCol]);228 }229 settings[setting.treeObjId] = setting;230231 setting.treeObj.empty();232 zTreeNodeCache[setting.treeObjId] = [];233 bindTreeNodes(setting, this);234 if (setting.root[setting.nodesCol] && setting.root[setting.nodesCol].length > 0) {235 initTreeNodes(setting, 0, setting.root[setting.nodesCol]);236 } else if (setting.async && setting.asyncUrl && setting.asyncUrl.length > 0) {237 asyncGetNode(setting);238 }239 240 return new zTreePlugin().init(this);241 };242243 //绑定事件244 function bindTreeNodes(setting, treeObj) {245 var eventParam = {treeObjId: setting.treeObjId};246 setting.treeObj.unbind('click', eventProxy);247 setting.treeObj.bind('click', eventParam, eventProxy);248 setting.treeObj.unbind('dblclick', eventProxy);249 setting.treeObj.bind('dblclick', eventParam, eventProxy);250 setting.treeObj.unbind('mouseover', eventProxy);251 setting.treeObj.bind('mouseover', eventParam, eventProxy);252 setting.treeObj.unbind('mouseout', eventProxy);253 setting.treeObj.bind('mouseout', eventParam, eventProxy);254 setting.treeObj.unbind('mousedown', eventProxy);255 setting.treeObj.bind('mousedown', eventParam, eventProxy);256 setting.treeObj.unbind('mouseup', eventProxy);257 setting.treeObj.bind('mouseup', eventParam, eventProxy);258 setting.treeObj.unbind('contextmenu', eventProxy);259 setting.treeObj.bind('contextmenu', eventParam, eventProxy);260261 treeObj.unbind(ZTREE_NODECREATED); 262 treeObj.bind(ZTREE_NODECREATED, function (event, treeId, treeNode) {263 tools.apply(setting.callback.nodeCreated, [event, treeId, treeNode]);264 });265266 treeObj.unbind(ZTREE_CLICK); 267 treeObj.bind(ZTREE_CLICK, function (event, treeId, treeNode) {268 tools.apply(setting.callback.click, [event, treeId, treeNode]);269 });270271 treeObj.unbind(ZTREE_CHANGE);272 treeObj.bind(ZTREE_CHANGE, function (event, treeId, treeNode) {273 tools.apply(setting.callback.change, [event, treeId, treeNode]);274 });275276 treeObj.unbind(ZTREE_RENAME);277 treeObj.bind(ZTREE_RENAME, function (event, treeId, treeNode) {278 tools.apply(setting.callback.rename, [event, treeId, treeNode]);279 });280 281 treeObj.unbind(ZTREE_REMOVE);282 treeObj.bind(ZTREE_REMOVE, function (event, treeId, treeNode) {283 tools.apply(setting.callback.remove, [event, treeId, treeNode]);284 });285286 treeObj.unbind(ZTREE_DRAG);287 treeObj.bind(ZTREE_DRAG, function (event, treeId, treeNode) {288 tools.apply(setting.callback.drag, [event, treeId, treeNode]);289 });290291 treeObj.unbind(ZTREE_DROP);292 treeObj.bind(ZTREE_DROP, function (event, treeId, treeNode, targetNode, moveType) {293 tools.apply(setting.callback.drop, [event, treeId, treeNode, targetNode, moveType]);294 });295296 treeObj.unbind(ZTREE_EXPAND);297 treeObj.bind(ZTREE_EXPAND, function (event, treeId, treeNode) {298 tools.apply(setting.callback.expand, [event, treeId, treeNode]);299 });300301 treeObj.unbind(ZTREE_COLLAPSE);302 treeObj.bind(ZTREE_COLLAPSE, function (event, treeId, treeNode) {303 tools.apply(setting.callback.collapse, [event, treeId, treeNode]);304 });305306 treeObj.unbind(ZTREE_ASYNC_SUCCESS);307 treeObj.bind(ZTREE_ASYNC_SUCCESS, function (event, treeId, treeNode, msg) {308 tools.apply(setting.callback.asyncSuccess, [event, treeId, treeNode, msg]);309 });310311 treeObj.unbind(ZTREE_ASYNC_ERROR);312 treeObj.bind(ZTREE_ASYNC_ERROR, function (event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown) {313 tools.apply(setting.callback.asyncError, [event, treeId, treeNode, XMLHttpRequest, textStatus, errorThrown]);314 });315 }316 317 //初始化并显示节点Json对象318 function initTreeNodes(setting, level, treeNodes, parentNode) {319 if (!treeNodes) return;320321 var zTreeHtml = appendTreeNodes(setting, level, treeNodes, parentNode);322 if (!parentNode) {323 setting.treeObj.append(zTreeHtml.join(''));324 } else {325 $("#" + parentNode.tId + IDMark_Ul).append(zTreeHtml.join(''));326 }327 repairParentChkClassWithSelf(setting, parentNode);328 createCallback(setting, treeNodes);329 }330331 function createCallback(setting, treeNodes) {332 for (var i = 0, l = treeNodes.length; i < l; i++) {333 var node = treeNodes[i];334 tools.apply(setting.addDiyDom, [setting.treeObjId, node]);335 //触发nodeCreated事件336 setting.treeObj.trigger(ZTREE_NODECREATED, [setting.treeObjId, node]);337 if (node[setting.nodesCol] && node[setting.nodesCol].length > 0) {338 createCallback(setting, node[setting.nodesCol], node);339 }340 }341 }342343 function appendTreeNodes(setting, level, treeNodes, parentNode) {344 if (!treeNodes) return [];345 var html = [];346 for (var i = 0, l = treeNodes.length; i < l; i++) {347 var node = treeNodes[i];348 node.level = level;349 node.tId = setting.treeObjId + "_" + (++zTreeId);350 node.parentNode = parentNode;351 node[setting.checkedCol] = !!node[setting.checkedCol];352 node.checkedOld = node[setting.checkedCol];353 node.check_Focus = false;354 node.check_True_Full = true;355 node.check_False_Full = true;356 node.editNameStatus = false;357 node.isAjaxing = null;358 addCache(setting, node);359 fixParentKeyValue(setting, node);360361 var tmpParentNode = (parentNode) ? parentNode: setting.root;362 //允许在非空节点上增加节点363 node.isFirstNode = (tmpParentNode[setting.nodesCol].length == treeNodes.length) && (i == 0);364 node.isLastNode = (i == (treeNodes.length - 1));365366 if (node[setting.nodesCol] && node[setting.nodesCol].length > 0) {367 node.open = (node.open) ? true: false;368 node.isParent = true;369 } else {370 node.isParent = (node.isParent) ? true: false;371 }372 373 var url = makeNodeUrl(setting, node);374 var fontcss = makeNodeFontCss(setting, node);375 var fontStyle = [];376 for (var f in fontcss) {377 fontStyle.push(f, ":", fontcss[f], ";");378 }379 380 var childHtml = [];381 if (node[setting.nodesCol] && node[setting.nodesCol].length > 0) {382 childHtml = appendTreeNodes(setting, level + 1, node[setting.nodesCol], node);383 }384 html.push("<li id='", node.tId, "' treenode>",385 "<button type='button' id='", node.tId, IDMark_Switch,386 "' title='' class='", makeNodeLineClass(setting, node), "' treeNode", IDMark_Switch," onfocus='this.blur();'></button>");387 if (setting.checkable) {388 makeChkFlag(setting, node);389 if (setting.checkStyle == Check_Style_Radio && setting.checkRadioType == Radio_Type_All && node[setting.checkedCol] ) {390 setting.checkRadioCheckedList = setting.checkRadioCheckedList.concat([node]);391 }392 html.push("<button type='button' ID='", node.tId, IDMark_Check, "' class='", makeChkClass(setting, node), "' treeNode", IDMark_Check," onfocus='this.blur();' ",(node.nocheck === true?"style='display:none;'":""),"></button>");393 }394 html.push("<a id='", node.tId, IDMark_A, "' treeNode", IDMark_A," onclick=\"", (node.click || ''),395 "\" ", ((url != null && url.length > 0) ? "href='" + url + "'" : ""), " target='",makeNodeTarget(node),"' style='", fontStyle.join(''), 396 "'><button type='button' id='", node.tId, IDMark_Icon,397 "' title='' treeNode", IDMark_Icon," onfocus='this.blur();' class='", makeNodeIcoClass(setting, node), "' style='", makeNodeIcoStyle(setting, node), "'></button><span id='", node.tId, IDMark_Span,398 "'>",node[setting.nameCol].replace(/&/g,'&amp;').replace(/</g,'&lt;').replace(/>/g,'&gt;'),"</span></a><ul id='", node.tId, IDMark_Ul, "' class='", makeUlLineClass(setting, node), "' style='display:", (node.open ? "block": "none"),"'>");399 html.push(childHtml.join(''));400 html.push("</ul></li>");401 }402 return html;403 }404405 function eventProxy(event) {406 var target = event.target;407 var relatedTarget = event.relatedTarget;408 var setting = settings[event.data.treeObjId];409 var tId = "";410 var childEventType = "", mainEventType = "";411 var tmp = null;412413 if (tools.eqs(event.type, "mouseover")) {414 if (setting.checkable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+IDMark_Check) !== null) {415 tId = target.parentNode.id;416 childEventType = "mouseoverCheck";417 } else {418 tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+IDMark_A}]);419 if (tmp) {420 tId = tmp.parentNode.id;421 childEventType = "hoverOverNode";422 }423 }424 } else if (tools.eqs(event.type, "mouseout")) {425 if (setting.checkable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+IDMark_Check) !== null) {426 tId = target.parentNode.id;427 childEventType = "mouseoutCheck";428 } else {429 tmp = tools.getMDom(setting, relatedTarget, [{tagName:"a", attrName:"treeNode"+IDMark_A}]);430 if (!tmp) {431 tId = "remove";432 childEventType = "hoverOutNode";433 }434 }435 } else if (tools.eqs(event.type, "mousedown")) {436 mainEventType = "mousedown";437 tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+IDMark_A}]);438 if (tmp) {439 tId = tmp.parentNode.id;440 childEventType = "mousedownNode";441 }442 } else if (tools.eqs(event.type, "mouseup")) {443 mainEventType = "mouseup";444 tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+IDMark_A}]);445 if (tmp) {tId = tmp.parentNode.id;}446 } else if (tools.eqs(event.type, "contextmenu")) {447 mainEventType = "contextmenu";448 tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+IDMark_A}]);449 if (tmp) {tId = tmp.parentNode.id;}450 } else if (tools.eqs(event.type, "click")) {451 if (tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+IDMark_Switch) !== null) {452 tId = target.parentNode.id;453 childEventType = "switchNode";454 } else if (setting.checkable && tools.eqs(target.tagName, "button") && target.getAttribute("treeNode"+IDMark_Check) !== null) {455 tId = target.parentNode.id;456 childEventType = "checkNode";457 } else {458 tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+IDMark_A}]);459 if (tmp) {460 tId = tmp.parentNode.id;461 childEventType = "clickNode";462 }463 }464 } else if (tools.eqs(event.type, "dblclick")) {465 mainEventType = "dblclick";466 tmp = tools.getMDom(setting, target, [{tagName:"a", attrName:"treeNode"+IDMark_A}]);467 if (tmp) {468 tId = tmp.parentNode.id;469 childEventType = "switchNode";470 }471 }472473 if (tId.length>0 || mainEventType.length>0) {474 if (childEventType!="hoverOverNode" && childEventType != "hoverOutNode"475 && childEventType!="mouseoverCheck" && childEventType != "mouseoutCheck"476 && target.getAttribute("treeNode"+IDMark_Input) === null477 && !st.checkEvent(setting)) return false;478 }479 if (tId.length>0) {480 // 编辑框Text状态下 允许选择文本481 if (!(setting.curTreeNode && setting.curTreeNode.editNameStatus)) {482 tools.noSel();483 }484 event.data.treeNode = getTreeNodeByTId(setting, tId);485 switch (childEventType) {486 case "switchNode" :487 handler.onSwitchNode(event);488 break;489 case "clickNode" :490 handler.onClickNode(event);491 break;492 case "checkNode" :493 handler.onCheckNode(event);494 break;495 case "mouseoverCheck" :496 handler.onMouseoverCheck(event);497 break;498 case "mouseoutCheck" :499 handler.onMouseoutCheck(event);500 break;501 case "mousedownNode" :502 handler.onMousedownNode(event);503 break;504 case "hoverOverNode" :505 handler.onHoverOverNode(event);506 break;507 case "hoverOutNode" :508 handler.onHoverOutNode(event);509 break;510 }511 } else {512 event.data.treeNode = null;513 }514 switch (mainEventType) {515 case "mousedown" :516 return handler.onZTreeMousedown(event);517 break;518 case "mouseup" :519 return handler.onZTreeMouseup(event);520 break;521 case "dblclick" :522 return handler.onZTreeDblclick(event);523 break;524 case "contextmenu" :525 return handler.onZTreeContextmenu(event);526 break;527 }528 }529530 var tools = {531 eqs: function(str1, str2) {532 return str1.toLowerCase() === str2.toLowerCase();533 },534 isArray: function(arr) {535 return Object.prototype.toString.apply(arr) === "[object Array]";536 },537 noSel: function() {538 //除掉默认事件,防止文本被选择539 window.getSelection ? window.getSelection().removeAllRanges() : setTimeout(function(){document.selection.empty();}, 10);540 },541 inputFocus: function(inputObj) {542 if (inputObj.get(0)) {543 inputObj.focus();544 setCursorPosition(inputObj.get(0), inputObj.val().length);545 }546 },547 apply: function(fun, param, defaultValue) {548 if ((typeof fun) == "function") {549 return fun.apply(tools, param);550 }551 return defaultValue;552 },553 getAbs: function (obj) {554 //获取对象的绝对坐标555 oRect = obj.getBoundingClientRect();556 return [oRect.left,oRect.top]557 },558 getMDom: function (setting, curDom, targetExpr) {559 if (!curDom) return null;560 while (curDom && curDom.id !== setting.treeObjId) {561 for (var i=0, l=targetExpr.length; curDom.tagName && i<l; i++) {562 if (tools.eqs(curDom.tagName, targetExpr[i].tagName) && curDom.getAttribute(targetExpr[i].attrName) !== null) {563 return curDom;564 }565 }566 curDom = curDom.parentNode;567 }568 return null;569 },570 clone: function (jsonObj) {571 var buf;572 if (jsonObj instanceof Array) {573 buf = [];574 var i = jsonObj.length;575 while (i--) {576 buf[i] = arguments.callee(jsonObj[i]);577 }578 return buf;579 }else if (typeof jsonObj == "function"){580 return jsonObj;581 }else if (jsonObj instanceof Object){582 buf = {};583 for (var k in jsonObj) {584 if (k!="parentNode") {585 buf[k] = arguments.callee(jsonObj[k]);586 }587 }588 return buf;589 }else{590 return jsonObj;591 }592 }593 };594595 var st = {596 checkEvent: function(setting) {597 return st.checkCancelPreEditNode(setting);598 },599 //取消之前选中节点状态600 cancelPreSelectedNode: function (setting) {601 if (setting.curTreeNode) {602 $("#" + setting.curTreeNode.tId + IDMark_A).removeClass(Class_CurSelectedNode);603 setNodeName(setting, setting.curTreeNode);604 removeTreeDom(setting, setting.curTreeNode);605 setting.curTreeNode = null;606 }607 },608 //校验取消之前编辑节点状态609 checkCancelPreEditNode: function (setting) {610 if (setting.curEditTreeNode) {611 var inputObj = setting.curEditInput;612 if ( tools.apply(setting.callback.confirmRename, [setting.treeObjId, setting.curEditTreeNode, inputObj.val()], true) === false) {613 setting.curEditTreeNode.editNameStatus = true;614 tools.inputFocus(inputObj);615 return false;616 }617 }618 return true;619 },620 //取消之前编辑节点状态621 cancelPreEditNode: function (setting, newName) {622 if (setting.curEditTreeNode) {623 var inputObj = $("#" + setting.curEditTreeNode.tId + IDMark_Input);624 setting.curEditTreeNode[setting.nameCol] = newName ? newName:inputObj.val();625 //触发rename事件626 setting.treeObj.trigger(ZTREE_RENAME, [setting.treeObjId, setting.curEditTreeNode]);627628 $("#" + setting.curEditTreeNode.tId + IDMark_A).removeClass(Class_CurSelectedNode_Edit);629 inputObj.unbind();630 setNodeName(setting, setting.curEditTreeNode);631 setting.curEditTreeNode.editNameStatus = false;632 setting.curEditTreeNode = null;633 setting.curEditInput = null;634 }635 return true;636 }637 }638639 var handler = {640 //点击展开、折叠节点641 onSwitchNode: function (event) {642 var setting = settings[event.data.treeObjId];643 var treeNode = event.data.treeNode;644645 if (treeNode.open) {646 if (tools.apply(setting.callback.beforeCollapse, [setting.treeObjId, treeNode], true) == false) return;647 setting.expandTriggerFlag = true;648 switchNode(setting, treeNode);649 } else {650 if (tools.apply(setting.callback.beforeExpand, [setting.treeObjId, treeNode], true) == false) return;651 setting.expandTriggerFlag = true;652 switchNode(setting, treeNode);653 }654 },655 onClickNode: function (event) {656 var setting = settings[event.data.treeObjId];657 var treeNode = event.data.treeNode;658 if (tools.apply(setting.callback.beforeClick, [setting.treeObjId, treeNode], true) == false) return;659 //设置节点为选中状态660 selectNode(setting, treeNode);661 //触发click事件662 setting.treeObj.trigger(ZTREE_CLICK, [setting.treeObjId, treeNode]);663 },664 onCheckNode: function (event) {665 var setting = settings[event.data.treeObjId];666 var treeNode = event.data.treeNode;667 if (tools.apply(setting.callback.beforeChange, [setting.treeObjId, treeNode], true) == false) return;668669 treeNode[setting.checkedCol] = !treeNode[setting.checkedCol];670 checkNodeRelation(setting, treeNode);671672 var checkObj = $("#" + treeNode.tId + IDMark_Check);673 setChkClass(setting, checkObj, treeNode);674 repairParentChkClassWithSelf(setting, treeNode);675676 //触发 CheckBox 点击事件677 setting.treeObj.trigger(ZTREE_CHANGE, [setting.treeObjId, treeNode]);678 },679 onMouseoverCheck: function(event) {680 var setting = settings[event.data.treeObjId];681 var treeNode = event.data.treeNode;682 var checkObj = $("#" + treeNode.tId + IDMark_Check);683 treeNode.checkboxFocus = true;684 setChkClass(setting, checkObj, treeNode); 685 },686 onMouseoutCheck: function(event) {687 var setting = settings[event.data.treeObjId];688 var treeNode = event.data.treeNode;689 var checkObj = $("#" + treeNode.tId + IDMark_Check);690 treeNode.checkboxFocus = false;691 setChkClass(setting, checkObj, treeNode);692 },693 onMousedownNode: function(eventMouseDown) {694 var setting = settings[eventMouseDown.data.treeObjId];695 var treeNode = eventMouseDown.data.treeNode;696 //右键、禁用拖拽功能 不能拖拽697 if (eventMouseDown.button == 2 || !setting.editable || (!setting.dragCopy && !setting.dragMove)) return;698 //编辑输入框内不能拖拽节点699 var target = eventMouseDown.target;700 if (treeNode.editNameStatus && tools.eqs(target.tagName, "input") && target.getAttribute("treeNode"+IDMark_Input) !== null) {701 return;702 }703704 var doc = document;705 var curNode;706 var tmpArrow;707 var tmpTarget;708 var isOtherTree = false;709 var targetSetting = setting;710 var preTmpTargetNodeId = null;711 var preTmpMoveType = null;712 var tmpTargetNodeId = null;713 var moveType = MoveType_Inner;714 var mouseDownX = eventMouseDown.clientX;715 var mouseDownY = eventMouseDown.clientY;716 var startTime = (new Date()).getTime();717718 $(doc).mousemove(function(event) {719 tools.noSel();720721 //避免鼠标误操作,对于第一次移动小于MinMoveSize时,不开启拖拽功能722 if (setting.dragStatus == 0 && Math.abs(mouseDownX - event.clientX) < MinMoveSize723 && Math.abs(mouseDownY - event.clientY) < MinMoveSize) {724 return true;725 }726727 $("body").css("cursor", "pointer");728729 if (setting.dragStatus == 0 && treeNode.isParent && treeNode.open) {730 expandAndCollapseNode(setting, treeNode, !treeNode.open);731 setting.dragNodeShowBefore = true;732 }733734 if (setting.dragStatus == 0) {735 //避免beforeDrag alert时,得到返回值之前仍能拖拽的Bug736 setting.dragStatus = -1;737 if (tools.apply(setting.callback.beforeDrag, [setting.treeObjId, treeNode], true) == false) return true;738739 setting.dragStatus = 1;740 showIfameMask(true);741742 //设置节点为选中状态743 treeNode.editNameStatus = false;744 selectNode(setting, treeNode);745 removeTreeDom(setting, treeNode);746747 var tmpNode = $("#" + treeNode.tId).clone();748 tmpNode.attr("id", treeNode.tId + "_tmp");749 tmpNode.css("padding", "0");750 tmpNode.children("#" + treeNode.tId + IDMark_A).removeClass(Class_CurSelectedNode);751 tmpNode.children("#" + treeNode.tId + IDMark_Ul).css("display", "none");752753 curNode = $("<ul class='zTreeDragUL'></ul>").append(tmpNode);754 curNode.attr("id", treeNode.tId + IDMark_Ul + "_tmp");755 curNode.addClass(setting.treeObj.attr("class"));756 curNode.appendTo("body");757758 tmpArrow = $("<button class='tmpzTreeMove_arrow'></button>");759 tmpArrow.attr("id", "zTreeMove_arrow_tmp");760 tmpArrow.appendTo("body");761762 //触发 DRAG 拖拽事件,返回正在拖拽的源数据对象763 setting.treeObj.trigger(ZTREE_DRAG, [setting.treeObjId, treeNode]);764 }765766 if (setting.dragStatus == 1 && tmpArrow.attr("id") != event.target.id) {767 if (tmpTarget) {768 tmpTarget.removeClass(Class_TmpTargetTree);769 if (tmpTargetNodeId) $("#" + tmpTargetNodeId + IDMark_A, tmpTarget).removeClass(Class_TmpTargetNode);770 }771 tmpTarget = null;772 tmpTargetNodeId = null;773774 //判断是否不同的树775 isOtherTree = false;776 targetSetting = setting;777 for (var s in settings) {778 if (settings[s].editable && settings[s].treeObjId != setting.treeObjId779 && (event.target.id == settings[s].treeObjId || $(event.target).parents("#" + settings[s].treeObjId).length>0)) {780 isOtherTree = true;781 targetSetting = settings[s];782 }783 }784785 var docScrollTop = $(doc).scrollTop();786 var docScrollLeft = $(doc).scrollLeft();787 var treeOffset = targetSetting.treeObj.offset();788 var scrollHeight = targetSetting.treeObj.get(0).scrollHeight;789 var scrollWidth = targetSetting.treeObj.get(0).scrollWidth;790 var dTop = (event.clientY + docScrollTop - treeOffset.top);791 var dBottom = (targetSetting.treeObj.height() + treeOffset.top - event.clientY - docScrollTop);792 var dLeft = (event.clientX + docScrollLeft - treeOffset.left);793 var dRight = (targetSetting.treeObj.width() + treeOffset.left - event.clientX - docScrollLeft);794 var isTop = (dTop < 10 && dTop > -5);795 var isBottom = (dBottom < 10 && dBottom > -5);796 var isLeft = (dLeft < 10 && dLeft > -5);797 var isRight = (dRight < 10 && dRight > -5);798 var isTreeTop = (isTop && targetSetting.treeObj.scrollTop() <= 0);799 var isTreeBottom = (isBottom && (targetSetting.treeObj.scrollTop() + targetSetting.treeObj.height()+10) >= scrollHeight);800 var isTreeLeft = (isLeft && targetSetting.treeObj.scrollLeft() <= 0);801 var isTreeRight = (isRight && (targetSetting.treeObj.scrollLeft() + targetSetting.treeObj.width()+10) >= scrollWidth);802803 if (event.target.id && targetSetting.treeObj.find("#" + event.target.id).length > 0) {804 //任意节点 移到 其他节点805 var targetObj = event.target;806 while (targetObj && targetObj.tagName && !tools.eqs(targetObj.tagName, "li") && targetObj.id != targetSetting.treeObjId) {807 targetObj = targetObj.parentNode;808 }809810 var canMove = false;811 //如果移到自己 或者自己的子集,则不能当做临时目标812 if (treeNode.parentNode && targetObj.id != treeNode.tId && $("#" + treeNode.tId).find("#" + targetObj.id).length == 0) {813 //非根节点移动814 canMove = true;815 } else if (treeNode.parentNode == null && targetObj.id != treeNode.tId && $("#" + treeNode.tId).find("#" + targetObj.id).length == 0) {816 //根节点移动817 canMove = true;818 }819 if (canMove) {820 if (event.target.id &&821 (event.target.id == (targetObj.id + IDMark_A) || $(event.target).parents("#" + targetObj.id + IDMark_A).length > 0)) {822 tmpTarget = $(targetObj);823 tmpTargetNodeId = targetObj.id;824 }825 }826 }827828 //确保鼠标在zTree内部829 if (event.target.id == targetSetting.treeObjId || $(event.target).parents("#" + targetSetting.treeObjId).length>0) {830 //只有移动到zTree容器的边缘才算移到 根(排除根节点在本棵树内的移动)831 if (!tmpTarget && (isTreeTop || isTreeBottom || isTreeLeft || isTreeRight) && (isOtherTree || (!isOtherTree && treeNode.parentNode != null))) {832 tmpTarget = targetSetting.treeObj;833 tmpTarget.addClass(Class_TmpTargetTree);834 }835 //滚动条自动滚动836 if (isTop) {837 targetSetting.treeObj.scrollTop(targetSetting.treeObj.scrollTop()-10);838 } else if (isBottom) {839 targetSetting.treeObj.scrollTop(targetSetting.treeObj.scrollTop()+10);840 }841 if (isLeft) {842 targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()-10);843 } else if (isRight) {844 targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()+10);845 }846 //目标节点在可视区域左侧,自动移动横向滚动条847 if (tmpTarget && tmpTarget != targetSetting.treeObj && tmpTarget.offset().left < targetSetting.treeObj.offset().left) {848 targetSetting.treeObj.scrollLeft(targetSetting.treeObj.scrollLeft()+ tmpTarget.offset().left - targetSetting.treeObj.offset().left);849 }850 }851852 curNode.css({853 "top": (event.clientY + docScrollTop + 3) + "px",854 "left": (event.clientX + docScrollLeft + 3) + "px"855 });856857 var dX = 0;858 var dY = 0;859 if (tmpTarget && tmpTarget.attr("id")!=targetSetting.treeObjId) {860 var tmpTargetNode = tmpTargetNodeId == null ? null: getTreeNodeByTId(targetSetting, tmpTargetNodeId);861 var tmpNodeObj = $("#" + treeNode.tId);862 var isPrev = (tmpNodeObj.prev().attr("id") == tmpTargetNodeId) ;863 var isNext = (tmpNodeObj.next().attr("id") == tmpTargetNodeId) ;864 var isInner = (treeNode.parentNode && treeNode.parentNode.tId == tmpTargetNodeId) ;865866 var canPrev = !isNext;867 var canNext = !isPrev;868 var canInner = !isInner && !(targetSetting.keepLeaf && !tmpTargetNode.isParent);869 if (!canPrev && !canNext && !canInner) {870 tmpTarget = null;871 tmpTargetNodeId = "";872 moveType = MoveType_Inner;873 tmpArrow.css({874 "display":"none"875 });876 if (window.zTreeMoveTimer) {877 clearTimeout(window.zTreeMoveTimer);878 }879 } else {880 var tmpTargetA = $("#" + tmpTargetNodeId + IDMark_A, tmpTarget);881 tmpTargetA.addClass(Class_TmpTargetNode);882883 var prevPercent = canPrev ? (canInner ? 0.25 : (canNext ? 0.5 : 1) ) : -1;884 var nextPercent = canNext ? (canInner ? 0.75 : (canPrev ? 0.5 : 0) ) : -1;885 var dY_percent = (event.clientY + docScrollTop - tmpTargetA.offset().top)/tmpTargetA.height();886 if ((prevPercent==1 ||dY_percent<=prevPercent && dY_percent>=-.2) && canPrev) {887 dX = 1 - tmpArrow.width();888 dY = 0 - tmpArrow.height()/2;889 moveType = MoveType_Before;890 } else if ((nextPercent==0 || dY_percent>=nextPercent && dY_percent<=1.2) && canNext) {891 dX = 1 - tmpArrow.width();892 dY = tmpTargetA.height() - tmpArrow.height()/2;893 moveType = MoveType_After;894 }else {895 dX = 5 - tmpArrow.width();896 dY = 0;897 moveType = MoveType_Inner;898 }899 tmpArrow.css({900 "display":"block",901 "top": (tmpTargetA.offset().top + dY) + "px",902 "left": (tmpTargetA.offset().left + dX) + "px"903 }); 904905 if (preTmpTargetNodeId != tmpTargetNodeId || preTmpMoveType != moveType) {906 startTime = (new Date()).getTime();907 }908 if (moveType == MoveType_Inner) {909 window.zTreeMoveTimer = setTimeout(function() {910 if (moveType != MoveType_Inner) return;911 var targetNode = getTreeNodeByTId(targetSetting, tmpTargetNodeId);912 if (targetNode && targetNode.isParent && !targetNode.open && (new Date()).getTime() - startTime > 500913 && tools.apply(targetSetting.callback.confirmDragOpen, [targetSetting.treeObjId, targetNode], true)) {914 switchNode(targetSetting, targetNode);915 }916 }, 600);917 }918 }919 } else {920 moveType = MoveType_Inner;921 tmpArrow.css({922 "display":"none"923 });924 if (window.zTreeMoveTimer) {925 clearTimeout(window.zTreeMoveTimer);926 }927 }928 preTmpTargetNodeId = tmpTargetNodeId;929 preTmpMoveType = moveType;930 }931 return false;932 });933934 $(doc).mouseup(function(event) {935 if (window.zTreeMoveTimer) {936 clearTimeout(window.zTreeMoveTimer);937 }938 preTmpTargetNodeId = null;939 preTmpMoveType = null;940 $(doc).unbind("mousemove");941 $(doc).unbind("mouseup");942 $("body").css("cursor", "auto");943 if (tmpTarget) {944 tmpTarget.removeClass(Class_TmpTargetTree);945 if (tmpTargetNodeId) $("#" + tmpTargetNodeId + IDMark_A, tmpTarget).removeClass(Class_TmpTargetNode);946 }947 showIfameMask(false);948949 if (setting.dragStatus == 0) return;950 setting.dragStatus = 0;951952 if (treeNode.isParent && setting.dragNodeShowBefore && !treeNode.open) {953 expandAndCollapseNode(setting, treeNode, !treeNode.open);954 setting.dragNodeShowBefore = false;955 }956957 if (curNode) curNode.remove();958 if (tmpArrow) tmpArrow.remove();959960 //显示树上 移动后的节点961 if (tmpTarget && tmpTargetNodeId && treeNode.parentNode && tmpTargetNodeId==treeNode.parentNode.tId && moveType == MoveType_Inner) {962 tmpTarget = null;963 }964 if (tmpTarget) {965 var dragTargetNode = tmpTargetNodeId == null ? null: getTreeNodeByTId(targetSetting, tmpTargetNodeId);966 if (tools.apply(setting.callback.beforeDrop, [targetSetting.treeObjId, treeNode, dragTargetNode, moveType], true) == false) return;967 var isCopy = (event.ctrlKey && setting.dragMove && setting.dragCopy) || (!setting.dragMove && setting.dragCopy);968969 var newNode = isCopy ? tools.clone(treeNode) : treeNode;970 if (isOtherTree) {971 if (!isCopy) {removeTreeNode(setting, treeNode);}972 if (moveType == MoveType_Inner) {973 addTreeNodes(targetSetting, dragTargetNode, [newNode]);974 } else {975 addTreeNodes(targetSetting, dragTargetNode.parentNode, [newNode]);976 moveTreeNode(targetSetting, dragTargetNode, newNode, moveType, false);977 }978 }else {979 if (isCopy) {980 if (moveType == MoveType_Inner) {981 addTreeNodes(targetSetting, dragTargetNode, [newNode]);982 } else {983 addTreeNodes(targetSetting, dragTargetNode.parentNode, [newNode]);984 moveTreeNode(targetSetting, dragTargetNode, newNode, moveType, false);985 }986 } else {987 moveTreeNode(targetSetting, dragTargetNode, newNode, moveType);988 } 989 }990 selectNode(targetSetting, newNode);991 $("#" + newNode.tId + IDMark_Icon).focus().blur();992993 //触发 DROP 拖拽事件,返回拖拽的目标数据对象994 setting.treeObj.trigger(ZTREE_DROP, [targetSetting.treeObjId, newNode, dragTargetNode, moveType]);995996 } else {997 //触发 DROP 拖拽事件,返回null998 setting.treeObj.trigger(ZTREE_DROP, [setting.treeObjId, null, null, null]);999 }1000 });10011002 //阻止默认事件专门用于处理 FireFox 的Bug,1003 //该 Bug 导致如果 zTree Div CSS 中存在 overflow 设置,则拖拽节点移出 zTree 时,无法得到正确的event.target1004 if(eventMouseDown.preventDefault) {1005 eventMouseDown.preventDefault();1006 }1007 },1008 onHoverOverNode: function(event) {1009 var setting = settings[event.data.treeObjId];1010 var treeNode = event.data.treeNode;1011 if (setting.curHoverTreeNode != treeNode) {1012 event.data.treeNode = setting.curHoverTreeNode;1013 handler.onHoverOutNode(event);1014 }1015 setting.curHoverTreeNode = treeNode;1016 addTreeDom(setting, treeNode);1017 },1018 onHoverOutNode: function(event) {1019 var setting = settings[event.data.treeObjId];1020 if (setting.curHoverTreeNode && setting.curTreeNode != setting.curHoverTreeNode) {1021 removeTreeDom(setting, setting.curHoverTreeNode);1022 setting.curHoverTreeNode = null;1023 }1024 },1025 onZTreeMousedown: function(event) {1026 var setting = settings[event.data.treeObjId];1027 var treeNode = event.data.treeNode;1028 //触发mouseDown事件1029 if (tools.apply(setting.callback.beforeMouseDown, [setting.treeObjId, treeNode], true)) {1030 tools.apply(setting.callback.mouseDown, [event, setting.treeObjId, treeNode]);1031 }1032 return true;1033 },1034 onZTreeMouseup: function(event) {1035 var setting = settings[event.data.treeObjId];1036 var treeNode = event.data.treeNode;1037 //触发mouseUp事件1038 if (tools.apply(setting.callback.beforeMouseUp, [setting.treeObjId, treeNode], true)) {1039 tools.apply(setting.callback.mouseUp, [event, setting.treeObjId, treeNode]);1040 }1041 return true;1042 },1043 onZTreeDblclick: function(event) {1044 var setting = settings[event.data.treeObjId];1045 var treeNode = event.data.treeNode;1046 //触发mouseUp事件1047 if (tools.apply(setting.callback.beforeDblclick, [setting.treeObjId, treeNode], true)) {1048 tools.apply(setting.callback.dblclick, [event, setting.treeObjId, treeNode]);1049 }1050 return true;1051 },1052 onZTreeContextmenu: function(event) {1053 var setting = settings[event.data.treeObjId];1054 var treeNode = event.data.treeNode;1055 //触发rightClick事件1056 if (tools.apply(setting.callback.beforeRightClick, [setting.treeObjId, treeNode], true)) {1057 tools.apply(setting.callback.rightClick, [event, setting.treeObjId, treeNode]);1058 }1059 return (typeof setting.callback.rightClick) != "function";1060 } 1061 };10621063 //设置光标位置函数1064 function setCursorPosition(obj, pos){1065 if(obj.setSelectionRange) {1066 obj.focus();1067 obj.setSelectionRange(pos,pos);1068 } else if (obj.createTextRange) {1069 var range = obj.createTextRange();1070 range.collapse(true);1071 range.moveEnd('character', pos);1072 range.moveStart('character', pos);1073 range.select();1074 }1075 }10761077 var dragMaskList = new Array();1078 //显示、隐藏 Iframe的遮罩层(主要用于避免拖拽不流畅)1079 function showIfameMask(showSign) {1080 //清空所有遮罩1081 while (dragMaskList.length > 0) {1082 dragMaskList[0].remove();1083 dragMaskList.shift();1084 }1085 if (showSign) {1086 //显示遮罩1087 var iframeList = $("iframe");1088 for (var i = 0, l = iframeList.length; i < l; i++) {1089 var obj = iframeList.get(i);1090 var r = tools.getAbs(obj);1091 var dragMask = $("<div id='zTreeMask_" + i + "' class='zTreeMask' style='top:" + r[1] + "px; left:" + r[0] + "px; width:" + obj.offsetWidth + "px; height:" + obj.offsetHeight + "px;'></div>");1092 dragMask.appendTo("body");1093 dragMaskList.push(dragMask);1094 }1095 }1096 }1097 1098 //设置Name1099 function setNodeName(setting, treeNode) {1100 var nObj = $("#" + treeNode.tId + IDMark_Span);1101 nObj.text(treeNode[setting.nameCol]);1102 }1103 //设置Target1104 function setNodeTarget(treeNode) {1105 var aObj = $("#" + treeNode.tId + IDMark_A);1106 aObj.attr("target", makeNodeTarget(treeNode));1107 }1108 function makeNodeTarget(treeNode) {1109 return (treeNode.target || "_blank");1110 }1111 //设置URL1112 function setNodeUrl(setting, treeNode) {1113 var aObj = $("#" + treeNode.tId + IDMark_A);1114 var url = makeNodeUrl(setting, treeNode);1115 if (url == null || url.length == 0) {1116 aObj.removeAttr("href");1117 } else {1118 aObj.attr("href", url);1119 }1120 }1121 function makeNodeUrl(setting, treeNode) {1122 return (treeNode.url && !setting.editable) ? treeNode.url : null; 1123 }1124 //设置Line、Ico等css属性1125 function setNodeLineIcos(setting, treeNode) {1126 if (!treeNode) return;1127 var switchObj = $("#" + treeNode.tId + IDMark_Switch);1128 var ulObj = $("#" + treeNode.tId + IDMark_Ul);1129 var icoObj = $("#" + treeNode.tId + IDMark_Icon);1130 1131 var ulLine = makeUlLineClass(setting, treeNode);1132 if (ulLine.length==0) {1133 ulObj.removeClass(LineMark_Line);1134 } else {1135 ulObj.addClass(ulLine);1136 }1137 1138 switchObj.attr("class", makeNodeLineClass(setting, treeNode)); 1139 icoObj.attr("style", makeNodeIcoStyle(setting, treeNode));1140 icoObj.attr("class", makeNodeIcoClass(setting, treeNode));1141 }1142 function makeNodeLineClass(setting, treeNode) {1143 var lineClass = ["switch"];1144 if (setting.showLine) {1145 if (treeNode.level == 0 && treeNode.isFirstNode && treeNode.isLastNode) {1146 lineClass.push(LineMark_Root);1147 } else if (treeNode.level == 0 && treeNode.isFirstNode) {1148 lineClass.push(LineMark_Roots);1149 } else if (treeNode.isLastNode) {1150 lineClass.push(LineMark_Bottom);1151 } else {1152 lineClass.push(LineMark_Center);1153 }1154 1155 } else {1156 lineClass.push(LineMark_NoLine);1157 }1158 if (treeNode.isParent) {1159 lineClass.push(treeNode.open ? FolderMark_Open : FolderMark_Close);1160 } else {1161 lineClass.push(FolderMark_Docu);1162 }1163 return lineClass.join('_');1164 }1165 function makeUlLineClass(setting, treeNode) {1166 return (setting.showLine && !treeNode.isLastNode) ? LineMark_Line : "";1167 }1168 function makeNodeIcoClass(setting, treeNode) {1169 var icoCss = ["ico"];1170 if (!treeNode.isAjaxing) {1171 icoCss[0] = (treeNode.iconSkin ? treeNode.iconSkin : "") + " " + icoCss[0];1172 if (treeNode.isParent) {1173 icoCss.push(treeNode.open ? FolderMark_Open : FolderMark_Close);1174 } else {1175 icoCss.push(FolderMark_Docu);1176 }1177 }1178 return icoCss.join('_');1179 }1180 function makeNodeIcoStyle(setting, treeNode) {1181 var icoStyle = [];1182 if (!treeNode.isAjaxing) {1183 var icon = (treeNode.isParent && treeNode.iconOpen && treeNode.iconClose) ? (treeNode.open ? treeNode.iconOpen : treeNode.iconClose) : treeNode.icon;1184 if (icon) icoStyle.push("background:url(", icon, ") 0 0 no-repeat;");1185 if (setting.showIcon == false || !tools.apply(setting.showIcon, [setting.treeObjId, treeNode], true)) {1186 icoStyle.push("width:0px;height:0px;");1187 } 1188 }1189 return icoStyle.join('');1190 }1191 1192 //设置自定义字体样式1193 function setNodeFontCss(setting, treeNode) {1194 var aObj = $("#" + treeNode.tId + IDMark_A);1195 var fontCss = makeNodeFontCss(setting, treeNode);1196 if (fontCss) {1197 aObj.css(fontCss);1198 }1199 }1200 function makeNodeFontCss(setting, treeNode) {1201 var fontCss = tools.apply(setting.fontCss, [setting.treeObjId, treeNode]);1202 if (fontCss == null) {1203 fontCss = setting.fontCss;1204 }1205 if (fontCss) {1206 return fontCss;1207 } else {1208 return {};1209 } 1210 }12111212 //对于button替换class 拼接字符串1213 function replaceSwitchClass(obj, newName) {1214 if (!obj) return;12151216 var tmpName = obj.attr("class");1217 if (tmpName == undefined) return;1218 var tmpList = tmpName.split("_");1219 switch (newName) {1220 case LineMark_Root:1221 case LineMark_Roots:1222 case LineMark_Center:1223 case LineMark_Bottom:1224 case LineMark_NoLine:1225 tmpList[1] = newName;1226 break;1227 case FolderMark_Open:1228 case FolderMark_Close:1229 case FolderMark_Docu:1230 tmpList[2] = newName;1231 break;1232 }12331234 obj.attr("class", tmpList.join("_"));1235 }1236 function replaceIcoClass(treeNode, obj, newName) {1237 if (!obj || treeNode.isAjaxing) return;12381239 var tmpName = obj.attr("class");1240 if (tmpName == undefined) return;1241 var tmpList = tmpName.split("_");1242 switch (newName) {1243 case FolderMark_Open:1244 case FolderMark_Close:1245 case FolderMark_Docu:1246 tmpList[1] = newName;1247 break;1248 }12491250 obj.attr("class", tmpList.join("_"));1251 }1252 1253 //添加zTree的按钮控件1254 function addTreeDom(setting, treeNode) {1255 if (setting.dragStatus == 0) {1256 treeNode.isHover = true;1257 if (setting.editable) {1258 addEditBtn(setting, treeNode);1259 addRemoveBtn(setting, treeNode);1260 }1261 tools.apply(setting.addHoverDom, [setting.treeObjId, treeNode]);1262 }1263 }1264 //删除zTree的按钮控件1265 function removeTreeDom(setting, treeNode) {1266 treeNode.isHover = false;1267 removeEditBtn(treeNode); 1268 removeRemoveBtn(treeNode);1269 tools.apply(setting.removeHoverDom, [setting.treeObjId, treeNode]);1270 }1271 //删除 编辑、删除按钮1272 function removeEditBtn(treeNode) { 1273 $("#" + treeNode.tId + IDMark_Edit).unbind().remove();1274 }1275 function removeRemoveBtn(treeNode) { 1276 $("#" + treeNode.tId + IDMark_Remove).unbind().remove();1277 }1278 function addEditBtn(setting, treeNode) {1279 if (treeNode.editNameStatus || $("#" + treeNode.tId + IDMark_Edit).length > 0) {1280 return;1281 }1282 if (!tools.apply(setting.edit_renameBtn, [treeNode], setting.edit_renameBtn)) {1283 return;1284 }1285 var nObj = $("#" + treeNode.tId + IDMark_Span);1286 var editStr = "<button type='button' class='edit' id='" + treeNode.tId + IDMark_Edit + "' title='' treeNode"+IDMark_Edit+" onfocus='this.blur();' style='display:none;'></button>";1287 nObj.after(editStr);1288 1289 $("#" + treeNode.tId + IDMark_Edit).bind('click', 1290 function() {1291 if (tools.apply(setting.callback.beforeRename, [setting.treeObjId, treeNode], true) == false) return true;1292 editTreeNode(setting, treeNode);1293 return false;1294 }1295 ).show();1296 }1297 function addRemoveBtn(setting, treeNode) { 1298 if (!setting.edit_removeBtn || $("#" + treeNode.tId + IDMark_Remove).length > 0) {1299 return;1300 }1301 if (!tools.apply(setting.edit_removeBtn, [treeNode], setting.edit_removeBtn)) {1302 return;1303 } 1304 var aObj = $("#" + treeNode.tId + IDMark_A);1305 var removeStr = "<button type='button' class='remove' id='" + treeNode.tId + IDMark_Remove + "' title='' treeNode"+IDMark_Remove+" onfocus='this.blur();' style='display:none;'></button>";1306 aObj.append(removeStr);1307 1308 $("#" + treeNode.tId + IDMark_Remove).bind('click', 1309 function() {1310 if (tools.apply(setting.callback.beforeRemove, [setting.treeObjId, treeNode], true) == false) return true;1311 removeTreeNode(setting, treeNode);1312 //触发remove事件1313 setting.treeObj.trigger(ZTREE_REMOVE, [setting.treeObjId, treeNode]);1314 return false;1315 }1316 ).bind('mousedown',1317 function(eventMouseDown) {1318 return true;1319 }1320 ).show();1321 }1322 1323 //设置check后,父子节点联动关系1324 function checkNodeRelation(setting, treeNode) {1325 var pNode, i, l;1326 if (setting.checkStyle == Check_Style_Radio) {1327 if (treeNode[setting.checkedCol]) {1328 if (setting.checkRadioType == Radio_Type_All) {1329 for (i = setting.checkRadioCheckedList.length-1; i >= 0; i--) {1330 pNode = setting.checkRadioCheckedList[i];1331 pNode[setting.checkedCol] = false;1332 setting.checkRadioCheckedList.splice(i, 1);1333 1334 setChkClass(setting, $("#" + pNode.tId + IDMark_Check), pNode);1335 if (pNode.parentNode != treeNode.parentNode) {1336 repairParentChkClassWithSelf(setting, pNode);1337 }1338 }1339 setting.checkRadioCheckedList = setting.checkRadioCheckedList.concat([treeNode]);1340 } else {1341 var parentNode = (treeNode.parentNode) ? treeNode.parentNode : setting.root;1342 for (i = 0, l = parentNode[setting.nodesCol].length; i < l; i++) {1343 pNode = parentNode[setting.nodesCol][i];1344 if (pNode[setting.checkedCol] && pNode != treeNode) {1345 pNode[setting.checkedCol] = false;1346 setChkClass(setting, $("#" + pNode.tId + IDMark_Check), pNode);1347 }1348 }1349 }1350 } else if (setting.checkRadioType == Radio_Type_All) {1351 for (i = 0, l = setting.checkRadioCheckedList.length; i < l; i++) {1352 if (treeNode == setting.checkRadioCheckedList[i]) {1353 setting.checkRadioCheckedList.splice(i, 1);1354 break;1355 }1356 }1357 }1358 1359 } else {1360 if (treeNode[setting.checkedCol] && setting.checkType.Y.indexOf("s") > -1) {1361 setSonNodeCheckBox(setting, treeNode, true);1362 }1363 if (treeNode[setting.checkedCol] && setting.checkType.Y.indexOf("p") > -1) {1364 setParentNodeCheckBox(setting, treeNode, true);1365 }1366 if (!treeNode[setting.checkedCol] && setting.checkType.N.indexOf("s") > -1) {1367 setSonNodeCheckBox(setting, treeNode, false);1368 }1369 if (!treeNode[setting.checkedCol] && setting.checkType.N.indexOf("p") > -1) {1370 setParentNodeCheckBox(setting, treeNode, false);1371 }1372 }1373 }1374 1375 //遍历父节点设置checkbox1376 function setParentNodeCheckBox(setting, treeNode, value) {1377 var checkObj = $("#" + treeNode.tId + IDMark_Check);1378 treeNode[setting.checkedCol] = value;1379 setChkClass(setting, checkObj, treeNode);1380 if (treeNode.parentNode) {1381 var pSign = true;1382 if (!value) {1383 for (var i = 0, l = treeNode.parentNode[setting.nodesCol].length; i < l; i++) {1384 if (treeNode.parentNode[setting.nodesCol][i][setting.checkedCol]) {1385 pSign = false;1386 break;1387 }1388 }1389 }1390 if (pSign) {1391 setParentNodeCheckBox(setting, treeNode.parentNode, value);1392 }1393 }1394 }13951396 //遍历子节点设置checkbox1397 function setSonNodeCheckBox(setting, treeNode, value) {1398 if (!treeNode) return;1399 var checkObj = $("#" + treeNode.tId + IDMark_Check);14001401 if (treeNode != setting.root) {1402 treeNode[setting.checkedCol] = value;1403 treeNode.check_True_Full = true;1404 treeNode.check_False_Full = true;1405 setChkClass(setting, checkObj, treeNode);1406 }14071408 if (!treeNode[setting.nodesCol]) return;1409 for (var i = 0, l = treeNode[setting.nodesCol].length; i < l; i++) {1410 if (treeNode[setting.nodesCol][i]) setSonNodeCheckBox(setting, treeNode[setting.nodesCol][i], value);1411 }1412 }1413 1414 //设置CheckBox的Class类型,主要用于显示子节点是否全部被选择的样式1415 function setChkClass(setting, obj, treeNode) {1416 if (!obj) return;1417 if (treeNode.nocheck === true) {1418 obj.hide();1419 } else {1420 obj.show();1421 }1422 obj.removeClass();1423 obj.addClass(makeChkClass(setting, treeNode));1424 }1425 function makeChkClass(setting, treeNode) {1426 var chkName = setting.checkStyle + "_" + (treeNode[setting.checkedCol] ? CheckBox_True : CheckBox_False)1427 + "_" + ((treeNode[setting.checkedCol] || setting.checkStyle == Check_Style_Radio) ? (treeNode.check_True_Full? CheckBox_Full:CheckBox_Part) : (treeNode.check_False_Full? CheckBox_Full:CheckBox_Part) );1428 chkName = treeNode.checkboxFocus ? chkName + "_" + CheckBox_Focus : chkName;1429 return CheckBox_Default + " " + chkName;1430 }1431 1432 function repairAllChk(setting, checked) {1433 if (setting.checkable) {1434 for (var son = 0; son < setting.root[setting.nodesCol].length; son++) {1435 var treeNode = setting.root[setting.nodesCol][son];1436 treeNode[setting.checkedCol] = checked;1437 setSonNodeCheckBox(setting, treeNode, checked);1438 }1439 }1440 }1441 //修正父节点选择的样式1442 function repairParentChkClass(setting, treeNode) {1443 if (!treeNode || !treeNode.parentNode) return;1444 repairChkClass(setting, treeNode.parentNode);1445 repairParentChkClass(setting, treeNode.parentNode);1446 } 1447 function repairParentChkClassWithSelf(setting, treeNode) {1448 if (!treeNode) return;1449 if (treeNode[setting.nodesCol] && treeNode[setting.nodesCol].length > 0) {1450 repairParentChkClass(setting, treeNode[setting.nodesCol][0]);1451 } else {1452 repairParentChkClass(setting, treeNode);1453 }1454 }14551456 function repairChkClass(setting, treeNode) {1457 if (!treeNode) return;1458 makeChkFlag(setting, treeNode);1459 var checkObj = $("#" + treeNode.tId + IDMark_Check);1460 setChkClass(setting, checkObj, treeNode);1461 }1462 function makeChkFlag(setting, treeNode) {1463 if (!treeNode) return;1464 var chkFlag = {"trueFlag": true, "falseFlag": true};1465 if (treeNode[setting.nodesCol]) {1466 for (var i = 0, l = treeNode[setting.nodesCol].length; i < l; i++) {1467 if (setting.checkStyle == Check_Style_Radio && (treeNode[setting.nodesCol][i][setting.checkedCol] || !treeNode[setting.nodesCol][i].check_True_Full)) {1468 chkFlag.trueFlag = false;1469 } else if (setting.checkStyle != Check_Style_Radio && treeNode[setting.checkedCol] && (!treeNode[setting.nodesCol][i][setting.checkedCol] || !treeNode[setting.nodesCol][i].check_True_Full)) {1470 chkFlag.trueFlag = false;1471 } else if (setting.checkStyle != Check_Style_Radio && !treeNode[setting.checkedCol] && (treeNode[setting.nodesCol][i][setting.checkedCol] || !treeNode[setting.nodesCol][i].check_False_Full)) {1472 chkFlag.falseFlag = false;1473 }1474 if (!chkFlag.trueFlag || !chkFlag.falseFlag) break;1475 }1476 }1477 treeNode.check_True_Full = chkFlag.trueFlag;1478 treeNode.check_False_Full = chkFlag.falseFlag;1479 }14801481 function switchNode(setting, treeNode) {1482 if (treeNode.open || (treeNode && treeNode[setting.nodesCol] && treeNode[setting.nodesCol].length > 0)) {1483 expandAndCollapseNode(setting, treeNode, !treeNode.open);1484 } else if (setting.async) {1485 if (tools.apply(setting.callback.beforeAsync, [setting.treeObjId, treeNode], true) == false) {1486 expandAndCollapseNode(setting, treeNode, !treeNode.open);1487 return;1488 } 1489 asyncGetNode(setting, treeNode);1490 } else if (treeNode) {1491 expandAndCollapseNode(setting, treeNode, !treeNode.open);1492 }1493 }14941495 function asyncGetNode(setting, treeNode) {1496 var i, l;1497 if (treeNode && (treeNode.isAjaxing || !treeNode.isParent)) {1498 return;1499 }1500 if (treeNode) {1501 treeNode.isAjaxing = true;1502 var icoObj = $("#" + treeNode.tId + IDMark_Icon);1503 icoObj.attr("class", "ico_loading");1504 }15051506 var tmpParam = "";1507 for (i = 0, l = setting.asyncParam.length; treeNode && i < l; i++) {1508 tmpParam += (tmpParam.length > 0 ? "&": "") + setting.asyncParam[i] + "=" + treeNode[setting.asyncParam[i]];1509 }1510 if (tools.isArray(setting.asyncParamOther)) {1511 for (i = 0, l = setting.asyncParamOther.length; i < l; i += 2) {1512 tmpParam += (tmpParam.length > 0 ? "&": "") + setting.asyncParamOther[i] + "=" + setting.asyncParamOther[i + 1];1513 }1514 } else {1515 for (var p in setting.asyncParamOther) {1516 tmpParam += (tmpParam.length > 0 ? "&" : "") + p + "=" + setting.asyncParamOther[p];1517 }1518 }1519 1520 $.ajax({1521 type: "POST",1522 url: tools.apply(setting.asyncUrl, [treeNode], setting.asyncUrl),1523 data: tmpParam,1524 dataType: "text",1525 success: function(msg) {1526 var newNodes = [];1527 try {1528 if (!msg || msg.length == 0) {1529 newNodes = [];1530 } else if (typeof msg == "string") {1531 newNodes = eval("(" + msg + ")");1532 } else {1533 newNodes = msg;1534 }1535 } catch(err) {}1536 1537 if (treeNode) treeNode.isAjaxing = null;1538 setNodeLineIcos(setting, treeNode);1539 if (newNodes && newNodes != "") {1540 newNodes = tools.apply(setting.asyncDataFilter, [setting.treeObjId, treeNode, newNodes], newNodes);1541 addTreeNodes(setting, treeNode, newNodes, false);1542 } else {1543 addTreeNodes(setting, treeNode, [], false);1544 }1545 setting.treeObj.trigger(ZTREE_ASYNC_SUCCESS, [setting.treeObjId, treeNode, msg]);15461547 },1548 error: function(XMLHttpRequest, textStatus, errorThrown) {1549 setting.expandTriggerFlag = false;1550 setNodeLineIcos(setting, treeNode);1551 if (treeNode) treeNode.isAjaxing = null;1552 setting.treeObj.trigger(ZTREE_ASYNC_ERROR, [setting.treeObjId, treeNode, XMLHttpRequest, textStatus, errorThrown]);1553 }1554 });1555 }15561557 // 展开 或者 折叠 节点下级1558 function expandAndCollapseNode(setting, treeNode, expandSign, animateSign, callback) {1559 if (!treeNode || treeNode.open == expandSign) {1560 tools.apply(callback, []);1561 return;1562 } 1563 if (setting.expandTriggerFlag) {1564 callback = function(){1565 if (treeNode.open) {1566 //触发expand事件1567 setting.treeObj.trigger(ZTREE_EXPAND, [setting.treeObjId, treeNode]);1568 } else {1569 //触发collapse事件1570 setting.treeObj.trigger(ZTREE_COLLAPSE, [setting.treeObjId, treeNode]);1571 }1572 };1573 setting.expandTriggerFlag = false;1574 }1575 1576 var switchObj = $("#" + treeNode.tId + IDMark_Switch);1577 var icoObj = $("#" + treeNode.tId + IDMark_Icon);1578 var ulObj = $("#" + treeNode.tId + IDMark_Ul);15791580 if (treeNode.isParent) {1581 treeNode.open = !treeNode.open;1582 if (treeNode.iconOpen && treeNode.iconClose) {1583 icoObj.attr("style", makeNodeIcoStyle(setting, treeNode));1584 }15851586 if (treeNode.open) {1587 replaceSwitchClass(switchObj, FolderMark_Open);1588 replaceIcoClass(treeNode, icoObj, FolderMark_Open);1589 if (animateSign == false || setting.expandSpeed == "") {1590 ulObj.show();1591 tools.apply(callback, []);1592 } else {1593 if (treeNode[setting.nodesCol] && treeNode[setting.nodesCol].length > 0) {1594 ulObj.show(setting.expandSpeed, callback);1595 } else {1596 ulObj.show();1597 tools.apply(callback, []);1598 }1599 }1600 } else {1601 replaceSwitchClass(switchObj, FolderMark_Close);1602 replaceIcoClass(treeNode, icoObj, FolderMark_Close);1603 if (animateSign == false || setting.expandSpeed == "") {1604 ulObj.hide();1605 tools.apply(callback, []);1606 } else {1607 ulObj.hide(setting.expandSpeed, callback);1608 }1609 }1610 } else {1611 tools.apply(callback, []);1612 }1613 }16141615 //遍历子节点展开 或 折叠1616 function expandCollapseSonNode(setting, treeNode, expandSign, animateSign, callback) {1617 var treeNodes = (treeNode) ? treeNode[setting.nodesCol]: setting.root[setting.nodesCol];1618 1619 //针对动画进行优化,一般来说只有在第一层的时候,才进行动画效果1620 var selfAnimateSign = (treeNode) ? false : animateSign;1621 if (treeNodes) {1622 for (var i = 0, l = treeNodes.length; i < l; i++) {1623 if (treeNodes[i]) expandCollapseSonNode(setting, treeNodes[i], expandSign, selfAnimateSign);1624 }1625 }1626 //保证callback只执行一次1627 expandAndCollapseNode(setting, treeNode, expandSign, animateSign, callback );16281629 }16301631 //遍历父节点展开 或 折叠1632 function expandCollapseParentNode(setting, treeNode, expandSign, animateSign, callback) {1633 //针对动画进行优化,一般来说只有在第一层的时候,才进行动画效果1634 if (!treeNode) return;1635 if (!treeNode.parentNode) {1636 //保证callback只执行一次1637 expandAndCollapseNode(setting, treeNode, expandSign, animateSign, callback);1638 return ;1639 } else {1640 expandAndCollapseNode(setting, treeNode, expandSign, animateSign);1641 }1642 1643 if (treeNode.parentNode) {1644 expandCollapseParentNode(setting, treeNode.parentNode, expandSign, animateSign, callback);1645 }1646 }16471648 //遍历子节点设置level,主要用于移动节点后的处理1649 function setSonNodeLevel(setting, parentNode, treeNode) {1650 if (!treeNode) return;1651 treeNode.level = (parentNode)? parentNode.level + 1 : 0;1652 if (!treeNode[setting.nodesCol]) return;1653 for (var i = 0, l = treeNode[setting.nodesCol].length; i < l; i++) {1654 if (treeNode[setting.nodesCol][i]) setSonNodeLevel(setting, treeNode, treeNode[setting.nodesCol][i]);1655 }1656 }16571658 //增加子节点1659 function addTreeNodes(setting, parentNode, newNodes, isSilent) {1660 if (setting.keepLeaf && parentNode && !parentNode.isParent) {1661 return;1662 }1663 if (setting.isSimpleData) {1664 newNodes = transformTozTreeFormat(setting, newNodes);1665 }1666 if (parentNode) {1667 //目标节点必须在当前树内1668 if (setting.treeObj.find("#" + parentNode.tId).length == 0) return;16691670 var target_switchObj = $("#" + parentNode.tId + IDMark_Switch);1671 var target_icoObj = $("#" + parentNode.tId + IDMark_Icon);1672 var target_ulObj = $("#" + parentNode.tId + IDMark_Ul);16731674 //处理节点在目标节点的图片、线1675 if (!parentNode.open) {1676 replaceSwitchClass(target_switchObj, FolderMark_Close);1677 replaceIcoClass(parentNode, target_icoObj, FolderMark_Close); 1678 parentNode.open = false;1679 target_ulObj.css({"display": "none"});1680 }16811682 addTreeNodesData(setting, parentNode, newNodes);1683 initTreeNodes(setting, parentNode.level + 1, newNodes, parentNode);1684 //如果选择某节点,则必须展开其全部父节点1685 if (!isSilent) {1686 expandCollapseParentNode(setting, parentNode, true);1687 }1688 } else {1689 addTreeNodesData(setting, setting.root, newNodes);1690 initTreeNodes(setting, 0, newNodes, null);1691 }1692 }16931694 //增加节点数据1695 function addTreeNodesData(setting, parentNode, treenodes) {1696 if (!parentNode[setting.nodesCol]) parentNode[setting.nodesCol] = [];1697 if (parentNode[setting.nodesCol].length > 0) {1698 parentNode[setting.nodesCol][parentNode[setting.nodesCol].length - 1].isLastNode = false;1699 setNodeLineIcos(setting, parentNode[setting.nodesCol][parentNode[setting.nodesCol].length - 1]);1700 }1701 parentNode.isParent = true;1702 parentNode[setting.nodesCol] = parentNode[setting.nodesCol].concat(treenodes);1703 }17041705 //移动子节点1706 function moveTreeNode(setting, targetNode, treeNode, moveType, animateSign) {1707 if (targetNode == treeNode) return;1708 if (setting.keepLeaf && targetNode && !targetNode.isParent && moveType == MoveType_Inner) return;1709 var oldParentNode = treeNode.parentNode == null ? setting.root: treeNode.parentNode;1710 1711 var targetNodeIsRoot = (targetNode === null || targetNode == setting.root);1712 if (targetNodeIsRoot && targetNode === null) targetNode = setting.root;1713 if (targetNodeIsRoot) moveType = MoveType_Inner;1714 var targetParentNode = (targetNode.parentNode ? targetNode.parentNode : setting.root);17151716 if (moveType != MoveType_Before && moveType != MoveType_After) {1717 moveType = MoveType_Inner;1718 }1719 1720 //进行数据结构修正1721 var i,l;1722 var tmpSrcIndex = -1;1723 var tmpTargetIndex = 0;1724 var oldNeighbor = null;1725 var newNeighbor = null;1726 if (treeNode.isFirstNode) {1727 tmpSrcIndex = 0;1728 if (oldParentNode[setting.nodesCol].length > 1 ) {1729 oldNeighbor = oldParentNode[setting.nodesCol][1];1730 oldNeighbor.isFirstNode = true;1731 }1732 } else if (treeNode.isLastNode) {1733 tmpSrcIndex = oldParentNode[setting.nodesCol].length -1;1734 oldNeighbor = oldParentNode[setting.nodesCol][tmpSrcIndex - 1];1735 oldNeighbor.isLastNode = true;1736 } else {1737 for (i = 0, l = oldParentNode[setting.nodesCol].length; i < l; i++) {1738 if (oldParentNode[setting.nodesCol][i].tId == treeNode.tId) tmpSrcIndex = i;1739 }1740 }1741 if (tmpSrcIndex >= 0) {1742 oldParentNode[setting.nodesCol].splice(tmpSrcIndex, 1);1743 }1744 if (moveType != MoveType_Inner) {1745 for (i = 0, l = targetParentNode[setting.nodesCol].length; i < l; i++) {1746 if (targetParentNode[setting.nodesCol][i].tId == targetNode.tId) tmpTargetIndex = i;1747 }1748 }1749 if (moveType == MoveType_Inner) {1750 if (targetNodeIsRoot) {1751 //成为根节点,则不操作目标节点数据1752 treeNode.parentNode = null;1753 } else {1754 targetNode.isParent = true;1755 treeNode.parentNode = targetNode;1756 }1757 1758 if (!targetNode[setting.nodesCol]) targetNode[setting.nodesCol] = new Array();1759 if (targetNode[setting.nodesCol].length > 0) {1760 newNeighbor = targetNode[setting.nodesCol][targetNode[setting.nodesCol].length - 1];1761 newNeighbor.isLastNode = false;1762 }1763 targetNode[setting.nodesCol].splice(targetNode[setting.nodesCol].length, 0, treeNode);1764 treeNode.isLastNode = true;1765 treeNode.isFirstNode = (targetNode[setting.nodesCol].length == 1);1766 } else if (targetNode.isFirstNode && moveType == MoveType_Before) {1767 targetParentNode[setting.nodesCol].splice(tmpTargetIndex, 0, treeNode);1768 newNeighbor = targetNode;1769 newNeighbor.isFirstNode = false;1770 treeNode.parentNode = targetNode.parentNode;1771 treeNode.isFirstNode = true;1772 treeNode.isLastNode = false;1773 1774 } else if (targetNode.isLastNode && moveType == MoveType_After) {1775 targetParentNode[setting.nodesCol].splice(tmpTargetIndex + 1, 0, treeNode);1776 newNeighbor = targetNode;1777 newNeighbor.isLastNode = false;1778 treeNode.parentNode = targetNode.parentNode;1779 treeNode.isFirstNode = false;1780 treeNode.isLastNode = true;1781 1782 } else {1783 if (moveType == MoveType_Before) {1784 targetParentNode[setting.nodesCol].splice(tmpTargetIndex, 0, treeNode);1785 } else {1786 targetParentNode[setting.nodesCol].splice(tmpTargetIndex + 1, 0, treeNode);1787 }1788 treeNode.parentNode = targetNode.parentNode;1789 treeNode.isFirstNode = false;1790 treeNode.isLastNode = false;1791 }1792 fixParentKeyValue(setting, treeNode);1793 1794 setSonNodeLevel(setting, treeNode.parentNode, treeNode);1795 1796 //进行HTML结构修正1797 var targetObj;1798 var target_switchObj;1799 var target_icoObj;1800 var target_ulObj;18011802 if (targetNodeIsRoot) {1803 //转移到根节点1804 targetObj = setting.treeObj;1805 target_ulObj = targetObj;1806 } else {1807 //转移到子节点1808 targetObj = $("#" + targetNode.tId);1809 target_switchObj = $("#" + targetNode.tId + IDMark_Switch);1810 target_icoObj = $("#" + targetNode.tId + IDMark_Icon);1811 target_ulObj = $("#" + targetNode.tId + IDMark_Ul);1812 }1813 1814 //处理目标节点1815 if (moveType == MoveType_Inner) {1816 replaceSwitchClass(target_switchObj, FolderMark_Open);1817 replaceIcoClass(targetNode, target_icoObj, FolderMark_Open);1818 targetNode.open = true;1819 target_ulObj.css({1820 "display":"block"1821 });1822 target_ulObj.append($("#" + treeNode.tId).remove(null, true));1823 } else if (moveType == MoveType_Before) {1824 targetObj.before($("#" + treeNode.tId).remove(null, true));1825 1826 } else if (moveType == MoveType_After) {1827 targetObj.after($("#" + treeNode.tId).remove(null, true));1828 }18291830 //处理被移动的节点1831 setNodeLineIcos(setting, treeNode);1832 1833 //处理原节点的父节点1834 if (!setting.keepParent && oldParentNode[setting.nodesCol].length < 1) {1835 //原所在父节点无子节点1836 oldParentNode.isParent = false;1837 var tmp_ulObj = $("#" + oldParentNode.tId + IDMark_Ul);1838 var tmp_switchObj = $("#" + oldParentNode.tId + IDMark_Switch);1839 var tmp_icoObj = $("#" + oldParentNode.tId + IDMark_Icon);1840 replaceSwitchClass(tmp_switchObj, FolderMark_Docu);1841 replaceIcoClass(oldParentNode, tmp_icoObj, FolderMark_Docu);1842 tmp_ulObj.css("display", "none");18431844 } else if (oldNeighbor) {1845 //原所在位置需要处理的相邻节点1846 setNodeLineIcos(setting, oldNeighbor);1847 }1848 1849 //处理目标节点的相邻节点1850 if (newNeighbor) {1851 setNodeLineIcos(setting, newNeighbor);1852 }1853 1854 //修正父节点Check状态1855 if (setting.checkable) {1856 repairChkClass(setting, oldParentNode);1857 repairParentChkClassWithSelf(setting, oldParentNode);1858 if (oldParentNode != treeNode.parent) 1859 repairParentChkClassWithSelf(setting, treeNode);1860 }1861 1862 //移动后,则必须展开新位置的全部父节点1863 expandCollapseParentNode(setting, treeNode.parentNode, true, animateSign);1864 }1865 1866 //修正pId1867 function fixParentKeyValue(setting, treeNode) {1868 if (setting.isSimpleData) {1869 treeNode[setting.treeNodeParentKey] = treeNode.parentNode ? treeNode.parentNode[setting.treeNodeKey] : setting.rootPID;1870 }1871 }1872 1873 //编辑子节点名称1874 function editTreeNode(setting, treeNode) {1875 treeNode.editNameStatus = true;1876 removeTreeDom(setting, treeNode);1877 selectNode(setting, treeNode);1878 }18791880 //删除子节点1881 function removeTreeNode(setting, treeNode) {1882 var parentNode = treeNode.parentNode == null ? setting.root: treeNode.parentNode;1883 if (setting.curTreeNode === treeNode) setting.curTreeNode = null;1884 if (setting.curEditTreeNode === treeNode) setting.curEditTreeNode = null;18851886 $("#" + treeNode.tId).remove();1887 removeCache(setting, treeNode);18881889 //进行数据结构修正1890 var tmpSrcIndex = -1;1891 for (var i = 0, l = parentNode[setting.nodesCol].length; i < l; i++) {1892 if (parentNode[setting.nodesCol][i].tId == treeNode.tId) tmpSrcIndex = i;1893 }1894 if (tmpSrcIndex >= 0) {1895 parentNode[setting.nodesCol].splice(tmpSrcIndex, 1);1896 }1897 var tmp_ulObj,tmp_switchObj,tmp_icoObj;18981899 //处理原节点的父节点的图标、线1900 if (!setting.keepParent && parentNode[setting.nodesCol].length < 1) {1901 //原所在父节点无子节点1902 parentNode.isParent = false;1903 parentNode.open = false;1904 tmp_ulObj = $("#" + parentNode.tId + IDMark_Ul);1905 tmp_switchObj = $("#" + parentNode.tId + IDMark_Switch);1906 tmp_icoObj = $("#" + parentNode.tId + IDMark_Icon);1907 replaceSwitchClass(tmp_switchObj, FolderMark_Docu);1908 replaceIcoClass(parentNode, tmp_icoObj, FolderMark_Docu);1909 tmp_ulObj.css("display", "none");19101911 } else if (setting.showLine && parentNode[setting.nodesCol].length > 0) {1912 //原所在父节点有子节点1913 parentNode[setting.nodesCol][parentNode[setting.nodesCol].length - 1].isLastNode = true;1914 parentNode[setting.nodesCol][parentNode[setting.nodesCol].length - 1].isFirstNode = (parentNode[setting.nodesCol].length == 1);1915 tmp_ulObj = $("#" + parentNode[setting.nodesCol][parentNode[setting.nodesCol].length - 1].tId + IDMark_Ul);1916 tmp_switchObj = $("#" + parentNode[setting.nodesCol][parentNode[setting.nodesCol].length - 1].tId + IDMark_Switch);1917 tmp_icoObj = $("#" + parentNode[setting.nodesCol][parentNode[setting.nodesCol].length - 1].tId + IDMark_Icon);1918 if (parentNode == setting.root) {1919 if (parentNode[setting.nodesCol].length == 1) {1920 //原为根节点 ,且移动后只有一个根节点1921 replaceSwitchClass(tmp_switchObj, LineMark_Root);1922 } else {1923 var tmp_first_switchObj = $("#" + parentNode[setting.nodesCol][0].tId + IDMark_Switch);1924 replaceSwitchClass(tmp_first_switchObj, LineMark_Roots);1925 replaceSwitchClass(tmp_switchObj, LineMark_Bottom);1926 }1927 } else {1928 replaceSwitchClass(tmp_switchObj, LineMark_Bottom);1929 }19301931 tmp_ulObj.removeClass(LineMark_Line);1932 }1933 }19341935 //根据 tId 获取 节点的数据对象1936 function getTreeNodeByTId(setting, treeId) {1937 return zTreeNodeCache[setting.treeObjId][treeId];1938 }1939 function addCache(setting, treeNode) {1940 zTreeNodeCache[setting.treeObjId][treeNode.tId] = treeNode;1941 }1942 function removeCache(setting, treeNode) {1943 delete zTreeNodeCache[setting.treeObjId][treeNode.tId];1944 }1945 //根据唯一属性 获取 节点的数据对象1946 function getTreeNodeByParam(setting, treeNodes, key, value) {1947 if (!treeNodes || !key) return null;1948 for (var i = 0, l = treeNodes.length; i < l; i++) {1949 if (treeNodes[i][key] == value) {1950 return treeNodes[i];1951 }1952 var tmp = getTreeNodeByParam(setting, treeNodes[i][setting.nodesCol], key, value);1953 if (tmp) return tmp;1954 }1955 return null;1956 }1957 //根据属性 获取 节点的数据对象集合1958 function getTreeNodesByParam(setting, treeNodes, key, value) {1959 if (!treeNodes || !key) return [];1960 var result = [];1961 for (var i = 0, l = treeNodes.length; i < l; i++) {1962 if (treeNodes[i][key] == value) {1963 result.push(treeNodes[i]);1964 }1965 result = result.concat(getTreeNodesByParam(setting, treeNodes[i][setting.nodesCol], key, value));1966 }1967 return result;1968 }1969 //根据属性 模糊搜索获取 节点的数据对象集合(仅限String)1970 function getTreeNodesByParamFuzzy(setting, treeNodes, key, value) {1971 if (!treeNodes || !key) return [];1972 var result = [];1973 for (var i = 0, l = treeNodes.length; i < l; i++) {1974 if (typeof treeNodes[i][key] == "string" && treeNodes[i][key].indexOf(value)>-1) {1975 result.push(treeNodes[i]);1976 }1977 result = result.concat(getTreeNodesByParamFuzzy(setting, treeNodes[i][setting.nodesCol], key, value));1978 }1979 return result;1980 }1981 1982 //设置节点为当前选中节点1983 function selectNode(setting, treeNode) {1984 if (setting.curTreeNode == treeNode && ((setting.curEditTreeNode == treeNode && treeNode.editNameStatus))) {return;}1985 st.cancelPreEditNode(setting);1986 st.cancelPreSelectedNode(setting);1987 1988 if (setting.editable && treeNode.editNameStatus) {1989 $("#" + treeNode.tId + IDMark_Span).html("<input type=text class='rename' id='" + treeNode.tId + IDMark_Input + "' treeNode" + IDMark_Input + " >");1990 1991 var inputObj = $("#" + treeNode.tId + IDMark_Input);1992 setting.curEditInput = inputObj;1993 inputObj.attr("value", treeNode[setting.nameCol]);1994 tools.inputFocus(inputObj);1995 1996 //拦截A的click dblclick监听1997 inputObj.bind('blur', function(event) {1998 if (st.checkEvent(setting)) {1999 treeNode.editNameStatus = false;2000 selectNode(setting, treeNode);2001 }2002 }).bind('keyup', function(event) {2003 if (event.keyCode=="13") {2004 if (st.checkEvent(setting)) {2005 treeNode.editNameStatus = false;2006 selectNode(setting, treeNode);2007 }2008 } else if (event.keyCode=="27") {2009 inputObj.attr("value", treeNode[setting.nameCol]);2010 treeNode.editNameStatus = false;2011 selectNode(setting, treeNode);2012 }2013 }).bind('click', function(event) {2014 return false;2015 }).bind('dblclick', function(event) {2016 return false;2017 });2018 2019 $("#" + treeNode.tId + IDMark_A).addClass(Class_CurSelectedNode_Edit);2020 setting.curEditTreeNode = treeNode;2021 } else {2022 $("#" + treeNode.tId + IDMark_A).addClass(Class_CurSelectedNode);2023 }2024 addTreeDom(setting, treeNode);2025 setting.curTreeNode = treeNode;2026 }2027 2028 //获取全部 checked = true or false 的节点集合2029 function getTreeCheckedNodes(setting, treeNodes, checked) {2030 if (!treeNodes) return [];2031 var results = [];2032 for (var i = 0, l = treeNodes.length; i < l; i++) {2033 if (treeNodes[i].nocheck !== true && treeNodes[i][setting.checkedCol] == checked) {2034 results = results.concat([treeNodes[i]]);2035 }2036 var tmp = getTreeCheckedNodes(setting, treeNodes[i][setting.nodesCol], checked);2037 if (tmp.length > 0) results = results.concat(tmp);2038 }2039 return results;2040 }2041 2042 //获取全部 被修改Check状态 的节点集合2043 function getTreeChangeCheckedNodes(setting, treeNodes) {2044 if (!treeNodes) return [];2045 var results = [];2046 for (var i = 0, l = treeNodes.length; i < l; i++) {2047 if (treeNodes[i].nocheck !== true && treeNodes[i][setting.checkedCol] != treeNodes[i].checkedOld) {2048 results = results.concat([treeNodes[i]]);2049 }2050 var tmp = getTreeChangeCheckedNodes(setting, treeNodes[i][setting.nodesCol]);2051 if (tmp.length > 0) results = results.concat(tmp);2052 }2053 return results;2054 }2055 2056 //简要数据转换为标准JSON数组2057 function transformTozTreeFormat(setting, simpleTreeNodes) {2058 var i,l;2059 var key = setting.treeNodeKey;2060 var parentKey = setting.treeNodeParentKey;2061 if (!key || key=="" || !simpleTreeNodes) return [];2062 2063 if (tools.isArray(simpleTreeNodes)) {2064 var r = [];2065 var tmpMap = [];2066 for (i=0, l=simpleTreeNodes.length; i<l; i++) {2067 tmpMap[simpleTreeNodes[i][key]] = simpleTreeNodes[i];2068 }2069 for (i=0, l=simpleTreeNodes.length; i<l; i++) {2070 if (tmpMap[simpleTreeNodes[i][parentKey]]) {2071 if (!tmpMap[simpleTreeNodes[i][parentKey]][setting.nodesCol])2072 tmpMap[simpleTreeNodes[i][parentKey]][setting.nodesCol] = [];2073 tmpMap[simpleTreeNodes[i][parentKey]][setting.nodesCol].push(simpleTreeNodes[i]);2074 } else {2075 r.push(simpleTreeNodes[i]);2076 }2077 }2078 return r;2079 }else {2080 return [simpleTreeNodes];2081 }2082 }2083 2084 //标准JSON zTreeNode 数组转换为普通Array简要数据2085 function transformToArrayFormat(setting, treeNodes) {2086 if (!treeNodes) return [];2087 var r = [];2088 if (tools.isArray(treeNodes)) {2089 for (var i=0, l=treeNodes.length; i<l; i++) {2090 r.push(treeNodes[i]);2091 if (treeNodes[i][setting.nodesCol])2092 r = r.concat(transformToArrayFormat(setting, treeNodes[i][setting.nodesCol]));2093 }2094 } else {2095 r.push(treeNodes);2096 if (treeNodes[setting.nodesCol])2097 r = r.concat(transformToArrayFormat(setting, treeNodes[setting.nodesCol]));2098 }2099 return r;2100 }21012102 function zTreePlugin(){2103 return {2104 container:null,2105 setting:null,21062107 init: function(obj) {2108 this.container = obj;2109 this.setting = settings[obj.attr("id")];2110 return this;2111 },21122113 refresh : function() {2114 this.setting.treeObj.empty();2115 zTreeNodeCache[this.setting.treeObjId] = [];2116 this.setting.curTreeNode = null;2117 this.setting.curEditTreeNode = null;2118 this.setting.dragStatus = 0;2119 this.setting.dragNodeShowBefore = false;2120 this.setting.checkRadioCheckedList = [];2121 initTreeNodes(this.setting, 0, this.setting.root[this.setting.nodesCol]);2122 },21232124 setEditable : function(editable) {2125 this.setting.editable = editable;2126 return this.refresh();2127 },2128 2129 transformTozTreeNodes : function(simpleTreeNodes) {2130 return transformTozTreeFormat(this.setting, simpleTreeNodes);2131 },2132 2133 transformToArray : function(treeNodes) {2134 return transformToArrayFormat(this.setting, treeNodes);2135 },21362137 getNodes : function() {2138 return this.setting.root[this.setting.nodesCol];2139 },21402141 getSelectedNode : function() {2142 return this.setting.curTreeNode;2143 },21442145 getCheckedNodes : function(checked) {2146 checked = (checked != false);2147 return getTreeCheckedNodes(this.setting, this.setting.root[this.setting.nodesCol], checked);2148 },2149 2150 getChangeCheckedNodes : function() {2151 return getTreeChangeCheckedNodes(this.setting, this.setting.root[this.setting.nodesCol]);2152 },21532154 getNodeByTId : function(treeId) {2155 if (!treeId) return null;2156 return getTreeNodeByTId(this.setting, treeId);2157 },2158 getNodeByParam : function(key, value) {2159 if (!key) return null;2160 return getTreeNodeByParam(this.setting, this.setting.root[this.setting.nodesCol], key, value);2161 },2162 getNodesByParam : function(key, value) {2163 if (!key) return null;2164 return getTreeNodesByParam(this.setting, this.setting.root[this.setting.nodesCol], key, value);2165 },2166 getNodesByParamFuzzy : function(key, value, parentNode) {2167 if (!key) return null;2168 return getTreeNodesByParamFuzzy(this.setting, parentNode?parentNode[this.setting.nodesCol]:this.setting.root[this.setting.nodesCol], key, value);2169 },2170 2171 getNodeIndex : function(treeNode) {2172 if (!treeNode) return null;2173 var parentNode = (treeNode.parentNode == null) ? this.setting.root : treeNode.parentNode;2174 for (var i=0, l = parentNode[this.setting.nodesCol].length; i < l; i++) {2175 if (parentNode[this.setting.nodesCol][i] == treeNode) return i;2176 }2177 return -1;2178 },2179 2180 getSetting : function() {2181 var zTreeSetting = this.setting;2182 var setting = {2183 checkType:{}, 2184 callback:{}2185 };2186 2187 var tmp_checkType = zTreeSetting.checkType;2188 zTreeSetting.checkType = undefined;2189 var tmp_callback = zTreeSetting.callback;2190 zTreeSetting.callback = undefined;2191 var tmp_root = zTreeSetting.root;2192 zTreeSetting.root = undefined;2193 2194 $.extend(setting, zTreeSetting);2195 2196 zTreeSetting.checkType = tmp_checkType; 2197 zTreeSetting.callback = tmp_callback; 2198 zTreeSetting.root = tmp_root; 21992200 //不能获取root信息2201 $.extend(true, setting.checkType, tmp_checkType);2202 $.extend(setting.callback, tmp_callback);2203 2204 return setting;2205 },2206 2207 updateSetting : function(zTreeSetting) {2208 if (!zTreeSetting) return;2209 var setting = this.setting;2210 var treeObjId = setting.treeObjId;2211 2212 var tmp_checkType = zTreeSetting.checkType;2213 zTreeSetting.checkType = undefined;2214 var tmp_callback = zTreeSetting.callback;2215 zTreeSetting.callback = undefined;2216 var tmp_root = zTreeSetting.root;2217 zTreeSetting.root = undefined;2218 2219 $.extend(setting, zTreeSetting);2220 2221 zTreeSetting.checkType = tmp_checkType;2222 zTreeSetting.callback = tmp_callback;2223 zTreeSetting.root = tmp_root;2224 2225 //不提供root信息update2226 $.extend(true, setting.checkType, tmp_checkType);2227 $.extend(setting.callback, tmp_callback);2228 setting.treeObjId = treeObjId;2229 setting.treeObj = this.container;2230 2231 },22322233 expandAll : function(expandSign) {2234 expandCollapseSonNode(this.setting, null, expandSign, true);2235 },22362237 expandNode : function(treeNode, expandSign, sonSign, focus) {2238 if (!treeNode) return;22392240 if (expandSign) {2241 //如果展开某节点,则必须展开其全部父节点2242 //为了保证效率,展开父节点时不使用动画2243 if (treeNode.parentNode) expandCollapseParentNode(this.setting, treeNode.parentNode, expandSign, false);2244 }2245 if (sonSign) {2246 //多个图层同时进行动画,导致产生的延迟很难用代码准确捕获动画最终结束时间2247 //因此为了保证准确将节点focus进行定位,则对于js操作节点时,不进行动画2248 expandCollapseSonNode(this.setting, treeNode, expandSign, false, function() {2249 if (focus !== false) {$("#" + treeNode.tId + IDMark_Icon).focus().blur();}2250 });2251 } else if (treeNode.open != expandSign) {2252 switchNode(this.setting, treeNode);2253 if (focus !== false) {$("#" + treeNode.tId + IDMark_Icon).focus().blur();}2254 }2255 },22562257 selectNode : function(treeNode) {2258 if (!treeNode) return;22592260 if (st.checkEvent(this.setting)) {2261 selectNode(this.setting, treeNode);2262 //如果选择某节点,则必须展开其全部父节点2263 //多个图层同时进行动画,导致产生的延迟很难用代码准确捕获动画最终结束时间2264 //因此为了保证准确将节点focus进行定位,则对于js操作节点时,不进行动画2265 if (treeNode.parentNode) {2266 expandCollapseParentNode(this.setting, treeNode.parentNode, true, false, function() {2267 $("#" + treeNode.tId + IDMark_Icon).focus().blur();2268 });2269 } else {2270 $("#" + treeNode.tId + IDMark_Icon).focus().blur();2271 }2272 }2273 },2274 2275 cancleSelectedNode : function() {2276 this.cancelSelectedNode();2277 },2278 cancelSelectedNode : function() {2279 st.cancelPreSelectedNode(this.setting);2280 },2281 2282 checkAllNodes : function(checked) {2283 repairAllChk(this.setting, checked);2284 },2285 2286 reAsyncChildNodes : function(parentNode, reloadType) {2287 if (!this.setting.async) return;2288 var isRoot = !parentNode;2289 if (isRoot) {2290 parentNode = this.setting.root;2291 }2292 if (reloadType=="refresh") {2293 parentNode[this.setting.nodesCol] = [];2294 if (isRoot) {2295 this.setting.treeObj.empty();2296 } else {2297 var ulObj = $("#" + parentNode.tId + IDMark_Ul);2298 ulObj.empty();2299 }2300 }2301 asyncGetNode(this.setting, isRoot? null:parentNode);2302 },23032304 addNodes : function(parentNode, newNodes, isSilent) {2305 if (!newNodes) return;2306 if (!parentNode) parentNode = null;2307 var xNewNodes = tools.isArray(newNodes)? newNodes: [newNodes];2308 addTreeNodes(this.setting, parentNode, xNewNodes, (isSilent==true));2309 },2310 inputNodeName: function(treeNode) {2311 if (!treeNode) return;2312 if (st.checkEvent(this.setting)) {2313 editTreeNode(this.setting, treeNode)2314 }2315 },2316 cancelInput: function(newName) {2317 if (!this.setting.curEditTreeNode) return;2318 var treeNode = this.setting.curEditTreeNode;2319 st.cancelPreEditNode(this.setting, newName?newName:treeNode[this.setting.nameCol]);2320 this.selectNode(treeNode);2321 },2322 updateNode : function(treeNode, checkTypeFlag) {2323 if (!treeNode) return;2324 if (st.checkEvent(this.setting)) {2325 var checkObj = $("#" + treeNode.tId + IDMark_Check);2326 if (this.setting.checkable) {2327 if (checkTypeFlag == true) checkNodeRelation(this.setting, treeNode);2328 setChkClass(this.setting, checkObj, treeNode);2329 repairParentChkClassWithSelf(this.setting, treeNode);2330 }2331 setNodeName(this.setting, treeNode);2332 setNodeTarget(treeNode);2333 setNodeUrl(this.setting, treeNode);2334 setNodeLineIcos(this.setting, treeNode);2335 setNodeFontCss(this.setting, treeNode);2336 }2337 },23382339 moveNode : function(targetNode, treeNode, moveType) {2340 if (!treeNode) return;2341 2342 if (targetNode && ((treeNode.parentNode == targetNode && moveType == MoveType_Inner) || $("#" + treeNode.tId).find("#" + targetNode.tId).length > 0)) {2343 return;2344 } else if (!targetNode) {2345 targetNode = null;2346 }2347 moveTreeNode(this.setting, targetNode, treeNode, moveType, false);2348 },23492350 copyNode : function(targetNode, treeNode, moveType) {2351 if (!treeNode) return null;2352 var newNode = tools.clone(treeNode);2353 if (!targetNode) {2354 targetNode = null;2355 moveType = MoveType_Inner;2356 }2357 if (moveType == MoveType_Inner) {2358 addTreeNodes(this.setting, targetNode, [newNode]);2359 } else {2360 addTreeNodes(this.setting, targetNode.parentNode, [newNode]);2361 moveTreeNode(this.setting, targetNode, newNode, moveType, false);2362 }2363 return newNode;2364 },23652366 removeNode : function(treeNode) {2367 if (!treeNode) return;2368 removeTreeNode(this.setting, treeNode);2369 }2370 };2371 } ...

Full Screen

Full Screen

test.js

Source:test.js Github

copy

Full Screen

...76 $('body').append('<div id="tree1"></div>');77 },78 teardown: function() {79 var $tree = $('#tree1');80 $tree.tree('destroy');81 $tree.remove();82 }83});84test("create jqtree from data", function() {85 $('#tree1').tree({86 data: example_data87 });88 equal(89 $('#tree1').children().length, 1,90 'number of children on level 0'91 );92 ok(93 $('#tree1').children().is('ul.jqtree-tree'),94 'first element is ul.jqtree-tree'95 );96 equal(97 $('#tree1 ul.jqtree-tree > li').length, 2,98 'number of children on level 1'99 );100 ok(101 $('#tree1 ul.jqtree-tree li:eq(0)').is('li.jqtree-folder.jqtree-closed'),102 'first child is li.jqtree-folder.jqtree-closed'103 );104 ok(105 $('#tree1 ul.jqtree-tree li:eq(0) > .jqtree-element > a.jqtree-toggler').is('a.jqtree-toggler.jqtree-closed'),106 'button in first folder'107 );108 equal(109 $('#tree1 ul.jqtree-tree li:eq(0) > .jqtree-element span.jqtree-title').text(),110 'node1'111 );112});113test('toggle', function() {114 // create tree115 var $tree = $('#tree1');116 var $node1;117 var node1;118 $tree.tree({119 data: example_data120 });121 $tree.bind(122 'tree.open',123 function(e) {124 start();125 ok(! isNodeClosed($node1), 'node1 is open');126 // 2. close node1127 $tree.tree('toggle', node1);128 stop();129 }130 );131 $tree.bind(132 'tree.close',133 function(e) {134 start();135 ok(isNodeClosed($node1), 'node1 is closed');136 }137 );138 var tree = $tree.tree('getTree');139 node1 = tree.children[0];140 $node1 = $tree.find('ul.jqtree-tree li:eq(0)');141 // node1 is initially closed142 ok(isNodeClosed($node1), 'node1 is closed');143 // 1. open node1144 $tree.tree('toggle', node1);145 stop();146});147test("click event", function() {148 stop();149 // create tree150 var $tree = $('#tree1');151 $tree.tree({152 data: example_data,153 selectable: true154 });155 $tree.bind('tree.click', function(e) {156 equal(e.node.name, 'node1');157 });158 $tree.bind('tree.select', function(e) {159 start();160 equal(e.node.name, 'node1');161 });162 // click on node1163 var $node1 = $tree.find('ul.jqtree-tree li:first');164 var $text_span = $node1.find('span:first');165 $text_span.click();166});167test('saveState', function() {168 var $tree = $('#tree1');169 var saved_state;170 function setState(state) {171 saved_state = state;172 }173 function getState() {174 return saved_state;175 }176 function createTree() {177 $tree.tree({178 data: example_data,179 saveState: true,180 onSetStateFromStorage: setState,181 onGetStateFromStorage: getState,182 selectable: true183 });184 }185 // create tree186 createTree();187 // nodes are initially closed188 var tree = $tree.tree('getTree');189 tree.iterate(function(node) {190 ok(! node.is_open, 'jqtree-closed');191 return true;192 });193 // open node1194 $tree.tree('toggle', tree.children[0]);195 // node1 is open196 ok(tree.children[0].is_open, 'node1 is_open');197 // select node2198 $tree.tree('selectNode', tree.children[1]);199 // node2 is selected200 equal(201 $tree.tree('getSelectedNode').name,202 'node2',203 'getSelectedNode'204 );205 // create tree again206 $tree.tree('destroy');207 createTree();208 tree = $tree.tree('getTree');209 ok(tree.children[0].is_open, 'node1 is_open');210 ok(! tree.children[1].is_open, 'node2 is closed');211 // node2 is selected212 equal(213 $tree.tree('getSelectedNode').name,214 'node2',215 'getSelectedNode'216 );217});218test('getSelectedNode', function() {219 var $tree = $('#tree1');220 // create tree221 $tree.tree({222 data: example_data,223 selectable: true224 });225 // there is no node selected226 equal(227 $tree.tree('getSelectedNode'),228 false,229 'getSelectedNode'230 );231 // select node1232 var tree = $tree.tree('getTree');233 var node1 = tree.children[0];234 $tree.tree('selectNode', node1);235 // node1 is selected236 equal(237 $tree.tree('getSelectedNode').name,238 'node1',239 'getSelectedNode'240 );241});242test("toJson", function() {243 // setup244 var $tree = $('#tree1');245 $tree.tree({246 data: example_data247 });248 // 1. call toJson249 equal(250 $tree.tree('toJson'),251 '[{"name":"node1","id":123,"children":'+252 '[{"name":"child1","id":125},{"name":"child2","id":126}]},'+253 '{"name":"node2","id":124,"children":[{"name":"child3","id":127}]}]'254 );255 // Check that properties 'children', 'parent' and 'element' still exist.256 var tree = $tree.tree('getTree');257 equal(tree.children.length, 2);258 ok(tree.children[0].parent != undefined, 'parent');259 ok($(tree.children[0].element).is('li'), 'element');260});261test('loadData', function() {262 // setup263 var $tree = $('#tree1');264 $tree.tree({265 data: example_data,266 autoOpen: true267 });268 // first node is 'node1'269 equal(270 $tree.find('> ul > li:first .jqtree-element:first > span').text(),271 'node1'272 );273 // - load new data274 $tree.tree('loadData', example_data2);275 // first node is 'main'276 equal(277 $tree.find('> ul > li:first .jqtree-element:first > span').text(),278 'main'279 );280 // - load new data under node 'child3'281 $tree.tree('loadData', example_data);282 var child3 = $tree.tree('getNodeByName', 'child3');283 var data = [284 { label: 'c4', id: 200 },285 {286 label: 'c5', id: 201,287 children: [288 { label: 'c6', id: 202 }289 ]290 }291 ];292 $tree.tree('loadData', data, child3);293 // first node in html is still 'node1'294 equal(295 $tree.find('li:eq(0)').find('.jqtree-element:eq(0) span.jqtree-title').text(),296 'node1'297 );298 // Node 'child3' now has a children 'c4' and 'c5'299 var $child3 = $tree.find('span:contains(child3)');300 var $li = $child3.closest('li');301 equal(302 $li.children('ul').children('li:eq(0)').find('.jqtree-element span.jqtree-title').text(),303 'c4'304 );305 // Node 'child3' must have toggler button306 ok($child3.prev().is('a.jqtree-toggler'));307 // - select node 'c5' and load new data under 'child3'308 var c5 = $tree.tree('getNodeByName', 'c5');309 $tree.tree('selectNode', c5);310 equal($tree.tree('getSelectedNode').name, 'c5');311 var data2 = [312 { label: 'c7' },313 { label: 'c8' }314 ];315 $tree.tree('loadData', data2, child3);316 // c5 must be deselected317 equal($tree.tree('getSelectedNode'), false);318 // - select c7; load new data under child3; note that c7 has no id319 $tree.tree('selectNode', $tree.tree('getNodeByName', 'c7'));320 equal($tree.tree('getSelectedNode').name, 'c7');321 $tree.tree('loadData', [ 'c9' ], child3);322 equal($tree.tree('getSelectedNode'), false);323 // - select c9 (which has no id); load new nodes under child2324 $tree.tree('selectNode', $tree.tree('getNodeByName', 'c9'));325 var child2 = $tree.tree('getNodeByName', 'child2');326 $tree.tree('loadData', [ 'c10' ], child2);327 equal($tree.tree('getSelectedNode').name, 'c9');328});329test('openNode and closeNode', function() {330 // setup331 var $tree = $('#tree1');332 $tree.tree({333 data: example_data334 });335 var node2 = $tree.tree('getNodeByName', 'node2');336 equal(node2.name, 'node2');337 equal(node2.is_open, undefined);338 // 1. open node2339 $tree.tree('openNode', node2, false);340 equal(node2.is_open, true);341 equal(isNodeOpen($(node2.element)), true);342 // 2. close node2343 $tree.tree('closeNode', node2, false);344 equal(node2.is_open, false);345 equal(isNodeClosed($(node2.element)), true);346 // 3. open child1347 var node1 = $tree.tree('getNodeByName', 'node1');348 var child1 = $tree.tree('getNodeByName', 'child1');349 // add a child to child1 so it is a folder350 $tree.tree('appendNode', 'child1a', child1);351 // node1 is initialy closed352 equal(node1.is_open, undefined);353 // open child1354 $tree.tree('openNode', child1, false);355 // node1 and child1 are now open1356 equal(node1.is_open, true);357 equal(child1.is_open, true);358});359test('selectNode', function() {360 // setup361 var $tree = $('#tree1');362 $tree.tree({363 data: example_data,364 selectable: true365 });366 var node1 = $tree.tree('getTree').children[0];367 var node2 = $tree.tree('getTree').children[1];368 var child3 = node2.children[0];369 equal(child3.name, 'child3');370 equal(node1.is_open, undefined);371 equal(node2.is_open, undefined);372 equal(child3.is_open, undefined);373 // -- select node 'child3', which is a child of 'node2'; must_open_parents = true374 $tree.tree('selectNode', child3, true);375 equal($tree.tree('getSelectedNode').name, 'child3');376 equal(node1.is_open, undefined);377 equal(node2.is_open, true);378 equal(child3.is_open, undefined);379 // -- select node 'node1'380 $tree.tree('selectNode', node1);381 equal($tree.tree('getSelectedNode').name, 'node1');382 // -- is 'node1' selected?383 ok($tree.tree('isNodeSelected', node1));384});385test('selectNode when another node is selected', function() {386 // setup387 var $tree = $('#tree1');388 $tree.tree({389 data: example_data,390 selectable: true391 });392 var node1 = $tree.tree('getTree').children[0];393 var node2 = $tree.tree('getTree').children[1];394 395 // -- select node 'node2'396 $tree.tree('selectNode', node2);397 equal($tree.tree('getSelectedNode').name, 'node2');398 // -- setting event399 // -- is node 'node2' named 'deselected_node' in object's attributes?400 stop();401 $tree.bind('tree.select', function(e) {402 start();403 equal(e.deselected_node, node2);404 });405 // -- select node 'node1'; node 'node2' is selected before it406 $tree.tree('selectNode', node1);407 equal($tree.tree('getSelectedNode').name, 'node1');408 ok($tree.tree('isNodeSelected', node1));409});410test('click toggler', function() {411 // setup412 stop();413 var $tree = $('#tree1');414 $tree.tree({415 data: example_data,416 selectable: true417 });418 var $title = $tree.find('li:eq(0)').find('> .jqtree-element > span.jqtree-title');419 equal($title.text(), 'node1');420 var $toggler = $title.prev();421 ok($toggler.is('a.jqtree-toggler.jqtree-closed'));422 $tree.bind('tree.open', function(e) {423 // 2. handle 'open' event424 start();425 equal(e.node.name, 'node1');426 stop();427 // 3. click toggler again428 $toggler.click();429 });430 $tree.bind('tree.close', function(e) {431 start();432 equal(e.node.name, 'node1');433 });434 // 1. click toggler of 'node1'435 $toggler.click();436});437test('getNodeById', function() {438 // setup439 var $tree = $('#tree1');440 $tree.tree({441 data: example_data442 });443 var node2 = $tree.tree('getNodeByName', 'node2');444 // 1. get 'node2' by id445 equal(446 $tree.tree('getNodeById', 124).name,447 'node2'448 );449 // 2. get id that does not exist450 equal($tree.tree('getNodeById', 333), null);451 // 3. get id by string452 equal(453 $tree.tree('getNodeById', '124').name,454 'node2'455 );456 // 4. add node with string id; search by int457 $tree.tree(458 'appendNode',459 {460 label: 'abc',461 id: '234'462 }463 );464 equal(465 $tree.tree('getNodeById', 234).name,466 'abc'467 );468 equal(469 $tree.tree('getNodeById', '234').name,470 'abc'471 );472 // 5. load subtree in node2473 var subtree_data = [474 {475 label: 'sub1',476 id: 200,477 children: [478 {label: 'sub2', id: 201}479 ]480 }481 ];482 $tree.tree('loadData', subtree_data, node2);483 var t = $tree.tree('getTree');484 equal(485 $tree.tree('getNodeById', 200).name,486 'sub1'487 );488 equal(489 $tree.tree('getNodeById', 201).name,490 'sub2'491 );492});493test('autoOpen', function() {494 var $tree = $('#tree1');495 function formatOpenFolders() {496 var open_nodes = [];497 $tree.find('li').each(function() {498 var $li = $(this);499 if ($li.is('.jqtree-folder') && ! $li.is('.jqtree-closed')) {500 var label = $li.children('.jqtree-element').find('span').text();501 open_nodes.push(label);502 };503 });504 return open_nodes.join(';');505 }506 /*507 -l1n1 (level 0)508 ----l2n1 (1)509 ----l2n2 (1)510 -------l3n1 (2)511 ----------l4n1 (3)512 -l1n2513 */514 var data = [515 {516 label: 'l1n1',517 children: [518 'l2n1',519 {520 label: 'l2n2',521 children: [522 {523 label: 'l3n1',524 children: [525 'l4n1'526 ]527 }528 ]529 }530 ]531 },532 'l1n2'533 ];534 // 1. autoOpen is false535 $tree.tree({536 data: data,537 autoOpen: false538 });539 equal(formatOpenFolders(), '');540 $tree.tree('destroy');541 // 2. autoOpen is true542 $tree.tree({543 data: data,544 autoOpen: true545 });546 equal(formatOpenFolders(), 'l1n1;l2n2;l3n1');547 $tree.tree('destroy');548 // 3. autoOpen level 1549 $tree.tree({550 data: data,551 autoOpen: 1552 });553 equal(formatOpenFolders(), 'l1n1;l2n2');554});555test('onCreateLi', function() {556 // 1. init tree with onCreateLi557 var $tree = $('#tree1');558 $tree.tree({559 data: example_data,560 onCreateLi: function(node, $li) {561 var $span = $li.children('.jqtree-element').find('span');562 $span.html('_' + node.name + '_');563 }564 });565 equal(566 $tree.find('span:eq(0)').text(),567 '_node1_'568 );569});570test('save state', function() {571 // setup572 var state = null;573 // Fake $.cookie plugin for browsers that do not support localstorage574 $.cookie = function(key, param2, param3) {575 if (typeof param3 == 'object') {576 // set577 state = param2;578 }579 else {580 // get581 return state;582 }583 }584 // Remove state from localstorage585 if (typeof localStorage != 'undefined') {586 localStorage.setItem('my_tree', null);587 }588 // 1. init tree589 var $tree = $('#tree1');590 $tree.tree({591 data: example_data,592 selectable: true,593 saveState: 'my_tree'594 });595 var tree = $tree.tree('getTree');596 equal($tree.tree('getSelectedNode'), false);597 // 2. select node -> state is saved598 $tree.tree('selectNode', tree.children[0]);599 equal($tree.tree('getSelectedNode').name, 'node1');600 // 3. init tree again601 $tree.tree('destroy');602 $tree.tree({603 data: example_data,604 selectable: true,605 saveState: 'my_tree'606 });607 equal($tree.tree('getSelectedNode').name, 'node1');608 $.cookie = null;609});610test('generate hit areas', function() {611 // setup612 var $tree = $('#tree1');613 $tree.tree({614 data: example_data615 });616 // 1. get hit areas617 var node = $tree.tree('getNodeById', 123);618 var hit_areas = $tree.tree('testGenerateHitAreas', node);619 var strings = $.map(hit_areas, function(hit_area) {620 return hit_area.node.name + ' ' + Tree.Position.getName(hit_area.position);621 });622 equal(strings.join(';'), 'node1 none;node2 inside;node2 after');623});624test('removeNode', function() {625 // setup626 var $tree = $('#tree1');627 $tree.tree({628 data: example_data,629 selectable: true630 });631 // 1. Remove selected node; node is 'child1'632 var child1 = $tree.tree('getNodeByName', 'child1');633 $tree.tree('selectNode', child1);634 equal($tree.tree('getSelectedNode').name, 'child1');635 $tree.tree('removeNode', child1);636 equal(637 formatTitles($tree),638 'node1 child2 node2 child3'639 );640 // getSelectedNode must now return false641 equal($tree.tree('getSelectedNode'), false);642 // 2. No node is selected; remove child3643 $tree.tree('loadData', example_data);644 var child3 = $tree.tree('getNodeByName', 'child3');645 $tree.tree('removeNode', child3);646 equal(647 formatTitles($tree),648 'node1 child1 child2 node2'649 );650 equal($tree.tree('getSelectedNode'), false);651 // 3. Remove parent of selected node652 $tree.tree('loadData', example_data);653 child1 = $tree.tree('getNodeByName', 'child1');654 var node1 = $tree.tree('getNodeByName', 'node1');655 $tree.tree('selectNode', child1);656 $tree.tree('removeNode', node1);657 // node is unselected658 equal($tree.tree('getSelectedNode'), false);659 // 4. Remove unselected node without an id660 $tree.tree('loadData', example_data2);661 var c1 = $tree.tree('getNodeByName', 'c1');662 663 $tree.tree('removeNode', c1);664 equal(665 formatTitles($tree),666 'main c2'667 )668});669test('appendNode', function() {670 // setup671 var $tree = $('#tree1');672 $tree.tree({673 data: example_data674 });675 var node1 = $tree.tree('getNodeByName', 'node1');676 // 1. Add child3 to node1677 $tree.tree('appendNode', 'child3', node1);678 equal(679 formatTitles($(node1.element)),680 'node1 child1 child2 child3'681 );682 // 2. Add child4 to child1683 var child1 = $tree.tree('getNodeByName', 'child1');684 // Node 'child1' does not have a toggler button685 equal(686 $(child1.element).find('> .jqtree-element > .jqtree-toggler').length,687 0688 );689 $tree.tree('appendNode', 'child4', child1);690 equal(formatTitles($(child1.element)), 'child1 child4');691 // Node 'child1' must get a toggler button692 equal(693 $(child1.element).find('> .jqtree-element > .jqtree-toggler').length,694 1695 );696});697test('prependNode', function() {698 // setup699 var $tree = $('#tree1');700 $tree.tree({701 data: example_data702 });703 var node1 = $tree.tree('getNodeByName', 'node1');704 // 1. Prepend child0 to node1705 $tree.tree('prependNode', 'child0', node1);706 equal(707 formatTitles($(node1.element)),708 'node1 child0 child1 child2'709 );710});711test('init event', function() {712 // setup713 var $tree = $('#tree1');714 $tree.bind('tree.init', function() {715 start();716 // Check that we can call functions in 'tree.init' event717 equal($tree.tree('getNodeByName', 'node2').name, 'node2');718 });719 stop();720 $tree.tree({721 data: example_data722 });723});724test('updateNode', function() {725 // setup726 var $tree = $('#tree1');727 $tree.tree({ data: example_data });728 equal(formatTitles($tree), 'node1 child1 child2 node2 child3');729 // -- update label730 var node2 = $tree.tree('getNodeByName', 'node2');731 $tree.tree('updateNode', node2, 'CHANGED');732 equal(formatTitles($tree), 'node1 child1 child2 CHANGED child3');733 equal(node2.name, 'CHANGED');734 // -- update data735 $tree.tree(736 'updateNode',737 node2,738 {739 name: 'xyz',740 tag1: 'abc'741 }742 );743 equal(formatTitles($tree), 'node1 child1 child2 xyz child3');744 equal(node2.name, 'xyz');745 equal(node2.tag1, 'abc');746 // - update id747 equal(node2.id, 124);748 $tree.tree('updateNode', node2, {id: 555});749 equal(node2.id, 555);750 equal(node2.name, 'xyz');751 // get node by id752 var node_555 = $tree.tree('getNodeById', 555);753 equal(node_555.name, 'xyz');754 var node_124 = $tree.tree('getNodeById', 124);755 equal(node_124, undefined);756 // update child1757 var child1 = $tree.tree('getNodeByName', 'child1');758 $tree.tree('updateNode', child1, 'child1a');759 equal(formatTitles($tree), 'node1 child1a child2 xyz child3');760 // select child1761 $tree.tree('selectNode', child1);762 $tree.tree('updateNode', child1, 'child1b');763 ok($(child1.element).hasClass('jqtree-selected'));764});765test('moveNode', function() {766 // setup767 var $tree = $('#tree1');768 $tree.tree({ data: example_data });769 var child1 = $tree.tree('getNodeByName', 'child1');770 var child2 = $tree.tree('getNodeByName', 'child2');771 var node1 = $tree.tree('getNodeByName', 'node1');772 var node2 = $tree.tree('getNodeByName', 'node2');773 // -- Move child1 after node2774 $tree.tree('moveNode', child1, node2, 'after');775 equal(formatTitles($tree), 'node1 child2 node2 child3 child1');776 // -- Check that illegal moves are skipped777 $tree.tree('moveNode', node1, child2, 'inside');778});779test('load on demand', function() {780 // setup781 var $tree = $('#tree1');782 $tree.tree({783 data: [784 {785 id: 1,786 label: 'node1',787 load_on_demand: true788 }789 ],790 dataUrl: '/tree/'791 });792 $.mockjax({793 url: '*',794 response: function(options) {795 equal(options.url, '/tree/', '2');796 deepEqual(options.data, { 'node' : 1 }, '3')797 this.responseText = [798 {799 id: 2,800 label: 'child1'801 }802 ];803 },804 logging: false805 });806 // -- open node807 $tree.bind('tree.refresh', function(e) {808 start();809 equal(formatTitles($tree), 'node1 child1', '4');810 });811 var node1 = $tree.tree('getNodeByName', 'node1');812 equal(formatTitles($tree), 'node1', '1');813 $tree.tree('openNode', node1, true);814 stop();815});816test('addNodeAfter', function() {817 // setup818 var $tree = $('#tree1');819 $tree.tree({ data: example_data });820 var node1 = $tree.tree('getNodeByName', 'node1');821 // -- add node after node1822 $tree.tree('addNodeAfter', 'node3', node1);823 equal(formatTitles($tree), 'node1 child1 child2 node3 node2 child3');824});825test('addNodeBefore', function() {826 // setup827 var $tree = $('#tree1');828 $tree.tree({ data: example_data });829 var node1 = $tree.tree('getNodeByName', 'node1');830 // -- add node before node1831 var new_node = $tree.tree('addNodeBefore', 'node3', node1);832 equal(formatTitles($tree), 'node3 node1 child1 child2 node2 child3');833});834test('addParentNode', function() {835 // setup836 var $tree = $('#tree1');837 $tree.tree({ data: example_data });838 var child3 = $tree.tree('getNodeByName', 'child3');839 // -- add parent to child3840 $tree.tree('addParentNode', 'node3', child3);841 equal(formatTitles($tree), 'node1 child1 child2 node2 node3 child3');842});843test('mouse events', function() {844 // setup845 var $tree = $('#tree1');846 $tree.tree({847 data: example_data,848 dragAndDrop: true,849 autoOpen: true850 });851 $tree.tree('setMouseDelay', 0);852 function getTitleElement(node_name) {853 var node = $tree.tree('getNodeByName', node_name);854 var $el = $(node.element);855 return $($el.find('.jqtree-title'));856 }857 var $node1 = getTitleElement('node1');858 var $child3 = getTitleElement('child3');859 // Move node1 inside child3860 // trigger mousedown event on node1861 $node1.trigger(862 $.Event('mousedown', { which: 1 })863 );864 // trigger mouse move to child3865 var child3_offset = $child3.offset();866 $tree.trigger(867 $.Event('mousemove', { pageX: child3_offset.left, pageY: child3_offset.top })868 );869 $tree.trigger('mouseup');870 equal(871 formatTitles($tree),872 'node2 child3 node1 child1 child2'873 );874});875test('multiple select', function() {876 // setup877 var $tree = $('#tree1');878 $tree.tree({ data: example_data });879 var child1 = $tree.tree('getNodeByName', 'child1');880 var child2 = $tree.tree('getNodeByName', 'child2');881 // -- add nodes to selection882 // todo: more nodes as parameters?883 // todo: rename to 'selection.add' or 'selection' 'add'?884 $tree.tree('addToSelection', child1);885 $tree.tree('addToSelection', child2);886 // -- get selected nodes887 var selected_nodes = $tree.tree('getSelectedNodes');888 equal(889 formatNodes(selected_nodes),890 'child1 child2'891 );892});893test('keyboard', function() {894 // setup895 var $tree = $('#tree1');896 function keyDown(key) {897 $tree.trigger(898 $.Event('keydown', { which: key })899 );900 }901 $tree.tree({ data: example_data });902 var node1 = $tree.tree('getNodeByName', 'node1');903 // select node1904 $tree.tree('selectNode', node1);905 equal(node1.is_open, undefined);906 // - move down; -> node2907 keyDown(40);908 equal($tree.tree('getSelectedNode').name, 'node2');909 // - move up; -> back to node1910 keyDown(38);911 equal($tree.tree('getSelectedNode').name, 'node1');912 // - move right; open node1913 keyDown(39);914 equal(node1.is_open, true);915 equal($tree.tree('getSelectedNode').name, 'node1');916 // - select child3 and move up -> node2917 $tree.tree('selectNode', $tree.tree('getNodeByName', 'child3'));918 keyDown(38);919 equal($tree.tree('getSelectedNode').name, 'node2');920 // - move up -> child2921 keyDown(38);922 equal($tree.tree('getSelectedNode').name, 'child2');923 // - select node1 and move left -> close924 $tree.tree('selectNode', node1);925 keyDown(37);926 equal(node1.is_open, false);927 equal($tree.tree('getSelectedNode').name, 'node1');928});929module("Tree");930test('constructor', function() {931 // 1. Create node from string932 var node = new Tree.Node('n1');933 equal(node.name, 'n1');934 equal(node.children.length, 0);935 equal(node.parent, null);936 // 2. Create node from object937 node = new Tree.Node({938 label: 'n2',939 id: 123,940 parent: 'abc', // parent must be ignored941 children: ['c'], // children must be ignored...

Full Screen

Full Screen

tree.ts

Source:tree.ts Github

copy

Full Screen

1import * as treePath from './path';2import * as ops from './ops';3import { defined } from 'common';4export type MaybeNode = Tree.Node | undefined;5export interface TreeWrapper {6 root: Tree.Node;7 lastPly(): number;8 nodeAtPath(path: Tree.Path): Tree.Node;9 getNodeList(path: Tree.Path): Tree.Node[];10 longestValidPath(path: string): Tree.Path;11 updateAt(path: Tree.Path, update: (node: Tree.Node) => void): MaybeNode;12 addNode(node: Tree.Node, path: Tree.Path): Tree.Path | undefined;13 addNodes(nodes: Tree.Node[], path: Tree.Path): Tree.Path | undefined;14 addDests(dests: string, path: Tree.Path): MaybeNode;15 setShapes(shapes: Tree.Shape[], path: Tree.Path): MaybeNode;16 setCommentAt(comment: Tree.Comment, path: Tree.Path): MaybeNode;17 deleteCommentAt(id: string, path: Tree.Path): MaybeNode;18 setGlyphsAt(glyphs: Tree.Glyph[], path: Tree.Path): MaybeNode;19 setClockAt(clock: Tree.Clock | undefined, path: Tree.Path): MaybeNode;20 pathIsMainline(path: Tree.Path): boolean;21 pathIsForcedVariation(path: Tree.Path): boolean;22 lastMainlineNode(path: Tree.Path): Tree.Node;23 pathExists(path: Tree.Path): boolean;24 deleteNodeAt(path: Tree.Path): void;25 promoteAt(path: Tree.Path, toMainline: boolean): void;26 forceVariationAt(path: Tree.Path, force: boolean): MaybeNode;27 getCurrentNodesAfterPly(nodeList: Tree.Node[], mainline: Tree.Node[], ply: number): Tree.Node[];28 merge(tree: Tree.Node): void;29 removeCeval(): void;30 removeComputerVariations(): void;31 parentNode(path: Tree.Path): Tree.Node;32 getParentClock(node: Tree.Node, path: Tree.Path): Tree.Clock | undefined;33}34export function build(root: Tree.Node): TreeWrapper {35 function lastNode(): MaybeNode {36 return ops.findInMainline(root, (node: Tree.Node) => !node.children.length);37 }38 function nodeAtPath(path: Tree.Path): Tree.Node {39 return nodeAtPathFrom(root, path);40 }41 function nodeAtPathFrom(node: Tree.Node, path: Tree.Path): Tree.Node {42 if (path === '') return node;43 const child = ops.childById(node, treePath.head(path));44 return child ? nodeAtPathFrom(child, treePath.tail(path)) : node;45 }46 function nodeAtPathOrNull(path: Tree.Path): Tree.Node | undefined {47 return nodeAtPathOrNullFrom(root, path);48 }49 function nodeAtPathOrNullFrom(node: Tree.Node, path: Tree.Path): Tree.Node | undefined {50 if (path === '') return node;51 const child = ops.childById(node, treePath.head(path));52 return child ? nodeAtPathOrNullFrom(child, treePath.tail(path)) : undefined;53 }54 function longestValidPathFrom(node: Tree.Node, path: Tree.Path): Tree.Path {55 const id = treePath.head(path);56 const child = ops.childById(node, id);57 return child ? id + longestValidPathFrom(child, treePath.tail(path)) : '';58 }59 function getCurrentNodesAfterPly(nodeList: Tree.Node[], mainline: Tree.Node[], ply: number): Tree.Node[] {60 const nodes = [];61 for (const i in nodeList) {62 const node = nodeList[i];63 if (node.ply <= ply && mainline[i].id !== node.id) break;64 if (node.ply > ply) nodes.push(node);65 }66 return nodes;67 }68 function pathIsMainline(path: Tree.Path): boolean {69 return pathIsMainlineFrom(root, path);70 }71 function pathExists(path: Tree.Path): boolean {72 return !!nodeAtPathOrNull(path);73 }74 function pathIsMainlineFrom(node: Tree.Node, path: Tree.Path): boolean {75 if (path === '') return true;76 const pathId = treePath.head(path),77 child = node.children[0];78 if (!child || child.id !== pathId) return false;79 return pathIsMainlineFrom(child, treePath.tail(path));80 }81 function pathIsForcedVariation(path: Tree.Path): boolean {82 return !!getNodeList(path).find(n => n.forceVariation);83 }84 function lastMainlineNodeFrom(node: Tree.Node, path: Tree.Path): Tree.Node {85 if (path === '') return node;86 const pathId = treePath.head(path);87 const child = node.children[0];88 if (!child || child.id !== pathId) return node;89 return lastMainlineNodeFrom(child, treePath.tail(path));90 }91 function getNodeList(path: Tree.Path): Tree.Node[] {92 return ops.collect(root, function (node: Tree.Node) {93 const id = treePath.head(path);94 if (id === '') return;95 path = treePath.tail(path);96 return ops.childById(node, id);97 });98 }99 function updateAt(path: Tree.Path, update: (node: Tree.Node) => void): Tree.Node | undefined {100 const node = nodeAtPathOrNull(path);101 if (node) {102 update(node);103 return node;104 }105 return;106 }107 // returns new path108 function addNode(node: Tree.Node, path: Tree.Path): Tree.Path | undefined {109 const newPath = path + node.id,110 existing = nodeAtPathOrNull(newPath);111 if (existing) {112 (['dests', 'drops', 'clock'] as Array<keyof Tree.Node>).forEach(key => {113 if (defined(node[key]) && !defined(existing[key])) existing[key] = node[key] as never;114 });115 return newPath;116 }117 return updateAt(path, function (parent: Tree.Node) {118 parent.children.push(node);119 })120 ? newPath121 : undefined;122 }123 function addNodes(nodes: Tree.Node[], path: Tree.Path): Tree.Path | undefined {124 const node = nodes[0];125 if (!node) return path;126 const newPath = addNode(node, path);127 return newPath ? addNodes(nodes.slice(1), newPath) : undefined;128 }129 function deleteNodeAt(path: Tree.Path): void {130 ops.removeChild(parentNode(path), treePath.last(path));131 }132 function promoteAt(path: Tree.Path, toMainline: boolean): void {133 const nodes = getNodeList(path);134 for (let i = nodes.length - 2; i >= 0; i--) {135 const node = nodes[i + 1];136 const parent = nodes[i];137 if (parent.children[0].id !== node.id) {138 ops.removeChild(parent, node.id);139 parent.children.unshift(node);140 if (!toMainline) break;141 } else if (node.forceVariation) {142 node.forceVariation = false;143 if (!toMainline) break;144 }145 }146 }147 function setCommentAt(comment: Tree.Comment, path: Tree.Path) {148 return !comment.text149 ? deleteCommentAt(comment.id, path)150 : updateAt(path, function (node) {151 node.comments = node.comments || [];152 const existing = node.comments.find(function (c) {153 return c.id === comment.id;154 });155 if (existing) existing.text = comment.text;156 else node.comments.push(comment);157 });158 }159 function deleteCommentAt(id: string, path: Tree.Path) {160 return updateAt(path, function (node) {161 const comments = (node.comments || []).filter(function (c) {162 return c.id !== id;163 });164 node.comments = comments.length ? comments : undefined;165 });166 }167 function setGlyphsAt(glyphs: Tree.Glyph[], path: Tree.Path) {168 return updateAt(path, function (node) {169 node.glyphs = glyphs;170 });171 }172 function parentNode(path: Tree.Path): Tree.Node {173 return nodeAtPath(treePath.init(path));174 }175 function getParentClock(node: Tree.Node, path: Tree.Path): Tree.Clock | undefined {176 if (!('parentClock' in node)) {177 const par = path && parentNode(path);178 if (!par) node.parentClock = node.clock;179 else if (!('clock' in par)) node.parentClock = undefined;180 else node.parentClock = par.clock;181 }182 return node.parentClock;183 }184 return {185 root,186 lastPly(): number {187 return lastNode()?.ply || root.ply;188 },189 nodeAtPath,190 getNodeList,191 longestValidPath: (path: string) => longestValidPathFrom(root, path),192 updateAt,193 addNode,194 addNodes,195 addDests(dests: string, path: Tree.Path) {196 return updateAt(path, function (node: Tree.Node) {197 node.dests = dests;198 });199 },200 setShapes(shapes: Tree.Shape[], path: Tree.Path) {201 return updateAt(path, function (node: Tree.Node) {202 node.shapes = shapes;203 });204 },205 setCommentAt,206 deleteCommentAt,207 setGlyphsAt,208 setClockAt(clock: Tree.Clock | undefined, path: Tree.Path) {209 return updateAt(path, function (node) {210 node.clock = clock;211 });212 },213 pathIsMainline,214 pathIsForcedVariation,215 lastMainlineNode(path: Tree.Path): Tree.Node {216 return lastMainlineNodeFrom(root, path);217 },218 pathExists,219 deleteNodeAt,220 promoteAt,221 forceVariationAt(path: Tree.Path, force: boolean) {222 return updateAt(path, function (node) {223 node.forceVariation = force;224 });225 },226 getCurrentNodesAfterPly,227 merge(tree: Tree.Node) {228 ops.merge(root, tree);229 },230 removeCeval() {231 ops.updateAll(root, function (n) {232 delete n.ceval;233 delete n.threat;234 });235 },236 removeComputerVariations() {237 ops.mainlineNodeList(root).forEach(function (n) {238 n.children = n.children.filter(function (c) {239 return !c.comp;240 });241 });242 },243 parentNode,244 getParentClock,245 };...

Full Screen

Full Screen

tree_test.py

Source:tree_test.py Github

copy

Full Screen

...10 511 3 712 2 4 6 813 '''14 def _read_tree(self):15 txt = textwrap.dedent('''\16 5 3 717 3 2 418 7 6 8''')19 tree = read_tree(txt) 20 self.assertTrue(tree is not None)21 return tree22 def test_pre_order_recursion(self):23 tree = self._read_tree()24 output = pre_order_recursion(tree)25 self.assertEqual([5, 3, 2, 4, 7, 6, 8], output)26 def test_in_order_recursion(self):27 tree = self._read_tree()28 output = in_order_recursion(tree)29 self.assertEqual([2, 3, 4, 5, 6, 7, 8], output)30 def test_post_order_recursion(self):31 tree = self._read_tree()32 output = post_order_recursion(tree)33 self.assertEqual([2, 3, 4, 6, 7, 8, 5], output)34 def test_breadth_first(self):35 tree = self._read_tree()36 output = breadth_first(tree)37 self.assertEqual([5, 3, 7, 2, 4, 6, 8], output)38 def test_depth_first(self):39 tree = self._read_tree()40 output = depth_first(tree)41 self.assertEqual([5, 3, 2, 4, 7, 6, 8], output)42 def test_pre_order_non_recursion(self):43 tree = self._read_tree()44 output = pre_order_non_recursion(tree)45 self.assertEqual([5, 3, 2, 4, 7, 6, 8], output)46 def test_in_order_non_recursion(self):47 tree = self._read_tree()48 output = in_order_non_recursion(tree)49 self.assertEqual([2, 3, 4, 5, 6, 7, 8], output)50 def test_rotate_right(self):51 tree = read_tree(textwrap.dedent('''\52 3 2 - 53 2 1 -''')) 54 self.assertTrue(tree is not None)55 56 output = breadth_first(tree)57 self.assertEqual([3, 2, 1], output)58 tree = rotate_right(tree)59 output = breadth_first(tree)60 self.assertEqual([2, 1, 3], output)61 def test_rotate_right_with_move_left_child(self):62 tree = read_tree(textwrap.dedent('''\63 5 3 6 64 3 2 465 2 1 -''')) 66 self.assertTrue(tree is not None)67 68 output = breadth_first(tree)69 self.assertEqual([5, 3, 6, 2, 4, 1], output)70 tree = rotate_right(tree)71 output = breadth_first(tree)72 self.assertEqual([3, 2, 5, 1, 4, 6], output)73 def test_rotate_left(self):74 tree = read_tree(textwrap.dedent('''\75 1 - 2 76 2 - 3''')) 77 self.assertTrue(tree is not None)78 79 output = breadth_first(tree)80 self.assertEqual([1, 2, 3], output)81 tree = rotate_left(tree)82 output = breadth_first(tree)83 self.assertEqual([2, 1, 3], output)84 def test_str_tree(self):85 tree = self._read_tree()86 s = str(tree)87 self.assertEqual(textwrap.dedent('''\88 5.089 |--3.090 |--2.091 |--4.092 |--7.093 |--6.094 |--8.095 '''), s)96 def test_tree_height(self):97 tree = self._read_tree()98 self.assertEqual(3, tree_height(tree))99 self.assertEqual(2, tree_height(tree.l))100 self.assertEqual(1, tree_height(tree.l.l))101 self.assertEqual(0, tree_height(tree.l.l.l))102 def test_balance_factor(self):103 tree = read_tree(textwrap.dedent('''\104 5 3 6 105 3 2 4106 2 1 -''')) 107 self.assertEqual(2, blance_factor(tree))108 self.assertEqual(0, blance_factor(tree.r))109 self.assertEqual(1, blance_factor(tree.l))110 self.assertEqual(1, blance_factor(tree.l.l))111 self.assertEqual(0, blance_factor(tree.l.r))112 self.assertEqual(0, blance_factor(tree.l.l.l))113 self.assertEqual(0, blance_factor(None))114 def test_lose_bance_type(self):115 tree = read_tree(textwrap.dedent('''\116 1 2 -117 2 3 -118 ''')) 119 self.assertEqual('ll', lose_blance_type(tree))120 tree = read_tree(textwrap.dedent('''\121 3 1 -122 1 - 2 123 ''')) 124 self.assertEqual('lr', lose_blance_type(tree))125 tree = read_tree(textwrap.dedent('''\126 1 - 2127 2 - 3 128 ''')) 129 self.assertEqual('rr', lose_blance_type(tree))130 tree = read_tree(textwrap.dedent('''\131 1 - 2132 2 3 - 133 ''')) 134 self.assertEqual('rl', lose_blance_type(tree))135 def test_re_blance_ll(self):136 tree = read_tree(textwrap.dedent('''\137 3 2 -138 2 1 -139 ''')) 140 tree = re_blance(tree)141 self.assertEqual([2, 1, 3], breadth_first(tree))142 def test_re_blance_lr(self):143 tree = read_tree(textwrap.dedent('''\144 3 1 -145 1 - 2146 ''')) 147 tree = re_blance(tree)148 self.assertEqual([2, 1, 3], breadth_first(tree))149 def test_re_blance_rr(self):150 tree = read_tree(textwrap.dedent('''\151 1 - 2 152 2 - 3 153 ''')) 154 tree = re_blance(tree)155 self.assertEqual([2, 1, 3], breadth_first(tree))156 def test_re_blance_rl(self):157 tree = read_tree(textwrap.dedent('''\158 1 - 3 159 3 2 - 160 ''')) 161 tree = re_blance(tree)162 self.assertEqual([2, 1, 3], breadth_first(tree))163 def test_put_value(self):164 tree = read_tree(textwrap.dedent('''\165 2 1 3166 ''')) 167 tree = put_value(tree, 0)168 self.assertEqual([2, 1, 3, 0], breadth_first(tree))169 tree = put_value(tree, 4)170 self.assertEqual([2, 1, 3, 0, 4], breadth_first(tree))171 # rr172 tree = put_value(tree, 5)173 self.assertEqual([2, 1, 4, 0, 3, 5], breadth_first(tree))174 # rl 175 tree = put_value(tree, 6)176 tree = put_value(tree, 5.5)177 self.assertEqual([2, 1, 4, 0, 3, 5.5, 5, 6], breadth_first(tree))178 # ll...

Full Screen

Full Screen

Automation Testing Tutorials

Learn to execute automation testing from scratch with LambdaTest Learning Hub. Right from setting up the prerequisites to run your first automation test, to following best practices and diving deeper into advanced test scenarios. LambdaTest Learning Hubs compile a list of step-by-step guides to help you be proficient with different test automation frameworks i.e. Selenium, Cypress, TestNG etc.

LambdaTest Learning Hubs:

YouTube

You could also refer to video tutorials over LambdaTest YouTube channel to get step by step demonstration from industry experts.

Run Kiwi automation tests on LambdaTest cloud grid

Perform automation testing on 3000+ real desktop and mobile devices online.

Try LambdaTest Now !!

Get 100 minutes of automation test minutes FREE!!

Next-Gen App & Browser Testing Cloud

Was this article helpful?

Helpful

NotHelpful