You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 
 

7375 lines
214 KiB

  1. /*!
  2. * jquery.fancytree.js
  3. * Tree view control with support for lazy loading and much more.
  4. * https://github.com/mar10/fancytree/
  5. *
  6. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  7. * Released under the MIT license
  8. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  9. *
  10. * @version 2.38.3
  11. * @date 2023-02-01T20:52:50Z
  12. */
  13. /** Core Fancytree module.
  14. */
  15. // UMD wrapper for the Fancytree core module
  16. (function (factory) {
  17. if (typeof define === "function" && define.amd) {
  18. // AMD. Register as an anonymous module.
  19. define(["jquery", "./jquery.fancytree.ui-deps"], factory);
  20. } else if (typeof module === "object" && module.exports) {
  21. // Node/CommonJS
  22. require("./jquery.fancytree.ui-deps");
  23. module.exports = factory(require("jquery"));
  24. } else {
  25. // Browser globals
  26. factory(jQuery);
  27. }
  28. })(function ($) {
  29. "use strict";
  30. // prevent duplicate loading
  31. if ($.ui && $.ui.fancytree) {
  32. $.ui.fancytree.warn("Fancytree: ignored duplicate include");
  33. return;
  34. }
  35. /******************************************************************************
  36. * Private functions and variables
  37. */
  38. var i,
  39. attr,
  40. FT = null, // initialized below
  41. TEST_IMG = new RegExp(/\.|\//), // strings are considered image urls if they contain '.' or '/'
  42. REX_HTML = /[&<>"'/]/g, // Escape those characters
  43. REX_TOOLTIP = /[<>"'/]/g, // Don't escape `&` in tooltips
  44. RECURSIVE_REQUEST_ERROR = "$recursive_request",
  45. INVALID_REQUEST_TARGET_ERROR = "$request_target_invalid",
  46. ENTITY_MAP = {
  47. "&": "&amp;",
  48. "<": "&lt;",
  49. ">": "&gt;",
  50. '"': "&quot;",
  51. "'": "&#39;",
  52. "/": "&#x2F;",
  53. },
  54. IGNORE_KEYCODES = { 16: true, 17: true, 18: true },
  55. SPECIAL_KEYCODES = {
  56. 8: "backspace",
  57. 9: "tab",
  58. 10: "return",
  59. 13: "return",
  60. // 16: null, 17: null, 18: null, // ignore shift, ctrl, alt
  61. 19: "pause",
  62. 20: "capslock",
  63. 27: "esc",
  64. 32: "space",
  65. 33: "pageup",
  66. 34: "pagedown",
  67. 35: "end",
  68. 36: "home",
  69. 37: "left",
  70. 38: "up",
  71. 39: "right",
  72. 40: "down",
  73. 45: "insert",
  74. 46: "del",
  75. 59: ";",
  76. 61: "=",
  77. // 91: null, 93: null, // ignore left and right meta
  78. 96: "0",
  79. 97: "1",
  80. 98: "2",
  81. 99: "3",
  82. 100: "4",
  83. 101: "5",
  84. 102: "6",
  85. 103: "7",
  86. 104: "8",
  87. 105: "9",
  88. 106: "*",
  89. 107: "+",
  90. 109: "-",
  91. 110: ".",
  92. 111: "/",
  93. 112: "f1",
  94. 113: "f2",
  95. 114: "f3",
  96. 115: "f4",
  97. 116: "f5",
  98. 117: "f6",
  99. 118: "f7",
  100. 119: "f8",
  101. 120: "f9",
  102. 121: "f10",
  103. 122: "f11",
  104. 123: "f12",
  105. 144: "numlock",
  106. 145: "scroll",
  107. 173: "-",
  108. 186: ";",
  109. 187: "=",
  110. 188: ",",
  111. 189: "-",
  112. 190: ".",
  113. 191: "/",
  114. 192: "`",
  115. 219: "[",
  116. 220: "\\",
  117. 221: "]",
  118. 222: "'",
  119. },
  120. MODIFIERS = {
  121. 16: "shift",
  122. 17: "ctrl",
  123. 18: "alt",
  124. 91: "meta",
  125. 93: "meta",
  126. },
  127. MOUSE_BUTTONS = { 0: "", 1: "left", 2: "middle", 3: "right" },
  128. // Boolean attributes that can be set with equivalent class names in the LI tags
  129. // Note: v2.23: checkbox and hideCheckbox are *not* in this list
  130. CLASS_ATTRS =
  131. "active expanded focus folder lazy radiogroup selected unselectable unselectableIgnore".split(
  132. " "
  133. ),
  134. CLASS_ATTR_MAP = {},
  135. // Top-level Fancytree attributes, that can be set by dict
  136. TREE_ATTRS = "columns types".split(" "),
  137. // TREE_ATTR_MAP = {},
  138. // Top-level FancytreeNode attributes, that can be set by dict
  139. NODE_ATTRS =
  140. "checkbox expanded extraClasses folder icon iconTooltip key lazy partsel radiogroup refKey selected statusNodeType title tooltip type unselectable unselectableIgnore unselectableStatus".split(
  141. " "
  142. ),
  143. NODE_ATTR_MAP = {},
  144. // Mapping of lowercase -> real name (because HTML5 data-... attribute only supports lowercase)
  145. NODE_ATTR_LOWERCASE_MAP = {},
  146. // Attribute names that should NOT be added to node.data
  147. NONE_NODE_DATA_MAP = {
  148. active: true,
  149. children: true,
  150. data: true,
  151. focus: true,
  152. };
  153. for (i = 0; i < CLASS_ATTRS.length; i++) {
  154. CLASS_ATTR_MAP[CLASS_ATTRS[i]] = true;
  155. }
  156. for (i = 0; i < NODE_ATTRS.length; i++) {
  157. attr = NODE_ATTRS[i];
  158. NODE_ATTR_MAP[attr] = true;
  159. if (attr !== attr.toLowerCase()) {
  160. NODE_ATTR_LOWERCASE_MAP[attr.toLowerCase()] = attr;
  161. }
  162. }
  163. // for(i=0; i<TREE_ATTRS.length; i++) {
  164. // TREE_ATTR_MAP[TREE_ATTRS[i]] = true;
  165. // }
  166. function _assert(cond, msg) {
  167. // TODO: see qunit.js extractStacktrace()
  168. if (!cond) {
  169. msg = msg ? ": " + msg : "";
  170. msg = "Fancytree assertion failed" + msg;
  171. // consoleApply("assert", [!!cond, msg]);
  172. // #1041: Raised exceptions may not be visible in the browser
  173. // console if inside promise chains, so we also print directly:
  174. $.ui.fancytree.error(msg);
  175. // Throw exception:
  176. $.error(msg);
  177. }
  178. }
  179. function _hasProp(object, property) {
  180. return Object.prototype.hasOwnProperty.call(object, property);
  181. }
  182. /* Replacement for the deprecated `jQuery.isFunction()`. */
  183. function _isFunction(obj) {
  184. return typeof obj === "function";
  185. }
  186. /* Replacement for the deprecated `jQuery.trim()`. */
  187. function _trim(text) {
  188. return text == null ? "" : text.trim();
  189. }
  190. /* Replacement for the deprecated `jQuery.isArray()`. */
  191. var _isArray = Array.isArray;
  192. _assert($.ui, "Fancytree requires jQuery UI (http://jqueryui.com)");
  193. function consoleApply(method, args) {
  194. var i,
  195. s,
  196. fn = window.console ? window.console[method] : null;
  197. if (fn) {
  198. try {
  199. fn.apply(window.console, args);
  200. } catch (e) {
  201. // IE 8?
  202. s = "";
  203. for (i = 0; i < args.length; i++) {
  204. s += args[i];
  205. }
  206. fn(s);
  207. }
  208. }
  209. }
  210. /* support: IE8 Polyfil for Date.now() */
  211. if (!Date.now) {
  212. Date.now = function now() {
  213. return new Date().getTime();
  214. };
  215. }
  216. /*Return true if x is a FancytreeNode.*/
  217. function _isNode(x) {
  218. return !!(x.tree && x.statusNodeType !== undefined);
  219. }
  220. /** Return true if dotted version string is equal or higher than requested version.
  221. *
  222. * See http://jsfiddle.net/mar10/FjSAN/
  223. */
  224. function isVersionAtLeast(dottedVersion, major, minor, patch) {
  225. var i,
  226. v,
  227. t,
  228. verParts = $.map(_trim(dottedVersion).split("."), function (e) {
  229. return parseInt(e, 10);
  230. }),
  231. testParts = $.map(
  232. Array.prototype.slice.call(arguments, 1),
  233. function (e) {
  234. return parseInt(e, 10);
  235. }
  236. );
  237. for (i = 0; i < testParts.length; i++) {
  238. v = verParts[i] || 0;
  239. t = testParts[i] || 0;
  240. if (v !== t) {
  241. return v > t;
  242. }
  243. }
  244. return true;
  245. }
  246. /**
  247. * Deep-merge a list of objects (but replace array-type options).
  248. *
  249. * jQuery's $.extend(true, ...) method does a deep merge, that also merges Arrays.
  250. * This variant is used to merge extension defaults with user options, and should
  251. * merge objects, but override arrays (for example the `triggerStart: [...]` option
  252. * of ext-edit). Also `null` values are copied over and not skipped.
  253. *
  254. * See issue #876
  255. *
  256. * Example:
  257. * _simpleDeepMerge({}, o1, o2);
  258. */
  259. function _simpleDeepMerge() {
  260. var options,
  261. name,
  262. src,
  263. copy,
  264. clone,
  265. target = arguments[0] || {},
  266. i = 1,
  267. length = arguments.length;
  268. // Handle case when target is a string or something (possible in deep copy)
  269. if (typeof target !== "object" && !_isFunction(target)) {
  270. target = {};
  271. }
  272. if (i === length) {
  273. throw Error("need at least two args");
  274. }
  275. for (; i < length; i++) {
  276. // Only deal with non-null/undefined values
  277. if ((options = arguments[i]) != null) {
  278. // Extend the base object
  279. for (name in options) {
  280. if (_hasProp(options, name)) {
  281. src = target[name];
  282. copy = options[name];
  283. // Prevent never-ending loop
  284. if (target === copy) {
  285. continue;
  286. }
  287. // Recurse if we're merging plain objects
  288. // (NOTE: unlike $.extend, we don't merge arrays, but replace them)
  289. if (copy && $.isPlainObject(copy)) {
  290. clone = src && $.isPlainObject(src) ? src : {};
  291. // Never move original objects, clone them
  292. target[name] = _simpleDeepMerge(clone, copy);
  293. // Don't bring in undefined values
  294. } else if (copy !== undefined) {
  295. target[name] = copy;
  296. }
  297. }
  298. }
  299. }
  300. }
  301. // Return the modified object
  302. return target;
  303. }
  304. /** Return a wrapper that calls sub.methodName() and exposes
  305. * this : tree
  306. * this._local : tree.ext.EXTNAME
  307. * this._super : base.methodName.call()
  308. * this._superApply : base.methodName.apply()
  309. */
  310. function _makeVirtualFunction(methodName, tree, base, extension, extName) {
  311. // $.ui.fancytree.debug("_makeVirtualFunction", methodName, tree, base, extension, extName);
  312. // if(rexTestSuper && !rexTestSuper.test(func)){
  313. // // extension.methodName() doesn't call _super(), so no wrapper required
  314. // return func;
  315. // }
  316. // Use an immediate function as closure
  317. var proxy = (function () {
  318. var prevFunc = tree[methodName], // org. tree method or prev. proxy
  319. baseFunc = extension[methodName], //
  320. _local = tree.ext[extName],
  321. _super = function () {
  322. return prevFunc.apply(tree, arguments);
  323. },
  324. _superApply = function (args) {
  325. return prevFunc.apply(tree, args);
  326. };
  327. // Return the wrapper function
  328. return function () {
  329. var prevLocal = tree._local,
  330. prevSuper = tree._super,
  331. prevSuperApply = tree._superApply;
  332. try {
  333. tree._local = _local;
  334. tree._super = _super;
  335. tree._superApply = _superApply;
  336. return baseFunc.apply(tree, arguments);
  337. } finally {
  338. tree._local = prevLocal;
  339. tree._super = prevSuper;
  340. tree._superApply = prevSuperApply;
  341. }
  342. };
  343. })(); // end of Immediate Function
  344. return proxy;
  345. }
  346. /**
  347. * Subclass `base` by creating proxy functions
  348. */
  349. function _subclassObject(tree, base, extension, extName) {
  350. // $.ui.fancytree.debug("_subclassObject", tree, base, extension, extName);
  351. for (var attrName in extension) {
  352. if (typeof extension[attrName] === "function") {
  353. if (typeof tree[attrName] === "function") {
  354. // override existing method
  355. tree[attrName] = _makeVirtualFunction(
  356. attrName,
  357. tree,
  358. base,
  359. extension,
  360. extName
  361. );
  362. } else if (attrName.charAt(0) === "_") {
  363. // Create private methods in tree.ext.EXTENSION namespace
  364. tree.ext[extName][attrName] = _makeVirtualFunction(
  365. attrName,
  366. tree,
  367. base,
  368. extension,
  369. extName
  370. );
  371. } else {
  372. $.error(
  373. "Could not override tree." +
  374. attrName +
  375. ". Use prefix '_' to create tree." +
  376. extName +
  377. "._" +
  378. attrName
  379. );
  380. }
  381. } else {
  382. // Create member variables in tree.ext.EXTENSION namespace
  383. if (attrName !== "options") {
  384. tree.ext[extName][attrName] = extension[attrName];
  385. }
  386. }
  387. }
  388. }
  389. function _getResolvedPromise(context, argArray) {
  390. if (context === undefined) {
  391. return $.Deferred(function () {
  392. this.resolve();
  393. }).promise();
  394. }
  395. return $.Deferred(function () {
  396. this.resolveWith(context, argArray);
  397. }).promise();
  398. }
  399. function _getRejectedPromise(context, argArray) {
  400. if (context === undefined) {
  401. return $.Deferred(function () {
  402. this.reject();
  403. }).promise();
  404. }
  405. return $.Deferred(function () {
  406. this.rejectWith(context, argArray);
  407. }).promise();
  408. }
  409. function _makeResolveFunc(deferred, context) {
  410. return function () {
  411. deferred.resolveWith(context);
  412. };
  413. }
  414. function _getElementDataAsDict($el) {
  415. // Evaluate 'data-NAME' attributes with special treatment for 'data-json'.
  416. var d = $.extend({}, $el.data()),
  417. json = d.json;
  418. delete d.fancytree; // added to container by widget factory (old jQuery UI)
  419. delete d.uiFancytree; // added to container by widget factory
  420. if (json) {
  421. delete d.json;
  422. // <li data-json='...'> is already returned as object (http://api.jquery.com/data/#data-html5)
  423. d = $.extend(d, json);
  424. }
  425. return d;
  426. }
  427. function _escapeTooltip(s) {
  428. return ("" + s).replace(REX_TOOLTIP, function (s) {
  429. return ENTITY_MAP[s];
  430. });
  431. }
  432. // TODO: use currying
  433. function _makeNodeTitleMatcher(s) {
  434. s = s.toLowerCase();
  435. return function (node) {
  436. return node.title.toLowerCase().indexOf(s) >= 0;
  437. };
  438. }
  439. function _makeNodeTitleStartMatcher(s) {
  440. var reMatch = new RegExp("^" + s, "i");
  441. return function (node) {
  442. return reMatch.test(node.title);
  443. };
  444. }
  445. /******************************************************************************
  446. * FancytreeNode
  447. */
  448. /**
  449. * Creates a new FancytreeNode
  450. *
  451. * @class FancytreeNode
  452. * @classdesc A FancytreeNode represents the hierarchical data model and operations.
  453. *
  454. * @param {FancytreeNode} parent
  455. * @param {NodeData} obj
  456. *
  457. * @property {Fancytree} tree The tree instance
  458. * @property {FancytreeNode} parent The parent node
  459. * @property {string} key Node id (must be unique inside the tree)
  460. * @property {string} title Display name (may contain HTML)
  461. * @property {object} data Contains all extra data that was passed on node creation
  462. * @property {FancytreeNode[] | null | undefined} children Array of child nodes.<br>
  463. * For lazy nodes, null or undefined means 'not yet loaded'. Use an empty array
  464. * to define a node that has no children.
  465. * @property {boolean} expanded Use isExpanded(), setExpanded() to access this property.
  466. * @property {string} extraClasses Additional CSS classes, added to the node's `<span>`.<br>
  467. * Note: use `node.add/remove/toggleClass()` to modify.
  468. * @property {boolean} folder Folder nodes have different default icons and click behavior.<br>
  469. * Note: Also non-folders may have children.
  470. * @property {string} statusNodeType null for standard nodes. Otherwise type of special system node: 'error', 'loading', 'nodata', or 'paging'.
  471. * @property {boolean} lazy True if this node is loaded on demand, i.e. on first expansion.
  472. * @property {boolean} selected Use isSelected(), setSelected() to access this property.
  473. * @property {string} tooltip Alternative description used as hover popup
  474. * @property {string} iconTooltip Description used as hover popup for icon. @since 2.27
  475. * @property {string} type Node type, used with tree.types map. @since 2.27
  476. */
  477. function FancytreeNode(parent, obj) {
  478. var i, l, name, cl;
  479. this.parent = parent;
  480. this.tree = parent.tree;
  481. this.ul = null;
  482. this.li = null; // <li id='key' ftnode=this> tag
  483. this.statusNodeType = null; // if this is a temp. node to display the status of its parent
  484. this._isLoading = false; // if this node itself is loading
  485. this._error = null; // {message: '...'} if a load error occurred
  486. this.data = {};
  487. // TODO: merge this code with node.toDict()
  488. // copy attributes from obj object
  489. for (i = 0, l = NODE_ATTRS.length; i < l; i++) {
  490. name = NODE_ATTRS[i];
  491. this[name] = obj[name];
  492. }
  493. // unselectableIgnore and unselectableStatus imply unselectable
  494. if (
  495. this.unselectableIgnore != null ||
  496. this.unselectableStatus != null
  497. ) {
  498. this.unselectable = true;
  499. }
  500. if (obj.hideCheckbox) {
  501. $.error(
  502. "'hideCheckbox' node option was removed in v2.23.0: use 'checkbox: false'"
  503. );
  504. }
  505. // node.data += obj.data
  506. if (obj.data) {
  507. $.extend(this.data, obj.data);
  508. }
  509. // Copy all other attributes to this.data.NAME
  510. for (name in obj) {
  511. if (
  512. !NODE_ATTR_MAP[name] &&
  513. (this.tree.options.copyFunctionsToData ||
  514. !_isFunction(obj[name])) &&
  515. !NONE_NODE_DATA_MAP[name]
  516. ) {
  517. // node.data.NAME = obj.NAME
  518. this.data[name] = obj[name];
  519. }
  520. }
  521. // Fix missing key
  522. if (this.key == null) {
  523. // test for null OR undefined
  524. if (this.tree.options.defaultKey) {
  525. this.key = "" + this.tree.options.defaultKey(this);
  526. _assert(this.key, "defaultKey() must return a unique key");
  527. } else {
  528. this.key = "_" + FT._nextNodeKey++;
  529. }
  530. } else {
  531. this.key = "" + this.key; // Convert to string (#217)
  532. }
  533. // Fix tree.activeNode
  534. // TODO: not elegant: we use obj.active as marker to set tree.activeNode
  535. // when loading from a dictionary.
  536. if (obj.active) {
  537. _assert(
  538. this.tree.activeNode === null,
  539. "only one active node allowed"
  540. );
  541. this.tree.activeNode = this;
  542. }
  543. if (obj.selected) {
  544. // #186
  545. this.tree.lastSelectedNode = this;
  546. }
  547. // TODO: handle obj.focus = true
  548. // Create child nodes
  549. cl = obj.children;
  550. if (cl) {
  551. if (cl.length) {
  552. this._setChildren(cl);
  553. } else {
  554. // if an empty array was passed for a lazy node, keep it, in order to mark it 'loaded'
  555. this.children = this.lazy ? [] : null;
  556. }
  557. } else {
  558. this.children = null;
  559. }
  560. // Add to key/ref map (except for root node)
  561. // if( parent ) {
  562. this.tree._callHook("treeRegisterNode", this.tree, true, this);
  563. // }
  564. }
  565. FancytreeNode.prototype = /** @lends FancytreeNode# */ {
  566. /* Return the direct child FancytreeNode with a given key, index. */
  567. _findDirectChild: function (ptr) {
  568. var i,
  569. l,
  570. cl = this.children;
  571. if (cl) {
  572. if (typeof ptr === "string") {
  573. for (i = 0, l = cl.length; i < l; i++) {
  574. if (cl[i].key === ptr) {
  575. return cl[i];
  576. }
  577. }
  578. } else if (typeof ptr === "number") {
  579. return this.children[ptr];
  580. } else if (ptr.parent === this) {
  581. return ptr;
  582. }
  583. }
  584. return null;
  585. },
  586. // TODO: activate()
  587. // TODO: activateSilently()
  588. /* Internal helper called in recursive addChildren sequence.*/
  589. _setChildren: function (children) {
  590. _assert(
  591. children && (!this.children || this.children.length === 0),
  592. "only init supported"
  593. );
  594. this.children = [];
  595. for (var i = 0, l = children.length; i < l; i++) {
  596. this.children.push(new FancytreeNode(this, children[i]));
  597. }
  598. this.tree._callHook(
  599. "treeStructureChanged",
  600. this.tree,
  601. "setChildren"
  602. );
  603. },
  604. /**
  605. * Append (or insert) a list of child nodes.
  606. *
  607. * @param {NodeData[]} children array of child node definitions (also single child accepted)
  608. * @param {FancytreeNode | string | Integer} [insertBefore] child node (or key or index of such).
  609. * If omitted, the new children are appended.
  610. * @returns {FancytreeNode} first child added
  611. *
  612. * @see FancytreeNode#applyPatch
  613. */
  614. addChildren: function (children, insertBefore) {
  615. var i,
  616. l,
  617. pos,
  618. origFirstChild = this.getFirstChild(),
  619. origLastChild = this.getLastChild(),
  620. firstNode = null,
  621. nodeList = [];
  622. if ($.isPlainObject(children)) {
  623. children = [children];
  624. }
  625. if (!this.children) {
  626. this.children = [];
  627. }
  628. for (i = 0, l = children.length; i < l; i++) {
  629. nodeList.push(new FancytreeNode(this, children[i]));
  630. }
  631. firstNode = nodeList[0];
  632. if (insertBefore == null) {
  633. this.children = this.children.concat(nodeList);
  634. } else {
  635. // Returns null if insertBefore is not a direct child:
  636. insertBefore = this._findDirectChild(insertBefore);
  637. pos = $.inArray(insertBefore, this.children);
  638. _assert(pos >= 0, "insertBefore must be an existing child");
  639. // insert nodeList after children[pos]
  640. this.children.splice.apply(
  641. this.children,
  642. [pos, 0].concat(nodeList)
  643. );
  644. }
  645. if (origFirstChild && !insertBefore) {
  646. // #708: Fast path -- don't render every child of root, just the new ones!
  647. // #723, #729: but only if it's appended to an existing child list
  648. for (i = 0, l = nodeList.length; i < l; i++) {
  649. nodeList[i].render(); // New nodes were never rendered before
  650. }
  651. // Adjust classes where status may have changed
  652. // Has a first child
  653. if (origFirstChild !== this.getFirstChild()) {
  654. // Different first child -- recompute classes
  655. origFirstChild.renderStatus();
  656. }
  657. if (origLastChild !== this.getLastChild()) {
  658. // Different last child -- recompute classes
  659. origLastChild.renderStatus();
  660. }
  661. } else if (!this.parent || this.parent.ul || this.tr) {
  662. // render if the parent was rendered (or this is a root node)
  663. this.render();
  664. }
  665. if (this.tree.options.selectMode === 3) {
  666. this.fixSelection3FromEndNodes();
  667. }
  668. this.triggerModifyChild(
  669. "add",
  670. nodeList.length === 1 ? nodeList[0] : null
  671. );
  672. return firstNode;
  673. },
  674. /**
  675. * Add class to node's span tag and to .extraClasses.
  676. *
  677. * @param {string} className class name
  678. *
  679. * @since 2.17
  680. */
  681. addClass: function (className) {
  682. return this.toggleClass(className, true);
  683. },
  684. /**
  685. * Append or prepend a node, or append a child node.
  686. *
  687. * This a convenience function that calls addChildren()
  688. *
  689. * @param {NodeData} node node definition
  690. * @param {string} [mode=child] 'before', 'after', 'firstChild', or 'child' ('over' is a synonym for 'child')
  691. * @returns {FancytreeNode} new node
  692. */
  693. addNode: function (node, mode) {
  694. if (mode === undefined || mode === "over") {
  695. mode = "child";
  696. }
  697. switch (mode) {
  698. case "after":
  699. return this.getParent().addChildren(
  700. node,
  701. this.getNextSibling()
  702. );
  703. case "before":
  704. return this.getParent().addChildren(node, this);
  705. case "firstChild":
  706. // Insert before the first child if any
  707. var insertBefore = this.children ? this.children[0] : null;
  708. return this.addChildren(node, insertBefore);
  709. case "child":
  710. case "over":
  711. return this.addChildren(node);
  712. }
  713. _assert(false, "Invalid mode: " + mode);
  714. },
  715. /**Add child status nodes that indicate 'More...', etc.
  716. *
  717. * This also maintains the node's `partload` property.
  718. * @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes.
  719. * @param {string} [mode='child'] 'child'|firstChild'
  720. * @since 2.15
  721. */
  722. addPagingNode: function (node, mode) {
  723. var i, n;
  724. mode = mode || "child";
  725. if (node === false) {
  726. for (i = this.children.length - 1; i >= 0; i--) {
  727. n = this.children[i];
  728. if (n.statusNodeType === "paging") {
  729. this.removeChild(n);
  730. }
  731. }
  732. this.partload = false;
  733. return;
  734. }
  735. node = $.extend(
  736. {
  737. title: this.tree.options.strings.moreData,
  738. statusNodeType: "paging",
  739. icon: false,
  740. },
  741. node
  742. );
  743. this.partload = true;
  744. return this.addNode(node, mode);
  745. },
  746. /**
  747. * Append new node after this.
  748. *
  749. * This a convenience function that calls addNode(node, 'after')
  750. *
  751. * @param {NodeData} node node definition
  752. * @returns {FancytreeNode} new node
  753. */
  754. appendSibling: function (node) {
  755. return this.addNode(node, "after");
  756. },
  757. /**
  758. * (experimental) Apply a modification (or navigation) operation.
  759. *
  760. * @param {string} cmd
  761. * @param {object} [opts]
  762. * @see Fancytree#applyCommand
  763. * @since 2.32
  764. */
  765. applyCommand: function (cmd, opts) {
  766. return this.tree.applyCommand(cmd, this, opts);
  767. },
  768. /**
  769. * Modify existing child nodes.
  770. *
  771. * @param {NodePatch} patch
  772. * @returns {$.Promise}
  773. * @see FancytreeNode#addChildren
  774. */
  775. applyPatch: function (patch) {
  776. // patch [key, null] means 'remove'
  777. if (patch === null) {
  778. this.remove();
  779. return _getResolvedPromise(this);
  780. }
  781. // TODO: make sure that root node is not collapsed or modified
  782. // copy (most) attributes to node.ATTR or node.data.ATTR
  783. var name,
  784. promise,
  785. v,
  786. IGNORE_MAP = { children: true, expanded: true, parent: true }; // TODO: should be global
  787. for (name in patch) {
  788. if (_hasProp(patch, name)) {
  789. v = patch[name];
  790. if (!IGNORE_MAP[name] && !_isFunction(v)) {
  791. if (NODE_ATTR_MAP[name]) {
  792. this[name] = v;
  793. } else {
  794. this.data[name] = v;
  795. }
  796. }
  797. }
  798. }
  799. // Remove and/or create children
  800. if (_hasProp(patch, "children")) {
  801. this.removeChildren();
  802. if (patch.children) {
  803. // only if not null and not empty list
  804. // TODO: addChildren instead?
  805. this._setChildren(patch.children);
  806. }
  807. // TODO: how can we APPEND or INSERT child nodes?
  808. }
  809. if (this.isVisible()) {
  810. this.renderTitle();
  811. this.renderStatus();
  812. }
  813. // Expand collapse (final step, since this may be async)
  814. if (_hasProp(patch, "expanded")) {
  815. promise = this.setExpanded(patch.expanded);
  816. } else {
  817. promise = _getResolvedPromise(this);
  818. }
  819. return promise;
  820. },
  821. /** Collapse all sibling nodes.
  822. * @returns {$.Promise}
  823. */
  824. collapseSiblings: function () {
  825. return this.tree._callHook("nodeCollapseSiblings", this);
  826. },
  827. /** Copy this node as sibling or child of `node`.
  828. *
  829. * @param {FancytreeNode} node source node
  830. * @param {string} [mode=child] 'before' | 'after' | 'child'
  831. * @param {Function} [map] callback function(NodeData, FancytreeNode) that could modify the new node
  832. * @returns {FancytreeNode} new
  833. */
  834. copyTo: function (node, mode, map) {
  835. return node.addNode(this.toDict(true, map), mode);
  836. },
  837. /** Count direct and indirect children.
  838. *
  839. * @param {boolean} [deep=true] pass 'false' to only count direct children
  840. * @returns {int} number of child nodes
  841. */
  842. countChildren: function (deep) {
  843. var cl = this.children,
  844. i,
  845. l,
  846. n;
  847. if (!cl) {
  848. return 0;
  849. }
  850. n = cl.length;
  851. if (deep !== false) {
  852. for (i = 0, l = n; i < l; i++) {
  853. n += cl[i].countChildren();
  854. }
  855. }
  856. return n;
  857. },
  858. // TODO: deactivate()
  859. /** Write to browser console if debugLevel >= 4 (prepending node info)
  860. *
  861. * @param {*} msg string or object or array of such
  862. */
  863. debug: function (msg) {
  864. if (this.tree.options.debugLevel >= 4) {
  865. Array.prototype.unshift.call(arguments, this.toString());
  866. consoleApply("log", arguments);
  867. }
  868. },
  869. /** Deprecated.
  870. * @deprecated since 2014-02-16. Use resetLazy() instead.
  871. */
  872. discard: function () {
  873. this.warn(
  874. "FancytreeNode.discard() is deprecated since 2014-02-16. Use .resetLazy() instead."
  875. );
  876. return this.resetLazy();
  877. },
  878. /** Remove DOM elements for all descendents. May be called on .collapse event
  879. * to keep the DOM small.
  880. * @param {boolean} [includeSelf=false]
  881. */
  882. discardMarkup: function (includeSelf) {
  883. var fn = includeSelf ? "nodeRemoveMarkup" : "nodeRemoveChildMarkup";
  884. this.tree._callHook(fn, this);
  885. },
  886. /** Write error to browser console if debugLevel >= 1 (prepending tree info)
  887. *
  888. * @param {*} msg string or object or array of such
  889. */
  890. error: function (msg) {
  891. if (this.tree.options.debugLevel >= 1) {
  892. Array.prototype.unshift.call(arguments, this.toString());
  893. consoleApply("error", arguments);
  894. }
  895. },
  896. /**Find all nodes that match condition (excluding self).
  897. *
  898. * @param {string | function(node)} match title string to search for, or a
  899. * callback function that returns `true` if a node is matched.
  900. * @returns {FancytreeNode[]} array of nodes (may be empty)
  901. */
  902. findAll: function (match) {
  903. match = _isFunction(match) ? match : _makeNodeTitleMatcher(match);
  904. var res = [];
  905. this.visit(function (n) {
  906. if (match(n)) {
  907. res.push(n);
  908. }
  909. });
  910. return res;
  911. },
  912. /**Find first node that matches condition (excluding self).
  913. *
  914. * @param {string | function(node)} match title string to search for, or a
  915. * callback function that returns `true` if a node is matched.
  916. * @returns {FancytreeNode} matching node or null
  917. * @see FancytreeNode#findAll
  918. */
  919. findFirst: function (match) {
  920. match = _isFunction(match) ? match : _makeNodeTitleMatcher(match);
  921. var res = null;
  922. this.visit(function (n) {
  923. if (match(n)) {
  924. res = n;
  925. return false;
  926. }
  927. });
  928. return res;
  929. },
  930. /** Find a node relative to self.
  931. *
  932. * @param {number|string} where The keyCode that would normally trigger this move,
  933. * or a keyword ('down', 'first', 'last', 'left', 'parent', 'right', 'up').
  934. * @returns {FancytreeNode}
  935. * @since v2.31
  936. */
  937. findRelatedNode: function (where, includeHidden) {
  938. return this.tree.findRelatedNode(this, where, includeHidden);
  939. },
  940. /* Apply selection state (internal use only) */
  941. _changeSelectStatusAttrs: function (state) {
  942. var changed = false,
  943. opts = this.tree.options,
  944. unselectable = FT.evalOption(
  945. "unselectable",
  946. this,
  947. this,
  948. opts,
  949. false
  950. ),
  951. unselectableStatus = FT.evalOption(
  952. "unselectableStatus",
  953. this,
  954. this,
  955. opts,
  956. undefined
  957. );
  958. if (unselectable && unselectableStatus != null) {
  959. state = unselectableStatus;
  960. }
  961. switch (state) {
  962. case false:
  963. changed = this.selected || this.partsel;
  964. this.selected = false;
  965. this.partsel = false;
  966. break;
  967. case true:
  968. changed = !this.selected || !this.partsel;
  969. this.selected = true;
  970. this.partsel = true;
  971. break;
  972. case undefined:
  973. changed = this.selected || !this.partsel;
  974. this.selected = false;
  975. this.partsel = true;
  976. break;
  977. default:
  978. _assert(false, "invalid state: " + state);
  979. }
  980. // this.debug("fixSelection3AfterLoad() _changeSelectStatusAttrs()", state, changed);
  981. if (changed) {
  982. this.renderStatus();
  983. }
  984. return changed;
  985. },
  986. /**
  987. * Fix selection status, after this node was (de)selected in multi-hier mode.
  988. * This includes (de)selecting all children.
  989. */
  990. fixSelection3AfterClick: function (callOpts) {
  991. var flag = this.isSelected();
  992. // this.debug("fixSelection3AfterClick()");
  993. this.visit(function (node) {
  994. node._changeSelectStatusAttrs(flag);
  995. if (node.radiogroup) {
  996. // #931: don't (de)select this branch
  997. return "skip";
  998. }
  999. });
  1000. this.fixSelection3FromEndNodes(callOpts);
  1001. },
  1002. /**
  1003. * Fix selection status for multi-hier mode.
  1004. * Only end-nodes are considered to update the descendants branch and parents.
  1005. * Should be called after this node has loaded new children or after
  1006. * children have been modified using the API.
  1007. */
  1008. fixSelection3FromEndNodes: function (callOpts) {
  1009. var opts = this.tree.options;
  1010. // this.debug("fixSelection3FromEndNodes()");
  1011. _assert(opts.selectMode === 3, "expected selectMode 3");
  1012. // Visit all end nodes and adjust their parent's `selected` and `partsel`
  1013. // attributes. Return selection state true, false, or undefined.
  1014. function _walk(node) {
  1015. var i,
  1016. l,
  1017. child,
  1018. s,
  1019. state,
  1020. allSelected,
  1021. someSelected,
  1022. unselIgnore,
  1023. unselState,
  1024. children = node.children;
  1025. if (children && children.length) {
  1026. // check all children recursively
  1027. allSelected = true;
  1028. someSelected = false;
  1029. for (i = 0, l = children.length; i < l; i++) {
  1030. child = children[i];
  1031. // the selection state of a node is not relevant; we need the end-nodes
  1032. s = _walk(child);
  1033. // if( !child.unselectableIgnore ) {
  1034. unselIgnore = FT.evalOption(
  1035. "unselectableIgnore",
  1036. child,
  1037. child,
  1038. opts,
  1039. false
  1040. );
  1041. if (!unselIgnore) {
  1042. if (s !== false) {
  1043. someSelected = true;
  1044. }
  1045. if (s !== true) {
  1046. allSelected = false;
  1047. }
  1048. }
  1049. }
  1050. // eslint-disable-next-line no-nested-ternary
  1051. state = allSelected
  1052. ? true
  1053. : someSelected
  1054. ? undefined
  1055. : false;
  1056. } else {
  1057. // This is an end-node: simply report the status
  1058. unselState = FT.evalOption(
  1059. "unselectableStatus",
  1060. node,
  1061. node,
  1062. opts,
  1063. undefined
  1064. );
  1065. state = unselState == null ? !!node.selected : !!unselState;
  1066. }
  1067. // #939: Keep a `partsel` flag that was explicitly set on a lazy node
  1068. if (
  1069. node.partsel &&
  1070. !node.selected &&
  1071. node.lazy &&
  1072. node.children == null
  1073. ) {
  1074. state = undefined;
  1075. }
  1076. node._changeSelectStatusAttrs(state);
  1077. return state;
  1078. }
  1079. _walk(this);
  1080. // Update parent's state
  1081. this.visitParents(function (node) {
  1082. var i,
  1083. l,
  1084. child,
  1085. state,
  1086. unselIgnore,
  1087. unselState,
  1088. children = node.children,
  1089. allSelected = true,
  1090. someSelected = false;
  1091. for (i = 0, l = children.length; i < l; i++) {
  1092. child = children[i];
  1093. unselIgnore = FT.evalOption(
  1094. "unselectableIgnore",
  1095. child,
  1096. child,
  1097. opts,
  1098. false
  1099. );
  1100. if (!unselIgnore) {
  1101. unselState = FT.evalOption(
  1102. "unselectableStatus",
  1103. child,
  1104. child,
  1105. opts,
  1106. undefined
  1107. );
  1108. state =
  1109. unselState == null
  1110. ? !!child.selected
  1111. : !!unselState;
  1112. // When fixing the parents, we trust the sibling status (i.e.
  1113. // we don't recurse)
  1114. if (state || child.partsel) {
  1115. someSelected = true;
  1116. }
  1117. if (!state) {
  1118. allSelected = false;
  1119. }
  1120. }
  1121. }
  1122. // eslint-disable-next-line no-nested-ternary
  1123. state = allSelected ? true : someSelected ? undefined : false;
  1124. node._changeSelectStatusAttrs(state);
  1125. });
  1126. },
  1127. // TODO: focus()
  1128. /**
  1129. * Update node data. If dict contains 'children', then also replace
  1130. * the hole sub tree.
  1131. * @param {NodeData} dict
  1132. *
  1133. * @see FancytreeNode#addChildren
  1134. * @see FancytreeNode#applyPatch
  1135. */
  1136. fromDict: function (dict) {
  1137. // copy all other attributes to this.data.xxx
  1138. for (var name in dict) {
  1139. if (NODE_ATTR_MAP[name]) {
  1140. // node.NAME = dict.NAME
  1141. this[name] = dict[name];
  1142. } else if (name === "data") {
  1143. // node.data += dict.data
  1144. $.extend(this.data, dict.data);
  1145. } else if (
  1146. !_isFunction(dict[name]) &&
  1147. !NONE_NODE_DATA_MAP[name]
  1148. ) {
  1149. // node.data.NAME = dict.NAME
  1150. this.data[name] = dict[name];
  1151. }
  1152. }
  1153. if (dict.children) {
  1154. // recursively set children and render
  1155. this.removeChildren();
  1156. this.addChildren(dict.children);
  1157. }
  1158. this.renderTitle();
  1159. /*
  1160. var children = dict.children;
  1161. if(children === undefined){
  1162. this.data = $.extend(this.data, dict);
  1163. this.render();
  1164. return;
  1165. }
  1166. dict = $.extend({}, dict);
  1167. dict.children = undefined;
  1168. this.data = $.extend(this.data, dict);
  1169. this.removeChildren();
  1170. this.addChild(children);
  1171. */
  1172. },
  1173. /** Return the list of child nodes (undefined for unexpanded lazy nodes).
  1174. * @returns {FancytreeNode[] | undefined}
  1175. */
  1176. getChildren: function () {
  1177. if (this.hasChildren() === undefined) {
  1178. // TODO: only required for lazy nodes?
  1179. return undefined; // Lazy node: unloaded, currently loading, or load error
  1180. }
  1181. return this.children;
  1182. },
  1183. /** Return the first child node or null.
  1184. * @returns {FancytreeNode | null}
  1185. */
  1186. getFirstChild: function () {
  1187. return this.children ? this.children[0] : null;
  1188. },
  1189. /** Return the 0-based child index.
  1190. * @returns {int}
  1191. */
  1192. getIndex: function () {
  1193. // return this.parent.children.indexOf(this);
  1194. return $.inArray(this, this.parent.children); // indexOf doesn't work in IE7
  1195. },
  1196. /** Return the hierarchical child index (1-based, e.g. '3.2.4').
  1197. * @param {string} [separator="."]
  1198. * @param {int} [digits=1]
  1199. * @returns {string}
  1200. */
  1201. getIndexHier: function (separator, digits) {
  1202. separator = separator || ".";
  1203. var s,
  1204. res = [];
  1205. $.each(this.getParentList(false, true), function (i, o) {
  1206. s = "" + (o.getIndex() + 1);
  1207. if (digits) {
  1208. // prepend leading zeroes
  1209. s = ("0000000" + s).substr(-digits);
  1210. }
  1211. res.push(s);
  1212. });
  1213. return res.join(separator);
  1214. },
  1215. /** Return the parent keys separated by options.keyPathSeparator, e.g. "/id_1/id_17/id_32".
  1216. *
  1217. * (Unlike `node.getPath()`, this method prepends a "/" and inverts the first argument.)
  1218. *
  1219. * @see FancytreeNode#getPath
  1220. * @param {boolean} [excludeSelf=false]
  1221. * @returns {string}
  1222. */
  1223. getKeyPath: function (excludeSelf) {
  1224. var sep = this.tree.options.keyPathSeparator;
  1225. return sep + this.getPath(!excludeSelf, "key", sep);
  1226. },
  1227. /** Return the last child of this node or null.
  1228. * @returns {FancytreeNode | null}
  1229. */
  1230. getLastChild: function () {
  1231. return this.children
  1232. ? this.children[this.children.length - 1]
  1233. : null;
  1234. },
  1235. /** Return node depth. 0: System root node, 1: visible top-level node, 2: first sub-level, ... .
  1236. * @returns {int}
  1237. */
  1238. getLevel: function () {
  1239. var level = 0,
  1240. dtn = this.parent;
  1241. while (dtn) {
  1242. level++;
  1243. dtn = dtn.parent;
  1244. }
  1245. return level;
  1246. },
  1247. /** Return the successor node (under the same parent) or null.
  1248. * @returns {FancytreeNode | null}
  1249. */
  1250. getNextSibling: function () {
  1251. // TODO: use indexOf, if available: (not in IE6)
  1252. if (this.parent) {
  1253. var i,
  1254. l,
  1255. ac = this.parent.children;
  1256. for (i = 0, l = ac.length - 1; i < l; i++) {
  1257. // up to length-2, so next(last) = null
  1258. if (ac[i] === this) {
  1259. return ac[i + 1];
  1260. }
  1261. }
  1262. }
  1263. return null;
  1264. },
  1265. /** Return the parent node (null for the system root node).
  1266. * @returns {FancytreeNode | null}
  1267. */
  1268. getParent: function () {
  1269. // TODO: return null for top-level nodes?
  1270. return this.parent;
  1271. },
  1272. /** Return an array of all parent nodes (top-down).
  1273. * @param {boolean} [includeRoot=false] Include the invisible system root node.
  1274. * @param {boolean} [includeSelf=false] Include the node itself.
  1275. * @returns {FancytreeNode[]}
  1276. */
  1277. getParentList: function (includeRoot, includeSelf) {
  1278. var l = [],
  1279. dtn = includeSelf ? this : this.parent;
  1280. while (dtn) {
  1281. if (includeRoot || dtn.parent) {
  1282. l.unshift(dtn);
  1283. }
  1284. dtn = dtn.parent;
  1285. }
  1286. return l;
  1287. },
  1288. /** Return a string representing the hierachical node path, e.g. "a/b/c".
  1289. * @param {boolean} [includeSelf=true]
  1290. * @param {string | function} [part="title"] node property name or callback
  1291. * @param {string} [separator="/"]
  1292. * @returns {string}
  1293. * @since v2.31
  1294. */
  1295. getPath: function (includeSelf, part, separator) {
  1296. includeSelf = includeSelf !== false;
  1297. part = part || "title";
  1298. separator = separator || "/";
  1299. var val,
  1300. path = [],
  1301. isFunc = _isFunction(part);
  1302. this.visitParents(function (n) {
  1303. if (n.parent) {
  1304. val = isFunc ? part(n) : n[part];
  1305. path.unshift(val);
  1306. }
  1307. }, includeSelf);
  1308. return path.join(separator);
  1309. },
  1310. /** Return the predecessor node (under the same parent) or null.
  1311. * @returns {FancytreeNode | null}
  1312. */
  1313. getPrevSibling: function () {
  1314. if (this.parent) {
  1315. var i,
  1316. l,
  1317. ac = this.parent.children;
  1318. for (i = 1, l = ac.length; i < l; i++) {
  1319. // start with 1, so prev(first) = null
  1320. if (ac[i] === this) {
  1321. return ac[i - 1];
  1322. }
  1323. }
  1324. }
  1325. return null;
  1326. },
  1327. /**
  1328. * Return an array of selected descendant nodes.
  1329. * @param {boolean} [stopOnParents=false] only return the topmost selected
  1330. * node (useful with selectMode 3)
  1331. * @returns {FancytreeNode[]}
  1332. */
  1333. getSelectedNodes: function (stopOnParents) {
  1334. var nodeList = [];
  1335. this.visit(function (node) {
  1336. if (node.selected) {
  1337. nodeList.push(node);
  1338. if (stopOnParents === true) {
  1339. return "skip"; // stop processing this branch
  1340. }
  1341. }
  1342. });
  1343. return nodeList;
  1344. },
  1345. /** Return true if node has children. Return undefined if not sure, i.e. the node is lazy and not yet loaded).
  1346. * @returns {boolean | undefined}
  1347. */
  1348. hasChildren: function () {
  1349. if (this.lazy) {
  1350. if (this.children == null) {
  1351. // null or undefined: Not yet loaded
  1352. return undefined;
  1353. } else if (this.children.length === 0) {
  1354. // Loaded, but response was empty
  1355. return false;
  1356. } else if (
  1357. this.children.length === 1 &&
  1358. this.children[0].isStatusNode()
  1359. ) {
  1360. // Currently loading or load error
  1361. return undefined;
  1362. }
  1363. return true;
  1364. }
  1365. return !!(this.children && this.children.length);
  1366. },
  1367. /**
  1368. * Return true if node has `className` defined in .extraClasses.
  1369. *
  1370. * @param {string} className class name (separate multiple classes by space)
  1371. * @returns {boolean}
  1372. *
  1373. * @since 2.32
  1374. */
  1375. hasClass: function (className) {
  1376. return (
  1377. (" " + (this.extraClasses || "") + " ").indexOf(
  1378. " " + className + " "
  1379. ) >= 0
  1380. );
  1381. },
  1382. /** Return true if node has keyboard focus.
  1383. * @returns {boolean}
  1384. */
  1385. hasFocus: function () {
  1386. return this.tree.hasFocus() && this.tree.focusNode === this;
  1387. },
  1388. /** Write to browser console if debugLevel >= 3 (prepending node info)
  1389. *
  1390. * @param {*} msg string or object or array of such
  1391. */
  1392. info: function (msg) {
  1393. if (this.tree.options.debugLevel >= 3) {
  1394. Array.prototype.unshift.call(arguments, this.toString());
  1395. consoleApply("info", arguments);
  1396. }
  1397. },
  1398. /** Return true if node is active (see also FancytreeNode#isSelected).
  1399. * @returns {boolean}
  1400. */
  1401. isActive: function () {
  1402. return this.tree.activeNode === this;
  1403. },
  1404. /** Return true if node is vertically below `otherNode`, i.e. rendered in a subsequent row.
  1405. * @param {FancytreeNode} otherNode
  1406. * @returns {boolean}
  1407. * @since 2.28
  1408. */
  1409. isBelowOf: function (otherNode) {
  1410. return this.getIndexHier(".", 5) > otherNode.getIndexHier(".", 5);
  1411. },
  1412. /** Return true if node is a direct child of otherNode.
  1413. * @param {FancytreeNode} otherNode
  1414. * @returns {boolean}
  1415. */
  1416. isChildOf: function (otherNode) {
  1417. return this.parent && this.parent === otherNode;
  1418. },
  1419. /** Return true, if node is a direct or indirect sub node of otherNode.
  1420. * @param {FancytreeNode} otherNode
  1421. * @returns {boolean}
  1422. */
  1423. isDescendantOf: function (otherNode) {
  1424. if (!otherNode || otherNode.tree !== this.tree) {
  1425. return false;
  1426. }
  1427. var p = this.parent;
  1428. while (p) {
  1429. if (p === otherNode) {
  1430. return true;
  1431. }
  1432. if (p === p.parent) {
  1433. $.error("Recursive parent link: " + p);
  1434. }
  1435. p = p.parent;
  1436. }
  1437. return false;
  1438. },
  1439. /** Return true if node is expanded.
  1440. * @returns {boolean}
  1441. */
  1442. isExpanded: function () {
  1443. return !!this.expanded;
  1444. },
  1445. /** Return true if node is the first node of its parent's children.
  1446. * @returns {boolean}
  1447. */
  1448. isFirstSibling: function () {
  1449. var p = this.parent;
  1450. return !p || p.children[0] === this;
  1451. },
  1452. /** Return true if node is a folder, i.e. has the node.folder attribute set.
  1453. * @returns {boolean}
  1454. */
  1455. isFolder: function () {
  1456. return !!this.folder;
  1457. },
  1458. /** Return true if node is the last node of its parent's children.
  1459. * @returns {boolean}
  1460. */
  1461. isLastSibling: function () {
  1462. var p = this.parent;
  1463. return !p || p.children[p.children.length - 1] === this;
  1464. },
  1465. /** Return true if node is lazy (even if data was already loaded)
  1466. * @returns {boolean}
  1467. */
  1468. isLazy: function () {
  1469. return !!this.lazy;
  1470. },
  1471. /** Return true if node is lazy and loaded. For non-lazy nodes always return true.
  1472. * @returns {boolean}
  1473. */
  1474. isLoaded: function () {
  1475. return !this.lazy || this.hasChildren() !== undefined; // Also checks if the only child is a status node
  1476. },
  1477. /** Return true if children are currently beeing loaded, i.e. a Ajax request is pending.
  1478. * @returns {boolean}
  1479. */
  1480. isLoading: function () {
  1481. return !!this._isLoading;
  1482. },
  1483. /*
  1484. * @deprecated since v2.4.0: Use isRootNode() instead
  1485. */
  1486. isRoot: function () {
  1487. return this.isRootNode();
  1488. },
  1489. /** Return true if node is partially selected (tri-state).
  1490. * @returns {boolean}
  1491. * @since 2.23
  1492. */
  1493. isPartsel: function () {
  1494. return !this.selected && !!this.partsel;
  1495. },
  1496. /** (experimental) Return true if this is partially loaded.
  1497. * @returns {boolean}
  1498. * @since 2.15
  1499. */
  1500. isPartload: function () {
  1501. return !!this.partload;
  1502. },
  1503. /** Return true if this is the (invisible) system root node.
  1504. * @returns {boolean}
  1505. * @since 2.4
  1506. */
  1507. isRootNode: function () {
  1508. return this.tree.rootNode === this;
  1509. },
  1510. /** Return true if node is selected, i.e. has a checkmark set (see also FancytreeNode#isActive).
  1511. * @returns {boolean}
  1512. */
  1513. isSelected: function () {
  1514. return !!this.selected;
  1515. },
  1516. /** Return true if this node is a temporarily generated system node like
  1517. * 'loading', 'paging', or 'error' (node.statusNodeType contains the type).
  1518. * @returns {boolean}
  1519. */
  1520. isStatusNode: function () {
  1521. return !!this.statusNodeType;
  1522. },
  1523. /** Return true if this node is a status node of type 'paging'.
  1524. * @returns {boolean}
  1525. * @since 2.15
  1526. */
  1527. isPagingNode: function () {
  1528. return this.statusNodeType === "paging";
  1529. },
  1530. /** Return true if this a top level node, i.e. a direct child of the (invisible) system root node.
  1531. * @returns {boolean}
  1532. * @since 2.4
  1533. */
  1534. isTopLevel: function () {
  1535. return this.tree.rootNode === this.parent;
  1536. },
  1537. /** Return true if node is lazy and not yet loaded. For non-lazy nodes always return false.
  1538. * @returns {boolean}
  1539. */
  1540. isUndefined: function () {
  1541. return this.hasChildren() === undefined; // also checks if the only child is a status node
  1542. },
  1543. /** Return true if all parent nodes are expanded. Note: this does not check
  1544. * whether the node is scrolled into the visible part of the screen.
  1545. * @returns {boolean}
  1546. */
  1547. isVisible: function () {
  1548. var i,
  1549. l,
  1550. n,
  1551. hasFilter = this.tree.enableFilter,
  1552. parents = this.getParentList(false, false);
  1553. // TODO: check $(n.span).is(":visible")
  1554. // i.e. return false for nodes (but not parents) that are hidden
  1555. // by a filter
  1556. if (hasFilter && !this.match && !this.subMatchCount) {
  1557. // this.debug( "isVisible: HIDDEN (" + hasFilter + ", " + this.match + ", " + this.match + ")" );
  1558. return false;
  1559. }
  1560. for (i = 0, l = parents.length; i < l; i++) {
  1561. n = parents[i];
  1562. if (!n.expanded) {
  1563. // this.debug("isVisible: HIDDEN (parent collapsed)");
  1564. return false;
  1565. }
  1566. // if (hasFilter && !n.match && !n.subMatchCount) {
  1567. // this.debug("isVisible: HIDDEN (" + hasFilter + ", " + this.match + ", " + this.match + ")");
  1568. // return false;
  1569. // }
  1570. }
  1571. // this.debug("isVisible: VISIBLE");
  1572. return true;
  1573. },
  1574. /** Deprecated.
  1575. * @deprecated since 2014-02-16: use load() instead.
  1576. */
  1577. lazyLoad: function (discard) {
  1578. $.error(
  1579. "FancytreeNode.lazyLoad() is deprecated since 2014-02-16. Use .load() instead."
  1580. );
  1581. },
  1582. /**
  1583. * Load all children of a lazy node if neccessary. The <i>expanded</i> state is maintained.
  1584. * @param {boolean} [forceReload=false] Pass true to discard any existing nodes before. Otherwise this method does nothing if the node was already loaded.
  1585. * @returns {$.Promise}
  1586. */
  1587. load: function (forceReload) {
  1588. var res,
  1589. source,
  1590. self = this,
  1591. wasExpanded = this.isExpanded();
  1592. _assert(this.isLazy(), "load() requires a lazy node");
  1593. // _assert( forceReload || this.isUndefined(), "Pass forceReload=true to re-load a lazy node" );
  1594. if (!forceReload && !this.isUndefined()) {
  1595. return _getResolvedPromise(this);
  1596. }
  1597. if (this.isLoaded()) {
  1598. this.resetLazy(); // also collapses
  1599. }
  1600. // This method is also called by setExpanded() and loadKeyPath(), so we
  1601. // have to avoid recursion.
  1602. source = this.tree._triggerNodeEvent("lazyLoad", this);
  1603. if (source === false) {
  1604. // #69
  1605. return _getResolvedPromise(this);
  1606. }
  1607. _assert(
  1608. typeof source !== "boolean",
  1609. "lazyLoad event must return source in data.result"
  1610. );
  1611. res = this.tree._callHook("nodeLoadChildren", this, source);
  1612. if (wasExpanded) {
  1613. this.expanded = true;
  1614. res.always(function () {
  1615. self.render();
  1616. });
  1617. } else {
  1618. res.always(function () {
  1619. self.renderStatus(); // fix expander icon to 'loaded'
  1620. });
  1621. }
  1622. return res;
  1623. },
  1624. /** Expand all parents and optionally scroll into visible area as neccessary.
  1625. * Promise is resolved, when lazy loading and animations are done.
  1626. * @param {object} [opts] passed to `setExpanded()`.
  1627. * Defaults to {noAnimation: false, noEvents: false, scrollIntoView: true}
  1628. * @returns {$.Promise}
  1629. */
  1630. makeVisible: function (opts) {
  1631. var i,
  1632. self = this,
  1633. deferreds = [],
  1634. dfd = new $.Deferred(),
  1635. parents = this.getParentList(false, false),
  1636. len = parents.length,
  1637. effects = !(opts && opts.noAnimation === true),
  1638. scroll = !(opts && opts.scrollIntoView === false);
  1639. // Expand bottom-up, so only the top node is animated
  1640. for (i = len - 1; i >= 0; i--) {
  1641. // self.debug("pushexpand" + parents[i]);
  1642. deferreds.push(parents[i].setExpanded(true, opts));
  1643. }
  1644. $.when.apply($, deferreds).done(function () {
  1645. // All expands have finished
  1646. // self.debug("expand DONE", scroll);
  1647. if (scroll) {
  1648. self.scrollIntoView(effects).done(function () {
  1649. // self.debug("scroll DONE");
  1650. dfd.resolve();
  1651. });
  1652. } else {
  1653. dfd.resolve();
  1654. }
  1655. });
  1656. return dfd.promise();
  1657. },
  1658. /** Move this node to targetNode.
  1659. * @param {FancytreeNode} targetNode
  1660. * @param {string} mode <pre>
  1661. * 'child': append this node as last child of targetNode.
  1662. * This is the default. To be compatble with the D'n'd
  1663. * hitMode, we also accept 'over'.
  1664. * 'firstChild': add this node as first child of targetNode.
  1665. * 'before': add this node as sibling before targetNode.
  1666. * 'after': add this node as sibling after targetNode.</pre>
  1667. * @param {function} [map] optional callback(FancytreeNode) to allow modifcations
  1668. */
  1669. moveTo: function (targetNode, mode, map) {
  1670. if (mode === undefined || mode === "over") {
  1671. mode = "child";
  1672. } else if (mode === "firstChild") {
  1673. if (targetNode.children && targetNode.children.length) {
  1674. mode = "before";
  1675. targetNode = targetNode.children[0];
  1676. } else {
  1677. mode = "child";
  1678. }
  1679. }
  1680. var pos,
  1681. tree = this.tree,
  1682. prevParent = this.parent,
  1683. targetParent =
  1684. mode === "child" ? targetNode : targetNode.parent;
  1685. if (this === targetNode) {
  1686. return;
  1687. } else if (!this.parent) {
  1688. $.error("Cannot move system root");
  1689. } else if (targetParent.isDescendantOf(this)) {
  1690. $.error("Cannot move a node to its own descendant");
  1691. }
  1692. if (targetParent !== prevParent) {
  1693. prevParent.triggerModifyChild("remove", this);
  1694. }
  1695. // Unlink this node from current parent
  1696. if (this.parent.children.length === 1) {
  1697. if (this.parent === targetParent) {
  1698. return; // #258
  1699. }
  1700. this.parent.children = this.parent.lazy ? [] : null;
  1701. this.parent.expanded = false;
  1702. } else {
  1703. pos = $.inArray(this, this.parent.children);
  1704. _assert(pos >= 0, "invalid source parent");
  1705. this.parent.children.splice(pos, 1);
  1706. }
  1707. // Remove from source DOM parent
  1708. // if(this.parent.ul){
  1709. // this.parent.ul.removeChild(this.li);
  1710. // }
  1711. // Insert this node to target parent's child list
  1712. this.parent = targetParent;
  1713. if (targetParent.hasChildren()) {
  1714. switch (mode) {
  1715. case "child":
  1716. // Append to existing target children
  1717. targetParent.children.push(this);
  1718. break;
  1719. case "before":
  1720. // Insert this node before target node
  1721. pos = $.inArray(targetNode, targetParent.children);
  1722. _assert(pos >= 0, "invalid target parent");
  1723. targetParent.children.splice(pos, 0, this);
  1724. break;
  1725. case "after":
  1726. // Insert this node after target node
  1727. pos = $.inArray(targetNode, targetParent.children);
  1728. _assert(pos >= 0, "invalid target parent");
  1729. targetParent.children.splice(pos + 1, 0, this);
  1730. break;
  1731. default:
  1732. $.error("Invalid mode " + mode);
  1733. }
  1734. } else {
  1735. targetParent.children = [this];
  1736. }
  1737. // Parent has no <ul> tag yet:
  1738. // if( !targetParent.ul ) {
  1739. // // This is the parent's first child: create UL tag
  1740. // // (Hidden, because it will be
  1741. // targetParent.ul = document.createElement("ul");
  1742. // targetParent.ul.style.display = "none";
  1743. // targetParent.li.appendChild(targetParent.ul);
  1744. // }
  1745. // // Issue 319: Add to target DOM parent (only if node was already rendered(expanded))
  1746. // if(this.li){
  1747. // targetParent.ul.appendChild(this.li);
  1748. // }
  1749. // Let caller modify the nodes
  1750. if (map) {
  1751. targetNode.visit(map, true);
  1752. }
  1753. if (targetParent === prevParent) {
  1754. targetParent.triggerModifyChild("move", this);
  1755. } else {
  1756. // prevParent.triggerModifyChild("remove", this);
  1757. targetParent.triggerModifyChild("add", this);
  1758. }
  1759. // Handle cross-tree moves
  1760. if (tree !== targetNode.tree) {
  1761. // Fix node.tree for all source nodes
  1762. // _assert(false, "Cross-tree move is not yet implemented.");
  1763. this.warn("Cross-tree moveTo is experimental!");
  1764. this.visit(function (n) {
  1765. // TODO: fix selection state and activation, ...
  1766. n.tree = targetNode.tree;
  1767. }, true);
  1768. }
  1769. // A collaposed node won't re-render children, so we have to remove it manually
  1770. // if( !targetParent.expanded ){
  1771. // prevParent.ul.removeChild(this.li);
  1772. // }
  1773. tree._callHook("treeStructureChanged", tree, "moveTo");
  1774. // Update HTML markup
  1775. if (!prevParent.isDescendantOf(targetParent)) {
  1776. prevParent.render();
  1777. }
  1778. if (
  1779. !targetParent.isDescendantOf(prevParent) &&
  1780. targetParent !== prevParent
  1781. ) {
  1782. targetParent.render();
  1783. }
  1784. // TODO: fix selection state
  1785. // TODO: fix active state
  1786. /*
  1787. var tree = this.tree;
  1788. var opts = tree.options;
  1789. var pers = tree.persistence;
  1790. // Always expand, if it's below minExpandLevel
  1791. // tree.logDebug ("%s._addChildNode(%o), l=%o", this, ftnode, ftnode.getLevel());
  1792. if ( opts.minExpandLevel >= ftnode.getLevel() ) {
  1793. // tree.logDebug ("Force expand for %o", ftnode);
  1794. this.bExpanded = true;
  1795. }
  1796. // In multi-hier mode, update the parents selection state
  1797. // DT issue #82: only if not initializing, because the children may not exist yet
  1798. // if( !ftnode.data.isStatusNode() && opts.selectMode==3 && !isInitializing )
  1799. // ftnode._fixSelectionState();
  1800. // In multi-hier mode, update the parents selection state
  1801. if( ftnode.bSelected && opts.selectMode==3 ) {
  1802. var p = this;
  1803. while( p ) {
  1804. if( !p.hasSubSel )
  1805. p._setSubSel(true);
  1806. p = p.parent;
  1807. }
  1808. }
  1809. // render this node and the new child
  1810. if ( tree.bEnableUpdate )
  1811. this.render();
  1812. return ftnode;
  1813. */
  1814. },
  1815. /** Set focus relative to this node and optionally activate.
  1816. *
  1817. * 'left' collapses the node if it is expanded, or move to the parent
  1818. * otherwise.
  1819. * 'right' expands the node if it is collapsed, or move to the first
  1820. * child otherwise.
  1821. *
  1822. * @param {string|number} where 'down', 'first', 'last', 'left', 'parent', 'right', or 'up'.
  1823. * (Alternatively the keyCode that would normally trigger this move,
  1824. * e.g. `$.ui.keyCode.LEFT` = 'left'.
  1825. * @param {boolean} [activate=true]
  1826. * @returns {$.Promise}
  1827. */
  1828. navigate: function (where, activate) {
  1829. var node,
  1830. KC = $.ui.keyCode;
  1831. // Handle optional expand/collapse action for LEFT/RIGHT
  1832. switch (where) {
  1833. case "left":
  1834. case KC.LEFT:
  1835. if (this.expanded) {
  1836. return this.setExpanded(false);
  1837. }
  1838. break;
  1839. case "right":
  1840. case KC.RIGHT:
  1841. if (!this.expanded && (this.children || this.lazy)) {
  1842. return this.setExpanded();
  1843. }
  1844. break;
  1845. }
  1846. // Otherwise activate or focus the related node
  1847. node = this.findRelatedNode(where);
  1848. if (node) {
  1849. // setFocus/setActive will scroll later (if autoScroll is specified)
  1850. try {
  1851. node.makeVisible({ scrollIntoView: false });
  1852. } catch (e) {} // #272
  1853. if (activate === false) {
  1854. node.setFocus();
  1855. return _getResolvedPromise();
  1856. }
  1857. return node.setActive();
  1858. }
  1859. this.warn("Could not find related node '" + where + "'.");
  1860. return _getResolvedPromise();
  1861. },
  1862. /**
  1863. * Remove this node (not allowed for system root).
  1864. */
  1865. remove: function () {
  1866. return this.parent.removeChild(this);
  1867. },
  1868. /**
  1869. * Remove childNode from list of direct children.
  1870. * @param {FancytreeNode} childNode
  1871. */
  1872. removeChild: function (childNode) {
  1873. return this.tree._callHook("nodeRemoveChild", this, childNode);
  1874. },
  1875. /**
  1876. * Remove all child nodes and descendents. This converts the node into a leaf.<br>
  1877. * If this was a lazy node, it is still considered 'loaded'; call node.resetLazy()
  1878. * in order to trigger lazyLoad on next expand.
  1879. */
  1880. removeChildren: function () {
  1881. return this.tree._callHook("nodeRemoveChildren", this);
  1882. },
  1883. /**
  1884. * Remove class from node's span tag and .extraClasses.
  1885. *
  1886. * @param {string} className class name
  1887. *
  1888. * @since 2.17
  1889. */
  1890. removeClass: function (className) {
  1891. return this.toggleClass(className, false);
  1892. },
  1893. /**
  1894. * This method renders and updates all HTML markup that is required
  1895. * to display this node in its current state.<br>
  1896. * Note:
  1897. * <ul>
  1898. * <li>It should only be neccessary to call this method after the node object
  1899. * was modified by direct access to its properties, because the common
  1900. * API methods (node.setTitle(), moveTo(), addChildren(), remove(), ...)
  1901. * already handle this.
  1902. * <li> {@link FancytreeNode#renderTitle} and {@link FancytreeNode#renderStatus}
  1903. * are implied. If changes are more local, calling only renderTitle() or
  1904. * renderStatus() may be sufficient and faster.
  1905. * </ul>
  1906. *
  1907. * @param {boolean} [force=false] re-render, even if html markup was already created
  1908. * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
  1909. */
  1910. render: function (force, deep) {
  1911. return this.tree._callHook("nodeRender", this, force, deep);
  1912. },
  1913. /** Create HTML markup for the node's outer `<span>` (expander, checkbox, icon, and title).
  1914. * Implies {@link FancytreeNode#renderStatus}.
  1915. * @see Fancytree_Hooks#nodeRenderTitle
  1916. */
  1917. renderTitle: function () {
  1918. return this.tree._callHook("nodeRenderTitle", this);
  1919. },
  1920. /** Update element's CSS classes according to node state.
  1921. * @see Fancytree_Hooks#nodeRenderStatus
  1922. */
  1923. renderStatus: function () {
  1924. return this.tree._callHook("nodeRenderStatus", this);
  1925. },
  1926. /**
  1927. * (experimental) Replace this node with `source`.
  1928. * (Currently only available for paging nodes.)
  1929. * @param {NodeData[]} source List of child node definitions
  1930. * @since 2.15
  1931. */
  1932. replaceWith: function (source) {
  1933. var res,
  1934. parent = this.parent,
  1935. pos = $.inArray(this, parent.children),
  1936. self = this;
  1937. _assert(
  1938. this.isPagingNode(),
  1939. "replaceWith() currently requires a paging status node"
  1940. );
  1941. res = this.tree._callHook("nodeLoadChildren", this, source);
  1942. res.done(function (data) {
  1943. // New nodes are currently children of `this`.
  1944. var children = self.children;
  1945. // Prepend newly loaded child nodes to `this`
  1946. // Move new children after self
  1947. for (i = 0; i < children.length; i++) {
  1948. children[i].parent = parent;
  1949. }
  1950. parent.children.splice.apply(
  1951. parent.children,
  1952. [pos + 1, 0].concat(children)
  1953. );
  1954. // Remove self
  1955. self.children = null;
  1956. self.remove();
  1957. // Redraw new nodes
  1958. parent.render();
  1959. // TODO: set node.partload = false if this was tha last paging node?
  1960. // parent.addPagingNode(false);
  1961. }).fail(function () {
  1962. self.setExpanded();
  1963. });
  1964. return res;
  1965. // $.error("Not implemented: replaceWith()");
  1966. },
  1967. /**
  1968. * Remove all children, collapse, and set the lazy-flag, so that the lazyLoad
  1969. * event is triggered on next expand.
  1970. */
  1971. resetLazy: function () {
  1972. this.removeChildren();
  1973. this.expanded = false;
  1974. this.lazy = true;
  1975. this.children = undefined;
  1976. this.renderStatus();
  1977. },
  1978. /** Schedule activity for delayed execution (cancel any pending request).
  1979. * scheduleAction('cancel') will only cancel a pending request (if any).
  1980. * @param {string} mode
  1981. * @param {number} ms
  1982. */
  1983. scheduleAction: function (mode, ms) {
  1984. if (this.tree.timer) {
  1985. clearTimeout(this.tree.timer);
  1986. this.tree.debug("clearTimeout(%o)", this.tree.timer);
  1987. }
  1988. this.tree.timer = null;
  1989. var self = this; // required for closures
  1990. switch (mode) {
  1991. case "cancel":
  1992. // Simply made sure that timer was cleared
  1993. break;
  1994. case "expand":
  1995. this.tree.timer = setTimeout(function () {
  1996. self.tree.debug("setTimeout: trigger expand");
  1997. self.setExpanded(true);
  1998. }, ms);
  1999. break;
  2000. case "activate":
  2001. this.tree.timer = setTimeout(function () {
  2002. self.tree.debug("setTimeout: trigger activate");
  2003. self.setActive(true);
  2004. }, ms);
  2005. break;
  2006. default:
  2007. $.error("Invalid mode " + mode);
  2008. }
  2009. // this.tree.debug("setTimeout(%s, %s): %s", mode, ms, this.tree.timer);
  2010. },
  2011. /**
  2012. *
  2013. * @param {boolean | PlainObject} [effects=false] animation options.
  2014. * @param {object} [options=null] {topNode: null, effects: ..., parent: ...} this node will remain visible in
  2015. * any case, even if `this` is outside the scroll pane.
  2016. * @returns {$.Promise}
  2017. */
  2018. scrollIntoView: function (effects, options) {
  2019. if (options !== undefined && _isNode(options)) {
  2020. throw Error(
  2021. "scrollIntoView() with 'topNode' option is deprecated since 2014-05-08. Use 'options.topNode' instead."
  2022. );
  2023. }
  2024. // The scroll parent is typically the plain tree's <UL> container.
  2025. // For ext-table, we choose the nearest parent that has `position: relative`
  2026. // and `overflow` set.
  2027. // (This default can be overridden by the local or global `scrollParent` option.)
  2028. var opts = $.extend(
  2029. {
  2030. effects:
  2031. effects === true
  2032. ? { duration: 200, queue: false }
  2033. : effects,
  2034. scrollOfs: this.tree.options.scrollOfs,
  2035. scrollParent: this.tree.options.scrollParent,
  2036. topNode: null,
  2037. },
  2038. options
  2039. ),
  2040. $scrollParent = opts.scrollParent,
  2041. $container = this.tree.$container,
  2042. overflowY = $container.css("overflow-y");
  2043. if (!$scrollParent) {
  2044. if (this.tree.tbody) {
  2045. $scrollParent = $container.scrollParent();
  2046. } else if (overflowY === "scroll" || overflowY === "auto") {
  2047. $scrollParent = $container;
  2048. } else {
  2049. // #922 plain tree in a non-fixed-sized UL scrolls inside its parent
  2050. $scrollParent = $container.scrollParent();
  2051. }
  2052. } else if (!$scrollParent.jquery) {
  2053. // Make sure we have a jQuery object
  2054. $scrollParent = $($scrollParent);
  2055. }
  2056. if (
  2057. $scrollParent[0] === document ||
  2058. $scrollParent[0] === document.body
  2059. ) {
  2060. // `document` may be returned by $().scrollParent(), if nothing is found,
  2061. // but would not work: (see #894)
  2062. this.debug(
  2063. "scrollIntoView(): normalizing scrollParent to 'window':",
  2064. $scrollParent[0]
  2065. );
  2066. $scrollParent = $(window);
  2067. }
  2068. // eslint-disable-next-line one-var
  2069. var topNodeY,
  2070. nodeY,
  2071. horzScrollbarHeight,
  2072. containerOffsetTop,
  2073. dfd = new $.Deferred(),
  2074. self = this,
  2075. nodeHeight = $(this.span).height(),
  2076. topOfs = opts.scrollOfs.top || 0,
  2077. bottomOfs = opts.scrollOfs.bottom || 0,
  2078. containerHeight = $scrollParent.height(),
  2079. scrollTop = $scrollParent.scrollTop(),
  2080. $animateTarget = $scrollParent,
  2081. isParentWindow = $scrollParent[0] === window,
  2082. topNode = opts.topNode || null,
  2083. newScrollTop = null;
  2084. // this.debug("scrollIntoView(), scrollTop=" + scrollTop, opts.scrollOfs);
  2085. // _assert($(this.span).is(":visible"), "scrollIntoView node is invisible"); // otherwise we cannot calc offsets
  2086. if (this.isRootNode() || !this.isVisible()) {
  2087. // We cannot calc offsets for hidden elements
  2088. this.info("scrollIntoView(): node is invisible.");
  2089. return _getResolvedPromise();
  2090. }
  2091. if (isParentWindow) {
  2092. nodeY = $(this.span).offset().top;
  2093. topNodeY =
  2094. topNode && topNode.span ? $(topNode.span).offset().top : 0;
  2095. $animateTarget = $("html,body");
  2096. } else {
  2097. _assert(
  2098. $scrollParent[0] !== document &&
  2099. $scrollParent[0] !== document.body,
  2100. "scrollParent should be a simple element or `window`, not document or body."
  2101. );
  2102. containerOffsetTop = $scrollParent.offset().top;
  2103. nodeY =
  2104. $(this.span).offset().top - containerOffsetTop + scrollTop; // relative to scroll parent
  2105. topNodeY = topNode
  2106. ? $(topNode.span).offset().top -
  2107. containerOffsetTop +
  2108. scrollTop
  2109. : 0;
  2110. horzScrollbarHeight = Math.max(
  2111. 0,
  2112. $scrollParent.innerHeight() - $scrollParent[0].clientHeight
  2113. );
  2114. containerHeight -= horzScrollbarHeight;
  2115. }
  2116. // this.debug(" scrollIntoView(), nodeY=" + nodeY + ", containerHeight=" + containerHeight);
  2117. if (nodeY < scrollTop + topOfs) {
  2118. // Node is above visible container area
  2119. newScrollTop = nodeY - topOfs;
  2120. // this.debug(" scrollIntoView(), UPPER newScrollTop=" + newScrollTop);
  2121. } else if (
  2122. nodeY + nodeHeight >
  2123. scrollTop + containerHeight - bottomOfs
  2124. ) {
  2125. newScrollTop = nodeY + nodeHeight - containerHeight + bottomOfs;
  2126. // this.debug(" scrollIntoView(), LOWER newScrollTop=" + newScrollTop);
  2127. // If a topNode was passed, make sure that it is never scrolled
  2128. // outside the upper border
  2129. if (topNode) {
  2130. _assert(
  2131. topNode.isRootNode() || topNode.isVisible(),
  2132. "topNode must be visible"
  2133. );
  2134. if (topNodeY < newScrollTop) {
  2135. newScrollTop = topNodeY - topOfs;
  2136. // this.debug(" scrollIntoView(), TOP newScrollTop=" + newScrollTop);
  2137. }
  2138. }
  2139. }
  2140. if (newScrollTop === null) {
  2141. dfd.resolveWith(this);
  2142. } else {
  2143. // this.debug(" scrollIntoView(), SET newScrollTop=" + newScrollTop);
  2144. if (opts.effects) {
  2145. opts.effects.complete = function () {
  2146. dfd.resolveWith(self);
  2147. };
  2148. $animateTarget.stop(true).animate(
  2149. {
  2150. scrollTop: newScrollTop,
  2151. },
  2152. opts.effects
  2153. );
  2154. } else {
  2155. $animateTarget[0].scrollTop = newScrollTop;
  2156. dfd.resolveWith(this);
  2157. }
  2158. }
  2159. return dfd.promise();
  2160. },
  2161. /**Activate this node.
  2162. *
  2163. * The `cell` option requires the ext-table and ext-ariagrid extensions.
  2164. *
  2165. * @param {boolean} [flag=true] pass false to deactivate
  2166. * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false, cell: null}
  2167. * @returns {$.Promise}
  2168. */
  2169. setActive: function (flag, opts) {
  2170. return this.tree._callHook("nodeSetActive", this, flag, opts);
  2171. },
  2172. /**Expand or collapse this node. Promise is resolved, when lazy loading and animations are done.
  2173. * @param {boolean} [flag=true] pass false to collapse
  2174. * @param {object} [opts] additional options. Defaults to {noAnimation: false, noEvents: false}
  2175. * @returns {$.Promise}
  2176. */
  2177. setExpanded: function (flag, opts) {
  2178. return this.tree._callHook("nodeSetExpanded", this, flag, opts);
  2179. },
  2180. /**Set keyboard focus to this node.
  2181. * @param {boolean} [flag=true] pass false to blur
  2182. * @see Fancytree#setFocus
  2183. */
  2184. setFocus: function (flag) {
  2185. return this.tree._callHook("nodeSetFocus", this, flag);
  2186. },
  2187. /**Select this node, i.e. check the checkbox.
  2188. * @param {boolean} [flag=true] pass false to deselect
  2189. * @param {object} [opts] additional options. Defaults to {noEvents: false, p
  2190. * propagateDown: null, propagateUp: null, callback: null }
  2191. */
  2192. setSelected: function (flag, opts) {
  2193. return this.tree._callHook("nodeSetSelected", this, flag, opts);
  2194. },
  2195. /**Mark a lazy node as 'error', 'loading', 'nodata', or 'ok'.
  2196. * @param {string} status 'error'|'loading'|'nodata'|'ok'
  2197. * @param {string} [message]
  2198. * @param {string} [details]
  2199. */
  2200. setStatus: function (status, message, details) {
  2201. return this.tree._callHook(
  2202. "nodeSetStatus",
  2203. this,
  2204. status,
  2205. message,
  2206. details
  2207. );
  2208. },
  2209. /**Rename this node.
  2210. * @param {string} title
  2211. */
  2212. setTitle: function (title) {
  2213. this.title = title;
  2214. this.renderTitle();
  2215. this.triggerModify("rename");
  2216. },
  2217. /**Sort child list by title.
  2218. * @param {function} [cmp] custom compare function(a, b) that returns -1, 0, or 1 (defaults to sort by title).
  2219. * @param {boolean} [deep=false] pass true to sort all descendant nodes
  2220. */
  2221. sortChildren: function (cmp, deep) {
  2222. var i,
  2223. l,
  2224. cl = this.children;
  2225. if (!cl) {
  2226. return;
  2227. }
  2228. cmp =
  2229. cmp ||
  2230. function (a, b) {
  2231. var x = a.title.toLowerCase(),
  2232. y = b.title.toLowerCase();
  2233. // eslint-disable-next-line no-nested-ternary
  2234. return x === y ? 0 : x > y ? 1 : -1;
  2235. };
  2236. cl.sort(cmp);
  2237. if (deep) {
  2238. for (i = 0, l = cl.length; i < l; i++) {
  2239. if (cl[i].children) {
  2240. cl[i].sortChildren(cmp, "$norender$");
  2241. }
  2242. }
  2243. }
  2244. if (deep !== "$norender$") {
  2245. this.render();
  2246. }
  2247. this.triggerModifyChild("sort");
  2248. },
  2249. /** Convert node (or whole branch) into a plain object.
  2250. *
  2251. * The result is compatible with node.addChildren().
  2252. *
  2253. * @param {boolean} [recursive=false] include child nodes
  2254. * @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications.
  2255. * Return `false` to ignore this node or `"skip"` to include this node without its children.
  2256. * @returns {NodeData}
  2257. */
  2258. toDict: function (recursive, callback) {
  2259. var i,
  2260. l,
  2261. node,
  2262. res,
  2263. dict = {},
  2264. self = this;
  2265. $.each(NODE_ATTRS, function (i, a) {
  2266. if (self[a] || self[a] === false) {
  2267. dict[a] = self[a];
  2268. }
  2269. });
  2270. if (!$.isEmptyObject(this.data)) {
  2271. dict.data = $.extend({}, this.data);
  2272. if ($.isEmptyObject(dict.data)) {
  2273. delete dict.data;
  2274. }
  2275. }
  2276. if (callback) {
  2277. res = callback(dict, self);
  2278. if (res === false) {
  2279. return false; // Don't include this node nor its children
  2280. }
  2281. if (res === "skip") {
  2282. recursive = false; // Include this node, but not the children
  2283. }
  2284. }
  2285. if (recursive) {
  2286. if (_isArray(this.children)) {
  2287. dict.children = [];
  2288. for (i = 0, l = this.children.length; i < l; i++) {
  2289. node = this.children[i];
  2290. if (!node.isStatusNode()) {
  2291. res = node.toDict(true, callback);
  2292. if (res !== false) {
  2293. dict.children.push(res);
  2294. }
  2295. }
  2296. }
  2297. }
  2298. }
  2299. return dict;
  2300. },
  2301. /**
  2302. * Set, clear, or toggle class of node's span tag and .extraClasses.
  2303. *
  2304. * @param {string} className class name (separate multiple classes by space)
  2305. * @param {boolean} [flag] true/false to add/remove class. If omitted, class is toggled.
  2306. * @returns {boolean} true if a class was added
  2307. *
  2308. * @since 2.17
  2309. */
  2310. toggleClass: function (value, flag) {
  2311. var className,
  2312. hasClass,
  2313. rnotwhite = /\S+/g,
  2314. classNames = value.match(rnotwhite) || [],
  2315. i = 0,
  2316. wasAdded = false,
  2317. statusElem = this[this.tree.statusClassPropName],
  2318. curClasses = " " + (this.extraClasses || "") + " ";
  2319. // this.info("toggleClass('" + value + "', " + flag + ")", curClasses);
  2320. // Modify DOM element directly if it already exists
  2321. if (statusElem) {
  2322. $(statusElem).toggleClass(value, flag);
  2323. }
  2324. // Modify node.extraClasses to make this change persistent
  2325. // Toggle if flag was not passed
  2326. while ((className = classNames[i++])) {
  2327. hasClass = curClasses.indexOf(" " + className + " ") >= 0;
  2328. flag = flag === undefined ? !hasClass : !!flag;
  2329. if (flag) {
  2330. if (!hasClass) {
  2331. curClasses += className + " ";
  2332. wasAdded = true;
  2333. }
  2334. } else {
  2335. while (curClasses.indexOf(" " + className + " ") > -1) {
  2336. curClasses = curClasses.replace(
  2337. " " + className + " ",
  2338. " "
  2339. );
  2340. }
  2341. }
  2342. }
  2343. this.extraClasses = _trim(curClasses);
  2344. // this.info("-> toggleClass('" + value + "', " + flag + "): '" + this.extraClasses + "'");
  2345. return wasAdded;
  2346. },
  2347. /** Flip expanded status. */
  2348. toggleExpanded: function () {
  2349. return this.tree._callHook("nodeToggleExpanded", this);
  2350. },
  2351. /** Flip selection status. */
  2352. toggleSelected: function () {
  2353. return this.tree._callHook("nodeToggleSelected", this);
  2354. },
  2355. toString: function () {
  2356. return "FancytreeNode@" + this.key + "[title='" + this.title + "']";
  2357. // return "<FancytreeNode(#" + this.key + ", '" + this.title + "')>";
  2358. },
  2359. /**
  2360. * Trigger `modifyChild` event on a parent to signal that a child was modified.
  2361. * @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ...
  2362. * @param {FancytreeNode} [childNode]
  2363. * @param {object} [extra]
  2364. */
  2365. triggerModifyChild: function (operation, childNode, extra) {
  2366. var data,
  2367. modifyChild = this.tree.options.modifyChild;
  2368. if (modifyChild) {
  2369. if (childNode && childNode.parent !== this) {
  2370. $.error(
  2371. "childNode " + childNode + " is not a child of " + this
  2372. );
  2373. }
  2374. data = {
  2375. node: this,
  2376. tree: this.tree,
  2377. operation: operation,
  2378. childNode: childNode || null,
  2379. };
  2380. if (extra) {
  2381. $.extend(data, extra);
  2382. }
  2383. modifyChild({ type: "modifyChild" }, data);
  2384. }
  2385. },
  2386. /**
  2387. * Trigger `modifyChild` event on node.parent(!).
  2388. * @param {string} operation Type of change: 'add', 'remove', 'rename', 'move', 'data', ...
  2389. * @param {object} [extra]
  2390. */
  2391. triggerModify: function (operation, extra) {
  2392. this.parent.triggerModifyChild(operation, this, extra);
  2393. },
  2394. /** Call fn(node) for all child nodes in hierarchical order (depth-first).<br>
  2395. * Stop iteration, if fn() returns false. Skip current branch, if fn() returns "skip".<br>
  2396. * Return false if iteration was stopped.
  2397. *
  2398. * @param {function} fn the callback function.
  2399. * Return false to stop iteration, return "skip" to skip this node and
  2400. * its children only.
  2401. * @param {boolean} [includeSelf=false]
  2402. * @returns {boolean}
  2403. */
  2404. visit: function (fn, includeSelf) {
  2405. var i,
  2406. l,
  2407. res = true,
  2408. children = this.children;
  2409. if (includeSelf === true) {
  2410. res = fn(this);
  2411. if (res === false || res === "skip") {
  2412. return res;
  2413. }
  2414. }
  2415. if (children) {
  2416. for (i = 0, l = children.length; i < l; i++) {
  2417. res = children[i].visit(fn, true);
  2418. if (res === false) {
  2419. break;
  2420. }
  2421. }
  2422. }
  2423. return res;
  2424. },
  2425. /** Call fn(node) for all child nodes and recursively load lazy children.<br>
  2426. * <b>Note:</b> If you need this method, you probably should consider to review
  2427. * your architecture! Recursivley loading nodes is a perfect way for lazy
  2428. * programmers to flood the server with requests ;-)
  2429. *
  2430. * @param {function} [fn] optional callback function.
  2431. * Return false to stop iteration, return "skip" to skip this node and
  2432. * its children only.
  2433. * @param {boolean} [includeSelf=false]
  2434. * @returns {$.Promise}
  2435. * @since 2.4
  2436. */
  2437. visitAndLoad: function (fn, includeSelf, _recursion) {
  2438. var dfd,
  2439. res,
  2440. loaders,
  2441. node = this;
  2442. // node.debug("visitAndLoad");
  2443. if (fn && includeSelf === true) {
  2444. res = fn(node);
  2445. if (res === false || res === "skip") {
  2446. return _recursion ? res : _getResolvedPromise();
  2447. }
  2448. }
  2449. if (!node.children && !node.lazy) {
  2450. return _getResolvedPromise();
  2451. }
  2452. dfd = new $.Deferred();
  2453. loaders = [];
  2454. // node.debug("load()...");
  2455. node.load().done(function () {
  2456. // node.debug("load()... done.");
  2457. for (var i = 0, l = node.children.length; i < l; i++) {
  2458. res = node.children[i].visitAndLoad(fn, true, true);
  2459. if (res === false) {
  2460. dfd.reject();
  2461. break;
  2462. } else if (res !== "skip") {
  2463. loaders.push(res); // Add promise to the list
  2464. }
  2465. }
  2466. $.when.apply(this, loaders).then(function () {
  2467. dfd.resolve();
  2468. });
  2469. });
  2470. return dfd.promise();
  2471. },
  2472. /** Call fn(node) for all parent nodes, bottom-up, including invisible system root.<br>
  2473. * Stop iteration, if fn() returns false.<br>
  2474. * Return false if iteration was stopped.
  2475. *
  2476. * @param {function} fn the callback function.
  2477. * Return false to stop iteration, return "skip" to skip this node and children only.
  2478. * @param {boolean} [includeSelf=false]
  2479. * @returns {boolean}
  2480. */
  2481. visitParents: function (fn, includeSelf) {
  2482. // Visit parent nodes (bottom up)
  2483. if (includeSelf && fn(this) === false) {
  2484. return false;
  2485. }
  2486. var p = this.parent;
  2487. while (p) {
  2488. if (fn(p) === false) {
  2489. return false;
  2490. }
  2491. p = p.parent;
  2492. }
  2493. return true;
  2494. },
  2495. /** Call fn(node) for all sibling nodes.<br>
  2496. * Stop iteration, if fn() returns false.<br>
  2497. * Return false if iteration was stopped.
  2498. *
  2499. * @param {function} fn the callback function.
  2500. * Return false to stop iteration.
  2501. * @param {boolean} [includeSelf=false]
  2502. * @returns {boolean}
  2503. */
  2504. visitSiblings: function (fn, includeSelf) {
  2505. var i,
  2506. l,
  2507. n,
  2508. ac = this.parent.children;
  2509. for (i = 0, l = ac.length; i < l; i++) {
  2510. n = ac[i];
  2511. if (includeSelf || n !== this) {
  2512. if (fn(n) === false) {
  2513. return false;
  2514. }
  2515. }
  2516. }
  2517. return true;
  2518. },
  2519. /** Write warning to browser console if debugLevel >= 2 (prepending node info)
  2520. *
  2521. * @param {*} msg string or object or array of such
  2522. */
  2523. warn: function (msg) {
  2524. if (this.tree.options.debugLevel >= 2) {
  2525. Array.prototype.unshift.call(arguments, this.toString());
  2526. consoleApply("warn", arguments);
  2527. }
  2528. },
  2529. };
  2530. /******************************************************************************
  2531. * Fancytree
  2532. */
  2533. /**
  2534. * Construct a new tree object.
  2535. *
  2536. * @class Fancytree
  2537. * @classdesc The controller behind a fancytree.
  2538. * This class also contains 'hook methods': see {@link Fancytree_Hooks}.
  2539. *
  2540. * @param {Widget} widget
  2541. *
  2542. * @property {string} _id Automatically generated unique tree instance ID, e.g. "1".
  2543. * @property {string} _ns Automatically generated unique tree namespace, e.g. ".fancytree-1".
  2544. * @property {FancytreeNode} activeNode Currently active node or null.
  2545. * @property {string} ariaPropName Property name of FancytreeNode that contains the element which will receive the aria attributes.
  2546. * Typically "li", but "tr" for table extension.
  2547. * @property {jQueryObject} $container Outer `<ul>` element (or `<table>` element for ext-table).
  2548. * @property {jQueryObject} $div A jQuery object containing the element used to instantiate the tree widget (`widget.element`)
  2549. * @property {object|array} columns Recommended place to store shared column meta data. @since 2.27
  2550. * @property {object} data Metadata, i.e. properties that may be passed to `source` in addition to a children array.
  2551. * @property {object} ext Hash of all active plugin instances.
  2552. * @property {FancytreeNode} focusNode Currently focused node or null.
  2553. * @property {FancytreeNode} lastSelectedNode Used to implement selectMode 1 (single select)
  2554. * @property {string} nodeContainerAttrName Property name of FancytreeNode that contains the outer element of single nodes.
  2555. * Typically "li", but "tr" for table extension.
  2556. * @property {FancytreeOptions} options Current options, i.e. default options + options passed to constructor.
  2557. * @property {FancytreeNode} rootNode Invisible system root node.
  2558. * @property {string} statusClassPropName Property name of FancytreeNode that contains the element which will receive the status classes.
  2559. * Typically "span", but "tr" for table extension.
  2560. * @property {object} types Map for shared type specific meta data, used with node.type attribute. @since 2.27
  2561. * @property {object} viewport See ext-vieport. @since v2.31
  2562. * @property {object} widget Base widget instance.
  2563. */
  2564. function Fancytree(widget) {
  2565. this.widget = widget;
  2566. this.$div = widget.element;
  2567. this.options = widget.options;
  2568. if (this.options) {
  2569. if (this.options.lazyload !== undefined) {
  2570. $.error(
  2571. "The 'lazyload' event is deprecated since 2014-02-25. Use 'lazyLoad' (with uppercase L) instead."
  2572. );
  2573. }
  2574. if (this.options.loaderror !== undefined) {
  2575. $.error(
  2576. "The 'loaderror' event was renamed since 2014-07-03. Use 'loadError' (with uppercase E) instead."
  2577. );
  2578. }
  2579. if (this.options.fx !== undefined) {
  2580. $.error(
  2581. "The 'fx' option was replaced by 'toggleEffect' since 2014-11-30."
  2582. );
  2583. }
  2584. if (this.options.removeNode !== undefined) {
  2585. $.error(
  2586. "The 'removeNode' event was replaced by 'modifyChild' since 2.20 (2016-09-10)."
  2587. );
  2588. }
  2589. }
  2590. this.ext = {}; // Active extension instances
  2591. this.types = {};
  2592. this.columns = {};
  2593. // allow to init tree.data.foo from <div data-foo=''>
  2594. this.data = _getElementDataAsDict(this.$div);
  2595. // TODO: use widget.uuid instead?
  2596. this._id = "" + (this.options.treeId || $.ui.fancytree._nextId++);
  2597. // TODO: use widget.eventNamespace instead?
  2598. this._ns = ".fancytree-" + this._id; // append for namespaced events
  2599. this.activeNode = null;
  2600. this.focusNode = null;
  2601. this._hasFocus = null;
  2602. this._tempCache = {};
  2603. this._lastMousedownNode = null;
  2604. this._enableUpdate = true;
  2605. this.lastSelectedNode = null;
  2606. this.systemFocusElement = null;
  2607. this.lastQuicksearchTerm = "";
  2608. this.lastQuicksearchTime = 0;
  2609. this.viewport = null; // ext-grid
  2610. this.statusClassPropName = "span";
  2611. this.ariaPropName = "li";
  2612. this.nodeContainerAttrName = "li";
  2613. // Remove previous markup if any
  2614. this.$div.find(">ul.fancytree-container").remove();
  2615. // Create a node without parent.
  2616. var fakeParent = { tree: this },
  2617. $ul;
  2618. this.rootNode = new FancytreeNode(fakeParent, {
  2619. title: "root",
  2620. key: "root_" + this._id,
  2621. children: null,
  2622. expanded: true,
  2623. });
  2624. this.rootNode.parent = null;
  2625. // Create root markup
  2626. $ul = $("<ul>", {
  2627. id: "ft-id-" + this._id,
  2628. class: "ui-fancytree fancytree-container fancytree-plain",
  2629. }).appendTo(this.$div);
  2630. this.$container = $ul;
  2631. this.rootNode.ul = $ul[0];
  2632. if (this.options.debugLevel == null) {
  2633. this.options.debugLevel = FT.debugLevel;
  2634. }
  2635. // // Add container to the TAB chain
  2636. // // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
  2637. // // #577: Allow to set tabindex to "0", "-1" and ""
  2638. // this.$container.attr("tabindex", this.options.tabindex);
  2639. // if( this.options.rtl ) {
  2640. // this.$container.attr("DIR", "RTL").addClass("fancytree-rtl");
  2641. // // }else{
  2642. // // this.$container.attr("DIR", null).removeClass("fancytree-rtl");
  2643. // }
  2644. // if(this.options.aria){
  2645. // this.$container.attr("role", "tree");
  2646. // if( this.options.selectMode !== 1 ) {
  2647. // this.$container.attr("aria-multiselectable", true);
  2648. // }
  2649. // }
  2650. }
  2651. Fancytree.prototype = /** @lends Fancytree# */ {
  2652. /* Return a context object that can be re-used for _callHook().
  2653. * @param {Fancytree | FancytreeNode | EventData} obj
  2654. * @param {Event} originalEvent
  2655. * @param {Object} extra
  2656. * @returns {EventData}
  2657. */
  2658. _makeHookContext: function (obj, originalEvent, extra) {
  2659. var ctx, tree;
  2660. if (obj.node !== undefined) {
  2661. // obj is already a context object
  2662. if (originalEvent && obj.originalEvent !== originalEvent) {
  2663. $.error("invalid args");
  2664. }
  2665. ctx = obj;
  2666. } else if (obj.tree) {
  2667. // obj is a FancytreeNode
  2668. tree = obj.tree;
  2669. ctx = {
  2670. node: obj,
  2671. tree: tree,
  2672. widget: tree.widget,
  2673. options: tree.widget.options,
  2674. originalEvent: originalEvent,
  2675. typeInfo: tree.types[obj.type] || {},
  2676. };
  2677. } else if (obj.widget) {
  2678. // obj is a Fancytree
  2679. ctx = {
  2680. node: null,
  2681. tree: obj,
  2682. widget: obj.widget,
  2683. options: obj.widget.options,
  2684. originalEvent: originalEvent,
  2685. };
  2686. } else {
  2687. $.error("invalid args");
  2688. }
  2689. if (extra) {
  2690. $.extend(ctx, extra);
  2691. }
  2692. return ctx;
  2693. },
  2694. /* Trigger a hook function: funcName(ctx, [...]).
  2695. *
  2696. * @param {string} funcName
  2697. * @param {Fancytree|FancytreeNode|EventData} contextObject
  2698. * @param {any} [_extraArgs] optional additional arguments
  2699. * @returns {any}
  2700. */
  2701. _callHook: function (funcName, contextObject, _extraArgs) {
  2702. var ctx = this._makeHookContext(contextObject),
  2703. fn = this[funcName],
  2704. args = Array.prototype.slice.call(arguments, 2);
  2705. if (!_isFunction(fn)) {
  2706. $.error("_callHook('" + funcName + "') is not a function");
  2707. }
  2708. args.unshift(ctx);
  2709. // this.debug("_hook", funcName, ctx.node && ctx.node.toString() || ctx.tree.toString(), args);
  2710. return fn.apply(this, args);
  2711. },
  2712. _setExpiringValue: function (key, value, ms) {
  2713. this._tempCache[key] = {
  2714. value: value,
  2715. expire: Date.now() + (+ms || 50),
  2716. };
  2717. },
  2718. _getExpiringValue: function (key) {
  2719. var entry = this._tempCache[key];
  2720. if (entry && entry.expire > Date.now()) {
  2721. return entry.value;
  2722. }
  2723. delete this._tempCache[key];
  2724. return null;
  2725. },
  2726. /* Check if this tree has extension `name` enabled.
  2727. *
  2728. * @param {string} name name of the required extension
  2729. */
  2730. _usesExtension: function (name) {
  2731. return $.inArray(name, this.options.extensions) >= 0;
  2732. },
  2733. /* Check if current extensions dependencies are met and throw an error if not.
  2734. *
  2735. * This method may be called inside the `treeInit` hook for custom extensions.
  2736. *
  2737. * @param {string} name name of the required extension
  2738. * @param {boolean} [required=true] pass `false` if the extension is optional, but we want to check for order if it is present
  2739. * @param {boolean} [before] `true` if `name` must be included before this, `false` otherwise (use `null` if order doesn't matter)
  2740. * @param {string} [message] optional error message (defaults to a descriptve error message)
  2741. */
  2742. _requireExtension: function (name, required, before, message) {
  2743. if (before != null) {
  2744. before = !!before;
  2745. }
  2746. var thisName = this._local.name,
  2747. extList = this.options.extensions,
  2748. isBefore =
  2749. $.inArray(name, extList) < $.inArray(thisName, extList),
  2750. isMissing = required && this.ext[name] == null,
  2751. badOrder = !isMissing && before != null && before !== isBefore;
  2752. _assert(
  2753. thisName && thisName !== name,
  2754. "invalid or same name '" + thisName + "' (require yourself?)"
  2755. );
  2756. if (isMissing || badOrder) {
  2757. if (!message) {
  2758. if (isMissing || required) {
  2759. message =
  2760. "'" +
  2761. thisName +
  2762. "' extension requires '" +
  2763. name +
  2764. "'";
  2765. if (badOrder) {
  2766. message +=
  2767. " to be registered " +
  2768. (before ? "before" : "after") +
  2769. " itself";
  2770. }
  2771. } else {
  2772. message =
  2773. "If used together, `" +
  2774. name +
  2775. "` must be registered " +
  2776. (before ? "before" : "after") +
  2777. " `" +
  2778. thisName +
  2779. "`";
  2780. }
  2781. }
  2782. $.error(message);
  2783. return false;
  2784. }
  2785. return true;
  2786. },
  2787. /** Activate node with a given key and fire focus and activate events.
  2788. *
  2789. * A previously activated node will be deactivated.
  2790. * If activeVisible option is set, all parents will be expanded as necessary.
  2791. * Pass key = false, to deactivate the current node only.
  2792. * @param {string} key
  2793. * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false}
  2794. * @returns {FancytreeNode} activated node (null, if not found)
  2795. */
  2796. activateKey: function (key, opts) {
  2797. var node = this.getNodeByKey(key);
  2798. if (node) {
  2799. node.setActive(true, opts);
  2800. } else if (this.activeNode) {
  2801. this.activeNode.setActive(false, opts);
  2802. }
  2803. return node;
  2804. },
  2805. /** (experimental) Add child status nodes that indicate 'More...', ....
  2806. * @param {boolean|object} node optional node definition. Pass `false` to remove all paging nodes.
  2807. * @param {string} [mode='append'] 'child'|firstChild'
  2808. * @since 2.15
  2809. */
  2810. addPagingNode: function (node, mode) {
  2811. return this.rootNode.addPagingNode(node, mode);
  2812. },
  2813. /**
  2814. * (experimental) Apply a modification (or navigation) operation.
  2815. *
  2816. * Valid commands:
  2817. * - 'moveUp', 'moveDown'
  2818. * - 'indent', 'outdent'
  2819. * - 'remove'
  2820. * - 'edit', 'addChild', 'addSibling': (reqires ext-edit extension)
  2821. * - 'cut', 'copy', 'paste': (use an internal singleton 'clipboard')
  2822. * - 'down', 'first', 'last', 'left', 'parent', 'right', 'up': navigate
  2823. *
  2824. * @param {string} cmd
  2825. * @param {FancytreeNode} [node=active_node]
  2826. * @param {object} [opts] Currently unused
  2827. *
  2828. * @since 2.32
  2829. */
  2830. applyCommand: function (cmd, node, opts_) {
  2831. var // clipboard,
  2832. refNode;
  2833. // opts = $.extend(
  2834. // { setActive: true, clipboard: CLIPBOARD },
  2835. // opts_
  2836. // );
  2837. node = node || this.getActiveNode();
  2838. // clipboard = opts.clipboard;
  2839. switch (cmd) {
  2840. // Sorting and indentation:
  2841. case "moveUp":
  2842. refNode = node.getPrevSibling();
  2843. if (refNode) {
  2844. node.moveTo(refNode, "before");
  2845. node.setActive();
  2846. }
  2847. break;
  2848. case "moveDown":
  2849. refNode = node.getNextSibling();
  2850. if (refNode) {
  2851. node.moveTo(refNode, "after");
  2852. node.setActive();
  2853. }
  2854. break;
  2855. case "indent":
  2856. refNode = node.getPrevSibling();
  2857. if (refNode) {
  2858. node.moveTo(refNode, "child");
  2859. refNode.setExpanded();
  2860. node.setActive();
  2861. }
  2862. break;
  2863. case "outdent":
  2864. if (!node.isTopLevel()) {
  2865. node.moveTo(node.getParent(), "after");
  2866. node.setActive();
  2867. }
  2868. break;
  2869. // Remove:
  2870. case "remove":
  2871. refNode = node.getPrevSibling() || node.getParent();
  2872. node.remove();
  2873. if (refNode) {
  2874. refNode.setActive();
  2875. }
  2876. break;
  2877. // Add, edit (requires ext-edit):
  2878. case "addChild":
  2879. node.editCreateNode("child", "");
  2880. break;
  2881. case "addSibling":
  2882. node.editCreateNode("after", "");
  2883. break;
  2884. case "rename":
  2885. node.editStart();
  2886. break;
  2887. // Simple clipboard simulation:
  2888. // case "cut":
  2889. // clipboard = { mode: cmd, data: node };
  2890. // break;
  2891. // case "copy":
  2892. // clipboard = {
  2893. // mode: cmd,
  2894. // data: node.toDict(function(d, n) {
  2895. // delete d.key;
  2896. // }),
  2897. // };
  2898. // break;
  2899. // case "clear":
  2900. // clipboard = null;
  2901. // break;
  2902. // case "paste":
  2903. // if (clipboard.mode === "cut") {
  2904. // // refNode = node.getPrevSibling();
  2905. // clipboard.data.moveTo(node, "child");
  2906. // clipboard.data.setActive();
  2907. // } else if (clipboard.mode === "copy") {
  2908. // node.addChildren(clipboard.data).setActive();
  2909. // }
  2910. // break;
  2911. // Navigation commands:
  2912. case "down":
  2913. case "first":
  2914. case "last":
  2915. case "left":
  2916. case "parent":
  2917. case "right":
  2918. case "up":
  2919. return node.navigate(cmd);
  2920. default:
  2921. $.error("Unhandled command: '" + cmd + "'");
  2922. }
  2923. },
  2924. /** (experimental) Modify existing data model.
  2925. *
  2926. * @param {Array} patchList array of [key, NodePatch] arrays
  2927. * @returns {$.Promise} resolved, when all patches have been applied
  2928. * @see TreePatch
  2929. */
  2930. applyPatch: function (patchList) {
  2931. var dfd,
  2932. i,
  2933. p2,
  2934. key,
  2935. patch,
  2936. node,
  2937. patchCount = patchList.length,
  2938. deferredList = [];
  2939. for (i = 0; i < patchCount; i++) {
  2940. p2 = patchList[i];
  2941. _assert(
  2942. p2.length === 2,
  2943. "patchList must be an array of length-2-arrays"
  2944. );
  2945. key = p2[0];
  2946. patch = p2[1];
  2947. node = key === null ? this.rootNode : this.getNodeByKey(key);
  2948. if (node) {
  2949. dfd = new $.Deferred();
  2950. deferredList.push(dfd);
  2951. node.applyPatch(patch).always(_makeResolveFunc(dfd, node));
  2952. } else {
  2953. this.warn("could not find node with key '" + key + "'");
  2954. }
  2955. }
  2956. // Return a promise that is resolved, when ALL patches were applied
  2957. return $.when.apply($, deferredList).promise();
  2958. },
  2959. /* TODO: implement in dnd extension
  2960. cancelDrag: function() {
  2961. var dd = $.ui.ddmanager.current;
  2962. if(dd){
  2963. dd.cancel();
  2964. }
  2965. },
  2966. */
  2967. /** Remove all nodes.
  2968. * @since 2.14
  2969. */
  2970. clear: function (source) {
  2971. this._callHook("treeClear", this);
  2972. },
  2973. /** Return the number of nodes.
  2974. * @returns {integer}
  2975. */
  2976. count: function () {
  2977. return this.rootNode.countChildren();
  2978. },
  2979. /** Write to browser console if debugLevel >= 4 (prepending tree name)
  2980. *
  2981. * @param {*} msg string or object or array of such
  2982. */
  2983. debug: function (msg) {
  2984. if (this.options.debugLevel >= 4) {
  2985. Array.prototype.unshift.call(arguments, this.toString());
  2986. consoleApply("log", arguments);
  2987. }
  2988. },
  2989. /** Destroy this widget, restore previous markup and cleanup resources.
  2990. *
  2991. * @since 2.34
  2992. */
  2993. destroy: function () {
  2994. this.widget.destroy();
  2995. },
  2996. /** Enable (or disable) the tree control.
  2997. *
  2998. * @param {boolean} [flag=true] pass false to disable
  2999. * @since 2.30
  3000. */
  3001. enable: function (flag) {
  3002. if (flag === false) {
  3003. this.widget.disable();
  3004. } else {
  3005. this.widget.enable();
  3006. }
  3007. },
  3008. /** Temporarily suppress rendering to improve performance on bulk-updates.
  3009. *
  3010. * @param {boolean} flag
  3011. * @returns {boolean} previous status
  3012. * @since 2.19
  3013. */
  3014. enableUpdate: function (flag) {
  3015. flag = flag !== false;
  3016. if (!!this._enableUpdate === !!flag) {
  3017. return flag;
  3018. }
  3019. this._enableUpdate = flag;
  3020. if (flag) {
  3021. this.debug("enableUpdate(true): redraw "); //, this._dirtyRoots);
  3022. this._callHook("treeStructureChanged", this, "enableUpdate");
  3023. this.render();
  3024. } else {
  3025. // this._dirtyRoots = null;
  3026. this.debug("enableUpdate(false)...");
  3027. }
  3028. return !flag; // return previous value
  3029. },
  3030. /** Write error to browser console if debugLevel >= 1 (prepending tree info)
  3031. *
  3032. * @param {*} msg string or object or array of such
  3033. */
  3034. error: function (msg) {
  3035. if (this.options.debugLevel >= 1) {
  3036. Array.prototype.unshift.call(arguments, this.toString());
  3037. consoleApply("error", arguments);
  3038. }
  3039. },
  3040. /** Expand (or collapse) all parent nodes.
  3041. *
  3042. * This convenience method uses `tree.visit()` and `tree.setExpanded()`
  3043. * internally.
  3044. *
  3045. * @param {boolean} [flag=true] pass false to collapse
  3046. * @param {object} [opts] passed to setExpanded()
  3047. * @since 2.30
  3048. */
  3049. expandAll: function (flag, opts) {
  3050. var prev = this.enableUpdate(false);
  3051. flag = flag !== false;
  3052. this.visit(function (node) {
  3053. if (
  3054. node.hasChildren() !== false &&
  3055. node.isExpanded() !== flag
  3056. ) {
  3057. node.setExpanded(flag, opts);
  3058. }
  3059. });
  3060. this.enableUpdate(prev);
  3061. },
  3062. /**Find all nodes that matches condition.
  3063. *
  3064. * @param {string | function(node)} match title string to search for, or a
  3065. * callback function that returns `true` if a node is matched.
  3066. * @returns {FancytreeNode[]} array of nodes (may be empty)
  3067. * @see FancytreeNode#findAll
  3068. * @since 2.12
  3069. */
  3070. findAll: function (match) {
  3071. return this.rootNode.findAll(match);
  3072. },
  3073. /**Find first node that matches condition.
  3074. *
  3075. * @param {string | function(node)} match title string to search for, or a
  3076. * callback function that returns `true` if a node is matched.
  3077. * @returns {FancytreeNode} matching node or null
  3078. * @see FancytreeNode#findFirst
  3079. * @since 2.12
  3080. */
  3081. findFirst: function (match) {
  3082. return this.rootNode.findFirst(match);
  3083. },
  3084. /** Find the next visible node that starts with `match`, starting at `startNode`
  3085. * and wrap-around at the end.
  3086. *
  3087. * @param {string|function} match
  3088. * @param {FancytreeNode} [startNode] defaults to first node
  3089. * @returns {FancytreeNode} matching node or null
  3090. */
  3091. findNextNode: function (match, startNode) {
  3092. //, visibleOnly) {
  3093. var res = null,
  3094. firstNode = this.getFirstChild();
  3095. match =
  3096. typeof match === "string"
  3097. ? _makeNodeTitleStartMatcher(match)
  3098. : match;
  3099. startNode = startNode || firstNode;
  3100. function _checkNode(n) {
  3101. // console.log("_check " + n)
  3102. if (match(n)) {
  3103. res = n;
  3104. }
  3105. if (res || n === startNode) {
  3106. return false;
  3107. }
  3108. }
  3109. this.visitRows(_checkNode, {
  3110. start: startNode,
  3111. includeSelf: false,
  3112. });
  3113. // Wrap around search
  3114. if (!res && startNode !== firstNode) {
  3115. this.visitRows(_checkNode, {
  3116. start: firstNode,
  3117. includeSelf: true,
  3118. });
  3119. }
  3120. return res;
  3121. },
  3122. /** Find a node relative to another node.
  3123. *
  3124. * @param {FancytreeNode} node
  3125. * @param {string|number} where 'down', 'first', 'last', 'left', 'parent', 'right', or 'up'.
  3126. * (Alternatively the keyCode that would normally trigger this move,
  3127. * e.g. `$.ui.keyCode.LEFT` = 'left'.
  3128. * @param {boolean} [includeHidden=false] Not yet implemented
  3129. * @returns {FancytreeNode|null}
  3130. * @since v2.31
  3131. */
  3132. findRelatedNode: function (node, where, includeHidden) {
  3133. var res = null,
  3134. KC = $.ui.keyCode;
  3135. switch (where) {
  3136. case "parent":
  3137. case KC.BACKSPACE:
  3138. if (node.parent && node.parent.parent) {
  3139. res = node.parent;
  3140. }
  3141. break;
  3142. case "first":
  3143. case KC.HOME:
  3144. // First visible node
  3145. this.visit(function (n) {
  3146. if (n.isVisible()) {
  3147. res = n;
  3148. return false;
  3149. }
  3150. });
  3151. break;
  3152. case "last":
  3153. case KC.END:
  3154. this.visit(function (n) {
  3155. // last visible node
  3156. if (n.isVisible()) {
  3157. res = n;
  3158. }
  3159. });
  3160. break;
  3161. case "left":
  3162. case KC.LEFT:
  3163. if (node.expanded) {
  3164. node.setExpanded(false);
  3165. } else if (node.parent && node.parent.parent) {
  3166. res = node.parent;
  3167. }
  3168. break;
  3169. case "right":
  3170. case KC.RIGHT:
  3171. if (!node.expanded && (node.children || node.lazy)) {
  3172. node.setExpanded();
  3173. res = node;
  3174. } else if (node.children && node.children.length) {
  3175. res = node.children[0];
  3176. }
  3177. break;
  3178. case "up":
  3179. case KC.UP:
  3180. this.visitRows(
  3181. function (n) {
  3182. res = n;
  3183. return false;
  3184. },
  3185. { start: node, reverse: true, includeSelf: false }
  3186. );
  3187. break;
  3188. case "down":
  3189. case KC.DOWN:
  3190. this.visitRows(
  3191. function (n) {
  3192. res = n;
  3193. return false;
  3194. },
  3195. { start: node, includeSelf: false }
  3196. );
  3197. break;
  3198. default:
  3199. this.tree.warn("Unknown relation '" + where + "'.");
  3200. }
  3201. return res;
  3202. },
  3203. // TODO: fromDict
  3204. /**
  3205. * Generate INPUT elements that can be submitted with html forms.
  3206. *
  3207. * In selectMode 3 only the topmost selected nodes are considered, unless
  3208. * `opts.stopOnParents: false` is passed.
  3209. *
  3210. * @example
  3211. * // Generate input elements for active and selected nodes
  3212. * tree.generateFormElements();
  3213. * // Generate input elements selected nodes, using a custom `name` attribute
  3214. * tree.generateFormElements("cust_sel", false);
  3215. * // Generate input elements using a custom filter
  3216. * tree.generateFormElements(true, true, { filter: function(node) {
  3217. * return node.isSelected() && node.data.yes;
  3218. * }});
  3219. *
  3220. * @param {boolean | string} [selected=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID[]')
  3221. * @param {boolean | string} [active=true] Pass false to disable, pass a string to override the field name (default: 'ft_ID_active')
  3222. * @param {object} [opts] default { filter: null, stopOnParents: true }
  3223. */
  3224. generateFormElements: function (selected, active, opts) {
  3225. opts = opts || {};
  3226. var nodeList,
  3227. selectedName =
  3228. typeof selected === "string"
  3229. ? selected
  3230. : "ft_" + this._id + "[]",
  3231. activeName =
  3232. typeof active === "string"
  3233. ? active
  3234. : "ft_" + this._id + "_active",
  3235. id = "fancytree_result_" + this._id,
  3236. $result = $("#" + id),
  3237. stopOnParents =
  3238. this.options.selectMode === 3 &&
  3239. opts.stopOnParents !== false;
  3240. if ($result.length) {
  3241. $result.empty();
  3242. } else {
  3243. $result = $("<div>", {
  3244. id: id,
  3245. })
  3246. .hide()
  3247. .insertAfter(this.$container);
  3248. }
  3249. if (active !== false && this.activeNode) {
  3250. $result.append(
  3251. $("<input>", {
  3252. type: "radio",
  3253. name: activeName,
  3254. value: this.activeNode.key,
  3255. checked: true,
  3256. })
  3257. );
  3258. }
  3259. function _appender(node) {
  3260. $result.append(
  3261. $("<input>", {
  3262. type: "checkbox",
  3263. name: selectedName,
  3264. value: node.key,
  3265. checked: true,
  3266. })
  3267. );
  3268. }
  3269. if (opts.filter) {
  3270. this.visit(function (node) {
  3271. var res = opts.filter(node);
  3272. if (res === "skip") {
  3273. return res;
  3274. }
  3275. if (res !== false) {
  3276. _appender(node);
  3277. }
  3278. });
  3279. } else if (selected !== false) {
  3280. nodeList = this.getSelectedNodes(stopOnParents);
  3281. $.each(nodeList, function (idx, node) {
  3282. _appender(node);
  3283. });
  3284. }
  3285. },
  3286. /**
  3287. * Return the currently active node or null.
  3288. * @returns {FancytreeNode}
  3289. */
  3290. getActiveNode: function () {
  3291. return this.activeNode;
  3292. },
  3293. /** Return the first top level node if any (not the invisible root node).
  3294. * @returns {FancytreeNode | null}
  3295. */
  3296. getFirstChild: function () {
  3297. return this.rootNode.getFirstChild();
  3298. },
  3299. /**
  3300. * Return node that has keyboard focus or null.
  3301. * @returns {FancytreeNode}
  3302. */
  3303. getFocusNode: function () {
  3304. return this.focusNode;
  3305. },
  3306. /**
  3307. * Return current option value.
  3308. * (Note: this is the preferred variant of `$().fancytree("option", "KEY")`)
  3309. *
  3310. * @param {string} name option name (may contain '.')
  3311. * @returns {any}
  3312. */
  3313. getOption: function (optionName) {
  3314. return this.widget.option(optionName);
  3315. },
  3316. /**
  3317. * Return node with a given key or null if not found.
  3318. *
  3319. * @param {string} key
  3320. * @param {FancytreeNode} [searchRoot] only search below this node
  3321. * @returns {FancytreeNode | null}
  3322. */
  3323. getNodeByKey: function (key, searchRoot) {
  3324. // Search the DOM by element ID (assuming this is faster than traversing all nodes).
  3325. var el, match;
  3326. // TODO: use tree.keyMap if available
  3327. // TODO: check opts.generateIds === true
  3328. if (!searchRoot) {
  3329. el = document.getElementById(this.options.idPrefix + key);
  3330. if (el) {
  3331. return el.ftnode ? el.ftnode : null;
  3332. }
  3333. }
  3334. // Not found in the DOM, but still may be in an unrendered part of tree
  3335. searchRoot = searchRoot || this.rootNode;
  3336. match = null;
  3337. key = "" + key; // Convert to string (#1005)
  3338. searchRoot.visit(function (node) {
  3339. if (node.key === key) {
  3340. match = node;
  3341. return false; // Stop iteration
  3342. }
  3343. }, true);
  3344. return match;
  3345. },
  3346. /** Return the invisible system root node.
  3347. * @returns {FancytreeNode}
  3348. */
  3349. getRootNode: function () {
  3350. return this.rootNode;
  3351. },
  3352. /**
  3353. * Return an array of selected nodes.
  3354. *
  3355. * Note: you cannot send this result via Ajax directly. Instead the
  3356. * node object need to be converted to plain objects, for example
  3357. * by using `$.map()` and `node.toDict()`.
  3358. * @param {boolean} [stopOnParents=false] only return the topmost selected
  3359. * node (useful with selectMode 3)
  3360. * @returns {FancytreeNode[]}
  3361. */
  3362. getSelectedNodes: function (stopOnParents) {
  3363. return this.rootNode.getSelectedNodes(stopOnParents);
  3364. },
  3365. /** Return true if the tree control has keyboard focus
  3366. * @returns {boolean}
  3367. */
  3368. hasFocus: function () {
  3369. // var ae = document.activeElement,
  3370. // hasFocus = !!(
  3371. // ae && $(ae).closest(".fancytree-container").length
  3372. // );
  3373. // if (hasFocus !== !!this._hasFocus) {
  3374. // this.warn(
  3375. // "hasFocus(): fix inconsistent container state, now: " +
  3376. // hasFocus
  3377. // );
  3378. // this._hasFocus = hasFocus;
  3379. // this.$container.toggleClass("fancytree-treefocus", hasFocus);
  3380. // }
  3381. // return hasFocus;
  3382. return !!this._hasFocus;
  3383. },
  3384. /** Write to browser console if debugLevel >= 3 (prepending tree name)
  3385. * @param {*} msg string or object or array of such
  3386. */
  3387. info: function (msg) {
  3388. if (this.options.debugLevel >= 3) {
  3389. Array.prototype.unshift.call(arguments, this.toString());
  3390. consoleApply("info", arguments);
  3391. }
  3392. },
  3393. /** Return true if any node is currently beeing loaded, i.e. a Ajax request is pending.
  3394. * @returns {boolean}
  3395. * @since 2.32
  3396. */
  3397. isLoading: function () {
  3398. var res = false;
  3399. this.rootNode.visit(function (n) {
  3400. // also visit rootNode
  3401. if (n._isLoading || n._requestId) {
  3402. res = true;
  3403. return false;
  3404. }
  3405. }, true);
  3406. return res;
  3407. },
  3408. /*
  3409. TODO: isInitializing: function() {
  3410. return ( this.phase=="init" || this.phase=="postInit" );
  3411. },
  3412. TODO: isReloading: function() {
  3413. return ( this.phase=="init" || this.phase=="postInit" ) && this.options.persist && this.persistence.cookiesFound;
  3414. },
  3415. TODO: isUserEvent: function() {
  3416. return ( this.phase=="userEvent" );
  3417. },
  3418. */
  3419. /**
  3420. * Make sure that a node with a given ID is loaded, by traversing - and
  3421. * loading - its parents. This method is meant for lazy hierarchies.
  3422. * A callback is executed for every node as we go.
  3423. * @example
  3424. * // Resolve using node.key:
  3425. * tree.loadKeyPath("/_3/_23/_26/_27", function(node, status){
  3426. * if(status === "loaded") {
  3427. * console.log("loaded intermediate node " + node);
  3428. * }else if(status === "ok") {
  3429. * node.activate();
  3430. * }
  3431. * });
  3432. * // Use deferred promise:
  3433. * tree.loadKeyPath("/_3/_23/_26/_27").progress(function(data){
  3434. * if(data.status === "loaded") {
  3435. * console.log("loaded intermediate node " + data.node);
  3436. * }else if(data.status === "ok") {
  3437. * node.activate();
  3438. * }
  3439. * }).done(function(){
  3440. * ...
  3441. * });
  3442. * // Custom path segment resolver:
  3443. * tree.loadKeyPath("/321/431/21/2", {
  3444. * matchKey: function(node, key){
  3445. * return node.data.refKey === key;
  3446. * },
  3447. * callback: function(node, status){
  3448. * if(status === "loaded") {
  3449. * console.log("loaded intermediate node " + node);
  3450. * }else if(status === "ok") {
  3451. * node.activate();
  3452. * }
  3453. * }
  3454. * });
  3455. * @param {string | string[]} keyPathList one or more key paths (e.g. '/3/2_1/7')
  3456. * @param {function | object} optsOrCallback callback(node, status) is called for every visited node ('loading', 'loaded', 'ok', 'error').
  3457. * Pass an object to define custom key matchers for the path segments: {callback: function, matchKey: function}.
  3458. * @returns {$.Promise}
  3459. */
  3460. loadKeyPath: function (keyPathList, optsOrCallback) {
  3461. var callback,
  3462. i,
  3463. path,
  3464. self = this,
  3465. dfd = new $.Deferred(),
  3466. parent = this.getRootNode(),
  3467. sep = this.options.keyPathSeparator,
  3468. pathSegList = [],
  3469. opts = $.extend({}, optsOrCallback);
  3470. // Prepare options
  3471. if (typeof optsOrCallback === "function") {
  3472. callback = optsOrCallback;
  3473. } else if (optsOrCallback && optsOrCallback.callback) {
  3474. callback = optsOrCallback.callback;
  3475. }
  3476. opts.callback = function (ctx, node, status) {
  3477. if (callback) {
  3478. callback.call(ctx, node, status);
  3479. }
  3480. dfd.notifyWith(ctx, [{ node: node, status: status }]);
  3481. };
  3482. if (opts.matchKey == null) {
  3483. opts.matchKey = function (node, key) {
  3484. return node.key === key;
  3485. };
  3486. }
  3487. // Convert array of path strings to array of segment arrays
  3488. if (!_isArray(keyPathList)) {
  3489. keyPathList = [keyPathList];
  3490. }
  3491. for (i = 0; i < keyPathList.length; i++) {
  3492. path = keyPathList[i];
  3493. // strip leading slash
  3494. if (path.charAt(0) === sep) {
  3495. path = path.substr(1);
  3496. }
  3497. // segListMap[path] = { parent: parent, segList: path.split(sep) };
  3498. pathSegList.push(path.split(sep));
  3499. // targetList.push({ parent: parent, segList: path.split(sep)/* , path: path*/});
  3500. }
  3501. // The timeout forces async behavior always (even if nodes are all loaded)
  3502. // This way a potential progress() event will fire.
  3503. setTimeout(function () {
  3504. self._loadKeyPathImpl(dfd, opts, parent, pathSegList).done(
  3505. function () {
  3506. dfd.resolve();
  3507. }
  3508. );
  3509. }, 0);
  3510. return dfd.promise();
  3511. },
  3512. /*
  3513. * Resolve a list of paths, relative to one parent node.
  3514. */
  3515. _loadKeyPathImpl: function (dfd, opts, parent, pathSegList) {
  3516. var deferredList,
  3517. i,
  3518. key,
  3519. node,
  3520. nodeKey,
  3521. remain,
  3522. remainMap,
  3523. tmpParent,
  3524. segList,
  3525. subDfd,
  3526. self = this;
  3527. function __findChild(parent, key) {
  3528. // console.log("__findChild", key, parent);
  3529. var i,
  3530. l,
  3531. cl = parent.children;
  3532. if (cl) {
  3533. for (i = 0, l = cl.length; i < l; i++) {
  3534. if (opts.matchKey(cl[i], key)) {
  3535. return cl[i];
  3536. }
  3537. }
  3538. }
  3539. return null;
  3540. }
  3541. // console.log("_loadKeyPathImpl, parent=", parent, ", pathSegList=", pathSegList);
  3542. // Pass 1:
  3543. // Handle all path segments for nodes that are already loaded.
  3544. // Collect distinct top-most lazy nodes in a map.
  3545. // Note that we can use node.key to de-dupe entries, even if a custom matcher would
  3546. // look for other node attributes.
  3547. // map[node.key] => {node: node, pathList: [list of remaining rest-paths]}
  3548. remainMap = {};
  3549. for (i = 0; i < pathSegList.length; i++) {
  3550. segList = pathSegList[i];
  3551. // target = targetList[i];
  3552. // Traverse and pop path segments (i.e. keys), until we hit a lazy, unloaded node
  3553. tmpParent = parent;
  3554. while (segList.length) {
  3555. key = segList.shift();
  3556. node = __findChild(tmpParent, key);
  3557. if (!node) {
  3558. this.warn(
  3559. "loadKeyPath: key not found: " +
  3560. key +
  3561. " (parent: " +
  3562. tmpParent +
  3563. ")"
  3564. );
  3565. opts.callback(this, key, "error");
  3566. break;
  3567. } else if (segList.length === 0) {
  3568. opts.callback(this, node, "ok");
  3569. break;
  3570. } else if (!node.lazy || node.hasChildren() !== undefined) {
  3571. opts.callback(this, node, "loaded");
  3572. tmpParent = node;
  3573. } else {
  3574. opts.callback(this, node, "loaded");
  3575. key = node.key; //target.segList.join(sep);
  3576. if (remainMap[key]) {
  3577. remainMap[key].pathSegList.push(segList);
  3578. } else {
  3579. remainMap[key] = {
  3580. parent: node,
  3581. pathSegList: [segList],
  3582. };
  3583. }
  3584. break;
  3585. }
  3586. }
  3587. }
  3588. // console.log("_loadKeyPathImpl AFTER pass 1, remainMap=", remainMap);
  3589. // Now load all lazy nodes and continue iteration for remaining paths
  3590. deferredList = [];
  3591. // Avoid jshint warning 'Don't make functions within a loop.':
  3592. function __lazyload(dfd, parent, pathSegList) {
  3593. // console.log("__lazyload", parent, "pathSegList=", pathSegList);
  3594. opts.callback(self, parent, "loading");
  3595. parent
  3596. .load()
  3597. .done(function () {
  3598. self._loadKeyPathImpl
  3599. .call(self, dfd, opts, parent, pathSegList)
  3600. .always(_makeResolveFunc(dfd, self));
  3601. })
  3602. .fail(function (errMsg) {
  3603. self.warn("loadKeyPath: error loading lazy " + parent);
  3604. opts.callback(self, node, "error");
  3605. dfd.rejectWith(self);
  3606. });
  3607. }
  3608. // remainMap contains parent nodes, each with a list of relative sub-paths.
  3609. // We start loading all of them now, and pass the the list to each loader.
  3610. for (nodeKey in remainMap) {
  3611. if (_hasProp(remainMap, nodeKey)) {
  3612. remain = remainMap[nodeKey];
  3613. // console.log("for(): remain=", remain, "remainMap=", remainMap);
  3614. // key = remain.segList.shift();
  3615. // node = __findChild(remain.parent, key);
  3616. // if (node == null) { // #576
  3617. // // Issue #576, refactored for v2.27:
  3618. // // The root cause was, that sometimes the wrong parent was used here
  3619. // // to find the next segment.
  3620. // // Falling back to getNodeByKey() was a hack that no longer works if a custom
  3621. // // matcher is used, because we cannot assume that a single segment-key is unique
  3622. // // throughout the tree.
  3623. // self.error("loadKeyPath: error loading child by key '" + key + "' (parent: " + target.parent + ")", target);
  3624. // // node = self.getNodeByKey(key);
  3625. // continue;
  3626. // }
  3627. subDfd = new $.Deferred();
  3628. deferredList.push(subDfd);
  3629. __lazyload(subDfd, remain.parent, remain.pathSegList);
  3630. }
  3631. }
  3632. // Return a promise that is resolved, when ALL paths were loaded
  3633. return $.when.apply($, deferredList).promise();
  3634. },
  3635. /** Re-fire beforeActivate, activate, and (optional) focus events.
  3636. * Calling this method in the `init` event, will activate the node that
  3637. * was marked 'active' in the source data, and optionally set the keyboard
  3638. * focus.
  3639. * @param [setFocus=false]
  3640. */
  3641. reactivate: function (setFocus) {
  3642. var res,
  3643. node = this.activeNode;
  3644. if (!node) {
  3645. return _getResolvedPromise();
  3646. }
  3647. this.activeNode = null; // Force re-activating
  3648. res = node.setActive(true, { noFocus: true });
  3649. if (setFocus) {
  3650. node.setFocus();
  3651. }
  3652. return res;
  3653. },
  3654. /** Reload tree from source and return a promise.
  3655. * @param [source] optional new source (defaults to initial source data)
  3656. * @returns {$.Promise}
  3657. */
  3658. reload: function (source) {
  3659. this._callHook("treeClear", this);
  3660. return this._callHook("treeLoad", this, source);
  3661. },
  3662. /**Render tree (i.e. create DOM elements for all top-level nodes).
  3663. * @param {boolean} [force=false] create DOM elemnts, even if parent is collapsed
  3664. * @param {boolean} [deep=false]
  3665. */
  3666. render: function (force, deep) {
  3667. return this.rootNode.render(force, deep);
  3668. },
  3669. /**(De)select all nodes.
  3670. * @param {boolean} [flag=true]
  3671. * @since 2.28
  3672. */
  3673. selectAll: function (flag) {
  3674. this.visit(function (node) {
  3675. node.setSelected(flag);
  3676. });
  3677. },
  3678. // TODO: selectKey: function(key, select)
  3679. // TODO: serializeArray: function(stopOnParents)
  3680. /**
  3681. * @param {boolean} [flag=true]
  3682. */
  3683. setFocus: function (flag) {
  3684. return this._callHook("treeSetFocus", this, flag);
  3685. },
  3686. /**
  3687. * Set current option value.
  3688. * (Note: this is the preferred variant of `$().fancytree("option", "KEY", VALUE)`)
  3689. * @param {string} name option name (may contain '.')
  3690. * @param {any} new value
  3691. */
  3692. setOption: function (optionName, value) {
  3693. return this.widget.option(optionName, value);
  3694. },
  3695. /**
  3696. * Call console.time() when in debug mode (verbose >= 4).
  3697. *
  3698. * @param {string} label
  3699. */
  3700. debugTime: function (label) {
  3701. if (this.options.debugLevel >= 4) {
  3702. window.console.time(this + " - " + label);
  3703. }
  3704. },
  3705. /**
  3706. * Call console.timeEnd() when in debug mode (verbose >= 4).
  3707. *
  3708. * @param {string} label
  3709. */
  3710. debugTimeEnd: function (label) {
  3711. if (this.options.debugLevel >= 4) {
  3712. window.console.timeEnd(this + " - " + label);
  3713. }
  3714. },
  3715. /**
  3716. * Return all nodes as nested list of {@link NodeData}.
  3717. *
  3718. * @param {boolean} [includeRoot=false] Returns the hidden system root node (and its children)
  3719. * @param {function} [callback] callback(dict, node) is called for every node, in order to allow modifications.
  3720. * Return `false` to ignore this node or "skip" to include this node without its children.
  3721. * @returns {Array | object}
  3722. * @see FancytreeNode#toDict
  3723. */
  3724. toDict: function (includeRoot, callback) {
  3725. var res = this.rootNode.toDict(true, callback);
  3726. return includeRoot ? res : res.children;
  3727. },
  3728. /* Implicitly called for string conversions.
  3729. * @returns {string}
  3730. */
  3731. toString: function () {
  3732. return "Fancytree@" + this._id;
  3733. // return "<Fancytree(#" + this._id + ")>";
  3734. },
  3735. /* _trigger a widget event with additional node ctx.
  3736. * @see EventData
  3737. */
  3738. _triggerNodeEvent: function (type, node, originalEvent, extra) {
  3739. // this.debug("_trigger(" + type + "): '" + ctx.node.title + "'", ctx);
  3740. var ctx = this._makeHookContext(node, originalEvent, extra),
  3741. res = this.widget._trigger(type, originalEvent, ctx);
  3742. if (res !== false && ctx.result !== undefined) {
  3743. return ctx.result;
  3744. }
  3745. return res;
  3746. },
  3747. /* _trigger a widget event with additional tree data. */
  3748. _triggerTreeEvent: function (type, originalEvent, extra) {
  3749. // this.debug("_trigger(" + type + ")", ctx);
  3750. var ctx = this._makeHookContext(this, originalEvent, extra),
  3751. res = this.widget._trigger(type, originalEvent, ctx);
  3752. if (res !== false && ctx.result !== undefined) {
  3753. return ctx.result;
  3754. }
  3755. return res;
  3756. },
  3757. /** Call fn(node) for all nodes in hierarchical order (depth-first).
  3758. *
  3759. * @param {function} fn the callback function.
  3760. * Return false to stop iteration, return "skip" to skip this node and children only.
  3761. * @returns {boolean} false, if the iterator was stopped.
  3762. */
  3763. visit: function (fn) {
  3764. return this.rootNode.visit(fn, false);
  3765. },
  3766. /** Call fn(node) for all nodes in vertical order, top down (or bottom up).<br>
  3767. * Stop iteration, if fn() returns false.<br>
  3768. * Return false if iteration was stopped.
  3769. *
  3770. * @param {function} fn the callback function.
  3771. * Return false to stop iteration, return "skip" to skip this node and children only.
  3772. * @param {object} [options]
  3773. * Defaults:
  3774. * {start: First top node, reverse: false, includeSelf: true, includeHidden: false}
  3775. * @returns {boolean} false if iteration was cancelled
  3776. * @since 2.28
  3777. */
  3778. visitRows: function (fn, opts) {
  3779. if (!this.rootNode.hasChildren()) {
  3780. return false;
  3781. }
  3782. if (opts && opts.reverse) {
  3783. delete opts.reverse;
  3784. return this._visitRowsUp(fn, opts);
  3785. }
  3786. opts = opts || {};
  3787. var i,
  3788. nextIdx,
  3789. parent,
  3790. res,
  3791. siblings,
  3792. siblingOfs = 0,
  3793. skipFirstNode = opts.includeSelf === false,
  3794. includeHidden = !!opts.includeHidden,
  3795. checkFilter = !includeHidden && this.enableFilter,
  3796. node = opts.start || this.rootNode.children[0];
  3797. parent = node.parent;
  3798. while (parent) {
  3799. // visit siblings
  3800. siblings = parent.children;
  3801. nextIdx = siblings.indexOf(node) + siblingOfs;
  3802. _assert(
  3803. nextIdx >= 0,
  3804. "Could not find " +
  3805. node +
  3806. " in parent's children: " +
  3807. parent
  3808. );
  3809. for (i = nextIdx; i < siblings.length; i++) {
  3810. node = siblings[i];
  3811. if (checkFilter && !node.match && !node.subMatchCount) {
  3812. continue;
  3813. }
  3814. if (!skipFirstNode && fn(node) === false) {
  3815. return false;
  3816. }
  3817. skipFirstNode = false;
  3818. // Dive into node's child nodes
  3819. if (
  3820. node.children &&
  3821. node.children.length &&
  3822. (includeHidden || node.expanded)
  3823. ) {
  3824. // Disable warning: Functions declared within loops referencing an outer
  3825. // scoped variable may lead to confusing semantics:
  3826. /*jshint -W083 */
  3827. res = node.visit(function (n) {
  3828. if (checkFilter && !n.match && !n.subMatchCount) {
  3829. return "skip";
  3830. }
  3831. if (fn(n) === false) {
  3832. return false;
  3833. }
  3834. if (!includeHidden && n.children && !n.expanded) {
  3835. return "skip";
  3836. }
  3837. }, false);
  3838. /*jshint +W083 */
  3839. if (res === false) {
  3840. return false;
  3841. }
  3842. }
  3843. }
  3844. // Visit parent nodes (bottom up)
  3845. node = parent;
  3846. parent = parent.parent;
  3847. siblingOfs = 1; //
  3848. }
  3849. return true;
  3850. },
  3851. /* Call fn(node) for all nodes in vertical order, bottom up.
  3852. */
  3853. _visitRowsUp: function (fn, opts) {
  3854. var children,
  3855. idx,
  3856. parent,
  3857. includeHidden = !!opts.includeHidden,
  3858. node = opts.start || this.rootNode.children[0];
  3859. while (true) {
  3860. parent = node.parent;
  3861. children = parent.children;
  3862. if (children[0] === node) {
  3863. // If this is already the first sibling, goto parent
  3864. node = parent;
  3865. if (!node.parent) {
  3866. break; // first node of the tree
  3867. }
  3868. children = parent.children;
  3869. } else {
  3870. // Otherwise, goto prev. sibling
  3871. idx = children.indexOf(node);
  3872. node = children[idx - 1];
  3873. // If the prev. sibling has children, follow down to last descendant
  3874. while (
  3875. // See: https://github.com/eslint/eslint/issues/11302
  3876. // eslint-disable-next-line no-unmodified-loop-condition
  3877. (includeHidden || node.expanded) &&
  3878. node.children &&
  3879. node.children.length
  3880. ) {
  3881. children = node.children;
  3882. parent = node;
  3883. node = children[children.length - 1];
  3884. }
  3885. }
  3886. // Skip invisible
  3887. if (!includeHidden && !node.isVisible()) {
  3888. continue;
  3889. }
  3890. if (fn(node) === false) {
  3891. return false;
  3892. }
  3893. }
  3894. },
  3895. /** Write warning to browser console if debugLevel >= 2 (prepending tree info)
  3896. *
  3897. * @param {*} msg string or object or array of such
  3898. */
  3899. warn: function (msg) {
  3900. if (this.options.debugLevel >= 2) {
  3901. Array.prototype.unshift.call(arguments, this.toString());
  3902. consoleApply("warn", arguments);
  3903. }
  3904. },
  3905. };
  3906. /**
  3907. * These additional methods of the {@link Fancytree} class are 'hook functions'
  3908. * that can be used and overloaded by extensions.
  3909. *
  3910. * @see [writing extensions](https://github.com/mar10/fancytree/wiki/TutorialExtensions)
  3911. * @mixin Fancytree_Hooks
  3912. */
  3913. $.extend(
  3914. Fancytree.prototype,
  3915. /** @lends Fancytree_Hooks# */
  3916. {
  3917. /** Default handling for mouse click events.
  3918. *
  3919. * @param {EventData} ctx
  3920. */
  3921. nodeClick: function (ctx) {
  3922. var activate,
  3923. expand,
  3924. // event = ctx.originalEvent,
  3925. targetType = ctx.targetType,
  3926. node = ctx.node;
  3927. // this.debug("ftnode.onClick(" + event.type + "): ftnode:" + this + ", button:" + event.button + ", which: " + event.which, ctx);
  3928. // TODO: use switch
  3929. // TODO: make sure clicks on embedded <input> doesn't steal focus (see table sample)
  3930. if (targetType === "expander") {
  3931. if (node.isLoading()) {
  3932. // #495: we probably got a click event while a lazy load is pending.
  3933. // The 'expanded' state is not yet set, so 'toggle' would expand
  3934. // and trigger lazyLoad again.
  3935. // It would be better to allow to collapse/expand the status node
  3936. // while loading (instead of ignoring), but that would require some
  3937. // more work.
  3938. node.debug("Got 2nd click while loading: ignored");
  3939. return;
  3940. }
  3941. // Clicking the expander icon always expands/collapses
  3942. this._callHook("nodeToggleExpanded", ctx);
  3943. } else if (targetType === "checkbox") {
  3944. // Clicking the checkbox always (de)selects
  3945. this._callHook("nodeToggleSelected", ctx);
  3946. if (ctx.options.focusOnSelect) {
  3947. // #358
  3948. this._callHook("nodeSetFocus", ctx, true);
  3949. }
  3950. } else {
  3951. // Honor `clickFolderMode` for
  3952. expand = false;
  3953. activate = true;
  3954. if (node.folder) {
  3955. switch (ctx.options.clickFolderMode) {
  3956. case 2: // expand only
  3957. expand = true;
  3958. activate = false;
  3959. break;
  3960. case 3: // expand and activate
  3961. activate = true;
  3962. expand = true; //!node.isExpanded();
  3963. break;
  3964. // else 1 or 4: just activate
  3965. }
  3966. }
  3967. if (activate) {
  3968. this.nodeSetFocus(ctx);
  3969. this._callHook("nodeSetActive", ctx, true);
  3970. }
  3971. if (expand) {
  3972. if (!activate) {
  3973. // this._callHook("nodeSetFocus", ctx);
  3974. }
  3975. // this._callHook("nodeSetExpanded", ctx, true);
  3976. this._callHook("nodeToggleExpanded", ctx);
  3977. }
  3978. }
  3979. // Make sure that clicks stop, otherwise <a href='#'> jumps to the top
  3980. // if(event.target.localName === "a" && event.target.className === "fancytree-title"){
  3981. // event.preventDefault();
  3982. // }
  3983. // TODO: return promise?
  3984. },
  3985. /** Collapse all other children of same parent.
  3986. *
  3987. * @param {EventData} ctx
  3988. * @param {object} callOpts
  3989. */
  3990. nodeCollapseSiblings: function (ctx, callOpts) {
  3991. // TODO: return promise?
  3992. var ac,
  3993. i,
  3994. l,
  3995. node = ctx.node;
  3996. if (node.parent) {
  3997. ac = node.parent.children;
  3998. for (i = 0, l = ac.length; i < l; i++) {
  3999. if (ac[i] !== node && ac[i].expanded) {
  4000. this._callHook(
  4001. "nodeSetExpanded",
  4002. ac[i],
  4003. false,
  4004. callOpts
  4005. );
  4006. }
  4007. }
  4008. }
  4009. },
  4010. /** Default handling for mouse douleclick events.
  4011. * @param {EventData} ctx
  4012. */
  4013. nodeDblclick: function (ctx) {
  4014. // TODO: return promise?
  4015. if (
  4016. ctx.targetType === "title" &&
  4017. ctx.options.clickFolderMode === 4
  4018. ) {
  4019. // this.nodeSetFocus(ctx);
  4020. // this._callHook("nodeSetActive", ctx, true);
  4021. this._callHook("nodeToggleExpanded", ctx);
  4022. }
  4023. // TODO: prevent text selection on dblclicks
  4024. if (ctx.targetType === "title") {
  4025. ctx.originalEvent.preventDefault();
  4026. }
  4027. },
  4028. /** Default handling for mouse keydown events.
  4029. *
  4030. * NOTE: this may be called with node == null if tree (but no node) has focus.
  4031. * @param {EventData} ctx
  4032. */
  4033. nodeKeydown: function (ctx) {
  4034. // TODO: return promise?
  4035. var matchNode,
  4036. stamp,
  4037. _res,
  4038. focusNode,
  4039. event = ctx.originalEvent,
  4040. node = ctx.node,
  4041. tree = ctx.tree,
  4042. opts = ctx.options,
  4043. which = event.which,
  4044. // #909: Use event.key, to get unicode characters.
  4045. // We can't use `/\w/.test(key)`, because that would
  4046. // only detect plain ascii alpha-numerics. But we still need
  4047. // to ignore modifier-only, whitespace, cursor-keys, etc.
  4048. key = event.key || String.fromCharCode(which),
  4049. specialModifiers = !!(
  4050. event.altKey ||
  4051. event.ctrlKey ||
  4052. event.metaKey
  4053. ),
  4054. isAlnum =
  4055. !MODIFIERS[which] &&
  4056. !SPECIAL_KEYCODES[which] &&
  4057. !specialModifiers,
  4058. $target = $(event.target),
  4059. handled = true,
  4060. activate = !(event.ctrlKey || !opts.autoActivate);
  4061. // (node || FT).debug("ftnode.nodeKeydown(" + event.type + "): ftnode:" + this + ", charCode:" + event.charCode + ", keyCode: " + event.keyCode + ", which: " + event.which);
  4062. // FT.debug( "eventToString(): " + FT.eventToString(event) + ", key='" + key + "', isAlnum: " + isAlnum );
  4063. // Set focus to active (or first node) if no other node has the focus yet
  4064. if (!node) {
  4065. focusNode = this.getActiveNode() || this.getFirstChild();
  4066. if (focusNode) {
  4067. focusNode.setFocus();
  4068. node = ctx.node = this.focusNode;
  4069. node.debug("Keydown force focus on active node");
  4070. }
  4071. }
  4072. if (
  4073. opts.quicksearch &&
  4074. isAlnum &&
  4075. !$target.is(":input:enabled")
  4076. ) {
  4077. // Allow to search for longer streaks if typed in quickly
  4078. stamp = Date.now();
  4079. if (stamp - tree.lastQuicksearchTime > 500) {
  4080. tree.lastQuicksearchTerm = "";
  4081. }
  4082. tree.lastQuicksearchTime = stamp;
  4083. tree.lastQuicksearchTerm += key;
  4084. // tree.debug("quicksearch find", tree.lastQuicksearchTerm);
  4085. matchNode = tree.findNextNode(
  4086. tree.lastQuicksearchTerm,
  4087. tree.getActiveNode()
  4088. );
  4089. if (matchNode) {
  4090. matchNode.setActive();
  4091. }
  4092. event.preventDefault();
  4093. return;
  4094. }
  4095. switch (FT.eventToString(event)) {
  4096. case "+":
  4097. case "=": // 187: '+' @ Chrome, Safari
  4098. tree.nodeSetExpanded(ctx, true);
  4099. break;
  4100. case "-":
  4101. tree.nodeSetExpanded(ctx, false);
  4102. break;
  4103. case "space":
  4104. if (node.isPagingNode()) {
  4105. tree._triggerNodeEvent("clickPaging", ctx, event);
  4106. } else if (
  4107. FT.evalOption("checkbox", node, node, opts, false)
  4108. ) {
  4109. // #768
  4110. tree.nodeToggleSelected(ctx);
  4111. } else {
  4112. tree.nodeSetActive(ctx, true);
  4113. }
  4114. break;
  4115. case "return":
  4116. tree.nodeSetActive(ctx, true);
  4117. break;
  4118. case "home":
  4119. case "end":
  4120. case "backspace":
  4121. case "left":
  4122. case "right":
  4123. case "up":
  4124. case "down":
  4125. _res = node.navigate(event.which, activate);
  4126. break;
  4127. default:
  4128. handled = false;
  4129. }
  4130. if (handled) {
  4131. event.preventDefault();
  4132. }
  4133. },
  4134. // /** Default handling for mouse keypress events. */
  4135. // nodeKeypress: function(ctx) {
  4136. // var event = ctx.originalEvent;
  4137. // },
  4138. // /** Trigger lazyLoad event (async). */
  4139. // nodeLazyLoad: function(ctx) {
  4140. // var node = ctx.node;
  4141. // if(this._triggerNodeEvent())
  4142. // },
  4143. /** Load child nodes (async).
  4144. *
  4145. * @param {EventData} ctx
  4146. * @param {object[]|object|string|$.Promise|function} source
  4147. * @returns {$.Promise} The deferred will be resolved as soon as the (ajax)
  4148. * data was rendered.
  4149. */
  4150. nodeLoadChildren: function (ctx, source) {
  4151. var ajax,
  4152. delay,
  4153. ajaxDfd = null,
  4154. resultDfd,
  4155. isAsync = true,
  4156. tree = ctx.tree,
  4157. node = ctx.node,
  4158. nodePrevParent = node.parent,
  4159. tag = "nodeLoadChildren",
  4160. requestId = Date.now();
  4161. // `source` is a callback: use the returned result instead:
  4162. if (_isFunction(source)) {
  4163. source = source.call(tree, { type: "source" }, ctx);
  4164. _assert(
  4165. !_isFunction(source),
  4166. "source callback must not return another function"
  4167. );
  4168. }
  4169. // `source` is already a promise:
  4170. if (_isFunction(source.then)) {
  4171. // _assert(_isFunction(source.always), "Expected jQuery?");
  4172. ajaxDfd = source;
  4173. } else if (source.url) {
  4174. // `source` is an Ajax options object
  4175. ajax = $.extend({}, ctx.options.ajax, source);
  4176. if (ajax.debugDelay) {
  4177. // Simulate a slow server
  4178. delay = ajax.debugDelay;
  4179. delete ajax.debugDelay; // remove debug option
  4180. if (_isArray(delay)) {
  4181. // random delay range [min..max]
  4182. delay =
  4183. delay[0] +
  4184. Math.random() * (delay[1] - delay[0]);
  4185. }
  4186. node.warn(
  4187. "nodeLoadChildren waiting debugDelay " +
  4188. Math.round(delay) +
  4189. " ms ..."
  4190. );
  4191. ajaxDfd = $.Deferred(function (ajaxDfd) {
  4192. setTimeout(function () {
  4193. $.ajax(ajax)
  4194. .done(function () {
  4195. ajaxDfd.resolveWith(this, arguments);
  4196. })
  4197. .fail(function () {
  4198. ajaxDfd.rejectWith(this, arguments);
  4199. });
  4200. }, delay);
  4201. });
  4202. } else {
  4203. ajaxDfd = $.ajax(ajax);
  4204. }
  4205. } else if ($.isPlainObject(source) || _isArray(source)) {
  4206. // `source` is already a constant dict or list, but we convert
  4207. // to a thenable for unified processing.
  4208. // 2020-01-03: refactored.
  4209. // `ajaxDfd = $.when(source)` would do the trick, but the returned
  4210. // promise will resolve async, which broke some tests and
  4211. // would probably also break current implementations out there.
  4212. // So we mock-up a thenable that resolves synchronously:
  4213. ajaxDfd = {
  4214. then: function (resolve, reject) {
  4215. resolve(source, null, null);
  4216. },
  4217. };
  4218. isAsync = false;
  4219. } else {
  4220. $.error("Invalid source type: " + source);
  4221. }
  4222. // Check for overlapping requests
  4223. if (node._requestId) {
  4224. node.warn(
  4225. "Recursive load request #" +
  4226. requestId +
  4227. " while #" +
  4228. node._requestId +
  4229. " is pending."
  4230. );
  4231. node._requestId = requestId;
  4232. // node.debug("Send load request #" + requestId);
  4233. }
  4234. if (isAsync) {
  4235. tree.debugTime(tag);
  4236. tree.nodeSetStatus(ctx, "loading");
  4237. }
  4238. // The async Ajax request has now started...
  4239. // Defer the deferred:
  4240. // we want to be able to reject invalid responses, even if
  4241. // the raw HTTP Ajax XHR resolved as Ok.
  4242. // We use the ajaxDfd.then() syntax here, which is compatible with
  4243. // jQuery and ECMA6.
  4244. // However resultDfd is a jQuery deferred, which is currently the
  4245. // expected result type of nodeLoadChildren()
  4246. resultDfd = new $.Deferred();
  4247. ajaxDfd.then(
  4248. function (data, textStatus, jqXHR) {
  4249. // ajaxDfd was resolved, but we reject or resolve resultDfd
  4250. // depending on the response data
  4251. var errorObj, res;
  4252. if (
  4253. (source.dataType === "json" ||
  4254. source.dataType === "jsonp") &&
  4255. typeof data === "string"
  4256. ) {
  4257. $.error(
  4258. "Ajax request returned a string (did you get the JSON dataType wrong?)."
  4259. );
  4260. }
  4261. if (node._requestId && node._requestId > requestId) {
  4262. // The expected request time stamp is later than `requestId`
  4263. // (which was kept as as closure variable to this handler function)
  4264. // node.warn("Ignored load response for obsolete request #" + requestId + " (expected #" + node._requestId + ")");
  4265. resultDfd.rejectWith(this, [
  4266. RECURSIVE_REQUEST_ERROR,
  4267. ]);
  4268. return;
  4269. // } else {
  4270. // node.debug("Response returned for load request #" + requestId);
  4271. }
  4272. if (node.parent === null && nodePrevParent !== null) {
  4273. resultDfd.rejectWith(this, [
  4274. INVALID_REQUEST_TARGET_ERROR,
  4275. ]);
  4276. return;
  4277. }
  4278. // Allow to adjust the received response data in the `postProcess` event.
  4279. if (ctx.options.postProcess) {
  4280. // The handler may either
  4281. // - modify `ctx.response` in-place (and leave `ctx.result` undefined)
  4282. // => res = undefined
  4283. // - return a replacement in `ctx.result`
  4284. // => res = <new data>
  4285. // If res contains an `error` property, an error status is displayed
  4286. try {
  4287. res = tree._triggerNodeEvent(
  4288. "postProcess",
  4289. ctx,
  4290. ctx.originalEvent,
  4291. {
  4292. response: data,
  4293. error: null,
  4294. dataType: source.dataType,
  4295. }
  4296. );
  4297. if (res.error) {
  4298. tree.warn(
  4299. "postProcess returned error:",
  4300. res
  4301. );
  4302. }
  4303. } catch (e) {
  4304. res = {
  4305. error: e,
  4306. message: "" + e,
  4307. details: "postProcess failed",
  4308. };
  4309. }
  4310. if (res.error) {
  4311. // Either postProcess failed with an exception, or the returned
  4312. // result object has an 'error' property attached:
  4313. errorObj = $.isPlainObject(res.error)
  4314. ? res.error
  4315. : { message: res.error };
  4316. errorObj = tree._makeHookContext(
  4317. node,
  4318. null,
  4319. errorObj
  4320. );
  4321. resultDfd.rejectWith(this, [errorObj]);
  4322. return;
  4323. }
  4324. if (
  4325. _isArray(res) ||
  4326. ($.isPlainObject(res) && _isArray(res.children))
  4327. ) {
  4328. // Use `ctx.result` if valid
  4329. // (otherwise use existing data, which may have been modified in-place)
  4330. data = res;
  4331. }
  4332. } else if (
  4333. data &&
  4334. _hasProp(data, "d") &&
  4335. ctx.options.enableAspx
  4336. ) {
  4337. // Process ASPX WebMethod JSON object inside "d" property
  4338. // (only if no postProcess event was defined)
  4339. if (ctx.options.enableAspx === 42) {
  4340. tree.warn(
  4341. "The default for enableAspx will change to `false` in the fututure. " +
  4342. "Pass `enableAspx: true` or implement postProcess to silence this warning."
  4343. );
  4344. }
  4345. data =
  4346. typeof data.d === "string"
  4347. ? $.parseJSON(data.d)
  4348. : data.d;
  4349. }
  4350. resultDfd.resolveWith(this, [data]);
  4351. },
  4352. function (jqXHR, textStatus, errorThrown) {
  4353. // ajaxDfd was rejected, so we reject resultDfd as well
  4354. var errorObj = tree._makeHookContext(node, null, {
  4355. error: jqXHR,
  4356. args: Array.prototype.slice.call(arguments),
  4357. message: errorThrown,
  4358. details: jqXHR.status + ": " + errorThrown,
  4359. });
  4360. resultDfd.rejectWith(this, [errorObj]);
  4361. }
  4362. );
  4363. // The async Ajax request has now started.
  4364. // resultDfd will be resolved/rejected after the response arrived,
  4365. // was postProcessed, and checked.
  4366. // Now we implement the UI update and add the data to the tree.
  4367. // We also return this promise to the caller.
  4368. resultDfd
  4369. .done(function (data) {
  4370. tree.nodeSetStatus(ctx, "ok");
  4371. var children, metaData, noDataRes;
  4372. if ($.isPlainObject(data)) {
  4373. // We got {foo: 'abc', children: [...]}
  4374. // Copy extra properties to tree.data.foo
  4375. _assert(
  4376. node.isRootNode(),
  4377. "source may only be an object for root nodes (expecting an array of child objects otherwise)"
  4378. );
  4379. _assert(
  4380. _isArray(data.children),
  4381. "if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')"
  4382. );
  4383. metaData = data;
  4384. children = data.children;
  4385. delete metaData.children;
  4386. // Copy some attributes to tree.data
  4387. $.each(TREE_ATTRS, function (i, attr) {
  4388. if (metaData[attr] !== undefined) {
  4389. tree[attr] = metaData[attr];
  4390. delete metaData[attr];
  4391. }
  4392. });
  4393. // Copy all other attributes to tree.data.NAME
  4394. $.extend(tree.data, metaData);
  4395. } else {
  4396. children = data;
  4397. }
  4398. _assert(
  4399. _isArray(children),
  4400. "expected array of children"
  4401. );
  4402. node._setChildren(children);
  4403. if (tree.options.nodata && children.length === 0) {
  4404. if (_isFunction(tree.options.nodata)) {
  4405. noDataRes = tree.options.nodata.call(
  4406. tree,
  4407. { type: "nodata" },
  4408. ctx
  4409. );
  4410. } else if (
  4411. tree.options.nodata === true &&
  4412. node.isRootNode()
  4413. ) {
  4414. noDataRes = tree.options.strings.noData;
  4415. } else if (
  4416. typeof tree.options.nodata === "string" &&
  4417. node.isRootNode()
  4418. ) {
  4419. noDataRes = tree.options.nodata;
  4420. }
  4421. if (noDataRes) {
  4422. node.setStatus("nodata", noDataRes);
  4423. }
  4424. }
  4425. // trigger fancytreeloadchildren
  4426. tree._triggerNodeEvent("loadChildren", node);
  4427. })
  4428. .fail(function (error) {
  4429. var ctxErr;
  4430. if (error === RECURSIVE_REQUEST_ERROR) {
  4431. node.warn(
  4432. "Ignored response for obsolete load request #" +
  4433. requestId +
  4434. " (expected #" +
  4435. node._requestId +
  4436. ")"
  4437. );
  4438. return;
  4439. } else if (error === INVALID_REQUEST_TARGET_ERROR) {
  4440. node.warn(
  4441. "Lazy parent node was removed while loading: discarding response."
  4442. );
  4443. return;
  4444. } else if (error.node && error.error && error.message) {
  4445. // error is already a context object
  4446. ctxErr = error;
  4447. } else {
  4448. ctxErr = tree._makeHookContext(node, null, {
  4449. error: error, // it can be jqXHR or any custom error
  4450. args: Array.prototype.slice.call(arguments),
  4451. message: error
  4452. ? error.message || error.toString()
  4453. : "",
  4454. });
  4455. if (ctxErr.message === "[object Object]") {
  4456. ctxErr.message = "";
  4457. }
  4458. }
  4459. node.warn(
  4460. "Load children failed (" + ctxErr.message + ")",
  4461. ctxErr
  4462. );
  4463. if (
  4464. tree._triggerNodeEvent(
  4465. "loadError",
  4466. ctxErr,
  4467. null
  4468. ) !== false
  4469. ) {
  4470. tree.nodeSetStatus(
  4471. ctx,
  4472. "error",
  4473. ctxErr.message,
  4474. ctxErr.details
  4475. );
  4476. }
  4477. })
  4478. .always(function () {
  4479. node._requestId = null;
  4480. if (isAsync) {
  4481. tree.debugTimeEnd(tag);
  4482. }
  4483. });
  4484. return resultDfd.promise();
  4485. },
  4486. /** [Not Implemented] */
  4487. nodeLoadKeyPath: function (ctx, keyPathList) {
  4488. // TODO: implement and improve
  4489. // http://code.google.com/p/dynatree/issues/detail?id=222
  4490. },
  4491. /**
  4492. * Remove a single direct child of ctx.node.
  4493. * @param {EventData} ctx
  4494. * @param {FancytreeNode} childNode dircect child of ctx.node
  4495. */
  4496. nodeRemoveChild: function (ctx, childNode) {
  4497. var idx,
  4498. node = ctx.node,
  4499. // opts = ctx.options,
  4500. subCtx = $.extend({}, ctx, { node: childNode }),
  4501. children = node.children;
  4502. // FT.debug("nodeRemoveChild()", node.toString(), childNode.toString());
  4503. if (children.length === 1) {
  4504. _assert(childNode === children[0], "invalid single child");
  4505. return this.nodeRemoveChildren(ctx);
  4506. }
  4507. if (
  4508. this.activeNode &&
  4509. (childNode === this.activeNode ||
  4510. this.activeNode.isDescendantOf(childNode))
  4511. ) {
  4512. this.activeNode.setActive(false); // TODO: don't fire events
  4513. }
  4514. if (
  4515. this.focusNode &&
  4516. (childNode === this.focusNode ||
  4517. this.focusNode.isDescendantOf(childNode))
  4518. ) {
  4519. this.focusNode = null;
  4520. }
  4521. // TODO: persist must take care to clear select and expand cookies
  4522. this.nodeRemoveMarkup(subCtx);
  4523. this.nodeRemoveChildren(subCtx);
  4524. idx = $.inArray(childNode, children);
  4525. _assert(idx >= 0, "invalid child");
  4526. // Notify listeners
  4527. node.triggerModifyChild("remove", childNode);
  4528. // Unlink to support GC
  4529. childNode.visit(function (n) {
  4530. n.parent = null;
  4531. }, true);
  4532. this._callHook("treeRegisterNode", this, false, childNode);
  4533. // remove from child list
  4534. children.splice(idx, 1);
  4535. },
  4536. /**Remove HTML markup for all descendents of ctx.node.
  4537. * @param {EventData} ctx
  4538. */
  4539. nodeRemoveChildMarkup: function (ctx) {
  4540. var node = ctx.node;
  4541. // FT.debug("nodeRemoveChildMarkup()", node.toString());
  4542. // TODO: Unlink attr.ftnode to support GC
  4543. if (node.ul) {
  4544. if (node.isRootNode()) {
  4545. $(node.ul).empty();
  4546. } else {
  4547. $(node.ul).remove();
  4548. node.ul = null;
  4549. }
  4550. node.visit(function (n) {
  4551. n.li = n.ul = null;
  4552. });
  4553. }
  4554. },
  4555. /**Remove all descendants of ctx.node.
  4556. * @param {EventData} ctx
  4557. */
  4558. nodeRemoveChildren: function (ctx) {
  4559. var //subCtx,
  4560. tree = ctx.tree,
  4561. node = ctx.node,
  4562. children = node.children;
  4563. // opts = ctx.options;
  4564. // FT.debug("nodeRemoveChildren()", node.toString());
  4565. if (!children) {
  4566. return;
  4567. }
  4568. if (this.activeNode && this.activeNode.isDescendantOf(node)) {
  4569. this.activeNode.setActive(false); // TODO: don't fire events
  4570. }
  4571. if (this.focusNode && this.focusNode.isDescendantOf(node)) {
  4572. this.focusNode = null;
  4573. }
  4574. // TODO: persist must take care to clear select and expand cookies
  4575. this.nodeRemoveChildMarkup(ctx);
  4576. // Unlink children to support GC
  4577. // TODO: also delete this.children (not possible using visit())
  4578. // subCtx = $.extend({}, ctx);
  4579. node.triggerModifyChild("remove", null);
  4580. node.visit(function (n) {
  4581. n.parent = null;
  4582. tree._callHook("treeRegisterNode", tree, false, n);
  4583. });
  4584. if (node.lazy) {
  4585. // 'undefined' would be interpreted as 'not yet loaded' for lazy nodes
  4586. node.children = [];
  4587. } else {
  4588. node.children = null;
  4589. }
  4590. if (!node.isRootNode()) {
  4591. node.expanded = false; // #449, #459
  4592. }
  4593. this.nodeRenderStatus(ctx);
  4594. },
  4595. /**Remove HTML markup for ctx.node and all its descendents.
  4596. * @param {EventData} ctx
  4597. */
  4598. nodeRemoveMarkup: function (ctx) {
  4599. var node = ctx.node;
  4600. // FT.debug("nodeRemoveMarkup()", node.toString());
  4601. // TODO: Unlink attr.ftnode to support GC
  4602. if (node.li) {
  4603. $(node.li).remove();
  4604. node.li = null;
  4605. }
  4606. this.nodeRemoveChildMarkup(ctx);
  4607. },
  4608. /**
  4609. * Create `<li><span>..</span> .. </li>` tags for this node.
  4610. *
  4611. * This method takes care that all HTML markup is created that is required
  4612. * to display this node in its current state.
  4613. *
  4614. * Call this method to create new nodes, or after the strucuture
  4615. * was changed (e.g. after moving this node or adding/removing children)
  4616. * nodeRenderTitle() and nodeRenderStatus() are implied.
  4617. *
  4618. * ```html
  4619. * <li id='KEY' ftnode=NODE>
  4620. * <span class='fancytree-node fancytree-expanded fancytree-has-children fancytree-lastsib fancytree-exp-el fancytree-ico-e'>
  4621. * <span class="fancytree-expander"></span>
  4622. * <span class="fancytree-checkbox"></span> // only present in checkbox mode
  4623. * <span class="fancytree-icon"></span>
  4624. * <a href="#" class="fancytree-title"> Node 1 </a>
  4625. * </span>
  4626. * <ul> // only present if node has children
  4627. * <li id='KEY' ftnode=NODE> child1 ... </li>
  4628. * <li id='KEY' ftnode=NODE> child2 ... </li>
  4629. * </ul>
  4630. * </li>
  4631. * ```
  4632. *
  4633. * @param {EventData} ctx
  4634. * @param {boolean} [force=false] re-render, even if html markup was already created
  4635. * @param {boolean} [deep=false] also render all descendants, even if parent is collapsed
  4636. * @param {boolean} [collapsed=false] force root node to be collapsed, so we can apply animated expand later
  4637. */
  4638. nodeRender: function (ctx, force, deep, collapsed, _recursive) {
  4639. /* This method must take care of all cases where the current data mode
  4640. * (i.e. node hierarchy) does not match the current markup.
  4641. *
  4642. * - node was not yet rendered:
  4643. * create markup
  4644. * - node was rendered: exit fast
  4645. * - children have been added
  4646. * - children have been removed
  4647. */
  4648. var childLI,
  4649. childNode1,
  4650. childNode2,
  4651. i,
  4652. l,
  4653. next,
  4654. subCtx,
  4655. node = ctx.node,
  4656. tree = ctx.tree,
  4657. opts = ctx.options,
  4658. aria = opts.aria,
  4659. firstTime = false,
  4660. parent = node.parent,
  4661. isRootNode = !parent,
  4662. children = node.children,
  4663. successorLi = null;
  4664. // FT.debug("nodeRender(" + !!force + ", " + !!deep + ")", node.toString());
  4665. if (tree._enableUpdate === false) {
  4666. // tree.debug("no render", tree._enableUpdate);
  4667. return;
  4668. }
  4669. if (!isRootNode && !parent.ul) {
  4670. // Calling node.collapse on a deep, unrendered node
  4671. return;
  4672. }
  4673. _assert(isRootNode || parent.ul, "parent UL must exist");
  4674. // Render the node
  4675. if (!isRootNode) {
  4676. // Discard markup on force-mode, or if it is not linked to parent <ul>
  4677. if (
  4678. node.li &&
  4679. (force || node.li.parentNode !== node.parent.ul)
  4680. ) {
  4681. if (node.li.parentNode === node.parent.ul) {
  4682. // #486: store following node, so we can insert the new markup there later
  4683. successorLi = node.li.nextSibling;
  4684. } else {
  4685. // May happen, when a top-level node was dropped over another
  4686. this.debug(
  4687. "Unlinking " +
  4688. node +
  4689. " (must be child of " +
  4690. node.parent +
  4691. ")"
  4692. );
  4693. }
  4694. // this.debug("nodeRemoveMarkup...");
  4695. this.nodeRemoveMarkup(ctx);
  4696. }
  4697. // Create <li><span /> </li>
  4698. // node.debug("render...");
  4699. if (node.li) {
  4700. // this.nodeRenderTitle(ctx);
  4701. this.nodeRenderStatus(ctx);
  4702. } else {
  4703. // node.debug("render... really");
  4704. firstTime = true;
  4705. node.li = document.createElement("li");
  4706. node.li.ftnode = node;
  4707. if (node.key && opts.generateIds) {
  4708. node.li.id = opts.idPrefix + node.key;
  4709. }
  4710. node.span = document.createElement("span");
  4711. node.span.className = "fancytree-node";
  4712. if (aria && !node.tr) {
  4713. $(node.li).attr("role", "treeitem");
  4714. }
  4715. node.li.appendChild(node.span);
  4716. // Create inner HTML for the <span> (expander, checkbox, icon, and title)
  4717. this.nodeRenderTitle(ctx);
  4718. // Allow tweaking and binding, after node was created for the first time
  4719. if (opts.createNode) {
  4720. opts.createNode.call(
  4721. tree,
  4722. { type: "createNode" },
  4723. ctx
  4724. );
  4725. }
  4726. }
  4727. // Allow tweaking after node state was rendered
  4728. if (opts.renderNode) {
  4729. opts.renderNode.call(tree, { type: "renderNode" }, ctx);
  4730. }
  4731. }
  4732. // Visit child nodes
  4733. if (children) {
  4734. if (isRootNode || node.expanded || deep === true) {
  4735. // Create a UL to hold the children
  4736. if (!node.ul) {
  4737. node.ul = document.createElement("ul");
  4738. if (
  4739. (collapsed === true && !_recursive) ||
  4740. !node.expanded
  4741. ) {
  4742. // hide top UL, so we can use an animation to show it later
  4743. node.ul.style.display = "none";
  4744. }
  4745. if (aria) {
  4746. $(node.ul).attr("role", "group");
  4747. }
  4748. if (node.li) {
  4749. // issue #67
  4750. node.li.appendChild(node.ul);
  4751. } else {
  4752. node.tree.$div.append(node.ul);
  4753. }
  4754. }
  4755. // Add child markup
  4756. for (i = 0, l = children.length; i < l; i++) {
  4757. subCtx = $.extend({}, ctx, { node: children[i] });
  4758. this.nodeRender(subCtx, force, deep, false, true);
  4759. }
  4760. // Remove <li> if nodes have moved to another parent
  4761. childLI = node.ul.firstChild;
  4762. while (childLI) {
  4763. childNode2 = childLI.ftnode;
  4764. if (childNode2 && childNode2.parent !== node) {
  4765. node.debug(
  4766. "_fixParent: remove missing " + childNode2,
  4767. childLI
  4768. );
  4769. next = childLI.nextSibling;
  4770. childLI.parentNode.removeChild(childLI);
  4771. childLI = next;
  4772. } else {
  4773. childLI = childLI.nextSibling;
  4774. }
  4775. }
  4776. // Make sure, that <li> order matches node.children order.
  4777. childLI = node.ul.firstChild;
  4778. for (i = 0, l = children.length - 1; i < l; i++) {
  4779. childNode1 = children[i];
  4780. childNode2 = childLI.ftnode;
  4781. if (childNode1 === childNode2) {
  4782. childLI = childLI.nextSibling;
  4783. } else {
  4784. // node.debug("_fixOrder: mismatch at index " + i + ": " + childNode1 + " != " + childNode2);
  4785. node.ul.insertBefore(
  4786. childNode1.li,
  4787. childNode2.li
  4788. );
  4789. }
  4790. }
  4791. }
  4792. } else {
  4793. // No children: remove markup if any
  4794. if (node.ul) {
  4795. // alert("remove child markup for " + node);
  4796. this.warn("remove child markup for " + node);
  4797. this.nodeRemoveChildMarkup(ctx);
  4798. }
  4799. }
  4800. if (!isRootNode) {
  4801. // Update element classes according to node state
  4802. // this.nodeRenderStatus(ctx);
  4803. // Finally add the whole structure to the DOM, so the browser can render
  4804. if (firstTime) {
  4805. // #486: successorLi is set, if we re-rendered (i.e. discarded)
  4806. // existing markup, which we want to insert at the same position.
  4807. // (null is equivalent to append)
  4808. // parent.ul.appendChild(node.li);
  4809. parent.ul.insertBefore(node.li, successorLi);
  4810. }
  4811. }
  4812. },
  4813. /** Create HTML inside the node's outer `<span>` (i.e. expander, checkbox,
  4814. * icon, and title).
  4815. *
  4816. * nodeRenderStatus() is implied.
  4817. * @param {EventData} ctx
  4818. * @param {string} [title] optinal new title
  4819. */
  4820. nodeRenderTitle: function (ctx, title) {
  4821. // set node connector images, links and text
  4822. var checkbox,
  4823. className,
  4824. icon,
  4825. nodeTitle,
  4826. role,
  4827. tabindex,
  4828. tooltip,
  4829. iconTooltip,
  4830. node = ctx.node,
  4831. tree = ctx.tree,
  4832. opts = ctx.options,
  4833. aria = opts.aria,
  4834. level = node.getLevel(),
  4835. ares = [];
  4836. if (title !== undefined) {
  4837. node.title = title;
  4838. }
  4839. if (!node.span || tree._enableUpdate === false) {
  4840. // Silently bail out if node was not rendered yet, assuming
  4841. // node.render() will be called as the node becomes visible
  4842. return;
  4843. }
  4844. // Connector (expanded, expandable or simple)
  4845. role =
  4846. aria && node.hasChildren() !== false
  4847. ? " role='button'"
  4848. : "";
  4849. if (level < opts.minExpandLevel) {
  4850. if (!node.lazy) {
  4851. node.expanded = true;
  4852. }
  4853. if (level > 1) {
  4854. ares.push(
  4855. "<span " +
  4856. role +
  4857. " class='fancytree-expander fancytree-expander-fixed'></span>"
  4858. );
  4859. }
  4860. // .. else (i.e. for root level) skip expander/connector alltogether
  4861. } else {
  4862. ares.push(
  4863. "<span " + role + " class='fancytree-expander'></span>"
  4864. );
  4865. }
  4866. // Checkbox mode
  4867. checkbox = FT.evalOption("checkbox", node, node, opts, false);
  4868. if (checkbox && !node.isStatusNode()) {
  4869. role = aria ? " role='checkbox'" : "";
  4870. className = "fancytree-checkbox";
  4871. if (
  4872. checkbox === "radio" ||
  4873. (node.parent && node.parent.radiogroup)
  4874. ) {
  4875. className += " fancytree-radio";
  4876. }
  4877. ares.push(
  4878. "<span " + role + " class='" + className + "'></span>"
  4879. );
  4880. }
  4881. // Folder or doctype icon
  4882. if (node.data.iconClass !== undefined) {
  4883. // 2015-11-16
  4884. // Handle / warn about backward compatibility
  4885. if (node.icon) {
  4886. $.error(
  4887. "'iconClass' node option is deprecated since v2.14.0: use 'icon' only instead"
  4888. );
  4889. } else {
  4890. node.warn(
  4891. "'iconClass' node option is deprecated since v2.14.0: use 'icon' instead"
  4892. );
  4893. node.icon = node.data.iconClass;
  4894. }
  4895. }
  4896. // If opts.icon is a callback and returns something other than undefined, use that
  4897. // else if node.icon is a boolean or string, use that
  4898. // else if opts.icon is a boolean or string, use that
  4899. // else show standard icon (which may be different for folders or documents)
  4900. icon = FT.evalOption("icon", node, node, opts, true);
  4901. // if( typeof icon !== "boolean" ) {
  4902. // // icon is defined, but not true/false: must be a string
  4903. // icon = "" + icon;
  4904. // }
  4905. if (icon !== false) {
  4906. role = aria ? " role='presentation'" : "";
  4907. iconTooltip = FT.evalOption(
  4908. "iconTooltip",
  4909. node,
  4910. node,
  4911. opts,
  4912. null
  4913. );
  4914. iconTooltip = iconTooltip
  4915. ? " title='" + _escapeTooltip(iconTooltip) + "'"
  4916. : "";
  4917. if (typeof icon === "string") {
  4918. if (TEST_IMG.test(icon)) {
  4919. // node.icon is an image url. Prepend imagePath
  4920. icon =
  4921. icon.charAt(0) === "/"
  4922. ? icon
  4923. : (opts.imagePath || "") + icon;
  4924. ares.push(
  4925. "<img src='" +
  4926. icon +
  4927. "' class='fancytree-icon'" +
  4928. iconTooltip +
  4929. " alt='' />"
  4930. );
  4931. } else {
  4932. ares.push(
  4933. "<span " +
  4934. role +
  4935. " class='fancytree-custom-icon " +
  4936. icon +
  4937. "'" +
  4938. iconTooltip +
  4939. "></span>"
  4940. );
  4941. }
  4942. } else if (icon.text) {
  4943. ares.push(
  4944. "<span " +
  4945. role +
  4946. " class='fancytree-custom-icon " +
  4947. (icon.addClass || "") +
  4948. "'" +
  4949. iconTooltip +
  4950. ">" +
  4951. FT.escapeHtml(icon.text) +
  4952. "</span>"
  4953. );
  4954. } else if (icon.html) {
  4955. ares.push(
  4956. "<span " +
  4957. role +
  4958. " class='fancytree-custom-icon " +
  4959. (icon.addClass || "") +
  4960. "'" +
  4961. iconTooltip +
  4962. ">" +
  4963. icon.html +
  4964. "</span>"
  4965. );
  4966. } else {
  4967. // standard icon: theme css will take care of this
  4968. ares.push(
  4969. "<span " +
  4970. role +
  4971. " class='fancytree-icon'" +
  4972. iconTooltip +
  4973. "></span>"
  4974. );
  4975. }
  4976. }
  4977. // Node title
  4978. nodeTitle = "";
  4979. if (opts.renderTitle) {
  4980. nodeTitle =
  4981. opts.renderTitle.call(
  4982. tree,
  4983. { type: "renderTitle" },
  4984. ctx
  4985. ) || "";
  4986. }
  4987. if (!nodeTitle) {
  4988. tooltip = FT.evalOption("tooltip", node, node, opts, null);
  4989. if (tooltip === true) {
  4990. tooltip = node.title;
  4991. }
  4992. // if( node.tooltip ) {
  4993. // tooltip = node.tooltip;
  4994. // } else if ( opts.tooltip ) {
  4995. // tooltip = opts.tooltip === true ? node.title : opts.tooltip.call(tree, node);
  4996. // }
  4997. tooltip = tooltip
  4998. ? " title='" + _escapeTooltip(tooltip) + "'"
  4999. : "";
  5000. tabindex = opts.titlesTabbable ? " tabindex='0'" : "";
  5001. nodeTitle =
  5002. "<span class='fancytree-title'" +
  5003. tooltip +
  5004. tabindex +
  5005. ">" +
  5006. (opts.escapeTitles
  5007. ? FT.escapeHtml(node.title)
  5008. : node.title) +
  5009. "</span>";
  5010. }
  5011. ares.push(nodeTitle);
  5012. // Note: this will trigger focusout, if node had the focus
  5013. //$(node.span).html(ares.join("")); // it will cleanup the jQuery data currently associated with SPAN (if any), but it executes more slowly
  5014. node.span.innerHTML = ares.join("");
  5015. // Update CSS classes
  5016. this.nodeRenderStatus(ctx);
  5017. if (opts.enhanceTitle) {
  5018. ctx.$title = $(">span.fancytree-title", node.span);
  5019. nodeTitle =
  5020. opts.enhanceTitle.call(
  5021. tree,
  5022. { type: "enhanceTitle" },
  5023. ctx
  5024. ) || "";
  5025. }
  5026. },
  5027. /** Update element classes according to node state.
  5028. * @param {EventData} ctx
  5029. */
  5030. nodeRenderStatus: function (ctx) {
  5031. // Set classes for current status
  5032. var $ariaElem,
  5033. node = ctx.node,
  5034. tree = ctx.tree,
  5035. opts = ctx.options,
  5036. // nodeContainer = node[tree.nodeContainerAttrName],
  5037. hasChildren = node.hasChildren(),
  5038. isLastSib = node.isLastSibling(),
  5039. aria = opts.aria,
  5040. cn = opts._classNames,
  5041. cnList = [],
  5042. statusElem = node[tree.statusClassPropName];
  5043. if (!statusElem || tree._enableUpdate === false) {
  5044. // if this function is called for an unrendered node, ignore it (will be updated on nect render anyway)
  5045. return;
  5046. }
  5047. if (aria) {
  5048. $ariaElem = $(node.tr || node.li);
  5049. }
  5050. // Build a list of class names that we will add to the node <span>
  5051. cnList.push(cn.node);
  5052. if (tree.activeNode === node) {
  5053. cnList.push(cn.active);
  5054. // $(">span.fancytree-title", statusElem).attr("tabindex", "0");
  5055. // tree.$container.removeAttr("tabindex");
  5056. // }else{
  5057. // $(">span.fancytree-title", statusElem).removeAttr("tabindex");
  5058. // tree.$container.attr("tabindex", "0");
  5059. }
  5060. if (tree.focusNode === node) {
  5061. cnList.push(cn.focused);
  5062. }
  5063. if (node.expanded) {
  5064. cnList.push(cn.expanded);
  5065. }
  5066. if (aria) {
  5067. if (hasChildren === false) {
  5068. $ariaElem.removeAttr("aria-expanded");
  5069. } else {
  5070. $ariaElem.attr("aria-expanded", Boolean(node.expanded));
  5071. }
  5072. }
  5073. if (node.folder) {
  5074. cnList.push(cn.folder);
  5075. }
  5076. if (hasChildren !== false) {
  5077. cnList.push(cn.hasChildren);
  5078. }
  5079. // TODO: required?
  5080. if (isLastSib) {
  5081. cnList.push(cn.lastsib);
  5082. }
  5083. if (node.lazy && node.children == null) {
  5084. cnList.push(cn.lazy);
  5085. }
  5086. if (node.partload) {
  5087. cnList.push(cn.partload);
  5088. }
  5089. if (node.partsel) {
  5090. cnList.push(cn.partsel);
  5091. }
  5092. if (FT.evalOption("unselectable", node, node, opts, false)) {
  5093. cnList.push(cn.unselectable);
  5094. }
  5095. if (node._isLoading) {
  5096. cnList.push(cn.loading);
  5097. }
  5098. if (node._error) {
  5099. cnList.push(cn.error);
  5100. }
  5101. if (node.statusNodeType) {
  5102. cnList.push(cn.statusNodePrefix + node.statusNodeType);
  5103. }
  5104. if (node.selected) {
  5105. cnList.push(cn.selected);
  5106. if (aria) {
  5107. $ariaElem.attr("aria-selected", true);
  5108. }
  5109. } else if (aria) {
  5110. $ariaElem.attr("aria-selected", false);
  5111. }
  5112. if (node.extraClasses) {
  5113. cnList.push(node.extraClasses);
  5114. }
  5115. // IE6 doesn't correctly evaluate multiple class names,
  5116. // so we create combined class names that can be used in the CSS
  5117. if (hasChildren === false) {
  5118. cnList.push(
  5119. cn.combinedExpanderPrefix + "n" + (isLastSib ? "l" : "")
  5120. );
  5121. } else {
  5122. cnList.push(
  5123. cn.combinedExpanderPrefix +
  5124. (node.expanded ? "e" : "c") +
  5125. (node.lazy && node.children == null ? "d" : "") +
  5126. (isLastSib ? "l" : "")
  5127. );
  5128. }
  5129. cnList.push(
  5130. cn.combinedIconPrefix +
  5131. (node.expanded ? "e" : "c") +
  5132. (node.folder ? "f" : "")
  5133. );
  5134. // node.span.className = cnList.join(" ");
  5135. statusElem.className = cnList.join(" ");
  5136. // TODO: we should not set this in the <span> tag also, if we set it here:
  5137. // Maybe most (all) of the classes should be set in LI instead of SPAN?
  5138. if (node.li) {
  5139. // #719: we have to consider that there may be already other classes:
  5140. $(node.li).toggleClass(cn.lastsib, isLastSib);
  5141. }
  5142. },
  5143. /** Activate node.
  5144. * flag defaults to true.
  5145. * If flag is true, the node is activated (must be a synchronous operation)
  5146. * If flag is false, the node is deactivated (must be a synchronous operation)
  5147. * @param {EventData} ctx
  5148. * @param {boolean} [flag=true]
  5149. * @param {object} [opts] additional options. Defaults to {noEvents: false, noFocus: false}
  5150. * @returns {$.Promise}
  5151. */
  5152. nodeSetActive: function (ctx, flag, callOpts) {
  5153. // Handle user click / [space] / [enter], according to clickFolderMode.
  5154. callOpts = callOpts || {};
  5155. var subCtx,
  5156. node = ctx.node,
  5157. tree = ctx.tree,
  5158. opts = ctx.options,
  5159. noEvents = callOpts.noEvents === true,
  5160. noFocus = callOpts.noFocus === true,
  5161. scroll = callOpts.scrollIntoView !== false,
  5162. isActive = node === tree.activeNode;
  5163. // flag defaults to true
  5164. flag = flag !== false;
  5165. // node.debug("nodeSetActive", flag);
  5166. if (isActive === flag) {
  5167. // Nothing to do
  5168. return _getResolvedPromise(node);
  5169. }
  5170. // #1042: don't scroll between mousedown/-up when clicking an embedded link
  5171. if (
  5172. scroll &&
  5173. ctx.originalEvent &&
  5174. $(ctx.originalEvent.target).is("a,:checkbox")
  5175. ) {
  5176. node.info("Not scrolling while clicking an embedded link.");
  5177. scroll = false;
  5178. }
  5179. if (
  5180. flag &&
  5181. !noEvents &&
  5182. this._triggerNodeEvent(
  5183. "beforeActivate",
  5184. node,
  5185. ctx.originalEvent
  5186. ) === false
  5187. ) {
  5188. // Callback returned false
  5189. return _getRejectedPromise(node, ["rejected"]);
  5190. }
  5191. if (flag) {
  5192. if (tree.activeNode) {
  5193. _assert(
  5194. tree.activeNode !== node,
  5195. "node was active (inconsistency)"
  5196. );
  5197. subCtx = $.extend({}, ctx, { node: tree.activeNode });
  5198. tree.nodeSetActive(subCtx, false);
  5199. _assert(
  5200. tree.activeNode === null,
  5201. "deactivate was out of sync?"
  5202. );
  5203. }
  5204. if (opts.activeVisible) {
  5205. // If no focus is set (noFocus: true) and there is no focused node, this node is made visible.
  5206. // scroll = noFocus && tree.focusNode == null;
  5207. // #863: scroll by default (unless `scrollIntoView: false` was passed)
  5208. node.makeVisible({ scrollIntoView: scroll });
  5209. }
  5210. tree.activeNode = node;
  5211. tree.nodeRenderStatus(ctx);
  5212. if (!noFocus) {
  5213. tree.nodeSetFocus(ctx);
  5214. }
  5215. if (!noEvents) {
  5216. tree._triggerNodeEvent(
  5217. "activate",
  5218. node,
  5219. ctx.originalEvent
  5220. );
  5221. }
  5222. } else {
  5223. _assert(
  5224. tree.activeNode === node,
  5225. "node was not active (inconsistency)"
  5226. );
  5227. tree.activeNode = null;
  5228. this.nodeRenderStatus(ctx);
  5229. if (!noEvents) {
  5230. ctx.tree._triggerNodeEvent(
  5231. "deactivate",
  5232. node,
  5233. ctx.originalEvent
  5234. );
  5235. }
  5236. }
  5237. return _getResolvedPromise(node);
  5238. },
  5239. /** Expand or collapse node, return Deferred.promise.
  5240. *
  5241. * @param {EventData} ctx
  5242. * @param {boolean} [flag=true]
  5243. * @param {object} [opts] additional options. Defaults to `{noAnimation: false, noEvents: false}`
  5244. * @returns {$.Promise} The deferred will be resolved as soon as the (lazy)
  5245. * data was retrieved, rendered, and the expand animation finished.
  5246. */
  5247. nodeSetExpanded: function (ctx, flag, callOpts) {
  5248. callOpts = callOpts || {};
  5249. var _afterLoad,
  5250. dfd,
  5251. i,
  5252. l,
  5253. parents,
  5254. prevAC,
  5255. node = ctx.node,
  5256. tree = ctx.tree,
  5257. opts = ctx.options,
  5258. noAnimation = callOpts.noAnimation === true,
  5259. noEvents = callOpts.noEvents === true;
  5260. // flag defaults to true
  5261. flag = flag !== false;
  5262. // node.debug("nodeSetExpanded(" + flag + ")");
  5263. if ($(node.li).hasClass(opts._classNames.animating)) {
  5264. node.warn(
  5265. "setExpanded(" + flag + ") while animating: ignored."
  5266. );
  5267. return _getRejectedPromise(node, ["recursion"]);
  5268. }
  5269. if ((node.expanded && flag) || (!node.expanded && !flag)) {
  5270. // Nothing to do
  5271. // node.debug("nodeSetExpanded(" + flag + "): nothing to do");
  5272. return _getResolvedPromise(node);
  5273. } else if (flag && !node.lazy && !node.hasChildren()) {
  5274. // Prevent expanding of empty nodes
  5275. // return _getRejectedPromise(node, ["empty"]);
  5276. return _getResolvedPromise(node);
  5277. } else if (!flag && node.getLevel() < opts.minExpandLevel) {
  5278. // Prevent collapsing locked levels
  5279. return _getRejectedPromise(node, ["locked"]);
  5280. } else if (
  5281. !noEvents &&
  5282. this._triggerNodeEvent(
  5283. "beforeExpand",
  5284. node,
  5285. ctx.originalEvent
  5286. ) === false
  5287. ) {
  5288. // Callback returned false
  5289. return _getRejectedPromise(node, ["rejected"]);
  5290. }
  5291. // If this node inside a collpased node, no animation and scrolling is needed
  5292. if (!noAnimation && !node.isVisible()) {
  5293. noAnimation = callOpts.noAnimation = true;
  5294. }
  5295. dfd = new $.Deferred();
  5296. // Auto-collapse mode: collapse all siblings
  5297. if (flag && !node.expanded && opts.autoCollapse) {
  5298. parents = node.getParentList(false, true);
  5299. prevAC = opts.autoCollapse;
  5300. try {
  5301. opts.autoCollapse = false;
  5302. for (i = 0, l = parents.length; i < l; i++) {
  5303. // TODO: should return promise?
  5304. this._callHook(
  5305. "nodeCollapseSiblings",
  5306. parents[i],
  5307. callOpts
  5308. );
  5309. }
  5310. } finally {
  5311. opts.autoCollapse = prevAC;
  5312. }
  5313. }
  5314. // Trigger expand/collapse after expanding
  5315. dfd.done(function () {
  5316. var lastChild = node.getLastChild();
  5317. if (
  5318. flag &&
  5319. opts.autoScroll &&
  5320. !noAnimation &&
  5321. lastChild &&
  5322. tree._enableUpdate
  5323. ) {
  5324. // Scroll down to last child, but keep current node visible
  5325. lastChild
  5326. .scrollIntoView(true, { topNode: node })
  5327. .always(function () {
  5328. if (!noEvents) {
  5329. ctx.tree._triggerNodeEvent(
  5330. flag ? "expand" : "collapse",
  5331. ctx
  5332. );
  5333. }
  5334. });
  5335. } else {
  5336. if (!noEvents) {
  5337. ctx.tree._triggerNodeEvent(
  5338. flag ? "expand" : "collapse",
  5339. ctx
  5340. );
  5341. }
  5342. }
  5343. });
  5344. // vvv Code below is executed after loading finished:
  5345. _afterLoad = function (callback) {
  5346. var cn = opts._classNames,
  5347. isVisible,
  5348. isExpanded,
  5349. effect = opts.toggleEffect;
  5350. node.expanded = flag;
  5351. tree._callHook(
  5352. "treeStructureChanged",
  5353. ctx,
  5354. flag ? "expand" : "collapse"
  5355. );
  5356. // Create required markup, but make sure the top UL is hidden, so we
  5357. // can animate later
  5358. tree._callHook("nodeRender", ctx, false, false, true);
  5359. // Hide children, if node is collapsed
  5360. if (node.ul) {
  5361. isVisible = node.ul.style.display !== "none";
  5362. isExpanded = !!node.expanded;
  5363. if (isVisible === isExpanded) {
  5364. node.warn(
  5365. "nodeSetExpanded: UL.style.display already set"
  5366. );
  5367. } else if (!effect || noAnimation) {
  5368. node.ul.style.display =
  5369. node.expanded || !parent ? "" : "none";
  5370. } else {
  5371. // The UI toggle() effect works with the ext-wide extension,
  5372. // while jQuery.animate() has problems when the title span
  5373. // has position: absolute.
  5374. // Since jQuery UI 1.12, the blind effect requires the parent
  5375. // element to have 'position: relative'.
  5376. // See #716, #717
  5377. $(node.li).addClass(cn.animating); // #717
  5378. if (_isFunction($(node.ul)[effect.effect])) {
  5379. // tree.debug( "use jquery." + effect.effect + " method" );
  5380. $(node.ul)[effect.effect]({
  5381. duration: effect.duration,
  5382. always: function () {
  5383. // node.debug("fancytree-animating end: " + node.li.className);
  5384. $(this).removeClass(cn.animating); // #716
  5385. $(node.li).removeClass(cn.animating); // #717
  5386. callback();
  5387. },
  5388. });
  5389. } else {
  5390. // The UI toggle() effect works with the ext-wide extension,
  5391. // while jQuery.animate() has problems when the title span
  5392. // has positon: absolute.
  5393. // Since jQuery UI 1.12, the blind effect requires the parent
  5394. // element to have 'position: relative'.
  5395. // See #716, #717
  5396. // tree.debug("use specified effect (" + effect.effect + ") with the jqueryui.toggle method");
  5397. // try to stop an animation that might be already in progress
  5398. $(node.ul).stop(true, true); //< does not work after resetLazy has been called for a node whose animation wasn't complete and effect was "blind"
  5399. // dirty fix to remove a defunct animation (effect: "blind") after resetLazy has been called
  5400. $(node.ul)
  5401. .parent()
  5402. .find(".ui-effects-placeholder")
  5403. .remove();
  5404. $(node.ul).toggle(
  5405. effect.effect,
  5406. effect.options,
  5407. effect.duration,
  5408. function () {
  5409. // node.debug("fancytree-animating end: " + node.li.className);
  5410. $(this).removeClass(cn.animating); // #716
  5411. $(node.li).removeClass(cn.animating); // #717
  5412. callback();
  5413. }
  5414. );
  5415. }
  5416. return;
  5417. }
  5418. }
  5419. callback();
  5420. };
  5421. // ^^^ Code above is executed after loading finshed.
  5422. // Load lazy nodes, if any. Then continue with _afterLoad()
  5423. if (flag && node.lazy && node.hasChildren() === undefined) {
  5424. // node.debug("nodeSetExpanded: load start...");
  5425. node.load()
  5426. .done(function () {
  5427. // node.debug("nodeSetExpanded: load done");
  5428. if (dfd.notifyWith) {
  5429. // requires jQuery 1.6+
  5430. dfd.notifyWith(node, ["loaded"]);
  5431. }
  5432. _afterLoad(function () {
  5433. dfd.resolveWith(node);
  5434. });
  5435. })
  5436. .fail(function (errMsg) {
  5437. _afterLoad(function () {
  5438. dfd.rejectWith(node, [
  5439. "load failed (" + errMsg + ")",
  5440. ]);
  5441. });
  5442. });
  5443. /*
  5444. var source = tree._triggerNodeEvent("lazyLoad", node, ctx.originalEvent);
  5445. _assert(typeof source !== "boolean", "lazyLoad event must return source in data.result");
  5446. node.debug("nodeSetExpanded: load start...");
  5447. this._callHook("nodeLoadChildren", ctx, source).done(function(){
  5448. node.debug("nodeSetExpanded: load done");
  5449. if(dfd.notifyWith){ // requires jQuery 1.6+
  5450. dfd.notifyWith(node, ["loaded"]);
  5451. }
  5452. _afterLoad.call(tree);
  5453. }).fail(function(errMsg){
  5454. dfd.rejectWith(node, ["load failed (" + errMsg + ")"]);
  5455. });
  5456. */
  5457. } else {
  5458. _afterLoad(function () {
  5459. dfd.resolveWith(node);
  5460. });
  5461. }
  5462. // node.debug("nodeSetExpanded: returns");
  5463. return dfd.promise();
  5464. },
  5465. /** Focus or blur this node.
  5466. * @param {EventData} ctx
  5467. * @param {boolean} [flag=true]
  5468. */
  5469. nodeSetFocus: function (ctx, flag) {
  5470. // ctx.node.debug("nodeSetFocus(" + flag + ")");
  5471. var ctx2,
  5472. tree = ctx.tree,
  5473. node = ctx.node,
  5474. opts = tree.options,
  5475. // et = ctx.originalEvent && ctx.originalEvent.type,
  5476. isInput = ctx.originalEvent
  5477. ? $(ctx.originalEvent.target).is(":input")
  5478. : false;
  5479. flag = flag !== false;
  5480. // (node || tree).debug("nodeSetFocus(" + flag + "), event: " + et + ", isInput: "+ isInput);
  5481. // Blur previous node if any
  5482. if (tree.focusNode) {
  5483. if (tree.focusNode === node && flag) {
  5484. // node.debug("nodeSetFocus(" + flag + "): nothing to do");
  5485. return;
  5486. }
  5487. ctx2 = $.extend({}, ctx, { node: tree.focusNode });
  5488. tree.focusNode = null;
  5489. this._triggerNodeEvent("blur", ctx2);
  5490. this._callHook("nodeRenderStatus", ctx2);
  5491. }
  5492. // Set focus to container and node
  5493. if (flag) {
  5494. if (!this.hasFocus()) {
  5495. node.debug("nodeSetFocus: forcing container focus");
  5496. this._callHook("treeSetFocus", ctx, true, {
  5497. calledByNode: true,
  5498. });
  5499. }
  5500. node.makeVisible({ scrollIntoView: false });
  5501. tree.focusNode = node;
  5502. if (opts.titlesTabbable) {
  5503. if (!isInput) {
  5504. // #621
  5505. $(node.span).find(".fancytree-title").focus();
  5506. }
  5507. }
  5508. if (opts.aria) {
  5509. // Set active descendant to node's span ID (create one, if needed)
  5510. $(tree.$container).attr(
  5511. "aria-activedescendant",
  5512. $(node.tr || node.li)
  5513. .uniqueId()
  5514. .attr("id")
  5515. );
  5516. // "ftal_" + opts.idPrefix + node.key);
  5517. }
  5518. // $(node.span).find(".fancytree-title").focus();
  5519. this._triggerNodeEvent("focus", ctx);
  5520. // determine if we have focus on or inside tree container
  5521. var hasFancytreeFocus =
  5522. document.activeElement === tree.$container.get(0) ||
  5523. $(document.activeElement, tree.$container).length >= 1;
  5524. if (!hasFancytreeFocus) {
  5525. // We cannot set KB focus to a node, so use the tree container
  5526. // #563, #570: IE scrolls on every call to .focus(), if the container
  5527. // is partially outside the viewport. So do it only, when absolutely
  5528. // necessary.
  5529. $(tree.$container).focus();
  5530. }
  5531. // if( opts.autoActivate ){
  5532. // tree.nodeSetActive(ctx, true);
  5533. // }
  5534. if (opts.autoScroll) {
  5535. node.scrollIntoView();
  5536. }
  5537. this._callHook("nodeRenderStatus", ctx);
  5538. }
  5539. },
  5540. /** (De)Select node, return new status (sync).
  5541. *
  5542. * @param {EventData} ctx
  5543. * @param {boolean} [flag=true]
  5544. * @param {object} [opts] additional options. Defaults to {noEvents: false,
  5545. * propagateDown: null, propagateUp: null,
  5546. * callback: null,
  5547. * }
  5548. * @returns {boolean} previous status
  5549. */
  5550. nodeSetSelected: function (ctx, flag, callOpts) {
  5551. callOpts = callOpts || {};
  5552. var node = ctx.node,
  5553. tree = ctx.tree,
  5554. opts = ctx.options,
  5555. noEvents = callOpts.noEvents === true,
  5556. parent = node.parent;
  5557. // flag defaults to true
  5558. flag = flag !== false;
  5559. // node.debug("nodeSetSelected(" + flag + ")", ctx);
  5560. // Cannot (de)select unselectable nodes directly (only by propagation or
  5561. // by setting the `.selected` property)
  5562. if (FT.evalOption("unselectable", node, node, opts, false)) {
  5563. return;
  5564. }
  5565. // Remember the user's intent, in case down -> up propagation prevents
  5566. // applying it to node.selected
  5567. node._lastSelectIntent = flag; // Confusing use of '!'
  5568. // Nothing to do?
  5569. if (!!node.selected === flag) {
  5570. if (opts.selectMode === 3 && node.partsel && !flag) {
  5571. // If propagation prevented selecting this node last time, we still
  5572. // want to allow to apply setSelected(false) now
  5573. } else {
  5574. return flag;
  5575. }
  5576. }
  5577. if (
  5578. !noEvents &&
  5579. this._triggerNodeEvent(
  5580. "beforeSelect",
  5581. node,
  5582. ctx.originalEvent
  5583. ) === false
  5584. ) {
  5585. return !!node.selected;
  5586. }
  5587. if (flag && opts.selectMode === 1) {
  5588. // single selection mode (we don't uncheck all tree nodes, for performance reasons)
  5589. if (tree.lastSelectedNode) {
  5590. tree.lastSelectedNode.setSelected(false);
  5591. }
  5592. node.selected = flag;
  5593. } else if (
  5594. opts.selectMode === 3 &&
  5595. parent &&
  5596. !parent.radiogroup &&
  5597. !node.radiogroup
  5598. ) {
  5599. // multi-hierarchical selection mode
  5600. node.selected = flag;
  5601. node.fixSelection3AfterClick(callOpts);
  5602. } else if (parent && parent.radiogroup) {
  5603. node.visitSiblings(function (n) {
  5604. n._changeSelectStatusAttrs(flag && n === node);
  5605. }, true);
  5606. } else {
  5607. // default: selectMode: 2, multi selection mode
  5608. node.selected = flag;
  5609. }
  5610. this.nodeRenderStatus(ctx);
  5611. tree.lastSelectedNode = flag ? node : null;
  5612. if (!noEvents) {
  5613. tree._triggerNodeEvent("select", ctx);
  5614. }
  5615. },
  5616. /** Show node status (ok, loading, error, nodata) using styles and a dummy child node.
  5617. *
  5618. * @param {EventData} ctx
  5619. * @param status
  5620. * @param message
  5621. * @param details
  5622. * @since 2.3
  5623. */
  5624. nodeSetStatus: function (ctx, status, message, details) {
  5625. var node = ctx.node,
  5626. tree = ctx.tree;
  5627. function _clearStatusNode() {
  5628. // Remove dedicated dummy node, if any
  5629. var firstChild = node.children ? node.children[0] : null;
  5630. if (firstChild && firstChild.isStatusNode()) {
  5631. try {
  5632. // I've seen exceptions here with loadKeyPath...
  5633. if (node.ul) {
  5634. node.ul.removeChild(firstChild.li);
  5635. firstChild.li = null; // avoid leaks (DT issue 215)
  5636. }
  5637. } catch (e) {}
  5638. if (node.children.length === 1) {
  5639. node.children = [];
  5640. } else {
  5641. node.children.shift();
  5642. }
  5643. tree._callHook(
  5644. "treeStructureChanged",
  5645. ctx,
  5646. "clearStatusNode"
  5647. );
  5648. }
  5649. }
  5650. function _setStatusNode(data, type) {
  5651. // Create/modify the dedicated dummy node for 'loading...' or
  5652. // 'error!' status. (only called for direct child of the invisible
  5653. // system root)
  5654. var firstChild = node.children ? node.children[0] : null;
  5655. if (firstChild && firstChild.isStatusNode()) {
  5656. $.extend(firstChild, data);
  5657. firstChild.statusNodeType = type;
  5658. tree._callHook("nodeRenderTitle", firstChild);
  5659. } else {
  5660. node._setChildren([data]);
  5661. tree._callHook(
  5662. "treeStructureChanged",
  5663. ctx,
  5664. "setStatusNode"
  5665. );
  5666. node.children[0].statusNodeType = type;
  5667. tree.render();
  5668. }
  5669. return node.children[0];
  5670. }
  5671. switch (status) {
  5672. case "ok":
  5673. _clearStatusNode();
  5674. node._isLoading = false;
  5675. node._error = null;
  5676. node.renderStatus();
  5677. break;
  5678. case "loading":
  5679. if (!node.parent) {
  5680. _setStatusNode(
  5681. {
  5682. title:
  5683. tree.options.strings.loading +
  5684. (message ? " (" + message + ")" : ""),
  5685. // icon: true, // needed for 'loding' icon
  5686. checkbox: false,
  5687. tooltip: details,
  5688. },
  5689. status
  5690. );
  5691. }
  5692. node._isLoading = true;
  5693. node._error = null;
  5694. node.renderStatus();
  5695. break;
  5696. case "error":
  5697. _setStatusNode(
  5698. {
  5699. title:
  5700. tree.options.strings.loadError +
  5701. (message ? " (" + message + ")" : ""),
  5702. // icon: false,
  5703. checkbox: false,
  5704. tooltip: details,
  5705. },
  5706. status
  5707. );
  5708. node._isLoading = false;
  5709. node._error = { message: message, details: details };
  5710. node.renderStatus();
  5711. break;
  5712. case "nodata":
  5713. _setStatusNode(
  5714. {
  5715. title: message || tree.options.strings.noData,
  5716. // icon: false,
  5717. checkbox: false,
  5718. tooltip: details,
  5719. },
  5720. status
  5721. );
  5722. node._isLoading = false;
  5723. node._error = null;
  5724. node.renderStatus();
  5725. break;
  5726. default:
  5727. $.error("invalid node status " + status);
  5728. }
  5729. },
  5730. /**
  5731. *
  5732. * @param {EventData} ctx
  5733. */
  5734. nodeToggleExpanded: function (ctx) {
  5735. return this.nodeSetExpanded(ctx, !ctx.node.expanded);
  5736. },
  5737. /**
  5738. * @param {EventData} ctx
  5739. */
  5740. nodeToggleSelected: function (ctx) {
  5741. var node = ctx.node,
  5742. flag = !node.selected;
  5743. // In selectMode: 3 this node may be unselected+partsel, even if
  5744. // setSelected(true) was called before, due to `unselectable` children.
  5745. // In this case, we now toggle as `setSelected(false)`
  5746. if (
  5747. node.partsel &&
  5748. !node.selected &&
  5749. node._lastSelectIntent === true
  5750. ) {
  5751. flag = false;
  5752. node.selected = true; // so it is not considered 'nothing to do'
  5753. }
  5754. node._lastSelectIntent = flag;
  5755. return this.nodeSetSelected(ctx, flag);
  5756. },
  5757. /** Remove all nodes.
  5758. * @param {EventData} ctx
  5759. */
  5760. treeClear: function (ctx) {
  5761. var tree = ctx.tree;
  5762. tree.activeNode = null;
  5763. tree.focusNode = null;
  5764. tree.$div.find(">ul.fancytree-container").empty();
  5765. // TODO: call destructors and remove reference loops
  5766. tree.rootNode.children = null;
  5767. tree._callHook("treeStructureChanged", ctx, "clear");
  5768. },
  5769. /** Widget was created (called only once, even it re-initialized).
  5770. * @param {EventData} ctx
  5771. */
  5772. treeCreate: function (ctx) {},
  5773. /** Widget was destroyed.
  5774. * @param {EventData} ctx
  5775. */
  5776. treeDestroy: function (ctx) {
  5777. this.$div.find(">ul.fancytree-container").remove();
  5778. if (this.$source) {
  5779. this.$source.removeClass("fancytree-helper-hidden");
  5780. }
  5781. },
  5782. /** Widget was (re-)initialized.
  5783. * @param {EventData} ctx
  5784. */
  5785. treeInit: function (ctx) {
  5786. var tree = ctx.tree,
  5787. opts = tree.options;
  5788. //this.debug("Fancytree.treeInit()");
  5789. // Add container to the TAB chain
  5790. // See http://www.w3.org/TR/wai-aria-practices/#focus_activedescendant
  5791. // #577: Allow to set tabindex to "0", "-1" and ""
  5792. tree.$container.attr("tabindex", opts.tabindex);
  5793. // Copy some attributes to tree.data
  5794. $.each(TREE_ATTRS, function (i, attr) {
  5795. if (opts[attr] !== undefined) {
  5796. tree.info("Move option " + attr + " to tree");
  5797. tree[attr] = opts[attr];
  5798. delete opts[attr];
  5799. }
  5800. });
  5801. if (opts.checkboxAutoHide) {
  5802. tree.$container.addClass("fancytree-checkbox-auto-hide");
  5803. }
  5804. if (opts.rtl) {
  5805. tree.$container
  5806. .attr("DIR", "RTL")
  5807. .addClass("fancytree-rtl");
  5808. } else {
  5809. tree.$container
  5810. .removeAttr("DIR")
  5811. .removeClass("fancytree-rtl");
  5812. }
  5813. if (opts.aria) {
  5814. tree.$container.attr("role", "tree");
  5815. if (opts.selectMode !== 1) {
  5816. tree.$container.attr("aria-multiselectable", true);
  5817. }
  5818. }
  5819. this.treeLoad(ctx);
  5820. },
  5821. /** Parse Fancytree from source, as configured in the options.
  5822. * @param {EventData} ctx
  5823. * @param {object} [source] optional new source (use last data otherwise)
  5824. */
  5825. treeLoad: function (ctx, source) {
  5826. var metaData,
  5827. type,
  5828. $ul,
  5829. tree = ctx.tree,
  5830. $container = ctx.widget.element,
  5831. dfd,
  5832. // calling context for root node
  5833. rootCtx = $.extend({}, ctx, { node: this.rootNode });
  5834. if (tree.rootNode.children) {
  5835. this.treeClear(ctx);
  5836. }
  5837. source = source || this.options.source;
  5838. if (!source) {
  5839. type = $container.data("type") || "html";
  5840. switch (type) {
  5841. case "html":
  5842. // There should be an embedded `<ul>` with initial nodes,
  5843. // but another `<ul class='fancytree-container'>` is appended
  5844. // to the tree's <div> on startup anyway.
  5845. $ul = $container
  5846. .find(">ul")
  5847. .not(".fancytree-container")
  5848. .first();
  5849. if ($ul.length) {
  5850. $ul.addClass(
  5851. "ui-fancytree-source fancytree-helper-hidden"
  5852. );
  5853. source = $.ui.fancytree.parseHtml($ul);
  5854. // allow to init tree.data.foo from <ul data-foo=''>
  5855. this.data = $.extend(
  5856. this.data,
  5857. _getElementDataAsDict($ul)
  5858. );
  5859. } else {
  5860. FT.warn(
  5861. "No `source` option was passed and container does not contain `<ul>`: assuming `source: []`."
  5862. );
  5863. source = [];
  5864. }
  5865. break;
  5866. case "json":
  5867. source = $.parseJSON($container.text());
  5868. // $container already contains the <ul>, but we remove the plain (json) text
  5869. // $container.empty();
  5870. $container
  5871. .contents()
  5872. .filter(function () {
  5873. return this.nodeType === 3;
  5874. })
  5875. .remove();
  5876. if ($.isPlainObject(source)) {
  5877. // We got {foo: 'abc', children: [...]}
  5878. _assert(
  5879. _isArray(source.children),
  5880. "if an object is passed as source, it must contain a 'children' array (all other properties are added to 'tree.data')"
  5881. );
  5882. metaData = source;
  5883. source = source.children;
  5884. delete metaData.children;
  5885. // Copy some attributes to tree.data
  5886. $.each(TREE_ATTRS, function (i, attr) {
  5887. if (metaData[attr] !== undefined) {
  5888. tree[attr] = metaData[attr];
  5889. delete metaData[attr];
  5890. }
  5891. });
  5892. // Copy extra properties to tree.data.foo
  5893. $.extend(tree.data, metaData);
  5894. }
  5895. break;
  5896. default:
  5897. $.error("Invalid data-type: " + type);
  5898. }
  5899. } else if (typeof source === "string") {
  5900. // TODO: source is an element ID
  5901. $.error("Not implemented");
  5902. }
  5903. // preInit is fired when the widget markup is created, but nodes
  5904. // not yet loaded
  5905. tree._triggerTreeEvent("preInit", null);
  5906. // Trigger fancytreeinit after nodes have been loaded
  5907. dfd = this.nodeLoadChildren(rootCtx, source)
  5908. .done(function () {
  5909. tree._callHook(
  5910. "treeStructureChanged",
  5911. ctx,
  5912. "loadChildren"
  5913. );
  5914. tree.render();
  5915. if (ctx.options.selectMode === 3) {
  5916. tree.rootNode.fixSelection3FromEndNodes();
  5917. }
  5918. if (tree.activeNode && tree.options.activeVisible) {
  5919. tree.activeNode.makeVisible();
  5920. }
  5921. tree._triggerTreeEvent("init", null, { status: true });
  5922. })
  5923. .fail(function () {
  5924. tree.render();
  5925. tree._triggerTreeEvent("init", null, { status: false });
  5926. });
  5927. return dfd;
  5928. },
  5929. /** Node was inserted into or removed from the tree.
  5930. * @param {EventData} ctx
  5931. * @param {boolean} add
  5932. * @param {FancytreeNode} node
  5933. */
  5934. treeRegisterNode: function (ctx, add, node) {
  5935. ctx.tree._callHook(
  5936. "treeStructureChanged",
  5937. ctx,
  5938. add ? "addNode" : "removeNode"
  5939. );
  5940. },
  5941. /** Widget got focus.
  5942. * @param {EventData} ctx
  5943. * @param {boolean} [flag=true]
  5944. */
  5945. treeSetFocus: function (ctx, flag, callOpts) {
  5946. var targetNode;
  5947. flag = flag !== false;
  5948. // this.debug("treeSetFocus(" + flag + "), callOpts: ", callOpts, this.hasFocus());
  5949. // this.debug(" focusNode: " + this.focusNode);
  5950. // this.debug(" activeNode: " + this.activeNode);
  5951. if (flag !== this.hasFocus()) {
  5952. this._hasFocus = flag;
  5953. if (!flag && this.focusNode) {
  5954. // Node also looses focus if widget blurs
  5955. this.focusNode.setFocus(false);
  5956. } else if (flag && (!callOpts || !callOpts.calledByNode)) {
  5957. $(this.$container).focus();
  5958. }
  5959. this.$container.toggleClass("fancytree-treefocus", flag);
  5960. this._triggerTreeEvent(flag ? "focusTree" : "blurTree");
  5961. if (flag && !this.activeNode) {
  5962. // #712: Use last mousedowned node ('click' event fires after focusin)
  5963. targetNode =
  5964. this._lastMousedownNode || this.getFirstChild();
  5965. if (targetNode) {
  5966. targetNode.setFocus();
  5967. }
  5968. }
  5969. }
  5970. },
  5971. /** Widget option was set using `$().fancytree("option", "KEY", VALUE)`.
  5972. *
  5973. * Note: `key` may reference a nested option, e.g. 'dnd5.scroll'.
  5974. * In this case `value`contains the complete, modified `dnd5` option hash.
  5975. * We can check for changed values like
  5976. * if( value.scroll !== tree.options.dnd5.scroll ) {...}
  5977. *
  5978. * @param {EventData} ctx
  5979. * @param {string} key option name
  5980. * @param {any} value option value
  5981. */
  5982. treeSetOption: function (ctx, key, value) {
  5983. var tree = ctx.tree,
  5984. callDefault = true,
  5985. callCreate = false,
  5986. callRender = false;
  5987. switch (key) {
  5988. case "aria":
  5989. case "checkbox":
  5990. case "icon":
  5991. case "minExpandLevel":
  5992. case "tabindex":
  5993. // tree._callHook("treeCreate", tree);
  5994. callCreate = true;
  5995. callRender = true;
  5996. break;
  5997. case "checkboxAutoHide":
  5998. tree.$container.toggleClass(
  5999. "fancytree-checkbox-auto-hide",
  6000. !!value
  6001. );
  6002. break;
  6003. case "escapeTitles":
  6004. case "tooltip":
  6005. callRender = true;
  6006. break;
  6007. case "rtl":
  6008. if (value === false) {
  6009. tree.$container
  6010. .removeAttr("DIR")
  6011. .removeClass("fancytree-rtl");
  6012. } else {
  6013. tree.$container
  6014. .attr("DIR", "RTL")
  6015. .addClass("fancytree-rtl");
  6016. }
  6017. callRender = true;
  6018. break;
  6019. case "source":
  6020. callDefault = false;
  6021. tree._callHook("treeLoad", tree, value);
  6022. callRender = true;
  6023. break;
  6024. }
  6025. tree.debug(
  6026. "set option " +
  6027. key +
  6028. "=" +
  6029. value +
  6030. " <" +
  6031. typeof value +
  6032. ">"
  6033. );
  6034. if (callDefault) {
  6035. if (this.widget._super) {
  6036. // jQuery UI 1.9+
  6037. this.widget._super.call(this.widget, key, value);
  6038. } else {
  6039. // jQuery UI <= 1.8, we have to manually invoke the _setOption method from the base widget
  6040. $.Widget.prototype._setOption.call(
  6041. this.widget,
  6042. key,
  6043. value
  6044. );
  6045. }
  6046. }
  6047. if (callCreate) {
  6048. tree._callHook("treeCreate", tree);
  6049. }
  6050. if (callRender) {
  6051. tree.render(true, false); // force, not-deep
  6052. }
  6053. },
  6054. /** A Node was added, removed, moved, or it's visibility changed.
  6055. * @param {EventData} ctx
  6056. */
  6057. treeStructureChanged: function (ctx, type) {},
  6058. }
  6059. );
  6060. /*******************************************************************************
  6061. * jQuery UI widget boilerplate
  6062. */
  6063. /**
  6064. * The plugin (derrived from [jQuery.Widget](http://api.jqueryui.com/jQuery.widget/)).
  6065. *
  6066. * **Note:**
  6067. * These methods implement the standard jQuery UI widget API.
  6068. * It is recommended to use methods of the {Fancytree} instance instead
  6069. *
  6070. * @example
  6071. * // DEPRECATED: Access jQuery UI widget methods and members:
  6072. * var tree = $("#tree").fancytree("getTree");
  6073. * var node = $("#tree").fancytree("getActiveNode");
  6074. *
  6075. * // RECOMMENDED: Use the Fancytree object API
  6076. * var tree = $.ui.fancytree.getTree("#tree");
  6077. * var node = tree.getActiveNode();
  6078. *
  6079. * // or you may already have stored the tree instance upon creation:
  6080. * import {createTree, version} from 'jquery.fancytree'
  6081. * const tree = createTree('#tree', { ... });
  6082. * var node = tree.getActiveNode();
  6083. *
  6084. * @see {Fancytree_Static#getTree}
  6085. * @deprecated Use methods of the {Fancytree} instance instead
  6086. * @mixin Fancytree_Widget
  6087. */
  6088. $.widget(
  6089. "ui.fancytree",
  6090. /** @lends Fancytree_Widget# */
  6091. {
  6092. /**These options will be used as defaults
  6093. * @type {FancytreeOptions}
  6094. */
  6095. options: {
  6096. activeVisible: true,
  6097. ajax: {
  6098. type: "GET",
  6099. cache: false, // false: Append random '_' argument to the request url to prevent caching.
  6100. // timeout: 0, // >0: Make sure we get an ajax error if server is unreachable
  6101. dataType: "json", // Expect json format and pass json object to callbacks.
  6102. },
  6103. aria: true,
  6104. autoActivate: true,
  6105. autoCollapse: false,
  6106. autoScroll: false,
  6107. checkbox: false,
  6108. clickFolderMode: 4,
  6109. copyFunctionsToData: false,
  6110. debugLevel: null, // 0..4 (null: use global setting $.ui.fancytree.debugLevel)
  6111. disabled: false, // TODO: required anymore?
  6112. enableAspx: 42, // TODO: this is truethy, but distinguishable from true: default will change to false in the future
  6113. escapeTitles: false,
  6114. extensions: [],
  6115. focusOnSelect: false,
  6116. generateIds: false,
  6117. icon: true,
  6118. idPrefix: "ft_",
  6119. keyboard: true,
  6120. keyPathSeparator: "/",
  6121. minExpandLevel: 1,
  6122. nodata: true, // (bool, string, or callback) display message, when no data available
  6123. quicksearch: false,
  6124. rtl: false,
  6125. scrollOfs: { top: 0, bottom: 0 },
  6126. scrollParent: null,
  6127. selectMode: 2,
  6128. strings: {
  6129. loading: "Loading...", // &#8230; would be escaped when escapeTitles is true
  6130. loadError: "Load error!",
  6131. moreData: "More...",
  6132. noData: "No data.",
  6133. },
  6134. tabindex: "0",
  6135. titlesTabbable: false,
  6136. toggleEffect: { effect: "slideToggle", duration: 200 }, //< "toggle" or "slideToggle" to use jQuery instead of jQueryUI for toggleEffect animation
  6137. tooltip: false,
  6138. treeId: null,
  6139. _classNames: {
  6140. active: "fancytree-active",
  6141. animating: "fancytree-animating",
  6142. combinedExpanderPrefix: "fancytree-exp-",
  6143. combinedIconPrefix: "fancytree-ico-",
  6144. error: "fancytree-error",
  6145. expanded: "fancytree-expanded",
  6146. focused: "fancytree-focused",
  6147. folder: "fancytree-folder",
  6148. hasChildren: "fancytree-has-children",
  6149. lastsib: "fancytree-lastsib",
  6150. lazy: "fancytree-lazy",
  6151. loading: "fancytree-loading",
  6152. node: "fancytree-node",
  6153. partload: "fancytree-partload",
  6154. partsel: "fancytree-partsel",
  6155. radio: "fancytree-radio",
  6156. selected: "fancytree-selected",
  6157. statusNodePrefix: "fancytree-statusnode-",
  6158. unselectable: "fancytree-unselectable",
  6159. },
  6160. // events
  6161. lazyLoad: null,
  6162. postProcess: null,
  6163. },
  6164. _deprecationWarning: function (name) {
  6165. var tree = this.tree;
  6166. if (tree && tree.options.debugLevel >= 3) {
  6167. tree.warn(
  6168. "$().fancytree('" +
  6169. name +
  6170. "') is deprecated (see https://wwwendt.de/tech/fancytree/doc/jsdoc/Fancytree_Widget.html"
  6171. );
  6172. }
  6173. },
  6174. /* Set up the widget, Called on first $().fancytree() */
  6175. _create: function () {
  6176. this.tree = new Fancytree(this);
  6177. this.$source =
  6178. this.source || this.element.data("type") === "json"
  6179. ? this.element
  6180. : this.element.find(">ul").first();
  6181. // Subclass Fancytree instance with all enabled extensions
  6182. var extension,
  6183. extName,
  6184. i,
  6185. opts = this.options,
  6186. extensions = opts.extensions,
  6187. base = this.tree;
  6188. for (i = 0; i < extensions.length; i++) {
  6189. extName = extensions[i];
  6190. extension = $.ui.fancytree._extensions[extName];
  6191. if (!extension) {
  6192. $.error(
  6193. "Could not apply extension '" +
  6194. extName +
  6195. "' (it is not registered, did you forget to include it?)"
  6196. );
  6197. }
  6198. // Add extension options as tree.options.EXTENSION
  6199. // _assert(!this.tree.options[extName], "Extension name must not exist as option name: " + extName);
  6200. // console.info("extend " + extName, extension.options, this.tree.options[extName])
  6201. // issue #876: we want to replace custom array-options, not merge them
  6202. this.tree.options[extName] = _simpleDeepMerge(
  6203. {},
  6204. extension.options,
  6205. this.tree.options[extName]
  6206. );
  6207. // this.tree.options[extName] = $.extend(true, {}, extension.options, this.tree.options[extName]);
  6208. // console.info("extend " + extName + " =>", this.tree.options[extName])
  6209. // console.info("extend " + extName + " org default =>", extension.options)
  6210. // Add a namespace tree.ext.EXTENSION, to hold instance data
  6211. _assert(
  6212. this.tree.ext[extName] === undefined,
  6213. "Extension name must not exist as Fancytree.ext attribute: '" +
  6214. extName +
  6215. "'"
  6216. );
  6217. // this.tree[extName] = extension;
  6218. this.tree.ext[extName] = {};
  6219. // Subclass Fancytree methods using proxies.
  6220. _subclassObject(this.tree, base, extension, extName);
  6221. // current extension becomes base for the next extension
  6222. base = extension;
  6223. }
  6224. //
  6225. if (opts.icons !== undefined) {
  6226. // 2015-11-16
  6227. if (opts.icon === true) {
  6228. this.tree.warn(
  6229. "'icons' tree option is deprecated since v2.14.0: use 'icon' instead"
  6230. );
  6231. opts.icon = opts.icons;
  6232. } else {
  6233. $.error(
  6234. "'icons' tree option is deprecated since v2.14.0: use 'icon' only instead"
  6235. );
  6236. }
  6237. }
  6238. if (opts.iconClass !== undefined) {
  6239. // 2015-11-16
  6240. if (opts.icon) {
  6241. $.error(
  6242. "'iconClass' tree option is deprecated since v2.14.0: use 'icon' only instead"
  6243. );
  6244. } else {
  6245. this.tree.warn(
  6246. "'iconClass' tree option is deprecated since v2.14.0: use 'icon' instead"
  6247. );
  6248. opts.icon = opts.iconClass;
  6249. }
  6250. }
  6251. if (opts.tabbable !== undefined) {
  6252. // 2016-04-04
  6253. opts.tabindex = opts.tabbable ? "0" : "-1";
  6254. this.tree.warn(
  6255. "'tabbable' tree option is deprecated since v2.17.0: use 'tabindex='" +
  6256. opts.tabindex +
  6257. "' instead"
  6258. );
  6259. }
  6260. //
  6261. this.tree._callHook("treeCreate", this.tree);
  6262. // Note: 'fancytreecreate' event is fired by widget base class
  6263. // this.tree._triggerTreeEvent("create");
  6264. },
  6265. /* Called on every $().fancytree() */
  6266. _init: function () {
  6267. this.tree._callHook("treeInit", this.tree);
  6268. // TODO: currently we call bind after treeInit, because treeInit
  6269. // might change tree.$container.
  6270. // It would be better, to move event binding into hooks altogether
  6271. this._bind();
  6272. },
  6273. /* Use the _setOption method to respond to changes to options. */
  6274. _setOption: function (key, value) {
  6275. return this.tree._callHook(
  6276. "treeSetOption",
  6277. this.tree,
  6278. key,
  6279. value
  6280. );
  6281. },
  6282. /** Use the destroy method to clean up any modifications your widget has made to the DOM */
  6283. _destroy: function () {
  6284. this._unbind();
  6285. this.tree._callHook("treeDestroy", this.tree);
  6286. // In jQuery UI 1.8, you must invoke the destroy method from the base widget
  6287. // $.Widget.prototype.destroy.call(this);
  6288. // TODO: delete tree and nodes to make garbage collect easier?
  6289. // TODO: In jQuery UI 1.9 and above, you would define _destroy instead of destroy and not call the base method
  6290. },
  6291. // -------------------------------------------------------------------------
  6292. /* Remove all event handlers for our namespace */
  6293. _unbind: function () {
  6294. var ns = this.tree._ns;
  6295. this.element.off(ns);
  6296. this.tree.$container.off(ns);
  6297. $(document).off(ns);
  6298. },
  6299. /* Add mouse and kyboard handlers to the container */
  6300. _bind: function () {
  6301. var self = this,
  6302. opts = this.options,
  6303. tree = this.tree,
  6304. ns = tree._ns;
  6305. // selstartEvent = ( $.support.selectstart ? "selectstart" : "mousedown" )
  6306. // Remove all previuous handlers for this tree
  6307. this._unbind();
  6308. //alert("keydown" + ns + "foc=" + tree.hasFocus() + tree.$container);
  6309. // tree.debug("bind events; container: ", tree.$container);
  6310. tree.$container
  6311. .on("focusin" + ns + " focusout" + ns, function (event) {
  6312. var node = FT.getNode(event),
  6313. flag = event.type === "focusin";
  6314. if (!flag && node && $(event.target).is("a")) {
  6315. // #764
  6316. node.debug(
  6317. "Ignored focusout on embedded <a> element."
  6318. );
  6319. return;
  6320. }
  6321. // tree.treeOnFocusInOut.call(tree, event);
  6322. // tree.debug("Tree container got event " + event.type, node, event, FT.getEventTarget(event));
  6323. if (flag) {
  6324. if (tree._getExpiringValue("focusin")) {
  6325. // #789: IE 11 may send duplicate focusin events
  6326. tree.debug("Ignored double focusin.");
  6327. return;
  6328. }
  6329. tree._setExpiringValue("focusin", true, 50);
  6330. if (!node) {
  6331. // #789: IE 11 may send focusin before mousdown(?)
  6332. node = tree._getExpiringValue("mouseDownNode");
  6333. if (node) {
  6334. tree.debug(
  6335. "Reconstruct mouse target for focusin from recent event."
  6336. );
  6337. }
  6338. }
  6339. }
  6340. if (node) {
  6341. // For example clicking into an <input> that is part of a node
  6342. tree._callHook(
  6343. "nodeSetFocus",
  6344. tree._makeHookContext(node, event),
  6345. flag
  6346. );
  6347. } else {
  6348. if (
  6349. tree.tbody &&
  6350. $(event.target).parents(
  6351. "table.fancytree-container > thead"
  6352. ).length
  6353. ) {
  6354. // #767: ignore events in the table's header
  6355. tree.debug(
  6356. "Ignore focus event outside table body.",
  6357. event
  6358. );
  6359. } else {
  6360. tree._callHook("treeSetFocus", tree, flag);
  6361. }
  6362. }
  6363. })
  6364. .on(
  6365. "selectstart" + ns,
  6366. "span.fancytree-title",
  6367. function (event) {
  6368. // prevent mouse-drags to select text ranges
  6369. // tree.debug("<span title> got event " + event.type);
  6370. event.preventDefault();
  6371. }
  6372. )
  6373. .on("keydown" + ns, function (event) {
  6374. // TODO: also bind keyup and keypress
  6375. // tree.debug("got event " + event.type + ", hasFocus:" + tree.hasFocus());
  6376. // if(opts.disabled || opts.keyboard === false || !tree.hasFocus() ){
  6377. if (opts.disabled || opts.keyboard === false) {
  6378. return true;
  6379. }
  6380. var res,
  6381. node = tree.focusNode, // node may be null
  6382. ctx = tree._makeHookContext(node || tree, event),
  6383. prevPhase = tree.phase;
  6384. try {
  6385. tree.phase = "userEvent";
  6386. // If a 'fancytreekeydown' handler returns false, skip the default
  6387. // handling (implemented by tree.nodeKeydown()).
  6388. if (node) {
  6389. res = tree._triggerNodeEvent(
  6390. "keydown",
  6391. node,
  6392. event
  6393. );
  6394. } else {
  6395. res = tree._triggerTreeEvent("keydown", event);
  6396. }
  6397. if (res === "preventNav") {
  6398. res = true; // prevent keyboard navigation, but don't prevent default handling of embedded input controls
  6399. } else if (res !== false) {
  6400. res = tree._callHook("nodeKeydown", ctx);
  6401. }
  6402. return res;
  6403. } finally {
  6404. tree.phase = prevPhase;
  6405. }
  6406. })
  6407. .on("mousedown" + ns, function (event) {
  6408. var et = FT.getEventTarget(event);
  6409. // self.tree.debug("event(" + event.type + "): node: ", et.node);
  6410. // #712: Store the clicked node, so we can use it when we get a focusin event
  6411. // ('click' event fires after focusin)
  6412. // tree.debug("event(" + event.type + "): node: ", et.node);
  6413. tree._lastMousedownNode = et ? et.node : null;
  6414. // #789: Store the node also for a short period, so we can use it
  6415. // in a *resulting* focusin event
  6416. tree._setExpiringValue(
  6417. "mouseDownNode",
  6418. tree._lastMousedownNode
  6419. );
  6420. })
  6421. .on("click" + ns + " dblclick" + ns, function (event) {
  6422. if (opts.disabled) {
  6423. return true;
  6424. }
  6425. var ctx,
  6426. et = FT.getEventTarget(event),
  6427. node = et.node,
  6428. tree = self.tree,
  6429. prevPhase = tree.phase;
  6430. // self.tree.debug("event(" + event.type + "): node: ", node);
  6431. if (!node) {
  6432. return true; // Allow bubbling of other events
  6433. }
  6434. ctx = tree._makeHookContext(node, event);
  6435. // self.tree.debug("event(" + event.type + "): node: ", node);
  6436. try {
  6437. tree.phase = "userEvent";
  6438. switch (event.type) {
  6439. case "click":
  6440. ctx.targetType = et.type;
  6441. if (node.isPagingNode()) {
  6442. return (
  6443. tree._triggerNodeEvent(
  6444. "clickPaging",
  6445. ctx,
  6446. event
  6447. ) === true
  6448. );
  6449. }
  6450. return tree._triggerNodeEvent(
  6451. "click",
  6452. ctx,
  6453. event
  6454. ) === false
  6455. ? false
  6456. : tree._callHook("nodeClick", ctx);
  6457. case "dblclick":
  6458. ctx.targetType = et.type;
  6459. return tree._triggerNodeEvent(
  6460. "dblclick",
  6461. ctx,
  6462. event
  6463. ) === false
  6464. ? false
  6465. : tree._callHook("nodeDblclick", ctx);
  6466. }
  6467. } finally {
  6468. tree.phase = prevPhase;
  6469. }
  6470. });
  6471. },
  6472. /** Return the active node or null.
  6473. * @returns {FancytreeNode}
  6474. * @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>).
  6475. */
  6476. getActiveNode: function () {
  6477. this._deprecationWarning("getActiveNode");
  6478. return this.tree.activeNode;
  6479. },
  6480. /** Return the matching node or null.
  6481. * @param {string} key
  6482. * @returns {FancytreeNode}
  6483. * @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>).
  6484. */
  6485. getNodeByKey: function (key) {
  6486. this._deprecationWarning("getNodeByKey");
  6487. return this.tree.getNodeByKey(key);
  6488. },
  6489. /** Return the invisible system root node.
  6490. * @returns {FancytreeNode}
  6491. * @deprecated Use methods of the Fancytree instance instead (<a href="Fancytree_Widget.html">example above</a>).
  6492. */
  6493. getRootNode: function () {
  6494. this._deprecationWarning("getRootNode");
  6495. return this.tree.rootNode;
  6496. },
  6497. /** Return the current tree instance.
  6498. * @returns {Fancytree}
  6499. * @deprecated Use `$.ui.fancytree.getTree()` instead (<a href="Fancytree_Widget.html">example above</a>).
  6500. */
  6501. getTree: function () {
  6502. this._deprecationWarning("getTree");
  6503. return this.tree;
  6504. },
  6505. }
  6506. );
  6507. // $.ui.fancytree was created by the widget factory. Create a local shortcut:
  6508. FT = $.ui.fancytree;
  6509. /**
  6510. * Static members in the `$.ui.fancytree` namespace.
  6511. * This properties and methods can be accessed without instantiating a concrete
  6512. * Fancytree instance.
  6513. *
  6514. * @example
  6515. * // Access static members:
  6516. * var node = $.ui.fancytree.getNode(element);
  6517. * alert($.ui.fancytree.version);
  6518. *
  6519. * @mixin Fancytree_Static
  6520. */
  6521. $.extend(
  6522. $.ui.fancytree,
  6523. /** @lends Fancytree_Static# */
  6524. {
  6525. /** Version number `"MAJOR.MINOR.PATCH"`
  6526. * @type {string} */
  6527. version: "2.38.3", // Set to semver by 'grunt release'
  6528. /** @type {string}
  6529. * @description `"production" for release builds` */
  6530. buildType: "production", // Set to 'production' by 'grunt build'
  6531. /** @type {int}
  6532. * @description 0: silent .. 5: verbose (default: 3 for release builds). */
  6533. debugLevel: 3, // Set to 3 by 'grunt build'
  6534. // Used by $.ui.fancytree.debug() and as default for tree.options.debugLevel
  6535. _nextId: 1,
  6536. _nextNodeKey: 1,
  6537. _extensions: {},
  6538. // focusTree: null,
  6539. /** Expose class object as `$.ui.fancytree._FancytreeClass`.
  6540. * Useful to extend `$.ui.fancytree._FancytreeClass.prototype`.
  6541. * @type {Fancytree}
  6542. */
  6543. _FancytreeClass: Fancytree,
  6544. /** Expose class object as $.ui.fancytree._FancytreeNodeClass
  6545. * Useful to extend `$.ui.fancytree._FancytreeNodeClass.prototype`.
  6546. * @type {FancytreeNode}
  6547. */
  6548. _FancytreeNodeClass: FancytreeNode,
  6549. /* Feature checks to provide backwards compatibility */
  6550. jquerySupports: {
  6551. // http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
  6552. positionMyOfs: isVersionAtLeast($.ui.version, 1, 9),
  6553. },
  6554. /** Throw an error if condition fails (debug method).
  6555. * @param {boolean} cond
  6556. * @param {string} msg
  6557. */
  6558. assert: function (cond, msg) {
  6559. return _assert(cond, msg);
  6560. },
  6561. /** Create a new Fancytree instance on a target element.
  6562. *
  6563. * @param {Element | jQueryObject | string} el Target DOM element or selector
  6564. * @param {FancytreeOptions} [opts] Fancytree options
  6565. * @returns {Fancytree} new tree instance
  6566. * @example
  6567. * var tree = $.ui.fancytree.createTree("#tree", {
  6568. * source: {url: "my/webservice"}
  6569. * }); // Create tree for this matching element
  6570. *
  6571. * @since 2.25
  6572. */
  6573. createTree: function (el, opts) {
  6574. var $tree = $(el).fancytree(opts);
  6575. return FT.getTree($tree);
  6576. },
  6577. /** Return a function that executes *fn* at most every *timeout* ms.
  6578. * @param {integer} timeout
  6579. * @param {function} fn
  6580. * @param {boolean} [invokeAsap=false]
  6581. * @param {any} [ctx]
  6582. */
  6583. debounce: function (timeout, fn, invokeAsap, ctx) {
  6584. var timer;
  6585. if (arguments.length === 3 && typeof invokeAsap !== "boolean") {
  6586. ctx = invokeAsap;
  6587. invokeAsap = false;
  6588. }
  6589. return function () {
  6590. var args = arguments;
  6591. ctx = ctx || this;
  6592. // eslint-disable-next-line no-unused-expressions
  6593. invokeAsap && !timer && fn.apply(ctx, args);
  6594. clearTimeout(timer);
  6595. timer = setTimeout(function () {
  6596. // eslint-disable-next-line no-unused-expressions
  6597. invokeAsap || fn.apply(ctx, args);
  6598. timer = null;
  6599. }, timeout);
  6600. };
  6601. },
  6602. /** Write message to console if debugLevel >= 4
  6603. * @param {string} msg
  6604. */
  6605. debug: function (msg) {
  6606. if ($.ui.fancytree.debugLevel >= 4) {
  6607. consoleApply("log", arguments);
  6608. }
  6609. },
  6610. /** Write error message to console if debugLevel >= 1.
  6611. * @param {string} msg
  6612. */
  6613. error: function (msg) {
  6614. if ($.ui.fancytree.debugLevel >= 1) {
  6615. consoleApply("error", arguments);
  6616. }
  6617. },
  6618. /** Convert `<`, `>`, `&`, `"`, `'`, and `/` to the equivalent entities.
  6619. *
  6620. * @param {string} s
  6621. * @returns {string}
  6622. */
  6623. escapeHtml: function (s) {
  6624. return ("" + s).replace(REX_HTML, function (s) {
  6625. return ENTITY_MAP[s];
  6626. });
  6627. },
  6628. /** Make jQuery.position() arguments backwards compatible, i.e. if
  6629. * jQuery UI version <= 1.8, convert
  6630. * { my: "left+3 center", at: "left bottom", of: $target }
  6631. * to
  6632. * { my: "left center", at: "left bottom", of: $target, offset: "3 0" }
  6633. *
  6634. * See http://jqueryui.com/upgrade-guide/1.9/#deprecated-offset-option-merged-into-my-and-at
  6635. * and http://jsfiddle.net/mar10/6xtu9a4e/
  6636. *
  6637. * @param {object} opts
  6638. * @returns {object} the (potentially modified) original opts hash object
  6639. */
  6640. fixPositionOptions: function (opts) {
  6641. if (opts.offset || ("" + opts.my + opts.at).indexOf("%") >= 0) {
  6642. $.error(
  6643. "expected new position syntax (but '%' is not supported)"
  6644. );
  6645. }
  6646. if (!$.ui.fancytree.jquerySupports.positionMyOfs) {
  6647. var // parse 'left+3 center' into ['left+3 center', 'left', '+3', 'center', undefined]
  6648. myParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(
  6649. opts.my
  6650. ),
  6651. atParts = /(\w+)([+-]?\d+)?\s+(\w+)([+-]?\d+)?/.exec(
  6652. opts.at
  6653. ),
  6654. // convert to numbers
  6655. dx =
  6656. (myParts[2] ? +myParts[2] : 0) +
  6657. (atParts[2] ? +atParts[2] : 0),
  6658. dy =
  6659. (myParts[4] ? +myParts[4] : 0) +
  6660. (atParts[4] ? +atParts[4] : 0);
  6661. opts = $.extend({}, opts, {
  6662. // make a copy and overwrite
  6663. my: myParts[1] + " " + myParts[3],
  6664. at: atParts[1] + " " + atParts[3],
  6665. });
  6666. if (dx || dy) {
  6667. opts.offset = "" + dx + " " + dy;
  6668. }
  6669. }
  6670. return opts;
  6671. },
  6672. /** Return a {node: FancytreeNode, type: TYPE} object for a mouse event.
  6673. *
  6674. * @param {Event} event Mouse event, e.g. click, ...
  6675. * @returns {object} Return a {node: FancytreeNode, type: TYPE} object
  6676. * TYPE: 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
  6677. */
  6678. getEventTarget: function (event) {
  6679. var $target,
  6680. tree,
  6681. tcn = event && event.target ? event.target.className : "",
  6682. res = { node: this.getNode(event.target), type: undefined };
  6683. // We use a fast version of $(res.node).hasClass()
  6684. // See http://jsperf.com/test-for-classname/2
  6685. if (/\bfancytree-title\b/.test(tcn)) {
  6686. res.type = "title";
  6687. } else if (/\bfancytree-expander\b/.test(tcn)) {
  6688. res.type =
  6689. res.node.hasChildren() === false
  6690. ? "prefix"
  6691. : "expander";
  6692. // }else if( /\bfancytree-checkbox\b/.test(tcn) || /\bfancytree-radio\b/.test(tcn) ){
  6693. } else if (/\bfancytree-checkbox\b/.test(tcn)) {
  6694. res.type = "checkbox";
  6695. } else if (/\bfancytree(-custom)?-icon\b/.test(tcn)) {
  6696. res.type = "icon";
  6697. } else if (/\bfancytree-node\b/.test(tcn)) {
  6698. // Somewhere near the title
  6699. res.type = "title";
  6700. } else if (event && event.target) {
  6701. $target = $(event.target);
  6702. if ($target.is("ul[role=group]")) {
  6703. // #nnn: Clicking right to a node may hit the surrounding UL
  6704. tree = res.node && res.node.tree;
  6705. (tree || FT).debug("Ignoring click on outer UL.");
  6706. res.node = null;
  6707. } else if ($target.closest(".fancytree-title").length) {
  6708. // #228: clicking an embedded element inside a title
  6709. res.type = "title";
  6710. } else if ($target.closest(".fancytree-checkbox").length) {
  6711. // E.g. <svg> inside checkbox span
  6712. res.type = "checkbox";
  6713. } else if ($target.closest(".fancytree-expander").length) {
  6714. res.type = "expander";
  6715. }
  6716. }
  6717. return res;
  6718. },
  6719. /** Return a string describing the affected node region for a mouse event.
  6720. *
  6721. * @param {Event} event Mouse event, e.g. click, mousemove, ...
  6722. * @returns {string} 'title' | 'prefix' | 'expander' | 'checkbox' | 'icon' | undefined
  6723. */
  6724. getEventTargetType: function (event) {
  6725. return this.getEventTarget(event).type;
  6726. },
  6727. /** Return a FancytreeNode instance from element, event, or jQuery object.
  6728. *
  6729. * @param {Element | jQueryObject | Event} el
  6730. * @returns {FancytreeNode} matching node or null
  6731. */
  6732. getNode: function (el) {
  6733. if (el instanceof FancytreeNode) {
  6734. return el; // el already was a FancytreeNode
  6735. } else if (el instanceof $) {
  6736. el = el[0]; // el was a jQuery object: use the DOM element
  6737. } else if (el.originalEvent !== undefined) {
  6738. el = el.target; // el was an Event
  6739. }
  6740. while (el) {
  6741. if (el.ftnode) {
  6742. return el.ftnode;
  6743. }
  6744. el = el.parentNode;
  6745. }
  6746. return null;
  6747. },
  6748. /** Return a Fancytree instance, from element, index, event, or jQueryObject.
  6749. *
  6750. * @param {Element | jQueryObject | Event | integer | string} [el]
  6751. * @returns {Fancytree} matching tree or null
  6752. * @example
  6753. * $.ui.fancytree.getTree(); // Get first Fancytree instance on page
  6754. * $.ui.fancytree.getTree(1); // Get second Fancytree instance on page
  6755. * $.ui.fancytree.getTree(event); // Get tree for this mouse- or keyboard event
  6756. * $.ui.fancytree.getTree("foo"); // Get tree for this `opts.treeId`
  6757. * $.ui.fancytree.getTree("#tree"); // Get tree for this matching element
  6758. *
  6759. * @since 2.13
  6760. */
  6761. getTree: function (el) {
  6762. var widget,
  6763. orgEl = el;
  6764. if (el instanceof Fancytree) {
  6765. return el; // el already was a Fancytree
  6766. }
  6767. if (el === undefined) {
  6768. el = 0; // get first tree
  6769. }
  6770. if (typeof el === "number") {
  6771. el = $(".fancytree-container").eq(el); // el was an integer: return nth instance
  6772. } else if (typeof el === "string") {
  6773. // `el` may be a treeId or a selector:
  6774. el = $("#ft-id-" + orgEl).eq(0);
  6775. if (!el.length) {
  6776. el = $(orgEl).eq(0); // el was a selector: use first match
  6777. }
  6778. } else if (
  6779. el instanceof Element ||
  6780. el instanceof HTMLDocument
  6781. ) {
  6782. el = $(el);
  6783. } else if (el instanceof $) {
  6784. el = el.eq(0); // el was a jQuery object: use the first
  6785. } else if (el.originalEvent !== undefined) {
  6786. el = $(el.target); // el was an Event
  6787. }
  6788. // el is a jQuery object wit one element here
  6789. el = el.closest(":ui-fancytree");
  6790. widget = el.data("ui-fancytree") || el.data("fancytree"); // the latter is required by jQuery <= 1.8
  6791. return widget ? widget.tree : null;
  6792. },
  6793. /** Return an option value that has a default, but may be overridden by a
  6794. * callback or a node instance attribute.
  6795. *
  6796. * Evaluation sequence:
  6797. *
  6798. * If `tree.options.<optionName>` is a callback that returns something, use that.
  6799. * Else if `node.<optionName>` is defined, use that.
  6800. * Else if `tree.options.<optionName>` is a value, use that.
  6801. * Else use `defaultValue`.
  6802. *
  6803. * @param {string} optionName name of the option property (on node and tree)
  6804. * @param {FancytreeNode} node passed to the callback
  6805. * @param {object} nodeObject where to look for the local option property, e.g. `node` or `node.data`
  6806. * @param {object} treeOption where to look for the tree option, e.g. `tree.options` or `tree.options.dnd5`
  6807. * @param {any} [defaultValue]
  6808. * @returns {any}
  6809. *
  6810. * @example
  6811. * // Check for node.foo, tree,options.foo(), and tree.options.foo:
  6812. * $.ui.fancytree.evalOption("foo", node, node, tree.options);
  6813. * // Check for node.data.bar, tree,options.qux.bar(), and tree.options.qux.bar:
  6814. * $.ui.fancytree.evalOption("bar", node, node.data, tree.options.qux);
  6815. *
  6816. * @since 2.22
  6817. */
  6818. evalOption: function (
  6819. optionName,
  6820. node,
  6821. nodeObject,
  6822. treeOptions,
  6823. defaultValue
  6824. ) {
  6825. var ctx,
  6826. res,
  6827. tree = node.tree,
  6828. treeOpt = treeOptions[optionName],
  6829. nodeOpt = nodeObject[optionName];
  6830. if (_isFunction(treeOpt)) {
  6831. ctx = {
  6832. node: node,
  6833. tree: tree,
  6834. widget: tree.widget,
  6835. options: tree.widget.options,
  6836. typeInfo: tree.types[node.type] || {},
  6837. };
  6838. res = treeOpt.call(tree, { type: optionName }, ctx);
  6839. if (res == null) {
  6840. res = nodeOpt;
  6841. }
  6842. } else {
  6843. res = nodeOpt == null ? treeOpt : nodeOpt;
  6844. }
  6845. if (res == null) {
  6846. res = defaultValue; // no option set at all: return default
  6847. }
  6848. return res;
  6849. },
  6850. /** Set expander, checkbox, or node icon, supporting string and object format.
  6851. *
  6852. * @param {Element | jQueryObject} span
  6853. * @param {string} baseClass
  6854. * @param {string | object} icon
  6855. * @since 2.27
  6856. */
  6857. setSpanIcon: function (span, baseClass, icon) {
  6858. var $span = $(span);
  6859. if (typeof icon === "string") {
  6860. $span.attr("class", baseClass + " " + icon);
  6861. } else {
  6862. // support object syntax: { text: ligature, addClasse: classname }
  6863. if (icon.text) {
  6864. $span.text("" + icon.text);
  6865. } else if (icon.html) {
  6866. span.innerHTML = icon.html;
  6867. }
  6868. $span.attr(
  6869. "class",
  6870. baseClass + " " + (icon.addClass || "")
  6871. );
  6872. }
  6873. },
  6874. /** Convert a keydown or mouse event to a canonical string like 'ctrl+a',
  6875. * 'ctrl+shift+f2', 'shift+leftdblclick'.
  6876. *
  6877. * This is especially handy for switch-statements in event handlers.
  6878. *
  6879. * @param {event}
  6880. * @returns {string}
  6881. *
  6882. * @example
  6883. switch( $.ui.fancytree.eventToString(event) ) {
  6884. case "-":
  6885. tree.nodeSetExpanded(ctx, false);
  6886. break;
  6887. case "shift+return":
  6888. tree.nodeSetActive(ctx, true);
  6889. break;
  6890. case "down":
  6891. res = node.navigate(event.which, activate);
  6892. break;
  6893. default:
  6894. handled = false;
  6895. }
  6896. if( handled ){
  6897. event.preventDefault();
  6898. }
  6899. */
  6900. eventToString: function (event) {
  6901. // Poor-man's hotkeys. See here for a complete implementation:
  6902. // https://github.com/jeresig/jquery.hotkeys
  6903. var which = event.which,
  6904. et = event.type,
  6905. s = [];
  6906. if (event.altKey) {
  6907. s.push("alt");
  6908. }
  6909. if (event.ctrlKey) {
  6910. s.push("ctrl");
  6911. }
  6912. if (event.metaKey) {
  6913. s.push("meta");
  6914. }
  6915. if (event.shiftKey) {
  6916. s.push("shift");
  6917. }
  6918. if (et === "click" || et === "dblclick") {
  6919. s.push(MOUSE_BUTTONS[event.button] + et);
  6920. } else if (et === "wheel") {
  6921. s.push(et);
  6922. } else if (!IGNORE_KEYCODES[which]) {
  6923. s.push(
  6924. SPECIAL_KEYCODES[which] ||
  6925. String.fromCharCode(which).toLowerCase()
  6926. );
  6927. }
  6928. return s.join("+");
  6929. },
  6930. /** Write message to console if debugLevel >= 3
  6931. * @param {string} msg
  6932. */
  6933. info: function (msg) {
  6934. if ($.ui.fancytree.debugLevel >= 3) {
  6935. consoleApply("info", arguments);
  6936. }
  6937. },
  6938. /* @deprecated: use eventToString(event) instead.
  6939. */
  6940. keyEventToString: function (event) {
  6941. this.warn(
  6942. "keyEventToString() is deprecated: use eventToString()"
  6943. );
  6944. return this.eventToString(event);
  6945. },
  6946. /** Return a wrapped handler method, that provides `this._super`.
  6947. *
  6948. * @example
  6949. // Implement `opts.createNode` event to add the 'draggable' attribute
  6950. $.ui.fancytree.overrideMethod(ctx.options, "createNode", function(event, data) {
  6951. // Default processing if any
  6952. this._super.apply(this, arguments);
  6953. // Add 'draggable' attribute
  6954. data.node.span.draggable = true;
  6955. });
  6956. *
  6957. * @param {object} instance
  6958. * @param {string} methodName
  6959. * @param {function} handler
  6960. * @param {object} [context] optional context
  6961. */
  6962. overrideMethod: function (instance, methodName, handler, context) {
  6963. var prevSuper,
  6964. _super = instance[methodName] || $.noop;
  6965. instance[methodName] = function () {
  6966. var self = context || this;
  6967. try {
  6968. prevSuper = self._super;
  6969. self._super = _super;
  6970. return handler.apply(self, arguments);
  6971. } finally {
  6972. self._super = prevSuper;
  6973. }
  6974. };
  6975. },
  6976. /**
  6977. * Parse tree data from HTML <ul> markup
  6978. *
  6979. * @param {jQueryObject} $ul
  6980. * @returns {NodeData[]}
  6981. */
  6982. parseHtml: function ($ul) {
  6983. var classes,
  6984. className,
  6985. extraClasses,
  6986. i,
  6987. iPos,
  6988. l,
  6989. tmp,
  6990. tmp2,
  6991. $children = $ul.find(">li"),
  6992. children = [];
  6993. $children.each(function () {
  6994. var allData,
  6995. lowerCaseAttr,
  6996. $li = $(this),
  6997. $liSpan = $li.find(">span", this).first(),
  6998. $liA = $liSpan.length ? null : $li.find(">a").first(),
  6999. d = { tooltip: null, data: {} };
  7000. if ($liSpan.length) {
  7001. d.title = $liSpan.html();
  7002. } else if ($liA && $liA.length) {
  7003. // If a <li><a> tag is specified, use it literally and extract href/target.
  7004. d.title = $liA.html();
  7005. d.data.href = $liA.attr("href");
  7006. d.data.target = $liA.attr("target");
  7007. d.tooltip = $liA.attr("title");
  7008. } else {
  7009. // If only a <li> tag is specified, use the trimmed string up to
  7010. // the next child <ul> tag.
  7011. d.title = $li.html();
  7012. iPos = d.title.search(/<ul/i);
  7013. if (iPos >= 0) {
  7014. d.title = d.title.substring(0, iPos);
  7015. }
  7016. }
  7017. d.title = _trim(d.title);
  7018. // Make sure all fields exist
  7019. for (i = 0, l = CLASS_ATTRS.length; i < l; i++) {
  7020. d[CLASS_ATTRS[i]] = undefined;
  7021. }
  7022. // Initialize to `true`, if class is set and collect extraClasses
  7023. classes = this.className.split(" ");
  7024. extraClasses = [];
  7025. for (i = 0, l = classes.length; i < l; i++) {
  7026. className = classes[i];
  7027. if (CLASS_ATTR_MAP[className]) {
  7028. d[className] = true;
  7029. } else {
  7030. extraClasses.push(className);
  7031. }
  7032. }
  7033. d.extraClasses = extraClasses.join(" ");
  7034. // Parse node options from ID, title and class attributes
  7035. tmp = $li.attr("title");
  7036. if (tmp) {
  7037. d.tooltip = tmp; // overrides <a title='...'>
  7038. }
  7039. tmp = $li.attr("id");
  7040. if (tmp) {
  7041. d.key = tmp;
  7042. }
  7043. // Translate hideCheckbox -> checkbox:false
  7044. if ($li.attr("hideCheckbox")) {
  7045. d.checkbox = false;
  7046. }
  7047. // Add <li data-NAME='...'> as node.data.NAME
  7048. allData = _getElementDataAsDict($li);
  7049. if (allData && !$.isEmptyObject(allData)) {
  7050. // #507: convert data-hidecheckbox (lower case) to hideCheckbox
  7051. for (lowerCaseAttr in NODE_ATTR_LOWERCASE_MAP) {
  7052. if (_hasProp(allData, lowerCaseAttr)) {
  7053. allData[
  7054. NODE_ATTR_LOWERCASE_MAP[lowerCaseAttr]
  7055. ] = allData[lowerCaseAttr];
  7056. delete allData[lowerCaseAttr];
  7057. }
  7058. }
  7059. // #56: Allow to set special node.attributes from data-...
  7060. for (i = 0, l = NODE_ATTRS.length; i < l; i++) {
  7061. tmp = NODE_ATTRS[i];
  7062. tmp2 = allData[tmp];
  7063. if (tmp2 != null) {
  7064. delete allData[tmp];
  7065. d[tmp] = tmp2;
  7066. }
  7067. }
  7068. // All other data-... goes to node.data...
  7069. $.extend(d.data, allData);
  7070. }
  7071. // Recursive reading of child nodes, if LI tag contains an UL tag
  7072. $ul = $li.find(">ul").first();
  7073. if ($ul.length) {
  7074. d.children = $.ui.fancytree.parseHtml($ul);
  7075. } else {
  7076. d.children = d.lazy ? undefined : null;
  7077. }
  7078. children.push(d);
  7079. // FT.debug("parse ", d, children);
  7080. });
  7081. return children;
  7082. },
  7083. /** Add Fancytree extension definition to the list of globally available extensions.
  7084. *
  7085. * @param {object} definition
  7086. */
  7087. registerExtension: function (definition) {
  7088. _assert(
  7089. definition.name != null,
  7090. "extensions must have a `name` property."
  7091. );
  7092. _assert(
  7093. definition.version != null,
  7094. "extensions must have a `version` property."
  7095. );
  7096. $.ui.fancytree._extensions[definition.name] = definition;
  7097. },
  7098. /** Replacement for the deprecated `jQuery.trim()`.
  7099. *
  7100. * @param {string} text
  7101. */
  7102. trim: _trim,
  7103. /** Inverse of escapeHtml().
  7104. *
  7105. * @param {string} s
  7106. * @returns {string}
  7107. */
  7108. unescapeHtml: function (s) {
  7109. var e = document.createElement("div");
  7110. e.innerHTML = s;
  7111. return e.childNodes.length === 0
  7112. ? ""
  7113. : e.childNodes[0].nodeValue;
  7114. },
  7115. /** Write warning message to console if debugLevel >= 2.
  7116. * @param {string} msg
  7117. */
  7118. warn: function (msg) {
  7119. if ($.ui.fancytree.debugLevel >= 2) {
  7120. consoleApply("warn", arguments);
  7121. }
  7122. },
  7123. }
  7124. );
  7125. // Value returned by `require('jquery.fancytree')`
  7126. return $.ui.fancytree;
  7127. }); // End of closure