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.

treelist.js 30KB

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