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.
 
 
 
 
 

13179 lines
378 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
  7128. // Extending Fancytree
  7129. // ===================
  7130. //
  7131. // See also the [live demo](https://wwWendt.de/tech/fancytree/demo/sample-ext-childcounter.html) of this code.
  7132. //
  7133. // Every extension should have a comment header containing some information
  7134. // about the author, copyright and licensing. Also a pointer to the latest
  7135. // source code.
  7136. // Prefix with `/*!` so the comment is not removed by the minifier.
  7137. /*!
  7138. * jquery.fancytree.childcounter.js
  7139. *
  7140. * Add a child counter bubble to tree nodes.
  7141. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  7142. *
  7143. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  7144. *
  7145. * Released under the MIT license
  7146. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  7147. *
  7148. * @version 2.38.3
  7149. * @date 2023-02-01T20:52:50Z
  7150. */
  7151. // To keep the global namespace clean, we wrap everything in a closure.
  7152. // The UMD wrapper pattern defines the dependencies on jQuery and the
  7153. // Fancytree core module, and makes sure that we can use the `require()`
  7154. // syntax with package loaders.
  7155. (function (factory) {
  7156. if (typeof define === "function" && define.amd) {
  7157. // AMD. Register as an anonymous module.
  7158. define(["jquery", "./jquery.fancytree"], factory);
  7159. } else if (typeof module === "object" && module.exports) {
  7160. // Node/CommonJS
  7161. require("./jquery.fancytree");
  7162. module.exports = factory(require("jquery"));
  7163. } else {
  7164. // Browser globals
  7165. factory(jQuery);
  7166. }
  7167. })(function ($) {
  7168. // Consider to use [strict mode](http://ejohn.org/blog/ecmascript-5-strict-mode-json-and-more/)
  7169. "use strict";
  7170. // The [coding guidelines](http://contribute.jquery.org/style-guide/js/)
  7171. // require jshint /eslint compliance.
  7172. // But for this sample, we want to allow unused variables for demonstration purpose.
  7173. /*eslint-disable no-unused-vars */
  7174. // Adding methods
  7175. // --------------
  7176. // New member functions can be added to the `Fancytree` class.
  7177. // This function will be available for every tree instance:
  7178. //
  7179. // var tree = $.ui.fancytree.getTree("#tree");
  7180. // tree.countSelected(false);
  7181. $.ui.fancytree._FancytreeClass.prototype.countSelected = function (
  7182. topOnly
  7183. ) {
  7184. var tree = this,
  7185. treeOptions = tree.options;
  7186. return tree.getSelectedNodes(topOnly).length;
  7187. };
  7188. // The `FancytreeNode` class can also be easily extended. This would be called
  7189. // like
  7190. // node.updateCounters();
  7191. //
  7192. // It is also good practice to add a docstring comment.
  7193. /**
  7194. * [ext-childcounter] Update counter badges for `node` and its parents.
  7195. * May be called in the `loadChildren` event, to update parents of lazy loaded
  7196. * nodes.
  7197. * @alias FancytreeNode#updateCounters
  7198. * @requires jquery.fancytree.childcounters.js
  7199. */
  7200. $.ui.fancytree._FancytreeNodeClass.prototype.updateCounters = function () {
  7201. var node = this,
  7202. $badge = $("span.fancytree-childcounter", node.span),
  7203. extOpts = node.tree.options.childcounter,
  7204. count = node.countChildren(extOpts.deep);
  7205. node.data.childCounter = count;
  7206. if (
  7207. (count || !extOpts.hideZeros) &&
  7208. (!node.isExpanded() || !extOpts.hideExpanded)
  7209. ) {
  7210. if (!$badge.length) {
  7211. $badge = $("<span class='fancytree-childcounter'/>").appendTo(
  7212. $(
  7213. "span.fancytree-icon,span.fancytree-custom-icon",
  7214. node.span
  7215. )
  7216. );
  7217. }
  7218. $badge.text(count);
  7219. } else {
  7220. $badge.remove();
  7221. }
  7222. if (extOpts.deep && !node.isTopLevel() && !node.isRootNode()) {
  7223. node.parent.updateCounters();
  7224. }
  7225. };
  7226. // Finally, we can extend the widget API and create functions that are called
  7227. // like so:
  7228. //
  7229. // $("#tree").fancytree("widgetMethod1", "abc");
  7230. $.ui.fancytree.prototype.widgetMethod1 = function (arg1) {
  7231. var tree = this.tree;
  7232. return arg1;
  7233. };
  7234. // Register a Fancytree extension
  7235. // ------------------------------
  7236. // A full blown extension, extension is available for all trees and can be
  7237. // enabled like so (see also the [live demo](https://wwWendt.de/tech/fancytree/demo/sample-ext-childcounter.html)):
  7238. //
  7239. // <script src="../src/jquery.fancytree.js"></script>
  7240. // <script src="../src/jquery.fancytree.childcounter.js"></script>
  7241. // ...
  7242. //
  7243. // $("#tree").fancytree({
  7244. // extensions: ["childcounter"],
  7245. // childcounter: {
  7246. // hideExpanded: true
  7247. // },
  7248. // ...
  7249. // });
  7250. //
  7251. /* 'childcounter' extension */
  7252. $.ui.fancytree.registerExtension({
  7253. // Every extension must be registered by a unique name.
  7254. name: "childcounter",
  7255. // Version information should be compliant with [semver](http://semver.org)
  7256. version: "2.38.3",
  7257. // Extension specific options and their defaults.
  7258. // This options will be available as `tree.options.childcounter.hideExpanded`
  7259. options: {
  7260. deep: true,
  7261. hideZeros: true,
  7262. hideExpanded: false,
  7263. },
  7264. // Attributes other than `options` (or functions) can be defined here, and
  7265. // will be added to the tree.ext.EXTNAME namespace, in this case `tree.ext.childcounter.foo`.
  7266. // They can also be accessed as `this._local.foo` from within the extension
  7267. // methods.
  7268. foo: 42,
  7269. // Local functions are prefixed with an underscore '_'.
  7270. // Callable as `this._local._appendCounter()`.
  7271. _appendCounter: function (bar) {
  7272. var tree = this;
  7273. },
  7274. // **Override virtual methods for this extension.**
  7275. //
  7276. // Fancytree implements a number of 'hook methods', prefixed by 'node...' or 'tree...'.
  7277. // with a `ctx` argument (see [EventData](https://wwWendt.de/tech/fancytree/doc/jsdoc/global.html#EventData)
  7278. // for details) and an extended calling context:<br>
  7279. // `this` : the Fancytree instance<br>
  7280. // `this._local`: the namespace that contains extension attributes and private methods (same as this.ext.EXTNAME)<br>
  7281. // `this._super`: the virtual function that was overridden (member of previous extension or Fancytree)
  7282. //
  7283. // See also the [complete list of available hook functions](https://wwWendt.de/tech/fancytree/doc/jsdoc/Fancytree_Hooks.html).
  7284. /* Init */
  7285. // `treeInit` is triggered when a tree is initalized. We can set up classes or
  7286. // bind event handlers here...
  7287. treeInit: function (ctx) {
  7288. var tree = this, // same as ctx.tree,
  7289. opts = ctx.options,
  7290. extOpts = ctx.options.childcounter;
  7291. // Optionally check for dependencies with other extensions
  7292. /* this._requireExtension("glyph", false, false); */
  7293. // Call the base implementation
  7294. this._superApply(arguments);
  7295. // Add a class to the tree container
  7296. this.$container.addClass("fancytree-ext-childcounter");
  7297. },
  7298. // Destroy this tree instance (we only call the default implementation, so
  7299. // this method could as well be omitted).
  7300. treeDestroy: function (ctx) {
  7301. this._superApply(arguments);
  7302. },
  7303. // Overload the `renderTitle` hook, to append a counter badge
  7304. nodeRenderTitle: function (ctx, title) {
  7305. var node = ctx.node,
  7306. extOpts = ctx.options.childcounter,
  7307. count =
  7308. node.data.childCounter == null
  7309. ? node.countChildren(extOpts.deep)
  7310. : +node.data.childCounter;
  7311. // Let the base implementation render the title
  7312. // We use `_super()` instead of `_superApply()` here, since it is a little bit
  7313. // more performant when called often
  7314. this._super(ctx, title);
  7315. // Append a counter badge
  7316. if (
  7317. (count || !extOpts.hideZeros) &&
  7318. (!node.isExpanded() || !extOpts.hideExpanded)
  7319. ) {
  7320. $(
  7321. "span.fancytree-icon,span.fancytree-custom-icon",
  7322. node.span
  7323. ).append(
  7324. $("<span class='fancytree-childcounter'/>").text(count)
  7325. );
  7326. }
  7327. },
  7328. // Overload the `setExpanded` hook, so the counters are updated
  7329. nodeSetExpanded: function (ctx, flag, callOpts) {
  7330. var tree = ctx.tree,
  7331. node = ctx.node;
  7332. // Let the base implementation expand/collapse the node, then redraw the title
  7333. // after the animation has finished
  7334. return this._superApply(arguments).always(function () {
  7335. tree.nodeRenderTitle(ctx);
  7336. });
  7337. },
  7338. // End of extension definition
  7339. });
  7340. // Value returned by `require('jquery.fancytree..')`
  7341. return $.ui.fancytree;
  7342. }); // End of closure
  7343. /*!
  7344. *
  7345. * jquery.fancytree.clones.js
  7346. * Support faster lookup of nodes by key and shared ref-ids.
  7347. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  7348. *
  7349. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  7350. *
  7351. * Released under the MIT license
  7352. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  7353. *
  7354. * @version 2.38.3
  7355. * @date 2023-02-01T20:52:50Z
  7356. */
  7357. (function (factory) {
  7358. if (typeof define === "function" && define.amd) {
  7359. // AMD. Register as an anonymous module.
  7360. define(["jquery", "./jquery.fancytree"], factory);
  7361. } else if (typeof module === "object" && module.exports) {
  7362. // Node/CommonJS
  7363. require("./jquery.fancytree");
  7364. module.exports = factory(require("jquery"));
  7365. } else {
  7366. // Browser globals
  7367. factory(jQuery);
  7368. }
  7369. })(function ($) {
  7370. "use strict";
  7371. /*******************************************************************************
  7372. * Private functions and variables
  7373. */
  7374. var _assert = $.ui.fancytree.assert;
  7375. /* Return first occurrence of member from array. */
  7376. function _removeArrayMember(arr, elem) {
  7377. // TODO: use Array.indexOf for IE >= 9
  7378. var i;
  7379. for (i = arr.length - 1; i >= 0; i--) {
  7380. if (arr[i] === elem) {
  7381. arr.splice(i, 1);
  7382. return true;
  7383. }
  7384. }
  7385. return false;
  7386. }
  7387. /**
  7388. * JS Implementation of MurmurHash3 (r136) (as of May 20, 2011)
  7389. *
  7390. * @author <a href="mailto:gary.court@gmail.com">Gary Court</a>
  7391. * @see http://github.com/garycourt/murmurhash-js
  7392. * @author <a href="mailto:aappleby@gmail.com">Austin Appleby</a>
  7393. * @see http://sites.google.com/site/murmurhash/
  7394. *
  7395. * @param {string} key ASCII only
  7396. * @param {boolean} [asString=false]
  7397. * @param {number} seed Positive integer only
  7398. * @return {number} 32-bit positive integer hash
  7399. */
  7400. function hashMurmur3(key, asString, seed) {
  7401. /*eslint-disable no-bitwise */
  7402. var h1b,
  7403. k1,
  7404. remainder = key.length & 3,
  7405. bytes = key.length - remainder,
  7406. h1 = seed,
  7407. c1 = 0xcc9e2d51,
  7408. c2 = 0x1b873593,
  7409. i = 0;
  7410. while (i < bytes) {
  7411. k1 =
  7412. (key.charCodeAt(i) & 0xff) |
  7413. ((key.charCodeAt(++i) & 0xff) << 8) |
  7414. ((key.charCodeAt(++i) & 0xff) << 16) |
  7415. ((key.charCodeAt(++i) & 0xff) << 24);
  7416. ++i;
  7417. k1 =
  7418. ((k1 & 0xffff) * c1 + ((((k1 >>> 16) * c1) & 0xffff) << 16)) &
  7419. 0xffffffff;
  7420. k1 = (k1 << 15) | (k1 >>> 17);
  7421. k1 =
  7422. ((k1 & 0xffff) * c2 + ((((k1 >>> 16) * c2) & 0xffff) << 16)) &
  7423. 0xffffffff;
  7424. h1 ^= k1;
  7425. h1 = (h1 << 13) | (h1 >>> 19);
  7426. h1b =
  7427. ((h1 & 0xffff) * 5 + ((((h1 >>> 16) * 5) & 0xffff) << 16)) &
  7428. 0xffffffff;
  7429. h1 =
  7430. (h1b & 0xffff) +
  7431. 0x6b64 +
  7432. ((((h1b >>> 16) + 0xe654) & 0xffff) << 16);
  7433. }
  7434. k1 = 0;
  7435. switch (remainder) {
  7436. case 3:
  7437. k1 ^= (key.charCodeAt(i + 2) & 0xff) << 16;
  7438. // fall through
  7439. case 2:
  7440. k1 ^= (key.charCodeAt(i + 1) & 0xff) << 8;
  7441. // fall through
  7442. case 1:
  7443. k1 ^= key.charCodeAt(i) & 0xff;
  7444. k1 =
  7445. ((k1 & 0xffff) * c1 +
  7446. ((((k1 >>> 16) * c1) & 0xffff) << 16)) &
  7447. 0xffffffff;
  7448. k1 = (k1 << 15) | (k1 >>> 17);
  7449. k1 =
  7450. ((k1 & 0xffff) * c2 +
  7451. ((((k1 >>> 16) * c2) & 0xffff) << 16)) &
  7452. 0xffffffff;
  7453. h1 ^= k1;
  7454. }
  7455. h1 ^= key.length;
  7456. h1 ^= h1 >>> 16;
  7457. h1 =
  7458. ((h1 & 0xffff) * 0x85ebca6b +
  7459. ((((h1 >>> 16) * 0x85ebca6b) & 0xffff) << 16)) &
  7460. 0xffffffff;
  7461. h1 ^= h1 >>> 13;
  7462. h1 =
  7463. ((h1 & 0xffff) * 0xc2b2ae35 +
  7464. ((((h1 >>> 16) * 0xc2b2ae35) & 0xffff) << 16)) &
  7465. 0xffffffff;
  7466. h1 ^= h1 >>> 16;
  7467. if (asString) {
  7468. // Convert to 8 digit hex string
  7469. return ("0000000" + (h1 >>> 0).toString(16)).substr(-8);
  7470. }
  7471. return h1 >>> 0;
  7472. /*eslint-enable no-bitwise */
  7473. }
  7474. /*
  7475. * Return a unique key for node by calculating the hash of the parents refKey-list.
  7476. */
  7477. function calcUniqueKey(node) {
  7478. var key,
  7479. h1,
  7480. path = $.map(node.getParentList(false, true), function (e) {
  7481. return e.refKey || e.key;
  7482. });
  7483. path = path.join("/");
  7484. // 32-bit has a high probability of collisions, so we pump up to 64-bit
  7485. // https://security.stackexchange.com/q/209882/207588
  7486. h1 = hashMurmur3(path, true);
  7487. key = "id_" + h1 + hashMurmur3(h1 + path, true);
  7488. return key;
  7489. }
  7490. /**
  7491. * [ext-clones] Return a list of clone-nodes (i.e. same refKey) or null.
  7492. * @param {boolean} [includeSelf=false]
  7493. * @returns {FancytreeNode[] | null}
  7494. *
  7495. * @alias FancytreeNode#getCloneList
  7496. * @requires jquery.fancytree.clones.js
  7497. */
  7498. $.ui.fancytree._FancytreeNodeClass.prototype.getCloneList = function (
  7499. includeSelf
  7500. ) {
  7501. var key,
  7502. tree = this.tree,
  7503. refList = tree.refMap[this.refKey] || null,
  7504. keyMap = tree.keyMap;
  7505. if (refList) {
  7506. key = this.key;
  7507. // Convert key list to node list
  7508. if (includeSelf) {
  7509. refList = $.map(refList, function (val) {
  7510. return keyMap[val];
  7511. });
  7512. } else {
  7513. refList = $.map(refList, function (val) {
  7514. return val === key ? null : keyMap[val];
  7515. });
  7516. if (refList.length < 1) {
  7517. refList = null;
  7518. }
  7519. }
  7520. }
  7521. return refList;
  7522. };
  7523. /**
  7524. * [ext-clones] Return true if this node has at least another clone with same refKey.
  7525. * @returns {boolean}
  7526. *
  7527. * @alias FancytreeNode#isClone
  7528. * @requires jquery.fancytree.clones.js
  7529. */
  7530. $.ui.fancytree._FancytreeNodeClass.prototype.isClone = function () {
  7531. var refKey = this.refKey || null,
  7532. refList = (refKey && this.tree.refMap[refKey]) || null;
  7533. return !!(refList && refList.length > 1);
  7534. };
  7535. /**
  7536. * [ext-clones] Update key and/or refKey for an existing node.
  7537. * @param {string} key
  7538. * @param {string} refKey
  7539. * @returns {boolean}
  7540. *
  7541. * @alias FancytreeNode#reRegister
  7542. * @requires jquery.fancytree.clones.js
  7543. */
  7544. $.ui.fancytree._FancytreeNodeClass.prototype.reRegister = function (
  7545. key,
  7546. refKey
  7547. ) {
  7548. key = key == null ? null : "" + key;
  7549. refKey = refKey == null ? null : "" + refKey;
  7550. // this.debug("reRegister", key, refKey);
  7551. var tree = this.tree,
  7552. prevKey = this.key,
  7553. prevRefKey = this.refKey,
  7554. keyMap = tree.keyMap,
  7555. refMap = tree.refMap,
  7556. refList = refMap[prevRefKey] || null,
  7557. // curCloneKeys = refList ? node.getCloneList(true),
  7558. modified = false;
  7559. // Key has changed: update all references
  7560. if (key != null && key !== this.key) {
  7561. if (keyMap[key]) {
  7562. $.error(
  7563. "[ext-clones] reRegister(" +
  7564. key +
  7565. "): already exists: " +
  7566. this
  7567. );
  7568. }
  7569. // Update keyMap
  7570. delete keyMap[prevKey];
  7571. keyMap[key] = this;
  7572. // Update refMap
  7573. if (refList) {
  7574. refMap[prevRefKey] = $.map(refList, function (e) {
  7575. return e === prevKey ? key : e;
  7576. });
  7577. }
  7578. this.key = key;
  7579. modified = true;
  7580. }
  7581. // refKey has changed
  7582. if (refKey != null && refKey !== this.refKey) {
  7583. // Remove previous refKeys
  7584. if (refList) {
  7585. if (refList.length === 1) {
  7586. delete refMap[prevRefKey];
  7587. } else {
  7588. refMap[prevRefKey] = $.map(refList, function (e) {
  7589. return e === prevKey ? null : e;
  7590. });
  7591. }
  7592. }
  7593. // Add refKey
  7594. if (refMap[refKey]) {
  7595. refMap[refKey].append(key);
  7596. } else {
  7597. refMap[refKey] = [this.key];
  7598. }
  7599. this.refKey = refKey;
  7600. modified = true;
  7601. }
  7602. return modified;
  7603. };
  7604. /**
  7605. * [ext-clones] Define a refKey for an existing node.
  7606. * @param {string} refKey
  7607. * @returns {boolean}
  7608. *
  7609. * @alias FancytreeNode#setRefKey
  7610. * @requires jquery.fancytree.clones.js
  7611. * @since 2.16
  7612. */
  7613. $.ui.fancytree._FancytreeNodeClass.prototype.setRefKey = function (refKey) {
  7614. return this.reRegister(null, refKey);
  7615. };
  7616. /**
  7617. * [ext-clones] Return all nodes with a given refKey (null if not found).
  7618. * @param {string} refKey
  7619. * @param {FancytreeNode} [rootNode] optionally restrict results to descendants of this node
  7620. * @returns {FancytreeNode[] | null}
  7621. * @alias Fancytree#getNodesByRef
  7622. * @requires jquery.fancytree.clones.js
  7623. */
  7624. $.ui.fancytree._FancytreeClass.prototype.getNodesByRef = function (
  7625. refKey,
  7626. rootNode
  7627. ) {
  7628. var keyMap = this.keyMap,
  7629. refList = this.refMap[refKey] || null;
  7630. if (refList) {
  7631. // Convert key list to node list
  7632. if (rootNode) {
  7633. refList = $.map(refList, function (val) {
  7634. var node = keyMap[val];
  7635. return node.isDescendantOf(rootNode) ? node : null;
  7636. });
  7637. } else {
  7638. refList = $.map(refList, function (val) {
  7639. return keyMap[val];
  7640. });
  7641. }
  7642. if (refList.length < 1) {
  7643. refList = null;
  7644. }
  7645. }
  7646. return refList;
  7647. };
  7648. /**
  7649. * [ext-clones] Replace a refKey with a new one.
  7650. * @param {string} oldRefKey
  7651. * @param {string} newRefKey
  7652. * @alias Fancytree#changeRefKey
  7653. * @requires jquery.fancytree.clones.js
  7654. */
  7655. $.ui.fancytree._FancytreeClass.prototype.changeRefKey = function (
  7656. oldRefKey,
  7657. newRefKey
  7658. ) {
  7659. var i,
  7660. node,
  7661. keyMap = this.keyMap,
  7662. refList = this.refMap[oldRefKey] || null;
  7663. if (refList) {
  7664. for (i = 0; i < refList.length; i++) {
  7665. node = keyMap[refList[i]];
  7666. node.refKey = newRefKey;
  7667. }
  7668. delete this.refMap[oldRefKey];
  7669. this.refMap[newRefKey] = refList;
  7670. }
  7671. };
  7672. /*******************************************************************************
  7673. * Extension code
  7674. */
  7675. $.ui.fancytree.registerExtension({
  7676. name: "clones",
  7677. version: "2.38.3",
  7678. // Default options for this extension.
  7679. options: {
  7680. highlightActiveClones: true, // set 'fancytree-active-clone' on active clones and all peers
  7681. highlightClones: false, // set 'fancytree-clone' class on any node that has at least one clone
  7682. },
  7683. treeCreate: function (ctx) {
  7684. this._superApply(arguments);
  7685. ctx.tree.refMap = {};
  7686. ctx.tree.keyMap = {};
  7687. },
  7688. treeInit: function (ctx) {
  7689. this.$container.addClass("fancytree-ext-clones");
  7690. _assert(ctx.options.defaultKey == null);
  7691. // Generate unique / reproducible default keys
  7692. ctx.options.defaultKey = function (node) {
  7693. return calcUniqueKey(node);
  7694. };
  7695. // The default implementation loads initial data
  7696. this._superApply(arguments);
  7697. },
  7698. treeClear: function (ctx) {
  7699. ctx.tree.refMap = {};
  7700. ctx.tree.keyMap = {};
  7701. return this._superApply(arguments);
  7702. },
  7703. treeRegisterNode: function (ctx, add, node) {
  7704. var refList,
  7705. len,
  7706. tree = ctx.tree,
  7707. keyMap = tree.keyMap,
  7708. refMap = tree.refMap,
  7709. key = node.key,
  7710. refKey = node && node.refKey != null ? "" + node.refKey : null;
  7711. // ctx.tree.debug("clones.treeRegisterNode", add, node);
  7712. if (node.isStatusNode()) {
  7713. return this._super(ctx, add, node);
  7714. }
  7715. if (add) {
  7716. if (keyMap[node.key] != null) {
  7717. var other = keyMap[node.key],
  7718. msg =
  7719. "clones.treeRegisterNode: duplicate key '" +
  7720. node.key +
  7721. "': /" +
  7722. node.getPath(true) +
  7723. " => " +
  7724. other.getPath(true);
  7725. // Sometimes this exception is not visible in the console,
  7726. // so we also write it:
  7727. tree.error(msg);
  7728. $.error(msg);
  7729. }
  7730. keyMap[key] = node;
  7731. if (refKey) {
  7732. refList = refMap[refKey];
  7733. if (refList) {
  7734. refList.push(key);
  7735. if (
  7736. refList.length === 2 &&
  7737. ctx.options.clones.highlightClones
  7738. ) {
  7739. // Mark peer node, if it just became a clone (no need to
  7740. // mark current node, since it will be rendered later anyway)
  7741. keyMap[refList[0]].renderStatus();
  7742. }
  7743. } else {
  7744. refMap[refKey] = [key];
  7745. }
  7746. // node.debug("clones.treeRegisterNode: add clone =>", refMap[refKey]);
  7747. }
  7748. } else {
  7749. if (keyMap[key] == null) {
  7750. $.error(
  7751. "clones.treeRegisterNode: node.key not registered: " +
  7752. node.key
  7753. );
  7754. }
  7755. delete keyMap[key];
  7756. if (refKey) {
  7757. refList = refMap[refKey];
  7758. // node.debug("clones.treeRegisterNode: remove clone BEFORE =>", refMap[refKey]);
  7759. if (refList) {
  7760. len = refList.length;
  7761. if (len <= 1) {
  7762. _assert(len === 1);
  7763. _assert(refList[0] === key);
  7764. delete refMap[refKey];
  7765. } else {
  7766. _removeArrayMember(refList, key);
  7767. // Unmark peer node, if this was the only clone
  7768. if (
  7769. len === 2 &&
  7770. ctx.options.clones.highlightClones
  7771. ) {
  7772. // node.debug("clones.treeRegisterNode: last =>", node.getCloneList());
  7773. keyMap[refList[0]].renderStatus();
  7774. }
  7775. }
  7776. // node.debug("clones.treeRegisterNode: remove clone =>", refMap[refKey]);
  7777. }
  7778. }
  7779. }
  7780. return this._super(ctx, add, node);
  7781. },
  7782. nodeRenderStatus: function (ctx) {
  7783. var $span,
  7784. res,
  7785. node = ctx.node;
  7786. res = this._super(ctx);
  7787. if (ctx.options.clones.highlightClones) {
  7788. $span = $(node[ctx.tree.statusClassPropName]);
  7789. // Only if span already exists
  7790. if ($span.length && node.isClone()) {
  7791. // node.debug("clones.nodeRenderStatus: ", ctx.options.clones.highlightClones);
  7792. $span.addClass("fancytree-clone");
  7793. }
  7794. }
  7795. return res;
  7796. },
  7797. nodeSetActive: function (ctx, flag, callOpts) {
  7798. var res,
  7799. scpn = ctx.tree.statusClassPropName,
  7800. node = ctx.node;
  7801. res = this._superApply(arguments);
  7802. if (ctx.options.clones.highlightActiveClones && node.isClone()) {
  7803. $.each(node.getCloneList(true), function (idx, n) {
  7804. // n.debug("clones.nodeSetActive: ", flag !== false);
  7805. $(n[scpn]).toggleClass(
  7806. "fancytree-active-clone",
  7807. flag !== false
  7808. );
  7809. });
  7810. }
  7811. return res;
  7812. },
  7813. });
  7814. // Value returned by `require('jquery.fancytree..')`
  7815. return $.ui.fancytree;
  7816. }); // End of closure
  7817. /*!
  7818. * jquery.fancytree.dnd.js
  7819. *
  7820. * Drag-and-drop support (jQuery UI draggable/droppable).
  7821. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  7822. *
  7823. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  7824. *
  7825. * Released under the MIT license
  7826. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  7827. *
  7828. * @version 2.38.3
  7829. * @date 2023-02-01T20:52:50Z
  7830. */
  7831. (function (factory) {
  7832. if (typeof define === "function" && define.amd) {
  7833. // AMD. Register as an anonymous module.
  7834. define([
  7835. "jquery",
  7836. "jquery-ui/ui/widgets/draggable",
  7837. "jquery-ui/ui/widgets/droppable",
  7838. "./jquery.fancytree",
  7839. ], factory);
  7840. } else if (typeof module === "object" && module.exports) {
  7841. // Node/CommonJS
  7842. require("./jquery.fancytree");
  7843. module.exports = factory(require("jquery"));
  7844. } else {
  7845. // Browser globals
  7846. factory(jQuery);
  7847. }
  7848. })(function ($) {
  7849. "use strict";
  7850. /******************************************************************************
  7851. * Private functions and variables
  7852. */
  7853. var didRegisterDnd = false,
  7854. classDropAccept = "fancytree-drop-accept",
  7855. classDropAfter = "fancytree-drop-after",
  7856. classDropBefore = "fancytree-drop-before",
  7857. classDropOver = "fancytree-drop-over",
  7858. classDropReject = "fancytree-drop-reject",
  7859. classDropTarget = "fancytree-drop-target";
  7860. /* Convert number to string and prepend +/-; return empty string for 0.*/
  7861. function offsetString(n) {
  7862. // eslint-disable-next-line no-nested-ternary
  7863. return n === 0 ? "" : n > 0 ? "+" + n : "" + n;
  7864. }
  7865. //--- Extend ui.draggable event handling --------------------------------------
  7866. function _registerDnd() {
  7867. if (didRegisterDnd) {
  7868. return;
  7869. }
  7870. // Register proxy-functions for draggable.start/drag/stop
  7871. $.ui.plugin.add("draggable", "connectToFancytree", {
  7872. start: function (event, ui) {
  7873. // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
  7874. var draggable =
  7875. $(this).data("ui-draggable") ||
  7876. $(this).data("draggable"),
  7877. sourceNode = ui.helper.data("ftSourceNode") || null;
  7878. if (sourceNode) {
  7879. // Adjust helper offset, so cursor is slightly outside top/left corner
  7880. draggable.offset.click.top = -2;
  7881. draggable.offset.click.left = +16;
  7882. // Trigger dragStart event
  7883. // TODO: when called as connectTo..., the return value is ignored(?)
  7884. return sourceNode.tree.ext.dnd._onDragEvent(
  7885. "start",
  7886. sourceNode,
  7887. null,
  7888. event,
  7889. ui,
  7890. draggable
  7891. );
  7892. }
  7893. },
  7894. drag: function (event, ui) {
  7895. var ctx,
  7896. isHelper,
  7897. logObject,
  7898. // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10
  7899. draggable =
  7900. $(this).data("ui-draggable") ||
  7901. $(this).data("draggable"),
  7902. sourceNode = ui.helper.data("ftSourceNode") || null,
  7903. prevTargetNode = ui.helper.data("ftTargetNode") || null,
  7904. targetNode = $.ui.fancytree.getNode(event.target),
  7905. dndOpts = sourceNode && sourceNode.tree.options.dnd;
  7906. // logObject = sourceNode || prevTargetNode || $.ui.fancytree;
  7907. // logObject.debug("Drag event:", event, event.shiftKey);
  7908. if (event.target && !targetNode) {
  7909. // We got a drag event, but the targetNode could not be found
  7910. // at the event location. This may happen,
  7911. // 1. if the mouse jumped over the drag helper,
  7912. // 2. or if a non-fancytree element is dragged
  7913. // We ignore it:
  7914. isHelper =
  7915. $(event.target).closest(
  7916. "div.fancytree-drag-helper,#fancytree-drop-marker"
  7917. ).length > 0;
  7918. if (isHelper) {
  7919. logObject =
  7920. sourceNode || prevTargetNode || $.ui.fancytree;
  7921. logObject.debug("Drag event over helper: ignored.");
  7922. return;
  7923. }
  7924. }
  7925. ui.helper.data("ftTargetNode", targetNode);
  7926. if (dndOpts && dndOpts.updateHelper) {
  7927. ctx = sourceNode.tree._makeHookContext(sourceNode, event, {
  7928. otherNode: targetNode,
  7929. ui: ui,
  7930. draggable: draggable,
  7931. dropMarker: $("#fancytree-drop-marker"),
  7932. });
  7933. dndOpts.updateHelper.call(sourceNode.tree, sourceNode, ctx);
  7934. }
  7935. // Leaving a tree node
  7936. if (prevTargetNode && prevTargetNode !== targetNode) {
  7937. prevTargetNode.tree.ext.dnd._onDragEvent(
  7938. "leave",
  7939. prevTargetNode,
  7940. sourceNode,
  7941. event,
  7942. ui,
  7943. draggable
  7944. );
  7945. }
  7946. if (targetNode) {
  7947. if (!targetNode.tree.options.dnd.dragDrop) {
  7948. // not enabled as drop target
  7949. } else if (targetNode === prevTargetNode) {
  7950. // Moving over same node
  7951. targetNode.tree.ext.dnd._onDragEvent(
  7952. "over",
  7953. targetNode,
  7954. sourceNode,
  7955. event,
  7956. ui,
  7957. draggable
  7958. );
  7959. } else {
  7960. // Entering this node first time
  7961. targetNode.tree.ext.dnd._onDragEvent(
  7962. "enter",
  7963. targetNode,
  7964. sourceNode,
  7965. event,
  7966. ui,
  7967. draggable
  7968. );
  7969. targetNode.tree.ext.dnd._onDragEvent(
  7970. "over",
  7971. targetNode,
  7972. sourceNode,
  7973. event,
  7974. ui,
  7975. draggable
  7976. );
  7977. }
  7978. }
  7979. // else go ahead with standard event handling
  7980. },
  7981. stop: function (event, ui) {
  7982. var logObject,
  7983. // 'draggable' was renamed to 'ui-draggable' since jQueryUI 1.10:
  7984. draggable =
  7985. $(this).data("ui-draggable") ||
  7986. $(this).data("draggable"),
  7987. sourceNode = ui.helper.data("ftSourceNode") || null,
  7988. targetNode = ui.helper.data("ftTargetNode") || null,
  7989. dropped = event.type === "mouseup" && event.which === 1;
  7990. if (!dropped) {
  7991. logObject = sourceNode || targetNode || $.ui.fancytree;
  7992. logObject.debug("Drag was cancelled");
  7993. }
  7994. if (targetNode) {
  7995. if (dropped) {
  7996. targetNode.tree.ext.dnd._onDragEvent(
  7997. "drop",
  7998. targetNode,
  7999. sourceNode,
  8000. event,
  8001. ui,
  8002. draggable
  8003. );
  8004. }
  8005. targetNode.tree.ext.dnd._onDragEvent(
  8006. "leave",
  8007. targetNode,
  8008. sourceNode,
  8009. event,
  8010. ui,
  8011. draggable
  8012. );
  8013. }
  8014. if (sourceNode) {
  8015. sourceNode.tree.ext.dnd._onDragEvent(
  8016. "stop",
  8017. sourceNode,
  8018. null,
  8019. event,
  8020. ui,
  8021. draggable
  8022. );
  8023. }
  8024. },
  8025. });
  8026. didRegisterDnd = true;
  8027. }
  8028. /******************************************************************************
  8029. * Drag and drop support
  8030. */
  8031. function _initDragAndDrop(tree) {
  8032. var dnd = tree.options.dnd || null,
  8033. glyph = tree.options.glyph || null;
  8034. // Register 'connectToFancytree' option with ui.draggable
  8035. if (dnd) {
  8036. _registerDnd();
  8037. }
  8038. // Attach ui.draggable to this Fancytree instance
  8039. if (dnd && dnd.dragStart) {
  8040. tree.widget.element.draggable(
  8041. $.extend(
  8042. {
  8043. addClasses: false,
  8044. // DT issue 244: helper should be child of scrollParent:
  8045. appendTo: tree.$container,
  8046. // appendTo: "body",
  8047. containment: false,
  8048. // containment: "parent",
  8049. delay: 0,
  8050. distance: 4,
  8051. revert: false,
  8052. scroll: true, // to disable, also set css 'position: inherit' on ul.fancytree-container
  8053. scrollSpeed: 7,
  8054. scrollSensitivity: 10,
  8055. // Delegate draggable.start, drag, and stop events to our handler
  8056. connectToFancytree: true,
  8057. // Let source tree create the helper element
  8058. helper: function (event) {
  8059. var $helper,
  8060. $nodeTag,
  8061. opts,
  8062. sourceNode = $.ui.fancytree.getNode(
  8063. event.target
  8064. );
  8065. if (!sourceNode) {
  8066. // #405, DT issue 211: might happen, if dragging a table *header*
  8067. return "<div>ERROR?: helper requested but sourceNode not found</div>";
  8068. }
  8069. opts = sourceNode.tree.options.dnd;
  8070. $nodeTag = $(sourceNode.span);
  8071. // Only event and node argument is available
  8072. $helper = $(
  8073. "<div class='fancytree-drag-helper'><span class='fancytree-drag-helper-img' /></div>"
  8074. )
  8075. .css({ zIndex: 3, position: "relative" }) // so it appears above ext-wide selection bar
  8076. .append(
  8077. $nodeTag
  8078. .find("span.fancytree-title")
  8079. .clone()
  8080. );
  8081. // Attach node reference to helper object
  8082. $helper.data("ftSourceNode", sourceNode);
  8083. // Support glyph symbols instead of icons
  8084. if (glyph) {
  8085. $helper
  8086. .find(".fancytree-drag-helper-img")
  8087. .addClass(
  8088. glyph.map._addClass +
  8089. " " +
  8090. glyph.map.dragHelper
  8091. );
  8092. }
  8093. // Allow to modify the helper, e.g. to add multi-node-drag feedback
  8094. if (opts.initHelper) {
  8095. opts.initHelper.call(
  8096. sourceNode.tree,
  8097. sourceNode,
  8098. {
  8099. node: sourceNode,
  8100. tree: sourceNode.tree,
  8101. originalEvent: event,
  8102. ui: { helper: $helper },
  8103. }
  8104. );
  8105. }
  8106. // We return an unconnected element, so `draggable` will add this
  8107. // to the parent specified as `appendTo` option
  8108. return $helper;
  8109. },
  8110. start: function (event, ui) {
  8111. var sourceNode = ui.helper.data("ftSourceNode");
  8112. return !!sourceNode; // Abort dragging if no node could be found
  8113. },
  8114. },
  8115. tree.options.dnd.draggable
  8116. )
  8117. );
  8118. }
  8119. // Attach ui.droppable to this Fancytree instance
  8120. if (dnd && dnd.dragDrop) {
  8121. tree.widget.element.droppable(
  8122. $.extend(
  8123. {
  8124. addClasses: false,
  8125. tolerance: "intersect",
  8126. greedy: false,
  8127. /*
  8128. activate: function(event, ui) {
  8129. tree.debug("droppable - activate", event, ui, this);
  8130. },
  8131. create: function(event, ui) {
  8132. tree.debug("droppable - create", event, ui);
  8133. },
  8134. deactivate: function(event, ui) {
  8135. tree.debug("droppable - deactivate", event, ui);
  8136. },
  8137. drop: function(event, ui) {
  8138. tree.debug("droppable - drop", event, ui);
  8139. },
  8140. out: function(event, ui) {
  8141. tree.debug("droppable - out", event, ui);
  8142. },
  8143. over: function(event, ui) {
  8144. tree.debug("droppable - over", event, ui);
  8145. }
  8146. */
  8147. },
  8148. tree.options.dnd.droppable
  8149. )
  8150. );
  8151. }
  8152. }
  8153. /******************************************************************************
  8154. *
  8155. */
  8156. $.ui.fancytree.registerExtension({
  8157. name: "dnd",
  8158. version: "2.38.3",
  8159. // Default options for this extension.
  8160. options: {
  8161. // Make tree nodes accept draggables
  8162. autoExpandMS: 1000, // Expand nodes after n milliseconds of hovering.
  8163. draggable: null, // Additional options passed to jQuery draggable
  8164. droppable: null, // Additional options passed to jQuery droppable
  8165. focusOnClick: false, // Focus, although draggable cancels mousedown event (#270)
  8166. preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
  8167. preventRecursiveMoves: true, // Prevent dropping nodes on own descendants
  8168. smartRevert: true, // set draggable.revert = true if drop was rejected
  8169. dropMarkerOffsetX: -24, // absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop)
  8170. dropMarkerInsertOffsetX: -16, // additional offset for drop-marker with hitMode = "before"/"after"
  8171. // Events (drag support)
  8172. dragStart: null, // Callback(sourceNode, data), return true, to enable dnd
  8173. dragStop: null, // Callback(sourceNode, data)
  8174. initHelper: null, // Callback(sourceNode, data)
  8175. updateHelper: null, // Callback(sourceNode, data)
  8176. // Events (drop support)
  8177. dragEnter: null, // Callback(targetNode, data)
  8178. dragOver: null, // Callback(targetNode, data)
  8179. dragExpand: null, // Callback(targetNode, data), return false to prevent autoExpand
  8180. dragDrop: null, // Callback(targetNode, data)
  8181. dragLeave: null, // Callback(targetNode, data)
  8182. },
  8183. treeInit: function (ctx) {
  8184. var tree = ctx.tree;
  8185. this._superApply(arguments);
  8186. // issue #270: draggable eats mousedown events
  8187. if (tree.options.dnd.dragStart) {
  8188. tree.$container.on("mousedown", function (event) {
  8189. // if( !tree.hasFocus() && ctx.options.dnd.focusOnClick ) {
  8190. if (ctx.options.dnd.focusOnClick) {
  8191. // #270
  8192. var node = $.ui.fancytree.getNode(event);
  8193. if (node) {
  8194. node.debug(
  8195. "Re-enable focus that was prevented by jQuery UI draggable."
  8196. );
  8197. // node.setFocus();
  8198. // $(node.span).closest(":tabbable").focus();
  8199. // $(event.target).trigger("focus");
  8200. // $(event.target).closest(":tabbable").trigger("focus");
  8201. }
  8202. setTimeout(function () {
  8203. // #300
  8204. $(event.target).closest(":tabbable").focus();
  8205. }, 10);
  8206. }
  8207. });
  8208. }
  8209. _initDragAndDrop(tree);
  8210. },
  8211. /* Display drop marker according to hitMode ('after', 'before', 'over'). */
  8212. _setDndStatus: function (
  8213. sourceNode,
  8214. targetNode,
  8215. helper,
  8216. hitMode,
  8217. accept
  8218. ) {
  8219. var markerOffsetX,
  8220. pos,
  8221. markerAt = "center",
  8222. instData = this._local,
  8223. dndOpt = this.options.dnd,
  8224. glyphOpt = this.options.glyph,
  8225. $source = sourceNode ? $(sourceNode.span) : null,
  8226. $target = $(targetNode.span),
  8227. $targetTitle = $target.find("span.fancytree-title");
  8228. if (!instData.$dropMarker) {
  8229. instData.$dropMarker = $(
  8230. "<div id='fancytree-drop-marker'></div>"
  8231. )
  8232. .hide()
  8233. .css({ "z-index": 1000 })
  8234. .prependTo($(this.$div).parent());
  8235. // .prependTo("body");
  8236. if (glyphOpt) {
  8237. instData.$dropMarker.addClass(
  8238. glyphOpt.map._addClass + " " + glyphOpt.map.dropMarker
  8239. );
  8240. }
  8241. }
  8242. if (
  8243. hitMode === "after" ||
  8244. hitMode === "before" ||
  8245. hitMode === "over"
  8246. ) {
  8247. markerOffsetX = dndOpt.dropMarkerOffsetX || 0;
  8248. switch (hitMode) {
  8249. case "before":
  8250. markerAt = "top";
  8251. markerOffsetX += dndOpt.dropMarkerInsertOffsetX || 0;
  8252. break;
  8253. case "after":
  8254. markerAt = "bottom";
  8255. markerOffsetX += dndOpt.dropMarkerInsertOffsetX || 0;
  8256. break;
  8257. }
  8258. pos = {
  8259. my: "left" + offsetString(markerOffsetX) + " center",
  8260. at: "left " + markerAt,
  8261. of: $targetTitle,
  8262. };
  8263. if (this.options.rtl) {
  8264. pos.my = "right" + offsetString(-markerOffsetX) + " center";
  8265. pos.at = "right " + markerAt;
  8266. }
  8267. instData.$dropMarker
  8268. .toggleClass(classDropAfter, hitMode === "after")
  8269. .toggleClass(classDropOver, hitMode === "over")
  8270. .toggleClass(classDropBefore, hitMode === "before")
  8271. .toggleClass("fancytree-rtl", !!this.options.rtl)
  8272. .show()
  8273. .position($.ui.fancytree.fixPositionOptions(pos));
  8274. } else {
  8275. instData.$dropMarker.hide();
  8276. }
  8277. if ($source) {
  8278. $source
  8279. .toggleClass(classDropAccept, accept === true)
  8280. .toggleClass(classDropReject, accept === false);
  8281. }
  8282. $target
  8283. .toggleClass(
  8284. classDropTarget,
  8285. hitMode === "after" ||
  8286. hitMode === "before" ||
  8287. hitMode === "over"
  8288. )
  8289. .toggleClass(classDropAfter, hitMode === "after")
  8290. .toggleClass(classDropBefore, hitMode === "before")
  8291. .toggleClass(classDropAccept, accept === true)
  8292. .toggleClass(classDropReject, accept === false);
  8293. helper
  8294. .toggleClass(classDropAccept, accept === true)
  8295. .toggleClass(classDropReject, accept === false);
  8296. },
  8297. /*
  8298. * Handles drag'n'drop functionality.
  8299. *
  8300. * A standard jQuery drag-and-drop process may generate these calls:
  8301. *
  8302. * start:
  8303. * _onDragEvent("start", sourceNode, null, event, ui, draggable);
  8304. * drag:
  8305. * _onDragEvent("leave", prevTargetNode, sourceNode, event, ui, draggable);
  8306. * _onDragEvent("over", targetNode, sourceNode, event, ui, draggable);
  8307. * _onDragEvent("enter", targetNode, sourceNode, event, ui, draggable);
  8308. * stop:
  8309. * _onDragEvent("drop", targetNode, sourceNode, event, ui, draggable);
  8310. * _onDragEvent("leave", targetNode, sourceNode, event, ui, draggable);
  8311. * _onDragEvent("stop", sourceNode, null, event, ui, draggable);
  8312. */
  8313. _onDragEvent: function (
  8314. eventName,
  8315. node,
  8316. otherNode,
  8317. event,
  8318. ui,
  8319. draggable
  8320. ) {
  8321. // if(eventName !== "over"){
  8322. // this.debug("tree.ext.dnd._onDragEvent(%s, %o, %o) - %o", eventName, node, otherNode, this);
  8323. // }
  8324. var accept,
  8325. nodeOfs,
  8326. parentRect,
  8327. rect,
  8328. relPos,
  8329. relPos2,
  8330. enterResponse,
  8331. hitMode,
  8332. r,
  8333. opts = this.options,
  8334. dnd = opts.dnd,
  8335. ctx = this._makeHookContext(node, event, {
  8336. otherNode: otherNode,
  8337. ui: ui,
  8338. draggable: draggable,
  8339. }),
  8340. res = null,
  8341. self = this,
  8342. $nodeTag = $(node.span);
  8343. if (dnd.smartRevert) {
  8344. draggable.options.revert = "invalid";
  8345. }
  8346. switch (eventName) {
  8347. case "start":
  8348. if (node.isStatusNode()) {
  8349. res = false;
  8350. } else if (dnd.dragStart) {
  8351. res = dnd.dragStart(node, ctx);
  8352. }
  8353. if (res === false) {
  8354. this.debug("tree.dragStart() cancelled");
  8355. //draggable._clear();
  8356. // NOTE: the return value seems to be ignored (drag is not cancelled, when false is returned)
  8357. // TODO: call this._cancelDrag()?
  8358. ui.helper.trigger("mouseup").hide();
  8359. } else {
  8360. if (dnd.smartRevert) {
  8361. // #567, #593: fix revert position
  8362. // rect = node.li.getBoundingClientRect();
  8363. rect =
  8364. node[
  8365. ctx.tree.nodeContainerAttrName
  8366. ].getBoundingClientRect();
  8367. parentRect = $(
  8368. draggable.options.appendTo
  8369. )[0].getBoundingClientRect();
  8370. draggable.originalPosition.left = Math.max(
  8371. 0,
  8372. rect.left - parentRect.left
  8373. );
  8374. draggable.originalPosition.top = Math.max(
  8375. 0,
  8376. rect.top - parentRect.top
  8377. );
  8378. }
  8379. $nodeTag.addClass("fancytree-drag-source");
  8380. // Register global handlers to allow cancel
  8381. $(document).on(
  8382. "keydown.fancytree-dnd,mousedown.fancytree-dnd",
  8383. function (event) {
  8384. // node.tree.debug("dnd global event", event.type, event.which);
  8385. if (
  8386. event.type === "keydown" &&
  8387. event.which === $.ui.keyCode.ESCAPE
  8388. ) {
  8389. self.ext.dnd._cancelDrag();
  8390. } else if (event.type === "mousedown") {
  8391. self.ext.dnd._cancelDrag();
  8392. }
  8393. }
  8394. );
  8395. }
  8396. break;
  8397. case "enter":
  8398. if (
  8399. dnd.preventRecursiveMoves &&
  8400. node.isDescendantOf(otherNode)
  8401. ) {
  8402. r = false;
  8403. } else {
  8404. r = dnd.dragEnter ? dnd.dragEnter(node, ctx) : null;
  8405. }
  8406. if (!r) {
  8407. // convert null, undefined, false to false
  8408. res = false;
  8409. } else if (Array.isArray(r)) {
  8410. // TODO: also accept passing an object of this format directly
  8411. res = {
  8412. over: $.inArray("over", r) >= 0,
  8413. before: $.inArray("before", r) >= 0,
  8414. after: $.inArray("after", r) >= 0,
  8415. };
  8416. } else {
  8417. res = {
  8418. over: r === true || r === "over",
  8419. before: r === true || r === "before",
  8420. after: r === true || r === "after",
  8421. };
  8422. }
  8423. ui.helper.data("enterResponse", res);
  8424. // this.debug("helper.enterResponse: %o", res);
  8425. break;
  8426. case "over":
  8427. enterResponse = ui.helper.data("enterResponse");
  8428. hitMode = null;
  8429. if (enterResponse === false) {
  8430. // Don't call dragOver if onEnter returned false.
  8431. // break;
  8432. } else if (typeof enterResponse === "string") {
  8433. // Use hitMode from onEnter if provided.
  8434. hitMode = enterResponse;
  8435. } else {
  8436. // Calculate hitMode from relative cursor position.
  8437. nodeOfs = $nodeTag.offset();
  8438. relPos = {
  8439. x: event.pageX - nodeOfs.left,
  8440. y: event.pageY - nodeOfs.top,
  8441. };
  8442. relPos2 = {
  8443. x: relPos.x / $nodeTag.width(),
  8444. y: relPos.y / $nodeTag.height(),
  8445. };
  8446. if (enterResponse.after && relPos2.y > 0.75) {
  8447. hitMode = "after";
  8448. } else if (
  8449. !enterResponse.over &&
  8450. enterResponse.after &&
  8451. relPos2.y > 0.5
  8452. ) {
  8453. hitMode = "after";
  8454. } else if (enterResponse.before && relPos2.y <= 0.25) {
  8455. hitMode = "before";
  8456. } else if (
  8457. !enterResponse.over &&
  8458. enterResponse.before &&
  8459. relPos2.y <= 0.5
  8460. ) {
  8461. hitMode = "before";
  8462. } else if (enterResponse.over) {
  8463. hitMode = "over";
  8464. }
  8465. // Prevent no-ops like 'before source node'
  8466. // TODO: these are no-ops when moving nodes, but not in copy mode
  8467. if (dnd.preventVoidMoves) {
  8468. if (node === otherNode) {
  8469. this.debug(
  8470. " drop over source node prevented"
  8471. );
  8472. hitMode = null;
  8473. } else if (
  8474. hitMode === "before" &&
  8475. otherNode &&
  8476. node === otherNode.getNextSibling()
  8477. ) {
  8478. this.debug(
  8479. " drop after source node prevented"
  8480. );
  8481. hitMode = null;
  8482. } else if (
  8483. hitMode === "after" &&
  8484. otherNode &&
  8485. node === otherNode.getPrevSibling()
  8486. ) {
  8487. this.debug(
  8488. " drop before source node prevented"
  8489. );
  8490. hitMode = null;
  8491. } else if (
  8492. hitMode === "over" &&
  8493. otherNode &&
  8494. otherNode.parent === node &&
  8495. otherNode.isLastSibling()
  8496. ) {
  8497. this.debug(
  8498. " drop last child over own parent prevented"
  8499. );
  8500. hitMode = null;
  8501. }
  8502. }
  8503. // this.debug("hitMode: %s - %s - %s", hitMode, (node.parent === otherNode), node.isLastSibling());
  8504. ui.helper.data("hitMode", hitMode);
  8505. }
  8506. // Auto-expand node (only when 'over' the node, not 'before', or 'after')
  8507. if (
  8508. hitMode !== "before" &&
  8509. hitMode !== "after" &&
  8510. dnd.autoExpandMS &&
  8511. node.hasChildren() !== false &&
  8512. !node.expanded &&
  8513. (!dnd.dragExpand || dnd.dragExpand(node, ctx) !== false)
  8514. ) {
  8515. node.scheduleAction("expand", dnd.autoExpandMS);
  8516. }
  8517. if (hitMode && dnd.dragOver) {
  8518. // TODO: http://code.google.com/p/dynatree/source/detail?r=625
  8519. ctx.hitMode = hitMode;
  8520. res = dnd.dragOver(node, ctx);
  8521. }
  8522. accept = res !== false && hitMode !== null;
  8523. if (dnd.smartRevert) {
  8524. draggable.options.revert = !accept;
  8525. }
  8526. this._local._setDndStatus(
  8527. otherNode,
  8528. node,
  8529. ui.helper,
  8530. hitMode,
  8531. accept
  8532. );
  8533. break;
  8534. case "drop":
  8535. hitMode = ui.helper.data("hitMode");
  8536. if (hitMode && dnd.dragDrop) {
  8537. ctx.hitMode = hitMode;
  8538. dnd.dragDrop(node, ctx);
  8539. }
  8540. break;
  8541. case "leave":
  8542. // Cancel pending expand request
  8543. node.scheduleAction("cancel");
  8544. ui.helper.data("enterResponse", null);
  8545. ui.helper.data("hitMode", null);
  8546. this._local._setDndStatus(
  8547. otherNode,
  8548. node,
  8549. ui.helper,
  8550. "out",
  8551. undefined
  8552. );
  8553. if (dnd.dragLeave) {
  8554. dnd.dragLeave(node, ctx);
  8555. }
  8556. break;
  8557. case "stop":
  8558. $nodeTag.removeClass("fancytree-drag-source");
  8559. $(document).off(".fancytree-dnd");
  8560. if (dnd.dragStop) {
  8561. dnd.dragStop(node, ctx);
  8562. }
  8563. break;
  8564. default:
  8565. $.error("Unsupported drag event: " + eventName);
  8566. }
  8567. return res;
  8568. },
  8569. _cancelDrag: function () {
  8570. var dd = $.ui.ddmanager.current;
  8571. if (dd) {
  8572. dd.cancel();
  8573. }
  8574. },
  8575. });
  8576. // Value returned by `require('jquery.fancytree..')`
  8577. return $.ui.fancytree;
  8578. }); // End of closure
  8579. /*!
  8580. * jquery.fancytree.dnd5.js
  8581. *
  8582. * Drag-and-drop support (native HTML5).
  8583. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  8584. *
  8585. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  8586. *
  8587. * Released under the MIT license
  8588. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  8589. *
  8590. * @version 2.38.3
  8591. * @date 2023-02-01T20:52:50Z
  8592. */
  8593. /*
  8594. #TODO
  8595. Compatiblity when dragging between *separate* windows:
  8596. Drag from Chrome Edge FF IE11 Safari
  8597. To Chrome ok ok ok NO ?
  8598. Edge ok ok ok NO ?
  8599. FF ok ok ok NO ?
  8600. IE 11 ok ok ok ok ?
  8601. Safari ? ? ? ? ok
  8602. */
  8603. (function (factory) {
  8604. if (typeof define === "function" && define.amd) {
  8605. // AMD. Register as an anonymous module.
  8606. define(["jquery", "./jquery.fancytree"], factory);
  8607. } else if (typeof module === "object" && module.exports) {
  8608. // Node/CommonJS
  8609. require("./jquery.fancytree");
  8610. module.exports = factory(require("jquery"));
  8611. } else {
  8612. // Browser globals
  8613. factory(jQuery);
  8614. }
  8615. })(function ($) {
  8616. "use strict";
  8617. /******************************************************************************
  8618. * Private functions and variables
  8619. */
  8620. var FT = $.ui.fancytree,
  8621. isMac = /Mac/.test(navigator.platform),
  8622. classDragSource = "fancytree-drag-source",
  8623. classDragRemove = "fancytree-drag-remove",
  8624. classDropAccept = "fancytree-drop-accept",
  8625. classDropAfter = "fancytree-drop-after",
  8626. classDropBefore = "fancytree-drop-before",
  8627. classDropOver = "fancytree-drop-over",
  8628. classDropReject = "fancytree-drop-reject",
  8629. classDropTarget = "fancytree-drop-target",
  8630. nodeMimeType = "application/x-fancytree-node",
  8631. $dropMarker = null,
  8632. $dragImage,
  8633. $extraHelper,
  8634. SOURCE_NODE = null,
  8635. SOURCE_NODE_LIST = null,
  8636. $sourceList = null,
  8637. DRAG_ENTER_RESPONSE = null,
  8638. // SESSION_DATA = null, // plain object passed to events as `data`
  8639. SUGGESTED_DROP_EFFECT = null,
  8640. REQUESTED_DROP_EFFECT = null,
  8641. REQUESTED_EFFECT_ALLOWED = null,
  8642. LAST_HIT_MODE = null,
  8643. DRAG_OVER_STAMP = null; // Time when a node entered the 'over' hitmode
  8644. /* */
  8645. function _clearGlobals() {
  8646. DRAG_ENTER_RESPONSE = null;
  8647. DRAG_OVER_STAMP = null;
  8648. REQUESTED_DROP_EFFECT = null;
  8649. REQUESTED_EFFECT_ALLOWED = null;
  8650. SUGGESTED_DROP_EFFECT = null;
  8651. SOURCE_NODE = null;
  8652. SOURCE_NODE_LIST = null;
  8653. if ($sourceList) {
  8654. $sourceList.removeClass(classDragSource + " " + classDragRemove);
  8655. }
  8656. $sourceList = null;
  8657. if ($dropMarker) {
  8658. $dropMarker.hide();
  8659. }
  8660. // Take this badge off of me - I can't use it anymore:
  8661. if ($extraHelper) {
  8662. $extraHelper.remove();
  8663. $extraHelper = null;
  8664. }
  8665. }
  8666. /* Convert number to string and prepend +/-; return empty string for 0.*/
  8667. function offsetString(n) {
  8668. // eslint-disable-next-line no-nested-ternary
  8669. return n === 0 ? "" : n > 0 ? "+" + n : "" + n;
  8670. }
  8671. /* Convert a dragEnter() or dragOver() response to a canonical form.
  8672. * Return false or plain object
  8673. * @param {string|object|boolean} r
  8674. * @return {object|false}
  8675. */
  8676. function normalizeDragEnterResponse(r) {
  8677. var res;
  8678. if (!r) {
  8679. return false;
  8680. }
  8681. if ($.isPlainObject(r)) {
  8682. res = {
  8683. over: !!r.over,
  8684. before: !!r.before,
  8685. after: !!r.after,
  8686. };
  8687. } else if (Array.isArray(r)) {
  8688. res = {
  8689. over: $.inArray("over", r) >= 0,
  8690. before: $.inArray("before", r) >= 0,
  8691. after: $.inArray("after", r) >= 0,
  8692. };
  8693. } else {
  8694. res = {
  8695. over: r === true || r === "over",
  8696. before: r === true || r === "before",
  8697. after: r === true || r === "after",
  8698. };
  8699. }
  8700. if (Object.keys(res).length === 0) {
  8701. return false;
  8702. }
  8703. // if( Object.keys(res).length === 1 ) {
  8704. // res.unique = res[0];
  8705. // }
  8706. return res;
  8707. }
  8708. /* Convert a dataTransfer.effectAllowed to a canonical form.
  8709. * Return false or plain object
  8710. * @param {string|boolean} r
  8711. * @return {object|false}
  8712. */
  8713. // function normalizeEffectAllowed(r) {
  8714. // if (!r || r === "none") {
  8715. // return false;
  8716. // }
  8717. // var all = r === "all",
  8718. // res = {
  8719. // copy: all || /copy/i.test(r),
  8720. // link: all || /link/i.test(r),
  8721. // move: all || /move/i.test(r),
  8722. // };
  8723. // return res;
  8724. // }
  8725. /* Implement auto scrolling when drag cursor is in top/bottom area of scroll parent. */
  8726. function autoScroll(tree, event) {
  8727. var spOfs,
  8728. scrollTop,
  8729. delta,
  8730. dndOpts = tree.options.dnd5,
  8731. sp = tree.$scrollParent[0],
  8732. sensitivity = dndOpts.scrollSensitivity,
  8733. speed = dndOpts.scrollSpeed,
  8734. scrolled = 0;
  8735. if (sp !== document && sp.tagName !== "HTML") {
  8736. spOfs = tree.$scrollParent.offset();
  8737. scrollTop = sp.scrollTop;
  8738. if (spOfs.top + sp.offsetHeight - event.pageY < sensitivity) {
  8739. delta =
  8740. sp.scrollHeight -
  8741. tree.$scrollParent.innerHeight() -
  8742. scrollTop;
  8743. // console.log ("sp.offsetHeight: " + sp.offsetHeight
  8744. // + ", spOfs.top: " + spOfs.top
  8745. // + ", scrollTop: " + scrollTop
  8746. // + ", innerHeight: " + tree.$scrollParent.innerHeight()
  8747. // + ", scrollHeight: " + sp.scrollHeight
  8748. // + ", delta: " + delta
  8749. // );
  8750. if (delta > 0) {
  8751. sp.scrollTop = scrolled = scrollTop + speed;
  8752. }
  8753. } else if (scrollTop > 0 && event.pageY - spOfs.top < sensitivity) {
  8754. sp.scrollTop = scrolled = scrollTop - speed;
  8755. }
  8756. } else {
  8757. scrollTop = $(document).scrollTop();
  8758. if (scrollTop > 0 && event.pageY - scrollTop < sensitivity) {
  8759. scrolled = scrollTop - speed;
  8760. $(document).scrollTop(scrolled);
  8761. } else if (
  8762. $(window).height() - (event.pageY - scrollTop) <
  8763. sensitivity
  8764. ) {
  8765. scrolled = scrollTop + speed;
  8766. $(document).scrollTop(scrolled);
  8767. }
  8768. }
  8769. if (scrolled) {
  8770. tree.debug("autoScroll: " + scrolled + "px");
  8771. }
  8772. return scrolled;
  8773. }
  8774. /* Guess dropEffect from modifier keys.
  8775. * Using rules suggested here:
  8776. * https://ux.stackexchange.com/a/83769
  8777. * @returns
  8778. * 'copy', 'link', 'move', or 'none'
  8779. */
  8780. function evalEffectModifiers(tree, event, effectDefault) {
  8781. var res = effectDefault;
  8782. if (isMac) {
  8783. if (event.metaKey && event.altKey) {
  8784. // Mac: [Control] + [Option]
  8785. res = "link";
  8786. } else if (event.ctrlKey) {
  8787. // Chrome on Mac: [Control]
  8788. res = "link";
  8789. } else if (event.metaKey) {
  8790. // Mac: [Command]
  8791. res = "move";
  8792. } else if (event.altKey) {
  8793. // Mac: [Option]
  8794. res = "copy";
  8795. }
  8796. } else {
  8797. if (event.ctrlKey) {
  8798. // Windows: [Ctrl]
  8799. res = "copy";
  8800. } else if (event.shiftKey) {
  8801. // Windows: [Shift]
  8802. res = "move";
  8803. } else if (event.altKey) {
  8804. // Windows: [Alt]
  8805. res = "link";
  8806. }
  8807. }
  8808. if (res !== SUGGESTED_DROP_EFFECT) {
  8809. tree.info(
  8810. "evalEffectModifiers: " +
  8811. event.type +
  8812. " - evalEffectModifiers(): " +
  8813. SUGGESTED_DROP_EFFECT +
  8814. " -> " +
  8815. res
  8816. );
  8817. }
  8818. SUGGESTED_DROP_EFFECT = res;
  8819. // tree.debug("evalEffectModifiers: " + res);
  8820. return res;
  8821. }
  8822. /*
  8823. * Check if the previous callback (dragEnter, dragOver, ...) has changed
  8824. * the `data` object and apply those settings.
  8825. *
  8826. * Safari:
  8827. * It seems that `dataTransfer.dropEffect` can only be set on dragStart, and will remain
  8828. * even if the cursor changes when [Alt] or [Ctrl] are pressed (?)
  8829. * Using rules suggested here:
  8830. * https://ux.stackexchange.com/a/83769
  8831. * @returns
  8832. * 'copy', 'link', 'move', or 'none'
  8833. */
  8834. function prepareDropEffectCallback(event, data) {
  8835. var tree = data.tree,
  8836. dataTransfer = data.dataTransfer;
  8837. if (event.type === "dragstart") {
  8838. data.effectAllowed = tree.options.dnd5.effectAllowed;
  8839. data.dropEffect = tree.options.dnd5.dropEffectDefault;
  8840. } else {
  8841. data.effectAllowed = REQUESTED_EFFECT_ALLOWED;
  8842. data.dropEffect = REQUESTED_DROP_EFFECT;
  8843. }
  8844. data.dropEffectSuggested = evalEffectModifiers(
  8845. tree,
  8846. event,
  8847. tree.options.dnd5.dropEffectDefault
  8848. );
  8849. data.isMove = data.dropEffect === "move";
  8850. data.files = dataTransfer.files || [];
  8851. // if (REQUESTED_EFFECT_ALLOWED !== dataTransfer.effectAllowed) {
  8852. // tree.warn(
  8853. // "prepareDropEffectCallback(" +
  8854. // event.type +
  8855. // "): dataTransfer.effectAllowed changed from " +
  8856. // REQUESTED_EFFECT_ALLOWED +
  8857. // " -> " +
  8858. // dataTransfer.effectAllowed
  8859. // );
  8860. // }
  8861. // if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) {
  8862. // tree.warn(
  8863. // "prepareDropEffectCallback(" +
  8864. // event.type +
  8865. // "): dataTransfer.dropEffect changed from requested " +
  8866. // REQUESTED_DROP_EFFECT +
  8867. // " to " +
  8868. // dataTransfer.dropEffect
  8869. // );
  8870. // }
  8871. }
  8872. function applyDropEffectCallback(event, data, allowDrop) {
  8873. var tree = data.tree,
  8874. dataTransfer = data.dataTransfer;
  8875. if (
  8876. event.type !== "dragstart" &&
  8877. REQUESTED_EFFECT_ALLOWED !== data.effectAllowed
  8878. ) {
  8879. tree.warn(
  8880. "effectAllowed should only be changed in dragstart event: " +
  8881. event.type +
  8882. ": data.effectAllowed changed from " +
  8883. REQUESTED_EFFECT_ALLOWED +
  8884. " -> " +
  8885. data.effectAllowed
  8886. );
  8887. }
  8888. if (allowDrop === false) {
  8889. tree.info("applyDropEffectCallback: allowDrop === false");
  8890. data.effectAllowed = "none";
  8891. data.dropEffect = "none";
  8892. }
  8893. // if (REQUESTED_DROP_EFFECT !== data.dropEffect) {
  8894. // tree.debug(
  8895. // "applyDropEffectCallback(" +
  8896. // event.type +
  8897. // "): data.dropEffect changed from previous " +
  8898. // REQUESTED_DROP_EFFECT +
  8899. // " to " +
  8900. // data.dropEffect
  8901. // );
  8902. // }
  8903. data.isMove = data.dropEffect === "move";
  8904. // data.isMove = data.dropEffectSuggested === "move";
  8905. // `effectAllowed` must only be defined in dragstart event, so we
  8906. // store it in a global variable for reference
  8907. if (event.type === "dragstart") {
  8908. REQUESTED_EFFECT_ALLOWED = data.effectAllowed;
  8909. REQUESTED_DROP_EFFECT = data.dropEffect;
  8910. }
  8911. // if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) {
  8912. // data.tree.info(
  8913. // "applyDropEffectCallback(" +
  8914. // event.type +
  8915. // "): dataTransfer.dropEffect changed from " +
  8916. // REQUESTED_DROP_EFFECT +
  8917. // " -> " +
  8918. // dataTransfer.dropEffect
  8919. // );
  8920. // }
  8921. dataTransfer.effectAllowed = REQUESTED_EFFECT_ALLOWED;
  8922. dataTransfer.dropEffect = REQUESTED_DROP_EFFECT;
  8923. // tree.debug(
  8924. // "applyDropEffectCallback(" +
  8925. // event.type +
  8926. // "): set " +
  8927. // dataTransfer.dropEffect +
  8928. // "/" +
  8929. // dataTransfer.effectAllowed
  8930. // );
  8931. // if (REQUESTED_DROP_EFFECT !== dataTransfer.dropEffect) {
  8932. // data.tree.warn(
  8933. // "applyDropEffectCallback(" +
  8934. // event.type +
  8935. // "): could not set dataTransfer.dropEffect to " +
  8936. // REQUESTED_DROP_EFFECT +
  8937. // ": got " +
  8938. // dataTransfer.dropEffect
  8939. // );
  8940. // }
  8941. return REQUESTED_DROP_EFFECT;
  8942. }
  8943. /* Handle dragover event (fired every x ms) on valid drop targets.
  8944. *
  8945. * - Auto-scroll when cursor is in border regions
  8946. * - Apply restrictioan like 'preventVoidMoves'
  8947. * - Calculate hit mode
  8948. * - Calculate drop effect
  8949. * - Trigger dragOver() callback to let user modify hit mode and drop effect
  8950. * - Adjust the drop marker accordingly
  8951. *
  8952. * @returns hitMode
  8953. */
  8954. function handleDragOver(event, data) {
  8955. // Implement auto-scrolling
  8956. if (data.options.dnd5.scroll) {
  8957. autoScroll(data.tree, event);
  8958. }
  8959. // Bail out with previous response if we get an invalid dragover
  8960. if (!data.node) {
  8961. data.tree.warn("Ignored dragover for non-node"); //, event, data);
  8962. return LAST_HIT_MODE;
  8963. }
  8964. var markerOffsetX,
  8965. nodeOfs,
  8966. pos,
  8967. relPosY,
  8968. hitMode = null,
  8969. tree = data.tree,
  8970. options = tree.options,
  8971. dndOpts = options.dnd5,
  8972. targetNode = data.node,
  8973. sourceNode = data.otherNode,
  8974. markerAt = "center",
  8975. $target = $(targetNode.span),
  8976. $targetTitle = $target.find("span.fancytree-title");
  8977. if (DRAG_ENTER_RESPONSE === false) {
  8978. tree.debug("Ignored dragover, since dragenter returned false.");
  8979. return false;
  8980. } else if (typeof DRAG_ENTER_RESPONSE === "string") {
  8981. $.error("assert failed: dragenter returned string");
  8982. }
  8983. // Calculate hitMode from relative cursor position.
  8984. nodeOfs = $target.offset();
  8985. relPosY = (event.pageY - nodeOfs.top) / $target.height();
  8986. if (event.pageY === undefined) {
  8987. tree.warn("event.pageY is undefined: see issue #1013.");
  8988. }
  8989. if (DRAG_ENTER_RESPONSE.after && relPosY > 0.75) {
  8990. hitMode = "after";
  8991. } else if (
  8992. !DRAG_ENTER_RESPONSE.over &&
  8993. DRAG_ENTER_RESPONSE.after &&
  8994. relPosY > 0.5
  8995. ) {
  8996. hitMode = "after";
  8997. } else if (DRAG_ENTER_RESPONSE.before && relPosY <= 0.25) {
  8998. hitMode = "before";
  8999. } else if (
  9000. !DRAG_ENTER_RESPONSE.over &&
  9001. DRAG_ENTER_RESPONSE.before &&
  9002. relPosY <= 0.5
  9003. ) {
  9004. hitMode = "before";
  9005. } else if (DRAG_ENTER_RESPONSE.over) {
  9006. hitMode = "over";
  9007. }
  9008. // Prevent no-ops like 'before source node'
  9009. // TODO: these are no-ops when moving nodes, but not in copy mode
  9010. if (dndOpts.preventVoidMoves && data.dropEffect === "move") {
  9011. if (targetNode === sourceNode) {
  9012. targetNode.debug("Drop over source node prevented.");
  9013. hitMode = null;
  9014. } else if (
  9015. hitMode === "before" &&
  9016. sourceNode &&
  9017. targetNode === sourceNode.getNextSibling()
  9018. ) {
  9019. targetNode.debug("Drop after source node prevented.");
  9020. hitMode = null;
  9021. } else if (
  9022. hitMode === "after" &&
  9023. sourceNode &&
  9024. targetNode === sourceNode.getPrevSibling()
  9025. ) {
  9026. targetNode.debug("Drop before source node prevented.");
  9027. hitMode = null;
  9028. } else if (
  9029. hitMode === "over" &&
  9030. sourceNode &&
  9031. sourceNode.parent === targetNode &&
  9032. sourceNode.isLastSibling()
  9033. ) {
  9034. targetNode.debug("Drop last child over own parent prevented.");
  9035. hitMode = null;
  9036. }
  9037. }
  9038. // Let callback modify the calculated hitMode
  9039. data.hitMode = hitMode;
  9040. if (hitMode && dndOpts.dragOver) {
  9041. prepareDropEffectCallback(event, data);
  9042. dndOpts.dragOver(targetNode, data);
  9043. var allowDrop = !!hitMode;
  9044. applyDropEffectCallback(event, data, allowDrop);
  9045. hitMode = data.hitMode;
  9046. }
  9047. LAST_HIT_MODE = hitMode;
  9048. //
  9049. if (hitMode === "after" || hitMode === "before" || hitMode === "over") {
  9050. markerOffsetX = dndOpts.dropMarkerOffsetX || 0;
  9051. switch (hitMode) {
  9052. case "before":
  9053. markerAt = "top";
  9054. markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0;
  9055. break;
  9056. case "after":
  9057. markerAt = "bottom";
  9058. markerOffsetX += dndOpts.dropMarkerInsertOffsetX || 0;
  9059. break;
  9060. }
  9061. pos = {
  9062. my: "left" + offsetString(markerOffsetX) + " center",
  9063. at: "left " + markerAt,
  9064. of: $targetTitle,
  9065. };
  9066. if (options.rtl) {
  9067. pos.my = "right" + offsetString(-markerOffsetX) + " center";
  9068. pos.at = "right " + markerAt;
  9069. // console.log("rtl", pos);
  9070. }
  9071. $dropMarker
  9072. .toggleClass(classDropAfter, hitMode === "after")
  9073. .toggleClass(classDropOver, hitMode === "over")
  9074. .toggleClass(classDropBefore, hitMode === "before")
  9075. .show()
  9076. .position(FT.fixPositionOptions(pos));
  9077. } else {
  9078. $dropMarker.hide();
  9079. // console.log("hide dropmarker")
  9080. }
  9081. $(targetNode.span)
  9082. .toggleClass(
  9083. classDropTarget,
  9084. hitMode === "after" ||
  9085. hitMode === "before" ||
  9086. hitMode === "over"
  9087. )
  9088. .toggleClass(classDropAfter, hitMode === "after")
  9089. .toggleClass(classDropBefore, hitMode === "before")
  9090. .toggleClass(classDropAccept, hitMode === "over")
  9091. .toggleClass(classDropReject, hitMode === false);
  9092. return hitMode;
  9093. }
  9094. /*
  9095. * Handle dragstart drag dragend events on the container
  9096. */
  9097. function onDragEvent(event) {
  9098. var json,
  9099. tree = this,
  9100. dndOpts = tree.options.dnd5,
  9101. node = FT.getNode(event),
  9102. dataTransfer =
  9103. event.dataTransfer || event.originalEvent.dataTransfer,
  9104. data = {
  9105. tree: tree,
  9106. node: node,
  9107. options: tree.options,
  9108. originalEvent: event.originalEvent,
  9109. widget: tree.widget,
  9110. dataTransfer: dataTransfer,
  9111. useDefaultImage: true,
  9112. dropEffect: undefined,
  9113. dropEffectSuggested: undefined,
  9114. effectAllowed: undefined, // set by dragstart
  9115. files: undefined, // only for drop events
  9116. isCancelled: undefined, // set by dragend
  9117. isMove: undefined,
  9118. };
  9119. switch (event.type) {
  9120. case "dragstart":
  9121. if (!node) {
  9122. tree.info("Ignored dragstart on a non-node.");
  9123. return false;
  9124. }
  9125. // Store current source node in different formats
  9126. SOURCE_NODE = node;
  9127. // Also optionally store selected nodes
  9128. if (dndOpts.multiSource === false) {
  9129. SOURCE_NODE_LIST = [node];
  9130. } else if (dndOpts.multiSource === true) {
  9131. if (node.isSelected()) {
  9132. SOURCE_NODE_LIST = tree.getSelectedNodes();
  9133. } else {
  9134. SOURCE_NODE_LIST = [node];
  9135. }
  9136. } else {
  9137. SOURCE_NODE_LIST = dndOpts.multiSource(node, data);
  9138. }
  9139. // Cache as array of jQuery objects for faster access:
  9140. $sourceList = $(
  9141. $.map(SOURCE_NODE_LIST, function (n) {
  9142. return n.span;
  9143. })
  9144. );
  9145. // Set visual feedback
  9146. $sourceList.addClass(classDragSource);
  9147. // Set payload
  9148. // Note:
  9149. // Transfer data is only accessible on dragstart and drop!
  9150. // For all other events the formats and kinds in the drag
  9151. // data store list of items representing dragged data can be
  9152. // enumerated, but the data itself is unavailable and no new
  9153. // data can be added.
  9154. var nodeData = node.toDict(true, dndOpts.sourceCopyHook);
  9155. nodeData.treeId = node.tree._id;
  9156. json = JSON.stringify(nodeData);
  9157. try {
  9158. dataTransfer.setData(nodeMimeType, json);
  9159. dataTransfer.setData("text/html", $(node.span).html());
  9160. dataTransfer.setData("text/plain", node.title);
  9161. } catch (ex) {
  9162. // IE only accepts 'text' type
  9163. tree.warn(
  9164. "Could not set data (IE only accepts 'text') - " + ex
  9165. );
  9166. }
  9167. // We always need to set the 'text' type if we want to drag
  9168. // Because IE 11 only accepts this single type.
  9169. // If we pass JSON here, IE can can access all node properties,
  9170. // even when the source lives in another window. (D'n'd inside
  9171. // the same window will always work.)
  9172. // The drawback is, that in this case ALL browsers will see
  9173. // the JSON representation as 'text', so dragging
  9174. // to a text field will insert the JSON string instead of
  9175. // the node title.
  9176. if (dndOpts.setTextTypeJson) {
  9177. dataTransfer.setData("text", json);
  9178. } else {
  9179. dataTransfer.setData("text", node.title);
  9180. }
  9181. // Set the allowed drag modes (combinations of move, copy, and link)
  9182. // (effectAllowed can only be set in the dragstart event.)
  9183. // This can be overridden in the dragStart() callback
  9184. prepareDropEffectCallback(event, data);
  9185. // Let user cancel or modify above settings
  9186. // Realize potential changes by previous callback
  9187. if (dndOpts.dragStart(node, data) === false) {
  9188. // Cancel dragging
  9189. // dataTransfer.dropEffect = "none";
  9190. _clearGlobals();
  9191. return false;
  9192. }
  9193. applyDropEffectCallback(event, data);
  9194. // Unless user set `data.useDefaultImage` to false in dragStart,
  9195. // generata a default drag image now:
  9196. $extraHelper = null;
  9197. if (data.useDefaultImage) {
  9198. // Set the title as drag image (otherwise it would contain the expander)
  9199. $dragImage = $(node.span).find(".fancytree-title");
  9200. if (SOURCE_NODE_LIST && SOURCE_NODE_LIST.length > 1) {
  9201. // Add a counter badge to node title if dragging more than one node.
  9202. // We want this, because the element that is used as drag image
  9203. // must be *visible* in the DOM, so we cannot create some hidden
  9204. // custom markup.
  9205. // See https://kryogenix.org/code/browser/custom-drag-image.html
  9206. // Also, since IE 11 and Edge don't support setDragImage() alltogether,
  9207. // it gives som feedback to the user.
  9208. // The badge will be removed later on drag end.
  9209. $extraHelper = $(
  9210. "<span class='fancytree-childcounter'/>"
  9211. )
  9212. .text("+" + (SOURCE_NODE_LIST.length - 1))
  9213. .appendTo($dragImage);
  9214. }
  9215. if (dataTransfer.setDragImage) {
  9216. // IE 11 and Edge do not support this
  9217. dataTransfer.setDragImage($dragImage[0], -10, -10);
  9218. }
  9219. }
  9220. return true;
  9221. case "drag":
  9222. // Called every few milliseconds (no matter if the
  9223. // cursor is over a valid drop target)
  9224. // data.tree.info("drag", SOURCE_NODE)
  9225. prepareDropEffectCallback(event, data);
  9226. dndOpts.dragDrag(node, data);
  9227. applyDropEffectCallback(event, data);
  9228. $sourceList.toggleClass(classDragRemove, data.isMove);
  9229. break;
  9230. case "dragend":
  9231. // Called at the end of a d'n'd process (after drop)
  9232. // Note caveat: If drop removed the dragged source element,
  9233. // we may not get this event, since the target does not exist
  9234. // anymore
  9235. prepareDropEffectCallback(event, data);
  9236. _clearGlobals();
  9237. data.isCancelled = !LAST_HIT_MODE;
  9238. dndOpts.dragEnd(node, data, !LAST_HIT_MODE);
  9239. // applyDropEffectCallback(event, data);
  9240. break;
  9241. }
  9242. }
  9243. /*
  9244. * Handle dragenter dragover dragleave drop events on the container
  9245. */
  9246. function onDropEvent(event) {
  9247. var json,
  9248. allowAutoExpand,
  9249. nodeData,
  9250. isSourceFtNode,
  9251. r,
  9252. res,
  9253. tree = this,
  9254. dndOpts = tree.options.dnd5,
  9255. allowDrop = null,
  9256. node = FT.getNode(event),
  9257. dataTransfer =
  9258. event.dataTransfer || event.originalEvent.dataTransfer,
  9259. data = {
  9260. tree: tree,
  9261. node: node,
  9262. options: tree.options,
  9263. originalEvent: event.originalEvent,
  9264. widget: tree.widget,
  9265. hitMode: DRAG_ENTER_RESPONSE,
  9266. dataTransfer: dataTransfer,
  9267. otherNode: SOURCE_NODE || null,
  9268. otherNodeList: SOURCE_NODE_LIST || null,
  9269. otherNodeData: null, // set by drop event
  9270. useDefaultImage: true,
  9271. dropEffect: undefined,
  9272. dropEffectSuggested: undefined,
  9273. effectAllowed: undefined, // set by dragstart
  9274. files: null, // list of File objects (may be [])
  9275. isCancelled: undefined, // set by drop event
  9276. isMove: undefined,
  9277. };
  9278. // data.isMove = dropEffect === "move";
  9279. switch (event.type) {
  9280. case "dragenter":
  9281. // The dragenter event is fired when a dragged element or
  9282. // text selection enters a valid drop target.
  9283. DRAG_OVER_STAMP = null;
  9284. if (!node) {
  9285. // Sometimes we get dragenter for the container element
  9286. tree.debug(
  9287. "Ignore non-node " +
  9288. event.type +
  9289. ": " +
  9290. event.target.tagName +
  9291. "." +
  9292. event.target.className
  9293. );
  9294. DRAG_ENTER_RESPONSE = false;
  9295. break;
  9296. }
  9297. $(node.span)
  9298. .addClass(classDropOver)
  9299. .removeClass(classDropAccept + " " + classDropReject);
  9300. // Data is only readable in the dragstart and drop event,
  9301. // but we can check for the type:
  9302. isSourceFtNode =
  9303. $.inArray(nodeMimeType, dataTransfer.types) >= 0;
  9304. if (dndOpts.preventNonNodes && !isSourceFtNode) {
  9305. node.debug("Reject dropping a non-node.");
  9306. DRAG_ENTER_RESPONSE = false;
  9307. break;
  9308. } else if (
  9309. dndOpts.preventForeignNodes &&
  9310. (!SOURCE_NODE || SOURCE_NODE.tree !== node.tree)
  9311. ) {
  9312. node.debug("Reject dropping a foreign node.");
  9313. DRAG_ENTER_RESPONSE = false;
  9314. break;
  9315. } else if (
  9316. dndOpts.preventSameParent &&
  9317. data.otherNode &&
  9318. data.otherNode.tree === node.tree &&
  9319. node.parent === data.otherNode.parent
  9320. ) {
  9321. node.debug("Reject dropping as sibling (same parent).");
  9322. DRAG_ENTER_RESPONSE = false;
  9323. break;
  9324. } else if (
  9325. dndOpts.preventRecursion &&
  9326. data.otherNode &&
  9327. data.otherNode.tree === node.tree &&
  9328. node.isDescendantOf(data.otherNode)
  9329. ) {
  9330. node.debug("Reject dropping below own ancestor.");
  9331. DRAG_ENTER_RESPONSE = false;
  9332. break;
  9333. } else if (dndOpts.preventLazyParents && !node.isLoaded()) {
  9334. node.warn("Drop over unloaded target node prevented.");
  9335. DRAG_ENTER_RESPONSE = false;
  9336. break;
  9337. }
  9338. $dropMarker.show();
  9339. // Call dragEnter() to figure out if (and where) dropping is allowed
  9340. prepareDropEffectCallback(event, data);
  9341. r = dndOpts.dragEnter(node, data);
  9342. res = normalizeDragEnterResponse(r);
  9343. // alert("res:" + JSON.stringify(res))
  9344. DRAG_ENTER_RESPONSE = res;
  9345. allowDrop = res && (res.over || res.before || res.after);
  9346. applyDropEffectCallback(event, data, allowDrop);
  9347. break;
  9348. case "dragover":
  9349. if (!node) {
  9350. tree.debug(
  9351. "Ignore non-node " +
  9352. event.type +
  9353. ": " +
  9354. event.target.tagName +
  9355. "." +
  9356. event.target.className
  9357. );
  9358. break;
  9359. }
  9360. // The dragover event is fired when an element or text
  9361. // selection is being dragged over a valid drop target
  9362. // (every few hundred milliseconds).
  9363. // tree.debug(
  9364. // event.type +
  9365. // ": dropEffect: " +
  9366. // dataTransfer.dropEffect
  9367. // );
  9368. prepareDropEffectCallback(event, data);
  9369. LAST_HIT_MODE = handleDragOver(event, data);
  9370. // The flag controls the preventDefault() below:
  9371. allowDrop = !!LAST_HIT_MODE;
  9372. allowAutoExpand =
  9373. LAST_HIT_MODE === "over" || LAST_HIT_MODE === false;
  9374. if (
  9375. allowAutoExpand &&
  9376. !node.expanded &&
  9377. node.hasChildren() !== false
  9378. ) {
  9379. if (!DRAG_OVER_STAMP) {
  9380. DRAG_OVER_STAMP = Date.now();
  9381. } else if (
  9382. dndOpts.autoExpandMS &&
  9383. Date.now() - DRAG_OVER_STAMP > dndOpts.autoExpandMS &&
  9384. !node.isLoading() &&
  9385. (!dndOpts.dragExpand ||
  9386. dndOpts.dragExpand(node, data) !== false)
  9387. ) {
  9388. node.setExpanded();
  9389. }
  9390. } else {
  9391. DRAG_OVER_STAMP = null;
  9392. }
  9393. break;
  9394. case "dragleave":
  9395. // NOTE: dragleave is fired AFTER the dragenter event of the
  9396. // FOLLOWING element.
  9397. if (!node) {
  9398. tree.debug(
  9399. "Ignore non-node " +
  9400. event.type +
  9401. ": " +
  9402. event.target.tagName +
  9403. "." +
  9404. event.target.className
  9405. );
  9406. break;
  9407. }
  9408. if (!$(node.span).hasClass(classDropOver)) {
  9409. node.debug("Ignore dragleave (multi).");
  9410. break;
  9411. }
  9412. $(node.span).removeClass(
  9413. classDropOver +
  9414. " " +
  9415. classDropAccept +
  9416. " " +
  9417. classDropReject
  9418. );
  9419. node.scheduleAction("cancel");
  9420. dndOpts.dragLeave(node, data);
  9421. $dropMarker.hide();
  9422. break;
  9423. case "drop":
  9424. // Data is only readable in the (dragstart and) drop event:
  9425. if ($.inArray(nodeMimeType, dataTransfer.types) >= 0) {
  9426. nodeData = dataTransfer.getData(nodeMimeType);
  9427. tree.info(
  9428. event.type +
  9429. ": getData('application/x-fancytree-node'): '" +
  9430. nodeData +
  9431. "'"
  9432. );
  9433. }
  9434. if (!nodeData) {
  9435. // 1. Source is not a Fancytree node, or
  9436. // 2. If the FT mime type was set, but returns '', this
  9437. // is probably IE 11 (which only supports 'text')
  9438. nodeData = dataTransfer.getData("text");
  9439. tree.info(
  9440. event.type + ": getData('text'): '" + nodeData + "'"
  9441. );
  9442. }
  9443. if (nodeData) {
  9444. try {
  9445. // 'text' type may contain JSON if IE is involved
  9446. // and setTextTypeJson option was set
  9447. json = JSON.parse(nodeData);
  9448. if (json.title !== undefined) {
  9449. data.otherNodeData = json;
  9450. }
  9451. } catch (ex) {
  9452. // assume 'text' type contains plain text, so `otherNodeData`
  9453. // should not be set
  9454. }
  9455. }
  9456. tree.debug(
  9457. event.type +
  9458. ": nodeData: '" +
  9459. nodeData +
  9460. "', otherNodeData: ",
  9461. data.otherNodeData
  9462. );
  9463. $(node.span).removeClass(
  9464. classDropOver +
  9465. " " +
  9466. classDropAccept +
  9467. " " +
  9468. classDropReject
  9469. );
  9470. // Let user implement the actual drop operation
  9471. data.hitMode = LAST_HIT_MODE;
  9472. prepareDropEffectCallback(event, data, !LAST_HIT_MODE);
  9473. data.isCancelled = !LAST_HIT_MODE;
  9474. var orgSourceElem = SOURCE_NODE && SOURCE_NODE.span,
  9475. orgSourceTree = SOURCE_NODE && SOURCE_NODE.tree;
  9476. dndOpts.dragDrop(node, data);
  9477. // applyDropEffectCallback(event, data);
  9478. // Prevent browser's default drop handling, i.e. open as link, ...
  9479. event.preventDefault();
  9480. if (orgSourceElem && !document.body.contains(orgSourceElem)) {
  9481. // The drop handler removed the original drag source from
  9482. // the DOM, so the dragend event will probaly not fire.
  9483. if (orgSourceTree === tree) {
  9484. tree.debug(
  9485. "Drop handler removed source element: generating dragEnd."
  9486. );
  9487. dndOpts.dragEnd(SOURCE_NODE, data);
  9488. } else {
  9489. tree.warn(
  9490. "Drop handler removed source element: dragend event may be lost."
  9491. );
  9492. }
  9493. }
  9494. _clearGlobals();
  9495. break;
  9496. }
  9497. // Dnd API madness: we must PREVENT default handling to enable dropping
  9498. if (allowDrop) {
  9499. event.preventDefault();
  9500. return false;
  9501. }
  9502. }
  9503. /** [ext-dnd5] Return a Fancytree instance, from element, index, event, or jQueryObject.
  9504. *
  9505. * @returns {FancytreeNode[]} List of nodes (empty if no drag operation)
  9506. * @example
  9507. * $.ui.fancytree.getDragNodeList();
  9508. *
  9509. * @alias Fancytree_Static#getDragNodeList
  9510. * @requires jquery.fancytree.dnd5.js
  9511. * @since 2.31
  9512. */
  9513. $.ui.fancytree.getDragNodeList = function () {
  9514. return SOURCE_NODE_LIST || [];
  9515. };
  9516. /** [ext-dnd5] Return the FancytreeNode that is currently being dragged.
  9517. *
  9518. * If multiple nodes are dragged, only the first is returned.
  9519. *
  9520. * @returns {FancytreeNode | null} dragged nodes or null if no drag operation
  9521. * @example
  9522. * $.ui.fancytree.getDragNode();
  9523. *
  9524. * @alias Fancytree_Static#getDragNode
  9525. * @requires jquery.fancytree.dnd5.js
  9526. * @since 2.31
  9527. */
  9528. $.ui.fancytree.getDragNode = function () {
  9529. return SOURCE_NODE;
  9530. };
  9531. /******************************************************************************
  9532. *
  9533. */
  9534. $.ui.fancytree.registerExtension({
  9535. name: "dnd5",
  9536. version: "2.38.3",
  9537. // Default options for this extension.
  9538. options: {
  9539. autoExpandMS: 1500, // Expand nodes after n milliseconds of hovering
  9540. dropMarkerInsertOffsetX: -16, // Additional offset for drop-marker with hitMode = "before"/"after"
  9541. dropMarkerOffsetX: -24, // Absolute position offset for .fancytree-drop-marker relatively to ..fancytree-title (icon/img near a node accepting drop)
  9542. // #1021 `document.body` is not available yet
  9543. dropMarkerParent: "body", // Root Container used for drop marker (could be a shadow root)
  9544. multiSource: false, // true: Drag multiple (i.e. selected) nodes. Also a callback() is allowed
  9545. effectAllowed: "all", // Restrict the possible cursor shapes and modifier operations (can also be set in the dragStart event)
  9546. // dropEffect: "auto", // 'copy'|'link'|'move'|'auto'(calculate from `effectAllowed`+modifier keys) or callback(node, data) that returns such string.
  9547. dropEffectDefault: "move", // Default dropEffect ('copy', 'link', or 'move') when no modifier is pressed (overide in dragDrag, dragOver).
  9548. preventForeignNodes: false, // Prevent dropping nodes from different Fancytrees
  9549. preventLazyParents: true, // Prevent dropping items on unloaded lazy Fancytree nodes
  9550. preventNonNodes: false, // Prevent dropping items other than Fancytree nodes
  9551. preventRecursion: true, // Prevent dropping nodes on own descendants
  9552. preventSameParent: false, // Prevent dropping nodes under same direct parent
  9553. preventVoidMoves: true, // Prevent dropping nodes 'before self', etc.
  9554. scroll: true, // Enable auto-scrolling while dragging
  9555. scrollSensitivity: 20, // Active top/bottom margin in pixel
  9556. scrollSpeed: 5, // Pixel per event
  9557. setTextTypeJson: false, // Allow dragging of nodes to different IE windows
  9558. sourceCopyHook: null, // Optional callback passed to `toDict` on dragStart @since 2.38
  9559. // Events (drag support)
  9560. dragStart: null, // Callback(sourceNode, data), return true, to enable dnd drag
  9561. dragDrag: $.noop, // Callback(sourceNode, data)
  9562. dragEnd: $.noop, // Callback(sourceNode, data)
  9563. // Events (drop support)
  9564. dragEnter: null, // Callback(targetNode, data), return true, to enable dnd drop
  9565. dragOver: $.noop, // Callback(targetNode, data)
  9566. dragExpand: $.noop, // Callback(targetNode, data), return false to prevent autoExpand
  9567. dragDrop: $.noop, // Callback(targetNode, data)
  9568. dragLeave: $.noop, // Callback(targetNode, data)
  9569. },
  9570. treeInit: function (ctx) {
  9571. var $temp,
  9572. tree = ctx.tree,
  9573. opts = ctx.options,
  9574. glyph = opts.glyph || null,
  9575. dndOpts = opts.dnd5;
  9576. if ($.inArray("dnd", opts.extensions) >= 0) {
  9577. $.error("Extensions 'dnd' and 'dnd5' are mutually exclusive.");
  9578. }
  9579. if (dndOpts.dragStop) {
  9580. $.error(
  9581. "dragStop is not used by ext-dnd5. Use dragEnd instead."
  9582. );
  9583. }
  9584. if (dndOpts.preventRecursiveMoves != null) {
  9585. $.error(
  9586. "preventRecursiveMoves was renamed to preventRecursion."
  9587. );
  9588. }
  9589. // Implement `opts.createNode` event to add the 'draggable' attribute
  9590. // #680: this must happen before calling super.treeInit()
  9591. if (dndOpts.dragStart) {
  9592. FT.overrideMethod(
  9593. ctx.options,
  9594. "createNode",
  9595. function (event, data) {
  9596. // Default processing if any
  9597. this._super.apply(this, arguments);
  9598. if (data.node.span) {
  9599. data.node.span.draggable = true;
  9600. } else {
  9601. data.node.warn(
  9602. "Cannot add `draggable`: no span tag"
  9603. );
  9604. }
  9605. }
  9606. );
  9607. }
  9608. this._superApply(arguments);
  9609. this.$container.addClass("fancytree-ext-dnd5");
  9610. // Store the current scroll parent, which may be the tree
  9611. // container, any enclosing div, or the document.
  9612. // #761: scrollParent() always needs a container child
  9613. $temp = $("<span>").appendTo(this.$container);
  9614. this.$scrollParent = $temp.scrollParent();
  9615. $temp.remove();
  9616. $dropMarker = $("#fancytree-drop-marker");
  9617. if (!$dropMarker.length) {
  9618. $dropMarker = $("<div id='fancytree-drop-marker'></div>")
  9619. .hide()
  9620. .css({
  9621. "z-index": 1000,
  9622. // Drop marker should not steal dragenter/dragover events:
  9623. "pointer-events": "none",
  9624. })
  9625. .prependTo(dndOpts.dropMarkerParent);
  9626. if (glyph) {
  9627. FT.setSpanIcon(
  9628. $dropMarker[0],
  9629. glyph.map._addClass,
  9630. glyph.map.dropMarker
  9631. );
  9632. }
  9633. }
  9634. $dropMarker.toggleClass("fancytree-rtl", !!opts.rtl);
  9635. // Enable drag support if dragStart() is specified:
  9636. if (dndOpts.dragStart) {
  9637. // Bind drag event handlers
  9638. tree.$container.on(
  9639. "dragstart drag dragend",
  9640. onDragEvent.bind(tree)
  9641. );
  9642. }
  9643. // Enable drop support if dragEnter() is specified:
  9644. if (dndOpts.dragEnter) {
  9645. // Bind drop event handlers
  9646. tree.$container.on(
  9647. "dragenter dragover dragleave drop",
  9648. onDropEvent.bind(tree)
  9649. );
  9650. }
  9651. },
  9652. });
  9653. // Value returned by `require('jquery.fancytree..')`
  9654. return $.ui.fancytree;
  9655. }); // End of closure
  9656. /*!
  9657. * jquery.fancytree.edit.js
  9658. *
  9659. * Make node titles editable.
  9660. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  9661. *
  9662. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  9663. *
  9664. * Released under the MIT license
  9665. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  9666. *
  9667. * @version 2.38.3
  9668. * @date 2023-02-01T20:52:50Z
  9669. */
  9670. (function (factory) {
  9671. if (typeof define === "function" && define.amd) {
  9672. // AMD. Register as an anonymous module.
  9673. define(["jquery", "./jquery.fancytree"], factory);
  9674. } else if (typeof module === "object" && module.exports) {
  9675. // Node/CommonJS
  9676. require("./jquery.fancytree");
  9677. module.exports = factory(require("jquery"));
  9678. } else {
  9679. // Browser globals
  9680. factory(jQuery);
  9681. }
  9682. })(function ($) {
  9683. "use strict";
  9684. /*******************************************************************************
  9685. * Private functions and variables
  9686. */
  9687. var isMac = /Mac/.test(navigator.platform),
  9688. escapeHtml = $.ui.fancytree.escapeHtml,
  9689. trim = $.ui.fancytree.trim,
  9690. unescapeHtml = $.ui.fancytree.unescapeHtml;
  9691. /**
  9692. * [ext-edit] Start inline editing of current node title.
  9693. *
  9694. * @alias FancytreeNode#editStart
  9695. * @requires Fancytree
  9696. */
  9697. $.ui.fancytree._FancytreeNodeClass.prototype.editStart = function () {
  9698. var $input,
  9699. node = this,
  9700. tree = this.tree,
  9701. local = tree.ext.edit,
  9702. instOpts = tree.options.edit,
  9703. $title = $(".fancytree-title", node.span),
  9704. eventData = {
  9705. node: node,
  9706. tree: tree,
  9707. options: tree.options,
  9708. isNew: $(node[tree.statusClassPropName]).hasClass(
  9709. "fancytree-edit-new"
  9710. ),
  9711. orgTitle: node.title,
  9712. input: null,
  9713. dirty: false,
  9714. };
  9715. // beforeEdit may want to modify the title before editing
  9716. if (
  9717. instOpts.beforeEdit.call(
  9718. node,
  9719. { type: "beforeEdit" },
  9720. eventData
  9721. ) === false
  9722. ) {
  9723. return false;
  9724. }
  9725. $.ui.fancytree.assert(!local.currentNode, "recursive edit");
  9726. local.currentNode = this;
  9727. local.eventData = eventData;
  9728. // Disable standard Fancytree mouse- and key handling
  9729. tree.widget._unbind();
  9730. local.lastDraggableAttrValue = node.span.draggable;
  9731. if (local.lastDraggableAttrValue) {
  9732. node.span.draggable = false;
  9733. }
  9734. // #116: ext-dnd prevents the blur event, so we have to catch outer clicks
  9735. $(document).on("mousedown.fancytree-edit", function (event) {
  9736. if (!$(event.target).hasClass("fancytree-edit-input")) {
  9737. node.editEnd(true, event);
  9738. }
  9739. });
  9740. // Replace node with <input>
  9741. $input = $("<input />", {
  9742. class: "fancytree-edit-input",
  9743. type: "text",
  9744. value: tree.options.escapeTitles
  9745. ? eventData.orgTitle
  9746. : unescapeHtml(eventData.orgTitle),
  9747. });
  9748. local.eventData.input = $input;
  9749. if (instOpts.adjustWidthOfs != null) {
  9750. $input.width($title.width() + instOpts.adjustWidthOfs);
  9751. }
  9752. if (instOpts.inputCss != null) {
  9753. $input.css(instOpts.inputCss);
  9754. }
  9755. $title.html($input);
  9756. // Focus <input> and bind keyboard handler
  9757. $input
  9758. .focus()
  9759. .change(function (event) {
  9760. $input.addClass("fancytree-edit-dirty");
  9761. })
  9762. .on("keydown", function (event) {
  9763. switch (event.which) {
  9764. case $.ui.keyCode.ESCAPE:
  9765. node.editEnd(false, event);
  9766. break;
  9767. case $.ui.keyCode.ENTER:
  9768. node.editEnd(true, event);
  9769. return false; // so we don't start editmode on Mac
  9770. }
  9771. event.stopPropagation();
  9772. })
  9773. .blur(function (event) {
  9774. return node.editEnd(true, event);
  9775. });
  9776. instOpts.edit.call(node, { type: "edit" }, eventData);
  9777. };
  9778. /**
  9779. * [ext-edit] Stop inline editing.
  9780. * @param {Boolean} [applyChanges=false] false: cancel edit, true: save (if modified)
  9781. * @alias FancytreeNode#editEnd
  9782. * @requires jquery.fancytree.edit.js
  9783. */
  9784. $.ui.fancytree._FancytreeNodeClass.prototype.editEnd = function (
  9785. applyChanges,
  9786. _event
  9787. ) {
  9788. var newVal,
  9789. node = this,
  9790. tree = this.tree,
  9791. local = tree.ext.edit,
  9792. eventData = local.eventData,
  9793. instOpts = tree.options.edit,
  9794. $title = $(".fancytree-title", node.span),
  9795. $input = $title.find("input.fancytree-edit-input");
  9796. if (instOpts.trim) {
  9797. $input.val(trim($input.val()));
  9798. }
  9799. newVal = $input.val();
  9800. eventData.dirty = newVal !== node.title;
  9801. eventData.originalEvent = _event;
  9802. // Find out, if saving is required
  9803. if (applyChanges === false) {
  9804. // If true/false was passed, honor this (except in rename mode, if unchanged)
  9805. eventData.save = false;
  9806. } else if (eventData.isNew) {
  9807. // In create mode, we save everything, except for empty text
  9808. eventData.save = newVal !== "";
  9809. } else {
  9810. // In rename mode, we save everyting, except for empty or unchanged text
  9811. eventData.save = eventData.dirty && newVal !== "";
  9812. }
  9813. // Allow to break (keep editor open), modify input, or re-define data.save
  9814. if (
  9815. instOpts.beforeClose.call(
  9816. node,
  9817. { type: "beforeClose" },
  9818. eventData
  9819. ) === false
  9820. ) {
  9821. return false;
  9822. }
  9823. if (
  9824. eventData.save &&
  9825. instOpts.save.call(node, { type: "save" }, eventData) === false
  9826. ) {
  9827. return false;
  9828. }
  9829. $input.removeClass("fancytree-edit-dirty").off();
  9830. // Unbind outer-click handler
  9831. $(document).off(".fancytree-edit");
  9832. if (eventData.save) {
  9833. // # 171: escape user input (not required if global escaping is on)
  9834. node.setTitle(
  9835. tree.options.escapeTitles ? newVal : escapeHtml(newVal)
  9836. );
  9837. node.setFocus();
  9838. } else {
  9839. if (eventData.isNew) {
  9840. node.remove();
  9841. node = eventData.node = null;
  9842. local.relatedNode.setFocus();
  9843. } else {
  9844. node.renderTitle();
  9845. node.setFocus();
  9846. }
  9847. }
  9848. local.eventData = null;
  9849. local.currentNode = null;
  9850. local.relatedNode = null;
  9851. // Re-enable mouse and keyboard handling
  9852. tree.widget._bind();
  9853. if (node && local.lastDraggableAttrValue) {
  9854. node.span.draggable = true;
  9855. }
  9856. // Set keyboard focus, even if setFocus() claims 'nothing to do'
  9857. tree.$container.get(0).focus({ preventScroll: true });
  9858. eventData.input = null;
  9859. instOpts.close.call(node, { type: "close" }, eventData);
  9860. return true;
  9861. };
  9862. /**
  9863. * [ext-edit] Create a new child or sibling node and start edit mode.
  9864. *
  9865. * @param {String} [mode='child'] 'before', 'after', or 'child'
  9866. * @param {Object} [init] NodeData (or simple title string)
  9867. * @alias FancytreeNode#editCreateNode
  9868. * @requires jquery.fancytree.edit.js
  9869. * @since 2.4
  9870. */
  9871. $.ui.fancytree._FancytreeNodeClass.prototype.editCreateNode = function (
  9872. mode,
  9873. init
  9874. ) {
  9875. var newNode,
  9876. tree = this.tree,
  9877. self = this;
  9878. mode = mode || "child";
  9879. if (init == null) {
  9880. init = { title: "" };
  9881. } else if (typeof init === "string") {
  9882. init = { title: init };
  9883. } else {
  9884. $.ui.fancytree.assert($.isPlainObject(init));
  9885. }
  9886. // Make sure node is expanded (and loaded) in 'child' mode
  9887. if (
  9888. mode === "child" &&
  9889. !this.isExpanded() &&
  9890. this.hasChildren() !== false
  9891. ) {
  9892. this.setExpanded().done(function () {
  9893. self.editCreateNode(mode, init);
  9894. });
  9895. return;
  9896. }
  9897. newNode = this.addNode(init, mode);
  9898. // #644: Don't filter new nodes.
  9899. newNode.match = true;
  9900. $(newNode[tree.statusClassPropName])
  9901. .removeClass("fancytree-hide")
  9902. .addClass("fancytree-match");
  9903. newNode.makeVisible(/*{noAnimation: true}*/).done(function () {
  9904. $(newNode[tree.statusClassPropName]).addClass("fancytree-edit-new");
  9905. self.tree.ext.edit.relatedNode = self;
  9906. newNode.editStart();
  9907. });
  9908. };
  9909. /**
  9910. * [ext-edit] Check if any node in this tree in edit mode.
  9911. *
  9912. * @returns {FancytreeNode | null}
  9913. * @alias Fancytree#isEditing
  9914. * @requires jquery.fancytree.edit.js
  9915. */
  9916. $.ui.fancytree._FancytreeClass.prototype.isEditing = function () {
  9917. return this.ext.edit ? this.ext.edit.currentNode : null;
  9918. };
  9919. /**
  9920. * [ext-edit] Check if this node is in edit mode.
  9921. * @returns {Boolean} true if node is currently beeing edited
  9922. * @alias FancytreeNode#isEditing
  9923. * @requires jquery.fancytree.edit.js
  9924. */
  9925. $.ui.fancytree._FancytreeNodeClass.prototype.isEditing = function () {
  9926. return this.tree.ext.edit
  9927. ? this.tree.ext.edit.currentNode === this
  9928. : false;
  9929. };
  9930. /*******************************************************************************
  9931. * Extension code
  9932. */
  9933. $.ui.fancytree.registerExtension({
  9934. name: "edit",
  9935. version: "2.38.3",
  9936. // Default options for this extension.
  9937. options: {
  9938. adjustWidthOfs: 4, // null: don't adjust input size to content
  9939. allowEmpty: false, // Prevent empty input
  9940. inputCss: { minWidth: "3em" },
  9941. // triggerCancel: ["esc", "tab", "click"],
  9942. triggerStart: ["f2", "mac+enter", "shift+click"],
  9943. trim: true, // Trim whitespace before save
  9944. // Events:
  9945. beforeClose: $.noop, // Return false to prevent cancel/save (data.input is available)
  9946. beforeEdit: $.noop, // Return false to prevent edit mode
  9947. close: $.noop, // Editor was removed
  9948. edit: $.noop, // Editor was opened (available as data.input)
  9949. // keypress: $.noop, // Not yet implemented
  9950. save: $.noop, // Save data.input.val() or return false to keep editor open
  9951. },
  9952. // Local attributes
  9953. currentNode: null,
  9954. treeInit: function (ctx) {
  9955. var tree = ctx.tree;
  9956. this._superApply(arguments);
  9957. this.$container
  9958. .addClass("fancytree-ext-edit")
  9959. .on("fancytreebeforeupdateviewport", function (event, data) {
  9960. var editNode = tree.isEditing();
  9961. // When scrolling, the TR may be re-used by another node, so the
  9962. // active cell marker an
  9963. if (editNode) {
  9964. editNode.info("Cancel edit due to scroll event.");
  9965. editNode.editEnd(false, event);
  9966. }
  9967. });
  9968. },
  9969. nodeClick: function (ctx) {
  9970. var eventStr = $.ui.fancytree.eventToString(ctx.originalEvent),
  9971. triggerStart = ctx.options.edit.triggerStart;
  9972. if (
  9973. eventStr === "shift+click" &&
  9974. $.inArray("shift+click", triggerStart) >= 0
  9975. ) {
  9976. if (ctx.originalEvent.shiftKey) {
  9977. ctx.node.editStart();
  9978. return false;
  9979. }
  9980. }
  9981. if (
  9982. eventStr === "click" &&
  9983. $.inArray("clickActive", triggerStart) >= 0
  9984. ) {
  9985. // Only when click was inside title text (not aynwhere else in the row)
  9986. if (
  9987. ctx.node.isActive() &&
  9988. !ctx.node.isEditing() &&
  9989. $(ctx.originalEvent.target).hasClass("fancytree-title")
  9990. ) {
  9991. ctx.node.editStart();
  9992. return false;
  9993. }
  9994. }
  9995. return this._superApply(arguments);
  9996. },
  9997. nodeDblclick: function (ctx) {
  9998. if ($.inArray("dblclick", ctx.options.edit.triggerStart) >= 0) {
  9999. ctx.node.editStart();
  10000. return false;
  10001. }
  10002. return this._superApply(arguments);
  10003. },
  10004. nodeKeydown: function (ctx) {
  10005. switch (ctx.originalEvent.which) {
  10006. case 113: // [F2]
  10007. if ($.inArray("f2", ctx.options.edit.triggerStart) >= 0) {
  10008. ctx.node.editStart();
  10009. return false;
  10010. }
  10011. break;
  10012. case $.ui.keyCode.ENTER:
  10013. if (
  10014. $.inArray("mac+enter", ctx.options.edit.triggerStart) >=
  10015. 0 &&
  10016. isMac
  10017. ) {
  10018. ctx.node.editStart();
  10019. return false;
  10020. }
  10021. break;
  10022. }
  10023. return this._superApply(arguments);
  10024. },
  10025. });
  10026. // Value returned by `require('jquery.fancytree..')`
  10027. return $.ui.fancytree;
  10028. }); // End of closure
  10029. /*!
  10030. * jquery.fancytree.filter.js
  10031. *
  10032. * Remove or highlight tree nodes, based on a filter.
  10033. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  10034. *
  10035. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  10036. *
  10037. * Released under the MIT license
  10038. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  10039. *
  10040. * @version 2.38.3
  10041. * @date 2023-02-01T20:52:50Z
  10042. */
  10043. (function (factory) {
  10044. if (typeof define === "function" && define.amd) {
  10045. // AMD. Register as an anonymous module.
  10046. define(["jquery", "./jquery.fancytree"], factory);
  10047. } else if (typeof module === "object" && module.exports) {
  10048. // Node/CommonJS
  10049. require("./jquery.fancytree");
  10050. module.exports = factory(require("jquery"));
  10051. } else {
  10052. // Browser globals
  10053. factory(jQuery);
  10054. }
  10055. })(function ($) {
  10056. "use strict";
  10057. /*******************************************************************************
  10058. * Private functions and variables
  10059. */
  10060. var KeyNoData = "__not_found__",
  10061. escapeHtml = $.ui.fancytree.escapeHtml,
  10062. exoticStartChar = "\uFFF7",
  10063. exoticEndChar = "\uFFF8";
  10064. function _escapeRegex(str) {
  10065. return (str + "").replace(/([.?*+^$[\]\\(){}|-])/g, "\\$1");
  10066. }
  10067. function extractHtmlText(s) {
  10068. if (s.indexOf(">") >= 0) {
  10069. return $("<div/>").html(s).text();
  10070. }
  10071. return s;
  10072. }
  10073. /**
  10074. * @description Marks the matching charecters of `text` either by `mark` or
  10075. * by exotic*Chars (if `escapeTitles` is `true`) based on `regexMatchArray`
  10076. * which is an array of matching groups.
  10077. * @param {string} text
  10078. * @param {RegExpMatchArray} regexMatchArray
  10079. */
  10080. function _markFuzzyMatchedChars(text, regexMatchArray, escapeTitles) {
  10081. // It is extremely infuriating that we can not use `let` or `const` or arrow functions.
  10082. // Damn you IE!!!
  10083. var matchingIndices = [];
  10084. // get the indices of matched characters (Iterate through `RegExpMatchArray`)
  10085. for (
  10086. var _matchingArrIdx = 1;
  10087. _matchingArrIdx < regexMatchArray.length;
  10088. _matchingArrIdx++
  10089. ) {
  10090. var _mIdx =
  10091. // get matching char index by cumulatively adding
  10092. // the matched group length
  10093. regexMatchArray[_matchingArrIdx].length +
  10094. (_matchingArrIdx === 1 ? 0 : 1) +
  10095. (matchingIndices[matchingIndices.length - 1] || 0);
  10096. matchingIndices.push(_mIdx);
  10097. }
  10098. // Map each `text` char to its position and store in `textPoses`.
  10099. var textPoses = text.split("");
  10100. if (escapeTitles) {
  10101. // If escaping the title, then wrap the matchng char within exotic chars
  10102. matchingIndices.forEach(function (v) {
  10103. textPoses[v] = exoticStartChar + textPoses[v] + exoticEndChar;
  10104. });
  10105. } else {
  10106. // Otherwise, Wrap the matching chars within `mark`.
  10107. matchingIndices.forEach(function (v) {
  10108. textPoses[v] = "<mark>" + textPoses[v] + "</mark>";
  10109. });
  10110. }
  10111. // Join back the modified `textPoses` to create final highlight markup.
  10112. return textPoses.join("");
  10113. }
  10114. $.ui.fancytree._FancytreeClass.prototype._applyFilterImpl = function (
  10115. filter,
  10116. branchMode,
  10117. _opts
  10118. ) {
  10119. var match,
  10120. statusNode,
  10121. re,
  10122. reHighlight,
  10123. reExoticStartChar,
  10124. reExoticEndChar,
  10125. temp,
  10126. prevEnableUpdate,
  10127. count = 0,
  10128. treeOpts = this.options,
  10129. escapeTitles = treeOpts.escapeTitles,
  10130. prevAutoCollapse = treeOpts.autoCollapse,
  10131. opts = $.extend({}, treeOpts.filter, _opts),
  10132. hideMode = opts.mode === "hide",
  10133. leavesOnly = !!opts.leavesOnly && !branchMode;
  10134. // Default to 'match title substring (not case sensitive)'
  10135. if (typeof filter === "string") {
  10136. if (filter === "") {
  10137. this.warn(
  10138. "Fancytree passing an empty string as a filter is handled as clearFilter()."
  10139. );
  10140. this.clearFilter();
  10141. return;
  10142. }
  10143. if (opts.fuzzy) {
  10144. // See https://codereview.stackexchange.com/questions/23899/faster-javascript-fuzzy-string-matching-function/23905#23905
  10145. // and http://www.quora.com/How-is-the-fuzzy-search-algorithm-in-Sublime-Text-designed
  10146. // and http://www.dustindiaz.com/autocomplete-fuzzy-matching
  10147. match = filter
  10148. .split("")
  10149. // Escaping the `filter` will not work because,
  10150. // it gets further split into individual characters. So,
  10151. // escape each character after splitting
  10152. .map(_escapeRegex)
  10153. .reduce(function (a, b) {
  10154. // create capture groups for parts that comes before
  10155. // the character
  10156. return a + "([^" + b + "]*)" + b;
  10157. }, "");
  10158. } else {
  10159. match = _escapeRegex(filter); // make sure a '.' is treated literally
  10160. }
  10161. re = new RegExp(match, "i");
  10162. reHighlight = new RegExp(_escapeRegex(filter), "gi");
  10163. if (escapeTitles) {
  10164. reExoticStartChar = new RegExp(
  10165. _escapeRegex(exoticStartChar),
  10166. "g"
  10167. );
  10168. reExoticEndChar = new RegExp(_escapeRegex(exoticEndChar), "g");
  10169. }
  10170. filter = function (node) {
  10171. if (!node.title) {
  10172. return false;
  10173. }
  10174. var text = escapeTitles
  10175. ? node.title
  10176. : extractHtmlText(node.title),
  10177. // `.match` instead of `.test` to get the capture groups
  10178. res = text.match(re);
  10179. if (res && opts.highlight) {
  10180. if (escapeTitles) {
  10181. if (opts.fuzzy) {
  10182. temp = _markFuzzyMatchedChars(
  10183. text,
  10184. res,
  10185. escapeTitles
  10186. );
  10187. } else {
  10188. // #740: we must not apply the marks to escaped entity names, e.g. `&quot;`
  10189. // Use some exotic characters to mark matches:
  10190. temp = text.replace(reHighlight, function (s) {
  10191. return exoticStartChar + s + exoticEndChar;
  10192. });
  10193. }
  10194. // now we can escape the title...
  10195. node.titleWithHighlight = escapeHtml(temp)
  10196. // ... and finally insert the desired `<mark>` tags
  10197. .replace(reExoticStartChar, "<mark>")
  10198. .replace(reExoticEndChar, "</mark>");
  10199. } else {
  10200. if (opts.fuzzy) {
  10201. node.titleWithHighlight = _markFuzzyMatchedChars(
  10202. text,
  10203. res
  10204. );
  10205. } else {
  10206. node.titleWithHighlight = text.replace(
  10207. reHighlight,
  10208. function (s) {
  10209. return "<mark>" + s + "</mark>";
  10210. }
  10211. );
  10212. }
  10213. }
  10214. // node.debug("filter", escapeTitles, text, node.titleWithHighlight);
  10215. }
  10216. return !!res;
  10217. };
  10218. }
  10219. this.enableFilter = true;
  10220. this.lastFilterArgs = arguments;
  10221. prevEnableUpdate = this.enableUpdate(false);
  10222. this.$div.addClass("fancytree-ext-filter");
  10223. if (hideMode) {
  10224. this.$div.addClass("fancytree-ext-filter-hide");
  10225. } else {
  10226. this.$div.addClass("fancytree-ext-filter-dimm");
  10227. }
  10228. this.$div.toggleClass(
  10229. "fancytree-ext-filter-hide-expanders",
  10230. !!opts.hideExpanders
  10231. );
  10232. // Reset current filter
  10233. this.rootNode.subMatchCount = 0;
  10234. this.visit(function (node) {
  10235. delete node.match;
  10236. delete node.titleWithHighlight;
  10237. node.subMatchCount = 0;
  10238. });
  10239. statusNode = this.getRootNode()._findDirectChild(KeyNoData);
  10240. if (statusNode) {
  10241. statusNode.remove();
  10242. }
  10243. // Adjust node.hide, .match, and .subMatchCount properties
  10244. treeOpts.autoCollapse = false; // #528
  10245. this.visit(function (node) {
  10246. if (leavesOnly && node.children != null) {
  10247. return;
  10248. }
  10249. var res = filter(node),
  10250. matchedByBranch = false;
  10251. if (res === "skip") {
  10252. node.visit(function (c) {
  10253. c.match = false;
  10254. }, true);
  10255. return "skip";
  10256. }
  10257. if (!res && (branchMode || res === "branch") && node.parent.match) {
  10258. res = true;
  10259. matchedByBranch = true;
  10260. }
  10261. if (res) {
  10262. count++;
  10263. node.match = true;
  10264. node.visitParents(function (p) {
  10265. if (p !== node) {
  10266. p.subMatchCount += 1;
  10267. }
  10268. // Expand match (unless this is no real match, but only a node in a matched branch)
  10269. if (opts.autoExpand && !matchedByBranch && !p.expanded) {
  10270. p.setExpanded(true, {
  10271. noAnimation: true,
  10272. noEvents: true,
  10273. scrollIntoView: false,
  10274. });
  10275. p._filterAutoExpanded = true;
  10276. }
  10277. }, true);
  10278. }
  10279. });
  10280. treeOpts.autoCollapse = prevAutoCollapse;
  10281. if (count === 0 && opts.nodata && hideMode) {
  10282. statusNode = opts.nodata;
  10283. if (typeof statusNode === "function") {
  10284. statusNode = statusNode();
  10285. }
  10286. if (statusNode === true) {
  10287. statusNode = {};
  10288. } else if (typeof statusNode === "string") {
  10289. statusNode = { title: statusNode };
  10290. }
  10291. statusNode = $.extend(
  10292. {
  10293. statusNodeType: "nodata",
  10294. key: KeyNoData,
  10295. title: this.options.strings.noData,
  10296. },
  10297. statusNode
  10298. );
  10299. this.getRootNode().addNode(statusNode).match = true;
  10300. }
  10301. // Redraw whole tree
  10302. this._callHook("treeStructureChanged", this, "applyFilter");
  10303. // this.render();
  10304. this.enableUpdate(prevEnableUpdate);
  10305. return count;
  10306. };
  10307. /**
  10308. * [ext-filter] Dimm or hide nodes.
  10309. *
  10310. * @param {function | string} filter
  10311. * @param {boolean} [opts={autoExpand: false, leavesOnly: false}]
  10312. * @returns {integer} count
  10313. * @alias Fancytree#filterNodes
  10314. * @requires jquery.fancytree.filter.js
  10315. */
  10316. $.ui.fancytree._FancytreeClass.prototype.filterNodes = function (
  10317. filter,
  10318. opts
  10319. ) {
  10320. if (typeof opts === "boolean") {
  10321. opts = { leavesOnly: opts };
  10322. this.warn(
  10323. "Fancytree.filterNodes() leavesOnly option is deprecated since 2.9.0 / 2015-04-19. Use opts.leavesOnly instead."
  10324. );
  10325. }
  10326. return this._applyFilterImpl(filter, false, opts);
  10327. };
  10328. /**
  10329. * [ext-filter] Dimm or hide whole branches.
  10330. *
  10331. * @param {function | string} filter
  10332. * @param {boolean} [opts={autoExpand: false}]
  10333. * @returns {integer} count
  10334. * @alias Fancytree#filterBranches
  10335. * @requires jquery.fancytree.filter.js
  10336. */
  10337. $.ui.fancytree._FancytreeClass.prototype.filterBranches = function (
  10338. filter,
  10339. opts
  10340. ) {
  10341. return this._applyFilterImpl(filter, true, opts);
  10342. };
  10343. /**
  10344. * [ext-filter] Re-apply current filter.
  10345. *
  10346. * @returns {integer} count
  10347. * @alias Fancytree#updateFilter
  10348. * @requires jquery.fancytree.filter.js
  10349. * @since 2.38
  10350. */
  10351. $.ui.fancytree._FancytreeClass.prototype.updateFilter = function () {
  10352. if (
  10353. this.enableFilter &&
  10354. this.lastFilterArgs &&
  10355. this.options.filter.autoApply
  10356. ) {
  10357. this._applyFilterImpl.apply(this, this.lastFilterArgs);
  10358. } else {
  10359. this.warn("updateFilter(): no filter active.");
  10360. }
  10361. };
  10362. /**
  10363. * [ext-filter] Reset the filter.
  10364. *
  10365. * @alias Fancytree#clearFilter
  10366. * @requires jquery.fancytree.filter.js
  10367. */
  10368. $.ui.fancytree._FancytreeClass.prototype.clearFilter = function () {
  10369. var $title,
  10370. statusNode = this.getRootNode()._findDirectChild(KeyNoData),
  10371. escapeTitles = this.options.escapeTitles,
  10372. enhanceTitle = this.options.enhanceTitle,
  10373. prevEnableUpdate = this.enableUpdate(false);
  10374. if (statusNode) {
  10375. statusNode.remove();
  10376. }
  10377. // we also counted root node's subMatchCount
  10378. delete this.rootNode.match;
  10379. delete this.rootNode.subMatchCount;
  10380. this.visit(function (node) {
  10381. if (node.match && node.span) {
  10382. // #491, #601
  10383. $title = $(node.span).find(">span.fancytree-title");
  10384. if (escapeTitles) {
  10385. $title.text(node.title);
  10386. } else {
  10387. $title.html(node.title);
  10388. }
  10389. if (enhanceTitle) {
  10390. enhanceTitle(
  10391. { type: "enhanceTitle" },
  10392. { node: node, $title: $title }
  10393. );
  10394. }
  10395. }
  10396. delete node.match;
  10397. delete node.subMatchCount;
  10398. delete node.titleWithHighlight;
  10399. if (node.$subMatchBadge) {
  10400. node.$subMatchBadge.remove();
  10401. delete node.$subMatchBadge;
  10402. }
  10403. if (node._filterAutoExpanded && node.expanded) {
  10404. node.setExpanded(false, {
  10405. noAnimation: true,
  10406. noEvents: true,
  10407. scrollIntoView: false,
  10408. });
  10409. }
  10410. delete node._filterAutoExpanded;
  10411. });
  10412. this.enableFilter = false;
  10413. this.lastFilterArgs = null;
  10414. this.$div.removeClass(
  10415. "fancytree-ext-filter fancytree-ext-filter-dimm fancytree-ext-filter-hide"
  10416. );
  10417. this._callHook("treeStructureChanged", this, "clearFilter");
  10418. // this.render();
  10419. this.enableUpdate(prevEnableUpdate);
  10420. };
  10421. /**
  10422. * [ext-filter] Return true if a filter is currently applied.
  10423. *
  10424. * @returns {Boolean}
  10425. * @alias Fancytree#isFilterActive
  10426. * @requires jquery.fancytree.filter.js
  10427. * @since 2.13
  10428. */
  10429. $.ui.fancytree._FancytreeClass.prototype.isFilterActive = function () {
  10430. return !!this.enableFilter;
  10431. };
  10432. /**
  10433. * [ext-filter] Return true if this node is matched by current filter (or no filter is active).
  10434. *
  10435. * @returns {Boolean}
  10436. * @alias FancytreeNode#isMatched
  10437. * @requires jquery.fancytree.filter.js
  10438. * @since 2.13
  10439. */
  10440. $.ui.fancytree._FancytreeNodeClass.prototype.isMatched = function () {
  10441. return !(this.tree.enableFilter && !this.match);
  10442. };
  10443. /*******************************************************************************
  10444. * Extension code
  10445. */
  10446. $.ui.fancytree.registerExtension({
  10447. name: "filter",
  10448. version: "2.38.3",
  10449. // Default options for this extension.
  10450. options: {
  10451. autoApply: true, // Re-apply last filter if lazy data is loaded
  10452. autoExpand: false, // Expand all branches that contain matches while filtered
  10453. counter: true, // Show a badge with number of matching child nodes near parent icons
  10454. fuzzy: false, // Match single characters in order, e.g. 'fb' will match 'FooBar'
  10455. hideExpandedCounter: true, // Hide counter badge if parent is expanded
  10456. hideExpanders: false, // Hide expanders if all child nodes are hidden by filter
  10457. highlight: true, // Highlight matches by wrapping inside <mark> tags
  10458. leavesOnly: false, // Match end nodes only
  10459. nodata: true, // Display a 'no data' status node if result is empty
  10460. mode: "dimm", // Grayout unmatched nodes (pass "hide" to remove unmatched node instead)
  10461. },
  10462. nodeLoadChildren: function (ctx, source) {
  10463. var tree = ctx.tree;
  10464. return this._superApply(arguments).done(function () {
  10465. if (
  10466. tree.enableFilter &&
  10467. tree.lastFilterArgs &&
  10468. ctx.options.filter.autoApply
  10469. ) {
  10470. tree._applyFilterImpl.apply(tree, tree.lastFilterArgs);
  10471. }
  10472. });
  10473. },
  10474. nodeSetExpanded: function (ctx, flag, callOpts) {
  10475. var node = ctx.node;
  10476. delete node._filterAutoExpanded;
  10477. // Make sure counter badge is displayed again, when node is beeing collapsed
  10478. if (
  10479. !flag &&
  10480. ctx.options.filter.hideExpandedCounter &&
  10481. node.$subMatchBadge
  10482. ) {
  10483. node.$subMatchBadge.show();
  10484. }
  10485. return this._superApply(arguments);
  10486. },
  10487. nodeRenderStatus: function (ctx) {
  10488. // Set classes for current status
  10489. var res,
  10490. node = ctx.node,
  10491. tree = ctx.tree,
  10492. opts = ctx.options.filter,
  10493. $title = $(node.span).find("span.fancytree-title"),
  10494. $span = $(node[tree.statusClassPropName]),
  10495. enhanceTitle = ctx.options.enhanceTitle,
  10496. escapeTitles = ctx.options.escapeTitles;
  10497. res = this._super(ctx);
  10498. // nothing to do, if node was not yet rendered
  10499. if (!$span.length || !tree.enableFilter) {
  10500. return res;
  10501. }
  10502. $span
  10503. .toggleClass("fancytree-match", !!node.match)
  10504. .toggleClass("fancytree-submatch", !!node.subMatchCount)
  10505. .toggleClass(
  10506. "fancytree-hide",
  10507. !(node.match || node.subMatchCount)
  10508. );
  10509. // Add/update counter badge
  10510. if (
  10511. opts.counter &&
  10512. node.subMatchCount &&
  10513. (!node.isExpanded() || !opts.hideExpandedCounter)
  10514. ) {
  10515. if (!node.$subMatchBadge) {
  10516. node.$subMatchBadge = $(
  10517. "<span class='fancytree-childcounter'/>"
  10518. );
  10519. $(
  10520. "span.fancytree-icon, span.fancytree-custom-icon",
  10521. node.span
  10522. ).append(node.$subMatchBadge);
  10523. }
  10524. node.$subMatchBadge.show().text(node.subMatchCount);
  10525. } else if (node.$subMatchBadge) {
  10526. node.$subMatchBadge.hide();
  10527. }
  10528. // node.debug("nodeRenderStatus", node.titleWithHighlight, node.title)
  10529. // #601: also check for $title.length, because we don't need to render
  10530. // if node.span is null (i.e. not rendered)
  10531. if (node.span && (!node.isEditing || !node.isEditing.call(node))) {
  10532. if (node.titleWithHighlight) {
  10533. $title.html(node.titleWithHighlight);
  10534. } else if (escapeTitles) {
  10535. $title.text(node.title);
  10536. } else {
  10537. $title.html(node.title);
  10538. }
  10539. if (enhanceTitle) {
  10540. enhanceTitle(
  10541. { type: "enhanceTitle" },
  10542. { node: node, $title: $title }
  10543. );
  10544. }
  10545. }
  10546. return res;
  10547. },
  10548. });
  10549. // Value returned by `require('jquery.fancytree..')`
  10550. return $.ui.fancytree;
  10551. }); // End of closure
  10552. /*!
  10553. * jquery.fancytree.glyph.js
  10554. *
  10555. * Use glyph-fonts, ligature-fonts, or SVG icons instead of icon sprites.
  10556. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  10557. *
  10558. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  10559. *
  10560. * Released under the MIT license
  10561. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  10562. *
  10563. * @version 2.38.3
  10564. * @date 2023-02-01T20:52:50Z
  10565. */
  10566. (function (factory) {
  10567. if (typeof define === "function" && define.amd) {
  10568. // AMD. Register as an anonymous module.
  10569. define(["jquery", "./jquery.fancytree"], factory);
  10570. } else if (typeof module === "object" && module.exports) {
  10571. // Node/CommonJS
  10572. require("./jquery.fancytree");
  10573. module.exports = factory(require("jquery"));
  10574. } else {
  10575. // Browser globals
  10576. factory(jQuery);
  10577. }
  10578. })(function ($) {
  10579. "use strict";
  10580. /******************************************************************************
  10581. * Private functions and variables
  10582. */
  10583. var FT = $.ui.fancytree,
  10584. PRESETS = {
  10585. awesome3: {
  10586. // Outdated!
  10587. _addClass: "",
  10588. checkbox: "icon-check-empty",
  10589. checkboxSelected: "icon-check",
  10590. checkboxUnknown: "icon-check icon-muted",
  10591. dragHelper: "icon-caret-right",
  10592. dropMarker: "icon-caret-right",
  10593. error: "icon-exclamation-sign",
  10594. expanderClosed: "icon-caret-right",
  10595. expanderLazy: "icon-angle-right",
  10596. expanderOpen: "icon-caret-down",
  10597. loading: "icon-refresh icon-spin",
  10598. nodata: "icon-meh",
  10599. noExpander: "",
  10600. radio: "icon-circle-blank",
  10601. radioSelected: "icon-circle",
  10602. // radioUnknown: "icon-circle icon-muted",
  10603. // Default node icons.
  10604. // (Use tree.options.icon callback to define custom icons based on node data)
  10605. doc: "icon-file-alt",
  10606. docOpen: "icon-file-alt",
  10607. folder: "icon-folder-close-alt",
  10608. folderOpen: "icon-folder-open-alt",
  10609. },
  10610. awesome4: {
  10611. _addClass: "fa",
  10612. checkbox: "fa-square-o",
  10613. checkboxSelected: "fa-check-square-o",
  10614. checkboxUnknown: "fa-square fancytree-helper-indeterminate-cb",
  10615. dragHelper: "fa-arrow-right",
  10616. dropMarker: "fa-long-arrow-right",
  10617. error: "fa-warning",
  10618. expanderClosed: "fa-caret-right",
  10619. expanderLazy: "fa-angle-right",
  10620. expanderOpen: "fa-caret-down",
  10621. // We may prevent wobbling rotations on FF by creating a separate sub element:
  10622. loading: { html: "<span class='fa fa-spinner fa-pulse' />" },
  10623. nodata: "fa-meh-o",
  10624. noExpander: "",
  10625. radio: "fa-circle-thin", // "fa-circle-o"
  10626. radioSelected: "fa-circle",
  10627. // radioUnknown: "fa-dot-circle-o",
  10628. // Default node icons.
  10629. // (Use tree.options.icon callback to define custom icons based on node data)
  10630. doc: "fa-file-o",
  10631. docOpen: "fa-file-o",
  10632. folder: "fa-folder-o",
  10633. folderOpen: "fa-folder-open-o",
  10634. },
  10635. awesome5: {
  10636. // fontawesome 5 have several different base classes
  10637. // "far, fas, fal and fab" The rendered svg puts that prefix
  10638. // in a different location so we have to keep them separate here
  10639. _addClass: "",
  10640. checkbox: "far fa-square",
  10641. checkboxSelected: "far fa-check-square",
  10642. // checkboxUnknown: "far fa-window-close",
  10643. checkboxUnknown:
  10644. "fas fa-square fancytree-helper-indeterminate-cb",
  10645. radio: "far fa-circle",
  10646. radioSelected: "fas fa-circle",
  10647. radioUnknown: "far fa-dot-circle",
  10648. dragHelper: "fas fa-arrow-right",
  10649. dropMarker: "fas fa-long-arrow-alt-right",
  10650. error: "fas fa-exclamation-triangle",
  10651. expanderClosed: "fas fa-caret-right",
  10652. expanderLazy: "fas fa-angle-right",
  10653. expanderOpen: "fas fa-caret-down",
  10654. loading: "fas fa-spinner fa-pulse",
  10655. nodata: "far fa-meh",
  10656. noExpander: "",
  10657. // Default node icons.
  10658. // (Use tree.options.icon callback to define custom icons based on node data)
  10659. doc: "far fa-file",
  10660. docOpen: "far fa-file",
  10661. folder: "far fa-folder",
  10662. folderOpen: "far fa-folder-open",
  10663. },
  10664. bootstrap3: {
  10665. _addClass: "glyphicon",
  10666. checkbox: "glyphicon-unchecked",
  10667. checkboxSelected: "glyphicon-check",
  10668. checkboxUnknown:
  10669. "glyphicon-expand fancytree-helper-indeterminate-cb", // "glyphicon-share",
  10670. dragHelper: "glyphicon-play",
  10671. dropMarker: "glyphicon-arrow-right",
  10672. error: "glyphicon-warning-sign",
  10673. expanderClosed: "glyphicon-menu-right", // glyphicon-plus-sign
  10674. expanderLazy: "glyphicon-menu-right", // glyphicon-plus-sign
  10675. expanderOpen: "glyphicon-menu-down", // glyphicon-minus-sign
  10676. loading: "glyphicon-refresh fancytree-helper-spin",
  10677. nodata: "glyphicon-info-sign",
  10678. noExpander: "",
  10679. radio: "glyphicon-remove-circle", // "glyphicon-unchecked",
  10680. radioSelected: "glyphicon-ok-circle", // "glyphicon-check",
  10681. // radioUnknown: "glyphicon-ban-circle",
  10682. // Default node icons.
  10683. // (Use tree.options.icon callback to define custom icons based on node data)
  10684. doc: "glyphicon-file",
  10685. docOpen: "glyphicon-file",
  10686. folder: "glyphicon-folder-close",
  10687. folderOpen: "glyphicon-folder-open",
  10688. },
  10689. material: {
  10690. _addClass: "material-icons",
  10691. checkbox: { text: "check_box_outline_blank" },
  10692. checkboxSelected: { text: "check_box" },
  10693. checkboxUnknown: { text: "indeterminate_check_box" },
  10694. dragHelper: { text: "play_arrow" },
  10695. dropMarker: { text: "arrow-forward" },
  10696. error: { text: "warning" },
  10697. expanderClosed: { text: "chevron_right" },
  10698. expanderLazy: { text: "last_page" },
  10699. expanderOpen: { text: "expand_more" },
  10700. loading: {
  10701. text: "autorenew",
  10702. addClass: "fancytree-helper-spin",
  10703. },
  10704. nodata: { text: "info" },
  10705. noExpander: { text: "" },
  10706. radio: { text: "radio_button_unchecked" },
  10707. radioSelected: { text: "radio_button_checked" },
  10708. // Default node icons.
  10709. // (Use tree.options.icon callback to define custom icons based on node data)
  10710. doc: { text: "insert_drive_file" },
  10711. docOpen: { text: "insert_drive_file" },
  10712. folder: { text: "folder" },
  10713. folderOpen: { text: "folder_open" },
  10714. },
  10715. };
  10716. function setIcon(node, span, baseClass, opts, type) {
  10717. var map = opts.map,
  10718. icon = map[type],
  10719. $span = $(span),
  10720. $counter = $span.find(".fancytree-childcounter"),
  10721. setClass = baseClass + " " + (map._addClass || "");
  10722. // #871 Allow a callback
  10723. if (typeof icon === "function") {
  10724. icon = icon.call(this, node, span, type);
  10725. }
  10726. // node.debug( "setIcon(" + baseClass + ", " + type + "): " + "oldIcon" + " -> " + icon );
  10727. // #871: propsed this, but I am not sure how robust this is, e.g.
  10728. // the prefix (fas, far) class changes are not considered?
  10729. // if (span.tagName === "svg" && opts.preset === "awesome5") {
  10730. // // fa5 script converts <i> to <svg> so call a specific handler.
  10731. // var oldIcon = "fa-" + $span.data("icon");
  10732. // // node.debug( "setIcon(" + baseClass + ", " + type + "): " + oldIcon + " -> " + icon );
  10733. // if (typeof oldIcon === "string") {
  10734. // $span.removeClass(oldIcon);
  10735. // }
  10736. // if (typeof icon === "string") {
  10737. // $span.addClass(icon);
  10738. // }
  10739. // return;
  10740. // }
  10741. if (typeof icon === "string") {
  10742. // #883: remove inner html that may be added by prev. mode
  10743. span.innerHTML = "";
  10744. $span.attr("class", setClass + " " + icon).append($counter);
  10745. } else if (icon) {
  10746. if (icon.text) {
  10747. span.textContent = "" + icon.text;
  10748. } else if (icon.html) {
  10749. span.innerHTML = icon.html;
  10750. } else {
  10751. span.innerHTML = "";
  10752. }
  10753. $span
  10754. .attr("class", setClass + " " + (icon.addClass || ""))
  10755. .append($counter);
  10756. }
  10757. }
  10758. $.ui.fancytree.registerExtension({
  10759. name: "glyph",
  10760. version: "2.38.3",
  10761. // Default options for this extension.
  10762. options: {
  10763. preset: null, // 'awesome3', 'awesome4', 'bootstrap3', 'material'
  10764. map: {},
  10765. },
  10766. treeInit: function (ctx) {
  10767. var tree = ctx.tree,
  10768. opts = ctx.options.glyph;
  10769. if (opts.preset) {
  10770. FT.assert(
  10771. !!PRESETS[opts.preset],
  10772. "Invalid value for `options.glyph.preset`: " + opts.preset
  10773. );
  10774. opts.map = $.extend({}, PRESETS[opts.preset], opts.map);
  10775. } else {
  10776. tree.warn("ext-glyph: missing `preset` option.");
  10777. }
  10778. this._superApply(arguments);
  10779. tree.$container.addClass("fancytree-ext-glyph");
  10780. },
  10781. nodeRenderStatus: function (ctx) {
  10782. var checkbox,
  10783. icon,
  10784. res,
  10785. span,
  10786. node = ctx.node,
  10787. $span = $(node.span),
  10788. opts = ctx.options.glyph;
  10789. res = this._super(ctx);
  10790. if (node.isRootNode()) {
  10791. return res;
  10792. }
  10793. span = $span.children(".fancytree-expander").get(0);
  10794. if (span) {
  10795. // if( node.isLoading() ){
  10796. // icon = "loading";
  10797. if (node.expanded && node.hasChildren()) {
  10798. icon = "expanderOpen";
  10799. } else if (node.isUndefined()) {
  10800. icon = "expanderLazy";
  10801. } else if (node.hasChildren()) {
  10802. icon = "expanderClosed";
  10803. } else {
  10804. icon = "noExpander";
  10805. }
  10806. // span.className = "fancytree-expander " + map[icon];
  10807. setIcon(node, span, "fancytree-expander", opts, icon);
  10808. }
  10809. if (node.tr) {
  10810. span = $("td", node.tr).find(".fancytree-checkbox").get(0);
  10811. } else {
  10812. span = $span.children(".fancytree-checkbox").get(0);
  10813. }
  10814. if (span) {
  10815. checkbox = FT.evalOption("checkbox", node, node, opts, false);
  10816. if (
  10817. (node.parent && node.parent.radiogroup) ||
  10818. checkbox === "radio"
  10819. ) {
  10820. icon = node.selected ? "radioSelected" : "radio";
  10821. setIcon(
  10822. node,
  10823. span,
  10824. "fancytree-checkbox fancytree-radio",
  10825. opts,
  10826. icon
  10827. );
  10828. } else {
  10829. // eslint-disable-next-line no-nested-ternary
  10830. icon = node.selected
  10831. ? "checkboxSelected"
  10832. : node.partsel
  10833. ? "checkboxUnknown"
  10834. : "checkbox";
  10835. // span.className = "fancytree-checkbox " + map[icon];
  10836. setIcon(node, span, "fancytree-checkbox", opts, icon);
  10837. }
  10838. }
  10839. // Standard icon (note that this does not match .fancytree-custom-icon,
  10840. // that might be set by opts.icon callbacks)
  10841. span = $span.children(".fancytree-icon").get(0);
  10842. if (span) {
  10843. if (node.statusNodeType) {
  10844. icon = node.statusNodeType; // loading, error
  10845. } else if (node.folder) {
  10846. icon =
  10847. node.expanded && node.hasChildren()
  10848. ? "folderOpen"
  10849. : "folder";
  10850. } else {
  10851. icon = node.expanded ? "docOpen" : "doc";
  10852. }
  10853. setIcon(node, span, "fancytree-icon", opts, icon);
  10854. }
  10855. return res;
  10856. },
  10857. nodeSetStatus: function (ctx, status, message, details) {
  10858. var res,
  10859. span,
  10860. opts = ctx.options.glyph,
  10861. node = ctx.node;
  10862. res = this._superApply(arguments);
  10863. if (
  10864. status === "error" ||
  10865. status === "loading" ||
  10866. status === "nodata"
  10867. ) {
  10868. if (node.parent) {
  10869. span = $(".fancytree-expander", node.span).get(0);
  10870. if (span) {
  10871. setIcon(node, span, "fancytree-expander", opts, status);
  10872. }
  10873. } else {
  10874. //
  10875. span = $(
  10876. ".fancytree-statusnode-" + status,
  10877. node[this.nodeContainerAttrName]
  10878. )
  10879. .find(".fancytree-icon")
  10880. .get(0);
  10881. if (span) {
  10882. setIcon(node, span, "fancytree-icon", opts, status);
  10883. }
  10884. }
  10885. }
  10886. return res;
  10887. },
  10888. });
  10889. // Value returned by `require('jquery.fancytree..')`
  10890. return $.ui.fancytree;
  10891. }); // End of closure
  10892. /*!
  10893. * jquery.fancytree.gridnav.js
  10894. *
  10895. * Support keyboard navigation for trees with embedded input controls.
  10896. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  10897. *
  10898. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  10899. *
  10900. * Released under the MIT license
  10901. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  10902. *
  10903. * @version 2.38.3
  10904. * @date 2023-02-01T20:52:50Z
  10905. */
  10906. (function (factory) {
  10907. if (typeof define === "function" && define.amd) {
  10908. // AMD. Register as an anonymous module.
  10909. define([
  10910. "jquery",
  10911. "./jquery.fancytree",
  10912. "./jquery.fancytree.table",
  10913. ], factory);
  10914. } else if (typeof module === "object" && module.exports) {
  10915. // Node/CommonJS
  10916. require("./jquery.fancytree.table"); // core + table
  10917. module.exports = factory(require("jquery"));
  10918. } else {
  10919. // Browser globals
  10920. factory(jQuery);
  10921. }
  10922. })(function ($) {
  10923. "use strict";
  10924. /*******************************************************************************
  10925. * Private functions and variables
  10926. */
  10927. // Allow these navigation keys even when input controls are focused
  10928. var KC = $.ui.keyCode,
  10929. // which keys are *not* handled by embedded control, but passed to tree
  10930. // navigation handler:
  10931. NAV_KEYS = {
  10932. text: [KC.UP, KC.DOWN],
  10933. checkbox: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
  10934. link: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
  10935. radiobutton: [KC.UP, KC.DOWN, KC.LEFT, KC.RIGHT],
  10936. "select-one": [KC.LEFT, KC.RIGHT],
  10937. "select-multiple": [KC.LEFT, KC.RIGHT],
  10938. };
  10939. /* Calculate TD column index (considering colspans).*/
  10940. function getColIdx($tr, $td) {
  10941. var colspan,
  10942. td = $td.get(0),
  10943. idx = 0;
  10944. $tr.children().each(function () {
  10945. if (this === td) {
  10946. return false;
  10947. }
  10948. colspan = $(this).prop("colspan");
  10949. idx += colspan ? colspan : 1;
  10950. });
  10951. return idx;
  10952. }
  10953. /* Find TD at given column index (considering colspans).*/
  10954. function findTdAtColIdx($tr, colIdx) {
  10955. var colspan,
  10956. res = null,
  10957. idx = 0;
  10958. $tr.children().each(function () {
  10959. if (idx >= colIdx) {
  10960. res = $(this);
  10961. return false;
  10962. }
  10963. colspan = $(this).prop("colspan");
  10964. idx += colspan ? colspan : 1;
  10965. });
  10966. return res;
  10967. }
  10968. /* Find adjacent cell for a given direction. Skip empty cells and consider merged cells */
  10969. function findNeighbourTd($target, keyCode) {
  10970. var $tr,
  10971. colIdx,
  10972. $td = $target.closest("td"),
  10973. $tdNext = null;
  10974. switch (keyCode) {
  10975. case KC.LEFT:
  10976. $tdNext = $td.prev();
  10977. break;
  10978. case KC.RIGHT:
  10979. $tdNext = $td.next();
  10980. break;
  10981. case KC.UP:
  10982. case KC.DOWN:
  10983. $tr = $td.parent();
  10984. colIdx = getColIdx($tr, $td);
  10985. while (true) {
  10986. $tr = keyCode === KC.UP ? $tr.prev() : $tr.next();
  10987. if (!$tr.length) {
  10988. break;
  10989. }
  10990. // Skip hidden rows
  10991. if ($tr.is(":hidden")) {
  10992. continue;
  10993. }
  10994. // Find adjacent cell in the same column
  10995. $tdNext = findTdAtColIdx($tr, colIdx);
  10996. // Skip cells that don't conatain a focusable element
  10997. if ($tdNext && $tdNext.find(":input,a").length) {
  10998. break;
  10999. }
  11000. }
  11001. break;
  11002. }
  11003. return $tdNext;
  11004. }
  11005. /*******************************************************************************
  11006. * Extension code
  11007. */
  11008. $.ui.fancytree.registerExtension({
  11009. name: "gridnav",
  11010. version: "2.38.3",
  11011. // Default options for this extension.
  11012. options: {
  11013. autofocusInput: false, // Focus first embedded input if node gets activated
  11014. handleCursorKeys: true, // Allow UP/DOWN in inputs to move to prev/next node
  11015. },
  11016. treeInit: function (ctx) {
  11017. // gridnav requires the table extension to be loaded before itself
  11018. this._requireExtension("table", true, true);
  11019. this._superApply(arguments);
  11020. this.$container.addClass("fancytree-ext-gridnav");
  11021. // Activate node if embedded input gets focus (due to a click)
  11022. this.$container.on("focusin", function (event) {
  11023. var ctx2,
  11024. node = $.ui.fancytree.getNode(event.target);
  11025. if (node && !node.isActive()) {
  11026. // Call node.setActive(), but also pass the event
  11027. ctx2 = ctx.tree._makeHookContext(node, event);
  11028. ctx.tree._callHook("nodeSetActive", ctx2, true);
  11029. }
  11030. });
  11031. },
  11032. nodeSetActive: function (ctx, flag, callOpts) {
  11033. var $outer,
  11034. opts = ctx.options.gridnav,
  11035. node = ctx.node,
  11036. event = ctx.originalEvent || {},
  11037. triggeredByInput = $(event.target).is(":input");
  11038. flag = flag !== false;
  11039. this._superApply(arguments);
  11040. if (flag) {
  11041. if (ctx.options.titlesTabbable) {
  11042. if (!triggeredByInput) {
  11043. $(node.span).find("span.fancytree-title").focus();
  11044. node.setFocus();
  11045. }
  11046. // If one node is tabbable, the container no longer needs to be
  11047. ctx.tree.$container.attr("tabindex", "-1");
  11048. // ctx.tree.$container.removeAttr("tabindex");
  11049. } else if (opts.autofocusInput && !triggeredByInput) {
  11050. // Set focus to input sub input (if node was clicked, but not
  11051. // when TAB was pressed )
  11052. $outer = $(node.tr || node.span);
  11053. $outer.find(":input:enabled").first().focus();
  11054. }
  11055. }
  11056. },
  11057. nodeKeydown: function (ctx) {
  11058. var inputType,
  11059. handleKeys,
  11060. $td,
  11061. opts = ctx.options.gridnav,
  11062. event = ctx.originalEvent,
  11063. $target = $(event.target);
  11064. if ($target.is(":input:enabled")) {
  11065. inputType = $target.prop("type");
  11066. } else if ($target.is("a")) {
  11067. inputType = "link";
  11068. }
  11069. // ctx.tree.debug("ext-gridnav nodeKeydown", event, inputType);
  11070. if (inputType && opts.handleCursorKeys) {
  11071. handleKeys = NAV_KEYS[inputType];
  11072. if (handleKeys && $.inArray(event.which, handleKeys) >= 0) {
  11073. $td = findNeighbourTd($target, event.which);
  11074. if ($td && $td.length) {
  11075. // ctx.node.debug("ignore keydown in input", event.which, handleKeys);
  11076. $td.find(":input:enabled,a").focus();
  11077. // Prevent Fancytree default navigation
  11078. return false;
  11079. }
  11080. }
  11081. return true;
  11082. }
  11083. // ctx.tree.debug("ext-gridnav NOT HANDLED", event, inputType);
  11084. return this._superApply(arguments);
  11085. },
  11086. });
  11087. // Value returned by `require('jquery.fancytree..')`
  11088. return $.ui.fancytree;
  11089. }); // End of closure
  11090. /*!
  11091. * jquery.fancytree.multi.js
  11092. *
  11093. * Allow multiple selection of nodes by mouse or keyboard.
  11094. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  11095. *
  11096. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  11097. *
  11098. * Released under the MIT license
  11099. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  11100. *
  11101. * @version 2.38.3
  11102. * @date 2023-02-01T20:52:50Z
  11103. */
  11104. (function (factory) {
  11105. if (typeof define === "function" && define.amd) {
  11106. // AMD. Register as an anonymous module.
  11107. define(["jquery", "./jquery.fancytree"], factory);
  11108. } else if (typeof module === "object" && module.exports) {
  11109. // Node/CommonJS
  11110. require("./jquery.fancytree");
  11111. module.exports = factory(require("jquery"));
  11112. } else {
  11113. // Browser globals
  11114. factory(jQuery);
  11115. }
  11116. })(function ($) {
  11117. "use strict";
  11118. /*******************************************************************************
  11119. * Private functions and variables
  11120. */
  11121. // var isMac = /Mac/.test(navigator.platform);
  11122. /*******************************************************************************
  11123. * Extension code
  11124. */
  11125. $.ui.fancytree.registerExtension({
  11126. name: "multi",
  11127. version: "2.38.3",
  11128. // Default options for this extension.
  11129. options: {
  11130. allowNoSelect: false, //
  11131. mode: "sameParent", //
  11132. // Events:
  11133. // beforeSelect: $.noop // Return false to prevent cancel/save (data.input is available)
  11134. },
  11135. treeInit: function (ctx) {
  11136. this._superApply(arguments);
  11137. this.$container.addClass("fancytree-ext-multi");
  11138. if (ctx.options.selectMode === 1) {
  11139. $.error(
  11140. "Fancytree ext-multi: selectMode: 1 (single) is not compatible."
  11141. );
  11142. }
  11143. },
  11144. nodeClick: function (ctx) {
  11145. var //pluginOpts = ctx.options.multi,
  11146. tree = ctx.tree,
  11147. node = ctx.node,
  11148. activeNode = tree.getActiveNode() || tree.getFirstChild(),
  11149. isCbClick = ctx.targetType === "checkbox",
  11150. isExpanderClick = ctx.targetType === "expander",
  11151. eventStr = $.ui.fancytree.eventToString(ctx.originalEvent);
  11152. switch (eventStr) {
  11153. case "click":
  11154. if (isExpanderClick) {
  11155. break;
  11156. } // Default handler will expand/collapse
  11157. if (!isCbClick) {
  11158. tree.selectAll(false);
  11159. // Select clicked node (radio-button mode)
  11160. node.setSelected();
  11161. }
  11162. // Default handler will toggle checkbox clicks and activate
  11163. break;
  11164. case "shift+click":
  11165. // node.debug("click")
  11166. tree.visitRows(
  11167. function (n) {
  11168. // n.debug("click2", n===node, node)
  11169. n.setSelected();
  11170. if (n === node) {
  11171. return false;
  11172. }
  11173. },
  11174. {
  11175. start: activeNode,
  11176. reverse: activeNode.isBelowOf(node),
  11177. }
  11178. );
  11179. break;
  11180. case "ctrl+click":
  11181. case "meta+click": // Mac: [Command]
  11182. node.toggleSelected();
  11183. return;
  11184. }
  11185. return this._superApply(arguments);
  11186. },
  11187. nodeKeydown: function (ctx) {
  11188. var tree = ctx.tree,
  11189. node = ctx.node,
  11190. event = ctx.originalEvent,
  11191. eventStr = $.ui.fancytree.eventToString(event);
  11192. switch (eventStr) {
  11193. case "up":
  11194. case "down":
  11195. tree.selectAll(false);
  11196. node.navigate(event.which, true);
  11197. tree.getActiveNode().setSelected();
  11198. break;
  11199. case "shift+up":
  11200. case "shift+down":
  11201. node.navigate(event.which, true);
  11202. tree.getActiveNode().setSelected();
  11203. break;
  11204. }
  11205. return this._superApply(arguments);
  11206. },
  11207. });
  11208. // Value returned by `require('jquery.fancytree..')`
  11209. return $.ui.fancytree;
  11210. }); // End of closure
  11211. /*!
  11212. * jquery.fancytree.persist.js
  11213. *
  11214. * Persist tree status in cookiesRemove or highlight tree nodes, based on a filter.
  11215. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  11216. *
  11217. * @depends: js-cookie or jquery-cookie
  11218. *
  11219. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  11220. *
  11221. * Released under the MIT license
  11222. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  11223. *
  11224. * @version 2.38.3
  11225. * @date 2023-02-01T20:52:50Z
  11226. */
  11227. (function (factory) {
  11228. if (typeof define === "function" && define.amd) {
  11229. // AMD. Register as an anonymous module.
  11230. define(["jquery", "./jquery.fancytree"], factory);
  11231. } else if (typeof module === "object" && module.exports) {
  11232. // Node/CommonJS
  11233. require("./jquery.fancytree");
  11234. module.exports = factory(require("jquery"));
  11235. } else {
  11236. // Browser globals
  11237. factory(jQuery);
  11238. }
  11239. })(function ($) {
  11240. "use strict";
  11241. /* global Cookies:false */
  11242. /*******************************************************************************
  11243. * Private functions and variables
  11244. */
  11245. var cookieStore = null,
  11246. localStorageStore = null,
  11247. sessionStorageStore = null,
  11248. _assert = $.ui.fancytree.assert,
  11249. ACTIVE = "active",
  11250. EXPANDED = "expanded",
  11251. FOCUS = "focus",
  11252. SELECTED = "selected";
  11253. // Accessing window.xxxStorage may raise security exceptions (see #1022)
  11254. try {
  11255. _assert(window.localStorage && window.localStorage.getItem);
  11256. localStorageStore = {
  11257. get: function (key) {
  11258. return window.localStorage.getItem(key);
  11259. },
  11260. set: function (key, value) {
  11261. window.localStorage.setItem(key, value);
  11262. },
  11263. remove: function (key) {
  11264. window.localStorage.removeItem(key);
  11265. },
  11266. };
  11267. } catch (e) {
  11268. $.ui.fancytree.warn("Could not access window.localStorage", e);
  11269. }
  11270. try {
  11271. _assert(window.sessionStorage && window.sessionStorage.getItem);
  11272. sessionStorageStore = {
  11273. get: function (key) {
  11274. return window.sessionStorage.getItem(key);
  11275. },
  11276. set: function (key, value) {
  11277. window.sessionStorage.setItem(key, value);
  11278. },
  11279. remove: function (key) {
  11280. window.sessionStorage.removeItem(key);
  11281. },
  11282. };
  11283. } catch (e) {
  11284. $.ui.fancytree.warn("Could not access window.sessionStorage", e);
  11285. }
  11286. if (typeof Cookies === "function") {
  11287. // Assume https://github.com/js-cookie/js-cookie
  11288. cookieStore = {
  11289. get: Cookies.get,
  11290. set: function (key, value) {
  11291. Cookies.set(key, value, this.options.persist.cookie);
  11292. },
  11293. remove: Cookies.remove,
  11294. };
  11295. } else if ($ && typeof $.cookie === "function") {
  11296. // Fall back to https://github.com/carhartl/jquery-cookie
  11297. cookieStore = {
  11298. get: $.cookie,
  11299. set: function (key, value) {
  11300. $.cookie(key, value, this.options.persist.cookie);
  11301. },
  11302. remove: $.removeCookie,
  11303. };
  11304. }
  11305. /* Recursively load lazy nodes
  11306. * @param {string} mode 'load', 'expand', false
  11307. */
  11308. function _loadLazyNodes(tree, local, keyList, mode, dfd) {
  11309. var i,
  11310. key,
  11311. l,
  11312. node,
  11313. foundOne = false,
  11314. expandOpts = tree.options.persist.expandOpts,
  11315. deferredList = [],
  11316. missingKeyList = [];
  11317. keyList = keyList || [];
  11318. dfd = dfd || $.Deferred();
  11319. for (i = 0, l = keyList.length; i < l; i++) {
  11320. key = keyList[i];
  11321. node = tree.getNodeByKey(key);
  11322. if (node) {
  11323. if (mode && node.isUndefined()) {
  11324. foundOne = true;
  11325. tree.debug(
  11326. "_loadLazyNodes: " + node + " is lazy: loading..."
  11327. );
  11328. if (mode === "expand") {
  11329. deferredList.push(node.setExpanded(true, expandOpts));
  11330. } else {
  11331. deferredList.push(node.load());
  11332. }
  11333. } else {
  11334. tree.debug("_loadLazyNodes: " + node + " already loaded.");
  11335. node.setExpanded(true, expandOpts);
  11336. }
  11337. } else {
  11338. missingKeyList.push(key);
  11339. tree.debug("_loadLazyNodes: " + node + " was not yet found.");
  11340. }
  11341. }
  11342. $.when.apply($, deferredList).always(function () {
  11343. // All lazy-expands have finished
  11344. if (foundOne && missingKeyList.length > 0) {
  11345. // If we read new nodes from server, try to resolve yet-missing keys
  11346. _loadLazyNodes(tree, local, missingKeyList, mode, dfd);
  11347. } else {
  11348. if (missingKeyList.length) {
  11349. tree.warn(
  11350. "_loadLazyNodes: could not load those keys: ",
  11351. missingKeyList
  11352. );
  11353. for (i = 0, l = missingKeyList.length; i < l; i++) {
  11354. key = keyList[i];
  11355. local._appendKey(EXPANDED, keyList[i], false);
  11356. }
  11357. }
  11358. dfd.resolve();
  11359. }
  11360. });
  11361. return dfd;
  11362. }
  11363. /**
  11364. * [ext-persist] Remove persistence data of the given type(s).
  11365. * Called like
  11366. * $.ui.fancytree.getTree("#tree").clearCookies("active expanded focus selected");
  11367. *
  11368. * @alias Fancytree#clearPersistData
  11369. * @requires jquery.fancytree.persist.js
  11370. */
  11371. $.ui.fancytree._FancytreeClass.prototype.clearPersistData = function (
  11372. types
  11373. ) {
  11374. var local = this.ext.persist,
  11375. prefix = local.cookiePrefix;
  11376. types = types || "active expanded focus selected";
  11377. if (types.indexOf(ACTIVE) >= 0) {
  11378. local._data(prefix + ACTIVE, null);
  11379. }
  11380. if (types.indexOf(EXPANDED) >= 0) {
  11381. local._data(prefix + EXPANDED, null);
  11382. }
  11383. if (types.indexOf(FOCUS) >= 0) {
  11384. local._data(prefix + FOCUS, null);
  11385. }
  11386. if (types.indexOf(SELECTED) >= 0) {
  11387. local._data(prefix + SELECTED, null);
  11388. }
  11389. };
  11390. $.ui.fancytree._FancytreeClass.prototype.clearCookies = function (types) {
  11391. this.warn(
  11392. "'tree.clearCookies()' is deprecated since v2.27.0: use 'clearPersistData()' instead."
  11393. );
  11394. return this.clearPersistData(types);
  11395. };
  11396. /**
  11397. * [ext-persist] Return persistence information from cookies
  11398. *
  11399. * Called like
  11400. * $.ui.fancytree.getTree("#tree").getPersistData();
  11401. *
  11402. * @alias Fancytree#getPersistData
  11403. * @requires jquery.fancytree.persist.js
  11404. */
  11405. $.ui.fancytree._FancytreeClass.prototype.getPersistData = function () {
  11406. var local = this.ext.persist,
  11407. prefix = local.cookiePrefix,
  11408. delim = local.cookieDelimiter,
  11409. res = {};
  11410. res[ACTIVE] = local._data(prefix + ACTIVE);
  11411. res[EXPANDED] = (local._data(prefix + EXPANDED) || "").split(delim);
  11412. res[SELECTED] = (local._data(prefix + SELECTED) || "").split(delim);
  11413. res[FOCUS] = local._data(prefix + FOCUS);
  11414. return res;
  11415. };
  11416. /******************************************************************************
  11417. * Extension code
  11418. */
  11419. $.ui.fancytree.registerExtension({
  11420. name: "persist",
  11421. version: "2.38.3",
  11422. // Default options for this extension.
  11423. options: {
  11424. cookieDelimiter: "~",
  11425. cookiePrefix: undefined, // 'fancytree-<treeId>-' by default
  11426. cookie: {
  11427. raw: false,
  11428. expires: "",
  11429. path: "",
  11430. domain: "",
  11431. secure: false,
  11432. },
  11433. expandLazy: false, // true: recursively expand and load lazy nodes
  11434. expandOpts: undefined, // optional `opts` argument passed to setExpanded()
  11435. fireActivate: true, // false: suppress `activate` event after active node was restored
  11436. overrideSource: true, // true: cookie takes precedence over `source` data attributes.
  11437. store: "auto", // 'cookie': force cookie, 'local': force localStore, 'session': force sessionStore
  11438. types: "active expanded focus selected",
  11439. },
  11440. /* Generic read/write string data to cookie, sessionStorage or localStorage. */
  11441. _data: function (key, value) {
  11442. var store = this._local.store;
  11443. if (value === undefined) {
  11444. return store.get.call(this, key);
  11445. } else if (value === null) {
  11446. store.remove.call(this, key);
  11447. } else {
  11448. store.set.call(this, key, value);
  11449. }
  11450. },
  11451. /* Append `key` to a cookie. */
  11452. _appendKey: function (type, key, flag) {
  11453. key = "" + key; // #90
  11454. var local = this._local,
  11455. instOpts = this.options.persist,
  11456. delim = instOpts.cookieDelimiter,
  11457. cookieName = local.cookiePrefix + type,
  11458. data = local._data(cookieName),
  11459. keyList = data ? data.split(delim) : [],
  11460. idx = $.inArray(key, keyList);
  11461. // Remove, even if we add a key, so the key is always the last entry
  11462. if (idx >= 0) {
  11463. keyList.splice(idx, 1);
  11464. }
  11465. // Append key to cookie
  11466. if (flag) {
  11467. keyList.push(key);
  11468. }
  11469. local._data(cookieName, keyList.join(delim));
  11470. },
  11471. treeInit: function (ctx) {
  11472. var tree = ctx.tree,
  11473. opts = ctx.options,
  11474. local = this._local,
  11475. instOpts = this.options.persist;
  11476. // // For 'auto' or 'cookie' mode, the cookie plugin must be available
  11477. // _assert((instOpts.store !== "auto" && instOpts.store !== "cookie") || cookieStore,
  11478. // "Missing required plugin for 'persist' extension: js.cookie.js or jquery.cookie.js");
  11479. local.cookiePrefix =
  11480. instOpts.cookiePrefix || "fancytree-" + tree._id + "-";
  11481. local.storeActive = instOpts.types.indexOf(ACTIVE) >= 0;
  11482. local.storeExpanded = instOpts.types.indexOf(EXPANDED) >= 0;
  11483. local.storeSelected = instOpts.types.indexOf(SELECTED) >= 0;
  11484. local.storeFocus = instOpts.types.indexOf(FOCUS) >= 0;
  11485. local.store = null;
  11486. if (instOpts.store === "auto") {
  11487. instOpts.store = localStorageStore ? "local" : "cookie";
  11488. }
  11489. if ($.isPlainObject(instOpts.store)) {
  11490. local.store = instOpts.store;
  11491. } else if (instOpts.store === "cookie") {
  11492. local.store = cookieStore;
  11493. } else if (instOpts.store === "local") {
  11494. local.store =
  11495. instOpts.store === "local"
  11496. ? localStorageStore
  11497. : sessionStorageStore;
  11498. } else if (instOpts.store === "session") {
  11499. local.store =
  11500. instOpts.store === "local"
  11501. ? localStorageStore
  11502. : sessionStorageStore;
  11503. }
  11504. _assert(local.store, "Need a valid store.");
  11505. // Bind init-handler to apply cookie state
  11506. tree.$div.on("fancytreeinit", function (event) {
  11507. if (
  11508. tree._triggerTreeEvent("beforeRestore", null, {}) === false
  11509. ) {
  11510. return;
  11511. }
  11512. var cookie,
  11513. dfd,
  11514. i,
  11515. keyList,
  11516. node,
  11517. prevFocus = local._data(local.cookiePrefix + FOCUS), // record this before node.setActive() overrides it;
  11518. noEvents = instOpts.fireActivate === false;
  11519. // tree.debug("document.cookie:", document.cookie);
  11520. cookie = local._data(local.cookiePrefix + EXPANDED);
  11521. keyList = cookie && cookie.split(instOpts.cookieDelimiter);
  11522. if (local.storeExpanded) {
  11523. // Recursively load nested lazy nodes if expandLazy is 'expand' or 'load'
  11524. // Also remove expand-cookies for unmatched nodes
  11525. dfd = _loadLazyNodes(
  11526. tree,
  11527. local,
  11528. keyList,
  11529. instOpts.expandLazy ? "expand" : false,
  11530. null
  11531. );
  11532. } else {
  11533. // nothing to do
  11534. dfd = new $.Deferred().resolve();
  11535. }
  11536. dfd.done(function () {
  11537. if (local.storeSelected) {
  11538. cookie = local._data(local.cookiePrefix + SELECTED);
  11539. if (cookie) {
  11540. keyList = cookie.split(instOpts.cookieDelimiter);
  11541. for (i = 0; i < keyList.length; i++) {
  11542. node = tree.getNodeByKey(keyList[i]);
  11543. if (node) {
  11544. if (
  11545. node.selected === undefined ||
  11546. (instOpts.overrideSource &&
  11547. node.selected === false)
  11548. ) {
  11549. // node.setSelected();
  11550. node.selected = true;
  11551. node.renderStatus();
  11552. }
  11553. } else {
  11554. // node is no longer member of the tree: remove from cookie also
  11555. local._appendKey(
  11556. SELECTED,
  11557. keyList[i],
  11558. false
  11559. );
  11560. }
  11561. }
  11562. }
  11563. // In selectMode 3 we have to fix the child nodes, since we
  11564. // only stored the selected *top* nodes
  11565. if (tree.options.selectMode === 3) {
  11566. tree.visit(function (n) {
  11567. if (n.selected) {
  11568. n.fixSelection3AfterClick();
  11569. return "skip";
  11570. }
  11571. });
  11572. }
  11573. }
  11574. if (local.storeActive) {
  11575. cookie = local._data(local.cookiePrefix + ACTIVE);
  11576. if (
  11577. cookie &&
  11578. (opts.persist.overrideSource || !tree.activeNode)
  11579. ) {
  11580. node = tree.getNodeByKey(cookie);
  11581. if (node) {
  11582. node.debug("persist: set active", cookie);
  11583. // We only want to set the focus if the container
  11584. // had the keyboard focus before
  11585. node.setActive(true, {
  11586. noFocus: true,
  11587. noEvents: noEvents,
  11588. });
  11589. }
  11590. }
  11591. }
  11592. if (local.storeFocus && prevFocus) {
  11593. node = tree.getNodeByKey(prevFocus);
  11594. if (node) {
  11595. // node.debug("persist: set focus", cookie);
  11596. if (tree.options.titlesTabbable) {
  11597. $(node.span).find(".fancytree-title").focus();
  11598. } else {
  11599. $(tree.$container).focus();
  11600. }
  11601. // node.setFocus();
  11602. }
  11603. }
  11604. tree._triggerTreeEvent("restore", null, {});
  11605. });
  11606. });
  11607. // Init the tree
  11608. return this._superApply(arguments);
  11609. },
  11610. nodeSetActive: function (ctx, flag, callOpts) {
  11611. var res,
  11612. local = this._local;
  11613. flag = flag !== false;
  11614. res = this._superApply(arguments);
  11615. if (local.storeActive) {
  11616. local._data(
  11617. local.cookiePrefix + ACTIVE,
  11618. this.activeNode ? this.activeNode.key : null
  11619. );
  11620. }
  11621. return res;
  11622. },
  11623. nodeSetExpanded: function (ctx, flag, callOpts) {
  11624. var res,
  11625. node = ctx.node,
  11626. local = this._local;
  11627. flag = flag !== false;
  11628. res = this._superApply(arguments);
  11629. if (local.storeExpanded) {
  11630. local._appendKey(EXPANDED, node.key, flag);
  11631. }
  11632. return res;
  11633. },
  11634. nodeSetFocus: function (ctx, flag) {
  11635. var res,
  11636. local = this._local;
  11637. flag = flag !== false;
  11638. res = this._superApply(arguments);
  11639. if (local.storeFocus) {
  11640. local._data(
  11641. local.cookiePrefix + FOCUS,
  11642. this.focusNode ? this.focusNode.key : null
  11643. );
  11644. }
  11645. return res;
  11646. },
  11647. nodeSetSelected: function (ctx, flag, callOpts) {
  11648. var res,
  11649. selNodes,
  11650. tree = ctx.tree,
  11651. node = ctx.node,
  11652. local = this._local;
  11653. flag = flag !== false;
  11654. res = this._superApply(arguments);
  11655. if (local.storeSelected) {
  11656. if (tree.options.selectMode === 3) {
  11657. // In selectMode 3 we only store the the selected *top* nodes.
  11658. // De-selecting a node may also de-select some parents, so we
  11659. // calculate the current status again
  11660. selNodes = $.map(tree.getSelectedNodes(true), function (n) {
  11661. return n.key;
  11662. });
  11663. selNodes = selNodes.join(
  11664. ctx.options.persist.cookieDelimiter
  11665. );
  11666. local._data(local.cookiePrefix + SELECTED, selNodes);
  11667. } else {
  11668. // beforeSelect can prevent the change - flag doesn't reflect the node.selected state
  11669. local._appendKey(SELECTED, node.key, node.selected);
  11670. }
  11671. }
  11672. return res;
  11673. },
  11674. });
  11675. // Value returned by `require('jquery.fancytree..')`
  11676. return $.ui.fancytree;
  11677. }); // End of closure
  11678. /*!
  11679. * jquery.fancytree.table.js
  11680. *
  11681. * Render tree as table (aka 'tree grid', 'table tree').
  11682. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  11683. *
  11684. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  11685. *
  11686. * Released under the MIT license
  11687. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  11688. *
  11689. * @version 2.38.3
  11690. * @date 2023-02-01T20:52:50Z
  11691. */
  11692. (function (factory) {
  11693. if (typeof define === "function" && define.amd) {
  11694. // AMD. Register as an anonymous module.
  11695. define(["jquery", "./jquery.fancytree"], factory);
  11696. } else if (typeof module === "object" && module.exports) {
  11697. // Node/CommonJS
  11698. require("./jquery.fancytree");
  11699. module.exports = factory(require("jquery"));
  11700. } else {
  11701. // Browser globals
  11702. factory(jQuery);
  11703. }
  11704. })(function ($) {
  11705. "use strict";
  11706. /******************************************************************************
  11707. * Private functions and variables
  11708. */
  11709. var _assert = $.ui.fancytree.assert;
  11710. function insertFirstChild(referenceNode, newNode) {
  11711. referenceNode.insertBefore(newNode, referenceNode.firstChild);
  11712. }
  11713. function insertSiblingAfter(referenceNode, newNode) {
  11714. referenceNode.parentNode.insertBefore(
  11715. newNode,
  11716. referenceNode.nextSibling
  11717. );
  11718. }
  11719. /* Show/hide all rows that are structural descendants of `parent`. */
  11720. function setChildRowVisibility(parent, flag) {
  11721. parent.visit(function (node) {
  11722. var tr = node.tr;
  11723. // currentFlag = node.hide ? false : flag; // fix for ext-filter
  11724. if (tr) {
  11725. tr.style.display = node.hide || !flag ? "none" : "";
  11726. }
  11727. if (!node.expanded) {
  11728. return "skip";
  11729. }
  11730. });
  11731. }
  11732. /* Find node that is rendered in previous row. */
  11733. function findPrevRowNode(node) {
  11734. var i,
  11735. last,
  11736. prev,
  11737. parent = node.parent,
  11738. siblings = parent ? parent.children : null;
  11739. if (siblings && siblings.length > 1 && siblings[0] !== node) {
  11740. // use the lowest descendant of the preceeding sibling
  11741. i = $.inArray(node, siblings);
  11742. prev = siblings[i - 1];
  11743. _assert(prev.tr);
  11744. // descend to lowest child (with a <tr> tag)
  11745. while (prev.children && prev.children.length) {
  11746. last = prev.children[prev.children.length - 1];
  11747. if (!last.tr) {
  11748. break;
  11749. }
  11750. prev = last;
  11751. }
  11752. } else {
  11753. // if there is no preceding sibling, use the direct parent
  11754. prev = parent;
  11755. }
  11756. return prev;
  11757. }
  11758. $.ui.fancytree.registerExtension({
  11759. name: "table",
  11760. version: "2.38.3",
  11761. // Default options for this extension.
  11762. options: {
  11763. checkboxColumnIdx: null, // render the checkboxes into the this column index (default: nodeColumnIdx)
  11764. indentation: 16, // indent every node level by 16px
  11765. mergeStatusColumns: true, // display 'nodata', 'loading', 'error' centered in a single, merged TR
  11766. nodeColumnIdx: 0, // render node expander, icon, and title to this column (default: #0)
  11767. },
  11768. // Overide virtual methods for this extension.
  11769. // `this` : is this extension object
  11770. // `this._super`: the virtual function that was overriden (member of prev. extension or Fancytree)
  11771. treeInit: function (ctx) {
  11772. var i,
  11773. n,
  11774. $row,
  11775. $tbody,
  11776. tree = ctx.tree,
  11777. opts = ctx.options,
  11778. tableOpts = opts.table,
  11779. $table = tree.widget.element;
  11780. if (tableOpts.customStatus != null) {
  11781. if (opts.renderStatusColumns == null) {
  11782. tree.warn(
  11783. "The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' instead."
  11784. );
  11785. opts.renderStatusColumns = tableOpts.customStatus;
  11786. } else {
  11787. $.error(
  11788. "The 'customStatus' option is deprecated since v2.15.0. Use 'renderStatusColumns' only instead."
  11789. );
  11790. }
  11791. }
  11792. if (opts.renderStatusColumns) {
  11793. if (opts.renderStatusColumns === true) {
  11794. opts.renderStatusColumns = opts.renderColumns;
  11795. // } else if( opts.renderStatusColumns === "wide" ) {
  11796. // opts.renderStatusColumns = _renderStatusNodeWide;
  11797. }
  11798. }
  11799. $table.addClass("fancytree-container fancytree-ext-table");
  11800. $tbody = $table.find(">tbody");
  11801. if (!$tbody.length) {
  11802. // TODO: not sure if we can rely on browsers to insert missing <tbody> before <tr>s:
  11803. if ($table.find(">tr").length) {
  11804. $.error(
  11805. "Expected table > tbody > tr. If you see this please open an issue."
  11806. );
  11807. }
  11808. $tbody = $("<tbody>").appendTo($table);
  11809. }
  11810. tree.tbody = $tbody[0];
  11811. // Prepare row templates:
  11812. // Determine column count from table header if any
  11813. tree.columnCount = $("thead >tr", $table)
  11814. .last()
  11815. .find(">th", $table).length;
  11816. // Read TR templates from tbody if any
  11817. $row = $tbody.children("tr").first();
  11818. if ($row.length) {
  11819. n = $row.children("td").length;
  11820. if (tree.columnCount && n !== tree.columnCount) {
  11821. tree.warn(
  11822. "Column count mismatch between thead (" +
  11823. tree.columnCount +
  11824. ") and tbody (" +
  11825. n +
  11826. "): using tbody."
  11827. );
  11828. tree.columnCount = n;
  11829. }
  11830. $row = $row.clone();
  11831. } else {
  11832. // Only thead is defined: create default row markup
  11833. _assert(
  11834. tree.columnCount >= 1,
  11835. "Need either <thead> or <tbody> with <td> elements to determine column count."
  11836. );
  11837. $row = $("<tr />");
  11838. for (i = 0; i < tree.columnCount; i++) {
  11839. $row.append("<td />");
  11840. }
  11841. }
  11842. $row.find(">td")
  11843. .eq(tableOpts.nodeColumnIdx)
  11844. .html("<span class='fancytree-node' />");
  11845. if (opts.aria) {
  11846. $row.attr("role", "row");
  11847. $row.find("td").attr("role", "gridcell");
  11848. }
  11849. tree.rowFragment = document.createDocumentFragment();
  11850. tree.rowFragment.appendChild($row.get(0));
  11851. // // If tbody contains a second row, use this as status node template
  11852. // $row = $tbody.children("tr").eq(1);
  11853. // if( $row.length === 0 ) {
  11854. // tree.statusRowFragment = tree.rowFragment;
  11855. // } else {
  11856. // $row = $row.clone();
  11857. // tree.statusRowFragment = document.createDocumentFragment();
  11858. // tree.statusRowFragment.appendChild($row.get(0));
  11859. // }
  11860. //
  11861. $tbody.empty();
  11862. // Make sure that status classes are set on the node's <tr> elements
  11863. tree.statusClassPropName = "tr";
  11864. tree.ariaPropName = "tr";
  11865. this.nodeContainerAttrName = "tr";
  11866. // #489: make sure $container is set to <table>, even if ext-dnd is listed before ext-table
  11867. tree.$container = $table;
  11868. this._superApply(arguments);
  11869. // standard Fancytree created a root UL
  11870. $(tree.rootNode.ul).remove();
  11871. tree.rootNode.ul = null;
  11872. // Add container to the TAB chain
  11873. // #577: Allow to set tabindex to "0", "-1" and ""
  11874. this.$container.attr("tabindex", opts.tabindex);
  11875. // this.$container.attr("tabindex", opts.tabbable ? "0" : "-1");
  11876. if (opts.aria) {
  11877. tree.$container
  11878. .attr("role", "treegrid")
  11879. .attr("aria-readonly", true);
  11880. }
  11881. },
  11882. nodeRemoveChildMarkup: function (ctx) {
  11883. var node = ctx.node;
  11884. // node.debug("nodeRemoveChildMarkup()");
  11885. node.visit(function (n) {
  11886. if (n.tr) {
  11887. $(n.tr).remove();
  11888. n.tr = null;
  11889. }
  11890. });
  11891. },
  11892. nodeRemoveMarkup: function (ctx) {
  11893. var node = ctx.node;
  11894. // node.debug("nodeRemoveMarkup()");
  11895. if (node.tr) {
  11896. $(node.tr).remove();
  11897. node.tr = null;
  11898. }
  11899. this.nodeRemoveChildMarkup(ctx);
  11900. },
  11901. /* Override standard render. */
  11902. nodeRender: function (ctx, force, deep, collapsed, _recursive) {
  11903. var children,
  11904. firstTr,
  11905. i,
  11906. l,
  11907. newRow,
  11908. prevNode,
  11909. prevTr,
  11910. subCtx,
  11911. tree = ctx.tree,
  11912. node = ctx.node,
  11913. opts = ctx.options,
  11914. isRootNode = !node.parent;
  11915. if (tree._enableUpdate === false) {
  11916. // $.ui.fancytree.debug("*** nodeRender _enableUpdate: false");
  11917. return;
  11918. }
  11919. if (!_recursive) {
  11920. ctx.hasCollapsedParents = node.parent && !node.parent.expanded;
  11921. }
  11922. // $.ui.fancytree.debug("*** nodeRender " + node + ", isRoot=" + isRootNode, "tr=" + node.tr, "hcp=" + ctx.hasCollapsedParents, "parent.tr=" + (node.parent && node.parent.tr));
  11923. if (!isRootNode) {
  11924. if (node.tr && force) {
  11925. this.nodeRemoveMarkup(ctx);
  11926. }
  11927. if (node.tr) {
  11928. if (force) {
  11929. // Set icon, link, and title (normally this is only required on initial render)
  11930. this.nodeRenderTitle(ctx); // triggers renderColumns()
  11931. } else {
  11932. // Update element classes according to node state
  11933. this.nodeRenderStatus(ctx);
  11934. }
  11935. } else {
  11936. if (ctx.hasCollapsedParents && !deep) {
  11937. // #166: we assume that the parent will be (recursively) rendered
  11938. // later anyway.
  11939. // node.debug("nodeRender ignored due to unrendered parent");
  11940. return;
  11941. }
  11942. // Create new <tr> after previous row
  11943. // if( node.isStatusNode() ) {
  11944. // newRow = tree.statusRowFragment.firstChild.cloneNode(true);
  11945. // } else {
  11946. newRow = tree.rowFragment.firstChild.cloneNode(true);
  11947. // }
  11948. prevNode = findPrevRowNode(node);
  11949. // $.ui.fancytree.debug("*** nodeRender " + node + ": prev: " + prevNode.key);
  11950. _assert(prevNode);
  11951. if (collapsed === true && _recursive) {
  11952. // hide all child rows, so we can use an animation to show it later
  11953. newRow.style.display = "none";
  11954. } else if (deep && ctx.hasCollapsedParents) {
  11955. // also hide this row if deep === true but any parent is collapsed
  11956. newRow.style.display = "none";
  11957. // newRow.style.color = "red";
  11958. }
  11959. if (prevNode.tr) {
  11960. insertSiblingAfter(prevNode.tr, newRow);
  11961. } else {
  11962. _assert(
  11963. !prevNode.parent,
  11964. "prev. row must have a tr, or be system root"
  11965. );
  11966. // tree.tbody.appendChild(newRow);
  11967. insertFirstChild(tree.tbody, newRow); // #675
  11968. }
  11969. node.tr = newRow;
  11970. if (node.key && opts.generateIds) {
  11971. node.tr.id = opts.idPrefix + node.key;
  11972. }
  11973. node.tr.ftnode = node;
  11974. // if(opts.aria){
  11975. // $(node.tr).attr("aria-labelledby", "ftal_" + opts.idPrefix + node.key);
  11976. // }
  11977. node.span = $("span.fancytree-node", node.tr).get(0);
  11978. // Set icon, link, and title (normally this is only required on initial render)
  11979. this.nodeRenderTitle(ctx);
  11980. // Allow tweaking, binding, after node was created for the first time
  11981. // tree._triggerNodeEvent("createNode", ctx);
  11982. if (opts.createNode) {
  11983. opts.createNode.call(tree, { type: "createNode" }, ctx);
  11984. }
  11985. }
  11986. }
  11987. // Allow tweaking after node state was rendered
  11988. // tree._triggerNodeEvent("renderNode", ctx);
  11989. if (opts.renderNode) {
  11990. opts.renderNode.call(tree, { type: "renderNode" }, ctx);
  11991. }
  11992. // Visit child nodes
  11993. // Add child markup
  11994. children = node.children;
  11995. if (children && (isRootNode || deep || node.expanded)) {
  11996. for (i = 0, l = children.length; i < l; i++) {
  11997. subCtx = $.extend({}, ctx, { node: children[i] });
  11998. subCtx.hasCollapsedParents =
  11999. subCtx.hasCollapsedParents || !node.expanded;
  12000. this.nodeRender(subCtx, force, deep, collapsed, true);
  12001. }
  12002. }
  12003. // Make sure, that <tr> order matches node.children order.
  12004. if (children && !_recursive) {
  12005. // we only have to do it once, for the root branch
  12006. prevTr = node.tr || null;
  12007. firstTr = tree.tbody.firstChild;
  12008. // Iterate over all descendants
  12009. node.visit(function (n) {
  12010. if (n.tr) {
  12011. if (
  12012. !n.parent.expanded &&
  12013. n.tr.style.display !== "none"
  12014. ) {
  12015. // fix after a node was dropped over a collapsed
  12016. n.tr.style.display = "none";
  12017. setChildRowVisibility(n, false);
  12018. }
  12019. if (n.tr.previousSibling !== prevTr) {
  12020. node.debug("_fixOrder: mismatch at node: " + n);
  12021. var nextTr = prevTr ? prevTr.nextSibling : firstTr;
  12022. tree.tbody.insertBefore(n.tr, nextTr);
  12023. }
  12024. prevTr = n.tr;
  12025. }
  12026. });
  12027. }
  12028. // Update element classes according to node state
  12029. // if(!isRootNode){
  12030. // this.nodeRenderStatus(ctx);
  12031. // }
  12032. },
  12033. nodeRenderTitle: function (ctx, title) {
  12034. var $cb,
  12035. res,
  12036. tree = ctx.tree,
  12037. node = ctx.node,
  12038. opts = ctx.options,
  12039. isStatusNode = node.isStatusNode();
  12040. res = this._super(ctx, title);
  12041. if (node.isRootNode()) {
  12042. return res;
  12043. }
  12044. // Move checkbox to custom column
  12045. if (
  12046. opts.checkbox &&
  12047. !isStatusNode &&
  12048. opts.table.checkboxColumnIdx != null
  12049. ) {
  12050. $cb = $("span.fancytree-checkbox", node.span); //.detach();
  12051. $(node.tr)
  12052. .find("td")
  12053. .eq(+opts.table.checkboxColumnIdx)
  12054. .html($cb);
  12055. }
  12056. // Update element classes according to node state
  12057. this.nodeRenderStatus(ctx);
  12058. if (isStatusNode) {
  12059. if (opts.renderStatusColumns) {
  12060. // Let user code write column content
  12061. opts.renderStatusColumns.call(
  12062. tree,
  12063. { type: "renderStatusColumns" },
  12064. ctx
  12065. );
  12066. } else if (opts.table.mergeStatusColumns && node.isTopLevel()) {
  12067. $(node.tr)
  12068. .find(">td")
  12069. .eq(0)
  12070. .prop("colspan", tree.columnCount)
  12071. .text(node.title)
  12072. .addClass("fancytree-status-merged")
  12073. .nextAll()
  12074. .remove();
  12075. } // else: default rendering for status node: leave other cells empty
  12076. } else if (opts.renderColumns) {
  12077. opts.renderColumns.call(tree, { type: "renderColumns" }, ctx);
  12078. }
  12079. return res;
  12080. },
  12081. nodeRenderStatus: function (ctx) {
  12082. var indent,
  12083. node = ctx.node,
  12084. opts = ctx.options;
  12085. this._super(ctx);
  12086. $(node.tr).removeClass("fancytree-node");
  12087. // indent
  12088. indent = (node.getLevel() - 1) * opts.table.indentation;
  12089. if (opts.rtl) {
  12090. $(node.span).css({ paddingRight: indent + "px" });
  12091. } else {
  12092. $(node.span).css({ paddingLeft: indent + "px" });
  12093. }
  12094. },
  12095. /* Expand node, return Deferred.promise. */
  12096. nodeSetExpanded: function (ctx, flag, callOpts) {
  12097. // flag defaults to true
  12098. flag = flag !== false;
  12099. if ((ctx.node.expanded && flag) || (!ctx.node.expanded && !flag)) {
  12100. // Expanded state isn't changed - just call base implementation
  12101. return this._superApply(arguments);
  12102. }
  12103. var dfd = new $.Deferred(),
  12104. subOpts = $.extend({}, callOpts, {
  12105. noEvents: true,
  12106. noAnimation: true,
  12107. });
  12108. callOpts = callOpts || {};
  12109. function _afterExpand(ok, args) {
  12110. // ctx.tree.info("ok:" + ok, args);
  12111. if (ok) {
  12112. // #1108 minExpandLevel: 2 together with table extension does not work
  12113. // don't call when 'ok' is false:
  12114. setChildRowVisibility(ctx.node, flag);
  12115. if (
  12116. flag &&
  12117. ctx.options.autoScroll &&
  12118. !callOpts.noAnimation &&
  12119. ctx.node.hasChildren()
  12120. ) {
  12121. // Scroll down to last child, but keep current node visible
  12122. ctx.node
  12123. .getLastChild()
  12124. .scrollIntoView(true, { topNode: ctx.node })
  12125. .always(function () {
  12126. if (!callOpts.noEvents) {
  12127. ctx.tree._triggerNodeEvent(
  12128. flag ? "expand" : "collapse",
  12129. ctx
  12130. );
  12131. }
  12132. dfd.resolveWith(ctx.node);
  12133. });
  12134. } else {
  12135. if (!callOpts.noEvents) {
  12136. ctx.tree._triggerNodeEvent(
  12137. flag ? "expand" : "collapse",
  12138. ctx
  12139. );
  12140. }
  12141. dfd.resolveWith(ctx.node);
  12142. }
  12143. } else {
  12144. if (!callOpts.noEvents) {
  12145. ctx.tree._triggerNodeEvent(
  12146. flag ? "expand" : "collapse",
  12147. ctx
  12148. );
  12149. }
  12150. dfd.rejectWith(ctx.node);
  12151. }
  12152. }
  12153. // Call base-expand with disabled events and animation
  12154. this._super(ctx, flag, subOpts)
  12155. .done(function () {
  12156. _afterExpand(true, arguments);
  12157. })
  12158. .fail(function () {
  12159. _afterExpand(false, arguments);
  12160. });
  12161. return dfd.promise();
  12162. },
  12163. nodeSetStatus: function (ctx, status, message, details) {
  12164. if (status === "ok") {
  12165. var node = ctx.node,
  12166. firstChild = node.children ? node.children[0] : null;
  12167. if (firstChild && firstChild.isStatusNode()) {
  12168. $(firstChild.tr).remove();
  12169. }
  12170. }
  12171. return this._superApply(arguments);
  12172. },
  12173. treeClear: function (ctx) {
  12174. this.nodeRemoveChildMarkup(this._makeHookContext(this.rootNode));
  12175. return this._superApply(arguments);
  12176. },
  12177. treeDestroy: function (ctx) {
  12178. this.$container.find("tbody").empty();
  12179. if (this.$source) {
  12180. this.$source.removeClass("fancytree-helper-hidden");
  12181. }
  12182. return this._superApply(arguments);
  12183. },
  12184. /*,
  12185. treeSetFocus: function(ctx, flag) {
  12186. // alert("treeSetFocus" + ctx.tree.$container);
  12187. ctx.tree.$container.focus();
  12188. $.ui.fancytree.focusTree = ctx.tree;
  12189. }*/
  12190. });
  12191. // Value returned by `require('jquery.fancytree..')`
  12192. return $.ui.fancytree;
  12193. }); // End of closure
  12194. /*!
  12195. * jquery.fancytree.themeroller.js
  12196. *
  12197. * Enable jQuery UI ThemeRoller styles.
  12198. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  12199. *
  12200. * @see http://jqueryui.com/themeroller/
  12201. *
  12202. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  12203. *
  12204. * Released under the MIT license
  12205. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  12206. *
  12207. * @version 2.38.3
  12208. * @date 2023-02-01T20:52:50Z
  12209. */
  12210. (function (factory) {
  12211. if (typeof define === "function" && define.amd) {
  12212. // AMD. Register as an anonymous module.
  12213. define(["jquery", "./jquery.fancytree"], factory);
  12214. } else if (typeof module === "object" && module.exports) {
  12215. // Node/CommonJS
  12216. require("./jquery.fancytree");
  12217. module.exports = factory(require("jquery"));
  12218. } else {
  12219. // Browser globals
  12220. factory(jQuery);
  12221. }
  12222. })(function ($) {
  12223. "use strict";
  12224. /*******************************************************************************
  12225. * Extension code
  12226. */
  12227. $.ui.fancytree.registerExtension({
  12228. name: "themeroller",
  12229. version: "2.38.3",
  12230. // Default options for this extension.
  12231. options: {
  12232. activeClass: "ui-state-active", // Class added to active node
  12233. // activeClass: "ui-state-highlight",
  12234. addClass: "ui-corner-all", // Class added to all nodes
  12235. focusClass: "ui-state-focus", // Class added to focused node
  12236. hoverClass: "ui-state-hover", // Class added to hovered node
  12237. selectedClass: "ui-state-highlight", // Class added to selected nodes
  12238. // selectedClass: "ui-state-active"
  12239. },
  12240. treeInit: function (ctx) {
  12241. var $el = ctx.widget.element,
  12242. opts = ctx.options.themeroller;
  12243. this._superApply(arguments);
  12244. if ($el[0].nodeName === "TABLE") {
  12245. $el.addClass("ui-widget ui-corner-all");
  12246. $el.find(">thead tr").addClass("ui-widget-header");
  12247. $el.find(">tbody").addClass("ui-widget-conent");
  12248. } else {
  12249. $el.addClass("ui-widget ui-widget-content ui-corner-all");
  12250. }
  12251. $el.on(
  12252. "mouseenter mouseleave",
  12253. ".fancytree-node",
  12254. function (event) {
  12255. var node = $.ui.fancytree.getNode(event.target),
  12256. flag = event.type === "mouseenter";
  12257. $(node.tr ? node.tr : node.span).toggleClass(
  12258. opts.hoverClass + " " + opts.addClass,
  12259. flag
  12260. );
  12261. }
  12262. );
  12263. },
  12264. treeDestroy: function (ctx) {
  12265. this._superApply(arguments);
  12266. ctx.widget.element.removeClass(
  12267. "ui-widget ui-widget-content ui-corner-all"
  12268. );
  12269. },
  12270. nodeRenderStatus: function (ctx) {
  12271. var classes = {},
  12272. node = ctx.node,
  12273. $el = $(node.tr ? node.tr : node.span),
  12274. opts = ctx.options.themeroller;
  12275. this._super(ctx);
  12276. /*
  12277. .ui-state-highlight: Class to be applied to highlighted or selected elements. Applies "highlight" container styles to an element and its child text, links, and icons.
  12278. .ui-state-error: Class to be applied to error messaging container elements. Applies "error" container styles to an element and its child text, links, and icons.
  12279. .ui-state-error-text: An additional class that applies just the error text color without background. Can be used on form labels for instance. Also applies error icon color to child icons.
  12280. .ui-state-default: Class to be applied to clickable button-like elements. Applies "clickable default" container styles to an element and its child text, links, and icons.
  12281. .ui-state-hover: Class to be applied on mouseover to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
  12282. .ui-state-focus: Class to be applied on keyboard focus to clickable button-like elements. Applies "clickable hover" container styles to an element and its child text, links, and icons.
  12283. .ui-state-active: Class to be applied on mousedown to clickable button-like elements. Applies "clickable active" container styles to an element and its child text, links, and icons.
  12284. */
  12285. // Set ui-state-* class (handle the case that the same class is assigned
  12286. // to different states)
  12287. classes[opts.activeClass] = false;
  12288. classes[opts.focusClass] = false;
  12289. classes[opts.selectedClass] = false;
  12290. if (node.isActive()) {
  12291. classes[opts.activeClass] = true;
  12292. }
  12293. if (node.hasFocus()) {
  12294. classes[opts.focusClass] = true;
  12295. }
  12296. // activeClass takes precedence before selectedClass:
  12297. if (node.isSelected() && !node.isActive()) {
  12298. classes[opts.selectedClass] = true;
  12299. }
  12300. $el.toggleClass(opts.activeClass, classes[opts.activeClass]);
  12301. $el.toggleClass(opts.focusClass, classes[opts.focusClass]);
  12302. $el.toggleClass(opts.selectedClass, classes[opts.selectedClass]);
  12303. // Additional classes (e.g. 'ui-corner-all')
  12304. $el.addClass(opts.addClass);
  12305. },
  12306. });
  12307. // Value returned by `require('jquery.fancytree..')`
  12308. return $.ui.fancytree;
  12309. }); // End of closure
  12310. /*!
  12311. * jquery.fancytree.wide.js
  12312. * Support for 100% wide selection bars.
  12313. * (Extension module for jquery.fancytree.js: https://github.com/mar10/fancytree/)
  12314. *
  12315. * Copyright (c) 2008-2023, Martin Wendt (https://wwWendt.de)
  12316. *
  12317. * Released under the MIT license
  12318. * https://github.com/mar10/fancytree/wiki/LicenseInfo
  12319. *
  12320. * @version 2.38.3
  12321. * @date 2023-02-01T20:52:50Z
  12322. */
  12323. (function (factory) {
  12324. if (typeof define === "function" && define.amd) {
  12325. // AMD. Register as an anonymous module.
  12326. define(["jquery", "./jquery.fancytree"], factory);
  12327. } else if (typeof module === "object" && module.exports) {
  12328. // Node/CommonJS
  12329. require("./jquery.fancytree");
  12330. module.exports = factory(require("jquery"));
  12331. } else {
  12332. // Browser globals
  12333. factory(jQuery);
  12334. }
  12335. })(function ($) {
  12336. "use strict";
  12337. var reNumUnit = /^([+-]?(?:\d+|\d*\.\d+))([a-z]*|%)$/; // split "1.5em" to ["1.5", "em"]
  12338. /*******************************************************************************
  12339. * Private functions and variables
  12340. */
  12341. // var _assert = $.ui.fancytree.assert;
  12342. /* Calculate inner width without scrollbar */
  12343. // function realInnerWidth($el) {
  12344. // // http://blog.jquery.com/2012/08/16/jquery-1-8-box-sizing-width-csswidth-and-outerwidth/
  12345. // // inst.contWidth = parseFloat(this.$container.css("width"), 10);
  12346. // // 'Client width without scrollbar' - 'padding'
  12347. // return $el[0].clientWidth - ($el.innerWidth() - parseFloat($el.css("width"), 10));
  12348. // }
  12349. /* Create a global embedded CSS style for the tree. */
  12350. function defineHeadStyleElement(id, cssText) {
  12351. id = "fancytree-style-" + id;
  12352. var $headStyle = $("#" + id);
  12353. if (!cssText) {
  12354. $headStyle.remove();
  12355. return null;
  12356. }
  12357. if (!$headStyle.length) {
  12358. $headStyle = $("<style />")
  12359. .attr("id", id)
  12360. .addClass("fancytree-style")
  12361. .prop("type", "text/css")
  12362. .appendTo("head");
  12363. }
  12364. try {
  12365. $headStyle.html(cssText);
  12366. } catch (e) {
  12367. // fix for IE 6-8
  12368. $headStyle[0].styleSheet.cssText = cssText;
  12369. }
  12370. return $headStyle;
  12371. }
  12372. /* Calculate the CSS rules that indent title spans. */
  12373. function renderLevelCss(
  12374. containerId,
  12375. depth,
  12376. levelOfs,
  12377. lineOfs,
  12378. labelOfs,
  12379. measureUnit
  12380. ) {
  12381. var i,
  12382. prefix = "#" + containerId + " span.fancytree-level-",
  12383. rules = [];
  12384. for (i = 0; i < depth; i++) {
  12385. rules.push(
  12386. prefix +
  12387. (i + 1) +
  12388. " span.fancytree-title { padding-left: " +
  12389. (i * levelOfs + lineOfs) +
  12390. measureUnit +
  12391. "; }"
  12392. );
  12393. }
  12394. // Some UI animations wrap the UL inside a DIV and set position:relative on both.
  12395. // This breaks the left:0 and padding-left:nn settings of the title
  12396. rules.push(
  12397. "#" +
  12398. containerId +
  12399. " div.ui-effects-wrapper ul li span.fancytree-title, " +
  12400. "#" +
  12401. containerId +
  12402. " li.fancytree-animating span.fancytree-title " + // #716
  12403. "{ padding-left: " +
  12404. labelOfs +
  12405. measureUnit +
  12406. "; position: static; width: auto; }"
  12407. );
  12408. return rules.join("\n");
  12409. }
  12410. // /**
  12411. // * [ext-wide] Recalculate the width of the selection bar after the tree container
  12412. // * was resized.<br>
  12413. // * May be called explicitly on container resize, since there is no resize event
  12414. // * for DIV tags.
  12415. // *
  12416. // * @alias Fancytree#wideUpdate
  12417. // * @requires jquery.fancytree.wide.js
  12418. // */
  12419. // $.ui.fancytree._FancytreeClass.prototype.wideUpdate = function(){
  12420. // var inst = this.ext.wide,
  12421. // prevCw = inst.contWidth,
  12422. // prevLo = inst.lineOfs;
  12423. // inst.contWidth = realInnerWidth(this.$container);
  12424. // // Each title is precceeded by 2 or 3 icons (16px + 3 margin)
  12425. // // + 1px title border and 3px title padding
  12426. // // TODO: use code from treeInit() below
  12427. // inst.lineOfs = (this.options.checkbox ? 3 : 2) * 19;
  12428. // if( prevCw !== inst.contWidth || prevLo !== inst.lineOfs ) {
  12429. // this.debug("wideUpdate: " + inst.contWidth);
  12430. // this.visit(function(node){
  12431. // node.tree._callHook("nodeRenderTitle", node);
  12432. // });
  12433. // }
  12434. // };
  12435. /*******************************************************************************
  12436. * Extension code
  12437. */
  12438. $.ui.fancytree.registerExtension({
  12439. name: "wide",
  12440. version: "2.38.3",
  12441. // Default options for this extension.
  12442. options: {
  12443. iconWidth: null, // Adjust this if @fancy-icon-width != "16px"
  12444. iconSpacing: null, // Adjust this if @fancy-icon-spacing != "3px"
  12445. labelSpacing: null, // Adjust this if padding between icon and label != "3px"
  12446. levelOfs: null, // Adjust this if ul padding != "16px"
  12447. },
  12448. treeCreate: function (ctx) {
  12449. this._superApply(arguments);
  12450. this.$container.addClass("fancytree-ext-wide");
  12451. var containerId,
  12452. cssText,
  12453. iconSpacingUnit,
  12454. labelSpacingUnit,
  12455. iconWidthUnit,
  12456. levelOfsUnit,
  12457. instOpts = ctx.options.wide,
  12458. // css sniffing
  12459. $dummyLI = $(
  12460. "<li id='fancytreeTemp'><span class='fancytree-node'><span class='fancytree-icon' /><span class='fancytree-title' /></span><ul />"
  12461. ).appendTo(ctx.tree.$container),
  12462. $dummyIcon = $dummyLI.find(".fancytree-icon"),
  12463. $dummyUL = $dummyLI.find("ul"),
  12464. // $dummyTitle = $dummyLI.find(".fancytree-title"),
  12465. iconSpacing =
  12466. instOpts.iconSpacing || $dummyIcon.css("margin-left"),
  12467. iconWidth = instOpts.iconWidth || $dummyIcon.css("width"),
  12468. labelSpacing = instOpts.labelSpacing || "3px",
  12469. levelOfs = instOpts.levelOfs || $dummyUL.css("padding-left");
  12470. $dummyLI.remove();
  12471. iconSpacingUnit = iconSpacing.match(reNumUnit)[2];
  12472. iconSpacing = parseFloat(iconSpacing, 10);
  12473. labelSpacingUnit = labelSpacing.match(reNumUnit)[2];
  12474. labelSpacing = parseFloat(labelSpacing, 10);
  12475. iconWidthUnit = iconWidth.match(reNumUnit)[2];
  12476. iconWidth = parseFloat(iconWidth, 10);
  12477. levelOfsUnit = levelOfs.match(reNumUnit)[2];
  12478. if (
  12479. iconSpacingUnit !== iconWidthUnit ||
  12480. levelOfsUnit !== iconWidthUnit ||
  12481. labelSpacingUnit !== iconWidthUnit
  12482. ) {
  12483. $.error(
  12484. "iconWidth, iconSpacing, and levelOfs must have the same css measure unit"
  12485. );
  12486. }
  12487. this._local.measureUnit = iconWidthUnit;
  12488. this._local.levelOfs = parseFloat(levelOfs);
  12489. this._local.lineOfs =
  12490. (1 +
  12491. (ctx.options.checkbox ? 1 : 0) +
  12492. (ctx.options.icon === false ? 0 : 1)) *
  12493. (iconWidth + iconSpacing) +
  12494. iconSpacing;
  12495. this._local.labelOfs = labelSpacing;
  12496. this._local.maxDepth = 10;
  12497. // Get/Set a unique Id on the container (if not already exists)
  12498. containerId = this.$container.uniqueId().attr("id");
  12499. // Generated css rules for some levels (extended on demand)
  12500. cssText = renderLevelCss(
  12501. containerId,
  12502. this._local.maxDepth,
  12503. this._local.levelOfs,
  12504. this._local.lineOfs,
  12505. this._local.labelOfs,
  12506. this._local.measureUnit
  12507. );
  12508. defineHeadStyleElement(containerId, cssText);
  12509. },
  12510. treeDestroy: function (ctx) {
  12511. // Remove generated css rules
  12512. defineHeadStyleElement(this.$container.attr("id"), null);
  12513. return this._superApply(arguments);
  12514. },
  12515. nodeRenderStatus: function (ctx) {
  12516. var containerId,
  12517. cssText,
  12518. res,
  12519. node = ctx.node,
  12520. level = node.getLevel();
  12521. res = this._super(ctx);
  12522. // Generate some more level-n rules if required
  12523. if (level > this._local.maxDepth) {
  12524. containerId = this.$container.attr("id");
  12525. this._local.maxDepth *= 2;
  12526. node.debug(
  12527. "Define global ext-wide css up to level " +
  12528. this._local.maxDepth
  12529. );
  12530. cssText = renderLevelCss(
  12531. containerId,
  12532. this._local.maxDepth,
  12533. this._local.levelOfs,
  12534. this._local.lineOfs,
  12535. this._local.labelSpacing,
  12536. this._local.measureUnit
  12537. );
  12538. defineHeadStyleElement(containerId, cssText);
  12539. }
  12540. // Add level-n class to apply indentation padding.
  12541. // (Setting element style would not work, since it cannot easily be
  12542. // overriden while animations run)
  12543. $(node.span).addClass("fancytree-level-" + level);
  12544. return res;
  12545. },
  12546. });
  12547. // Value returned by `require('jquery.fancytree..')`
  12548. return $.ui.fancytree;
  12549. }); // End of closure