/js/jquery.fancytree/jquery.fancytree-all.js

https://bitbucket.org/sluchainiyznak/ais_reestr · JavaScript · 5824 lines · 3602 code · 312 blank · 1910 comment · 754 complexity · 18c7f0d5e4434a8bc96ff9c2234a3597 MD5 · raw file

  1. /*!
  2. * jquery.fancytree.js
  3. * Dynamic tree view control, with support for lazy loading of branches.
  4. * https://github.com/mar10/fancytree/
  5. *
  6. * Copyright (c) 2006-2014, Martin Wendt (http://wwWendt.de)
  7. * Released under the MIT license
  8. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  9. *
  10. * @version 2.0.0-7
  11. * @date 2014-03-09T20:32
  12. */
  13. /** Core Fancytree module.
  14. */
  15. // Start of local namespace
  16. ;(function($, window, document, undefined) {
  17. "use strict";
  18. // prevent duplicate loading
  19. if ( $.ui.fancytree && $.ui.fancytree.version ) {
  20. $.ui.fancytree.warn("Fancytree: ignored duplicate include");
  21. return;
  22. }
  23. /* *****************************************************************************
  24. * Private functions and variables
  25. */
  26. function _raiseNotImplemented(msg){
  27. msg = msg || "";
  28. $.error("Not implemented: " + msg);
  29. }
  30. function _assert(cond, msg){
  31. // TODO: see qunit.js extractStacktrace()
  32. if(!cond){
  33. msg = msg ? ": " + msg : "";
  34. $.error("Assertion failed" + msg);
  35. }
  36. }
  37. function consoleApply(method, args){
  38. var i, s,
  39. fn = window.console ? window.console[method] : null;
  40. if(fn){
  41. if(fn.apply){
  42. fn.apply(window.console, args);
  43. }else{
  44. // IE?
  45. s = "";
  46. for( i=0; i<args.length; i++){
  47. s += args[i];
  48. }
  49. fn(s);
  50. }
  51. }
  52. }
  53. /** Return true if dotted version string is equal or higher than requested version.
  54. *
  55. * See http://jsfiddle.net/mar10/FjSAN/
  56. */
  57. function isVersionAtLeast(dottedVersion, major, minor, patch){
  58. var i, v, t,
  59. verParts = $.map($.trim(dottedVersion).split("."), function(e){ return parseInt(e, 10); }),
  60. testParts = $.map(Array.prototype.slice.call(arguments, 1), function(e){ return parseInt(e, 10); });
  61. for( i = 0; i < testParts.length; i++ ){
  62. v = verParts[i] || 0;
  63. t = testParts[i] || 0;
  64. if( v !== t ){
  65. return ( v > t );
  66. }
  67. }
  68. return true;
  69. }
  70. /** Return a wrapper that calls sub.methodName() and exposes
  71. * this : tree
  72. * this._local : tree.ext.EXTNAME
  73. * this._super : base.methodName()
  74. */
  75. function _makeVirtualFunction(methodName, tree, base, extension, extName){
  76. // $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName);
  77. // if(rexTestSuper && !rexTestSuper.test(func)){
  78. // // extension.methodName() doesn't call _super(), so no wrapper required
  79. // return func;
  80. // }
  81. // Use an immediate function as closure
  82. var proxy = (function(){
  83. var prevFunc = tree[methodName], // org. tree method or prev. proxy
  84. baseFunc = extension[methodName], //
  85. _local = tree.ext[extName],
  86. _super = function(){
  87. return prevFunc.apply(tree, arguments);
  88. };
  89. // Return the wrapper function
  90. return function(){
  91. var prevLocal = tree._local,
  92. prevSuper = tree._super;
  93. try{
  94. tree._local = _local;
  95. tree._super = _super;
  96. return baseFunc.apply(tree, arguments);
  97. }finally{
  98. tree._local = prevLocal;
  99. tree._super = prevSuper;
  100. }
  101. };
  102. })(); // end of Immediate Function
  103. return proxy;
  104. }
  105. /**
  106. * Subclass `base` by creating proxy functions
  107. */
  108. function _subclassObject(tree, base, extension, extName){
  109. // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
  110. for(var attrName in extension){
  111. if(typeof extension[attrName] === "function"){
  112. if(typeof tree[attrName] === "function"){
  113. // override existing method
  114. tree[attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
  115. }else if(attrName.charAt(0) === "_"){
  116. // Create private methods in tree.ext.EXTENSION namespace
  117. tree.ext[extName][attrName] = _makeVirtualFunction(attrName, tree, base, extension, extName);
  118. }else{
  119. $.error("Could not override tree." + attrName + ". Use prefix '_' to create tree." + extName + "._" + attrName);
  120. }
  121. }else{
  122. // Create member variables in tree.ext.EXTENSION namespace
  123. if(attrName !== "options"){
  124. tree.ext[extName][attrName] = extension[attrName];
  125. }
  126. }
  127. }
  128. }
  129. function _getResolvedPromise(context, argArray){
  130. if(context === undefined){
  131. return $.Deferred(function(){this.resolve();}).promise();
  132. }else{
  133. return $.Deferred(function(){this.resolveWith(context, argArray);}).promise();
  134. }
  135. }
  136. function _getRejectedPromise(context, argArray){
  137. if(context === undefined){
  138. return $.Deferred(function(){this.reject();}).promise();
  139. }else{
  140. return $.Deferred(function(){this.rejectWith(context, argArray);}).promise();
  141. }
  142. }
  143. function _makeResolveFunc(deferred, context){
  144. return function(){
  145. deferred.resolveWith(context);
  146. };
  147. }
  148. // TODO: use currying
  149. function _makeNodeTitleMatcher(s){
  150. s = s.toLowerCase();
  151. return function(node){
  152. return node.title.toLowerCase().indexOf(s) >= 0;
  153. };
  154. }
  155. var i,
  156. FT = null, // initialized below
  157. //boolean attributes that can be set with equivalent class names in the LI tags
  158. CLASS_ATTRS = "active expanded focus folder hideCheckbox lazy selected unselectable".split(" "),
  159. CLASS_ATTR_MAP = {},
  160. // Top-level Fancytree node attributes, that can be set by dict
  161. NODE_ATTRS = "expanded extraClasses folder hideCheckbox key lazy selected title tooltip unselectable".split(" "),
  162. NODE_ATTR_MAP = {},
  163. // Attribute names that should NOT be added to node.data
  164. NONE_NODE_DATA_MAP = {"active": true, "children": true, "data": true, "focus": true};
  165. for(i=0; i<CLASS_ATTRS.length; i++){ CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true; }
  166. for(i=0; i<NODE_ATTRS.length; i++){ NODE_ATTR_MAP[NODE_ATTRS[i]] = true; }
  167. /* *****************************************************************************
  168. * FancytreeNode
  169. */
  170. /**
  171. * Creates a new FancytreeNode
  172. *
  173. * @class FancytreeNode
  174. * @classdesc A FancytreeNode represents the hierarchical data model and operations.
  175. *
  176. * @param {FancytreeNode} parent
  177. * @param {NodeData} obj
  178. *
  179. * @property {Fancytree} tree The tree instance
  180. * @property {FancytreeNode} parent The parent node
  181. * @property {string} key Node id (must be unique inside the tree)
  182. * @property {string} title Display name (may contain HTML)
  183. * @property {object} data Contains all extra data that was passed on node creation
  184. * @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br>
  185. * For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array
  186. * to define a node that has no children.
  187. * @property {boolean} expanded Use isExpanded(), setExpanded() to access this property.
  188. * @property {string} extraClasses Addtional CSS classes, added to the node's `&lt;span>`
  189. * @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
  190. * Note: Also non-folders may have children.
  191. * @property {string} statusNodeType null or type of temporarily generated system node like 'loading', or 'error'.
  192. * @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion.
  193. * @property {boolean} selected Use isSelected(), setSelected() to access this property.
  194. * @property {string} tooltip Alternative description used as hover banner
  195. */
  196. function FancytreeNode(parent, obj){
  197. var i, l, name, cl;
  198. this.parent = parent;
  199. this.tree = parent.tree;
  200. this.ul = null;
  201. this.li = null; // <li id='key' ftnode=this> tag
  202. // this.isStatusNode = false;
  203. this.statusNodeType = null;
  204. this._isLoading = false;
  205. this.data = {};
  206. // TODO: merge this code with node.toDict()
  207. // copy attributes from obj object
  208. for(i=0, l=NODE_ATTRS.length; i<l; i++){
  209. name = NODE_ATTRS[i];
  210. this[name] = obj[name];
  211. }
  212. // node.data += obj.data
  213. if(obj.data){
  214. $.extend(this.data, obj.data);
  215. }
  216. // copy all other attributes to this.data.NAME
  217. for(name in obj){
  218. if(!NODE_ATTR_MAP[name] && !$.isFunction(obj[name]) && !NONE_NODE_DATA_MAP[name]){
  219. // node.data.NAME = obj.NAME
  220. this.data[name] = obj[name];
  221. }
  222. }
  223. // Fix missing key
  224. if( this.key == null ){ // test for null OR undefined
  225. this.key = "_" + (FT._nextNodeKey++);
  226. }
  227. // Fix tree.activeNode
  228. // TODO: not elegant: we use obj.active as marker to set tree.activeNode
  229. // when loading from a dictionary.
  230. if(obj.active){
  231. _assert(this.tree.activeNode === null, "only one active node allowed");
  232. this.tree.activeNode = this;
  233. }
  234. // TODO: handle obj.focus = true
  235. // Create child nodes
  236. this.children = null;
  237. cl = obj.children;
  238. if(cl && cl.length){
  239. this._setChildren(cl);
  240. }
  241. }
  242. FancytreeNode.prototype = /** @lends FancytreeNode# */{
  243. /* Return the direct child FancytreeNode with a given key, index. */
  244. _findDirectChild: function(ptr){
  245. var i, l,
  246. cl = this.children;
  247. if(cl){
  248. if(typeof ptr === "string"){
  249. for(i=0, l=cl.length; i<l; i++){
  250. if(cl[i].key === ptr){
  251. return cl[i];
  252. }
  253. }
  254. }else if(typeof ptr === "number"){
  255. return this.children[ptr];
  256. }else if(ptr.parent === this){
  257. return ptr;
  258. }
  259. }
  260. return null;
  261. },
  262. // TODO: activate()
  263. // TODO: activateSilently()
  264. /* Internal helper called in recursive addChildren sequence.*/
  265. _setChildren: function(children){
  266. _assert(children && (!this.children || this.children.length === 0), "only init supported");
  267. this.children = [];
  268. for(var i=0, l=children.length; i<l; i++){
  269. this.children.push(new FancytreeNode(this, children[i]));
  270. }
  271. },
  272. /**
  273. * Append (or insert) a list of child nodes.
  274. *
  275. * @param {NodeData[]} children array of child node definitions (also single child accepted)
  276. * @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such).
  277. * If omitted, the new children are appended.
  278. * @returns {FancytreeNode} first child added
  279. *
  280. * @see FancytreeNode#applyPatch
  281. */
  282. addChildren: function(children, insertBefore){
  283. var i, l, pos,
  284. firstNode = null,
  285. nodeList = [];
  286. if($.isPlainObject(children) ){
  287. children = [children];
  288. }
  289. if(!this.children){
  290. this.children = [];
  291. }
  292. for(i=0, l=children.length; i<l; i++){
  293. nodeList.push(new FancytreeNode(this, children[i]));
  294. }
  295. firstNode = nodeList[0];
  296. if(insertBefore == null){
  297. this.children = this.children.concat(nodeList);
  298. }else{
  299. insertBefore = this._findDirectChild(insertBefore);
  300. pos = $.inArray(insertBefore, this.children);
  301. _assert(pos >= 0, "insertBefore must be an existing child");
  302. // insert nodeList after children[pos]
  303. this.children.splice.apply(this.children, [pos, 0].concat(nodeList));
  304. }
  305. if( !this.parent || this.parent.ul || this.tr ){
  306. // render if the parent was rendered (or this is a root node)
  307. this.render();
  308. }
  309. if( this.tree.options.selectMode === 3 ){
  310. this.fixSelection3FromEndNodes();
  311. }
  312. return firstNode;
  313. },
  314. /**
  315. * Append or prepend a node, or append a child node.
  316. *
  317. * This a convenience function that calls addChildren()
  318. *
  319. * @param {NodeData} node node definition
  320. * @param {string} [mode=child] 'before', 'after', or 'child' ('over' is a synonym for 'child')
  321. * @returns {FancytreeNode} new node
  322. */
  323. addNode: function(node, mode){
  324. if(mode === undefined || mode === "over"){
  325. mode = "child";
  326. }
  327. switch(mode){
  328. case "after":
  329. return this.getParent().addChildren(node, this.getNextSibling());
  330. case "before":
  331. return this.getParent().addChildren(node, this);
  332. case "child":
  333. case "over":
  334. return this.addChildren(node);
  335. }
  336. _assert(false, "Invalid mode: " + mode);
  337. },
  338. /**
  339. * Modify existing child nodes.
  340. *
  341. * @param {NodePatch} patch
  342. * @returns {$.Promise}
  343. * @see FancytreeNode#addChildren
  344. */
  345. applyPatch: function(patch) {
  346. // patch [key, null] means 'remove'
  347. if(patch === null){
  348. this.remove();
  349. return _getResolvedPromise(this);
  350. }
  351. // TODO: make sure that root node is not collapsed or modified
  352. // copy (most) attributes to node.ATTR or node.data.ATTR
  353. var name, promise, v,
  354. IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global
  355. for(name in patch){
  356. v = patch[name];
  357. if( !IGNORE_MAP[name] && !$.isFunction(v)){
  358. if(NODE_ATTR_MAP[name]){
  359. this[name] = v;
  360. }else{
  361. this.data[name] = v;
  362. }
  363. }
  364. }
  365. // Remove and/or create children
  366. if(patch.hasOwnProperty("children")){
  367. this.removeChildren();
  368. if(patch.children){ // only if not null and not empty list
  369. // TODO: addChildren instead?
  370. this._setChildren(patch.children);
  371. }
  372. // TODO: how can we APPEND or INSERT child nodes?
  373. }
  374. if(this.isVisible()){
  375. this.renderTitle();
  376. this.renderStatus();
  377. }
  378. // Expand collapse (final step, since this may be async)
  379. if(patch.hasOwnProperty("expanded")){
  380. promise = this.setExpanded(patch.expanded);
  381. }else{
  382. promise = _getResolvedPromise(this);
  383. }
  384. return promise;
  385. },
  386. /** Collapse all sibling nodes.
  387. * @returns {$.Promise}
  388. */
  389. collapseSiblings: function() {
  390. return this.tree._callHook("nodeCollapseSiblings", this);
  391. },
  392. /** Copy this node as sibling or child of `node`.
  393. *
  394. * @param {FancytreeNode} node source node
  395. * @param {string} mode 'before' | 'after' | 'child'
  396. * @param {Function} [map] callback function(NodeData) that could modify the new node
  397. * @returns {FancytreeNode} new
  398. */
  399. copyTo: function(node, mode, map) {
  400. return node.addNode(this.toDict(true, map), mode);
  401. },
  402. /** Count direct and indirect children.
  403. *
  404. * @param {boolean} [deep=true] pass 'false' to only count direct children
  405. * @returns {int} number of child nodes
  406. */
  407. countChildren: function(deep) {
  408. var cl = this.children, i, l, n;
  409. if( !cl ){
  410. return 0;
  411. }
  412. n = cl.length;
  413. if(deep !== false){
  414. for(i=0, l=n; i<l; i++){
  415. n += cl[i].countChildren();
  416. }
  417. }
  418. return n;
  419. },
  420. // TODO: deactivate()
  421. /** Write to browser console if debugLevel >= 2 (prepending node info)
  422. *
  423. * @param {*} msg string or object or array of such
  424. */
  425. debug: function(msg){
  426. if( this.tree.options.debugLevel >= 2 ) {
  427. Array.prototype.unshift.call(arguments, this.toString());
  428. consoleApply("debug", arguments);
  429. }
  430. },
  431. /** Deprecated.
  432. * @deprecated since 2014-02-16. Use resetLazy() instead.
  433. */
  434. discard: function(){
  435. this.warn("FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead.");
  436. return this.resetLazy();
  437. },
  438. // TODO: expand(flag)
  439. /**Find all nodes that contain `match` in the title.
  440. *
  441. * @param {string | function(node)} match string to search for, of a function that
  442. * returns `true` if a node is matched.
  443. * @returns {FancytreeNode[]} array of nodes (may be empty)
  444. * @see FancytreeNode#findAll
  445. */
  446. findAll: function(match) {
  447. match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
  448. var res = [];
  449. this.visit(function(n){
  450. if(match(n)){
  451. res.push(n);
  452. }
  453. });
  454. return res;
  455. },
  456. /**Find first node that contains `match` in the title (not including self).
  457. *
  458. * @param {string | function(node)} match string to search for, of a function that
  459. * returns `true` if a node is matched.
  460. * @returns {FancytreeNode} matching node or null
  461. * @example
  462. * <b>fat</b> text
  463. */
  464. findFirst: function(match) {
  465. match = $.isFunction(match) ? match : _makeNodeTitleMatcher(match);
  466. var res = null;
  467. this.visit(function(n){
  468. if(match(n)){
  469. res = n;
  470. return false;
  471. }
  472. });
  473. return res;
  474. },
  475. /* Apply selection state (internal use only) */
  476. _changeSelectStatusAttrs: function (state) {
  477. var changed = false;
  478. switch(state){
  479. case false:
  480. changed = ( this.selected || this.partsel );
  481. this.selected = false;
  482. this.partsel = false;
  483. break;
  484. case true:
  485. changed = ( !this.selected || !this.partsel );
  486. this.selected = true;
  487. this.partsel = true;
  488. break;
  489. case undefined:
  490. changed = ( this.selected || !this.partsel );
  491. this.selected = false;
  492. this.partsel = true;
  493. break;
  494. default:
  495. _assert(false, "invalid state: " + state);
  496. }
  497. // this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed);
  498. if( changed ){
  499. this.renderStatus();
  500. }
  501. return changed;
  502. },
  503. /**
  504. * Fix selection status, after this node was (de)selected in multi-hier mode.
  505. * This includes (de)selecting all children.
  506. */
  507. fixSelection3AfterClick: function() {
  508. var flag = this.isSelected();
  509. // this.debug("fixSelection3AfterClick()");
  510. this.visit(function(node){
  511. node._changeSelectStatusAttrs(flag);
  512. });
  513. this.fixSelection3FromEndNodes();
  514. },
  515. /**
  516. * Fix selection status for multi-hier mode.
  517. * Only end-nodes are considered to update the descendants branch and parents.
  518. * Should be called after this node has loaded new children or after
  519. * children have been modified using the API.
  520. */
  521. fixSelection3FromEndNodes: function() {
  522. // this.debug("fixSelection3FromEndNodes()");
  523. _assert(this.tree.options.selectMode === 3, "expected selectMode 3");
  524. // Visit all end nodes and adjust their parent's `selected` and `partsel`
  525. // attributes. Return selection state true, false, or undefined.
  526. function _walk(node){
  527. var i, l, child, s, state, allSelected,someSelected,
  528. children = node.children;
  529. if( children ){
  530. // check all children recursively
  531. allSelected = true;
  532. someSelected = false;
  533. for( i=0, l=children.length; i<l; i++ ){
  534. child = children[i];
  535. // the selection state of a node is not relevant; we need the end-nodes
  536. s = _walk(child);
  537. if( s !== false ) {
  538. someSelected = true;
  539. }
  540. if( s !== true ) {
  541. allSelected = false;
  542. }
  543. }
  544. state = allSelected ? true : (someSelected ? undefined : false);
  545. }else{
  546. // This is an end-node: simply report the status
  547. // state = ( node.unselectable ) ? undefined : !!node.selected;
  548. state = !!node.selected;
  549. }
  550. node._changeSelectStatusAttrs(state);
  551. return state;
  552. }
  553. _walk(this);
  554. // Update parent's state
  555. this.visitParents(function(node){
  556. var i, l, child, state,
  557. children = node.children,
  558. allSelected = true,
  559. someSelected = false;
  560. for( i=0, l=children.length; i<l; i++ ){
  561. child = children[i];
  562. // When fixing the parents, we trust the sibling status (i.e.
  563. // we don't recurse)
  564. if( child.selected || child.partsel ) {
  565. someSelected = true;
  566. }
  567. if( !child.unselectable && !child.selected ) {
  568. allSelected = false;
  569. }
  570. }
  571. state = allSelected ? true : (someSelected ? undefined : false);
  572. node._changeSelectStatusAttrs(state);
  573. });
  574. },
  575. // TODO: focus()
  576. /**
  577. * Update node data. If dict contains 'children', then also replace
  578. * the hole sub tree.
  579. * @param {NodeData} dict
  580. *
  581. * @see FancytreeNode#addChildren
  582. * @see FancytreeNode#applyPatch
  583. */
  584. fromDict: function(dict) {
  585. // copy all other attributes to this.data.xxx
  586. for(var name in dict){
  587. if(NODE_ATTR_MAP[name]){
  588. // node.NAME = dict.NAME
  589. this[name] = dict[name];
  590. }else if(name === "data"){
  591. // node.data += dict.data
  592. $.extend(this.data, dict.data);
  593. }else if(!$.isFunction(dict[name]) && !NONE_NODE_DATA_MAP[name]){
  594. // node.data.NAME = dict.NAME
  595. this.data[name] = dict[name];
  596. }
  597. }
  598. if(dict.children){
  599. // recursively set children and render
  600. this.removeChildren();
  601. this.addChildren(dict.children);
  602. }else{
  603. this.renderTitle();
  604. }
  605. /*
  606. var children = dict.children;
  607. if(children === undefined){
  608. this.data = $.extend(this.data, dict);
  609. this.render();
  610. return;
  611. }
  612. dict = $.extend({}, dict);
  613. dict.children = undefined;
  614. this.data = $.extend(this.data, dict);
  615. this.removeChildren();
  616. this.addChild(children);
  617. */
  618. },
  619. /** Return the list of child nodes (undefined for unexpanded lazy nodes).
  620. * @returns {FancytreeNode[] | undefined}
  621. */
  622. getChildren: function() {
  623. if(this.hasChildren() === undefined){ // TODO: only required for lazy nodes?
  624. return undefined; // Lazy node: unloaded, currently loading, or load error
  625. }
  626. return this.children;
  627. },
  628. /** Return the first child node or null.
  629. * @returns {FancytreeNode | null}
  630. */
  631. getFirstChild: function() {
  632. return this.children ? this.children[0] : null;
  633. },
  634. /** Return the 0-based child index.
  635. * @returns {int}
  636. */
  637. getIndex: function() {
  638. // return this.parent.children.indexOf(this);
  639. return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7
  640. },
  641. /** Return the hierarchical child index (1-based, e.g. '3.2.4').
  642. * @returns {string}
  643. */
  644. getIndexHier: function(separator) {
  645. separator = separator || ".";
  646. var res = [];
  647. $.each(this.getParentList(false, true), function(i, o){
  648. res.push(o.getIndex() + 1);
  649. });
  650. return res.join(separator);
  651. },
  652. /** Return the parent keys separated by options.keyPathSeparator, e.g. "id_1/id_17/id_32".
  653. * @param {boolean} [excludeSelf=false]
  654. * @returns {string}
  655. */
  656. getKeyPath: function(excludeSelf) {
  657. var path = [],
  658. sep = this.tree.options.keyPathSeparator;
  659. this.visitParents(function(n){
  660. if(n.parent){
  661. path.unshift(n.key);
  662. }
  663. }, !excludeSelf);
  664. return sep + path.join(sep);
  665. },
  666. /** Return the last child of this node or null.
  667. * @returns {FancytreeNode | null}
  668. */
  669. getLastChild: function() {
  670. return this.children ? this.children[this.children.length - 1] : null;
  671. },
  672. /** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... .
  673. * @returns {int}
  674. */
  675. getLevel: function() {
  676. var level = 0,
  677. dtn = this.parent;
  678. while( dtn ) {
  679. level++;
  680. dtn = dtn.parent;
  681. }
  682. return level;
  683. },
  684. /** Return the successor node (under the same parent) or null.
  685. * @returns {FancytreeNode | null}
  686. */
  687. getNextSibling: function() {
  688. // TODO: use indexOf, if available: (not in IE6)
  689. if( this.parent ){
  690. var i, l,
  691. ac = this.parent.children;
  692. for(i=0, l=ac.length-1; i<l; i++){ // up to length-2, so next(last) = null
  693. if( ac[i] === this ){
  694. return ac[i+1];
  695. }
  696. }
  697. }
  698. return null;
  699. },
  700. /** Return the parent node (null for the system root node).
  701. * @returns {FancytreeNode | null}
  702. */
  703. getParent: function() {
  704. // TODO: return null for top-level nodes?
  705. return this.parent;
  706. },
  707. /** Return an array of all parent nodes (top-down).
  708. * @param {boolean} [includeRoot=false] Include the invisible system root node.
  709. * @param {boolean} [includeSelf=false] Include the node itself.
  710. * @returns {FancytreeNode[]}
  711. */
  712. getParentList: function(includeRoot, includeSelf) {
  713. var l = [],
  714. dtn = includeSelf ? this : this.parent;
  715. while( dtn ) {
  716. if( includeRoot || dtn.parent ){
  717. l.unshift(dtn);
  718. }
  719. dtn = dtn.parent;
  720. }
  721. return l;
  722. },
  723. /** Return the predecessor node (under the same parent) or null.
  724. * @returns {FancytreeNode | null}
  725. */
  726. getPrevSibling: function() {
  727. if( this.parent ){
  728. var i, l,
  729. ac = this.parent.children;
  730. for(i=1, l=ac.length; i<l; i++){ // start with 1, so prev(first) = null
  731. if( ac[i] === this ){
  732. return ac[i-1];
  733. }
  734. }
  735. }
  736. return null;
  737. },
  738. /** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded).
  739. * @returns {boolean | undefined}
  740. */
  741. hasChildren: function() {
  742. if(this.lazy){
  743. if(this.children == null ){
  744. // null or undefined: Not yet loaded
  745. return undefined;
  746. }else if(this.children.length === 0){
  747. // Loaded, but response was empty
  748. return false;
  749. }else if(this.children.length === 1 && this.children[0].isStatusNode() ){
  750. // Currently loading or load error
  751. return undefined;
  752. }
  753. return true;
  754. }
  755. return !!this.children;
  756. },
  757. /** Return true if node has keyboard focus.
  758. * @returns {boolean}
  759. */
  760. hasFocus: function() {
  761. return (this.tree.hasFocus() && this.tree.focusNode === this);
  762. },
  763. /** Return true if node is active (see also FancytreeNode#isSelected).
  764. * @returns {boolean}
  765. */
  766. isActive: function() {
  767. return (this.tree.activeNode === this);
  768. },
  769. /** Return true if node is a direct child of otherNode.
  770. * @param {FancytreeNode} otherNode
  771. * @returns {boolean}
  772. */
  773. isChildOf: function(otherNode) {
  774. return (this.parent && this.parent === otherNode);
  775. },
  776. /** Return true, if node is a direct or indirect sub node of otherNode.
  777. * @param {FancytreeNode} otherNode
  778. * @returns {boolean}
  779. */
  780. isDescendantOf: function(otherNode) {
  781. if(!otherNode || otherNode.tree !== this.tree){
  782. return false;
  783. }
  784. var p = this.parent;
  785. while( p ) {
  786. if( p === otherNode ){
  787. return true;
  788. }
  789. p = p.parent;
  790. }
  791. return false;
  792. },
  793. /** Return true if node is expanded.
  794. * @returns {boolean}
  795. */
  796. isExpanded: function() {
  797. return !!this.expanded;
  798. },
  799. /** Return true if node is the first node of its parent's children.
  800. * @returns {boolean}
  801. */
  802. isFirstSibling: function() {
  803. var p = this.parent;
  804. return !p || p.children[0] === this;
  805. },
  806. /** Return true if node is a folder, i.e. has the node.folder attribute set.
  807. * @returns {boolean}
  808. */
  809. isFolder: function() {
  810. return !!this.folder;
  811. },
  812. /** Return true if node is the last node of its parent's children.
  813. * @returns {boolean}
  814. */
  815. isLastSibling: function() {
  816. var p = this.parent;
  817. return !p || p.children[p.children.length-1] === this;
  818. },
  819. /** Return true if node is lazy (even if data was already loaded)
  820. * @returns {boolean}
  821. */
  822. isLazy: function() {
  823. return !!this.lazy;
  824. },
  825. /** Return true if node is lazy and loaded. For non-lazy nodes always return true.
  826. * @returns {boolean}
  827. */
  828. isLoaded: function() {
  829. return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
  830. },
  831. /** Return true if children are currently beeing loaded, i.e. a Ajax request is pending.
  832. * @returns {boolean}
  833. */
  834. isLoading: function() {
  835. return !!this._isLoading;
  836. },
  837. /** Return true if this is the (invisible) system root node.
  838. * @returns {boolean}
  839. */
  840. isRoot: function() {
  841. return (this.tree.rootNode === this);
  842. },
  843. /** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive).
  844. * @returns {boolean}
  845. */
  846. isSelected: function() {
  847. return !!this.selected;
  848. },
  849. /** Return true if this node is a temporarily generated system node like
  850. * 'loading', or 'error' (node.statusNodeType contains the type).
  851. * @returns {boolean}
  852. */
  853. isStatusNode: function() {
  854. return !!this.statusNodeType;
  855. },
  856. /** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false.
  857. * @returns {boolean}
  858. */
  859. isUndefined: function() {
  860. return this.hasChildren() === undefined; // also checks if the only child is a status node
  861. },
  862. /** Return true if all parent nodes are expanded. Note: this does not check
  863. * whether the node is scrolled into the visible part of the screen.
  864. * @returns {boolean}
  865. */
  866. isVisible: function() {
  867. var i, l,
  868. parents = this.getParentList(false, false);
  869. for(i=0, l=parents.length; i<l; i++){
  870. if( ! parents[i].expanded ){ return false; }
  871. }
  872. return true;
  873. },
  874. /** Deprecated.
  875. * @deprecated since 2014-02-16: use load() instead.
  876. */
  877. lazyLoad: function(discard) {
  878. this.warn("FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead.");
  879. return this.load(discard);
  880. },
  881. /**
  882. * Load all children of a lazy node.
  883. * @param {boolean} [forceReload=false] Pass true to discard any existing nodes before.
  884. * @returns {$.Promise}
  885. */
  886. load: function(forceReload) {
  887. var res, source;
  888. _assert( this.isLazy(), "load() requires a lazy node" );
  889. _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" );
  890. if( forceReload && this.isLoaded() ){
  891. this.resetLazy();
  892. }
  893. // This method is also called by setExpanded() and loadKeyPath(), so we
  894. // have to avoid recursion.
  895. source = this.tree._triggerNodeEvent("lazyLoad", this);
  896. _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
  897. res = this.tree._callHook("nodeLoadChildren", this, source);
  898. return res;
  899. },
  900. /** Expand all parents and optionally scroll into visible area as neccessary.
  901. * Promise is resolved, when lazy loading and animations are done.
  902. * @param {object} [opts] passed to `setExpanded()`.
  903. * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
  904. * @returns {$.Promise}
  905. */
  906. makeVisible: function(opts) {
  907. var i,
  908. that = this,
  909. deferreds = [],
  910. dfd = new $.Deferred(),
  911. parents = this.getParentList(false, false),
  912. len = parents.length,
  913. effects = !(opts && opts.noAnimation === true),
  914. scroll = !(opts && opts.scrollIntoView === false);
  915. // Expand bottom-up, so only the top node is animated
  916. for(i = len - 1; i >= 0; i--){
  917. // that.debug("pushexpand" + parents[i]);
  918. deferreds.push(parents[i].setExpanded(true, opts));
  919. }
  920. $.when.apply($, deferreds).done(function(){
  921. // All expands have finished
  922. // that.debug("expand DONE", scroll);
  923. if( scroll ){
  924. that.scrollIntoView(effects).done(function(){
  925. // that.debug("scroll DONE");
  926. dfd.resolve();
  927. });
  928. } else {
  929. dfd.resolve();
  930. }
  931. });
  932. return dfd.promise();
  933. },
  934. /** Move this node to targetNode.
  935. * @param {FancytreeNode} targetNode
  936. * @param {string} mode <pre>
  937. * 'child': append this node as last child of targetNode.
  938. * This is the default. To be compatble with the D'n'd
  939. * hitMode, we also accept 'over'.
  940. * 'before': add this node as sibling before targetNode.
  941. * 'after': add this node as sibling after targetNode.</pre>
  942. * @param {function} [map] optional callback(FancytreeNode) to allow modifcations
  943. */
  944. moveTo: function(targetNode, mode, map) {
  945. if(mode === undefined || mode === "over"){
  946. mode = "child";
  947. }
  948. var pos,
  949. prevParent = this.parent,
  950. targetParent = (mode === "child") ? targetNode : targetNode.parent;
  951. if(this === targetNode){
  952. return;
  953. }else if( !this.parent ){
  954. throw "Cannot move system root";
  955. }else if( targetParent.isDescendantOf(this) ){
  956. throw "Cannot move a node to its own descendant";
  957. }
  958. // Unlink this node from current parent
  959. if( this.parent.children.length === 1 ) {
  960. this.parent.children = this.parent.lazy ? [] : null;
  961. this.parent.expanded = false;
  962. } else {
  963. pos = $.inArray(this, this.parent.children);
  964. _assert(pos >= 0);
  965. this.parent.children.splice(pos, 1);
  966. }
  967. // Remove from source DOM parent
  968. // if(this.parent.ul){
  969. // this.parent.ul.removeChild(this.li);
  970. // }
  971. // Insert this node to target parent's child list
  972. this.parent = targetParent;
  973. if( targetParent.hasChildren() ) {
  974. switch(mode) {
  975. case "child":
  976. // Append to existing target children
  977. targetParent.children.push(this);
  978. break;
  979. case "before":
  980. // Insert this node before target node
  981. pos = $.inArray(targetNode, targetParent.children);
  982. _assert(pos >= 0);
  983. targetParent.children.splice(pos, 0, this);
  984. break;
  985. case "after":
  986. // Insert this node after target node
  987. pos = $.inArray(targetNode, targetParent.children);
  988. _assert(pos >= 0);
  989. targetParent.children.splice(pos+1, 0, this);
  990. break;
  991. default:
  992. throw "Invalid mode " + mode;
  993. }
  994. } else {
  995. targetParent.children = [ this ];
  996. }
  997. // Parent has no <ul> tag yet:
  998. // if( !targetParent.ul ) {
  999. // // This is the parent's first child: create UL tag
  1000. // // (Hidden, because it will be
  1001. // targetParent.ul = document.createElement("ul");
  1002. // targetParent.ul.style.display = "none";
  1003. // targetParent.li.appendChild(targetParent.ul);
  1004. // }
  1005. // // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
  1006. // if(this.li){
  1007. // targetParent.ul.appendChild(this.li);
  1008. // }^
  1009. // Let caller modify the nodes
  1010. if( map ){
  1011. targetNode.visit(map, true);
  1012. }
  1013. // Handle cross-tree moves
  1014. if( this.tree !== targetNode.tree ) {
  1015. // Fix node.tree for all source nodes
  1016. // _assert(false, "Cross-tree move is not yet implemented.");
  1017. this.warn("Cross-tree moveTo is experimantal!");
  1018. this.visit(function(n){
  1019. // TODO: fix selection state and activation, ...
  1020. n.tree = targetNode.tree;
  1021. }, true);
  1022. }
  1023. // A collaposed node won't re-render children, so we have to remove it manually
  1024. // if( !targetParent.expanded ){
  1025. // prevParent.ul.removeChild(this.li);
  1026. // }
  1027. // Update HTML markup
  1028. if( !prevParent.isDescendantOf(targetParent)) {
  1029. prevParent.render();
  1030. }
  1031. if( !targetParent.isDescendantOf(prevParent) && targetParent !== prevParent) {
  1032. targetParent.render();
  1033. }
  1034. // TODO: fix selection state
  1035. // TODO: fix active state
  1036. /*
  1037. var tree = this.tree;
  1038. var opts = tree.options;
  1039. var pers = tree.persistence;
  1040. // Always expand, if it's below minExpandLevel
  1041. // tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel());
  1042. if ( opts.minExpandLevel >= ftnode.getLevel() ) {
  1043. // tree.logDebug ("Force expand for %o", ftnode);
  1044. this.bExpanded = true;
  1045. }
  1046. // In multi-hier mode, update the parents selection state
  1047. // issue #82: only if not initializing, because the children may not exist yet
  1048. // if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing )
  1049. // ftnode._fixSelectionState();
  1050. // In multi-hier mode, update the parents selection state
  1051. if( ftnode.bSelected && opts.selectMode==3 ) {
  1052. var p = this;
  1053. while( p ) {
  1054. if( !p.hasSubSel )
  1055. p._setSubSel(true);
  1056. p = p.parent;
  1057. }
  1058. }
  1059. // render this node and the new child
  1060. if ( tree.bEnableUpdate )
  1061. this.render();
  1062. return ftnode;
  1063. */
  1064. },
  1065. /** Set focus relative to this node and optionally activate.
  1066. *
  1067. * @param {number} where The keyCode that would normally trigger this move,
  1068. * e.g. `$.ui.keyCode.LEFT` would collapse the node if it
  1069. * is expanded or move to the parent oterwise.
  1070. * @param {boolean} [activate=true]
  1071. * @returns {$.Promise}
  1072. */
  1073. navigate: function(where, activate) {
  1074. var i, parents,
  1075. handled = true,
  1076. KC = $.ui.keyCode,
  1077. sib = null;
  1078. // Navigate to node
  1079. function _goto(n){
  1080. if( n ){
  1081. n.makeVisible();
  1082. // Node may still be hidden by a filter
  1083. if( ! $(n.span).is(":visible") ) {
  1084. n.debug("Navigate: skipping hidden node");
  1085. n.navigate(where, activate);
  1086. return;
  1087. }
  1088. return activate === false ? n.setFocus() : n.setActive();
  1089. }
  1090. }
  1091. switch( where ) {
  1092. case KC.BACKSPACE:
  1093. if( this.parent && this.parent.parent ) {
  1094. _goto(this.parent);
  1095. }
  1096. break;
  1097. case KC.LEFT:
  1098. if( this.expanded ) {
  1099. this.setExpanded(false);
  1100. _goto(this);
  1101. } else if( this.parent && this.parent.parent ) {
  1102. _goto(this.parent);
  1103. }
  1104. break;
  1105. case KC.RIGHT:
  1106. if( !this.expanded && (this.children || this.lazy) ) {
  1107. this.setExpanded();
  1108. _goto(this);
  1109. } else if( this.children && this.children.length ) {
  1110. _goto(this.children[0]);
  1111. }
  1112. break;
  1113. case KC.UP:
  1114. sib = this.getPrevSibling();
  1115. while( sib && sib.expanded && sib.children && sib.children.length ){
  1116. sib = sib.children[sib.children.length - 1];
  1117. }
  1118. if( !sib && this.parent && this.parent.parent ){
  1119. sib = this.parent;
  1120. }
  1121. _goto(sib);
  1122. break;
  1123. case KC.DOWN:
  1124. if( this.expanded && this.children && this.children.length ) {
  1125. sib = this.children[0];
  1126. } else {
  1127. parents = this.getParentList(false, true);
  1128. for(i=parents.length-1; i>=0; i--) {
  1129. sib = parents[i].getNextSibling();
  1130. if( sib ){ break; }
  1131. }
  1132. }
  1133. _goto(sib);
  1134. break;
  1135. default:
  1136. handled = false;
  1137. }
  1138. },
  1139. /**
  1140. * Remove this node (not allowed for system root).
  1141. */
  1142. remove: function() {
  1143. return this.parent.removeChild(this);
  1144. },
  1145. /**
  1146. * Remove childNode from list of direct children.
  1147. * @param {FancytreeNode} childNode
  1148. */
  1149. removeChild: function(childNode) {
  1150. return this.tree._callHook("nodeRemoveChild", this, childNode);
  1151. },
  1152. /**
  1153. * Remove all child nodes and descendents. This converts the node into a leaf.<br>
  1154. * If this was a lazy node, it is still considered 'loaded'; call node.resetLazy()
  1155. * in order to trigger lazyLoad on next expand.
  1156. */
  1157. removeChildren: function() {
  1158. return this.tree._callHook("nodeRemoveChildren", this);
  1159. },
  1160. /**
  1161. * This method renders and updates all HTML markup that is required
  1162. * to display this node in its current state.<br>
  1163. * Note:
  1164. * <ul>
  1165. * <li>It should only be neccessary to call this method after the node object
  1166. * was modified by direct access to its properties, because the common
  1167. * API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...)
  1168. * already handle this.
  1169. * <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus}
  1170. * are implied. If changes are more local, calling only renderTitle() or
  1171. * renderStatus() may be sufficient and faster.
  1172. * <li>If a node was created/removed, node.render() must be called <i>on the parent</i>.
  1173. * </ul>
  1174. *
  1175. * @param {boolean} [force=false] re-render, even if html markup was already created
  1176. * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
  1177. */
  1178. render: function(force, deep) {
  1179. return this.tree._callHook("nodeRender", this, force, deep);
  1180. },
  1181. /** Create HTML markup for the node's outer <span> (expander, checkbox, icon, and title).
  1182. * @see Fancytree_Hooks#nodeRenderTitle
  1183. */
  1184. renderTitle: function() {
  1185. return this.tree._callHook("nodeRenderTitle", this);
  1186. },
  1187. /** Update element's CSS classes according to node state.
  1188. * @see Fancytree_Hooks#nodeRenderStatus
  1189. */
  1190. renderStatus: function() {
  1191. return this.tree._callHook("nodeRenderStatus", this);
  1192. },
  1193. /**
  1194. * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
  1195. * event is triggered on next expand.
  1196. */
  1197. resetLazy: function() {
  1198. this.removeChildren(); // also collapses
  1199. this.lazy = true;
  1200. this.children = undefined;
  1201. this.renderStatus();
  1202. },
  1203. /** Schedule activity for delayed execution (cancel any pending request).
  1204. * scheduleAction('cancel') will only cancel a pending request (if any).
  1205. * @param {string} mode
  1206. * @param {number} ms
  1207. */
  1208. scheduleAction: function(mode, ms) {
  1209. if( this.tree.timer ) {
  1210. clearTimeout(this.tree.timer);
  1211. // this.tree.debug("clearTimeout(%o)", this.tree.timer);
  1212. }
  1213. this.tree.timer = null;
  1214. var self = this; // required for closures
  1215. switch (mode) {
  1216. case "cancel":
  1217. // Simply made sure that timer was cleared
  1218. break;
  1219. case "expand":
  1220. this.tree.timer = setTimeout(function(){
  1221. self.tree.debug("setTimeout: trigger expand");
  1222. self.setExpanded(true);
  1223. }, ms);
  1224. break;
  1225. case "activate":
  1226. this.tree.timer = setTimeout(function(){
  1227. self.tree.debug("setTimeout: trigger activate");
  1228. self.setActive(true);
  1229. }, ms);
  1230. break;
  1231. default:
  1232. throw "Invalid mode " + mode;
  1233. }
  1234. // this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
  1235. },
  1236. /**
  1237. *
  1238. * @param {boolean | PlainObject} [effects=false] animation options.
  1239. * @param {FancytreeNode} [topNode=null] this node will remain visible in
  1240. * any case, even if `this` is outside the scroll pane.
  1241. * @returns {$.Promise}
  1242. */
  1243. scrollIntoView: function(effects, topNode) {
  1244. effects = (effects === true) ? {duration: 200, queue: false} : effects;
  1245. var topNodeY,
  1246. dfd = new $.Deferred(),
  1247. that = this,
  1248. nodeY = $(this.span).position().top,
  1249. nodeHeight = $(this.span).height(),
  1250. $container = this.tree.$container,
  1251. scrollTop = $container[0].scrollTop,
  1252. horzScrollHeight = Math.max(0, ($container.innerHeight() - $container[0].clientHeight)),
  1253. // containerHeight = $container.height(),
  1254. containerHeight = $container.height() - horzScrollHeight,
  1255. newScrollTop = null;
  1256. // console.log("horzScrollHeight: " + horzScrollHeight);
  1257. // console.log("$container[0].scrollTop: " + $container[0].scrollTop);
  1258. // console.log("$container[0].scrollHeight: " + $container[0].scrollHeight);
  1259. // console.log("$container[0].clientHeight: " + $container[0].clientHeight);
  1260. // console.log("$container.innerHeight(): " + $container.innerHeight());
  1261. // console.log("$container.height(): " + $container.height());
  1262. if(nodeY < 0){
  1263. newScrollTop = scrollTop + nodeY;
  1264. }else if((nodeY + nodeHeight) > containerHeight){
  1265. newScrollTop = scrollTop + nodeY - containerHeight + nodeHeight;
  1266. // If a topNode was passed, make sure that it is never scrolled
  1267. // outside the upper border
  1268. if(topNode){
  1269. topNodeY = topNode ? $(topNode.span).position().top : 0;
  1270. if((nodeY - topNodeY) > containerHeight){
  1271. newScrollTop = scrollTop + topNodeY;
  1272. }
  1273. }
  1274. }
  1275. if(newScrollTop !== null){
  1276. if(effects){
  1277. // TODO: resolve dfd after animation
  1278. // var that = this;
  1279. effects.complete = function(){
  1280. dfd.resolveWith(that);
  1281. };
  1282. $container.animate({
  1283. scrollTop: newScrollTop
  1284. }, effects);
  1285. }else{
  1286. $container[0].scrollTop = newScrollTop;
  1287. dfd.resolveWith(this);
  1288. }
  1289. }else{
  1290. dfd.resolveWith(this);
  1291. }
  1292. return dfd.promise();
  1293. /* from jQuery.menu:
  1294. var borderTop, paddingTop, offset, scroll, elementHeight, itemHeight;
  1295. if ( this._hasScroll() ) {
  1296. borderTop = parseFloat( $.css( this.activeMenu[0], "borderTopWidth" ) ) || 0;
  1297. paddingTop = parseFloat( $.css( this.activeMenu[0], "paddingTop" ) ) || 0;
  1298. offset = item.offset().top - this.activeMenu.offset().top - borderTop - paddingTop;
  1299. scroll = this.activeMenu.scrollTop();
  1300. elementHeight = this.activeMenu.height();
  1301. itemHeight = item.height();
  1302. if ( offset < 0 ) {
  1303. this.activeMenu.scrollTop( scroll + offset );
  1304. } else if ( offset + itemHeight > elementHeight ) {
  1305. this.activeMenu.scrollTop( scroll + offset - elementHeight + itemHeight );
  1306. }
  1307. }
  1308. */
  1309. },
  1310. /**Activate this node.
  1311. * @param {boolean} [flag=true] pass false to deactivate
  1312. * @param {object} [opts] additional options. Defaults to {noEvents: false}
  1313. */
  1314. setActive: function(flag, opts){
  1315. return this.tree._callHook("nodeSetActive", this, flag, opts);
  1316. },
  1317. /**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done.
  1318. * @param {boolean} [flag=true] pass false to collapse
  1319. * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
  1320. * @returns {$.Promise}
  1321. */
  1322. setExpanded: function(flag, opts){
  1323. return this.tree._callHook("nodeSetExpanded", this, flag, opts);
  1324. },
  1325. /**Set keyboard focus to this node.
  1326. * @param {boolean} [flag=true] pass false to blur
  1327. * @see Fancytree#setFocus
  1328. */
  1329. setFocus: function(flag){
  1330. return this.tree._callHook("nodeSetFocus", this, flag);
  1331. },
  1332. // TODO: setLazyNodeStatus
  1333. /**Select this node, i.e. check the checkbox.
  1334. * @param {boolean} [flag=true] pass false to deselect
  1335. */
  1336. setSelected: function(flag){
  1337. return this.tree._callHook("nodeSetSelected", this, flag);
  1338. },
  1339. /**Rename this node.
  1340. * @param {string} title
  1341. */
  1342. setTitle: function(title){
  1343. this.title = title;
  1344. this.renderTitle();
  1345. },
  1346. /**Sort child list by title.
  1347. * @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title).
  1348. * @param {boolean} [deep=false] pass true to sort all descendant nodes
  1349. */
  1350. sortChildren: function(cmp, deep) {
  1351. var i,l,
  1352. cl = this.children;
  1353. if( !cl ){
  1354. return;
  1355. }
  1356. cmp = cmp || function(a, b) {
  1357. var x = a.title.toLowerCase(),
  1358. y = b.title.toLowerCase();
  1359. return x === y ? 0 : x > y ? 1 : -1;
  1360. };
  1361. cl.sort(cmp);
  1362. if( deep ){
  1363. for(i=0, l=cl.length; i<l; i++){
  1364. if( cl[i].children ){
  1365. cl[i].sortChildren(cmp, "$norender$");
  1366. }
  1367. }
  1368. }
  1369. if( deep !== "$norender$" ){
  1370. this.render();
  1371. }
  1372. },
  1373. /** Convert node (or whole branch) into a plain object.
  1374. *
  1375. * The result is compatible with node.addChildren().
  1376. *
  1377. * @param {boolean} recursive
  1378. * @param {function} callback callback(dict) is called for every node, in order to allow modifications
  1379. * @returns {NodeData}
  1380. */
  1381. toDict: function(recursive, callback) {
  1382. var i, l, node,
  1383. dict = {},
  1384. self = this;
  1385. $.each(NODE_ATTRS, function(i, a){
  1386. if(self[a] || self[a] === false){
  1387. dict[a] = self[a];
  1388. }
  1389. });
  1390. if(!$.isEmptyObject(this.data)){
  1391. dict.data = $.extend({}, this.data);
  1392. if($.isEmptyObject(dict.data)){
  1393. delete dict.data;
  1394. }
  1395. }
  1396. if( callback ){
  1397. callback(dict);
  1398. }
  1399. if( recursive ) {
  1400. if(this.hasChildren()){
  1401. dict.children = [];
  1402. for(i=0, l=this.children.length; i<l; i++ ){
  1403. node = this.children[i];
  1404. if( !node.isStatusNode() ){
  1405. dict.children.push(node.toDict(true, callback));
  1406. }
  1407. }
  1408. }else{
  1409. // dict.children = null;
  1410. }
  1411. }
  1412. return dict;
  1413. },
  1414. /** Flip expanded status. */
  1415. toggleExpanded: function(){
  1416. return this.tree._callHook("nodeToggleExpanded", this);
  1417. },
  1418. /** Flip selection status. */
  1419. toggleSelected: function(){
  1420. return this.tree._callHook("nodeToggleSelected", this);
  1421. },
  1422. toString: function() {
  1423. return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>";
  1424. },
  1425. /** Call fn(node) for all child nodes.<br>
  1426. * Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br>
  1427. * Return false if iteration was stopped.
  1428. *
  1429. * @param {function} fn the callback function.
  1430. * Return false to stop iteration, return "skip" to skip this node and children only.
  1431. * @param {boolean} [includeSelf=false]
  1432. * @returns {boolean}
  1433. */
  1434. visit: function(fn, includeSelf) {
  1435. var i, l,
  1436. res = true,
  1437. children = this.children;
  1438. if( includeSelf === true ) {
  1439. res = fn(this);
  1440. if( res === false || res === "skip" ){
  1441. return res;
  1442. }
  1443. }
  1444. if(children){
  1445. for(i=0, l=children.length; i<l; i++){
  1446. res = children[i].visit(fn, true);
  1447. if( res === false ){
  1448. break;
  1449. }
  1450. }
  1451. }
  1452. return res;
  1453. },
  1454. /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
  1455. * Stop iteration, if fn() returns false.<br>
  1456. * Return false if iteration was stopped.
  1457. *
  1458. * @param {function} fn the callback function.
  1459. * Return false to stop iteration, return "skip" to skip this node and children only.
  1460. * @param {boolean} [includeSelf=false]
  1461. * @returns {boolean}
  1462. */
  1463. visitParents: function(fn, includeSelf) {
  1464. // Visit parent nodes (bottom up)
  1465. if(includeSelf && fn(this) === false){
  1466. return false;
  1467. }
  1468. var p = this.parent;
  1469. while( p ) {
  1470. if(fn(p) === false){
  1471. return false;
  1472. }
  1473. p = p.parent;
  1474. }
  1475. return true;
  1476. },
  1477. /** Write warning to browser console (prepending node info)
  1478. *
  1479. * @param {*} msg string or object or array of such
  1480. */
  1481. warn: function(msg){
  1482. Array.prototype.unshift.call(arguments, this.toString());
  1483. consoleApply("warn", arguments);
  1484. }
  1485. };
  1486. /* *****************************************************************************
  1487. * Fancytree
  1488. */
  1489. /**
  1490. * Construct a new tree object.
  1491. *
  1492. * @class Fancytree
  1493. * @classdesc A Fancytree is the controller behind a fancytree.
  1494. * This class also contains 'hook methods': see {@link Fancytree_Hooks}.
  1495. *
  1496. * @param {Widget} widget
  1497. *
  1498. * @property {FancytreeOptions} options
  1499. * @property {FancytreeNode} rootNode
  1500. * @property {FancytreeNode} activeNode
  1501. * @property {FancytreeNode} focusNode
  1502. * @property {jQueryObject} $div
  1503. * @property {object} widget
  1504. * @property {object} ext
  1505. * @property {object} data
  1506. * @property {object} options
  1507. * @property {string} _id
  1508. * @property {string} statusClassPropName
  1509. * @property {string} ariaPropName
  1510. * @property {string} nodeContainerAttrName
  1511. * @property {string} $container
  1512. * @property {FancytreeNode} lastSelectedNode
  1513. */
  1514. function Fancytree(widget) {
  1515. this.widget = widget;
  1516. this.$div = widget.element;
  1517. this.options = widget.options;
  1518. if( this.options && $.isFunction(this.options.lazyload) ) {
  1519. if( ! $.isFunction(this.options.lazyLoad ) ) {
  1520. this.options.lazyLoad = function() {
  1521. FT.warn("The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead.");
  1522. widget.options.lazyload.apply(this, arguments);
  1523. };
  1524. }
  1525. }
  1526. this.ext = {}; // Active extension instances
  1527. this.data = {};
  1528. this._id = $.ui.fancytree._nextId++;
  1529. this._ns = ".fancytree-" + this._id; // append for namespaced events
  1530. this.activeNode = null;
  1531. this.focusNode = null;
  1532. this._hasFocus = null;
  1533. this.lastSelectedNode = null;
  1534. this.systemFocusElement = null,
  1535. this.statusClassPropName = "span";
  1536. this.ariaPropName = "li";
  1537. this.nodeContainerAttrName = "li";
  1538. // Remove previous markup if any
  1539. this.$div.find(">ul.fancytree-container").remove();
  1540. // Create a node without parent.
  1541. var fakeParent = { tree: this },
  1542. $ul;
  1543. this.rootNode = new FancytreeNode(fakeParent, {
  1544. title: "root",
  1545. key: "root_" + this._id,
  1546. children: null,
  1547. expanded: true
  1548. });
  1549. this.rootNode.parent = null;
  1550. // Create root markup
  1551. $ul = $("<ul>", {
  1552. "class": "ui-fancytree fancytree-container"
  1553. }).appendTo(this.$div);
  1554. this.$container = $ul;
  1555. this.rootNode.ul = $ul[0];
  1556. if(this.options.debugLevel == null){
  1557. this.options.debugLevel = FT.debugLevel;
  1558. }
  1559. // Add container to the TAB chain
  1560. // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
  1561. this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
  1562. if(this.options.aria){
  1563. this.$container
  1564. .attr("role", "tree")
  1565. .attr("aria-multiselectable", true);
  1566. }
  1567. }
  1568. Fancytree.prototype = /** @lends Fancytree# */{
  1569. /* Return a context object that can be re-used for _callHook().
  1570. * @param {Fancytree | FancytreeNode | EventData} obj
  1571. * @param {Event} originalEvent
  1572. * @param {Object} extra
  1573. * @returns {EventData}
  1574. */
  1575. _makeHookContext: function(obj, originalEvent, extra) {
  1576. var ctx, tree;
  1577. if(obj.node !== undefined){
  1578. // obj is already a context object
  1579. if(originalEvent && obj.originalEvent !== originalEvent){
  1580. $.error("invalid args");
  1581. }
  1582. ctx = obj;
  1583. }else if(obj.tree){
  1584. // obj is a FancytreeNode
  1585. tree = obj.tree;
  1586. ctx = { node: obj, tree: tree, widget: tree.widget, options: tree.widget.options, originalEvent: originalEvent };
  1587. }else if(obj.widget){
  1588. // obj is a Fancytree
  1589. ctx = { node: null, tree: obj, widget: obj.widget, options: obj.widget.options, originalEvent: originalEvent };
  1590. }else{
  1591. $.error("invalid args");
  1592. }
  1593. if(extra){
  1594. $.extend(ctx, extra);
  1595. }
  1596. return ctx;
  1597. },
  1598. /* Trigger a hook function: funcName(ctx, [...]).
  1599. *
  1600. * @param {string} funcName
  1601. * @param {Fancytree|FancytreeNode|EventData} contextObject
  1602. * @param {any} [_extraArgs] optional additional arguments
  1603. * @returns {any}
  1604. */
  1605. _callHook: function(funcName, contextObject, _extraArgs) {
  1606. var ctx = this._makeHookContext(contextObject),
  1607. fn = this[funcName],
  1608. args = Array.prototype.slice.call(arguments, 2);
  1609. if(!$.isFunction(fn)){
  1610. $.error("_callHook('" + funcName + "') is not a function");
  1611. }
  1612. args.unshift(ctx);
  1613. // this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
  1614. return fn.apply(this, args);
  1615. },
  1616. /* Check if current extensions dependencies are met and throw an error if not.
  1617. *
  1618. * This method may be called inside the `treeInit` hook for custom extensions.
  1619. *
  1620. * @param {string} extension name of the required extension
  1621. * @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present
  1622. * @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter)
  1623. * @param {string} [message] optional error message (defaults to a descriptve error message)
  1624. */
  1625. _requireExtension: function(name, required, before, message) {
  1626. before = !!before;
  1627. var thisName = this._local.name,
  1628. extList = this.options.extensions,
  1629. isBefore = $.inArray(name, extList) < $.inArray(thisName, extList),
  1630. isMissing = required && this.ext[name] == null,
  1631. badOrder = !isMissing && before != null && (before !== isBefore);
  1632. _assert(thisName && thisName !== name);
  1633. if( isMissing || badOrder ){
  1634. if( !message ){
  1635. if( isMissing || required ){
  1636. message = "'" + thisName + "' extension requires '" + name + "'";
  1637. if( badOrder ){
  1638. message += " to be registered " + (before ? "before" : "after") + " itself";
  1639. }
  1640. }else{
  1641. message = "If used together, `" + name + "` must be registered " + (before ? "before" : "after") + " `" + thisName + "`";
  1642. }
  1643. }
  1644. $.error(message);
  1645. return false;
  1646. }
  1647. return true;
  1648. },
  1649. /** Activate node with a given key and fire focus and activate events.
  1650. *
  1651. * A prevously activated node will be deactivated.
  1652. * If activeVisible option is set, all parents will be expanded as necessary.
  1653. * Pass key = false, to deactivate the current node only.
  1654. * @param {string} key
  1655. * @returns {FancytreeNode} activated node (null, if not found)
  1656. */
  1657. activateKey: function(key) {
  1658. var node = this.getNodeByKey(key);
  1659. if(node){
  1660. node.setActive();
  1661. }else if(this.activeNode){
  1662. this.activeNode.setActive(false);
  1663. }
  1664. return node;
  1665. },
  1666. /** (experimental)
  1667. *
  1668. * @param {Array} patchList array of [key, NodePatch] arrays
  1669. * @returns {$.Promise} resolved, when all patches have been applied
  1670. * @see TreePatch
  1671. */
  1672. applyPatch: function(patchList) {
  1673. var dfd, i, p2, key, patch, node,
  1674. patchCount = patchList.length,
  1675. deferredList = [];
  1676. for(i=0; i<patchCount; i++){
  1677. p2 = patchList[i];
  1678. _assert(p2.length === 2, "patchList must be an array of length-2-arrays");
  1679. key = p2[0];
  1680. patch = p2[1];
  1681. node = (key === null) ? this.rootNode : this.getNodeByKey(key);
  1682. if(node){
  1683. dfd = new $.Deferred();
  1684. deferredList.push(dfd);
  1685. node.applyPatch(patch).always(_makeResolveFunc(dfd, node));
  1686. }else{
  1687. this.warn("could not find node with key '" + key + "'");
  1688. }
  1689. }
  1690. // Return a promise that is resovled, when ALL patches were applied
  1691. return $.when.apply($, deferredList).promise();
  1692. },
  1693. /* TODO: implement in dnd extension
  1694. cancelDrag: function() {
  1695. var dd = $.ui.ddmanager.current;
  1696. if(dd){
  1697. dd.cancel();
  1698. }
  1699. },
  1700. */
  1701. /** Return the number of nodes.
  1702. * @returns {integer}
  1703. */
  1704. count: function() {
  1705. return this.rootNode.countChildren();
  1706. },
  1707. /** Write to browser console if debugLevel >= 2 (prepending tree name)
  1708. *
  1709. * @param {*} msg string or object or array of such
  1710. */
  1711. debug: function(msg){
  1712. if( this.options.debugLevel >= 2 ) {
  1713. Array.prototype.unshift.call(arguments, this.toString());
  1714. consoleApply("debug", arguments);
  1715. }
  1716. },
  1717. // TODO: disable()
  1718. // TODO: enable()
  1719. // TODO: enableUpdate()
  1720. // TODO: fromDict
  1721. /**
  1722. * Generate INPUT elements that can be submitted with html forms.
  1723. *
  1724. * In selectMode 3 only the topmost selected nodes are considered.
  1725. *
  1726. * @param {boolean | string} [selected=true]
  1727. * @param {boolean | string} [active=true]
  1728. */
  1729. generateFormElements: function(selected, active) {
  1730. // TODO: test case
  1731. var nodeList,
  1732. selectedName = (selected !== false) ? "ft_" + this._id : selected,
  1733. activeName = (active !== false) ? "ft_" + this._id + "_active" : active,
  1734. id = "fancytree_result_" + this._id,
  1735. $result = this.$container.find("div#" + id);
  1736. if($result.length){
  1737. $result.empty();
  1738. }else{
  1739. $result = $("<div>", {
  1740. id: id
  1741. }).hide().appendTo(this.$container);
  1742. }
  1743. if(selectedName){
  1744. nodeList = this.getSelectedNodes( this.options.selectMode === 3 );
  1745. $.each(nodeList, function(idx, node){
  1746. $result.append($("<input>", {
  1747. type: "checkbox",
  1748. name: selectedName,
  1749. value: node.key,
  1750. checked: true
  1751. }));
  1752. });
  1753. }
  1754. if(activeName && this.activeNode){
  1755. $result.append($("<input>", {
  1756. type: "radio",
  1757. name: activeName,
  1758. value: this.activeNode.key,
  1759. checked: true
  1760. }));
  1761. }
  1762. },
  1763. /**
  1764. * Return the currently active node or null.
  1765. * @returns {FancytreeNode}
  1766. */
  1767. getActiveNode: function() {
  1768. return this.activeNode;
  1769. },
  1770. /** Return the first top level node if any (not the invisible root node).
  1771. * @returns {FancytreeNode | null}
  1772. */
  1773. getFirstChild: function() {
  1774. return this.rootNode.getFirstChild();
  1775. },
  1776. /**
  1777. * Return node that has keyboard focus.
  1778. * @param {boolean} [ifTreeHasFocus=false] (not yet implemented)
  1779. * @returns {FancytreeNode}
  1780. */
  1781. getFocusNode: function(ifTreeHasFocus) {
  1782. // TODO: implement ifTreeHasFocus
  1783. return this.focusNode;
  1784. },
  1785. /**
  1786. * Return node with a given key or null if not found.
  1787. * @param {string} key
  1788. * @param {FancytreeNode} [searchRoot] only search below this node
  1789. * @returns {FancytreeNode | null}
  1790. */
  1791. getNodeByKey: function(key, searchRoot) {
  1792. // Search the DOM by element ID (assuming this is faster than traversing all nodes).
  1793. // $("#...") has problems, if the key contains '.', so we use getElementById()
  1794. var el, match;
  1795. if(!searchRoot){
  1796. el = document.getElementById(this.options.idPrefix + key);
  1797. if( el ){
  1798. return el.ftnode ? el.ftnode : null;
  1799. }
  1800. }
  1801. // Not found in the DOM, but still may be in an unrendered part of tree
  1802. // TODO: optimize with specialized loop
  1803. // TODO: consider keyMap?
  1804. searchRoot = searchRoot || this.rootNode;
  1805. match = null;
  1806. searchRoot.visit(function(node){
  1807. // window.console.log("getNodeByKey(" + key + "): ", node.key);
  1808. if(node.key === key) {
  1809. match = node;
  1810. return false;
  1811. }
  1812. }, true);
  1813. return match;
  1814. },
  1815. // TODO: getRoot()
  1816. /**
  1817. * Return an array of selected nodes.
  1818. * @param {boolean} [stopOnParents=false] only return the topmost selected
  1819. * node (useful with selectMode 3)
  1820. * @returns {FancytreeNode[]}
  1821. */
  1822. getSelectedNodes: function(stopOnParents) {
  1823. var nodeList = [];
  1824. this.rootNode.visit(function(node){
  1825. if( node.selected ) {
  1826. nodeList.push(node);
  1827. if( stopOnParents === true ){
  1828. return "skip"; // stop processing this branch
  1829. }
  1830. }
  1831. });
  1832. return nodeList;
  1833. },
  1834. /** Return true if the tree control has keyboard focus
  1835. * @returns {boolean}
  1836. */
  1837. hasFocus: function(){
  1838. return !!this._hasFocus;
  1839. },
  1840. /** Write to browser console if debugLevel >= 1 (prepending tree name)
  1841. * @param {*} msg string or object or array of such
  1842. */
  1843. info: function(msg){
  1844. if( this.options.debugLevel >= 1 ) {
  1845. Array.prototype.unshift.call(arguments, this.toString());
  1846. consoleApply("info", arguments);
  1847. }
  1848. },
  1849. /*
  1850. TODO: isInitializing: function() {
  1851. return ( this.phase=="init" || this.phase=="postInit" );
  1852. },
  1853. TODO: isReloading: function() {
  1854. return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
  1855. },
  1856. TODO: isUserEvent: function() {
  1857. return ( this.phase=="userEvent" );
  1858. },
  1859. */
  1860. /**
  1861. * Make sure that a node with a given ID is loaded, by traversing - and
  1862. * loading - its parents. This method is ment for lazy hierarchies.
  1863. * A callback is executed for every node as we go.
  1864. * @example
  1865. * tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
  1866. * if(status === "loaded") {
  1867. * console.log("loaded intermiediate node " + node);
  1868. * }else if(status === "ok") {
  1869. * node.activate();
  1870. * }
  1871. * });
  1872. *
  1873. * @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7')
  1874. * @param {function} callback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error')
  1875. * @returns {$.Promise}
  1876. */
  1877. loadKeyPath: function(keyPathList, callback, _rootNode) {
  1878. var deferredList, dfd, i, path, key, loadMap, node, segList,
  1879. root = _rootNode || this.rootNode,
  1880. sep = this.options.keyPathSeparator,
  1881. self = this;
  1882. if(!$.isArray(keyPathList)){
  1883. keyPathList = [keyPathList];
  1884. }
  1885. // Pass 1: handle all path segments for nodes that are already loaded
  1886. // Collect distinct top-most lazy nodes in a map
  1887. loadMap = {};
  1888. for(i=0; i<keyPathList.length; i++){
  1889. path = keyPathList[i];
  1890. // strip leading slash
  1891. if(path.charAt(0) === sep){
  1892. path = path.substr(1);
  1893. }
  1894. // traverse and strip keys, until we hit a lazy, unloaded node
  1895. segList = path.split(sep);
  1896. while(segList.length){
  1897. key = segList.shift();
  1898. // node = _findDirectChild(root, key);
  1899. node = root._findDirectChild(key);
  1900. if(!node){
  1901. this.warn("loadKeyPath: key not found: " + key + " (parent: " + root + ")");
  1902. callback.call(this, key, "error");
  1903. break;
  1904. }else if(segList.length === 0){
  1905. callback.call(this, node, "ok");
  1906. break;
  1907. }else if(!node.lazy || (node.hasChildren() !== undefined )){
  1908. callback.call(this, node, "loaded");
  1909. root = node;
  1910. }else{
  1911. callback.call(this, node, "loaded");
  1912. // segList.unshift(key);
  1913. if(loadMap[key]){
  1914. loadMap[key].push(segList.join(sep));
  1915. }else{
  1916. loadMap[key] = [segList.join(sep)];
  1917. }
  1918. break;
  1919. }
  1920. }
  1921. }
  1922. // alert("loadKeyPath: loadMap=" + JSON.stringify(loadMap));
  1923. // Now load all lazy nodes and continue itearation for remaining paths
  1924. deferredList = [];
  1925. // Avoid jshint warning 'Don't make functions within a loop.':
  1926. function __lazyload(key, node, dfd){
  1927. callback.call(self, node, "loading");
  1928. node.load().done(function(){
  1929. self.loadKeyPath.call(self, loadMap[key], callback, node).always(_makeResolveFunc(dfd, self));
  1930. }).fail(function(errMsg){
  1931. self.warn("loadKeyPath: error loading: " + key + " (parent: " + root + ")");
  1932. callback.call(self, node, "error");
  1933. dfd.reject();
  1934. });
  1935. }
  1936. for(key in loadMap){
  1937. node = root._findDirectChild(key);
  1938. // alert("loadKeyPath: lazy node(" + key + ") = " + node);
  1939. dfd = new $.Deferred();
  1940. deferredList.push(dfd);
  1941. __lazyload(key, node, dfd);
  1942. }
  1943. // Return a promise that is resovled, when ALL paths were loaded
  1944. return $.when.apply($, deferredList).promise();
  1945. },
  1946. /** Re-fire beforeActivate and activate events. */
  1947. reactivate: function(setFocus) {
  1948. var node = this.activeNode;
  1949. if( node ) {
  1950. this.activeNode = null; // Force re-activating
  1951. node.setActive();
  1952. if( setFocus ){
  1953. node.setFocus();
  1954. }
  1955. }
  1956. },
  1957. /** Reload tree from source and return a promise.
  1958. * @param [source] optional new source (defaults to initial source data)
  1959. * @returns {$.Promise}
  1960. */
  1961. reload: function(source) {
  1962. this._callHook("treeClear", this);
  1963. return this._callHook("treeLoad", this, source);
  1964. },
  1965. /**Render tree (i.e. create DOM elements for all top-level nodes).
  1966. * @param {boolean} [force=false] create DOM elemnts, even is parent is collapsed
  1967. * @param {boolean} [deep=false]
  1968. */
  1969. render: function(force, deep) {
  1970. return this.rootNode.render(force, deep);
  1971. },
  1972. // TODO: selectKey: function(key, select)
  1973. // TODO: serializeArray: function(stopOnParents)
  1974. /**
  1975. * @param {boolean} [flag=true]
  1976. */
  1977. setFocus: function(flag) {
  1978. return this._callHook("treeSetFocus", this, flag);
  1979. },
  1980. /**
  1981. * Return all nodes as nested list of {@link NodeData}.
  1982. *
  1983. * @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children)
  1984. * @param {function} [callback(node)] Called for every node
  1985. * @returns {Array | object}
  1986. * @see FancytreeNode#toDict
  1987. */
  1988. toDict: function(includeRoot, callback){
  1989. var res = this.rootNode.toDict(true, callback);
  1990. return includeRoot ? res : res.children;
  1991. },
  1992. /* Implicitly called for string conversions.
  1993. * @returns {string}
  1994. */
  1995. toString: function(){
  1996. return "<Fancytree(#" + this._id + ")>";
  1997. },
  1998. /* _trigger a widget event with additional node ctx.
  1999. * @see EventData
  2000. */
  2001. _triggerNodeEvent: function(type, node, originalEvent, extra) {
  2002. // this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx);
  2003. var ctx = this._makeHookContext(node, originalEvent, extra),
  2004. res = this.widget._trigger(type, originalEvent, ctx);
  2005. if(res !== false && ctx.result !== undefined){
  2006. return ctx.result;
  2007. }
  2008. return res;
  2009. },
  2010. /* _trigger a widget event with additional tree data. */
  2011. _triggerTreeEvent: function(type, originalEvent) {
  2012. // this.debug("_trigger(" + type + ")", ctx);
  2013. var ctx = this._makeHookContext(this, originalEvent),
  2014. res = this.widget._trigger(type, originalEvent, ctx);
  2015. if(res !== false && ctx.result !== undefined){
  2016. return ctx.result;
  2017. }
  2018. return res;
  2019. },
  2020. /** Call fn(node) for all nodes.
  2021. *
  2022. * @param {function} fn the callback function.
  2023. * Return false to stop iteration, return "skip" to skip this node and children only.
  2024. * @returns {boolean} false, if the iterator was stopped.
  2025. */
  2026. visit: function(fn) {
  2027. return this.rootNode.visit(fn, false);
  2028. },
  2029. /** Write warning to browser console (prepending tree info)
  2030. *
  2031. * @param {*} msg string or object or array of such
  2032. */
  2033. warn: function(msg){
  2034. Array.prototype.unshift.call(arguments, this.toString());
  2035. consoleApply("warn", arguments);
  2036. }
  2037. };
  2038. /**
  2039. * These additional methods of the {@link Fancytree} class are 'hook functions'
  2040. * that can be used and overloaded by extensions.
  2041. * (See <a href="https://github.com/mar10/fancytree/wiki/TutorialExtensions">writing extensions</a>.)
  2042. * @mixin Fancytree_Hooks
  2043. */
  2044. $.extend(Fancytree.prototype,
  2045. /** @lends Fancytree_Hooks# */
  2046. {
  2047. /** _Default handling for mouse click events. */
  2048. nodeClick: function(ctx) {
  2049. // this.tree.logDebug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which);
  2050. var activate, expand,
  2051. event = ctx.originalEvent,
  2052. targetType = ctx.targetType,
  2053. node = ctx.node;
  2054. // TODO: use switch
  2055. // TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
  2056. if( targetType === "expander" ) {
  2057. // Clicking the expander icon always expands/collapses
  2058. this._callHook("nodeToggleExpanded", ctx);
  2059. // this._callHook("nodeSetFocus", ctx, true); // issue 95
  2060. } else if( targetType === "checkbox" ) {
  2061. // Clicking the checkbox always (de)selects
  2062. this._callHook("nodeToggleSelected", ctx);
  2063. this._callHook("nodeSetFocus", ctx, true); // issue 95
  2064. } else {
  2065. // Honor `clickFolderMode` for
  2066. expand = false;
  2067. activate = true;
  2068. if( node.folder ) {
  2069. switch( ctx.options.clickFolderMode ) {
  2070. case 2: // expand only
  2071. expand = true;
  2072. activate = false;
  2073. break;
  2074. case 3: // expand and activate
  2075. activate = true;
  2076. expand = true; //!node.isExpanded();
  2077. break;
  2078. // else 1 or 4: just activate
  2079. }
  2080. }
  2081. if( activate ) {
  2082. this.nodeSetFocus(ctx);
  2083. this._callHook("nodeSetActive", ctx, true);
  2084. }
  2085. if( expand ) {
  2086. if(!activate){
  2087. // this._callHook("nodeSetFocus", ctx);
  2088. }
  2089. // this._callHook("nodeSetExpanded", ctx, true);
  2090. this._callHook("nodeToggleExpanded", ctx);
  2091. }
  2092. }
  2093. // Make sure that clicks stop, otherwise <a href='#'> jumps to the top
  2094. if(event.target.localName === "a" && event.target.className === "fancytree-title"){
  2095. event.preventDefault();
  2096. }
  2097. // TODO: return promise?
  2098. },
  2099. nodeCollapseSiblings: function(ctx, callOpts) {
  2100. // TODO: return promise?
  2101. var ac, i, l,
  2102. node = ctx.node;
  2103. if( node.parent ){
  2104. ac = node.parent.children;
  2105. for (i=0, l=ac.length; i<l; i++) {
  2106. if ( ac[i] !== node && ac[i].expanded ){
  2107. this._callHook("nodeSetExpanded", ac[i], false, callOpts);
  2108. }
  2109. }
  2110. }
  2111. },
  2112. nodeDblclick: function(ctx) {
  2113. // TODO: return promise?
  2114. if( ctx.targetType === "title" && ctx.options.clickFolderMode === 4) {
  2115. // this.nodeSetFocus(ctx);
  2116. // this._callHook("nodeSetActive", ctx, true);
  2117. this._callHook("nodeToggleExpanded", ctx);
  2118. }
  2119. // TODO: prevent text selection on dblclicks
  2120. if( ctx.targetType === "title" ) {
  2121. ctx.originalEvent.preventDefault();
  2122. }
  2123. },
  2124. /** Default handling for mouse keydown events.
  2125. *
  2126. * NOTE: this may be called with node == null if tree (but no node) has focus.
  2127. */
  2128. nodeKeydown: function(ctx) {
  2129. // TODO: return promise?
  2130. var res,
  2131. event = ctx.originalEvent,
  2132. node = ctx.node,
  2133. tree = ctx.tree,
  2134. opts = ctx.options,
  2135. handled = true,
  2136. activate = !(event.ctrlKey || !opts.autoActivate ),
  2137. KC = $.ui.keyCode;
  2138. // node.debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
  2139. // Set focus to first node, if no other node has the focus yet
  2140. if( !node ){
  2141. this.rootNode.getFirstChild().setFocus();
  2142. node = ctx.node = this.focusNode;
  2143. node.debug("Keydown force focus on first node");
  2144. }
  2145. switch( event.which ) {
  2146. // charCodes:
  2147. case KC.NUMPAD_ADD: //107: // '+'
  2148. case 187: // '+' @ Chrome, Safari
  2149. tree.nodeSetExpanded(ctx, true);
  2150. break;
  2151. case KC.NUMPAD_SUBTRACT: // '-'
  2152. case 189: // '-' @ Chrome, Safari
  2153. tree.nodeSetExpanded(ctx, false);
  2154. break;
  2155. case KC.SPACE:
  2156. if(opts.checkbox){
  2157. tree.nodeToggleSelected(ctx);
  2158. }else{
  2159. tree.nodeSetActive(ctx, true);
  2160. }
  2161. break;
  2162. case KC.ENTER:
  2163. tree.nodeSetActive(ctx, true);
  2164. break;
  2165. case KC.BACKSPACE:
  2166. case KC.LEFT:
  2167. case KC.RIGHT:
  2168. case KC.UP:
  2169. case KC.DOWN:
  2170. res = node.navigate(event.which, activate);
  2171. break;
  2172. default:
  2173. handled = false;
  2174. }
  2175. if(handled){
  2176. event.preventDefault();
  2177. }
  2178. },
  2179. // /** Default handling for mouse keypress events. */
  2180. // nodeKeypress: function(ctx) {
  2181. // var event = ctx.originalEvent;
  2182. // },
  2183. // /** Trigger lazyLoad event (async). */
  2184. // nodeLazyLoad: function(ctx) {
  2185. // var node = ctx.node;
  2186. // if(this._triggerNodeEvent())
  2187. // },
  2188. /** Load children (async).
  2189. * source may be
  2190. * - an array of children
  2191. * - a node object
  2192. * - an Ajax options object
  2193. * - an Ajax.promise
  2194. *
  2195. * @param {EventData} ctx
  2196. * @param {object[]|object|string|$.Promise|function} source
  2197. * @returns {$.Promise} The deferred will be resolved as soon as the (ajax)
  2198. * data was rendered.
  2199. */
  2200. nodeLoadChildren: function(ctx, source) {
  2201. var ajax, delay,
  2202. tree = ctx.tree,
  2203. node = ctx.node;
  2204. if($.isFunction(source)){
  2205. source = source();
  2206. }
  2207. // TOTHINK: move to 'ajax' extension?
  2208. if(source.url){
  2209. // `source` is an Ajax options object
  2210. ajax = $.extend({}, ctx.options.ajax, source);
  2211. if(ajax.debugDelay){
  2212. // simulate a slow server
  2213. delay = ajax.debugDelay;
  2214. if($.isArray(delay)){ // random delay range [min..max]
  2215. delay = delay[0] + Math.random() * (delay[1] - delay[0]);
  2216. }
  2217. node.debug("nodeLoadChildren waiting debug delay " + Math.round(delay) + "ms");
  2218. ajax.debugDelay = false;
  2219. source = $.Deferred(function (dfd) {
  2220. setTimeout(function () {
  2221. $.ajax(ajax)
  2222. .done(function () { dfd.resolveWith(this, arguments); })
  2223. .fail(function () { dfd.rejectWith(this, arguments); });
  2224. }, delay);
  2225. });
  2226. }else{
  2227. source = $.ajax(ajax);
  2228. }
  2229. // TODO: change 'pipe' to 'then' for jQuery 1.8
  2230. // $.pipe returns a new Promise with filtered results
  2231. source = source.pipe(function (data, textStatus, jqXHR) {
  2232. var res;
  2233. if(typeof data === "string"){
  2234. $.error("Ajax request returned a string (did you get the JSON dataType wrong?).");
  2235. }
  2236. // postProcess is similar to the standard dataFilter hook,
  2237. // but it is also called for JSONP
  2238. if( ctx.options.postProcess ){
  2239. res = tree._triggerNodeEvent("postProcess", ctx, ctx.originalEvent, {response: data, dataType: this.dataType});
  2240. data = $.isArray(res) ? res : data;
  2241. } else if (data && data.hasOwnProperty("d") && ctx.options.enableAspx ) {
  2242. // Process ASPX WebMethod JSON object inside "d" property
  2243. data = (typeof data.d === "string") ? $.parseJSON(data.d) : data.d;
  2244. }
  2245. return data;
  2246. }, function (jqXHR, textStatus, errorThrown) {
  2247. return tree._makeHookContext(node, null, {
  2248. error: jqXHR,
  2249. args: Array.prototype.slice.call(arguments),
  2250. message: errorThrown,
  2251. details: jqXHR.status + ": " + errorThrown
  2252. });
  2253. });
  2254. }
  2255. if($.isFunction(source.promise)){
  2256. // `source` is a deferred, i.e. ajax request
  2257. _assert(!node.isLoading());
  2258. node._isLoading = true;
  2259. tree.nodeSetStatus(ctx, "loading");
  2260. source.done(function () {
  2261. tree.nodeSetStatus(ctx, "ok");
  2262. }).fail(function(error){
  2263. var ctxErr;
  2264. if (error.node && error.error && error.message) {
  2265. // error is already a context object
  2266. ctxErr = error;
  2267. } else {
  2268. ctxErr = tree._makeHookContext(node, null, {
  2269. error: error, // it can be jqXHR or any custom error
  2270. args: Array.prototype.slice.call(arguments),
  2271. message: error ? (error.message || error.toString()) : ""
  2272. });
  2273. }
  2274. tree._triggerNodeEvent("loaderror", ctxErr, null);
  2275. tree.nodeSetStatus(ctx, "error", ctxErr.message, ctxErr.details);
  2276. });
  2277. }
  2278. // $.when(source) resolves also for non-deferreds
  2279. return $.when(source).done(function(children){
  2280. var metaData;
  2281. if( $.isPlainObject(children) ){
  2282. // We got {foo: 'abc', children: [...]}
  2283. // Copy extra properties to tree.data.
  2284. _assert($.isArray(children.children), "source must contain (or be) an array of children");
  2285. _assert(node.isRoot(), "source may only be an object for root nodes");
  2286. metaData = children;
  2287. children = children.children;
  2288. delete metaData.children;
  2289. $.extend(tree.data, metaData);
  2290. }
  2291. _assert($.isArray(children), "expected array of children");
  2292. node._setChildren(children);
  2293. if(node.parent){
  2294. // trigger fancytreeloadchildren (except for tree-reload)
  2295. tree._triggerNodeEvent("loadChildren", node);
  2296. }
  2297. }).always(function(){
  2298. node._isLoading = false;
  2299. });
  2300. },
  2301. /** [Not Implemented] */
  2302. nodeLoadKeyPath: function(ctx, keyPathList) {
  2303. // TODO: implement and improve
  2304. // http://code.google.com/p/fancytree/issues/detail?id=222
  2305. },
  2306. /**
  2307. * Remove a single direct child of ctx.node.
  2308. * @param {EventData} ctx
  2309. * @param {FancytreeNode} childNode dircect child of ctx.node
  2310. */
  2311. nodeRemoveChild: function(ctx, childNode) {
  2312. var idx,
  2313. node = ctx.node,
  2314. opts = ctx.options,
  2315. subCtx = $.extend({}, ctx, {node: childNode}),
  2316. children = node.children;
  2317. // FT.debug("nodeRemoveChild()", node.toString(), childNode.toString());
  2318. if( children.length === 1 ) {
  2319. _assert(childNode === children[0]);
  2320. return this.nodeRemoveChildren(ctx);
  2321. }
  2322. if( this.activeNode && (childNode === this.activeNode || this.activeNode.isDescendantOf(childNode))){
  2323. this.activeNode.setActive(false); // TODO: don't fire events
  2324. }
  2325. if( this.focusNode && (childNode === this.focusNode || this.focusNode.isDescendantOf(childNode))){
  2326. this.focusNode = null;
  2327. }
  2328. // TODO: persist must take care to clear select and expand cookies
  2329. this.nodeRemoveMarkup(subCtx);
  2330. this.nodeRemoveChildren(subCtx);
  2331. idx = $.inArray(childNode, children);
  2332. _assert(idx >= 0);
  2333. // Unlink to support GC
  2334. childNode.visit(function(n){
  2335. n.parent = null;
  2336. }, true);
  2337. if ( opts.removeNode ){
  2338. opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
  2339. }
  2340. // remove from child list
  2341. children.splice(idx, 1);
  2342. },
  2343. /**Remove HTML markup for all descendents of ctx.node.
  2344. * @param {EventData} ctx
  2345. */
  2346. nodeRemoveChildMarkup: function(ctx) {
  2347. var node = ctx.node;
  2348. // FT.debug("nodeRemoveChildMarkup()", node.toString());
  2349. // TODO: Unlink attr.ftnode to support GC
  2350. if(node.ul){
  2351. if( node.isRoot() ) {
  2352. $(node.ul).empty();
  2353. } else {
  2354. $(node.ul).remove();
  2355. node.ul = null;
  2356. }
  2357. node.visit(function(n){
  2358. n.li = n.ul = null;
  2359. });
  2360. }
  2361. },
  2362. /**Remove all descendants of ctx.node.
  2363. * @param {EventData} ctx
  2364. */
  2365. nodeRemoveChildren: function(ctx) {
  2366. var subCtx,
  2367. node = ctx.node,
  2368. children = node.children,
  2369. opts = ctx.options;
  2370. // FT.debug("nodeRemoveChildren()", node.toString());
  2371. if(!children){
  2372. return;
  2373. }
  2374. if( this.activeNode && this.activeNode.isDescendantOf(node)){
  2375. this.activeNode.setActive(false); // TODO: don't fire events
  2376. }
  2377. if( this.focusNode && this.focusNode.isDescendantOf(node)){
  2378. this.focusNode = null;
  2379. }
  2380. // TODO: persist must take care to clear select and expand cookies
  2381. this.nodeRemoveChildMarkup(ctx);
  2382. // Unlink children to support GC
  2383. // TODO: also delete this.children (not possible using visit())
  2384. subCtx = $.extend({}, ctx);
  2385. node.visit(function(n){
  2386. n.parent = null;
  2387. if ( opts.removeNode ){
  2388. subCtx.node = n;
  2389. opts.removeNode.call(ctx.tree, {type: "removeNode"}, subCtx);
  2390. }
  2391. });
  2392. if( node.lazy ){
  2393. // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
  2394. node.children = [];
  2395. } else{
  2396. node.children = null;
  2397. }
  2398. node.expanded = false;
  2399. // TODO: ? this._isLoading = false;
  2400. this.nodeRenderStatus(ctx);
  2401. },
  2402. /**Remove HTML markup for ctx.node and all its descendents.
  2403. * @param {EventData} ctx
  2404. */
  2405. nodeRemoveMarkup: function(ctx) {
  2406. var node = ctx.node;
  2407. // FT.debug("nodeRemoveMarkup()", node.toString());
  2408. // TODO: Unlink attr.ftnode to support GC
  2409. if(node.li){
  2410. $(node.li).remove();
  2411. node.li = null;
  2412. }
  2413. this.nodeRemoveChildMarkup(ctx);
  2414. },
  2415. /**
  2416. * Create `<li><span>..</span> .. </li>` tags for this node.
  2417. *
  2418. * This method takes care that all HTML markup is created that is required
  2419. * to display this node in it's current state.
  2420. *
  2421. * Call this method to create new nodes, or after the strucuture
  2422. * was changed (e.g. after moving this node or adding/removing children)
  2423. * nodeRenderTitle() and nodeRenderStatus() are implied.
  2424. *
  2425. * Note: if a node was created/removed, nodeRender() must be called for the
  2426. * parent!
  2427. * <code>
  2428. * <li id='KEY' ftnode=NODE>
  2429. * <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'>
  2430. * <span class="fancytree-expander"></span>
  2431. * <span class="fancytree-checkbox"></span> // only present in checkbox mode
  2432. * <span class="fancytree-icon"></span>
  2433. * <a href="#" class="fancytree-title"> Node 1 </a>
  2434. * </span>
  2435. * <ul> // only present if node has children
  2436. * <li id='KEY' ftnode=NODE> child1 ... </li>
  2437. * <li id='KEY' ftnode=NODE> child2 ... </li>
  2438. * </ul>
  2439. * </li>
  2440. * </code>
  2441. *
  2442. * @param {EventData} ctx
  2443. * @param {boolean} [force=false] re-render, even if html markup was already created
  2444. * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
  2445. * @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later
  2446. */
  2447. nodeRender: function(ctx, force, deep, collapsed, _recursive) {
  2448. /* This method must take care of all cases where the current data mode
  2449. * (i.e. node hierarchy) does not match the current markup.
  2450. *
  2451. * - node was not yet rendered:
  2452. * create markup
  2453. * - node was rendered: exit fast
  2454. * - children have been added
  2455. * - childern have been removed
  2456. */
  2457. var childLI, childNode1, childNode2, i, l, next, subCtx,
  2458. node = ctx.node,
  2459. tree = ctx.tree,
  2460. opts = ctx.options,
  2461. aria = opts.aria,
  2462. firstTime = false,
  2463. parent = node.parent,
  2464. isRootNode = !parent,
  2465. children = node.children;
  2466. // FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
  2467. if( ! isRootNode && ! parent.ul ) {
  2468. // issue #105: calling node.collapse on a deep, unrendered node
  2469. return;
  2470. }
  2471. _assert(isRootNode || parent.ul, "parent UL must exist");
  2472. // if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
  2473. // if(node.li.parentNode !== node.parent.ul){
  2474. // // alert("unlink " + node + " (must be child of " + node.parent + ")");
  2475. // this.warn("unlink " + node + " (must be child of " + node.parent + ")");
  2476. // }
  2477. // // this.debug("nodeRemoveMarkup...");
  2478. // this.nodeRemoveMarkup(ctx);
  2479. // }
  2480. // Render the node
  2481. if( !isRootNode ){
  2482. // Discard markup on force-mode, or if it is not linked to parent <ul>
  2483. if(node.li && (force || (node.li.parentNode !== node.parent.ul) ) ){
  2484. if(node.li.parentNode !== node.parent.ul){
  2485. // alert("unlink " + node + " (must be child of " + node.parent + ")");
  2486. this.warn("unlink " + node + " (must be child of " + node.parent + ")");
  2487. }
  2488. // this.debug("nodeRemoveMarkup...");
  2489. this.nodeRemoveMarkup(ctx);
  2490. }
  2491. // Create <li><span /> </li>
  2492. // node.debug("render...");
  2493. if( !node.li ) {
  2494. // node.debug("render... really");
  2495. firstTime = true;
  2496. node.li = document.createElement("li");
  2497. node.li.ftnode = node;
  2498. if(aria){
  2499. // TODO: why doesn't this work:
  2500. // node.li.role = "treeitem";
  2501. // $(node.li).attr("role", "treeitem")
  2502. // .attr("aria-labelledby", "ftal_" + node.key);
  2503. }
  2504. if( node.key && opts.generateIds ){
  2505. node.li.id = opts.idPrefix + node.key;
  2506. }
  2507. node.span = document.createElement("span");
  2508. node.span.className = "fancytree-node";
  2509. if(aria){
  2510. $(node.span).attr("aria-labelledby", "ftal_" + node.key);
  2511. }
  2512. node.li.appendChild(node.span);
  2513. // Create inner HTML for the <span> (expander, checkbox, icon, and title)
  2514. this.nodeRenderTitle(ctx);
  2515. // Allow tweaking and binding, after node was created for the first time
  2516. if ( opts.createNode ){
  2517. opts.createNode.call(tree, {type: "createNode"}, ctx);
  2518. }
  2519. }else{
  2520. // this.nodeRenderTitle(ctx);
  2521. this.nodeRenderStatus(ctx);
  2522. }
  2523. // Allow tweaking after node state was rendered
  2524. if ( opts.renderNode ){
  2525. opts.renderNode.call(tree, {type: "renderNode"}, ctx);
  2526. }
  2527. }
  2528. // Visit child nodes
  2529. if( children ){
  2530. if( isRootNode || node.expanded || deep === true ) {
  2531. // Create a UL to hold the children
  2532. if( !node.ul ){
  2533. node.ul = document.createElement("ul");
  2534. if((collapsed === true && !_recursive) || !node.expanded){
  2535. // hide top UL, so we can use an animation to show it later
  2536. node.ul.style.display = "none";
  2537. }
  2538. if(aria){
  2539. $(node.ul).attr("role", "group");
  2540. }
  2541. if ( node.li ) { // issue #67
  2542. node.li.appendChild(node.ul);
  2543. } else {
  2544. node.tree.$div.append(node.ul);
  2545. }
  2546. }
  2547. // Add child markup
  2548. for(i=0, l=children.length; i<l; i++) {
  2549. subCtx = $.extend({}, ctx, {node: children[i]});
  2550. this.nodeRender(subCtx, force, deep, false, true);
  2551. }
  2552. // Remove <li> if nodes have moved to another parent
  2553. childLI = node.ul.firstChild;
  2554. while( childLI ){
  2555. childNode2 = childLI.ftnode;
  2556. if( childNode2 && childNode2.parent !== node ) {
  2557. node.debug("_fixParent: remove missing " + childNode2, childLI);
  2558. next = childLI.nextSibling;
  2559. childLI.parentNode.removeChild(childLI);
  2560. childLI = next;
  2561. }else{
  2562. childLI = childLI.nextSibling;
  2563. }
  2564. }
  2565. // Make sure, that <li> order matches node.children order.
  2566. childLI = node.ul.firstChild;
  2567. for(i=0, l=children.length-1; i<l; i++) {
  2568. childNode1 = children[i];
  2569. childNode2 = childLI.ftnode;
  2570. if( childNode1 !== childNode2 ) {
  2571. node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
  2572. node.ul.insertBefore(childNode1.li, childNode2.li);
  2573. } else {
  2574. childLI = childLI.nextSibling;
  2575. }
  2576. }
  2577. }
  2578. }else{
  2579. // No children: remove markup if any
  2580. if( node.ul ){
  2581. // alert("remove child markup for " + node);
  2582. this.warn("remove child markup for " + node);
  2583. this.nodeRemoveChildMarkup(ctx);
  2584. }
  2585. }
  2586. if( !isRootNode ){
  2587. // Update element classes according to node state
  2588. // this.nodeRenderStatus(ctx);
  2589. // Finally add the whole structure to the DOM, so the browser can render
  2590. if(firstTime){
  2591. parent.ul.appendChild(node.li);
  2592. }
  2593. }
  2594. },
  2595. /** Create HTML for the node's outer <span> (expander, checkbox, icon, and title).
  2596. *
  2597. * nodeRenderStatus() is implied.
  2598. * @param {EventData} ctx
  2599. */
  2600. nodeRenderTitle: function(ctx, title) {
  2601. // set node connector images, links and text
  2602. var id, imageSrc, nodeTitle, role, tabindex, tooltip,
  2603. node = ctx.node,
  2604. tree = ctx.tree,
  2605. opts = ctx.options,
  2606. aria = opts.aria,
  2607. level = node.getLevel(),
  2608. ares = [],
  2609. icon = node.data.icon;
  2610. if(title !== undefined){
  2611. node.title = title;
  2612. }
  2613. if(!node.span){
  2614. // Silently bail out if node was not rendered yet, assuming
  2615. // node.render() will be called as the node becomes visible
  2616. return;
  2617. }
  2618. // connector (expanded, expandable or simple)
  2619. // TODO: optiimize this if clause
  2620. if( level < opts.minExpandLevel ) {
  2621. if(level > 1){
  2622. if(aria){
  2623. ares.push("<span role='button' class='fancytree-expander'></span>");
  2624. }else{
  2625. ares.push("<span class='fancytree-expander'></span>");
  2626. }
  2627. }
  2628. // .. else (i.e. for root level) skip expander/connector alltogether
  2629. } else {
  2630. if(aria){
  2631. ares.push("<span role='button' class='fancytree-expander'></span>");
  2632. }else{
  2633. ares.push("<span class='fancytree-expander'></span>");
  2634. }
  2635. }
  2636. // Checkbox mode
  2637. if( opts.checkbox && node.hideCheckbox !== true && !node.isStatusNode() ) {
  2638. if(aria){
  2639. ares.push("<span role='checkbox' class='fancytree-checkbox'></span>");
  2640. }else{
  2641. ares.push("<span class='fancytree-checkbox'></span>");
  2642. }
  2643. }
  2644. // folder or doctype icon
  2645. role = aria ? " role='img'" : "";
  2646. if ( icon && typeof icon === "string" ) {
  2647. imageSrc = (icon.charAt(0) === "/") ? icon : (opts.imagePath + icon);
  2648. ares.push("<img src='" + imageSrc + "' alt='' />");
  2649. } else if ( node.data.iconclass ) {
  2650. // TODO: review and test and document
  2651. ares.push("<span " + role + " class='fancytree-custom-icon" + " " + node.data.iconclass + "'></span>");
  2652. } else if ( icon === true || (icon !== false && opts.icons !== false) ) {
  2653. // opts.icons defines the default behavior.
  2654. // node.icon == true/false can override this
  2655. ares.push("<span " + role + " class='fancytree-icon'></span>");
  2656. }
  2657. // node title
  2658. nodeTitle = "";
  2659. // TODO: currently undocumented; may be removed?
  2660. if ( opts.renderTitle ){
  2661. nodeTitle = opts.renderTitle.call(tree, {type: "renderTitle"}, ctx) || "";
  2662. }
  2663. if(!nodeTitle){
  2664. // TODO: escape tooltip string
  2665. tooltip = node.tooltip ? " title='" + node.tooltip.replace(/\"/g, "&quot;") + "'" : "";
  2666. id = aria ? " id='ftal_" + node.key + "'" : "";
  2667. role = aria ? " role='treeitem'" : "";
  2668. tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
  2669. nodeTitle = "<span " + role + " class='fancytree-title'" + id + tooltip + tabindex + ">" + node.title + "</span>";
  2670. }
  2671. ares.push(nodeTitle);
  2672. // Note: this will trigger focusout, if node had the focus
  2673. //$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly
  2674. node.span.innerHTML = ares.join("");
  2675. // Update CSS classes
  2676. this.nodeRenderStatus(ctx);
  2677. },
  2678. /** Update element classes according to node state.
  2679. * @param {EventData} ctx
  2680. */
  2681. nodeRenderStatus: function(ctx) {
  2682. // Set classes for current status
  2683. var node = ctx.node,
  2684. tree = ctx.tree,
  2685. opts = ctx.options,
  2686. // nodeContainer = node[tree.nodeContainerAttrName],
  2687. hasChildren = node.hasChildren(),
  2688. isLastSib = node.isLastSibling(),
  2689. aria = opts.aria,
  2690. // $ariaElem = aria ? $(node[tree.ariaPropName]) : null,
  2691. $ariaElem = $(node.span).find(".fancytree-title"),
  2692. cn = opts._classNames,
  2693. cnList = [],
  2694. statusElem = node[tree.statusClassPropName];
  2695. if( !statusElem ){
  2696. // if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
  2697. return;
  2698. }
  2699. // Build a list of class names that we will add to the node <span>
  2700. cnList.push(cn.node);
  2701. if( tree.activeNode === node ){
  2702. cnList.push(cn.active);
  2703. // $(">span.fancytree-title", statusElem).attr("tabindex", "0");
  2704. // tree.$container.removeAttr("tabindex");
  2705. }else{
  2706. // $(">span.fancytree-title", statusElem).removeAttr("tabindex");
  2707. // tree.$container.attr("tabindex", "0");
  2708. }
  2709. if( tree.focusNode === node ){
  2710. cnList.push(cn.focused);
  2711. if(aria){
  2712. // $(">span.fancytree-title", statusElem).attr("tabindex", "0");
  2713. // $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
  2714. // TODO: is this the right element for this attribute?
  2715. $ariaElem
  2716. .attr("aria-activedescendant", true);
  2717. // .attr("tabindex", "-1");
  2718. }
  2719. }else if(aria){
  2720. // $(">span.fancytree-title", statusElem).attr("tabindex", "-1");
  2721. $ariaElem
  2722. .removeAttr("aria-activedescendant");
  2723. // .removeAttr("tabindex");
  2724. }
  2725. if( node.expanded ){
  2726. cnList.push(cn.expanded);
  2727. if(aria){
  2728. $ariaElem.attr("aria-expanded", true);
  2729. }
  2730. }else if(aria){
  2731. $ariaElem.removeAttr("aria-expanded");
  2732. }
  2733. if( node.folder ){
  2734. cnList.push(cn.folder);
  2735. }
  2736. if( hasChildren !== false ){
  2737. cnList.push(cn.hasChildren);
  2738. }
  2739. // TODO: required?
  2740. if( isLastSib ){
  2741. cnList.push(cn.lastsib);
  2742. }
  2743. if( node.lazy && node.children == null ){
  2744. cnList.push(cn.lazy);
  2745. }
  2746. if( node.partsel ){
  2747. cnList.push(cn.partsel);
  2748. }
  2749. if( node.selected ){
  2750. cnList.push(cn.selected);
  2751. if(aria){
  2752. $ariaElem.attr("aria-selected", true);
  2753. }
  2754. }else if(aria){
  2755. $ariaElem.attr("aria-selected", false);
  2756. }
  2757. if( node.extraClasses ){
  2758. cnList.push(node.extraClasses);
  2759. }
  2760. // IE6 doesn't correctly evaluate multiple class names,
  2761. // so we create combined class names that can be used in the CSS
  2762. if( hasChildren === false ){
  2763. cnList.push(cn.combinedExpanderPrefix + "n" +
  2764. (isLastSib ? "l" : "")
  2765. );
  2766. }else{
  2767. cnList.push(cn.combinedExpanderPrefix +
  2768. (node.expanded ? "e" : "c") +
  2769. (node.lazy && node.children == null ? "d" : "") +
  2770. (isLastSib ? "l" : "")
  2771. );
  2772. }
  2773. cnList.push(cn.combinedIconPrefix +
  2774. (node.expanded ? "e" : "c") +
  2775. (node.folder ? "f" : "")
  2776. );
  2777. // node.span.className = cnList.join(" ");
  2778. statusElem.className = cnList.join(" ");
  2779. // TODO: we should not set this in the <span> tag also, if we set it here:
  2780. // Maybe most (all) of the classes should be set in LI instead of SPAN?
  2781. if(node.li){
  2782. node.li.className = isLastSib ? cn.lastsib : "";
  2783. }
  2784. },
  2785. /** Activate node.
  2786. * flag defaults to true.
  2787. * If flag is true, the node is activated (must be a synchronous operation)
  2788. * If flag is false, the node is deactivated (must be a synchronous operation)
  2789. * @param {EventData} ctx
  2790. * @param {boolean} [flag=true]
  2791. * @param {object} [opts] additional options. Defaults to {}
  2792. */
  2793. nodeSetActive: function(ctx, flag, callOpts) {
  2794. // Handle user click / [space] / [enter], according to clickFolderMode.
  2795. callOpts = callOpts || {};
  2796. var subCtx,
  2797. node = ctx.node,
  2798. tree = ctx.tree,
  2799. opts = ctx.options,
  2800. // userEvent = !!ctx.originalEvent,
  2801. isActive = (node === tree.activeNode);
  2802. // flag defaults to true
  2803. flag = (flag !== false);
  2804. // node.debug("nodeSetActive", flag);
  2805. if(isActive === flag){
  2806. // Nothing to do
  2807. return _getResolvedPromise(node);
  2808. }else if(flag && this._triggerNodeEvent("beforeActivate", node, ctx.originalEvent) === false ){
  2809. // Callback returned false
  2810. return _getRejectedPromise(node, ["rejected"]);
  2811. }
  2812. if(flag){
  2813. if(tree.activeNode){
  2814. _assert(tree.activeNode !== node, "node was active (inconsistency)");
  2815. subCtx = $.extend({}, ctx, {node: tree.activeNode});
  2816. tree.nodeSetActive(subCtx, false);
  2817. _assert(tree.activeNode === null, "deactivate was out of sync?");
  2818. }
  2819. if(opts.activeVisible){
  2820. // tree.nodeMakeVisible(ctx);
  2821. node.makeVisible();
  2822. }
  2823. tree.activeNode = node;
  2824. tree.nodeRenderStatus(ctx);
  2825. tree.nodeSetFocus(ctx);
  2826. tree._triggerNodeEvent("activate", node);
  2827. }else{
  2828. _assert(tree.activeNode === node, "node was not active (inconsistency)");
  2829. tree.activeNode = null;
  2830. this.nodeRenderStatus(ctx);
  2831. ctx.tree._triggerNodeEvent("deactivate", node);
  2832. }
  2833. },
  2834. /** Expand or collapse node, return Deferred.promise.
  2835. *
  2836. * @param {EventData} ctx
  2837. * @param {boolean} [flag=true]
  2838. * @param {object} [opts] additional options. Defaults to {noAnimation: false}
  2839. * @returns {$.Promise} The deferred will be resolved as soon as the (lazy)
  2840. * data was retrieved, rendered, and the expand animation finshed.
  2841. */
  2842. nodeSetExpanded: function(ctx, flag, callOpts) {
  2843. callOpts = callOpts || {};
  2844. var _afterLoad, dfd, i, l, parents, prevAC,
  2845. node = ctx.node,
  2846. tree = ctx.tree,
  2847. opts = ctx.options,
  2848. noAnimation = callOpts.noAnimation === true;
  2849. // flag defaults to true
  2850. flag = (flag !== false);
  2851. // node.debug("nodeSetExpanded(" + flag + ")");
  2852. if((node.expanded && flag) || (!node.expanded && !flag)){
  2853. // Nothing to do
  2854. // node.debug("nodeSetExpanded(" + flag + "): nothing to do");
  2855. return _getResolvedPromise(node);
  2856. }else if(flag && !node.lazy && !node.hasChildren() ){
  2857. // Prevent expanding of empty nodes
  2858. // return _getRejectedPromise(node, ["empty"]);
  2859. return _getResolvedPromise(node);
  2860. }else if( !flag && node.getLevel() < opts.minExpandLevel ) {
  2861. // Prevent collapsing locked levels
  2862. return _getRejectedPromise(node, ["locked"]);
  2863. }else if ( this._triggerNodeEvent("beforeExpand", node, ctx.originalEvent) === false ){
  2864. // Callback returned false
  2865. return _getRejectedPromise(node, ["rejected"]);
  2866. }
  2867. // If this node inside a collpased node, no animation and scrolling is needed
  2868. if( !noAnimation && !node.isVisible() ) {
  2869. noAnimation = callOpts.noAnimation = true;
  2870. }
  2871. dfd = new $.Deferred();
  2872. // Auto-collapse mode: collapse all siblings
  2873. if( flag && !node.expanded && opts.autoCollapse ) {
  2874. parents = node.getParentList(false, true);
  2875. prevAC = opts.autoCollapse;
  2876. try{
  2877. opts.autoCollapse = false;
  2878. for(i=0, l=parents.length; i<l; i++){
  2879. // TODO: should return promise?
  2880. this._callHook("nodeCollapseSiblings", parents[i], callOpts);
  2881. }
  2882. }finally{
  2883. opts.autoCollapse = prevAC;
  2884. }
  2885. }
  2886. // Trigger expand/collapse after expanding
  2887. dfd.done(function(){
  2888. ctx.tree._triggerNodeEvent(flag ? "expand" : "collapse", ctx);
  2889. if( opts.autoScroll && !noAnimation ) {
  2890. // Scroll down to last child, but keep current node visible
  2891. node.getLastChild().scrollIntoView(true, node);
  2892. }
  2893. });
  2894. // vvv Code below is executed after loading finished:
  2895. _afterLoad = function(callback){
  2896. var duration, easing, isVisible, isExpanded;
  2897. node.expanded = flag;
  2898. // Create required markup, but make sure the top UL is hidden, so we
  2899. // can animate later
  2900. tree._callHook("nodeRender", ctx, false, false, true);
  2901. // If the currently active node is now hidden, deactivate it
  2902. // if( opts.activeVisible && this.activeNode && ! this.activeNode.isVisible() ) {
  2903. // this.activeNode.deactivate();
  2904. // }
  2905. // Expanding a lazy node: set 'loading...' and call callback
  2906. // if( bExpand && this.data.isLazy && this.childList === null && !this._isLoading ) {
  2907. // this._loadContent();
  2908. // return;
  2909. // }
  2910. // Hide children, if node is collapsed
  2911. if( node.ul ) {
  2912. isVisible = (node.ul.style.display !== "none");
  2913. isExpanded = !!node.expanded;
  2914. if ( isVisible === isExpanded ) {
  2915. node.warn("nodeSetExpanded: UL.style.display already set");
  2916. } else if ( !opts.fx || noAnimation ) {
  2917. node.ul.style.display = ( node.expanded || !parent ) ? "" : "none";
  2918. } else {
  2919. duration = opts.fx.duration || 200;
  2920. easing = opts.fx.easing;
  2921. // node.debug("nodeSetExpanded: animate start...");
  2922. $(node.ul).animate(opts.fx, duration, easing, function(){
  2923. // node.debug("nodeSetExpanded: animate done");
  2924. callback();
  2925. });
  2926. return;
  2927. }
  2928. }
  2929. callback();
  2930. };
  2931. // ^^^ Code above is executed after loading finshed.
  2932. // Load lazy nodes, if any. Then continue with _afterLoad()
  2933. if(flag && node.lazy && node.hasChildren() === undefined){
  2934. // node.debug("nodeSetExpanded: load start...");
  2935. node.load().done(function(){
  2936. // node.debug("nodeSetExpanded: load done");
  2937. if(dfd.notifyWith){ // requires jQuery 1.6+
  2938. dfd.notifyWith(node, ["loaded"]);
  2939. }
  2940. _afterLoad(function () { dfd.resolveWith(node); });
  2941. }).fail(function(errMsg){
  2942. _afterLoad(function () { dfd.rejectWith(node, ["load failed (" + errMsg + ")"]); });
  2943. });
  2944. /*
  2945. var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent);
  2946. _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
  2947. node.debug("nodeSetExpanded: load start...");
  2948. this._callHook("nodeLoadChildren", ctx, source).done(function(){
  2949. node.debug("nodeSetExpanded: load done");
  2950. if(dfd.notifyWith){ // requires jQuery 1.6+
  2951. dfd.notifyWith(node, ["loaded"]);
  2952. }
  2953. _afterLoad.call(tree);
  2954. }).fail(function(errMsg){
  2955. dfd.rejectWith(node, ["load failed (" + errMsg + ")"]);
  2956. });
  2957. */
  2958. }else{
  2959. _afterLoad(function () { dfd.resolveWith(node); });
  2960. }
  2961. // node.debug("nodeSetExpanded: returns");
  2962. return dfd.promise();
  2963. },
  2964. /**
  2965. * @param {EventData} ctx
  2966. * @param {boolean} [flag=true]
  2967. */
  2968. nodeSetFocus: function(ctx, flag) {
  2969. // ctx.node.debug("nodeSetFocus(" + flag + ")");
  2970. var ctx2,
  2971. tree = ctx.tree,
  2972. node = ctx.node;
  2973. flag = (flag !== false);
  2974. // Blur previous node if any
  2975. if(tree.focusNode){
  2976. if(tree.focusNode === node && flag){
  2977. // node.debug("nodeSetFocus(" + flag + "): nothing to do");
  2978. return;
  2979. }
  2980. ctx2 = $.extend({}, ctx, {node: tree.focusNode});
  2981. tree.focusNode = null;
  2982. this._triggerNodeEvent("blur", ctx2);
  2983. this._callHook("nodeRenderStatus", ctx2);
  2984. }
  2985. // Set focus to container and node
  2986. if(flag){
  2987. if( !this.hasFocus() ){
  2988. node.debug("nodeSetFocus: forcing container focus");
  2989. // Note: we pass _calledByNodeSetFocus=true
  2990. this._callHook("treeSetFocus", ctx, true, true);
  2991. }
  2992. // this.nodeMakeVisible(ctx);
  2993. node.makeVisible();
  2994. tree.focusNode = node;
  2995. // node.debug("FOCUS...");
  2996. // $(node.span).find(".fancytree-title").focus();
  2997. this._triggerNodeEvent("focus", ctx);
  2998. // if(ctx.options.autoActivate){
  2999. // tree.nodeSetActive(ctx, true);
  3000. // }
  3001. if(ctx.options.autoScroll){
  3002. node.scrollIntoView();
  3003. }
  3004. this._callHook("nodeRenderStatus", ctx);
  3005. }
  3006. },
  3007. /** (De)Select node, return new status (sync).
  3008. *
  3009. * @param {EventData} ctx
  3010. * @param {boolean} [flag=true]
  3011. */
  3012. nodeSetSelected: function(ctx, flag) {
  3013. var node = ctx.node,
  3014. tree = ctx.tree,
  3015. opts = ctx.options;
  3016. // flag defaults to true
  3017. flag = (flag !== false);
  3018. node.debug("nodeSetSelected(" + flag + ")", ctx);
  3019. if( node.unselectable){
  3020. return;
  3021. }
  3022. // TODO: !!node.expanded is nicer, but doesn't pass jshint
  3023. // https://github.com/jshint/jshint/issues/455
  3024. // if( !!node.expanded === !!flag){
  3025. if((node.selected && flag) || (!node.selected && !flag)){
  3026. return !!node.selected;
  3027. }else if ( this._triggerNodeEvent("beforeSelect", node, ctx.originalEvent) === false ){
  3028. return !!node.selected;
  3029. }
  3030. if(flag && opts.selectMode === 1){
  3031. // single selection mode
  3032. if(tree.lastSelectedNode){
  3033. tree.lastSelectedNode.setSelected(false);
  3034. }
  3035. }else if(opts.selectMode === 3){
  3036. // multi.hier selection mode
  3037. node.selected = flag;
  3038. // this._fixSelectionState(node);
  3039. node.fixSelection3AfterClick();
  3040. }
  3041. node.selected = flag;
  3042. this.nodeRenderStatus(ctx);
  3043. tree.lastSelectedNode = flag ? node : null;
  3044. tree._triggerNodeEvent("select", ctx);
  3045. },
  3046. /** Show node status (ok, loading, error) using styles and a dummy child node.
  3047. *
  3048. * @param {EventData} ctx
  3049. * @param status
  3050. * @param message
  3051. * @param details
  3052. */
  3053. nodeSetStatus: function(ctx, status, message, details) {
  3054. var node = ctx.node,
  3055. tree = ctx.tree,
  3056. cn = ctx.options._classNames;
  3057. function _clearStatusNode() {
  3058. var firstChild = ( node.children ? node.children[0] : null );
  3059. if ( firstChild && firstChild.isStatusNode() ) {
  3060. try{
  3061. // I've seen exceptions here with loadKeyPath...
  3062. if(node.ul){
  3063. node.ul.removeChild(firstChild.li);
  3064. firstChild.li = null; // avoid leaks (issue 215)
  3065. }
  3066. }catch(e){}
  3067. if( node.children.length === 1 ){
  3068. node.children = [];
  3069. }else{
  3070. node.children.shift();
  3071. }
  3072. }
  3073. }
  3074. function _setStatusNode(data, type) {
  3075. var firstChild = ( node.children ? node.children[0] : null );
  3076. if ( firstChild && firstChild.isStatusNode() ) {
  3077. $.extend(firstChild, data);
  3078. tree._callHook("nodeRender", firstChild);
  3079. } else {
  3080. data.key = "_statusNode";
  3081. node._setChildren([data]);
  3082. // node.children[0].isStatusNode = true;
  3083. node.children[0].statusNodeType = type;
  3084. tree.render();
  3085. }
  3086. return node.children[0];
  3087. }
  3088. switch(status){
  3089. case "ok":
  3090. _clearStatusNode();
  3091. $(node.span).removeClass(cn.loading);
  3092. $(node.span).removeClass(cn.error);
  3093. break;
  3094. case "loading":
  3095. $(node.span).removeClass(cn.error);
  3096. $(node.span).addClass(cn.loading);
  3097. if(!node.parent){
  3098. _setStatusNode({
  3099. title: tree.options.strings.loading + (message ? " (" + message + ") " : ""),
  3100. tooltip: details,
  3101. extraClasses: "fancytree-statusnode-wait"
  3102. }, status);
  3103. }
  3104. break;
  3105. case "error":
  3106. $(node.span).removeClass(cn.loading);
  3107. $(node.span).addClass(cn.error);
  3108. _setStatusNode({
  3109. title: tree.options.strings.loadError + (message ? " (" + message + ") " : ""),
  3110. tooltip: details,
  3111. extraClasses: "fancytree-statusnode-error"
  3112. }, status);
  3113. break;
  3114. default:
  3115. $.error("invalid status " + status);
  3116. }
  3117. },
  3118. /**
  3119. *
  3120. * @param {EventData} ctx
  3121. */
  3122. nodeToggleExpanded: function(ctx) {
  3123. return this.nodeSetExpanded(ctx, !ctx.node.expanded);
  3124. },
  3125. /**
  3126. * @param {EventData} ctx
  3127. */
  3128. nodeToggleSelected: function(ctx) {
  3129. return this.nodeSetSelected(ctx, !ctx.node.selected);
  3130. },
  3131. /** Remove all nodes.
  3132. * @param {EventData} ctx
  3133. */
  3134. treeClear: function(ctx) {
  3135. var tree = ctx.tree;
  3136. tree.activeNode = null;
  3137. tree.focusNode = null;
  3138. tree.$div.find(">ul.fancytree-container").empty();
  3139. // TODO: call destructors and remove reference loops
  3140. tree.rootNode.children = null;
  3141. },
  3142. /** Widget was created (called only once, even it re-initialized).
  3143. * @param {EventData} ctx
  3144. */
  3145. treeCreate: function(ctx) {
  3146. },
  3147. /** Widget was destroyed.
  3148. * @param {EventData} ctx
  3149. */
  3150. treeDestroy: function(ctx) {
  3151. },
  3152. /** Widget was (re-)initialized.
  3153. * @param {EventData} ctx
  3154. */
  3155. treeInit: function(ctx) {
  3156. //this.debug("Fancytree.treeInit()");
  3157. this.treeLoad(ctx);
  3158. },
  3159. /** Parse Fancytree from source, as configured in the options.
  3160. * @param {EventData} ctx
  3161. * @param {object} [source] new source
  3162. */
  3163. treeLoad: function(ctx, source) {
  3164. var type, $ul,
  3165. tree = ctx.tree,
  3166. $container = ctx.widget.element,
  3167. dfd,
  3168. // calling context for root node
  3169. rootCtx = $.extend({}, ctx, {node: this.rootNode});
  3170. if(tree.rootNode.children){
  3171. this.treeClear(ctx);
  3172. }
  3173. source = source || this.options.source;
  3174. if(!source){
  3175. type = $container.data("type") || "html";
  3176. switch(type){
  3177. case "html":
  3178. $ul = $container.find(">ul:first");
  3179. $ul.addClass("ui-fancytree-source ui-helper-hidden");
  3180. source = $.ui.fancytree.parseHtml($ul);
  3181. break;
  3182. case "json":
  3183. // $().addClass("ui-helper-hidden");
  3184. source = $.parseJSON($container.text());
  3185. if(source.children){
  3186. if(source.title){tree.title = source.title;}
  3187. source = source.children;
  3188. }
  3189. break;
  3190. default:
  3191. $.error("Invalid data-type: " + type);
  3192. }
  3193. }else if(typeof source === "string"){
  3194. // TODO: source is an element ID
  3195. _raiseNotImplemented();
  3196. }
  3197. // $container.addClass("ui-widget ui-widget-content ui-corner-all");
  3198. // Trigger fancytreeinit after nodes have been loaded
  3199. dfd = this.nodeLoadChildren(rootCtx, source).done(function(){
  3200. tree.render();
  3201. if( ctx.options.selectMode === 3 ){
  3202. tree.rootNode.fixSelection3FromEndNodes();
  3203. }
  3204. tree._triggerTreeEvent("init", true);
  3205. }).fail(function(){
  3206. tree.render();
  3207. tree._triggerTreeEvent("init", false);
  3208. });
  3209. return dfd;
  3210. },
  3211. treeSetFocus: function(ctx, flag, _calledByNodeSetFocus) {
  3212. flag = (flag !== false);
  3213. // this.debug("treeSetFocus(" + flag + "), _calledByNodeSetFocus: " + _calledByNodeSetFocus);
  3214. // this.debug(" focusNode: " + this.focusNode);
  3215. // this.debug(" activeNode: " + this.activeNode);
  3216. if( flag !== this.hasFocus() ){
  3217. this._hasFocus = flag;
  3218. this.$container.toggleClass("fancytree-treefocus", flag);
  3219. this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
  3220. }
  3221. }
  3222. });
  3223. /* ******************************************************************************
  3224. * jQuery UI widget boilerplate
  3225. */
  3226. /**
  3227. * This constructor is not called directly. Use `$(selector).fancytre({})`
  3228. * to initialize the plugin instead.
  3229. *
  3230. * @class ui.fancytree
  3231. * @classdesc The plugin (derrived from <a href=" http://api.jqueryui.com/jQuery.widget/">jQuery.Widget</a>).<br>
  3232. * <pre class="sh_javascript sunlight-highlight-javascript">// Access instance methods and members:
  3233. * var tree = $(selector).fancytree("getTree");
  3234. * // Access static members:
  3235. * alert($.ui.fancytree.version);
  3236. * </pre>
  3237. */
  3238. $.widget("ui.fancytree",
  3239. /** @lends ui.fancytree# */
  3240. {
  3241. /**These options will be used as defaults
  3242. * @type {FancytreeOptions}
  3243. */
  3244. options:
  3245. {
  3246. activeVisible: true,
  3247. ajax: {
  3248. type: "GET",
  3249. cache: false, // false: Append random '_' argument to the request url to prevent caching.
  3250. // timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
  3251. dataType: "json" // Expect json format and pass json object to callbacks.
  3252. }, //
  3253. aria: false, // TODO: default to true
  3254. autoActivate: true,
  3255. autoCollapse: false,
  3256. // autoFocus: false,
  3257. autoScroll: false,
  3258. checkbox: false,
  3259. /**defines click behavior*/
  3260. clickFolderMode: 4,
  3261. debugLevel: null, // 0..2 (null: use global setting $.ui.fancytree.debugInfo)
  3262. disabled: false, // TODO: required anymore?
  3263. enableAspx: true, // TODO: document
  3264. extensions: [],
  3265. fx: { height: "toggle", duration: 200 },
  3266. generateIds: false,
  3267. icons: true,
  3268. idPrefix: "ft_",
  3269. keyboard: true,
  3270. keyPathSeparator: "/",
  3271. minExpandLevel: 1,
  3272. selectMode: 2,
  3273. strings: {
  3274. loading: "Loading&#8230;",
  3275. loadError: "Load error!"
  3276. },
  3277. tabbable: true,
  3278. titlesTabbable: false,
  3279. _classNames: {
  3280. node: "fancytree-node",
  3281. folder: "fancytree-folder",
  3282. combinedExpanderPrefix: "fancytree-exp-",
  3283. combinedIconPrefix: "fancytree-ico-",
  3284. hasChildren: "fancytree-has-children",
  3285. active: "fancytree-active",
  3286. selected: "fancytree-selected",
  3287. expanded: "fancytree-expanded",
  3288. lazy: "fancytree-lazy",
  3289. focused: "fancytree-focused",
  3290. partsel: "fancytree-partsel",
  3291. lastsib: "fancytree-lastsib",
  3292. loading: "fancytree-loading",
  3293. error: "fancytree-error"
  3294. },
  3295. // events
  3296. lazyLoad: null,
  3297. postProcess: null
  3298. },
  3299. /* Set up the widget, Called on first $().fancytree() */
  3300. _create: function() {
  3301. this.tree = new Fancytree(this);
  3302. this.$source = this.source || this.element.data("type") === "json" ? this.element
  3303. : this.element.find(">ul:first");
  3304. // Subclass Fancytree instance with all enabled extensions
  3305. var extension, extName, i,
  3306. extensions = this.options.extensions,
  3307. base = this.tree;
  3308. for(i=0; i<extensions.length; i++){
  3309. extName = extensions[i];
  3310. extension = $.ui.fancytree._extensions[extName];
  3311. if(!extension){
  3312. $.error("Could not apply extension '" + extName + "' (it is not registered, did you forget to include it?)");
  3313. }
  3314. // Add extension options as tree.options.EXTENSION
  3315. // _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName);
  3316. this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
  3317. // Add a namespace tree.ext.EXTENSION, to hold instance data
  3318. _assert(this.tree.ext[extName] === undefined, "Extension name must not exist as Fancytree.ext attribute: '" + extName + "'");
  3319. // this.tree[extName] = extension;
  3320. this.tree.ext[extName] = {};
  3321. // Subclass Fancytree methods using proxies.
  3322. _subclassObject(this.tree, base, extension, extName);
  3323. // current extension becomes base for the next extension
  3324. base = extension;
  3325. }
  3326. //
  3327. this.tree._callHook("treeCreate", this.tree);
  3328. // Note: 'fancytreecreate' event is fired by widget base class
  3329. // this.tree._triggerTreeEvent("create");
  3330. },
  3331. /* Called on every $().fancytree() */
  3332. _init: function() {
  3333. this.tree._callHook("treeInit", this.tree);
  3334. // TODO: currently we call bind after treeInit, because treeInit
  3335. // might change tree.$container.
  3336. // It would be better, to move ebent binding into hooks altogether
  3337. this._bind();
  3338. },
  3339. /* Use the _setOption method to respond to changes to options */
  3340. _setOption: function(key, value) {
  3341. var callDefault = true,
  3342. rerender = false;
  3343. switch( key ) {
  3344. case "aria":
  3345. case "checkbox":
  3346. case "icons":
  3347. case "minExpandLevel":
  3348. case "tabbable":
  3349. // case "nolink":
  3350. this.tree._callHook("treeCreate", this.tree);
  3351. rerender = true;
  3352. break;
  3353. case "source":
  3354. callDefault = false;
  3355. this.tree._callHook("treeLoad", this.tree, value);
  3356. break;
  3357. }
  3358. this.tree.debug("set option " + key + "=" + value + " <" + typeof(value) + ">");
  3359. if(callDefault){
  3360. // In jQuery UI 1.8, you have to manually invoke the _setOption method from the base widget
  3361. $.Widget.prototype._setOption.apply(this, arguments);
  3362. // TODO: In jQuery UI 1.9 and above, you use the _super method instead
  3363. // this._super( "_setOption", key, value );
  3364. }
  3365. if(rerender){
  3366. this.tree.render(true, false); // force, not-deep
  3367. }
  3368. },
  3369. /** Use the destroy method to clean up any modifications your widget has made to the DOM */
  3370. destroy: function() {
  3371. this._unbind();
  3372. this.tree._callHook("treeDestroy", this.tree);
  3373. // this.element.removeClass("ui-widget ui-widget-content ui-corner-all");
  3374. this.tree.$div.find(">ul.fancytree-container").remove();
  3375. this.$source && this.$source.removeClass("ui-helper-hidden");
  3376. // In jQuery UI 1.8, you must invoke the destroy method from the base widget
  3377. $.Widget.prototype.destroy.call(this);
  3378. // TODO: delete tree and nodes to make garbage collect easier?
  3379. // TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
  3380. },
  3381. // -------------------------------------------------------------------------
  3382. /* Remove all event handlers for our namespace */
  3383. _unbind: function() {
  3384. var ns = this.tree._ns;
  3385. this.element.unbind(ns);
  3386. this.tree.$container.unbind(ns);
  3387. $(document).unbind(ns);
  3388. },
  3389. /* Add mouse and kyboard handlers to the container */
  3390. _bind: function() {
  3391. var that = this,
  3392. opts = this.options,
  3393. tree = this.tree,
  3394. ns = tree._ns
  3395. // selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" )
  3396. ;
  3397. // Remove all previuous handlers for this tree
  3398. this._unbind();
  3399. //alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container);
  3400. // tree.debug("bind events; container: ", tree.$container);
  3401. tree.$container.on("focusin" + ns + " focusout" + ns, function(event){
  3402. var node = FT.getNode(event),
  3403. flag = (event.type === "focusin");
  3404. // tree.debug("Tree container got event " + event.type, node, event);
  3405. // tree.treeOnFocusInOut.call(tree, event);
  3406. if(node){
  3407. // For example clicking into an <input> that is part of a node
  3408. tree._callHook("nodeSetFocus", node, flag);
  3409. }else{
  3410. tree._callHook("treeSetFocus", tree, flag);
  3411. }
  3412. }).on("selectstart" + ns, "span.fancytree-title", function(event){
  3413. // prevent mouse-drags to select text ranges
  3414. // tree.debug("<span title> got event " + event.type);
  3415. event.preventDefault();
  3416. }).on("keydown" + ns, function(event){
  3417. // TODO: also bind keyup and keypress
  3418. // tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus());
  3419. // if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){
  3420. if(opts.disabled || opts.keyboard === false ){
  3421. return true;
  3422. }
  3423. var res,
  3424. node = tree.focusNode, // node may be null
  3425. ctx = tree._makeHookContext(node || tree, event),
  3426. prevPhase = tree.phase;
  3427. try {
  3428. tree.phase = "userEvent";
  3429. // If a 'fancytreekeydown' handler returns false, skip the default
  3430. // handling (implemented by tree.nodeKeydown()).
  3431. if(node){
  3432. res = tree._triggerNodeEvent("keydown", node, event);
  3433. }else{
  3434. res = tree._triggerTreeEvent("keydown", event);
  3435. }
  3436. if ( res === "preventNav" ){
  3437. res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls
  3438. } else if ( res !== false ){
  3439. res = tree._callHook("nodeKeydown", ctx);
  3440. }
  3441. return res;
  3442. } finally {
  3443. tree.phase = prevPhase;
  3444. }
  3445. }).on("click" + ns + " dblclick" + ns, function(event){
  3446. if(opts.disabled){
  3447. return true;
  3448. }
  3449. var ctx,
  3450. et = FT.getEventTarget(event),
  3451. node = et.node,
  3452. tree = that.tree,
  3453. prevPhase = tree.phase;
  3454. if( !node ){
  3455. return true; // Allow bubbling of other events
  3456. }
  3457. ctx = tree._makeHookContext(node, event);
  3458. // that.tree.debug("event(" + event.type + "): node: ", node);
  3459. try {
  3460. tree.phase = "userEvent";
  3461. switch(event.type) {
  3462. case "click":
  3463. ctx.targetType = et.type;
  3464. return ( tree._triggerNodeEvent("click", ctx, event) === false ) ? false : tree._callHook("nodeClick", ctx);
  3465. case "dblclick":
  3466. ctx.targetType = et.type;
  3467. return ( tree._triggerNodeEvent("dblclick", ctx, event) === false ) ? false : tree._callHook("nodeDblclick", ctx);
  3468. }
  3469. // } catch(e) {
  3470. // // var _ = null; // issue 117 // TODO
  3471. // $.error(e);
  3472. } finally {
  3473. tree.phase = prevPhase;
  3474. }
  3475. });
  3476. },
  3477. /** @returns {FancytreeNode} the active node or null */
  3478. getActiveNode: function() {
  3479. return this.tree.activeNode;
  3480. },
  3481. /**
  3482. * @param {string} key
  3483. * @returns {FancytreeNode} the matching node or null
  3484. */
  3485. getNodeByKey: function(key) {
  3486. return this.tree.getNodeByKey(key);
  3487. },
  3488. /** @returns {FancytreeNode} the invisible system root node */
  3489. getRootNode: function() {
  3490. return this.tree.rootNode;
  3491. },
  3492. /** @returns {Fancytree} the current tree instance */
  3493. getTree: function() {
  3494. return this.tree;
  3495. }
  3496. });
  3497. // $.ui.fancytree was created by the widget factory. Create a local shortcut:
  3498. FT = $.ui.fancytree;
  3499. /*
  3500. * Static members in the `$.ui.fancytree` namespace.
  3501. *
  3502. * @example:
  3503. * alert(""version: " + $.ui.fancytree.version);
  3504. * var node = $.ui.fancytree.getNode(element);
  3505. */
  3506. $.extend($.ui.fancytree,
  3507. /** @lends ui.fancytree */
  3508. {
  3509. /** @type {string} */
  3510. version: "2.0.0-7",
  3511. /** @type {string} */
  3512. buildType: "release",
  3513. /** @type {int} */
  3514. debugLevel: 1, // used by $.ui.fancytree.debug() and as default for tree.options.debugLevel
  3515. _nextId: 1,
  3516. _nextNodeKey: 1,
  3517. _extensions: {},
  3518. // focusTree: null,
  3519. /** Expose class object as $.ui.fancytree._FancytreeClass */
  3520. _FancytreeClass: Fancytree,
  3521. /** Expose class object as $.ui.fancytree._FancytreeNodeClass */
  3522. _FancytreeNodeClass: FancytreeNode,
  3523. /* Feature checks to provide backwards compatibility */
  3524. jquerySupports: {
  3525. // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
  3526. positionMyOfs: isVersionAtLeast($.ui.version, 1, 9)
  3527. },
  3528. assert: function(cond, msg){
  3529. return _assert(cond, msg);
  3530. },
  3531. debug: function(msg){
  3532. /*jshint expr:true */
  3533. ($.ui.fancytree.debugLevel >= 2) && consoleApply("log", arguments);
  3534. },
  3535. error: function(msg){
  3536. consoleApply("error", arguments);
  3537. },
  3538. /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
  3539. *
  3540. * @static
  3541. * @param {Event} event Mouse event, e.g. click, ...
  3542. * @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
  3543. */
  3544. getEventTargetType: function(event){
  3545. return this.getEventTarget(event).type;
  3546. },
  3547. /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
  3548. *
  3549. * @param {Event} event Mouse event, e.g. click, ...
  3550. * @returns {object} Return a {node: FancytreeNode, type: TYPE} object
  3551. * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
  3552. */
  3553. getEventTarget: function(event){
  3554. var tcn = event && event.target ? event.target.className : "",
  3555. res = {node: this.getNode(event.target), type: undefined};
  3556. // tcn may contains UI themeroller or Font Awesome classes, so we use
  3557. // a fast version of $(res.node).hasClass()
  3558. // See http://jsperf.com/test-for-classname/2
  3559. if( /\bfancytree-title\b/.test(tcn) ){
  3560. res.type = "title";
  3561. }else if( /\bfancytree-expander\b/.test(tcn) ){
  3562. res.type = (res.node.hasChildren() === false ? "prefix" : "expander");
  3563. }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){
  3564. res.type = "checkbox";
  3565. }else if( /\bfancytree-icon\b/.test(tcn) ){
  3566. res.type = "icon";
  3567. }else if( /\bfancytree-node\b/.test(tcn) ){
  3568. // TODO: issue #93 (http://code.google.com/p/fancytree/issues/detail?id=93)
  3569. // res.type = this._getTypeForOuterNodeEvent(event);
  3570. res.type = "title";
  3571. }
  3572. return res;
  3573. },
  3574. /** Return a FancytreeNode instance from element.
  3575. *
  3576. * @param {Element | jQueryObject | Event} el
  3577. * @returns {FancytreeNode} matching node or null
  3578. */
  3579. getNode: function(el){
  3580. if(el instanceof FancytreeNode){
  3581. return el; // el already was a FancytreeNode
  3582. }else if(el.selector !== undefined){
  3583. el = el[0]; // el was a jQuery object: use the DOM element
  3584. }else if(el.originalEvent !== undefined){
  3585. el = el.target; // el was an Event
  3586. }
  3587. while( el ) {
  3588. if(el.ftnode) {
  3589. return el.ftnode;
  3590. }
  3591. el = el.parentNode;
  3592. }
  3593. return null;
  3594. },
  3595. /* Return a Fancytree instance from element.
  3596. * TODO: this function could help to get around the data('fancytree') / data('ui-fancytree') problem
  3597. * @param {Element | jQueryObject | Event} el
  3598. * @returns {Fancytree} matching tree or null
  3599. * /
  3600. getTree: function(el){
  3601. if(el instanceof Fancytree){
  3602. return el; // el already was a Fancytree
  3603. }else if(el.selector !== undefined){
  3604. el = el[0]; // el was a jQuery object: use the DOM element
  3605. }else if(el.originalEvent !== undefined){
  3606. el = el.target; // el was an Event
  3607. }
  3608. ...
  3609. return null;
  3610. },
  3611. */
  3612. info: function(msg){
  3613. /*jshint expr:true */
  3614. ($.ui.fancytree.debugLevel >= 1) && consoleApply("info", arguments);
  3615. },
  3616. /**
  3617. * Parse tree data from HTML <ul> markup
  3618. *
  3619. * @param {jQueryObject} $ul
  3620. * @returns {NodeData[]}
  3621. */
  3622. parseHtml: function($ul) {
  3623. // TODO: understand this:
  3624. /*jshint validthis:true */
  3625. var $children = $ul.find(">li"),
  3626. extraClasses, i, l, iPos, tmp, classes, className,
  3627. children = [];
  3628. // that = this;
  3629. $children.each(function() {
  3630. var allData, jsonData,
  3631. $li = $(this),
  3632. $liSpan = $li.find(">span:first", this),
  3633. $liA = $liSpan.length ? null : $li.find(">a:first"),
  3634. d = { tooltip: null, data: {} };
  3635. if( $liSpan.length ) {
  3636. d.title = $liSpan.html();
  3637. } else if( $liA && $liA.length ) {
  3638. // If a <li><a> tag is specified, use it literally and extract href/target.
  3639. d.title = $liA.html();
  3640. d.data.href = $liA.attr("href");
  3641. d.data.target = $liA.attr("target");
  3642. d.tooltip = $liA.attr("title");
  3643. } else {
  3644. // If only a <li> tag is specified, use the trimmed string up to
  3645. // the next child <ul> tag.
  3646. d.title = $li.html();
  3647. iPos = d.title.search(/<ul/i);
  3648. if( iPos >= 0 ){
  3649. d.title = d.title.substring(0, iPos);
  3650. }
  3651. }
  3652. d.title = $.trim(d.title);
  3653. // Make sure all fields exist
  3654. for(i=0, l=CLASS_ATTRS.length; i<l; i++){
  3655. d[CLASS_ATTRS[i]] = undefined;
  3656. }
  3657. // Initialize to `true`, if class is set and collect extraClasses
  3658. classes = this.className.split(" ");
  3659. extraClasses = [];
  3660. for(i=0, l=classes.length; i<l; i++){
  3661. className = classes[i];
  3662. if(CLASS_ATTR_MAP[className]){
  3663. d[className] = true;
  3664. }else{
  3665. extraClasses.push(className);
  3666. }
  3667. }
  3668. d.extraClasses = extraClasses.join(" ");
  3669. // Parse node options from ID, title and class attributes
  3670. tmp = $li.attr("title");
  3671. if( tmp ){
  3672. d.tooltip = tmp; // overrides <a title='...'>
  3673. }
  3674. tmp = $li.attr("id");
  3675. if( tmp ){
  3676. d.key = tmp;
  3677. }
  3678. // Add <li data-NAME='...'> as node.data.NAME
  3679. // See http://api.jquery.com/data/#data-html5
  3680. allData = $li.data();
  3681. // alert("d: " + JSON.stringify(allData));
  3682. if(allData && !$.isEmptyObject(allData)) {
  3683. // Special handling for <li data-json='...'>
  3684. jsonData = allData.json;
  3685. delete allData.json;
  3686. $.extend(d.data, allData);
  3687. // If a 'data-json' attribute is present, evaluate and add to node.data
  3688. if(jsonData) {
  3689. // alert("$li.data()" + JSON.stringify(jsonData));
  3690. // <li data-json='...'> is already returned as object
  3691. // see http://api.jquery.com/data/#data-html5
  3692. $.extend(d.data, jsonData);
  3693. }
  3694. }
  3695. // that.debug("parse ", d);
  3696. // var childNode = parentTreeNode.addChild(data);
  3697. // Recursive reading of child nodes, if LI tag contains an UL tag
  3698. $ul = $li.find(">ul:first");
  3699. if( $ul.length ) {
  3700. d.children = $.ui.fancytree.parseHtml($ul);
  3701. }else{
  3702. d.children = d.lazy ? undefined : null;
  3703. }
  3704. children.push(d);
  3705. // FT.debug("parse ", d, children);
  3706. });
  3707. return children;
  3708. },
  3709. /** Add Fancytree extension definition to the list of globally available extensions.
  3710. *
  3711. * @param {Object} definition
  3712. */
  3713. registerExtension: function(definition){
  3714. _assert(definition.name != null, "extensions must have a `name` property.");
  3715. _assert(definition.version != null, "extensions must have a `version` property.");
  3716. $.ui.fancytree._extensions[definition.name] = definition;
  3717. },
  3718. warn: function(msg){
  3719. consoleApply("warn", arguments);
  3720. }
  3721. });
  3722. // Use $.ui.fancytree.debugLevel as default for tree.options.debugLevel
  3723. //$.ui.fancytree.debug($.ui.fancytree.prototype);
  3724. //$.ui.fancytree.prototype.options.debugLevel = $.ui.fancytree.debugLevel;
  3725. /* *****************************************************************************
  3726. * Register AMD
  3727. */
  3728. // http://stackoverflow.com/questions/10918063/how-to-make-a-jquery-plugin-loadable-with-requirejs
  3729. // if ( typeof define === "function" && define.amd && define.amd.jQuery ) {
  3730. // define( "jquery", [], function () { return jQuery; } );
  3731. // }
  3732. // TODO: maybe like so:?
  3733. // https://raw.github.com/malsup/blockui/master/jquery.blockUI.js
  3734. /*
  3735. if( typeof define === "function" && define.amd ) {
  3736. define( ["jquery"], function () {
  3737. return jQuery.ui.fancytree;
  3738. });
  3739. }
  3740. */
  3741. }(jQuery, window, document));
  3742. /*!
  3743. * jquery.fancytree.dnd.js
  3744. *
  3745. * Drag-and-drop support.
  3746. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  3747. *
  3748. * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
  3749. *
  3750. * Released under the MIT license
  3751. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  3752. *
  3753. * @version 2.0.0-7
  3754. * @date 2014-03-09T20:32
  3755. */
  3756. ;(function($, window, document, undefined) {
  3757. "use strict";
  3758. /* *****************************************************************************
  3759. * Private functions and variables
  3760. */
  3761. var logMsg = $.ui.fancytree.debug,
  3762. didRegisterDnd = false;
  3763. /* Convert number to string and prepend +/-; return empty string for 0.*/
  3764. function offsetString(n){
  3765. return n === 0 ? "" : (( n > 0 ) ? ("+" + n) : ("" + n));
  3766. }
  3767. /* *****************************************************************************
  3768. * Drag and drop support
  3769. */
  3770. function _initDragAndDrop(tree) {
  3771. var dnd = tree.options.dnd || null;
  3772. // Register 'connectToFancytree' option with ui.draggable
  3773. if(dnd /*&& (dnd.dragStart || dnd.dragDrop)*/) {
  3774. _registerDnd();
  3775. }
  3776. // Attach ui.draggable to this Fancytree instance
  3777. if(dnd && dnd.dragStart ) {
  3778. tree.widget.element.draggable({
  3779. addClasses: false,
  3780. appendTo: "body",
  3781. containment: false,
  3782. delay: 0,
  3783. distance: 4,
  3784. // TODO: merge Dynatree issue 419
  3785. revert: false,
  3786. scroll: true, // issue 244: enable scrolling (if ul.fancytree-container)
  3787. scrollSpeed: 7,
  3788. scrollSensitivity: 10,
  3789. // Delegate draggable.start, drag, and stop events to our handler
  3790. connectToFancytree: true,
  3791. // Let source tree create the helper element
  3792. helper: function(event) {
  3793. var sourceNode = $.ui.fancytree.getNode(event.target);
  3794. if(!sourceNode){ // issue 211
  3795. // TODO: remove this hint, when we understand when it happens
  3796. return "<div>ERROR?: helper requested but sourceNode not found</div>";
  3797. }
  3798. return sourceNode.tree.ext.dnd._onDragEvent("helper", sourceNode, null, event, null, null);
  3799. },
  3800. start: function(event, ui) {
  3801. // var sourceNode = $.ui.fancytree.getNode(event.target);
  3802. // don't return false if sourceNode == null (see issue 268)
  3803. }
  3804. });
  3805. }
  3806. // Attach ui.droppable to this Fancytree instance
  3807. if(dnd && dnd.dragDrop) {
  3808. tree.widget.element.droppable({
  3809. addClasses: false,
  3810. tolerance: "intersect",
  3811. greedy: false
  3812. /*
  3813. ,
  3814. activate: function(event, ui) {
  3815. logMsg("droppable - activate", event, ui, this);
  3816. },
  3817. create: function(event, ui) {
  3818. logMsg("droppable - create", event, ui);
  3819. },
  3820. deactivate: function(event, ui) {
  3821. logMsg("droppable - deactivate", event, ui);
  3822. },
  3823. drop: function(event, ui) {
  3824. logMsg("droppable - drop", event, ui);
  3825. },
  3826. out: function(event, ui) {
  3827. logMsg("droppable - out", event, ui);
  3828. },
  3829. over: function(event, ui) {
  3830. logMsg("droppable - over", event, ui);
  3831. }
  3832. */
  3833. });
  3834. }
  3835. }
  3836. //--- Extend ui.draggable event handling --------------------------------------
  3837. function _registerDnd() {
  3838. if(didRegisterDnd){
  3839. return;
  3840. }
  3841. // Register proxy-functions for draggable.start/drag/stop
  3842. $.ui.plugin.add("draggable", "connectToFancytree", {
  3843. start: function(event, ui) {
  3844. // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
  3845. var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
  3846. sourceNode = ui.helper.data("ftSourceNode") || null;
  3847. // logMsg("draggable-connectToFancytree.start, %s", sourceNode);
  3848. // logMsg(" this: %o", this);
  3849. // logMsg(" event: %o", event);
  3850. // logMsg(" draggable: %o", draggable);
  3851. // logMsg(" ui: %o", ui);
  3852. if(sourceNode) {
  3853. // Adjust helper offset, so cursor is slightly outside top/left corner
  3854. draggable.offset.click.top = -2;
  3855. draggable.offset.click.left = + 16;
  3856. // logMsg(" draggable2: %o", draggable);
  3857. // logMsg(" draggable.offset.click FIXED: %s/%s", draggable.offset.click.left, draggable.offset.click.top);
  3858. // Trigger dragStart event
  3859. // TODO: when called as connectTo..., the return value is ignored(?)
  3860. return sourceNode.tree.ext.dnd._onDragEvent("start", sourceNode, null, event, ui, draggable);
  3861. }
  3862. },
  3863. drag: function(event, ui) {
  3864. // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
  3865. var isHelper,
  3866. draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
  3867. sourceNode = ui.helper.data("ftSourceNode") || null,
  3868. prevTargetNode = ui.helper.data("ftTargetNode") || null,
  3869. targetNode = $.ui.fancytree.getNode(event.target);
  3870. // logMsg("$.ui.fancytree.getNode(%o): %s", event.target, targetNode);
  3871. // logMsg("connectToFancytree.drag: helper: %o", ui.helper[0]);
  3872. if(event.target && !targetNode){
  3873. // We got a drag event, but the targetNode could not be found
  3874. // at the event location. This may happen,
  3875. // 1. if the mouse jumped over the drag helper,
  3876. // 2. or if a non-fancytree element is dragged
  3877. // We ignore it:
  3878. isHelper = $(event.target).closest("div.fancytree-drag-helper,#fancytree-drop-marker").length > 0;
  3879. if(isHelper){
  3880. logMsg("Drag event over helper: ignored.");
  3881. return;
  3882. }
  3883. }
  3884. // logMsg("draggable-connectToFancytree.drag: targetNode(from event): %s, ftTargetNode: %s", targetNode, ui.helper.data("ftTargetNode"));
  3885. ui.helper.data("ftTargetNode", targetNode);
  3886. // Leaving a tree node
  3887. if(prevTargetNode && prevTargetNode !== targetNode ) {
  3888. prevTargetNode.tree.ext.dnd._onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
  3889. }
  3890. if(targetNode){
  3891. if(!targetNode.tree.options.dnd.dragDrop) {
  3892. // not enabled as drop target
  3893. } else if(targetNode === prevTargetNode) {
  3894. // Moving over same node
  3895. targetNode.tree.ext.dnd._onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
  3896. }else{
  3897. // Entering this node first time
  3898. targetNode.tree.ext.dnd._onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
  3899. }
  3900. }
  3901. // else go ahead with standard event handling
  3902. },
  3903. stop: function(event, ui) {
  3904. // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
  3905. var draggable = $(this).data("ui-draggable") || $(this).data("draggable"),
  3906. sourceNode = ui.helper.data("ftSourceNode") || null,
  3907. targetNode = ui.helper.data("ftTargetNode") || null,
  3908. // mouseDownEvent = draggable._mouseDownEvent,
  3909. eventType = event.type,
  3910. dropped = (eventType === "mouseup" && event.which === 1);
  3911. // logMsg("draggable-connectToFancytree.stop: targetNode(from event): %s, ftTargetNode: %s", targetNode, ui.helper.data("ftTargetNode"));
  3912. // logMsg("draggable-connectToFancytree.stop, %s", sourceNode);
  3913. // logMsg(" type: %o, downEvent: %o, upEvent: %o", eventType, mouseDownEvent, event);
  3914. // logMsg(" targetNode: %o", targetNode);
  3915. if(!dropped){
  3916. logMsg("Drag was cancelled");
  3917. }
  3918. if(targetNode) {
  3919. if(dropped){
  3920. targetNode.tree.ext.dnd._onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
  3921. }
  3922. targetNode.tree.ext.dnd._onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
  3923. }
  3924. if(sourceNode){
  3925. sourceNode.tree.ext.dnd._onDragEvent("stop", sourceNode, null, event, ui, draggable);
  3926. }
  3927. }
  3928. });
  3929. didRegisterDnd = true;
  3930. }
  3931. /* *****************************************************************************
  3932. *
  3933. */
  3934. $.ui.fancytree.registerExtension(
  3935. {
  3936. name: "dnd",
  3937. version: "0.1.0",
  3938. // Default options for this extension.
  3939. options: {
  3940. // Make tree nodes draggable:
  3941. dragStart: null, // Callback(sourceNode, data), return true, to enable dnd
  3942. dragStop: null, // Callback(sourceNode, data)
  3943. // helper: null,
  3944. // Make tree nodes accept draggables
  3945. autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
  3946. preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
  3947. preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
  3948. dragEnter: null, // Callback(targetNode, data)
  3949. dragOver: null, // Callback(targetNode, data)
  3950. dragDrop: null, // Callback(targetNode, data)
  3951. dragLeave: null // Callback(targetNode, data)
  3952. },
  3953. // Override virtual methods for this extension.
  3954. // `this` : Fancytree instance
  3955. // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
  3956. treeInit: function(ctx){
  3957. var tree = ctx.tree;
  3958. this._super(ctx);
  3959. _initDragAndDrop(tree);
  3960. },
  3961. /* Override key handler in order to cancel dnd on escape.*/
  3962. nodeKeydown: function(ctx) {
  3963. var event = ctx.originalEvent;
  3964. if( event.which === $.ui.keyCode.ESCAPE) {
  3965. this._local._cancelDrag();
  3966. }
  3967. return this._super(ctx);
  3968. },
  3969. /* Display drop marker according to hitMode ('after', 'before', 'over', 'out', 'start', 'stop'). */
  3970. _setDndStatus: function(sourceNode, targetNode, helper, hitMode, accept) {
  3971. var posOpts,
  3972. markerOffsetX = 0,
  3973. markerAt = "center",
  3974. instData = this._local,
  3975. $source = sourceNode ? $(sourceNode.span) : null,
  3976. $target = $(targetNode.span);
  3977. if( !instData.$dropMarker ) {
  3978. instData.$dropMarker = $("<div id='fancytree-drop-marker'></div>")
  3979. .hide()
  3980. .css({"z-index": 1000})
  3981. .prependTo($(this.$div).parent());
  3982. // .prependTo("body");
  3983. // logMsg("Creating marker: %o", this.$dropMarker);
  3984. }
  3985. /*
  3986. if(hitMode === "start"){
  3987. }
  3988. if(hitMode === "stop"){
  3989. // sourceNode.removeClass("fancytree-drop-target");
  3990. }
  3991. */
  3992. // this.$dropMarker.attr("class", hitMode);
  3993. if(hitMode === "after" || hitMode === "before" || hitMode === "over"){
  3994. // $source && $source.addClass("fancytree-drag-source");
  3995. // $target.addClass("fancytree-drop-target");
  3996. switch(hitMode){
  3997. case "before":
  3998. instData.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-over");
  3999. instData.$dropMarker.addClass("fancytree-drop-before");
  4000. markerAt = "top";
  4001. break;
  4002. case "after":
  4003. instData.$dropMarker.removeClass("fancytree-drop-before fancytree-drop-over");
  4004. instData.$dropMarker.addClass("fancytree-drop-after");
  4005. markerAt = "bottom";
  4006. break;
  4007. default:
  4008. instData.$dropMarker.removeClass("fancytree-drop-after fancytree-drop-before");
  4009. instData.$dropMarker.addClass("fancytree-drop-over");
  4010. $target.addClass("fancytree-drop-target");
  4011. markerOffsetX = 8;
  4012. }
  4013. if( $.ui.fancytree.jquerySupports.positionMyOfs ){
  4014. posOpts = {
  4015. my: "left" + offsetString(markerOffsetX) + " center",
  4016. at: "left " + markerAt,
  4017. of: $target
  4018. };
  4019. } else {
  4020. posOpts = {
  4021. my: "left center",
  4022. at: "left " + markerAt,
  4023. of: $target,
  4024. offset: "" + markerOffsetX + " 0"
  4025. };
  4026. }
  4027. instData.$dropMarker
  4028. .show()
  4029. .position(posOpts);
  4030. // helper.addClass("fancytree-drop-hover");
  4031. } else {
  4032. // $source && $source.removeClass("fancytree-drag-source");
  4033. $target.removeClass("fancytree-drop-target");
  4034. instData.$dropMarker.hide();
  4035. // helper.removeClass("fancytree-drop-hover");
  4036. }
  4037. if(hitMode === "after"){
  4038. $target.addClass("fancytree-drop-after");
  4039. } else {
  4040. $target.removeClass("fancytree-drop-after");
  4041. }
  4042. if(hitMode === "before"){
  4043. $target.addClass("fancytree-drop-before");
  4044. } else {
  4045. $target.removeClass("fancytree-drop-before");
  4046. }
  4047. if(accept === true){
  4048. if($source){
  4049. $source.addClass("fancytree-drop-accept");
  4050. }
  4051. $target.addClass("fancytree-drop-accept");
  4052. helper.addClass("fancytree-drop-accept");
  4053. }else{
  4054. if($source){
  4055. $source.removeClass("fancytree-drop-accept");
  4056. }
  4057. $target.removeClass("fancytree-drop-accept");
  4058. helper.removeClass("fancytree-drop-accept");
  4059. }
  4060. if(accept === false){
  4061. if($source){
  4062. $source.addClass("fancytree-drop-reject");
  4063. }
  4064. $target.addClass("fancytree-drop-reject");
  4065. helper.addClass("fancytree-drop-reject");
  4066. }else{
  4067. if($source){
  4068. $source.removeClass("fancytree-drop-reject");
  4069. }
  4070. $target.removeClass("fancytree-drop-reject");
  4071. helper.removeClass("fancytree-drop-reject");
  4072. }
  4073. },
  4074. /*
  4075. * Handles drag'n'drop functionality.
  4076. *
  4077. * A standard jQuery drag-and-drop process may generate these calls:
  4078. *
  4079. * draggable helper():
  4080. * _onDragEvent("helper", sourceNode, null, event, null, null);
  4081. * start:
  4082. * _onDragEvent("start", sourceNode, null, event, ui, draggable);
  4083. * drag:
  4084. * _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
  4085. * _onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
  4086. * _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
  4087. * stop:
  4088. * _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
  4089. * _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
  4090. * _onDragEvent("stop", sourceNode, null, event, ui, draggable);
  4091. */
  4092. _onDragEvent: function(eventName, node, otherNode, event, ui, draggable) {
  4093. if(eventName !== "over"){
  4094. logMsg("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this);
  4095. }
  4096. var $helper, nodeOfs, relPos, relPos2,
  4097. enterResponse, hitMode, r,
  4098. opts = this.options,
  4099. dnd = opts.dnd,
  4100. ctx = this._makeHookContext(node, event, {otherNode: otherNode, ui: ui, draggable: draggable}),
  4101. res = null,
  4102. nodeTag = $(node.span);
  4103. switch (eventName) {
  4104. case "helper":
  4105. // Only event and node argument is available
  4106. $helper = $("<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>")
  4107. // .append($(event.target).closest("span.fancytree-node").find("span.fancytree-title").clone());
  4108. .append(nodeTag.find("span.fancytree-title").clone());
  4109. // issue 244: helper should be child of scrollParent
  4110. $("ul.fancytree-container", node.tree.$div).append($helper);
  4111. // Attach node reference to helper object
  4112. $helper.data("ftSourceNode", node);
  4113. // logMsg("helper=%o", $helper);
  4114. // logMsg("helper.sourceNode=%o", $helper.data("ftSourceNode"));
  4115. res = $helper;
  4116. break;
  4117. case "start":
  4118. if( node.isStatusNode() ) {
  4119. res = false;
  4120. } else if(dnd.dragStart) {
  4121. res = dnd.dragStart(node, ctx);
  4122. }
  4123. if(res === false) {
  4124. this.debug("tree.dragStart() cancelled");
  4125. //draggable._clear();
  4126. // NOTE: the return value seems to be ignored (drag is not canceled, when false is returned)
  4127. // TODO: call this._cancelDrag()?
  4128. ui.helper.trigger("mouseup");
  4129. ui.helper.hide();
  4130. } else {
  4131. nodeTag.addClass("fancytree-drag-source");
  4132. }
  4133. break;
  4134. case "enter":
  4135. if(dnd.preventRecursiveMoves && node.isDescendantOf(otherNode)){
  4136. r = false;
  4137. }else{
  4138. r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null;
  4139. }
  4140. if(!r){
  4141. // convert null, undefined, false to false
  4142. res = false;
  4143. }else if ( $.isArray(r) ) {
  4144. // TODO: also accept passing an object of this format directly
  4145. res = {
  4146. over: ($.inArray("over", r) >= 0),
  4147. before: ($.inArray("before", r) >= 0),
  4148. after: ($.inArray("after", r) >= 0)
  4149. };
  4150. }else{
  4151. res = {
  4152. over: ((r === true) || (r === "over")),
  4153. before: ((r === true) || (r === "before")),
  4154. after: ((r === true) || (r === "after"))
  4155. };
  4156. }
  4157. ui.helper.data("enterResponse", res);
  4158. logMsg("helper.enterResponse: %o", res);
  4159. break;
  4160. case "over":
  4161. enterResponse = ui.helper.data("enterResponse");
  4162. hitMode = null;
  4163. if(enterResponse === false){
  4164. // Don't call dragOver if onEnter returned false.
  4165. // break;
  4166. } else if(typeof enterResponse === "string") {
  4167. // Use hitMode from onEnter if provided.
  4168. hitMode = enterResponse;
  4169. } else {
  4170. // Calculate hitMode from relative cursor position.
  4171. nodeOfs = nodeTag.offset();
  4172. relPos = { x: event.pageX - nodeOfs.left,
  4173. y: event.pageY - nodeOfs.top };
  4174. relPos2 = { x: relPos.x / nodeTag.width(),
  4175. y: relPos.y / nodeTag.height() };
  4176. if( enterResponse.after && relPos2.y > 0.75 ){
  4177. hitMode = "after";
  4178. } else if(!enterResponse.over && enterResponse.after && relPos2.y > 0.5 ){
  4179. hitMode = "after";
  4180. } else if(enterResponse.before && relPos2.y <= 0.25) {
  4181. hitMode = "before";
  4182. } else if(!enterResponse.over && enterResponse.before && relPos2.y <= 0.5) {
  4183. hitMode = "before";
  4184. } else if(enterResponse.over) {
  4185. hitMode = "over";
  4186. }
  4187. // Prevent no-ops like 'before source node'
  4188. // TODO: these are no-ops when moving nodes, but not in copy mode
  4189. if( dnd.preventVoidMoves ){
  4190. if(node === otherNode){
  4191. logMsg(" drop over source node prevented");
  4192. hitMode = null;
  4193. }else if(hitMode === "before" && otherNode && node === otherNode.getNextSibling()){
  4194. logMsg(" drop after source node prevented");
  4195. hitMode = null;
  4196. }else if(hitMode === "after" && otherNode && node === otherNode.getPrevSibling()){
  4197. logMsg(" drop before source node prevented");
  4198. hitMode = null;
  4199. }else if(hitMode === "over" && otherNode && otherNode.parent === node && otherNode.isLastSibling() ){
  4200. logMsg(" drop last child over own parent prevented");
  4201. hitMode = null;
  4202. }
  4203. }
  4204. // logMsg("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling());
  4205. ui.helper.data("hitMode", hitMode);
  4206. }
  4207. // Auto-expand node (only when 'over' the node, not 'before', or 'after')
  4208. if(hitMode === "over" && dnd.autoExpandMS && node.hasChildren() !== false && !node.expanded) {
  4209. node.scheduleAction("expand", dnd.autoExpandMS);
  4210. }
  4211. if(hitMode && dnd.dragOver){
  4212. // TODO: http://code.google.com/p/dynatree/source/detail?r=625
  4213. ctx.hitMode = hitMode;
  4214. res = dnd.dragOver(node, ctx);
  4215. }
  4216. // issue 332
  4217. // this._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false);
  4218. this._local._setDndStatus(otherNode, node, ui.helper, hitMode, res!==false && hitMode !== null);
  4219. break;
  4220. case "drop":
  4221. hitMode = ui.helper.data("hitMode");
  4222. if(hitMode && dnd.dragDrop){
  4223. ctx.hitMode = hitMode;
  4224. dnd.dragDrop(node, ctx);
  4225. }
  4226. break;
  4227. case "leave":
  4228. // Cancel pending expand request
  4229. node.scheduleAction("cancel");
  4230. ui.helper.data("enterResponse", null);
  4231. ui.helper.data("hitMode", null);
  4232. this._local._setDndStatus(otherNode, node, ui.helper, "out", undefined);
  4233. if(dnd.dragLeave){
  4234. dnd.dragLeave(node, ctx);
  4235. }
  4236. break;
  4237. case "stop":
  4238. nodeTag.removeClass("fancytree-drag-source");
  4239. if(dnd.dragStop){
  4240. dnd.dragStop(node, ctx);
  4241. }
  4242. break;
  4243. default:
  4244. throw "Unsupported drag event: " + eventName;
  4245. }
  4246. return res;
  4247. },
  4248. _cancelDrag: function() {
  4249. var dd = $.ui.ddmanager.current;
  4250. if(dd){
  4251. dd.cancel();
  4252. }
  4253. }
  4254. });
  4255. }(jQuery, window, document));
  4256. /*!
  4257. * jquery.fancytree.edit.js
  4258. *
  4259. * Make node titles editable.
  4260. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  4261. *
  4262. * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
  4263. *
  4264. * Released under the MIT license
  4265. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  4266. *
  4267. * @version 2.0.0-7
  4268. * @date 2014-03-09T20:32
  4269. */
  4270. /**
  4271. * @module fancytree/edit
  4272. */
  4273. ;(function($, window, document, undefined) {
  4274. "use strict";
  4275. /*******************************************************************************
  4276. * Private functions and variables
  4277. */
  4278. var isMac = /Mac/.test(navigator.platform)
  4279. // modifiers = {shift: "shiftKey", ctrl: "ctrlKey", alt: "altKey", meta: "metaKey"},
  4280. // specialKeys = {
  4281. // 8: "backspace", 9: "tab", 10: "return", 13: "return", 16: "shift", 17: "ctrl", 18: "alt", 19: "pause",
  4282. // 20: "capslock", 27: "esc", 32: "space", 33: "pageup", 34: "pagedown", 35: "end", 36: "home",
  4283. // 37: "left", 38: "up", 39: "right", 40: "down", 45: "insert", 46: "del",
  4284. // 96: "0", 97: "1", 98: "2", 99: "3", 100: "4", 101: "5", 102: "6", 103: "7",
  4285. // 104: "8", 105: "9", 106: "*", 107: "+", 109: "-", 110: ".", 111 : "/",
  4286. // 112: "f1", 113: "f2", 114: "f3", 115: "f4", 116: "f5", 117: "f6", 118: "f7", 119: "f8",
  4287. // 120: "f9", 121: "f10", 122: "f11", 123: "f12", 144: "numlock", 145: "scroll", 186: ";", 191: "/",
  4288. // 220: "\\", 222: "'", 224: "meta"
  4289. // },
  4290. // shiftNums = {
  4291. // "`": "~", "1": "!", "2": "@", "3": "#", "4": "$", "5": "%", "6": "^", "7": "&",
  4292. // "8": "*", "9": "(", "0": ")", "-": "_", "=": "+", ";": ": ", "'": "\"", ",": "<",
  4293. // ".": ">", "/": "?", "\\": "|"
  4294. // }
  4295. ;
  4296. // $.ui.fancytree.isKeydownEvent = function(e, code){
  4297. // var i, part, partmap, partlist = code.split("+"), len = parts.length;
  4298. // var c = String.fromCharCode(e.which).toLowerCase();
  4299. // for( i = 0; i < len; i++ ) {
  4300. // }
  4301. // alert (parts.unshift());
  4302. // alert (parts.unshift());
  4303. // alert (parts.unshift());
  4304. // };
  4305. /**
  4306. * [ext-edit] Start inline editing of current node title.
  4307. *
  4308. * @alias FancytreeNode#editStart
  4309. * @requires Fancytree
  4310. */
  4311. $.ui.fancytree._FancytreeNodeClass.prototype.editStart = function(){
  4312. var $input,
  4313. node = this,
  4314. tree = this.tree,
  4315. local = tree.ext.edit,
  4316. prevTitle = node.title,
  4317. instOpts = tree.options.edit,
  4318. $title = $(".fancytree-title", node.span),
  4319. eventData = {node: node, tree: tree, options: tree.options};
  4320. if( instOpts.beforeEdit.call(node, {type: "beforeEdit"}, eventData) === false){
  4321. return false;
  4322. }
  4323. // beforeEdit may want to modify the title before editing
  4324. prevTitle = node.title;
  4325. node.debug("editStart");
  4326. // Disable standard Fancytree mouse- and key handling
  4327. tree.widget._unbind();
  4328. // #116: ext-dnd prevents the blur event, so we have to catch outer clicks
  4329. $(document).on("mousedown.fancytree-edit", function(event){
  4330. if( ! $(event.target).hasClass("fancytree-edit-input") ){
  4331. node.editEnd(true, event);
  4332. }
  4333. });
  4334. // Replace node with <input>
  4335. $input = $("<input />", {
  4336. "class": "fancytree-edit-input",
  4337. value: prevTitle
  4338. });
  4339. if ( instOpts.adjustWidthOfs != null ) {
  4340. $input.width($title.width() + instOpts.adjustWidthOfs);
  4341. }
  4342. if ( instOpts.inputCss != null ) {
  4343. $input.css(instOpts.inputCss);
  4344. }
  4345. eventData.input = $input;
  4346. $title.html($input);
  4347. $.ui.fancytree.assert(!local.currentNode, "recursive edit");
  4348. local.currentNode = this;
  4349. // Focus <input> and bind keyboard handler
  4350. $input
  4351. .focus()
  4352. .change(function(event){
  4353. $input.addClass("fancytree-edit-dirty");
  4354. }).keydown(function(event){
  4355. switch( event.which ) {
  4356. case $.ui.keyCode.ESCAPE:
  4357. node.editEnd(false, event);
  4358. break;
  4359. case $.ui.keyCode.ENTER:
  4360. node.editEnd(true, event);
  4361. return false; // so we don't start editmode on Mac
  4362. }
  4363. }).blur(function(event){
  4364. return node.editEnd(true, event);
  4365. });
  4366. instOpts.edit.call(node, {type: "edit"}, eventData);
  4367. };
  4368. /**
  4369. * [ext-edit] Stop inline editing.
  4370. * @param {Boolean} [applyChanges=false]
  4371. * @alias FancytreeNode#editEnd
  4372. * @requires jquery.fancytree.edit.js
  4373. */
  4374. $.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function(applyChanges, _event){
  4375. var node = this,
  4376. tree = this.tree,
  4377. local = tree.ext.edit,
  4378. instOpts = tree.options.edit,
  4379. $title = $(".fancytree-title", node.span),
  4380. $input = $title.find("input.fancytree-edit-input"),
  4381. newVal = $input.val(),
  4382. dirty = $input.hasClass("fancytree-edit-dirty"),
  4383. doSave = (applyChanges || (dirty && applyChanges !== false)) && (newVal !== node.title),
  4384. eventData = {
  4385. node: node, tree: tree, options: tree.options, originalEvent: _event,
  4386. dirty: dirty,
  4387. save: doSave,
  4388. input: $input,
  4389. value: newVal
  4390. };
  4391. if( instOpts.beforeClose.call(node, {type: "beforeClose"}, eventData) === false){
  4392. return false;
  4393. }
  4394. if( doSave && instOpts.save.call(node, {type: "save"}, eventData) === false){
  4395. return false;
  4396. }
  4397. $input
  4398. .removeClass("fancytree-edit-dirty")
  4399. .unbind();
  4400. // Unbind outer-click handler
  4401. $(document).off(".fancytree-edit");
  4402. if( doSave ) {
  4403. node.setTitle( newVal );
  4404. }else{
  4405. node.renderTitle();
  4406. }
  4407. // Re-enable mouse and keyboard handling
  4408. tree.widget._bind();
  4409. local.currentNode = null;
  4410. node.setFocus();
  4411. // Set keyboard focus, even if setFocus() claims 'nothing to do'
  4412. $(tree.$container).focus();
  4413. eventData.input = null;
  4414. instOpts.close.call(node, {type: "close"}, eventData);
  4415. return true;
  4416. };
  4417. $.ui.fancytree._FancytreeNodeClass.prototype.startEdit = function(){
  4418. this.warn("FancytreeNode.startEdit() is deprecated since 2014-01-04. Use .editStart() instead.");
  4419. return this.editStart.apply(this, arguments);
  4420. };
  4421. $.ui.fancytree._FancytreeNodeClass.prototype.endEdit = function(){
  4422. this.warn("FancytreeNode.endEdit() is deprecated since 2014-01-04. Use .editEnd() instead.");
  4423. return this.editEnd.apply(this, arguments);
  4424. };
  4425. ///**
  4426. // * Create a new child or sibling node.
  4427. // *
  4428. // * @param {String} [mode] 'before', 'after', or 'child'
  4429. // * @lends FancytreeNode.prototype
  4430. // * @requires jquery.fancytree.edit.js
  4431. // */
  4432. //$.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function(mode){
  4433. // var newNode,
  4434. // node = this,
  4435. // tree = this.tree,
  4436. // local = tree.ext.edit,
  4437. // instOpts = tree.options.edit,
  4438. // $title = $(".fancytree-title", node.span),
  4439. // $input = $title.find("input.fancytree-edit-input"),
  4440. // newVal = $input.val(),
  4441. // dirty = $input.hasClass("fancytree-edit-dirty"),
  4442. // doSave = (applyChanges || (dirty && applyChanges !== false)) && (newVal !== node.title),
  4443. // eventData = {
  4444. // node: node, tree: tree, options: tree.options, originalEvent: _event,
  4445. // dirty: dirty,
  4446. // save: doSave,
  4447. // input: $input,
  4448. // value: newVal
  4449. // };
  4450. //
  4451. // node.debug("editCreate");
  4452. //
  4453. // if( instOpts.beforeEdit.call(node, {type: "beforeCreateNode"}, eventData) === false){
  4454. // return false;
  4455. // }
  4456. // newNode = this.addNode({title: "Neuer Knoten"}, mode);
  4457. //
  4458. // newNode.editStart();
  4459. //};
  4460. /**
  4461. * [ext-edit] Check if any node in this tree in edit mode.
  4462. *
  4463. * @returns {FancytreeNode | null}
  4464. * @lends Fancytree.prototype
  4465. * @requires jquery.fancytree.edit.js
  4466. */
  4467. $.ui.fancytree._FancytreeClass.prototype.isEditing = function(){
  4468. return this.ext.edit.currentNode;
  4469. };
  4470. /**
  4471. * [ext-edit] Check if this node is in edit mode.
  4472. * @returns {Boolean} true if node is currently beeing edited
  4473. * @lends FancytreeNode.prototype
  4474. * @requires jquery.fancytree.edit.js
  4475. */
  4476. $.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function(){
  4477. return this.tree.ext.edit.currentNode === this;
  4478. };
  4479. /*******************************************************************************
  4480. * Extension code
  4481. */
  4482. $.ui.fancytree.registerExtension({
  4483. name: "edit",
  4484. version: "0.1.0",
  4485. // Default options for this extension.
  4486. options: {
  4487. adjustWidthOfs: 4, // null: don't adjust input size to content
  4488. inputCss: {minWidth: "3em"},
  4489. triggerCancel: ["esc", "tab", "click"],
  4490. // triggerStart: ["f2", "dblclick", "shift+click", "mac+enter"],
  4491. triggerStart: ["f2", "shift+click", "mac+enter"],
  4492. beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available)
  4493. beforeEdit: $.noop, // Return false to prevent edit mode
  4494. close: $.noop, // Editor was removed
  4495. edit: $.noop, // Editor was opened (available as data.input)
  4496. // keypress: $.noop, // Not yet implemented
  4497. save: $.noop // Save data.input.val() or return false to keep editor open
  4498. },
  4499. // Local attributes
  4500. currentNode: null,
  4501. // Override virtual methods for this extension.
  4502. // `this` : the Fancytree instance
  4503. // `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)
  4504. // `this._super`: the virtual function that was overridden (member of previous extension or Fancytree)
  4505. treeInit: function(ctx){
  4506. this._super(ctx);
  4507. this.$container.addClass("fancytree-ext-edit");
  4508. },
  4509. nodeClick: function(ctx) {
  4510. if( $.inArray("shift+click", ctx.options.edit.triggerStart) >= 0 ){
  4511. if( ctx.originalEvent.shiftKey ){
  4512. ctx.node.editStart();
  4513. return false;
  4514. }
  4515. }
  4516. this._super(ctx);
  4517. },
  4518. nodeDblclick: function(ctx) {
  4519. if( $.inArray("dblclick", ctx.options.edit.triggerStart) >= 0 ){
  4520. ctx.node.editStart();
  4521. return false;
  4522. }
  4523. return this._super(ctx);
  4524. },
  4525. nodeKeydown: function(ctx) {
  4526. switch( ctx.originalEvent.which ) {
  4527. case 113: // [F2]
  4528. if( $.inArray("f2", ctx.options.edit.triggerStart) >= 0 ){
  4529. ctx.node.editStart();
  4530. return false;
  4531. }
  4532. break;
  4533. case $.ui.keyCode.ENTER:
  4534. if( $.inArray("mac+enter", ctx.options.edit.triggerStart) >= 0 && isMac ){
  4535. ctx.node.editStart();
  4536. return false;
  4537. }
  4538. break;
  4539. }
  4540. return this._super(ctx);
  4541. }
  4542. });
  4543. }(jQuery, window, document));
  4544. /*!
  4545. * jquery.fancytree.filter.js
  4546. *
  4547. * Remove or highlight tree nodes, based on a filter.
  4548. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  4549. *
  4550. * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
  4551. *
  4552. * Released under the MIT license
  4553. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  4554. *
  4555. * @version 2.0.0-7
  4556. * @date 2014-03-09T20:32
  4557. */
  4558. ;(function($, window, document, undefined) {
  4559. "use strict";
  4560. /*******************************************************************************
  4561. * Private functions and variables
  4562. */
  4563. function _escapeRegex(str){
  4564. /*jshint regexdash:true */
  4565. return (str + "").replace(/([.?*+\^\$\[\]\\(){}|-])/g, "\\$1");
  4566. }
  4567. /* EXT-TABLE: Show/hide all rows that are structural descendants of `parent`. */
  4568. // function setChildRowVisibility(parent, flag) {
  4569. // parent.visit(function(node){
  4570. // var tr = node.tr;
  4571. // if(tr){
  4572. // tr.style.display = flag ? "" : "none";
  4573. // }
  4574. // node.debug(flag ? "SHOW" : "HIDE");
  4575. // if(!node.expanded){
  4576. // return "skip";
  4577. // }
  4578. // });
  4579. // }
  4580. /**
  4581. * [ext-filter] Dimm or hide nodes.
  4582. *
  4583. * @param {function | string} filter
  4584. * @returns {integer} count
  4585. * @alias Fancytree#applyFilter
  4586. * @requires jquery.fancytree.filter.js
  4587. */
  4588. $.ui.fancytree._FancytreeClass.prototype.applyFilter = function(filter){
  4589. var match, re,
  4590. count = 0,
  4591. leavesOnly = this.options.filter.leavesOnly;
  4592. // Default to 'match title substring (not case sensitive)'
  4593. if(typeof filter === "string"){
  4594. match = _escapeRegex(filter); // make sure a '.' is treated literally
  4595. re = new RegExp(".*" + match + ".*", "i");
  4596. filter = function(node){
  4597. return !!re.exec(node.title);
  4598. };
  4599. }
  4600. this.enableFilter = true;
  4601. this.$div.addClass("fancytree-ext-filter");
  4602. if( this.options.filter.mode === "hide"){
  4603. this.$div.addClass("fancytree-ext-filter-hide");
  4604. } else {
  4605. this.$div.addClass("fancytree-ext-filter-dimm");
  4606. }
  4607. // Reset current filter
  4608. this.visit(function(node){
  4609. node.hide = true;
  4610. delete node.match;
  4611. delete node.subMatch;
  4612. });
  4613. // Adjust node.hide, .match, .subMatch flags
  4614. this.visit(function(node){
  4615. if ((!leavesOnly || node.children == null) && filter(node)) {
  4616. count++;
  4617. node.hide = false;
  4618. node.match = true;
  4619. node.visitParents(function(p){
  4620. p.hide = false;
  4621. p.subMatch = true;
  4622. });
  4623. }
  4624. });
  4625. // Redraw
  4626. this.render();
  4627. return count;
  4628. };
  4629. /**
  4630. * [ext-filter] Reset the filter.
  4631. *
  4632. * @alias Fancytree#applyFilter
  4633. * @requires jquery.fancytree.filter.js
  4634. */
  4635. $.ui.fancytree._FancytreeClass.prototype.clearFilter = function(){
  4636. this.visit(function(node){
  4637. delete node.hide;
  4638. delete node.match;
  4639. delete node.subMatch;
  4640. });
  4641. this.enableFilter = false;
  4642. this.$div.removeClass("fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide");
  4643. this.render();
  4644. };
  4645. /*******************************************************************************
  4646. * Extension code
  4647. */
  4648. $.ui.fancytree.registerExtension({
  4649. name: "filter",
  4650. version: "0.0.2",
  4651. // Default options for this extension.
  4652. options: {
  4653. mode: "dimm",
  4654. leavesOnly: false
  4655. },
  4656. // Override virtual methods for this extension.
  4657. // `this` : is this extension object
  4658. // `this._base` : the Fancytree instance
  4659. // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
  4660. treeInit: function(ctx){
  4661. this._super(ctx);
  4662. // ctx.tree.filter = false;
  4663. },
  4664. treeDestroy: function(ctx){
  4665. this._super(ctx);
  4666. },
  4667. nodeRenderStatus: function(ctx) {
  4668. // Set classes for current status
  4669. var res,
  4670. node = ctx.node,
  4671. tree = ctx.tree,
  4672. $span = $(node[tree.statusClassPropName]);
  4673. res = this._super(ctx);
  4674. if(!$span.length){
  4675. return res; // nothing to do, if node was not yet rendered
  4676. }
  4677. if(!tree.enableFilter){
  4678. return res;
  4679. }
  4680. $span.toggleClass("fancytree-match", !!node.match);
  4681. $span.toggleClass("fancytree-submatch", !!node.subMatch);
  4682. $span.toggleClass("fancytree-hide", !!node.hide);
  4683. // if(opts.filter.mode === "hide"){
  4684. // // visible = !!(node.match || node.subMatch);
  4685. // visible = !node.hide;
  4686. // node.debug(node.title + ": visible=" + visible);
  4687. // if( node.li ) {
  4688. // $(node.li).toggle(visible);
  4689. // } else if( node.tr ) {
  4690. // // Show/hide all rows that are structural descendants of `parent`
  4691. // $(node.tr).toggle(visible);
  4692. // // if( !visible ) {
  4693. // // setChildRowVisibility(node, visible);
  4694. // // }
  4695. // }
  4696. // }
  4697. return res;
  4698. }
  4699. });
  4700. }(jQuery, window, document));
  4701. /*!
  4702. * jquery.fancytree.gridnav.js
  4703. *
  4704. * Support keyboard navigation for trees with embedded input controls.
  4705. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  4706. *
  4707. * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
  4708. *
  4709. * Released under the MIT license
  4710. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  4711. *
  4712. * @version 2.0.0-7
  4713. * @date 2014-03-09T20:32
  4714. */
  4715. ;(function($, window, document, undefined) {
  4716. "use strict";
  4717. /*******************************************************************************
  4718. * Private functions and variables
  4719. */
  4720. // Allow these navigation keys even when input controls are focused
  4721. var KC = $.ui.keyCode,
  4722. // which keys are *not* handled by embedded control, but passed to tree
  4723. // navigation handler:
  4724. NAV_KEYS = {
  4725. "text": [KC.UP, KC.DOWN],
  4726. "checkbox": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
  4727. "radiobutton": [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
  4728. "select-one": [KC.LEFT, KC.RIGHT],
  4729. "select-multiple": [KC.LEFT, KC.RIGHT]
  4730. };
  4731. function findNeighbourTd($target, keyCode){
  4732. var $td = $target.closest("td");
  4733. switch( keyCode ){
  4734. case KC.LEFT:
  4735. return $td.prev();
  4736. case KC.RIGHT:
  4737. return $td.next();
  4738. case KC.UP:
  4739. return $td.parent().prevAll(":visible").first().find("td").eq($td.index());
  4740. case KC.DOWN:
  4741. return $td.parent().nextAll(":visible").first().find("td").eq($td.index());
  4742. }
  4743. return null;
  4744. }
  4745. /*******************************************************************************
  4746. * Extension code
  4747. */
  4748. $.ui.fancytree.registerExtension({
  4749. name: "gridnav",
  4750. version: "0.0.1",
  4751. // Default options for this extension.
  4752. options: {
  4753. autofocusInput: false, // Focus first embedded input if node gets activated
  4754. handleCursorKeys: true // Allow UP/DOWN in inputs to move to prev/next node
  4755. },
  4756. treeInit: function(ctx){
  4757. // gridnav requires the table extension to be loaded before itself
  4758. this._requireExtension("table", true, true);
  4759. this._super(ctx);
  4760. this.$container.addClass("fancytree-ext-gridnav");
  4761. // Activate node if embedded input gets focus (due to a click)
  4762. this.$container.on("focusin", function(event){
  4763. var ctx2,
  4764. node = $.ui.fancytree.getNode(event.target);
  4765. if( node && !node.isActive() ){
  4766. // Call node.setActive(), but also pass the event
  4767. ctx2 = ctx.tree._makeHookContext(node, event);
  4768. ctx.tree._callHook("nodeSetActive", ctx2, true);
  4769. }
  4770. });
  4771. },
  4772. nodeSetActive: function(ctx, flag) {
  4773. var $outer,
  4774. opts = ctx.options.gridnav,
  4775. node = ctx.node,
  4776. event = ctx.originalEvent || {},
  4777. triggeredByInput = $(event.target).is(":input");
  4778. flag = (flag !== false);
  4779. this._super(ctx, flag);
  4780. if( flag ){
  4781. if( ctx.options.titlesTabbable ){
  4782. if( !triggeredByInput ) {
  4783. $(node.span).find("span.fancytree-title").focus();
  4784. node.setFocus();
  4785. }
  4786. // If one node is tabbable, the container no longer needs to be
  4787. ctx.tree.$container.attr("tabindex", "-1");
  4788. // ctx.tree.$container.removeAttr("tabindex");
  4789. } else if( opts.autofocusInput && !triggeredByInput ){
  4790. // Set focus to input sub input (if node was clicked, but not
  4791. // when TAB was pressed )
  4792. $outer = $(node.tr || node.span);
  4793. $outer.find(":input:enabled:first").focus();
  4794. }
  4795. }
  4796. },
  4797. nodeKeydown: function(ctx) {
  4798. var inputType, handleKeys, $td,
  4799. opts = ctx.options.gridnav,
  4800. event = ctx.originalEvent,
  4801. $target = $(event.target);
  4802. // jQuery
  4803. inputType = $target.is(":input:enabled") ? $target.prop("type") : null;
  4804. ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType);
  4805. if( inputType && opts.handleCursorKeys ){
  4806. handleKeys = NAV_KEYS[inputType];
  4807. if( handleKeys && $.inArray(event.which, handleKeys) >= 0 ){
  4808. $td = findNeighbourTd($target, event.which);
  4809. // ctx.node.debug("ignore keydown in input", event.which, handleKeys);
  4810. if( $td && $td.length ) {
  4811. $td.find(":input:enabled").focus();
  4812. // Prevent Fancytree default navigation
  4813. return false;
  4814. }
  4815. }
  4816. return true;
  4817. }
  4818. ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType);
  4819. return this._super(ctx);
  4820. }
  4821. });
  4822. }(jQuery, window, document));
  4823. /*!
  4824. * jquery.fancytree.persist.js
  4825. *
  4826. * Persist tree status in cookiesRemove or highlight tree nodes, based on a filter.
  4827. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  4828. *
  4829. * @depends: jquery.cookie.js
  4830. *
  4831. * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
  4832. *
  4833. * Released under the MIT license
  4834. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  4835. *
  4836. * @version 2.0.0-7
  4837. * @date 2014-03-09T20:32
  4838. */
  4839. ;(function($, window, document, undefined) {
  4840. "use strict";
  4841. /*******************************************************************************
  4842. * Private functions and variables
  4843. */
  4844. function _assert(cond, msg){
  4845. msg = msg || "";
  4846. if(!cond){
  4847. $.error("Assertion failed " + msg);
  4848. }
  4849. }
  4850. var ACTIVE = "active",
  4851. EXPANDED = "expanded",
  4852. FOCUS = "focus",
  4853. SELECTED = "selected";
  4854. /* Recursively load lazy nodes
  4855. * @param {string} mode 'load', 'expand', false
  4856. */
  4857. function _loadLazyNodes(tree, instData, keyList, mode, dfd) {
  4858. var i, key, l, node,
  4859. foundOne = false,
  4860. deferredList = [],
  4861. // lazyNodeList = [],
  4862. missingKeyList = []; //keyList.slice(0),
  4863. keyList = keyList || [];
  4864. // expand = expand !== false;
  4865. dfd = dfd || $.Deferred();
  4866. for( i=0, l=keyList.length; i<l; i++ ) {
  4867. key = keyList[i];
  4868. node = tree.getNodeByKey(key);
  4869. if( node ) {
  4870. if( mode && node.isUndefined() ) {
  4871. // lazyNodeList.push(node);
  4872. foundOne = true;
  4873. tree.debug("_loadLazyNodes: " + node + " is lazy: loading...");
  4874. if( mode === "expand" ) {
  4875. deferredList.push(node.setExpanded());
  4876. } else {
  4877. deferredList.push(node.load());
  4878. }
  4879. } else {
  4880. tree.debug("_loadLazyNodes: " + node + " already loaded.");
  4881. node.setExpanded();
  4882. // node.expanded = true;
  4883. // node.render();
  4884. }
  4885. } else {
  4886. missingKeyList.push(key);
  4887. tree.debug("_loadLazyNodes: " + node + " was not yet found.");
  4888. }
  4889. }
  4890. $.when.apply($, deferredList).always(function(){
  4891. // All lazy-expands have finished
  4892. if( foundOne && missingKeyList.length > 0 ) {
  4893. // If we read new nodes from server, try to resolve yet-missing keys
  4894. _loadLazyNodes(tree, instData, missingKeyList, mode, dfd);
  4895. } else {
  4896. if( missingKeyList.length ) {
  4897. tree.warn("_loadLazyNodes: could not load those keys: ", missingKeyList);
  4898. for( i=0, l=missingKeyList.length; i<l; i++ ) {
  4899. key = keyList[i];
  4900. instData._setKey(EXPANDED, keyList[i], false);
  4901. }
  4902. }
  4903. dfd.resolve();
  4904. }
  4905. });
  4906. return dfd;
  4907. }
  4908. /**
  4909. * [ext-persist] Remove persistence cookies of the given type(s).
  4910. * Called like
  4911. * $("#tree").fancytree("getTree").clearCookies("active expanded focus selected");
  4912. *
  4913. * @alias Fancytree#clearCookies
  4914. * @requires jquery.fancytree.persist.js
  4915. */
  4916. $.ui.fancytree._FancytreeClass.prototype.clearCookies = function(types){
  4917. var inst = this.ext.persist,
  4918. cookiePrefix = inst.cookiePrefix;
  4919. types = types || "active expanded focus selected";
  4920. // TODO: optimize
  4921. if(types.indexOf(ACTIVE) >= 0){
  4922. // $.cookie(cookiePrefix + ACTIVE, null);
  4923. $.removeCookie(cookiePrefix + ACTIVE);
  4924. }
  4925. if(types.indexOf(EXPANDED) >= 0){
  4926. // $.cookie(cookiePrefix + EXPANDED, null);
  4927. $.removeCookie(cookiePrefix + EXPANDED);
  4928. }
  4929. if(types.indexOf(FOCUS) >= 0){
  4930. // $.cookie(cookiePrefix + FOCUS, null);
  4931. $.removeCookie(cookiePrefix + FOCUS);
  4932. }
  4933. if(types.indexOf(SELECTED) >= 0){
  4934. // $.cookie(cookiePrefix + SELECTED, null);
  4935. $.removeCookie(cookiePrefix + SELECTED);
  4936. }
  4937. };
  4938. /**
  4939. * [ext-persist] Return persistence information from cookies
  4940. *
  4941. * Called like
  4942. * $("#tree").fancytree("getTree").getPersistData();
  4943. *
  4944. * @alias Fancytree#getPersistData
  4945. * @requires jquery.fancytree.persist.js
  4946. */
  4947. $.ui.fancytree._FancytreeClass.prototype.getPersistData = function(){
  4948. var inst = this.ext.persist,
  4949. instOpts= this.options.persist,
  4950. delim = instOpts.cookieDelimiter,
  4951. res = {};
  4952. res[ACTIVE] = $.cookie(inst.cookiePrefix + ACTIVE);
  4953. res[EXPANDED] = ($.cookie(inst.cookiePrefix + EXPANDED) || "").split(delim);
  4954. res[SELECTED] = ($.cookie(inst.cookiePrefix + SELECTED) || "").split(delim);
  4955. res[FOCUS] = $.cookie(inst.cookiePrefix + FOCUS);
  4956. };
  4957. /* *****************************************************************************
  4958. * Extension code
  4959. */
  4960. $.ui.fancytree.registerExtension({
  4961. name: "persist",
  4962. version: "0.2.0",
  4963. // Default options for this extension.
  4964. options: {
  4965. // appendRequestInfo: false,
  4966. cookieDelimiter: "~",
  4967. cookiePrefix: undefined, // 'fancytree-<treeId>-' by default
  4968. cookie: {
  4969. raw: false,
  4970. expires: "",
  4971. path: "",
  4972. domain: "",
  4973. secure: false
  4974. },
  4975. expandLazy: false, // true: recursively expand and load lazy nodes
  4976. overrideSource: false, // true: cookie takes precedence over `source` data attributes.
  4977. types: "active expanded focus selected"
  4978. },
  4979. /* Append `key` to a cookie. */
  4980. _setKey: function(type, key, flag){
  4981. key = "" + key; // #90
  4982. var instData = this._local,
  4983. instOpts = this.options.persist,
  4984. cookieName = instData.cookiePrefix + type,
  4985. cookie = $.cookie(cookieName),
  4986. cookieList = cookie ? cookie.split(instOpts.cookieDelimiter) : [],
  4987. idx = $.inArray(key, cookieList);
  4988. // Remove, even if we add a key, so the key is always the last entry
  4989. if(idx >= 0){
  4990. cookieList.splice(idx, 1);
  4991. }
  4992. // Append key to cookie
  4993. if(flag){
  4994. cookieList.push(key);
  4995. }
  4996. $.cookie(cookieName, cookieList.join(instOpts.cookieDelimiter), instOpts.cookie);
  4997. },
  4998. // Overide virtual methods for this extension.
  4999. // `this` : is this Fancytree object
  5000. // `this._super`: the virtual function that was overridden (member of prev. extension or Fancytree)
  5001. treeInit: function(ctx){
  5002. var tree = ctx.tree,
  5003. opts = ctx.options,
  5004. instData = this._local,
  5005. instOpts = this.options.persist;
  5006. _assert($.cookie, "Missing required plugin for 'persist' extension: jquery.cookie.js");
  5007. instData.cookiePrefix = instOpts.cookiePrefix || ("fancytree-" + tree._id + "-");
  5008. instData.storeActive = instOpts.types.indexOf(ACTIVE) >= 0;
  5009. instData.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0;
  5010. instData.storeSelected = instOpts.types.indexOf(SELECTED) >= 0;
  5011. instData.storeFocus = instOpts.types.indexOf(FOCUS) >= 0;
  5012. // Bind init-handler to apply cookie state
  5013. tree.$div.bind("fancytreeinit", function(event){
  5014. var cookie, dfd, i, keyList, node,
  5015. prevFocus = $.cookie(instData.cookiePrefix + FOCUS); // record this before node.setActive() overrides it;
  5016. tree.debug("COOKIE " + document.cookie);
  5017. cookie = $.cookie(instData.cookiePrefix + EXPANDED);
  5018. keyList = cookie && cookie.split(instOpts.cookieDelimiter);
  5019. if( instData.storeExpanded ) {
  5020. // Recursively load nested lazy nodes if expandLazy is 'expand' or 'load'
  5021. // Also remove expand-cookies for unmatched nodes
  5022. dfd = _loadLazyNodes(tree, instData, keyList, instOpts.expandLazy ? "expand" : false , null);
  5023. } else {
  5024. // nothing to do
  5025. dfd = new $.Deferred().resolve();
  5026. }
  5027. dfd.done(function(){
  5028. // alert("persistent expand done");
  5029. // if(instData.storeExpanded){
  5030. // cookie = $.cookie(instData.cookiePrefix + EXPANDED);
  5031. // if(cookie){
  5032. // keyList = cookie.split(instOpts.cookieDelimiter);
  5033. // for(i=0; i<keyList.length; i++){
  5034. // node = tree.getNodeByKey(keyList[i]);
  5035. // if(node){
  5036. // if(node.expanded === undefined || instOpts.overrideSource && (node.expanded === false)){
  5037. // // node.setExpanded();
  5038. // node.expanded = true;
  5039. // node.render();
  5040. // }
  5041. // }else{
  5042. // // node is no longer member of the tree: remove from cookie
  5043. // instData._setKey(EXPANDED, keyList[i], false);
  5044. // }
  5045. // }
  5046. // }
  5047. // }
  5048. if(instData.storeSelected){
  5049. cookie = $.cookie(instData.cookiePrefix + SELECTED);
  5050. if(cookie){
  5051. keyList = cookie.split(instOpts.cookieDelimiter);
  5052. for(i=0; i<keyList.length; i++){
  5053. node = tree.getNodeByKey(keyList[i]);
  5054. if(node){
  5055. if(node.selected === undefined || instOpts.overrideSource && (node.selected === false)){
  5056. // node.setSelected();
  5057. node.selected = true;
  5058. node.renderStatus();
  5059. }
  5060. }else{
  5061. // node is no longer member of the tree: remove from cookie also
  5062. instData._setKey(SELECTED, keyList[i], false);
  5063. }
  5064. }
  5065. }
  5066. }
  5067. if(instData.storeActive){
  5068. cookie = $.cookie(instData.cookiePrefix + ACTIVE);
  5069. if(cookie && (opts.persist.overrideSource || !tree.activeNode)){
  5070. node = tree.getNodeByKey(cookie);
  5071. if(node){
  5072. node.setActive();
  5073. }
  5074. }
  5075. }
  5076. if(instData.storeFocus && prevFocus){
  5077. node = tree.getNodeByKey(prevFocus);
  5078. if(node){
  5079. node.setFocus();
  5080. }
  5081. }
  5082. });
  5083. });
  5084. // Init the tree
  5085. this._super(ctx);
  5086. },
  5087. // treeDestroy: function(ctx){
  5088. // this._super(ctx);
  5089. // },
  5090. nodeSetActive: function(ctx, flag, opts) {
  5091. var instData = this._local,
  5092. instOpts = this.options.persist;
  5093. flag = flag !== false;
  5094. this._super(ctx, flag, opts);
  5095. if(instData.storeActive){
  5096. $.cookie(instData.cookiePrefix + ACTIVE,
  5097. this.activeNode ? this.activeNode.key : null,
  5098. instOpts.cookie);
  5099. }
  5100. },
  5101. nodeSetExpanded: function(ctx, flag, opts) {
  5102. var res,
  5103. node = ctx.node,
  5104. instData = this._local;
  5105. flag = flag !== false;
  5106. res = this._super(ctx, flag, opts);
  5107. if(instData.storeExpanded){
  5108. instData._setKey(EXPANDED, node.key, flag);
  5109. }
  5110. return res;
  5111. },
  5112. nodeSetFocus: function(ctx) {
  5113. var instData = this._local,
  5114. instOpts = this.options.persist;
  5115. this._super(ctx);
  5116. if(instData.storeFocus){
  5117. $.cookie(instData.cookiePrefix + FOCUS,
  5118. this.focusNode ? this.focusNode.key : null,
  5119. instOpts.cookie);
  5120. }
  5121. },
  5122. nodeSetSelected: function(ctx, flag) {
  5123. var node = ctx.node,
  5124. instData = this._local;
  5125. flag = flag !== false;
  5126. this._super(ctx, flag);
  5127. if(instData.storeSelected){
  5128. instData._setKey(SELECTED, node.key, flag);
  5129. }
  5130. }
  5131. });
  5132. }(jQuery, window, document));
  5133. /*!
  5134. * jquery.fancytree.table.js
  5135. *
  5136. * Render tree as table (aka 'treegrid', 'tabletree').
  5137. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  5138. *
  5139. * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
  5140. *
  5141. * Released under the MIT license
  5142. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  5143. *
  5144. * @version 2.0.0-7
  5145. * @date 2014-03-09T20:32
  5146. */
  5147. ;(function($, window, document, undefined) {
  5148. "use strict";
  5149. /* *****************************************************************************
  5150. * Private functions and variables
  5151. */
  5152. function _assert(cond, msg){
  5153. msg = msg || "";
  5154. if(!cond){
  5155. $.error("Assertion failed " + msg);
  5156. }
  5157. }
  5158. function insertSiblingAfter(referenceNode, newNode) {
  5159. referenceNode.parentNode.insertBefore(newNode, referenceNode.nextSibling);
  5160. }
  5161. /* Show/hide all rows that are structural descendants of `parent`. */
  5162. function setChildRowVisibility(parent, flag) {
  5163. parent.visit(function(node){
  5164. var tr = node.tr;
  5165. flag = node.hide ? false : flag; // fix for ext-filter
  5166. if(tr){
  5167. tr.style.display = flag ? "" : "none";
  5168. }
  5169. if(!node.expanded){
  5170. return "skip";
  5171. }
  5172. });
  5173. }
  5174. /* Find node that is rendered in previous row. */
  5175. function findPrevRowNode(node){
  5176. var i, last, prev,
  5177. parent = node.parent,
  5178. siblings = parent ? parent.children : null;
  5179. if(siblings && siblings.length > 1 && siblings[0] !== node){
  5180. // use the lowest descendant of the preceeding sibling
  5181. i = $.inArray(node, siblings);
  5182. prev = siblings[i - 1];
  5183. _assert(prev.tr);
  5184. // descend to lowest child (with a <tr> tag)
  5185. while(prev.children){
  5186. last = prev.children[prev.children.length - 1];
  5187. if(!last.tr){
  5188. break;
  5189. }
  5190. prev = last;
  5191. }
  5192. }else{
  5193. // if there is no preceding sibling, use the direct parent
  5194. prev = parent;
  5195. }
  5196. return prev;
  5197. }
  5198. $.ui.fancytree.registerExtension({
  5199. name: "table",
  5200. version: "0.1.0",
  5201. // Default options for this extension.
  5202. options: {
  5203. indentation: 16, // indent every node level by 16px
  5204. nodeColumnIdx: 0, // render node expander, icon, and title to column #0
  5205. checkboxColumnIdx: null // render the checkboxes into the 1st column
  5206. },
  5207. // Overide virtual methods for this extension.
  5208. // `this` : is this extension object
  5209. // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
  5210. treeInit: function(ctx){
  5211. var i, $row, tdRole,
  5212. tree = ctx.tree,
  5213. $table = tree.widget.element;
  5214. $table.addClass("fancytree-container fancytree-ext-table");
  5215. tree.tbody = $table.find("> tbody")[0];
  5216. tree.columnCount = $("thead >tr >th", $table).length;
  5217. $(tree.tbody).empty();
  5218. tree.rowFragment = document.createDocumentFragment();
  5219. $row = $("<tr />");
  5220. tdRole = "";
  5221. if(ctx.options.aria){
  5222. $row.attr("role", "row");
  5223. tdRole = " role='gridcell'";
  5224. }
  5225. for(i=0; i<tree.columnCount; i++) {
  5226. if(ctx.options.table.nodeColumnIdx === i){
  5227. $row.append("<td" + tdRole + "><span class='fancytree-node'></span></td>");
  5228. }else{
  5229. $row.append("<td" + tdRole + ">");
  5230. }
  5231. }
  5232. tree.rowFragment.appendChild($row.get(0));
  5233. // Make sure that status classes are set on the node's <tr> elements
  5234. tree.statusClassPropName = "tr";
  5235. tree.ariaPropName = "tr";
  5236. this.nodeContainerAttrName = "tr";
  5237. this._super(ctx);
  5238. // standard Fancytree created a root UL
  5239. $(tree.rootNode.ul).remove();
  5240. tree.rootNode.ul = null;
  5241. tree.$container = $table;
  5242. // Add container to the TAB chain
  5243. this.$container.attr("tabindex", this.options.tabbable ? "0" : "-1");
  5244. if(this.options.aria){
  5245. tree.$container
  5246. .attr("role", "treegrid")
  5247. .attr("aria-readonly", true);
  5248. }
  5249. },
  5250. /* Called by nodeRender to sync node order with tag order.*/
  5251. // nodeFixOrder: function(ctx) {
  5252. // },
  5253. nodeRemoveChildMarkup: function(ctx) {
  5254. var node = ctx.node;
  5255. // DT.debug("nodeRemoveChildMarkup()", node.toString());
  5256. node.visit(function(n){
  5257. if(n.tr){
  5258. $(n.tr).remove();
  5259. n.tr = null;
  5260. }
  5261. });
  5262. },
  5263. nodeRemoveMarkup: function(ctx) {
  5264. var node = ctx.node;
  5265. // DT.debug("nodeRemoveMarkup()", node.toString());
  5266. if(node.tr){
  5267. $(node.tr).remove();
  5268. node.tr = null;
  5269. }
  5270. this.nodeRemoveChildMarkup(ctx);
  5271. },
  5272. /* Override standard render. */
  5273. nodeRender: function(ctx, force, deep, collapsed, _recursive) {
  5274. var children, firstTr, i, l, newRow, prevNode, prevTr, subCtx,
  5275. tree = ctx.tree,
  5276. node = ctx.node,
  5277. opts = ctx.options,
  5278. isRootNode = !node.parent;
  5279. if( !_recursive ){
  5280. ctx.hasCollapsedParents = node.parent && !node.parent.expanded;
  5281. }
  5282. // $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode);
  5283. if( !isRootNode ){
  5284. if(!node.tr){
  5285. // Create new <tr> after previous row
  5286. newRow = tree.rowFragment.firstChild.cloneNode(true);
  5287. prevNode = findPrevRowNode(node);
  5288. // $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key);
  5289. _assert(prevNode);
  5290. if(collapsed === true && _recursive){
  5291. // hide all child rows, so we can use an animation to show it later
  5292. newRow.style.display = "none";
  5293. }else if(deep && ctx.hasCollapsedParents){
  5294. // also hide this row if deep === true but any parent is collapsed
  5295. newRow.style.display = "none";
  5296. // newRow.style.color = "red";
  5297. }
  5298. if(!prevNode.tr){
  5299. _assert(!prevNode.parent, "prev. row must have a tr, or is system root");
  5300. tree.tbody.appendChild(newRow);
  5301. }else{
  5302. insertSiblingAfter(prevNode.tr, newRow);
  5303. }
  5304. node.tr = newRow;
  5305. if( node.key && opts.generateIds ){
  5306. node.tr.id = opts.idPrefix + node.key;
  5307. }
  5308. node.tr.ftnode = node;
  5309. if(opts.aria){
  5310. // TODO: why doesn't this work:
  5311. // node.li.role = "treeitem";
  5312. $(node.tr).attr("aria-labelledby", "ftal_" + node.key);
  5313. }
  5314. node.span = $("span.fancytree-node", node.tr).get(0);
  5315. // Set icon, link, and title (normally this is only required on initial render)
  5316. this.nodeRenderTitle(ctx);
  5317. // Allow tweaking, binding, after node was created for the first time
  5318. // tree._triggerNodeEvent("createNode", ctx);
  5319. if ( opts.createNode ){
  5320. opts.createNode.call(tree, {type: "createNode"}, ctx);
  5321. }
  5322. } else {
  5323. // Set icon, link, and title (normally this is only required on initial render)
  5324. //this.nodeRenderTitle(ctx);
  5325. // Update element classes according to node state
  5326. this.nodeRenderStatus(ctx);
  5327. }
  5328. }
  5329. // Allow tweaking after node state was rendered
  5330. // tree._triggerNodeEvent("renderNode", ctx);
  5331. if ( opts.renderNode ){
  5332. opts.renderNode.call(tree, {type: "renderNode"}, ctx);
  5333. }
  5334. // Visit child nodes
  5335. // Add child markup
  5336. children = node.children;
  5337. if(children && (isRootNode || deep || node.expanded)){
  5338. for(i=0, l=children.length; i<l; i++) {
  5339. subCtx = $.extend({}, ctx, {node: children[i]});
  5340. subCtx.hasCollapsedParents = subCtx.hasCollapsedParents || !node.expanded;
  5341. this.nodeRender(subCtx, force, deep, collapsed, true);
  5342. }
  5343. }
  5344. // Make sure, that <tr> order matches node.children order.
  5345. if(children && !_recursive){ // we only have to do it once, for the root branch
  5346. prevTr = node.tr || null;
  5347. firstTr = tree.tbody.firstChild;
  5348. // Iterate over all descendants
  5349. node.visit(function(n){
  5350. if(n.tr){
  5351. if(!n.parent.expanded && n.tr.style.display !== "none"){
  5352. // fix after a node was dropped over a collapsed
  5353. n.tr.style.display = "none";
  5354. setChildRowVisibility(n, false);
  5355. }
  5356. if(n.tr.previousSibling !== prevTr){
  5357. node.debug("_fixOrder: mismatch at node: " + n);
  5358. var nextTr = prevTr ? prevTr.nextSibling : firstTr;
  5359. tree.tbody.insertBefore(n.tr, nextTr);
  5360. }
  5361. prevTr = n.tr;
  5362. }
  5363. });
  5364. }
  5365. // Update element classes according to node state
  5366. // if(!isRootNode){
  5367. // this.nodeRenderStatus(ctx);
  5368. // }
  5369. },
  5370. nodeRenderTitle: function(ctx, title) {
  5371. var $cb,
  5372. node = ctx.node,
  5373. opts = ctx.options;
  5374. this._super(ctx);
  5375. // Move checkbox to custom column
  5376. if(opts.checkbox && opts.table.checkboxColumnIdx != null){
  5377. $cb = $("span.fancytree-checkbox", node.span).detach();
  5378. $(node.tr).find("td:first").html($cb);
  5379. }
  5380. // Let user code write column content
  5381. // ctx.tree._triggerNodeEvent("renderColumns", node);
  5382. // Update element classes according to node state
  5383. if( ! node.isRoot() ){
  5384. this.nodeRenderStatus(ctx);
  5385. }
  5386. if ( opts.renderColumns ){
  5387. opts.renderColumns.call(ctx.tree, {type: "renderColumns"}, ctx);
  5388. }
  5389. },
  5390. nodeRenderStatus: function(ctx) {
  5391. var indent,
  5392. node = ctx.node,
  5393. opts = ctx.options;
  5394. this._super(ctx);
  5395. $(node.tr).removeClass("fancytree-node");
  5396. // indent
  5397. indent = (node.getLevel() - 1) * opts.table.indentation;
  5398. $(node.span).css({marginLeft: indent + "px"});
  5399. },
  5400. /* Expand node, return Deferred.promise. */
  5401. nodeSetExpanded: function(ctx, flag, opts) {
  5402. return this._super(ctx, flag, opts).always(function () {
  5403. flag = (flag !== false);
  5404. setChildRowVisibility(ctx.node, flag);
  5405. });
  5406. },
  5407. nodeSetStatus: function(ctx, status, message, details) {
  5408. if(status === "ok"){
  5409. var node = ctx.node,
  5410. firstChild = ( node.children ? node.children[0] : null );
  5411. if ( firstChild && firstChild.isStatusNode() ) {
  5412. $(firstChild.tr).remove();
  5413. }
  5414. }
  5415. this._super(ctx, status, message, details);
  5416. },
  5417. treeClear: function(ctx) {
  5418. this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode));
  5419. return this._super(ctx);
  5420. }
  5421. /*,
  5422. treeSetFocus: function(ctx, flag) {
  5423. // alert("treeSetFocus" + ctx.tree.$container);
  5424. ctx.tree.$container.focus();
  5425. $.ui.fancytree.focusTree = ctx.tree;
  5426. }*/
  5427. });
  5428. }(jQuery, window, document));
  5429. /*!
  5430. * jquery.fancytree.themeroller.js
  5431. *
  5432. * Enable jQuery UI ThemeRoller styles.
  5433. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  5434. *
  5435. * @see http://jqueryui.com/themeroller/
  5436. *
  5437. * Copyright (c) 2014, Martin Wendt (http://wwWendt.de)
  5438. *
  5439. * Released under the MIT license
  5440. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  5441. *
  5442. * @version 2.0.0-7
  5443. * @date 2014-03-09T20:32
  5444. */
  5445. ;(function($, window, document, undefined) {
  5446. "use strict";
  5447. /*******************************************************************************
  5448. * Extension code
  5449. */
  5450. $.ui.fancytree.registerExtension({
  5451. name: "themeroller",
  5452. version: "0.0.1",
  5453. // Default options for this extension.
  5454. options: {
  5455. activeClass: "ui-state-active",
  5456. foccusClass: "ui-state-focus",
  5457. hoverClass: "ui-state-hover",
  5458. selectedClass: "ui-state-highlight"
  5459. },
  5460. // Overide virtual methods for this extension.
  5461. // `this` : is this extension object
  5462. // `this._base` : the Fancytree instance
  5463. // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
  5464. treeInit: function(ctx){
  5465. this._super(ctx);
  5466. var $el = ctx.widget.element;
  5467. if($el[0].nodeName === "TABLE"){
  5468. $el.addClass("ui-widget ui-corner-all");
  5469. $el.find(">thead tr").addClass("ui-widget-header");
  5470. $el.find(">tbody").addClass("ui-widget-conent");
  5471. }else{
  5472. $el.addClass("ui-widget ui-widget-content ui-corner-all");
  5473. }
  5474. $el.delegate(".fancytree-node", "mouseenter mouseleave", function(event){
  5475. var node = $.ui.fancytree.getNode(event.target),
  5476. flag = (event.type === "mouseenter");
  5477. node.debug("hover: " + flag);
  5478. $(node.span).toggleClass("ui-state-hover ui-corner-all", flag);
  5479. });
  5480. },
  5481. treeDestroy: function(ctx){
  5482. this._super(ctx);
  5483. ctx.widget.element.removeClass("ui-widget ui-widget-content ui-corner-all");
  5484. },
  5485. nodeRenderStatus: function(ctx){
  5486. var node = ctx.node,
  5487. $el = $(node.span);
  5488. this._super(ctx);
  5489. /*
  5490. .ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons.
  5491. .ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons.
  5492. .ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons.
  5493. .ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons.
  5494. .ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
  5495. .ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
  5496. .ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons.
  5497. */
  5498. $el.toggleClass("ui-state-active", node.isActive());
  5499. $el.toggleClass("ui-state-focus", node.hasFocus());
  5500. $el.toggleClass("ui-state-highlight", node.isSelected());
  5501. // node.debug("ext-themeroller.nodeRenderStatus: ", node.span.className);
  5502. }
  5503. });
  5504. }(jQuery, window, document));