treelist.js 30 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198
  1. /**
  2. * Roundcube Treelist Widget
  3. *
  4. * This file is part of the Roundcube Webmail client
  5. *
  6. * @licstart The following is the entire license notice for the
  7. * JavaScript code in this file.
  8. *
  9. * Copyright (c) 2013-2014, The Roundcube Dev Team
  10. *
  11. * The JavaScript code in this page is free software: you can
  12. * redistribute it and/or modify it under the terms of the GNU
  13. * General Public License (GNU GPL) as published by the Free Software
  14. * Foundation, either version 3 of the License, or (at your option)
  15. * any later version. The code is distributed WITHOUT ANY WARRANTY;
  16. * without even the implied warranty of MERCHANTABILITY or FITNESS
  17. * FOR A PARTICULAR PURPOSE. See the GNU GPL for more details.
  18. *
  19. * As additional permission under GNU GPL version 3 section 7, you
  20. * may distribute non-source (e.g., minimized or compacted) forms of
  21. * that code without the copy of the GNU GPL normally required by
  22. * section 4, provided you include this license notice and a URL
  23. * through which recipients can access the Corresponding Source.
  24. *
  25. * @licend The above is the entire license notice
  26. * for the JavaScript code in this file.
  27. *
  28. * @author Thomas Bruederli <roundcube@gmail.com>
  29. * @requires jquery.js, common.js
  30. */
  31. /**
  32. * Roundcube Treelist widget class
  33. * @contructor
  34. */
  35. function rcube_treelist_widget(node, p)
  36. {
  37. // apply some defaults to p
  38. p = $.extend({
  39. id_prefix: '',
  40. autoexpand: 1000,
  41. selectable: false,
  42. scroll_delay: 500,
  43. scroll_step: 5,
  44. scroll_speed: 20,
  45. save_state: false,
  46. keyboard: true,
  47. tabexit: true,
  48. parent_focus: false,
  49. check_droptarget: function(node) { return !node.virtual; }
  50. }, p || {});
  51. var container = $(node),
  52. data = p.data || [],
  53. indexbyid = {},
  54. selection = null,
  55. drag_active = false,
  56. search_active = false,
  57. last_search = '',
  58. has_focus = false,
  59. box_coords = {},
  60. item_coords = [],
  61. autoexpand_timer,
  62. autoexpand_item,
  63. body_scroll_top = 0,
  64. list_scroll_top = 0,
  65. scroll_timer,
  66. searchfield,
  67. tree_state,
  68. ui_droppable,
  69. ui_draggable,
  70. draggable_opts,
  71. droppable_opts,
  72. list_id = (container.attr('id') || p.id_prefix || '0'),
  73. me = this;
  74. /////// export public members and methods
  75. this.container = container;
  76. this.expand = expand;
  77. this.collapse = collapse;
  78. this.select = select;
  79. this.render = render;
  80. this.reset = reset;
  81. this.drag_start = drag_start;
  82. this.drag_end = drag_end;
  83. this.intersects = intersects;
  84. this.droppable = droppable;
  85. this.draggable = draggable;
  86. this.update = update_node;
  87. this.insert = insert;
  88. this.remove = remove;
  89. this.get_item = get_item;
  90. this.get_node = get_node;
  91. this.get_selection = get_selection;
  92. this.is_search = is_search;
  93. this.reset_search = reset_search;
  94. /////// startup code (constructor)
  95. // abort if node not found
  96. if (!container.length)
  97. return;
  98. if (p.data)
  99. index_data({ children:data });
  100. // load data from DOM
  101. else
  102. update_data();
  103. // scroll to the selected item
  104. if (selection) {
  105. scroll_to_node(id2dom(selection, true));
  106. }
  107. container.attr('role', 'tree')
  108. .on('focusin', function(e) {
  109. // TODO: only accept focus on virtual nodes from keyboard events
  110. has_focus = true;
  111. })
  112. .on('focusout', function(e) {
  113. has_focus = false;
  114. })
  115. // register click handlers on list
  116. .on('click', 'div.treetoggle', function(e) {
  117. toggle(dom2id($(this).parent()));
  118. e.stopPropagation();
  119. })
  120. .on('click', 'li', function(e) {
  121. // do not select record on checkbox/input click
  122. if ($(e.target).is('input'))
  123. return true;
  124. var node = p.selectable ? indexbyid[dom2id($(this))] : null;
  125. if (node && !node.virtual) {
  126. select(node.id);
  127. e.stopPropagation();
  128. }
  129. })
  130. // mute clicks on virtual folder links (they need tabindex="0" in order to be selectable by keyboard)
  131. .on('mousedown', 'a', function(e) {
  132. var link = $(e.target), node = indexbyid[dom2id(link.closest('li'))];
  133. if (node && node.virtual && !link.attr('href')) {
  134. e.preventDefault();
  135. e.stopPropagation();
  136. return false;
  137. }
  138. });
  139. // activate search function
  140. if (p.searchbox) {
  141. searchfield = $(p.searchbox).off('keyup.treelist').on('keyup.treelist', function(e) {
  142. var key = rcube_event.get_keycode(e),
  143. mod = rcube_event.get_modifier(e);
  144. switch (key) {
  145. case 9: // tab
  146. break;
  147. case 13: // enter
  148. search(this.value, true);
  149. return rcube_event.cancel(e);
  150. case 27: // escape
  151. reset_search();
  152. break;
  153. case 38: // arrow up
  154. case 37: // left
  155. case 39: // right
  156. case 40: // arrow down
  157. return; // ignore arrow keys
  158. default:
  159. search(this.value, false);
  160. break;
  161. }
  162. }).attr('autocomplete', 'off');
  163. // find the reset button for this search field
  164. searchfield.parent().find('a.reset').off('click.treelist').on('click.treelist', function(e) {
  165. reset_search();
  166. return false;
  167. })
  168. }
  169. $(document.body).on('keydown', keypress);
  170. // catch focus when clicking the list container area
  171. if (p.parent_focus) {
  172. container.parent(':not(body)').click(function(e) {
  173. // click on a checkbox does not catch the focus
  174. if ($(e.target).is('input'))
  175. return true;
  176. if (!has_focus && selection) {
  177. $(get_item(selection)).find(':focusable').first().focus();
  178. }
  179. else if (!has_focus) {
  180. container.children('li:has(:focusable)').first().find(':focusable').first().focus();
  181. }
  182. });
  183. }
  184. /////// private methods
  185. /**
  186. * Collaps a the node with the given ID
  187. */
  188. function collapse(id, recursive, set)
  189. {
  190. var node;
  191. if (node = indexbyid[id]) {
  192. node.collapsed = typeof set == 'undefined' || set;
  193. update_dom(node);
  194. if (recursive && node.children) {
  195. for (var i=0; i < node.children.length; i++) {
  196. collapse(node.children[i].id, recursive, set);
  197. }
  198. }
  199. me.triggerEvent(node.collapsed ? 'collapse' : 'expand', node);
  200. save_state(id, node.collapsed);
  201. }
  202. }
  203. /**
  204. * Expand a the node with the given ID
  205. */
  206. function expand(id, recursive)
  207. {
  208. collapse(id, recursive, false);
  209. }
  210. /**
  211. * Toggle collapsed state of a list node
  212. */
  213. function toggle(id, recursive)
  214. {
  215. var node;
  216. if (node = indexbyid[id]) {
  217. collapse(id, recursive, !node.collapsed);
  218. }
  219. }
  220. /**
  221. * Select a tree node by it's ID
  222. */
  223. function select(id)
  224. {
  225. // allow subscribes to prevent selection change
  226. if (me.triggerEvent('beforeselect', indexbyid[id]) === false) {
  227. return;
  228. }
  229. if (selection) {
  230. id2dom(selection, true).removeClass('selected').removeAttr('aria-selected');
  231. if (search_active)
  232. id2dom(selection).removeClass('selected').removeAttr('aria-selected');
  233. selection = null;
  234. }
  235. if (!id)
  236. return;
  237. var li = id2dom(id, true);
  238. if (li.length) {
  239. li.addClass('selected').attr('aria-selected', 'true');
  240. selection = id;
  241. // TODO: expand all parent nodes if collapsed
  242. if (search_active)
  243. id2dom(id).addClass('selected').attr('aria-selected', 'true');
  244. scroll_to_node(li);
  245. }
  246. me.triggerEvent('select', indexbyid[id]);
  247. }
  248. /**
  249. * Getter for the currently selected node ID
  250. */
  251. function get_selection()
  252. {
  253. return selection;
  254. }
  255. /**
  256. * Return the DOM element of the list item with the given ID
  257. */
  258. function get_node(id)
  259. {
  260. return indexbyid[id];
  261. }
  262. /**
  263. * Return the DOM element of the list item with the given ID
  264. */
  265. function get_item(id, real)
  266. {
  267. return id2dom(id, real).get(0);
  268. }
  269. /**
  270. * Insert the given node
  271. */
  272. function insert(node, parent_id, sort)
  273. {
  274. var li, parent_li,
  275. parent_node = parent_id ? indexbyid[parent_id] : null
  276. search_ = search_active;
  277. // ignore, already exists
  278. if (indexbyid[node.id]) {
  279. return;
  280. }
  281. // apply saved state
  282. state = get_state(node.id, node.collapsed);
  283. if (state !== undefined) {
  284. node.collapsed = state;
  285. }
  286. // insert as child of an existing node
  287. if (parent_node) {
  288. node.level = parent_node.level + 1;
  289. if (!parent_node.children)
  290. parent_node.children = [];
  291. search_active = false;
  292. parent_node.children.push(node);
  293. parent_li = id2dom(parent_id);
  294. // re-render the entire subtree
  295. if (parent_node.children.length == 1) {
  296. render_node(parent_node, null, parent_li);
  297. li = id2dom(node.id);
  298. }
  299. else {
  300. // append new node to parent's child list
  301. li = render_node(node, parent_li.children('ul').first());
  302. }
  303. // list is in search mode
  304. if (search_) {
  305. search_active = search_;
  306. // add clone to current search results (top level)
  307. if (!li.is(':visible')) {
  308. $('<li>')
  309. .attr('id', li.attr('id') + '--xsR')
  310. .attr('class', li.attr('class'))
  311. .addClass('searchresult__')
  312. .append(li.children().first().clone(true, true))
  313. .appendTo(container);
  314. }
  315. }
  316. }
  317. // insert at top level
  318. else {
  319. node.level = 0;
  320. data.push(node);
  321. li = render_node(node, container);
  322. }
  323. indexbyid[node.id] = node;
  324. // set new reference to node.html after insert
  325. // will otherwise vanish in Firefox 3.6
  326. if (typeof node.html == 'object') {
  327. indexbyid[node.id].html = id2dom(node.id, true).children();
  328. }
  329. if (sort) {
  330. resort_node(li, typeof sort == 'string' ? '[class~="' + sort + '"]' : '');
  331. }
  332. }
  333. /**
  334. * Update properties of an existing node
  335. */
  336. function update_node(id, updates, sort)
  337. {
  338. var li, parent_ul, parent_node, old_parent,
  339. node = indexbyid[id];
  340. if (node) {
  341. li = id2dom(id);
  342. parent_ul = li.parent();
  343. if (updates.id || updates.html || updates.children || updates.classes || updates.parent) {
  344. if (updates.parent && (parent_node = indexbyid[updates.parent])) {
  345. // remove reference from old parent's child list
  346. if (parent_ul.closest('li').length && (old_parent = indexbyid[dom2id(parent_ul.closest('li'))])) {
  347. old_parent.children = $.grep(old_parent.children, function(elem, i){ return elem.id != node.id; });
  348. }
  349. // append to new parent node
  350. parent_ul = id2dom(updates.parent).children('ul').first();
  351. if (!parent_node.children)
  352. parent_node.children = [];
  353. parent_node.children.push(node);
  354. }
  355. else if (updates.parent !== undefined) {
  356. parent_ul = container;
  357. }
  358. $.extend(node, updates);
  359. li = render_node(node, parent_ul, li);
  360. }
  361. if (node.id != id) {
  362. delete indexbyid[id];
  363. indexbyid[node.id] = node;
  364. }
  365. if (sort) {
  366. resort_node(li, typeof sort == 'string' ? '[class~="' + sort + '"]' : '');
  367. }
  368. }
  369. }
  370. /**
  371. * Helper method to sort the list of the given item
  372. */
  373. function resort_node(li, filter)
  374. {
  375. var first, sibling,
  376. myid = li.get(0).id,
  377. sortname = li.children().first().text().toUpperCase();
  378. li.parent().children('li' + filter).each(function(i, elem) {
  379. if (i == 0)
  380. first = elem;
  381. if (elem.id == myid) {
  382. // skip
  383. }
  384. else if (elem.id != myid && sortname >= $(elem).children().first().text().toUpperCase()) {
  385. sibling = elem;
  386. }
  387. else {
  388. return false;
  389. }
  390. });
  391. if (sibling) {
  392. li.insertAfter(sibling);
  393. }
  394. else if (first && first.id != myid) {
  395. li.insertBefore(first);
  396. }
  397. // reload data from dom
  398. update_data();
  399. }
  400. /**
  401. * Remove the item with the given ID
  402. */
  403. function remove(id)
  404. {
  405. var node, li;
  406. if (node = indexbyid[id]) {
  407. li = id2dom(id, true);
  408. li.remove();
  409. node.deleted = true;
  410. delete indexbyid[id];
  411. if (search_active) {
  412. id2dom(id, false).remove();
  413. }
  414. return true;
  415. }
  416. return false;
  417. }
  418. /**
  419. * (Re-)read tree data from DOM
  420. */
  421. function update_data()
  422. {
  423. data = walk_list(container, 0);
  424. }
  425. /**
  426. * Apply the 'collapsed' status of the data node to the corresponding DOM element(s)
  427. */
  428. function update_dom(node)
  429. {
  430. var li = id2dom(node.id, true);
  431. li.attr('aria-expanded', node.collapsed ? 'false' : 'true');
  432. li.children('ul').first()[(node.collapsed ? 'hide' : 'show')]();
  433. li.children('div.treetoggle').removeClass('collapsed expanded').addClass(node.collapsed ? 'collapsed' : 'expanded');
  434. me.triggerEvent('toggle', node);
  435. }
  436. /**
  437. *
  438. */
  439. function reset(keep_content)
  440. {
  441. select('');
  442. data = [];
  443. indexbyid = {};
  444. drag_active = false;
  445. if (keep_content) {
  446. if (draggable_opts) {
  447. if (ui_draggable)
  448. draggable('destroy');
  449. draggable(draggable_opts);
  450. }
  451. if (droppable_opts) {
  452. if (ui_droppable)
  453. droppable('destroy');
  454. droppable(droppable_opts);
  455. }
  456. update_data();
  457. }
  458. else {
  459. container.html('');
  460. }
  461. reset_search();
  462. }
  463. /**
  464. *
  465. */
  466. function search(q, enter)
  467. {
  468. q = String(q).toLowerCase();
  469. if (!q.length)
  470. return reset_search();
  471. else if (q == last_search && !enter)
  472. return 0;
  473. var hits = [];
  474. var search_tree = function(items) {
  475. $.each(items, function(i, node) {
  476. var li, sli;
  477. if (!node.virtual && !node.deleted && String(node.text).toLowerCase().indexOf(q) >= 0 && hits.indexOf(node.id) < 0) {
  478. li = id2dom(node.id);
  479. // skip already filtered nodes
  480. if (li.data('filtered'))
  481. return;
  482. sli = $('<li>')
  483. .attr('id', li.attr('id') + '--xsR')
  484. .attr('class', li.attr('class'))
  485. .addClass('searchresult__')
  486. // append all elements like links and inputs, but not sub-trees
  487. .append(li.children(':not(div.treetoggle,ul)').clone(true, true))
  488. .appendTo(container);
  489. hits.push(node.id);
  490. }
  491. if (node.children && node.children.length) {
  492. search_tree(node.children);
  493. }
  494. });
  495. };
  496. // reset old search results
  497. if (search_active) {
  498. $(container).children('li.searchresult__').remove();
  499. search_active = false;
  500. }
  501. // hide all list items
  502. $(container).children('li').hide().removeClass('selected');
  503. // search recursively in tree (to keep sorting order)
  504. search_tree(data);
  505. search_active = true;
  506. me.triggerEvent('search', { query: q, last: last_search, count: hits.length, ids: hits, execute: enter||false });
  507. last_search = q;
  508. return hits.count;
  509. }
  510. /**
  511. *
  512. */
  513. function reset_search()
  514. {
  515. if (searchfield)
  516. searchfield.val('');
  517. $(container).children('li.searchresult__').remove();
  518. $(container).children('li').filter(function() { return !$(this).data('filtered'); }).show();
  519. search_active = false;
  520. me.triggerEvent('search', { query: false, last: last_search });
  521. last_search = '';
  522. if (selection)
  523. select(selection);
  524. }
  525. /**
  526. *
  527. */
  528. function is_search()
  529. {
  530. return search_active;
  531. }
  532. /**
  533. * Render the tree list from the internal data structure
  534. */
  535. function render()
  536. {
  537. if (me.triggerEvent('renderBefore', data) === false)
  538. return;
  539. // remove all child nodes
  540. container.html('');
  541. // render child nodes
  542. for (var i=0; i < data.length; i++) {
  543. data[i].level = 0;
  544. render_node(data[i], container);
  545. }
  546. me.triggerEvent('renderAfter', container);
  547. }
  548. /**
  549. * Render a specific node into the DOM list
  550. */
  551. function render_node(node, parent, replace)
  552. {
  553. if (node.deleted)
  554. return;
  555. var li = $('<li>')
  556. .attr('id', p.id_prefix + (p.id_encode ? p.id_encode(node.id) : node.id))
  557. .attr('role', 'treeitem')
  558. .addClass((node.classes || []).join(' '))
  559. .data('id', node.id);
  560. if (replace) {
  561. replace.replaceWith(li);
  562. if (parent)
  563. li.appendTo(parent);
  564. }
  565. else
  566. li.appendTo(parent);
  567. if (typeof node.html == 'string')
  568. li.html(node.html);
  569. else if (typeof node.html == 'object')
  570. li.append(node.html);
  571. if (!node.text)
  572. node.text = li.children().first().text();
  573. if (node.virtual)
  574. li.addClass('virtual');
  575. if (node.id == selection)
  576. li.addClass('selected');
  577. // add child list and toggle icon
  578. if (node.children && node.children.length) {
  579. li.attr('aria-expanded', node.collapsed ? 'false' : 'true');
  580. $('<div class="treetoggle '+(node.collapsed ? 'collapsed' : 'expanded') + '">&nbsp;</div>').appendTo(li);
  581. var ul = $('<ul>').appendTo(li).attr('class', node.childlistclass).attr('role', 'group');
  582. if (node.collapsed)
  583. ul.hide();
  584. for (var i=0; i < node.children.length; i++) {
  585. node.children[i].level = node.level + 1;
  586. render_node(node.children[i], ul);
  587. }
  588. }
  589. return li;
  590. }
  591. /**
  592. * Recursively walk the DOM tree and build an internal data structure
  593. * representing the skeleton of this tree list.
  594. */
  595. function walk_list(ul, level)
  596. {
  597. var result = [];
  598. ul.children('li').each(function(i,e){
  599. var state, li = $(e), sublist = li.children('ul');
  600. var node = {
  601. id: dom2id(li),
  602. classes: String(li.attr('class')).split(' '),
  603. virtual: li.hasClass('virtual'),
  604. level: level,
  605. html: li.children().first().get(0).outerHTML,
  606. text: li.children().first().text(),
  607. children: walk_list(sublist, level+1)
  608. }
  609. if (sublist.length) {
  610. node.childlistclass = sublist.attr('class');
  611. }
  612. if (node.children.length) {
  613. if (node.collapsed === undefined)
  614. node.collapsed = sublist.css('display') == 'none';
  615. // apply saved state
  616. state = get_state(node.id, node.collapsed);
  617. if (state !== undefined) {
  618. node.collapsed = state;
  619. sublist[(state?'hide':'show')]();
  620. }
  621. if (!li.children('div.treetoggle').length)
  622. $('<div class="treetoggle '+(node.collapsed ? 'collapsed' : 'expanded') + '">&nbsp;</div>').appendTo(li);
  623. li.attr('aria-expanded', node.collapsed ? 'false' : 'true');
  624. }
  625. if (li.hasClass('selected')) {
  626. li.attr('aria-selected', 'true');
  627. selection = node.id;
  628. }
  629. li.data('id', node.id);
  630. // declare list item as treeitem
  631. li.attr('role', 'treeitem').attr('aria-level', node.level+1);
  632. // allow virtual nodes to receive focus
  633. if (node.virtual) {
  634. li.children('a:first').attr('tabindex', '0');
  635. }
  636. result.push(node);
  637. indexbyid[node.id] = node;
  638. });
  639. ul.attr('role', level == 0 ? 'tree' : 'group');
  640. return result;
  641. }
  642. /**
  643. * Recursively walk the data tree and index nodes by their ID
  644. */
  645. function index_data(node)
  646. {
  647. if (node.id) {
  648. indexbyid[node.id] = node;
  649. }
  650. for (var c=0; node.children && c < node.children.length; c++) {
  651. index_data(node.children[c]);
  652. }
  653. }
  654. /**
  655. * Get the (stripped) node ID from the given DOM element
  656. */
  657. function dom2id(li)
  658. {
  659. var domid = String(li.attr('id')).replace(new RegExp('^' + (p.id_prefix) || '%'), '').replace(/--xsR$/, '');
  660. return p.id_decode ? p.id_decode(domid) : domid;
  661. }
  662. /**
  663. * Get the <li> element for the given node ID
  664. */
  665. function id2dom(id, real)
  666. {
  667. var domid = p.id_encode ? p.id_encode(id) : id,
  668. suffix = search_active && !real ? '--xsR' : '';
  669. return $('#' + p.id_prefix + domid + suffix, container);
  670. }
  671. /**
  672. * Scroll the parent container to make the given list item visible
  673. */
  674. function scroll_to_node(li)
  675. {
  676. var scroller = container.parent(),
  677. current_offset = scroller.scrollTop(),
  678. rel_offset = li.offset().top - scroller.offset().top;
  679. if (rel_offset < 0 || rel_offset + li.height() > scroller.height())
  680. scroller.scrollTop(rel_offset + current_offset);
  681. }
  682. /**
  683. * Save node collapse state to localStorage
  684. */
  685. function save_state(id, collapsed)
  686. {
  687. if (p.save_state && window.rcmail) {
  688. var key = 'treelist-' + list_id;
  689. if (!tree_state) {
  690. tree_state = rcmail.local_storage_get_item(key, {});
  691. }
  692. if (tree_state[id] != collapsed) {
  693. tree_state[id] = collapsed;
  694. rcmail.local_storage_set_item(key, tree_state);
  695. }
  696. }
  697. }
  698. /**
  699. * Read node collapse state from localStorage
  700. */
  701. function get_state(id)
  702. {
  703. if (p.save_state && window.rcmail) {
  704. if (!tree_state) {
  705. tree_state = rcmail.local_storage_get_item('treelist-' + list_id, {});
  706. }
  707. return tree_state[id];
  708. }
  709. return undefined;
  710. }
  711. /**
  712. * Handler for keyboard events on treelist
  713. */
  714. function keypress(e)
  715. {
  716. var target = e.target || {},
  717. keyCode = rcube_event.get_keycode(e);
  718. if (!has_focus || target.nodeName == 'INPUT' && keyCode != 38 && keyCode != 40 || target.nodeName == 'TEXTAREA' || target.nodeName == 'SELECT')
  719. return true;
  720. switch (keyCode) {
  721. case 38:
  722. case 40:
  723. case 63232: // 'up', in safari keypress
  724. case 63233: // 'down', in safari keypress
  725. var li = p.keyboard ? container.find(':focus').closest('li') : [];
  726. if (li.length) {
  727. focus_next(li, (mod = keyCode == 38 || keyCode == 63232 ? -1 : 1));
  728. }
  729. return rcube_event.cancel(e);
  730. case 37: // Left arrow key
  731. case 39: // Right arrow key
  732. var id, node, li = container.find(':focus').closest('li');
  733. if (li.length) {
  734. id = dom2id(li);
  735. node = indexbyid[id];
  736. if (node && node.children.length && node.collapsed != (keyCode == 37))
  737. toggle(id, rcube_event.get_modifier(e) == SHIFT_KEY); // toggle subtree
  738. }
  739. return false;
  740. case 9: // Tab
  741. if (p.keyboard && p.tabexit) {
  742. // jump to last/first item to move focus away from the treelist widget by tab
  743. var limit = rcube_event.get_modifier(e) == SHIFT_KEY ? 'first' : 'last';
  744. focus_noscroll(container.find('li[role=treeitem]:has(a)')[limit]().find('a:'+limit));
  745. }
  746. break;
  747. }
  748. return true;
  749. }
  750. function focus_next(li, dir, from_child)
  751. {
  752. var mod = dir < 0 ? 'prev' : 'next',
  753. next = li[mod](), limit, parent;
  754. if (dir > 0 && !from_child && li.children('ul[role=group]:visible').length) {
  755. li.children('ul').children('li:first').find('a:first').focus();
  756. }
  757. else if (dir < 0 && !from_child && next.children('ul[role=group]:visible').length) {
  758. next.children('ul').children('li:last').find('a:first').focus();
  759. }
  760. else if (next.length && next.find('a:first').focus().length) {
  761. // focused
  762. }
  763. else {
  764. parent = li.parent().closest('li[role=treeitem]');
  765. if (parent.length)
  766. if (dir < 0) {
  767. parent.find('a:first').focus();
  768. }
  769. else {
  770. focus_next(parent, dir, true);
  771. }
  772. }
  773. }
  774. /**
  775. * Focus the given element without scrolling the list container
  776. */
  777. function focus_noscroll(elem)
  778. {
  779. if (elem.length) {
  780. var frame = container.parent().get(0) || { scrollTop:0 },
  781. y = frame.scrollTop || frame.scrollY;
  782. elem.focus();
  783. frame.scrollTop = y;
  784. }
  785. }
  786. ///// drag & drop support
  787. /**
  788. * When dragging starts, compute absolute bounding boxes of the list and it's items
  789. * for faster comparisons while mouse is moving
  790. */
  791. function drag_start(force)
  792. {
  793. if (!force && drag_active)
  794. return;
  795. drag_active = true;
  796. var li, item, height,
  797. pos = container.offset();
  798. body_scroll_top = bw.ie ? 0 : window.pageYOffset;
  799. list_scroll_top = container.parent().scrollTop();
  800. pos.top += list_scroll_top;
  801. box_coords = {
  802. x1: pos.left,
  803. y1: pos.top,
  804. x2: pos.left + container.width(),
  805. y2: pos.top + container.height()
  806. };
  807. item_coords = [];
  808. for (var id in indexbyid) {
  809. li = id2dom(id);
  810. item = li.children().first().get(0);
  811. if (item && (height = item.offsetHeight)) {
  812. pos = $(item).offset();
  813. pos.top += list_scroll_top;
  814. item_coords[id] = {
  815. x1: pos.left,
  816. y1: pos.top,
  817. x2: pos.left + item.offsetWidth,
  818. y2: pos.top + height,
  819. on: id == autoexpand_item
  820. };
  821. }
  822. }
  823. // enable auto-scrolling of list container
  824. if (container.height() > container.parent().height()) {
  825. container.parent()
  826. .mousemove(function(e) {
  827. var scroll = 0,
  828. mouse = rcube_event.get_mouse_pos(e);
  829. mouse.y -= container.parent().offset().top;
  830. if (mouse.y < 25 && list_scroll_top > 0) {
  831. scroll = -1; // up
  832. }
  833. else if (mouse.y > container.parent().height() - 25) {
  834. scroll = 1; // down
  835. }
  836. if (drag_active && scroll != 0) {
  837. if (!scroll_timer)
  838. scroll_timer = window.setTimeout(function(){ drag_scroll(scroll); }, p.scroll_delay);
  839. }
  840. else if (scroll_timer) {
  841. window.clearTimeout(scroll_timer);
  842. scroll_timer = null;
  843. }
  844. })
  845. .mouseleave(function() {
  846. if (scroll_timer) {
  847. window.clearTimeout(scroll_timer);
  848. scroll_timer = null;
  849. }
  850. });
  851. }
  852. }
  853. /**
  854. * Signal that dragging has stopped
  855. */
  856. function drag_end()
  857. {
  858. if (!drag_active)
  859. return;
  860. drag_active = false;
  861. scroll_timer = null;
  862. if (autoexpand_timer) {
  863. clearTimeout(autoexpand_timer);
  864. autoexpand_timer = null;
  865. autoexpand_item = null;
  866. }
  867. $('li.droptarget', container).removeClass('droptarget');
  868. }
  869. /**
  870. * Scroll list container in the given direction
  871. */
  872. function drag_scroll(dir)
  873. {
  874. if (!drag_active)
  875. return;
  876. var old_top = list_scroll_top;
  877. container.parent().get(0).scrollTop += p.scroll_step * dir;
  878. list_scroll_top = container.parent().scrollTop();
  879. scroll_timer = null;
  880. if (list_scroll_top != old_top)
  881. scroll_timer = window.setTimeout(function(){ drag_scroll(dir); }, p.scroll_speed);
  882. }
  883. /**
  884. * Determine if the given mouse coords intersect the list and one of its items
  885. */
  886. function intersects(mouse, highlight)
  887. {
  888. // offsets to compensate for scrolling while dragging a message
  889. var boffset = bw.ie ? -document.documentElement.scrollTop : body_scroll_top,
  890. moffset = container.parent().scrollTop(),
  891. result = null;
  892. mouse.top = mouse.y + moffset - boffset;
  893. // no intersection with list bounding box
  894. if (mouse.x < box_coords.x1 || mouse.x >= box_coords.x2 || mouse.top < box_coords.y1 || mouse.top >= box_coords.y2) {
  895. // TODO: optimize performance for this operation
  896. if (highlight)
  897. $('li.droptarget', container).removeClass('droptarget');
  898. return result;
  899. }
  900. // check intersection with visible list items
  901. var id, pos, node;
  902. for (id in item_coords) {
  903. pos = item_coords[id];
  904. if (mouse.x >= pos.x1 && mouse.x < pos.x2 && mouse.top >= pos.y1 && mouse.top < pos.y2) {
  905. node = indexbyid[id];
  906. // if the folder is collapsed, expand it after the configured time
  907. if (node.children && node.children.length && node.collapsed && p.autoexpand && autoexpand_item != id) {
  908. if (autoexpand_timer)
  909. clearTimeout(autoexpand_timer);
  910. autoexpand_item = id;
  911. autoexpand_timer = setTimeout(function() {
  912. expand(autoexpand_item);
  913. drag_start(true); // re-calculate item coords
  914. autoexpand_item = null;
  915. if (ui_droppable)
  916. $.ui.ddmanager.prepareOffsets($.ui.ddmanager.current, null);
  917. }, p.autoexpand);
  918. }
  919. else if (autoexpand_timer && autoexpand_item != id) {
  920. clearTimeout(autoexpand_timer);
  921. autoexpand_item = null;
  922. autoexpand_timer = null;
  923. }
  924. // check if this item is accepted as drop target
  925. if (p.check_droptarget(node)) {
  926. if (highlight) {
  927. id2dom(id).addClass('droptarget');
  928. pos.on = true;
  929. }
  930. result = id;
  931. }
  932. else {
  933. result = null;
  934. }
  935. }
  936. else if (pos.on) {
  937. id2dom(id).removeClass('droptarget');
  938. pos.on = false;
  939. }
  940. }
  941. return result;
  942. }
  943. /**
  944. * Wrapper for jQuery.UI.droppable() activation on this widget
  945. *
  946. * @param object Options as passed to regular .droppable() function
  947. */
  948. function droppable(opts)
  949. {
  950. if (!opts) opts = {};
  951. if ($.type(opts) == 'string') {
  952. if (opts == 'destroy') {
  953. ui_droppable = null;
  954. }
  955. $('li:not(.virtual)', container).droppable(opts);
  956. return this;
  957. }
  958. droppable_opts = opts;
  959. var my_opts = $.extend({
  960. greedy: true,
  961. tolerance: 'pointer',
  962. hoverClass: 'droptarget',
  963. addClasses: false
  964. }, opts);
  965. my_opts.activate = function(e, ui) {
  966. drag_start();
  967. ui_droppable = ui;
  968. if (opts.activate)
  969. opts.activate(e, ui);
  970. };
  971. my_opts.deactivate = function(e, ui) {
  972. drag_end();
  973. ui_droppable = null;
  974. if (opts.deactivate)
  975. opts.deactivate(e, ui);
  976. };
  977. my_opts.over = function(e, ui) {
  978. intersects(rcube_event.get_mouse_pos(e), false);
  979. if (opts.over)
  980. opts.over(e, ui);
  981. };
  982. $('li:not(.virtual)', container).droppable(my_opts);
  983. return this;
  984. }
  985. /**
  986. * Wrapper for jQuery.UI.draggable() activation on this widget
  987. *
  988. * @param object Options as passed to regular .draggable() function
  989. */
  990. function draggable(opts)
  991. {
  992. if (!opts) opts = {};
  993. if ($.type(opts) == 'string') {
  994. if (opts == 'destroy') {
  995. ui_draggable = null;
  996. }
  997. $('li:not(.virtual)', container).draggable(opts);
  998. return this;
  999. }
  1000. draggable_opts = opts;
  1001. var my_opts = $.extend({
  1002. appendTo: 'body',
  1003. revert: 'invalid',
  1004. iframeFix: true,
  1005. addClasses: false,
  1006. cursorAt: {left: -20, top: 5},
  1007. create: function(e, ui) { ui_draggable = ui; },
  1008. helper: function(e) {
  1009. return $('<div>').attr('id', 'rcmdraglayer')
  1010. .text($.trim($(e.target).first().text()));
  1011. }
  1012. }, opts);
  1013. $('li:not(.virtual)', container).draggable(my_opts);
  1014. return this;
  1015. }
  1016. }
  1017. // use event processing functions from Roundcube's rcube_event_engine
  1018. rcube_treelist_widget.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
  1019. rcube_treelist_widget.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
  1020. rcube_treelist_widget.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;