ah_toc.js 1.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  1. // $Id$
  2. /**
  3. * @file
  4. * TOC builder for advanced_help pages
  5. *
  6. * @copyright Ouest Systèmes Informatiques (OSInet)
  7. *
  8. * @license Licensed under the General Public License version 2 and later.
  9. */
  10. /**
  11. * Build a TOC div from the Hn elements in a given context
  12. *
  13. * Extract the H[1-7] list in DOM order manually: with jQuery < 1.4,
  14. * neither $('h1, h2...') nor .add() return in DOM order, hence the use
  15. * of filter() on a * selector instead.
  16. *
  17. * @return jQuery
  18. * A list of the headings in the page
  19. */
  20. function ahTocBuildToc() {
  21. var context, // the context of the help page
  22. elements, // the list of headings
  23. element, // one of the headings
  24. list, // the string form of the toc list
  25. index, // a running index for missing heading IDs
  26. id; // the current id when iterating on the headings
  27. context = $('div.advanced-help-topic');
  28. elements = $('*', context).filter(function (index) {
  29. return ['H1', 'H2', 'H3', 'H4', 'H5', 'H6', 'H7'].indexOf(this.nodeName) !== -1;
  30. });
  31. /**
  32. * Only build the toc if there 2 headings or more in the page
  33. */
  34. if (elements.length <= 1) {
  35. return;
  36. }
  37. // Build the headings list
  38. list = "<ul>\n";
  39. index = 0;
  40. elements.each(function() {
  41. element = $(this);
  42. id = element.attr('id');
  43. if (id === '') {
  44. index += 1; // Avoid JSline warning on ++ use
  45. id = 'toc' + index;
  46. element.attr('id', id);
  47. }
  48. // @TODO use some form of l() instead of string concatenation
  49. list += '<li class="' + this.nodeName.toLowerCase() + '">' +
  50. '<a href="#' + id + '">' + element.text() + "</a></li>\n";
  51. });
  52. list += "</ul>\n";
  53. // Avoid creating multiple TOCs if this function is called several times
  54. $('div.ah-toc', context).remove();
  55. // @TODO use a theme function
  56. context.prepend('<div class="ah-toc"><center>Contents</center></div>');
  57. $('div.ah-toc').append(list);
  58. return elements;
  59. }
  60. $(ahTocBuildToc);