') : $('');
1039 | $nodeLayer.append($nodeCell);
1040 | buildHierarchy($nodeCell, this, level + 1, opts, callback);
1041 | });
1042 | }
1043 | }
1044 |
1045 | // build the child nodes of specific node
1046 | function buildChildNode ($appendTo, nodeData, opts, callback) {
1047 | var opts = opts || $appendTo.closest('.orgchart').data('options');
1048 | var data = nodeData.children || nodeData.siblings;
1049 | $appendTo.find('td:first').attr('colspan', data.length * 2);
1050 | buildHierarchy($appendTo, { 'children': data }, 0, opts, callback);
1051 | }
1052 | // exposed method
1053 | function addChildren($node, data, opts) {
1054 | var opts = opts || $node.closest('.orgchart').data('options');
1055 | var count = 0;
1056 | buildChildNode.call($node.closest('.orgchart').parent(), $node.closest('table'), data, opts, function() {
1057 | if (++count === data.children.length) {
1058 | if (!$node.children('.bottomEdge').length) {
1059 | $node.append('');
1060 | }
1061 | if (!$node.find('.symbol').length) {
1062 | $node.children('.title');
1063 | }
1064 | showChildren($node);
1065 | }
1066 | });
1067 | }
1068 |
1069 | // build the parent node of specific node
1070 | function buildParentNode($currentRoot, nodeData, opts, callback) {
1071 | var that = this;
1072 | var $table = $('');
1073 | nodeData.relationship = nodeData.relationship || '001';
1074 | $.when(createNode(nodeData, 0, opts || $currentRoot.closest('.orgchart').data('options')))
1075 | .done(function($nodeDiv) {
1076 | $table.append($nodeDiv.removeClass('slide-up').addClass('slide-down').wrap(' | ').closest('tr'));
1077 | $table.append(' | ');
1078 | var linesRow = ' | | ';
1079 | $table.append('' + linesRow + ' ');
1080 | var $oc = that.children('.orgchart');
1081 | $oc.prepend($table)
1082 | .children('table:first').append(' | ')
1083 | .children('tr:last').children().append($oc.children('table').last());
1084 | callback();
1085 | })
1086 | .fail(function() {
1087 | console.log('Failed to create parent node');
1088 | });
1089 | }
1090 |
1091 | // exposed method
1092 | function addParent($currentRoot, data, opts) {
1093 | buildParentNode.call(this, $currentRoot, data, opts, function() {
1094 | if (!$currentRoot.children('.topEdge').length) {
1095 | $currentRoot.children('.title').after('');
1096 | }
1097 | showParent($currentRoot);
1098 | });
1099 | }
1100 |
1101 | // subsequent processing of build sibling nodes
1102 | function complementLine($oneSibling, siblingCount, existingSibligCount) {
1103 | var lines = '';
1104 | for (var i = 0; i < existingSibligCount; i++) {
1105 | lines += ' | | ';
1106 | }
1107 | $oneSibling.parent().prevAll('tr:gt(0)').children().attr('colspan', siblingCount * 2)
1108 | .end().next().children(':first').after(lines);
1109 | }
1110 |
1111 | // build the sibling nodes of specific node
1112 | function buildSiblingNode($nodeChart, nodeData, opts, callback) {
1113 | var opts = opts || $nodeChart.closest('.orgchart').data('options');
1114 | var newSiblingCount = nodeData.siblings ? nodeData.siblings.length : nodeData.children.length;
1115 | var existingSibligCount = $nodeChart.parent().is('td') ? $nodeChart.closest('tr').children().length : 1;
1116 | var siblingCount = existingSibligCount + newSiblingCount;
1117 | var insertPostion = (siblingCount > 1) ? Math.floor(siblingCount/2 - 1) : 0;
1118 | // just build the sibling nodes for the specific node
1119 | if ($nodeChart.parent().is('td')) {
1120 | var $parent = $nodeChart.closest('tr').prevAll('tr:last');
1121 | $nodeChart.closest('tr').prevAll('tr:lt(2)').remove();
1122 | var childCount = 0;
1123 | buildChildNode.call($nodeChart.closest('.orgchart').parent(),$nodeChart.parent().closest('table'), nodeData, opts, function() {
1124 | if (++childCount === newSiblingCount) {
1125 | var $siblingTds = $nodeChart.parent().closest('table').children('tr:last').children('td');
1126 | if (existingSibligCount > 1) {
1127 | complementLine($siblingTds.eq(0).before($nodeChart.closest('td').siblings().addBack().unwrap()), siblingCount, existingSibligCount);
1128 | $siblingTds.addClass('hidden').find('.node').addClass('slide-left');
1129 | } else {
1130 | complementLine($siblingTds.eq(insertPostion).after($nodeChart.closest('td').unwrap()), siblingCount, 1);
1131 | $siblingTds.not(':eq(' + insertPostion + 1 + ')').addClass('hidden')
1132 | .slice(0, insertPostion).find('.node').addClass('slide-right')
1133 | .end().end().slice(insertPostion).find('.node').addClass('slide-left');
1134 | }
1135 | callback();
1136 | }
1137 | });
1138 | } else { // build the sibling nodes and parent node for the specific ndoe
1139 | var nodeCount = 0;
1140 | buildHierarchy($nodeChart.closest('.orgchart'), nodeData, 0, opts, function() {
1141 | if (++nodeCount === siblingCount) {
1142 | complementLine($nodeChart.next().children('tr:last')
1143 | .children().eq(insertPostion).after($('')
1144 | .append($nodeChart)), siblingCount, 1);
1145 | $nodeChart.closest('tr').siblings().eq(0).addClass('hidden').find('.node').addClass('slide-down');
1146 | $nodeChart.parent().siblings().addClass('hidden')
1147 | .slice(0, insertPostion).find('.node').addClass('slide-right')
1148 | .end().end().slice(insertPostion).find('.node').addClass('slide-left');
1149 | callback();
1150 | }
1151 | });
1152 | }
1153 | }
1154 |
1155 | function addSiblings($node, data, opts) {
1156 | buildSiblingNode.call($node.closest('.orgchart').parent(), $node.closest('table'), data, opts, function() {
1157 | $node.closest('.nodes').data('siblingsLoaded', true);
1158 | if (!$node.children('.leftEdge').length) {
1159 | $node.children('.topEdge').after('');
1160 | }
1161 | showSiblings($node);
1162 | });
1163 | }
1164 |
1165 | function removeNodes($node) {
1166 | var $parent = $node.closest('table').parent();
1167 | var $sibs = $parent.parent().siblings();
1168 | if ($parent.is('td')) {
1169 | if (getNodeState($node, 'siblings').exist) {
1170 | $sibs.eq(2).children('.topLine:lt(2)').remove();
1171 | $sibs.slice(0, 2).children().attr('colspan', $sibs.eq(2).children().length);
1172 | $parent.remove();
1173 | } else {
1174 | $sibs.eq(0).children().removeAttr('colspan')
1175 | .find('.bottomEdge').remove()
1176 | .end().end().siblings().remove();
1177 | }
1178 | } else {
1179 | $parent.add($parent.siblings()).remove();
1180 | }
1181 | }
1182 |
1183 | }));
1184 |
--------------------------------------------------------------------------------
/src/main/resources/static/index.html:
--------------------------------------------------------------------------------
1 |
2 |
3 |
4 |
5 |
6 |
7 |
8 | 树图 - 页面
9 |
10 |
11 |
12 |
13 |
14 |
15 |
16 |
17 |
18 |
19 |
20 |
21 |
22 |
31 |
32 |
33 |
34 |
66 |
67 | 增加节点
68 | 删除节点
69 | 修改节点属性
70 |
71 |
72 |
73 |
--------------------------------------------------------------------------------
/src/main/resources/static/js/bootstrap.min.js:
--------------------------------------------------------------------------------
1 | /*!
2 | * Bootstrap v3.3.6 (http://getbootstrap.com)
3 | * Copyright 2011-2015 Twitter, Inc.
4 | * Licensed under the MIT license
5 | */
6 | if("undefined"==typeof jQuery)throw new Error("Bootstrap's JavaScript requires jQuery");+function(a){"use strict";var b=a.fn.jquery.split(" ")[0].split(".");if(b[0]<2&&b[1]<9||1==b[0]&&9==b[1]&&b[2]<1||b[0]>2)throw new Error("Bootstrap's JavaScript requires jQuery version 1.9.1 or higher, but lower than version 3")}(jQuery),+function(a){"use strict";function b(){var a=document.createElement("bootstrap"),b={WebkitTransition:"webkitTransitionEnd",MozTransition:"transitionend",OTransition:"oTransitionEnd otransitionend",transition:"transitionend"};for(var c in b)if(void 0!==a.style[c])return{end:b[c]};return!1}a.fn.emulateTransitionEnd=function(b){var c=!1,d=this;a(this).one("bsTransitionEnd",function(){c=!0});var e=function(){c||a(d).trigger(a.support.transition.end)};return setTimeout(e,b),this},a(function(){a.support.transition=b(),a.support.transition&&(a.event.special.bsTransitionEnd={bindType:a.support.transition.end,delegateType:a.support.transition.end,handle:function(b){return a(b.target).is(this)?b.handleObj.handler.apply(this,arguments):void 0}})})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var c=a(this),e=c.data("bs.alert");e||c.data("bs.alert",e=new d(this)),"string"==typeof b&&e[b].call(c)})}var c='[data-dismiss="alert"]',d=function(b){a(b).on("click",c,this.close)};d.VERSION="3.3.6",d.TRANSITION_DURATION=150,d.prototype.close=function(b){function c(){g.detach().trigger("closed.bs.alert").remove()}var e=a(this),f=e.attr("data-target");f||(f=e.attr("href"),f=f&&f.replace(/.*(?=#[^\s]*$)/,""));var g=a(f);b&&b.preventDefault(),g.length||(g=e.closest(".alert")),g.trigger(b=a.Event("close.bs.alert")),b.isDefaultPrevented()||(g.removeClass("in"),a.support.transition&&g.hasClass("fade")?g.one("bsTransitionEnd",c).emulateTransitionEnd(d.TRANSITION_DURATION):c())};var e=a.fn.alert;a.fn.alert=b,a.fn.alert.Constructor=d,a.fn.alert.noConflict=function(){return a.fn.alert=e,this},a(document).on("click.bs.alert.data-api",c,d.prototype.close)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.button"),f="object"==typeof b&&b;e||d.data("bs.button",e=new c(this,f)),"toggle"==b?e.toggle():b&&e.setState(b)})}var c=function(b,d){this.$element=a(b),this.options=a.extend({},c.DEFAULTS,d),this.isLoading=!1};c.VERSION="3.3.6",c.DEFAULTS={loadingText:"loading..."},c.prototype.setState=function(b){var c="disabled",d=this.$element,e=d.is("input")?"val":"html",f=d.data();b+="Text",null==f.resetText&&d.data("resetText",d[e]()),setTimeout(a.proxy(function(){d[e](null==f[b]?this.options[b]:f[b]),"loadingText"==b?(this.isLoading=!0,d.addClass(c).attr(c,c)):this.isLoading&&(this.isLoading=!1,d.removeClass(c).removeAttr(c))},this),0)},c.prototype.toggle=function(){var a=!0,b=this.$element.closest('[data-toggle="buttons"]');if(b.length){var c=this.$element.find("input");"radio"==c.prop("type")?(c.prop("checked")&&(a=!1),b.find(".active").removeClass("active"),this.$element.addClass("active")):"checkbox"==c.prop("type")&&(c.prop("checked")!==this.$element.hasClass("active")&&(a=!1),this.$element.toggleClass("active")),c.prop("checked",this.$element.hasClass("active")),a&&c.trigger("change")}else this.$element.attr("aria-pressed",!this.$element.hasClass("active")),this.$element.toggleClass("active")};var d=a.fn.button;a.fn.button=b,a.fn.button.Constructor=c,a.fn.button.noConflict=function(){return a.fn.button=d,this},a(document).on("click.bs.button.data-api",'[data-toggle^="button"]',function(c){var d=a(c.target);d.hasClass("btn")||(d=d.closest(".btn")),b.call(d,"toggle"),a(c.target).is('input[type="radio"]')||a(c.target).is('input[type="checkbox"]')||c.preventDefault()}).on("focus.bs.button.data-api blur.bs.button.data-api",'[data-toggle^="button"]',function(b){a(b.target).closest(".btn").toggleClass("focus",/^focus(in)?$/.test(b.type))})}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.carousel"),f=a.extend({},c.DEFAULTS,d.data(),"object"==typeof b&&b),g="string"==typeof b?b:f.slide;e||d.data("bs.carousel",e=new c(this,f)),"number"==typeof b?e.to(b):g?e[g]():f.interval&&e.pause().cycle()})}var c=function(b,c){this.$element=a(b),this.$indicators=this.$element.find(".carousel-indicators"),this.options=c,this.paused=null,this.sliding=null,this.interval=null,this.$active=null,this.$items=null,this.options.keyboard&&this.$element.on("keydown.bs.carousel",a.proxy(this.keydown,this)),"hover"==this.options.pause&&!("ontouchstart"in document.documentElement)&&this.$element.on("mouseenter.bs.carousel",a.proxy(this.pause,this)).on("mouseleave.bs.carousel",a.proxy(this.cycle,this))};c.VERSION="3.3.6",c.TRANSITION_DURATION=600,c.DEFAULTS={interval:5e3,pause:"hover",wrap:!0,keyboard:!0},c.prototype.keydown=function(a){if(!/input|textarea/i.test(a.target.tagName)){switch(a.which){case 37:this.prev();break;case 39:this.next();break;default:return}a.preventDefault()}},c.prototype.cycle=function(b){return b||(this.paused=!1),this.interval&&clearInterval(this.interval),this.options.interval&&!this.paused&&(this.interval=setInterval(a.proxy(this.next,this),this.options.interval)),this},c.prototype.getItemIndex=function(a){return this.$items=a.parent().children(".item"),this.$items.index(a||this.$active)},c.prototype.getItemForDirection=function(a,b){var c=this.getItemIndex(b),d="prev"==a&&0===c||"next"==a&&c==this.$items.length-1;if(d&&!this.options.wrap)return b;var e="prev"==a?-1:1,f=(c+e)%this.$items.length;return this.$items.eq(f)},c.prototype.to=function(a){var b=this,c=this.getItemIndex(this.$active=this.$element.find(".item.active"));return a>this.$items.length-1||0>a?void 0:this.sliding?this.$element.one("slid.bs.carousel",function(){b.to(a)}):c==a?this.pause().cycle():this.slide(a>c?"next":"prev",this.$items.eq(a))},c.prototype.pause=function(b){return b||(this.paused=!0),this.$element.find(".next, .prev").length&&a.support.transition&&(this.$element.trigger(a.support.transition.end),this.cycle(!0)),this.interval=clearInterval(this.interval),this},c.prototype.next=function(){return this.sliding?void 0:this.slide("next")},c.prototype.prev=function(){return this.sliding?void 0:this.slide("prev")},c.prototype.slide=function(b,d){var e=this.$element.find(".item.active"),f=d||this.getItemForDirection(b,e),g=this.interval,h="next"==b?"left":"right",i=this;if(f.hasClass("active"))return this.sliding=!1;var j=f[0],k=a.Event("slide.bs.carousel",{relatedTarget:j,direction:h});if(this.$element.trigger(k),!k.isDefaultPrevented()){if(this.sliding=!0,g&&this.pause(),this.$indicators.length){this.$indicators.find(".active").removeClass("active");var l=a(this.$indicators.children()[this.getItemIndex(f)]);l&&l.addClass("active")}var m=a.Event("slid.bs.carousel",{relatedTarget:j,direction:h});return a.support.transition&&this.$element.hasClass("slide")?(f.addClass(b),f[0].offsetWidth,e.addClass(h),f.addClass(h),e.one("bsTransitionEnd",function(){f.removeClass([b,h].join(" ")).addClass("active"),e.removeClass(["active",h].join(" ")),i.sliding=!1,setTimeout(function(){i.$element.trigger(m)},0)}).emulateTransitionEnd(c.TRANSITION_DURATION)):(e.removeClass("active"),f.addClass("active"),this.sliding=!1,this.$element.trigger(m)),g&&this.cycle(),this}};var d=a.fn.carousel;a.fn.carousel=b,a.fn.carousel.Constructor=c,a.fn.carousel.noConflict=function(){return a.fn.carousel=d,this};var e=function(c){var d,e=a(this),f=a(e.attr("data-target")||(d=e.attr("href"))&&d.replace(/.*(?=#[^\s]+$)/,""));if(f.hasClass("carousel")){var g=a.extend({},f.data(),e.data()),h=e.attr("data-slide-to");h&&(g.interval=!1),b.call(f,g),h&&f.data("bs.carousel").to(h),c.preventDefault()}};a(document).on("click.bs.carousel.data-api","[data-slide]",e).on("click.bs.carousel.data-api","[data-slide-to]",e),a(window).on("load",function(){a('[data-ride="carousel"]').each(function(){var c=a(this);b.call(c,c.data())})})}(jQuery),+function(a){"use strict";function b(b){var c,d=b.attr("data-target")||(c=b.attr("href"))&&c.replace(/.*(?=#[^\s]+$)/,"");return a(d)}function c(b){return this.each(function(){var c=a(this),e=c.data("bs.collapse"),f=a.extend({},d.DEFAULTS,c.data(),"object"==typeof b&&b);!e&&f.toggle&&/show|hide/.test(b)&&(f.toggle=!1),e||c.data("bs.collapse",e=new d(this,f)),"string"==typeof b&&e[b]()})}var d=function(b,c){this.$element=a(b),this.options=a.extend({},d.DEFAULTS,c),this.$trigger=a('[data-toggle="collapse"][href="#'+b.id+'"],[data-toggle="collapse"][data-target="#'+b.id+'"]'),this.transitioning=null,this.options.parent?this.$parent=this.getParent():this.addAriaAndCollapsedClass(this.$element,this.$trigger),this.options.toggle&&this.toggle()};d.VERSION="3.3.6",d.TRANSITION_DURATION=350,d.DEFAULTS={toggle:!0},d.prototype.dimension=function(){var a=this.$element.hasClass("width");return a?"width":"height"},d.prototype.show=function(){if(!this.transitioning&&!this.$element.hasClass("in")){var b,e=this.$parent&&this.$parent.children(".panel").children(".in, .collapsing");if(!(e&&e.length&&(b=e.data("bs.collapse"),b&&b.transitioning))){var f=a.Event("show.bs.collapse");if(this.$element.trigger(f),!f.isDefaultPrevented()){e&&e.length&&(c.call(e,"hide"),b||e.data("bs.collapse",null));var g=this.dimension();this.$element.removeClass("collapse").addClass("collapsing")[g](0).attr("aria-expanded",!0),this.$trigger.removeClass("collapsed").attr("aria-expanded",!0),this.transitioning=1;var h=function(){this.$element.removeClass("collapsing").addClass("collapse in")[g](""),this.transitioning=0,this.$element.trigger("shown.bs.collapse")};if(!a.support.transition)return h.call(this);var i=a.camelCase(["scroll",g].join("-"));this.$element.one("bsTransitionEnd",a.proxy(h,this)).emulateTransitionEnd(d.TRANSITION_DURATION)[g](this.$element[0][i])}}}},d.prototype.hide=function(){if(!this.transitioning&&this.$element.hasClass("in")){var b=a.Event("hide.bs.collapse");if(this.$element.trigger(b),!b.isDefaultPrevented()){var c=this.dimension();this.$element[c](this.$element[c]())[0].offsetHeight,this.$element.addClass("collapsing").removeClass("collapse in").attr("aria-expanded",!1),this.$trigger.addClass("collapsed").attr("aria-expanded",!1),this.transitioning=1;var e=function(){this.transitioning=0,this.$element.removeClass("collapsing").addClass("collapse").trigger("hidden.bs.collapse")};return a.support.transition?void this.$element[c](0).one("bsTransitionEnd",a.proxy(e,this)).emulateTransitionEnd(d.TRANSITION_DURATION):e.call(this)}}},d.prototype.toggle=function(){this[this.$element.hasClass("in")?"hide":"show"]()},d.prototype.getParent=function(){return a(this.options.parent).find('[data-toggle="collapse"][data-parent="'+this.options.parent+'"]').each(a.proxy(function(c,d){var e=a(d);this.addAriaAndCollapsedClass(b(e),e)},this)).end()},d.prototype.addAriaAndCollapsedClass=function(a,b){var c=a.hasClass("in");a.attr("aria-expanded",c),b.toggleClass("collapsed",!c).attr("aria-expanded",c)};var e=a.fn.collapse;a.fn.collapse=c,a.fn.collapse.Constructor=d,a.fn.collapse.noConflict=function(){return a.fn.collapse=e,this},a(document).on("click.bs.collapse.data-api",'[data-toggle="collapse"]',function(d){var e=a(this);e.attr("data-target")||d.preventDefault();var f=b(e),g=f.data("bs.collapse"),h=g?"toggle":e.data();c.call(f,h)})}(jQuery),+function(a){"use strict";function b(b){var c=b.attr("data-target");c||(c=b.attr("href"),c=c&&/#[A-Za-z]/.test(c)&&c.replace(/.*(?=#[^\s]*$)/,""));var d=c&&a(c);return d&&d.length?d:b.parent()}function c(c){c&&3===c.which||(a(e).remove(),a(f).each(function(){var d=a(this),e=b(d),f={relatedTarget:this};e.hasClass("open")&&(c&&"click"==c.type&&/input|textarea/i.test(c.target.tagName)&&a.contains(e[0],c.target)||(e.trigger(c=a.Event("hide.bs.dropdown",f)),c.isDefaultPrevented()||(d.attr("aria-expanded","false"),e.removeClass("open").trigger(a.Event("hidden.bs.dropdown",f)))))}))}function d(b){return this.each(function(){var c=a(this),d=c.data("bs.dropdown");d||c.data("bs.dropdown",d=new g(this)),"string"==typeof b&&d[b].call(c)})}var e=".dropdown-backdrop",f='[data-toggle="dropdown"]',g=function(b){a(b).on("click.bs.dropdown",this.toggle)};g.VERSION="3.3.6",g.prototype.toggle=function(d){var e=a(this);if(!e.is(".disabled, :disabled")){var f=b(e),g=f.hasClass("open");if(c(),!g){"ontouchstart"in document.documentElement&&!f.closest(".navbar-nav").length&&a(document.createElement("div")).addClass("dropdown-backdrop").insertAfter(a(this)).on("click",c);var h={relatedTarget:this};if(f.trigger(d=a.Event("show.bs.dropdown",h)),d.isDefaultPrevented())return;e.trigger("focus").attr("aria-expanded","true"),f.toggleClass("open").trigger(a.Event("shown.bs.dropdown",h))}return!1}},g.prototype.keydown=function(c){if(/(38|40|27|32)/.test(c.which)&&!/input|textarea/i.test(c.target.tagName)){var d=a(this);if(c.preventDefault(),c.stopPropagation(),!d.is(".disabled, :disabled")){var e=b(d),g=e.hasClass("open");if(!g&&27!=c.which||g&&27==c.which)return 27==c.which&&e.find(f).trigger("focus"),d.trigger("click");var h=" li:not(.disabled):visible a",i=e.find(".dropdown-menu"+h);if(i.length){var j=i.index(c.target);38==c.which&&j>0&&j--,40==c.which&&jdocument.documentElement.clientHeight;this.$element.css({paddingLeft:!this.bodyIsOverflowing&&a?this.scrollbarWidth:"",paddingRight:this.bodyIsOverflowing&&!a?this.scrollbarWidth:""})},c.prototype.resetAdjustments=function(){this.$element.css({paddingLeft:"",paddingRight:""})},c.prototype.checkScrollbar=function(){var a=window.innerWidth;if(!a){var b=document.documentElement.getBoundingClientRect();a=b.right-Math.abs(b.left)}this.bodyIsOverflowing=document.body.clientWidth',trigger:"hover focus",title:"",delay:0,html:!1,container:!1,viewport:{selector:"body",padding:0}},c.prototype.init=function(b,c,d){if(this.enabled=!0,this.type=b,this.$element=a(c),this.options=this.getOptions(d),this.$viewport=this.options.viewport&&a(a.isFunction(this.options.viewport)?this.options.viewport.call(this,this.$element):this.options.viewport.selector||this.options.viewport),this.inState={click:!1,hover:!1,focus:!1},this.$element[0]instanceof document.constructor&&!this.options.selector)throw new Error("`selector` option must be specified when initializing "+this.type+" on the window.document object!");for(var e=this.options.trigger.split(" "),f=e.length;f--;){var g=e[f];if("click"==g)this.$element.on("click."+this.type,this.options.selector,a.proxy(this.toggle,this));else if("manual"!=g){var h="hover"==g?"mouseenter":"focusin",i="hover"==g?"mouseleave":"focusout";this.$element.on(h+"."+this.type,this.options.selector,a.proxy(this.enter,this)),this.$element.on(i+"."+this.type,this.options.selector,a.proxy(this.leave,this))}}this.options.selector?this._options=a.extend({},this.options,{trigger:"manual",selector:""}):this.fixTitle()},c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.getOptions=function(b){return b=a.extend({},this.getDefaults(),this.$element.data(),b),b.delay&&"number"==typeof b.delay&&(b.delay={show:b.delay,hide:b.delay}),b},c.prototype.getDelegateOptions=function(){var b={},c=this.getDefaults();return this._options&&a.each(this._options,function(a,d){c[a]!=d&&(b[a]=d)}),b},c.prototype.enter=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusin"==b.type?"focus":"hover"]=!0),c.tip().hasClass("in")||"in"==c.hoverState?void(c.hoverState="in"):(clearTimeout(c.timeout),c.hoverState="in",c.options.delay&&c.options.delay.show?void(c.timeout=setTimeout(function(){"in"==c.hoverState&&c.show()},c.options.delay.show)):c.show())},c.prototype.isInStateTrue=function(){for(var a in this.inState)if(this.inState[a])return!0;return!1},c.prototype.leave=function(b){var c=b instanceof this.constructor?b:a(b.currentTarget).data("bs."+this.type);return c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c)),b instanceof a.Event&&(c.inState["focusout"==b.type?"focus":"hover"]=!1),c.isInStateTrue()?void 0:(clearTimeout(c.timeout),c.hoverState="out",c.options.delay&&c.options.delay.hide?void(c.timeout=setTimeout(function(){"out"==c.hoverState&&c.hide()},c.options.delay.hide)):c.hide())},c.prototype.show=function(){var b=a.Event("show.bs."+this.type);if(this.hasContent()&&this.enabled){this.$element.trigger(b);var d=a.contains(this.$element[0].ownerDocument.documentElement,this.$element[0]);if(b.isDefaultPrevented()||!d)return;var e=this,f=this.tip(),g=this.getUID(this.type);this.setContent(),f.attr("id",g),this.$element.attr("aria-describedby",g),this.options.animation&&f.addClass("fade");var h="function"==typeof this.options.placement?this.options.placement.call(this,f[0],this.$element[0]):this.options.placement,i=/\s?auto?\s?/i,j=i.test(h);j&&(h=h.replace(i,"")||"top"),f.detach().css({top:0,left:0,display:"block"}).addClass(h).data("bs."+this.type,this),this.options.container?f.appendTo(this.options.container):f.insertAfter(this.$element),this.$element.trigger("inserted.bs."+this.type);var k=this.getPosition(),l=f[0].offsetWidth,m=f[0].offsetHeight;if(j){var n=h,o=this.getPosition(this.$viewport);h="bottom"==h&&k.bottom+m>o.bottom?"top":"top"==h&&k.top-mo.width?"left":"left"==h&&k.left-lg.top+g.height&&(e.top=g.top+g.height-i)}else{var j=b.left-f,k=b.left+f+c;jg.right&&(e.left=g.left+g.width-k)}return e},c.prototype.getTitle=function(){var a,b=this.$element,c=this.options;return a=b.attr("data-original-title")||("function"==typeof c.title?c.title.call(b[0]):c.title)},c.prototype.getUID=function(a){do a+=~~(1e6*Math.random());while(document.getElementById(a));return a},c.prototype.tip=function(){if(!this.$tip&&(this.$tip=a(this.options.template),1!=this.$tip.length))throw new Error(this.type+" `template` option must consist of exactly 1 top-level element!");return this.$tip},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".tooltip-arrow")},c.prototype.enable=function(){this.enabled=!0},c.prototype.disable=function(){this.enabled=!1},c.prototype.toggleEnabled=function(){this.enabled=!this.enabled},c.prototype.toggle=function(b){var c=this;b&&(c=a(b.currentTarget).data("bs."+this.type),c||(c=new this.constructor(b.currentTarget,this.getDelegateOptions()),a(b.currentTarget).data("bs."+this.type,c))),b?(c.inState.click=!c.inState.click,c.isInStateTrue()?c.enter(c):c.leave(c)):c.tip().hasClass("in")?c.leave(c):c.enter(c)},c.prototype.destroy=function(){var a=this;clearTimeout(this.timeout),this.hide(function(){a.$element.off("."+a.type).removeData("bs."+a.type),a.$tip&&a.$tip.detach(),a.$tip=null,a.$arrow=null,a.$viewport=null})};var d=a.fn.tooltip;a.fn.tooltip=b,a.fn.tooltip.Constructor=c,a.fn.tooltip.noConflict=function(){return a.fn.tooltip=d,this}}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.popover"),f="object"==typeof b&&b;(e||!/destroy|hide/.test(b))&&(e||d.data("bs.popover",e=new c(this,f)),"string"==typeof b&&e[b]())})}var c=function(a,b){this.init("popover",a,b)};if(!a.fn.tooltip)throw new Error("Popover requires tooltip.js");c.VERSION="3.3.6",c.DEFAULTS=a.extend({},a.fn.tooltip.Constructor.DEFAULTS,{placement:"right",trigger:"click",content:"",template:''}),c.prototype=a.extend({},a.fn.tooltip.Constructor.prototype),c.prototype.constructor=c,c.prototype.getDefaults=function(){return c.DEFAULTS},c.prototype.setContent=function(){var a=this.tip(),b=this.getTitle(),c=this.getContent();a.find(".popover-title")[this.options.html?"html":"text"](b),a.find(".popover-content").children().detach().end()[this.options.html?"string"==typeof c?"html":"append":"text"](c),a.removeClass("fade top bottom left right in"),a.find(".popover-title").html()||a.find(".popover-title").hide()},c.prototype.hasContent=function(){return this.getTitle()||this.getContent()},c.prototype.getContent=function(){var a=this.$element,b=this.options;return a.attr("data-content")||("function"==typeof b.content?b.content.call(a[0]):b.content)},c.prototype.arrow=function(){return this.$arrow=this.$arrow||this.tip().find(".arrow")};var d=a.fn.popover;a.fn.popover=b,a.fn.popover.Constructor=c,a.fn.popover.noConflict=function(){return a.fn.popover=d,this}}(jQuery),+function(a){"use strict";function b(c,d){this.$body=a(document.body),this.$scrollElement=a(a(c).is(document.body)?window:c),this.options=a.extend({},b.DEFAULTS,d),this.selector=(this.options.target||"")+" .nav li > a",this.offsets=[],this.targets=[],this.activeTarget=null,this.scrollHeight=0,this.$scrollElement.on("scroll.bs.scrollspy",a.proxy(this.process,this)),this.refresh(),this.process()}function c(c){return this.each(function(){var d=a(this),e=d.data("bs.scrollspy"),f="object"==typeof c&&c;e||d.data("bs.scrollspy",e=new b(this,f)),"string"==typeof c&&e[c]()})}b.VERSION="3.3.6",b.DEFAULTS={offset:10},b.prototype.getScrollHeight=function(){return this.$scrollElement[0].scrollHeight||Math.max(this.$body[0].scrollHeight,document.documentElement.scrollHeight)},b.prototype.refresh=function(){var b=this,c="offset",d=0;this.offsets=[],this.targets=[],this.scrollHeight=this.getScrollHeight(),a.isWindow(this.$scrollElement[0])||(c="position",d=this.$scrollElement.scrollTop()),this.$body.find(this.selector).map(function(){var b=a(this),e=b.data("target")||b.attr("href"),f=/^#./.test(e)&&a(e);return f&&f.length&&f.is(":visible")&&[[f[c]().top+d,e]]||null}).sort(function(a,b){return a[0]-b[0]}).each(function(){b.offsets.push(this[0]),b.targets.push(this[1])})},b.prototype.process=function(){var a,b=this.$scrollElement.scrollTop()+this.options.offset,c=this.getScrollHeight(),d=this.options.offset+c-this.$scrollElement.height(),e=this.offsets,f=this.targets,g=this.activeTarget;if(this.scrollHeight!=c&&this.refresh(),b>=d)return g!=(a=f[f.length-1])&&this.activate(a);if(g&&b=e[a]&&(void 0===e[a+1]||b .dropdown-menu > .active").removeClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!1),b.addClass("active").find('[data-toggle="tab"]').attr("aria-expanded",!0),h?(b[0].offsetWidth,b.addClass("in")):b.removeClass("fade"),b.parent(".dropdown-menu").length&&b.closest("li.dropdown").addClass("active").end().find('[data-toggle="tab"]').attr("aria-expanded",!0),e&&e()}var g=d.find("> .active"),h=e&&a.support.transition&&(g.length&&g.hasClass("fade")||!!d.find("> .fade").length);g.length&&h?g.one("bsTransitionEnd",f).emulateTransitionEnd(c.TRANSITION_DURATION):f(),g.removeClass("in")};var d=a.fn.tab;a.fn.tab=b,a.fn.tab.Constructor=c,a.fn.tab.noConflict=function(){return a.fn.tab=d,this};var e=function(c){c.preventDefault(),b.call(a(this),"show")};a(document).on("click.bs.tab.data-api",'[data-toggle="tab"]',e).on("click.bs.tab.data-api",'[data-toggle="pill"]',e)}(jQuery),+function(a){"use strict";function b(b){return this.each(function(){var d=a(this),e=d.data("bs.affix"),f="object"==typeof b&&b;e||d.data("bs.affix",e=new c(this,f)),"string"==typeof b&&e[b]()})}var c=function(b,d){this.options=a.extend({},c.DEFAULTS,d),this.$target=a(this.options.target).on("scroll.bs.affix.data-api",a.proxy(this.checkPosition,this)).on("click.bs.affix.data-api",a.proxy(this.checkPositionWithEventLoop,this)),this.$element=a(b),this.affixed=null,this.unpin=null,this.pinnedOffset=null,this.checkPosition()};c.VERSION="3.3.6",c.RESET="affix affix-top affix-bottom",c.DEFAULTS={offset:0,target:window},c.prototype.getState=function(a,b,c,d){var e=this.$target.scrollTop(),f=this.$element.offset(),g=this.$target.height();if(null!=c&&"top"==this.affixed)return c>e?"top":!1;if("bottom"==this.affixed)return null!=c?e+this.unpin<=f.top?!1:"bottom":a-d>=e+g?!1:"bottom";var h=null==this.affixed,i=h?e:f.top,j=h?g:b;return null!=c&&c>=e?"top":null!=d&&i+j>=a-d?"bottom":!1},c.prototype.getPinnedOffset=function(){if(this.pinnedOffset)return this.pinnedOffset;this.$element.removeClass(c.RESET).addClass("affix");var a=this.$target.scrollTop(),b=this.$element.offset();return this.pinnedOffset=b.top-a},c.prototype.checkPositionWithEventLoop=function(){setTimeout(a.proxy(this.checkPosition,this),1)},c.prototype.checkPosition=function(){if(this.$element.is(":visible")){var b=this.$element.height(),d=this.options.offset,e=d.top,f=d.bottom,g=Math.max(a(document).height(),a(document.body).height());"object"!=typeof d&&(f=e=d),"function"==typeof e&&(e=d.top(this.$element)),"function"==typeof f&&(f=d.bottom(this.$element));var h=this.getState(g,b,e,f);if(this.affixed!=h){null!=this.unpin&&this.$element.css("top","");var i="affix"+(h?"-"+h:""),j=a.Event(i+".bs.affix");if(this.$element.trigger(j),j.isDefaultPrevented())return;this.affixed=h,this.unpin="bottom"==h?this.getPinnedOffset():null,this.$element.removeClass(c.RESET).addClass(i).trigger(i.replace("affix","affixed")+".bs.affix")}"bottom"==h&&this.$element.offset({top:g-b-f})}};var d=a.fn.affix;a.fn.affix=b,a.fn.affix.Constructor=c,a.fn.affix.noConflict=function(){return a.fn.affix=d,this},a(window).on("load",function(){a('[data-spy="affix"]').each(function(){var c=a(this),d=c.data();d.offset=d.offset||{},null!=d.offsetBottom&&(d.offset.bottom=d.offsetBottom),null!=d.offsetTop&&(d.offset.top=d.offsetTop),b.call(c,d)})})}(jQuery);
8 |
--------------------------------------------------------------------------------
/src/main/resources/static/js/new.js:
--------------------------------------------------------------------------------
1 | 'use strict';
2 |
3 | (function ($) {
4 | $(function () {
5 | var getdatasource = function () {
6 |
7 | //调用后台接口获得数据
8 | return {"id":"1659672105459487","name":"root","content":"cn.murfree.node.composite.CompositeSequence","children":[{"id":"1659672105460940","name":"选择执行","content":"cn.murfree.node.composite.CompositeSelector","children":[{"id":"1659672105461766","name":"释放技能【顺序】","content":"cn.murfree.node.composite.CompositeSequence","children":[{"id":"1659672105462229","name":"蓝是否充足","content":"cn.murfree.conditional.ConditionalMp"},{"id":"1659672105462452","name":"执行释放技能","content":"cn.murfree.action.ActionSkill"}]},{"id":"1659672105463028","name":"加血【顺序】","content":"cn.murfree.node.composite.CompositeSequence","children":[{"id":"1659672105464032","name":"是否血未满","content":"cn.murfree.conditional.ConditionalHp"},{"id":"1659672105464677","name":"执行加血","content":"cn.murfree.action.ActionAddHp"}]},{"id":"1659672105465892","name":"巡逻【持续2秒】","content":"cn.murfree.action.ActionPatrol"}]}]}
9 | };
10 |
11 | var getId = function () {
12 | return (new Date().getTime()) * 1000 + Math.floor(Math.random() * 1001);
13 | };
14 |
15 | var getdata = function () {
16 | if ($('#chart-container').find('.node:first').length === 0) return '';
17 | var hierarchy = $('#chart-container').orgchart('getHierarchy');
18 | if (hierarchy) {
19 | return hierarchy;
20 | }
21 | return '';
22 | }
23 |
24 | var addnode = function (name, content, cid, pid) {
25 | var $chartContainer = $('#chart-container')
26 | var nodeVals = []
27 | var obj = {name: '', content: ''}
28 | obj.name = name ? name : ''
29 | obj.content = content ? content : ''
30 | obj.id = cid ? cid : ''
31 | nodeVals.push(obj)
32 | if (pid) var $node = $('#' + pid);
33 | var hasChild = $node.parent().attr('colspan') > 0 ? true : false
34 | if (!hasChild) {
35 | var rel = nodeVals.length > 1 ? '110' : '100'
36 | $chartContainer.orgchart('addChildren', $node, {
37 | 'children': nodeVals.map(function (item) {
38 | return {'name': item.name, 'content': item.content, 'relationship': rel, 'Id': item.id}
39 | })
40 | }, $.extend({}, $chartContainer.find('.orgchart').data('options'), {depth: 0}))
41 | } else {
42 | $chartContainer.orgchart('addSiblings', $node.closest('tr').siblings('.nodes').find('.node:first'),
43 | {
44 | 'siblings': nodeVals.map(function (item) {
45 | return {'name': item.name, 'content': item.content, 'relationship': '110', 'Id': item.id};
46 | })
47 | })
48 | }
49 | }
50 |
51 | var deletenode = function (pid) {
52 | var $node = $('#' + pid)
53 | if ($node[0] === $('.orgchart').find('.node:first')[0]) {
54 | alert('不能删除根节点')
55 | return getdata();
56 | }
57 | $('#chart-container').orgchart('removeNodes', $node)
58 | $('#selected-node').val('').data('node', null)
59 | return getdata();
60 | }
61 |
62 | var renderpic = function (datascource) {
63 | $('#chart-container').empty();//渲染之前先全部清空
64 | $('#chart-container').orgchart({
65 | 'data': datascource,
66 | 'parentNodeSymbol': '',
67 | 'nodeContent': "content",
68 | 'createNode': function ($node, data) {
69 | $node[0].id = getId();
70 | },
71 | 'draggable': true,
72 | 'dropCriteria': function ($draggedNode, $dragZone, $dropZone) {
73 | if ($draggedNode.find('.content').text().indexOf('manager') > -1 && $dropZone.find('.content').text().indexOf('engineer') > -1) {
74 | return false;
75 | }
76 | return true;
77 | }
78 | })
79 | .on('contextmenu', '.node', function (ev) {
80 | var oEvent = ev || event;
81 | var oUl = document.getElementById("contextDiv");
82 | oUl.style.display = "block";
83 | oUl.style.left = oEvent.clientX + 'px';
84 | oUl.style.top = oEvent.clientY + 'px';
85 | clicknode = $(this)[0].id
86 | // clicknode = $(this)
87 | return false;
88 | })
89 | .children('.orgchart').on('nodedropped.orgchart', function (event) {
90 | console.log('draggedNode:' + event.draggedNode.children('.title').text()
91 | + ', dragZone:' + event.dragZone.children('.title').text()
92 | + ', dropZone:' + event.dropZone.children('.title').text()
93 | );
94 | })
95 |
96 | }
97 |
98 | var disnone = function () {
99 | var oUl = document.getElementById("contextDiv");
100 | oUl.style.display = "none";
101 | }
102 |
103 | var erg = function (obj, id) {
104 | var fobj
105 | findobj(obj, id)
106 |
107 | function findobj(obj, id) {
108 | if (Object.prototype.toString.call(obj) === "[object Object]") {
109 | if (obj.id === id) {
110 | fobj = obj;
111 | } else if (obj.children) {
112 | findobj(obj.children, id);
113 | }
114 | } else {
115 | for (var i in obj) {
116 | findobj(obj[i], id);
117 | }
118 | }
119 | }
120 |
121 | return fobj;
122 | }
123 |
124 | // 以上事封装的方法,下面是具体执行的顺序
125 | // 设置一些常用量
126 | var data = getdatasource()
127 | var clicknode = '';
128 | renderpic(data)
129 | // 给标签绑定增加事件
130 | $('#add-node').on('click', function () {
131 | disnone();
132 | var name = '新的节点' //默认name
133 | var content = '节点描述' // 默认content
134 | // console.log(clicknode +','+ name +','+ content)
135 | //调用接口返回新的id,cid
136 |
137 | //调用接口返回新的id,cid
138 | addnode(name, content, getId(), clicknode)//此处先用getId()代替
139 | })
140 | // 给标签绑定增加事件
141 |
142 | // 绑定删除事件
143 | $('#delete-node').on('click', function () {
144 | disnone()
145 | //因为可以修改节点内容,不允许删除根节点
146 | //调用接口通知后台
147 |
148 | //调用接口通知后台
149 | data = deletenode(clicknode);
150 | });
151 | // 绑定删除事件
152 |
153 | // body绑定disnone事件,用于隐藏contextnemu
154 | $('body').on('click', disnone)
155 | // body绑定disnone事件,用于隐藏contextnemu
156 |
157 | // 绑定修改属性事件
158 | $('#change-props').on('click', function () {
159 | $('#itemid').val(clicknode);
160 | data = getdata();
161 | // console.log(erg(data,clicknode))
162 | $('#itemname').val(erg(data, clicknode).name)
163 | $('#itemcontent').val(erg(data, clicknode).content)
164 | //console.log(getdata())
165 | //调用接口,返回数据
166 | $('#myModal').modal({show: true})
167 |
168 | })
169 | // 绑定修改属性事件
170 |
171 |
172 | $('#savechange').on('click', function () {
173 | //保存之后重新渲染
174 | erg(data, clicknode).type = $("input[name='optionsRadios']:checked").val()
175 | console.log(erg(data, clicknode))
176 | erg(data, clicknode).name = $('#itemname').val()
177 | erg(data, clicknode).content = $('#itemcontent').val()
178 | // console.log(data)
179 | renderpic(data);
180 | })
181 |
182 |
183 | $('#log').on('click', function () {
184 | console.log(JSON.stringify(getdata()))
185 | alert("生成json成功,请在控制台查看!")
186 | })
187 |
188 | $('#loadJson').on('click', function () {
189 | let json = prompt();
190 | if (json !== undefined && json !== null && json !== '') {
191 | data = JSON.parse(json);
192 | clicknode = '';
193 | renderpic(data)
194 | }
195 |
196 |
197 | })
198 |
199 | })
200 | })(jQuery);
--------------------------------------------------------------------------------
/src/test/java/cn/murfree/Main.java:
--------------------------------------------------------------------------------
1 | package cn.murfree;
2 |
3 | import cn.murfree.context.TestContext;
4 | import cn.murfree.node.base.INode;
5 | import cn.murfree.tree.TestTree;
6 | import cn.murfree.utils.MurFreeBuilder;
7 | import com.fasterxml.jackson.core.JsonProcessingException;
8 | import com.fasterxml.jackson.databind.JsonNode;
9 | import com.fasterxml.jackson.databind.ObjectMapper;
10 |
11 | /**
12 | * Main
13 | *
14 | * @author lujun
15 | * @date 2022/8/5
16 | */
17 | public class Main {
18 |
19 | private static final ObjectMapper mapper = new ObjectMapper();
20 |
21 | public static void main(String[] args) throws Exception {
22 | System.out.println("顺序节点测试");
23 | testSeq();
24 | System.out.println("选择节点测试");
25 | testSelector();
26 | }
27 |
28 | private static void testSeq() throws Exception {
29 | String json = "{\"id\":\"1659672105459487\",\"name\":\"root\",\"content\":\"cn.murfree.node.composite.CompositeSequence\",\"children\":[{\"id\":\"1659672105460940\",\"name\":\"顺序执行\",\"content\":\"cn.murfree.node.composite.CompositeSequence\",\"children\":[{\"id\":\"1659672105461766\",\"name\":\"释放技能【顺序】\",\"content\":\"cn.murfree.node.composite.CompositeSequence\",\"children\":[{\"id\":\"1659672105462229\",\"name\":\"蓝是否充足\",\"content\":\"cn.murfree.conditional.ConditionalMp\"},{\"id\":\"1659672105462452\",\"name\":\"执行释放技能\",\"content\":\"cn.murfree.action.ActionSkill\"}]},{\"id\":\"1659672105463028\",\"name\":\"加血【顺序】\",\"content\":\"cn.murfree.node.composite.CompositeSequence\",\"children\":[{\"id\":\"1659672105464032\",\"name\":\"是否血未满\",\"content\":\"cn.murfree.conditional.ConditionalHp\"},{\"id\":\"1659672105464677\",\"name\":\"执行加血\",\"content\":\"cn.murfree.action.ActionAddHp\"}]},{\"id\":\"1659672105465892\",\"name\":\"巡逻【持续2秒】\",\"content\":\"cn.murfree.action.ActionPatrol\"}]}]}";
30 | final JsonNode jsonNode = mapper.readTree(json);
31 | final INode root = MurFreeBuilder.build(jsonNode);
32 | final TestTree tree = new TestTree(root, new TestContext());
33 | //顺序节点 每次执行tick 会全部执行
34 | tree.tick();
35 | }
36 |
37 | private static void testSelector() throws Exception {
38 | String json = "{\"id\":\"1659672105459487\",\"name\":\"root\",\"content\":\"cn.murfree.node.composite.CompositeSequence\",\"children\":[{\"id\":\"1659672105460940\",\"name\":\"选择执行\",\"content\":\"cn.murfree.node.composite.CompositeSelector\",\"children\":[{\"id\":\"1659672105461766\",\"name\":\"释放技能【顺序】\",\"content\":\"cn.murfree.node.composite.CompositeSequence\",\"children\":[{\"id\":\"1659672105462229\",\"name\":\"蓝是否充足\",\"content\":\"cn.murfree.conditional.ConditionalMp\"},{\"id\":\"1659672105462452\",\"name\":\"执行释放技能\",\"content\":\"cn.murfree.action.ActionSkill\"}]},{\"id\":\"1659672105463028\",\"name\":\"加血【顺序】\",\"content\":\"cn.murfree.node.composite.CompositeSequence\",\"children\":[{\"id\":\"1659672105464032\",\"name\":\"是否血未满\",\"content\":\"cn.murfree.conditional.ConditionalHp\"},{\"id\":\"1659672105464677\",\"name\":\"执行加血\",\"content\":\"cn.murfree.action.ActionAddHp\"}]},{\"id\":\"1659672105465892\",\"name\":\"巡逻【持续2秒】\",\"content\":\"cn.murfree.action.ActionPatrol\"}]}]}";
39 | final JsonNode jsonNode = mapper.readTree(json);
40 | final INode root = MurFreeBuilder.build(jsonNode);
41 | final TestTree tree = new TestTree(root, new TestContext());
42 | //选择节点 每次执行tick 当有子节点执行成功时结束
43 | for (int i = 0; i < 4; i++) {
44 | tree.tick();
45 | System.out.println("tick over");
46 | Thread.sleep(3000);
47 | }
48 | }
49 | }
--------------------------------------------------------------------------------
/src/test/java/cn/murfree/action/ActionAddHp.java:
--------------------------------------------------------------------------------
1 | package cn.murfree.action;
2 |
3 | import cn.murfree.contents.NodeStatus;
4 | import cn.murfree.context.TestContext;
5 | import cn.murfree.node.base.IActionNode;
6 |
7 | /**
8 | * ActionSkill
9 | *
10 | * @author lujun
11 | * @date 2022/8/5
12 | */
13 | public class ActionAddHp extends IActionNode {
14 |
15 | /**
16 | * 节点运行前执行
17 | */
18 | public void onStart() {
19 | super.onStart();
20 | System.out.println(this.getClass().getSimpleName() + " is start");
21 | }
22 |
23 |
24 | /**
25 | * 节点结束运行时执行
26 | */
27 | public void onEnd() {
28 | super.onEnd();
29 | System.out.println(this.getClass().getSimpleName() + " is end");
30 | }
31 |
32 | public NodeStatus onUpdate(TestContext context) {
33 | context.setHp(context.getHp()+20);
34 | System.out.println("add Hp");
35 | return NodeStatus.Success;
36 | }
37 | }
--------------------------------------------------------------------------------
/src/test/java/cn/murfree/action/ActionPatrol.java:
--------------------------------------------------------------------------------
1 | package cn.murfree.action;
2 |
3 | import cn.murfree.contents.NodeStatus;
4 | import cn.murfree.context.TestContext;
5 | import cn.murfree.node.base.IActionNode;
6 |
7 | /**
8 | * 巡逻
9 | *
10 | * @author lujun
11 | * @date 2022/8/5
12 | */
13 | public class ActionPatrol extends IActionNode {
14 |
15 | //持续时间
16 | private final int duration = 2000;
17 | //当前时间
18 | private long startTime = 0;
19 |
20 | @Override
21 | public void onStart() {
22 | super.onStart();
23 | this.startTime = System.currentTimeMillis();
24 | }
25 | public NodeStatus onUpdate(TestContext context) {
26 | if (System.currentTimeMillis() - this.startTime >= this.duration) {
27 | System.out.println("巡逻完毕");
28 | return NodeStatus.Success;
29 | }
30 | System.out.println("巡逻中");
31 | return NodeStatus.Running;
32 | }
33 | }
--------------------------------------------------------------------------------
/src/test/java/cn/murfree/action/ActionSkill.java:
--------------------------------------------------------------------------------
1 | package cn.murfree.action;
2 |
3 | import cn.murfree.contents.NodeStatus;
4 | import cn.murfree.context.TestContext;
5 | import cn.murfree.node.base.IActionNode;
6 |
7 | /**
8 | * ActionSkill
9 | *
10 | * @author lujun
11 | * @date 2022/8/5
12 | */
13 | public class ActionSkill extends IActionNode {
14 |
15 | /**
16 | * 节点运行前执行
17 | */
18 | public void onStart() {
19 | super.onStart();
20 | System.out.println(this.getClass().getSimpleName() + " is start");
21 | }
22 |
23 |
24 | /**
25 | * 节点结束运行时执行
26 | */
27 | public void onEnd() {
28 | super.onEnd();
29 | //获得上下文
30 | final TestContext context = getContext();
31 | //技能释放完毕扣蓝
32 | context.setMp(context.getMp()-20);
33 | System.out.println(this.getClass().getSimpleName() + " is end");
34 | }
35 |
36 | public NodeStatus onUpdate(TestContext context) {
37 | System.out.println("release skills");
38 | return NodeStatus.Success;
39 | }
40 | }
--------------------------------------------------------------------------------
/src/test/java/cn/murfree/conditional/ConditionalHp.java:
--------------------------------------------------------------------------------
1 | package cn.murfree.conditional;
2 |
3 |
4 | import cn.murfree.contents.NodeStatus;
5 | import cn.murfree.context.TestContext;
6 | import cn.murfree.node.base.IConditionalNode;
7 |
8 | /**
9 | * ConditionalHp
10 | *
11 | * @author lujun
12 | * @date 2022/7/22
13 | */
14 | public class ConditionalHp extends IConditionalNode {
15 |
16 |
17 | @Override
18 | public NodeStatus onUpdate(TestContext cxt) {
19 | System.out.println("cxt.hp : "+cxt.getHp()+", ConditionalHp 判断结果 "+ (cxt.getHp() <= 80));
20 | if(cxt.getHp() <= 80){
21 | return NodeStatus.Success;
22 | }
23 | return NodeStatus.Failure;
24 | }
25 | }
--------------------------------------------------------------------------------
/src/test/java/cn/murfree/conditional/ConditionalMp.java:
--------------------------------------------------------------------------------
1 | package cn.murfree.conditional;
2 |
3 | import cn.murfree.contents.NodeStatus;
4 | import cn.murfree.context.TestContext;
5 | import cn.murfree.node.base.IConditionalNode;
6 |
7 | /**
8 | * ConditionalHp
9 | *
10 | * @author lujun
11 | * @date 2022/7/22
12 | */
13 | public class ConditionalMp extends IConditionalNode {
14 |
15 |
16 | @Override
17 | public NodeStatus onUpdate(TestContext cxt) {
18 | System.out.println("cxt.mp : "+cxt.getMp()+", ConditionalMp 判断结果 "+ (cxt.getMp() >= 100));
19 | if(cxt.getMp() >= 100){
20 | return NodeStatus.Success;
21 | }
22 | return NodeStatus.Failure;
23 | }
24 | }
--------------------------------------------------------------------------------
/src/test/java/cn/murfree/context/TestContext.java:
--------------------------------------------------------------------------------
1 | package cn.murfree.context;
2 |
3 | /**
4 | * LogContext
5 | *
6 | * @author lujun
7 | * @date 2022/8/5
8 | */
9 | public class TestContext implements IContext {
10 |
11 | private int hp = 70;
12 | private int mp = 100;
13 |
14 | public int getHp() {
15 | return hp;
16 | }
17 |
18 | public void setHp(int hp) {
19 | this.hp = hp;
20 | }
21 |
22 | public int getMp() {
23 | return mp;
24 | }
25 |
26 | public void setMp(int mp) {
27 | this.mp = mp;
28 | }
29 | }
--------------------------------------------------------------------------------
/src/test/java/cn/murfree/tree/TestTree.java:
--------------------------------------------------------------------------------
1 | package cn.murfree.tree;
2 |
3 | import cn.murfree.context.TestContext;
4 | import cn.murfree.node.base.INode;
5 | import cn.murfree.node.base.ITree;
6 |
7 | /**
8 | * TestTree
9 | *
10 | * @author lujun
11 | * @date 2022/8/5
12 | */
13 | public class TestTree extends ITree {
14 |
15 | public TestTree(INode root, TestContext context) {
16 | super(root, context);
17 | }
18 | }
--------------------------------------------------------------------------------
| |