您最多选择25个主题 主题必须以字母或数字开头,可以包含连字符 (-),并且长度不得超过35个字符

treelist.js 31KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205
  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. * @constructor
  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, parent;
  406. if (node = indexbyid[id]) {
  407. li = id2dom(id, true);
  408. parent = li.parent();
  409. li.remove();
  410. node.deleted = true;
  411. delete indexbyid[id];
  412. if (search_active) {
  413. id2dom(id, false).remove();
  414. }
  415. // remove tree-toggle button and children list
  416. if (!parent.children().length) {
  417. parent.parent().find('div.treetoggle').remove();
  418. parent.remove();
  419. }
  420. return true;
  421. }
  422. return false;
  423. }
  424. /**
  425. * (Re-)read tree data from DOM
  426. */
  427. function update_data()
  428. {
  429. data = walk_list(container, 0);
  430. }
  431. /**
  432. * Apply the 'collapsed' status of the data node to the corresponding DOM element(s)
  433. */
  434. function update_dom(node)
  435. {
  436. var li = id2dom(node.id, true);
  437. li.attr('aria-expanded', node.collapsed ? 'false' : 'true');
  438. li.children('ul').first()[(node.collapsed ? 'hide' : 'show')]();
  439. li.children('div.treetoggle').removeClass('collapsed expanded').addClass(node.collapsed ? 'collapsed' : 'expanded');
  440. me.triggerEvent('toggle', node);
  441. }
  442. /**
  443. *
  444. */
  445. function reset(keep_content)
  446. {
  447. select('');
  448. data = [];
  449. indexbyid = {};
  450. drag_active = false;
  451. if (keep_content) {
  452. if (draggable_opts) {
  453. if (ui_draggable)
  454. draggable('destroy');
  455. draggable(draggable_opts);
  456. }
  457. if (droppable_opts) {
  458. if (ui_droppable)
  459. droppable('destroy');
  460. droppable(droppable_opts);
  461. }
  462. update_data();
  463. }
  464. else {
  465. container.html('');
  466. }
  467. reset_search();
  468. }
  469. /**
  470. *
  471. */
  472. function search(q, enter)
  473. {
  474. q = String(q).toLowerCase();
  475. if (!q.length)
  476. return reset_search();
  477. else if (q == last_search && !enter)
  478. return 0;
  479. var hits = [];
  480. var search_tree = function(items) {
  481. $.each(items, function(i, node) {
  482. var li, sli;
  483. if (!node.virtual && !node.deleted && String(node.text).toLowerCase().indexOf(q) >= 0 && hits.indexOf(node.id) < 0) {
  484. li = id2dom(node.id);
  485. // skip already filtered nodes
  486. if (li.data('filtered'))
  487. return;
  488. sli = $('<li>')
  489. .attr('id', li.attr('id') + '--xsR')
  490. .attr('class', li.attr('class'))
  491. .addClass('searchresult__')
  492. // append all elements like links and inputs, but not sub-trees
  493. .append(li.children(':not(div.treetoggle,ul)').clone(true, true))
  494. .appendTo(container);
  495. hits.push(node.id);
  496. }
  497. if (node.children && node.children.length) {
  498. search_tree(node.children);
  499. }
  500. });
  501. };
  502. // reset old search results
  503. if (search_active) {
  504. $(container).children('li.searchresult__').remove();
  505. search_active = false;
  506. }
  507. // hide all list items
  508. $(container).children('li').hide().removeClass('selected');
  509. // search recursively in tree (to keep sorting order)
  510. search_tree(data);
  511. search_active = true;
  512. me.triggerEvent('search', { query: q, last: last_search, count: hits.length, ids: hits, execute: enter||false });
  513. last_search = q;
  514. return hits.count;
  515. }
  516. /**
  517. *
  518. */
  519. function reset_search()
  520. {
  521. if (searchfield)
  522. searchfield.val('');
  523. $(container).children('li.searchresult__').remove();
  524. $(container).children('li').filter(function() { return !$(this).data('filtered'); }).show();
  525. search_active = false;
  526. me.triggerEvent('search', { query: false, last: last_search });
  527. last_search = '';
  528. if (selection)
  529. select(selection);
  530. }
  531. /**
  532. *
  533. */
  534. function is_search()
  535. {
  536. return search_active;
  537. }
  538. /**
  539. * Render the tree list from the internal data structure
  540. */
  541. function render()
  542. {
  543. if (me.triggerEvent('renderBefore', data) === false)
  544. return;
  545. // remove all child nodes
  546. container.html('');
  547. // render child nodes
  548. for (var i=0; i < data.length; i++) {
  549. data[i].level = 0;
  550. render_node(data[i], container);
  551. }
  552. me.triggerEvent('renderAfter', container);
  553. }
  554. /**
  555. * Render a specific node into the DOM list
  556. */
  557. function render_node(node, parent, replace)
  558. {
  559. if (node.deleted)
  560. return;
  561. var li = $('<li>')
  562. .attr('id', p.id_prefix + (p.id_encode ? p.id_encode(node.id) : node.id))
  563. .attr('role', 'treeitem')
  564. .addClass((node.classes || []).join(' '))
  565. .data('id', node.id);
  566. if (replace) {
  567. replace.replaceWith(li);
  568. if (parent)
  569. li.appendTo(parent);
  570. }
  571. else
  572. li.appendTo(parent);
  573. if (typeof node.html == 'string')
  574. li.html(node.html);
  575. else if (typeof node.html == 'object')
  576. li.append(node.html);
  577. if (!node.text)
  578. node.text = li.children().first().text();
  579. if (node.virtual)
  580. li.addClass('virtual');
  581. if (node.id == selection)
  582. li.addClass('selected');
  583. // add child list and toggle icon
  584. if (node.children && node.children.length) {
  585. li.attr('aria-expanded', node.collapsed ? 'false' : 'true');
  586. $('<div class="treetoggle '+(node.collapsed ? 'collapsed' : 'expanded') + '">&nbsp;</div>').appendTo(li);
  587. var ul = $('<ul>').appendTo(li).attr('class', node.childlistclass).attr('role', 'group');
  588. if (node.collapsed)
  589. ul.hide();
  590. for (var i=0; i < node.children.length; i++) {
  591. node.children[i].level = node.level + 1;
  592. render_node(node.children[i], ul);
  593. }
  594. }
  595. return li;
  596. }
  597. /**
  598. * Recursively walk the DOM tree and build an internal data structure
  599. * representing the skeleton of this tree list.
  600. */
  601. function walk_list(ul, level)
  602. {
  603. var result = [];
  604. ul.children('li').each(function(i,e){
  605. var state, li = $(e), sublist = li.children('ul');
  606. var node = {
  607. id: dom2id(li),
  608. classes: String(li.attr('class')).split(' '),
  609. virtual: li.hasClass('virtual'),
  610. level: level,
  611. html: li.children().first().get(0).outerHTML,
  612. text: li.children().first().text(),
  613. children: walk_list(sublist, level+1)
  614. }
  615. if (sublist.length) {
  616. node.childlistclass = sublist.attr('class');
  617. }
  618. if (node.children.length) {
  619. if (node.collapsed === undefined)
  620. node.collapsed = sublist.css('display') == 'none';
  621. // apply saved state
  622. state = get_state(node.id, node.collapsed);
  623. if (state !== undefined) {
  624. node.collapsed = state;
  625. sublist[(state?'hide':'show')]();
  626. }
  627. if (!li.children('div.treetoggle').length)
  628. $('<div class="treetoggle '+(node.collapsed ? 'collapsed' : 'expanded') + '">&nbsp;</div>').appendTo(li);
  629. li.attr('aria-expanded', node.collapsed ? 'false' : 'true');
  630. }
  631. if (li.hasClass('selected')) {
  632. li.attr('aria-selected', 'true');
  633. selection = node.id;
  634. }
  635. li.data('id', node.id);
  636. // declare list item as treeitem
  637. li.attr('role', 'treeitem').attr('aria-level', node.level+1);
  638. // allow virtual nodes to receive focus
  639. if (node.virtual) {
  640. li.children('a:first').attr('tabindex', '0');
  641. }
  642. result.push(node);
  643. indexbyid[node.id] = node;
  644. });
  645. ul.attr('role', level == 0 ? 'tree' : 'group');
  646. return result;
  647. }
  648. /**
  649. * Recursively walk the data tree and index nodes by their ID
  650. */
  651. function index_data(node)
  652. {
  653. if (node.id) {
  654. indexbyid[node.id] = node;
  655. }
  656. for (var c=0; node.children && c < node.children.length; c++) {
  657. index_data(node.children[c]);
  658. }
  659. }
  660. /**
  661. * Get the (stripped) node ID from the given DOM element
  662. */
  663. function dom2id(li)
  664. {
  665. var domid = String(li.attr('id')).replace(new RegExp('^' + (p.id_prefix) || '%'), '').replace(/--xsR$/, '');
  666. return p.id_decode ? p.id_decode(domid) : domid;
  667. }
  668. /**
  669. * Get the <li> element for the given node ID
  670. */
  671. function id2dom(id, real)
  672. {
  673. var domid = p.id_encode ? p.id_encode(id) : id,
  674. suffix = search_active && !real ? '--xsR' : '';
  675. return $('#' + p.id_prefix + domid + suffix, container);
  676. }
  677. /**
  678. * Scroll the parent container to make the given list item visible
  679. */
  680. function scroll_to_node(li)
  681. {
  682. var scroller = container.parent(),
  683. current_offset = scroller.scrollTop(),
  684. rel_offset = li.offset().top - scroller.offset().top;
  685. if (rel_offset < 0 || rel_offset + li.height() > scroller.height())
  686. scroller.scrollTop(rel_offset + current_offset);
  687. }
  688. /**
  689. * Save node collapse state to localStorage
  690. */
  691. function save_state(id, collapsed)
  692. {
  693. if (p.save_state && window.rcmail) {
  694. var key = 'treelist-' + list_id;
  695. if (!tree_state) {
  696. tree_state = rcmail.local_storage_get_item(key, {});
  697. }
  698. if (tree_state[id] != collapsed) {
  699. tree_state[id] = collapsed;
  700. rcmail.local_storage_set_item(key, tree_state);
  701. }
  702. }
  703. }
  704. /**
  705. * Read node collapse state from localStorage
  706. */
  707. function get_state(id)
  708. {
  709. if (p.save_state && window.rcmail) {
  710. if (!tree_state) {
  711. tree_state = rcmail.local_storage_get_item('treelist-' + list_id, {});
  712. }
  713. return tree_state[id];
  714. }
  715. return undefined;
  716. }
  717. /**
  718. * Handler for keyboard events on treelist
  719. */
  720. function keypress(e)
  721. {
  722. var target = e.target || {},
  723. keyCode = rcube_event.get_keycode(e);
  724. if (!has_focus || target.nodeName == 'INPUT' && keyCode != 38 && keyCode != 40 || target.nodeName == 'TEXTAREA' || target.nodeName == 'SELECT')
  725. return true;
  726. switch (keyCode) {
  727. case 38:
  728. case 40:
  729. case 63232: // 'up', in safari keypress
  730. case 63233: // 'down', in safari keypress
  731. var li = p.keyboard ? container.find(':focus').closest('li') : [];
  732. if (li.length) {
  733. focus_next(li, (mod = keyCode == 38 || keyCode == 63232 ? -1 : 1));
  734. }
  735. return rcube_event.cancel(e);
  736. case 37: // Left arrow key
  737. case 39: // Right arrow key
  738. var id, node, li = container.find(':focus').closest('li');
  739. if (li.length) {
  740. id = dom2id(li);
  741. node = indexbyid[id];
  742. if (node && node.children.length && node.collapsed != (keyCode == 37))
  743. toggle(id, rcube_event.get_modifier(e) == SHIFT_KEY); // toggle subtree
  744. }
  745. return false;
  746. case 9: // Tab
  747. if (p.keyboard && p.tabexit) {
  748. // jump to last/first item to move focus away from the treelist widget by tab
  749. var limit = rcube_event.get_modifier(e) == SHIFT_KEY ? 'first' : 'last';
  750. focus_noscroll(container.find('li[role=treeitem]:has(a)')[limit]().find('a:'+limit));
  751. }
  752. break;
  753. }
  754. return true;
  755. }
  756. function focus_next(li, dir, from_child)
  757. {
  758. var mod = dir < 0 ? 'prev' : 'next',
  759. next = li[mod](), limit, parent;
  760. if (dir > 0 && !from_child && li.children('ul[role=group]:visible').length) {
  761. li.children('ul').children('li:first').find('a:first').focus();
  762. }
  763. else if (dir < 0 && !from_child && next.children('ul[role=group]:visible').length) {
  764. next.children('ul').children('li:last').find('a:first').focus();
  765. }
  766. else if (next.length && next.find('a:first').focus().length) {
  767. // focused
  768. }
  769. else {
  770. parent = li.parent().closest('li[role=treeitem]');
  771. if (parent.length)
  772. if (dir < 0) {
  773. parent.find('a:first').focus();
  774. }
  775. else {
  776. focus_next(parent, dir, true);
  777. }
  778. }
  779. }
  780. /**
  781. * Focus the given element without scrolling the list container
  782. */
  783. function focus_noscroll(elem)
  784. {
  785. if (elem.length) {
  786. var frame = container.parent().get(0) || { scrollTop:0 },
  787. y = frame.scrollTop || frame.scrollY;
  788. elem.focus();
  789. frame.scrollTop = y;
  790. }
  791. }
  792. ///// drag & drop support
  793. /**
  794. * When dragging starts, compute absolute bounding boxes of the list and it's items
  795. * for faster comparisons while mouse is moving
  796. */
  797. function drag_start(force)
  798. {
  799. if (!force && drag_active)
  800. return;
  801. drag_active = true;
  802. var li, item, height,
  803. pos = container.offset();
  804. body_scroll_top = bw.ie ? 0 : window.pageYOffset;
  805. list_scroll_top = container.parent().scrollTop();
  806. pos.top += list_scroll_top;
  807. box_coords = {
  808. x1: pos.left,
  809. y1: pos.top,
  810. x2: pos.left + container.width(),
  811. y2: pos.top + container.height()
  812. };
  813. item_coords = [];
  814. for (var id in indexbyid) {
  815. li = id2dom(id);
  816. item = li.children().first().get(0);
  817. if (item && (height = item.offsetHeight)) {
  818. pos = $(item).offset();
  819. pos.top += list_scroll_top;
  820. item_coords[id] = {
  821. x1: pos.left,
  822. y1: pos.top,
  823. x2: pos.left + item.offsetWidth,
  824. y2: pos.top + height,
  825. on: id == autoexpand_item
  826. };
  827. }
  828. }
  829. // enable auto-scrolling of list container
  830. if (container.height() > container.parent().height()) {
  831. container.parent()
  832. .mousemove(function(e) {
  833. var scroll = 0,
  834. mouse = rcube_event.get_mouse_pos(e);
  835. mouse.y -= container.parent().offset().top;
  836. if (mouse.y < 25 && list_scroll_top > 0) {
  837. scroll = -1; // up
  838. }
  839. else if (mouse.y > container.parent().height() - 25) {
  840. scroll = 1; // down
  841. }
  842. if (drag_active && scroll != 0) {
  843. if (!scroll_timer)
  844. scroll_timer = window.setTimeout(function(){ drag_scroll(scroll); }, p.scroll_delay);
  845. }
  846. else if (scroll_timer) {
  847. window.clearTimeout(scroll_timer);
  848. scroll_timer = null;
  849. }
  850. })
  851. .mouseleave(function() {
  852. if (scroll_timer) {
  853. window.clearTimeout(scroll_timer);
  854. scroll_timer = null;
  855. }
  856. });
  857. }
  858. }
  859. /**
  860. * Signal that dragging has stopped
  861. */
  862. function drag_end()
  863. {
  864. if (!drag_active)
  865. return;
  866. drag_active = false;
  867. scroll_timer = null;
  868. if (autoexpand_timer) {
  869. clearTimeout(autoexpand_timer);
  870. autoexpand_timer = null;
  871. autoexpand_item = null;
  872. }
  873. $('li.droptarget', container).removeClass('droptarget');
  874. }
  875. /**
  876. * Scroll list container in the given direction
  877. */
  878. function drag_scroll(dir)
  879. {
  880. if (!drag_active)
  881. return;
  882. var old_top = list_scroll_top;
  883. container.parent().get(0).scrollTop += p.scroll_step * dir;
  884. list_scroll_top = container.parent().scrollTop();
  885. scroll_timer = null;
  886. if (list_scroll_top != old_top)
  887. scroll_timer = window.setTimeout(function(){ drag_scroll(dir); }, p.scroll_speed);
  888. }
  889. /**
  890. * Determine if the given mouse coords intersect the list and one of its items
  891. */
  892. function intersects(mouse, highlight)
  893. {
  894. // offsets to compensate for scrolling while dragging a message
  895. var boffset = bw.ie ? -document.documentElement.scrollTop : body_scroll_top,
  896. moffset = container.parent().scrollTop(),
  897. result = null;
  898. mouse.top = mouse.y + moffset - boffset;
  899. // no intersection with list bounding box
  900. if (mouse.x < box_coords.x1 || mouse.x >= box_coords.x2 || mouse.top < box_coords.y1 || mouse.top >= box_coords.y2) {
  901. // TODO: optimize performance for this operation
  902. if (highlight)
  903. $('li.droptarget', container).removeClass('droptarget');
  904. return result;
  905. }
  906. // check intersection with visible list items
  907. var id, pos, node;
  908. for (id in item_coords) {
  909. pos = item_coords[id];
  910. if (mouse.x >= pos.x1 && mouse.x < pos.x2 && mouse.top >= pos.y1 && mouse.top < pos.y2) {
  911. node = indexbyid[id];
  912. // if the folder is collapsed, expand it after the configured time
  913. if (node.children && node.children.length && node.collapsed && p.autoexpand && autoexpand_item != id) {
  914. if (autoexpand_timer)
  915. clearTimeout(autoexpand_timer);
  916. autoexpand_item = id;
  917. autoexpand_timer = setTimeout(function() {
  918. expand(autoexpand_item);
  919. drag_start(true); // re-calculate item coords
  920. autoexpand_item = null;
  921. if (ui_droppable)
  922. $.ui.ddmanager.prepareOffsets($.ui.ddmanager.current, null);
  923. }, p.autoexpand);
  924. }
  925. else if (autoexpand_timer && autoexpand_item != id) {
  926. clearTimeout(autoexpand_timer);
  927. autoexpand_item = null;
  928. autoexpand_timer = null;
  929. }
  930. // check if this item is accepted as drop target
  931. if (p.check_droptarget(node)) {
  932. if (highlight) {
  933. id2dom(id).addClass('droptarget');
  934. pos.on = true;
  935. }
  936. result = id;
  937. }
  938. else {
  939. result = null;
  940. }
  941. }
  942. else if (pos.on) {
  943. id2dom(id).removeClass('droptarget');
  944. pos.on = false;
  945. }
  946. }
  947. return result;
  948. }
  949. /**
  950. * Wrapper for jQuery.UI.droppable() activation on this widget
  951. *
  952. * @param object Options as passed to regular .droppable() function
  953. */
  954. function droppable(opts)
  955. {
  956. if (!opts) opts = {};
  957. if ($.type(opts) == 'string') {
  958. if (opts == 'destroy') {
  959. ui_droppable = null;
  960. }
  961. $('li:not(.virtual)', container).droppable(opts);
  962. return this;
  963. }
  964. droppable_opts = opts;
  965. var my_opts = $.extend({
  966. greedy: true,
  967. tolerance: 'pointer',
  968. hoverClass: 'droptarget',
  969. addClasses: false
  970. }, opts);
  971. my_opts.activate = function(e, ui) {
  972. drag_start();
  973. ui_droppable = ui;
  974. if (opts.activate)
  975. opts.activate(e, ui);
  976. };
  977. my_opts.deactivate = function(e, ui) {
  978. drag_end();
  979. ui_droppable = null;
  980. if (opts.deactivate)
  981. opts.deactivate(e, ui);
  982. };
  983. my_opts.over = function(e, ui) {
  984. intersects(rcube_event.get_mouse_pos(e), false);
  985. if (opts.over)
  986. opts.over(e, ui);
  987. };
  988. $('li:not(.virtual)', container).droppable(my_opts);
  989. return this;
  990. }
  991. /**
  992. * Wrapper for jQuery.UI.draggable() activation on this widget
  993. *
  994. * @param object Options as passed to regular .draggable() function
  995. */
  996. function draggable(opts)
  997. {
  998. if (!opts) opts = {};
  999. if ($.type(opts) == 'string') {
  1000. if (opts == 'destroy') {
  1001. ui_draggable = null;
  1002. }
  1003. $('li:not(.virtual)', container).draggable(opts);
  1004. return this;
  1005. }
  1006. draggable_opts = opts;
  1007. var my_opts = $.extend({
  1008. appendTo: 'body',
  1009. revert: 'invalid',
  1010. iframeFix: true,
  1011. addClasses: false,
  1012. cursorAt: {left: -20, top: 5},
  1013. create: function(e, ui) { ui_draggable = ui; },
  1014. helper: function(e) {
  1015. return $('<div>').attr('id', 'rcmdraglayer')
  1016. .text($.trim($(e.target).first().text()));
  1017. }
  1018. }, opts);
  1019. $('li:not(.virtual)', container).draggable(my_opts);
  1020. return this;
  1021. }
  1022. }
  1023. // use event processing functions from Roundcube's rcube_event_engine
  1024. rcube_treelist_widget.prototype.addEventListener = rcube_event_engine.prototype.addEventListener;
  1025. rcube_treelist_widget.prototype.removeEventListener = rcube_event_engine.prototype.removeEventListener;
  1026. rcube_treelist_widget.prototype.triggerEvent = rcube_event_engine.prototype.triggerEvent;