expandable-chapters.js 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778
  1. require(['gitbook', 'jQuery'], function(gitbook, $) {
  2. var TOGGLE_CLASSNAME = 'expanded',
  3. CHAPTER = '.chapter',
  4. ARTICLES = '.articles',
  5. TRIGGER_TEMPLATE = '<i class="exc-trigger fa"></i>',
  6. LS_NAMESPACE = 'expChapters';
  7. var init = function () {
  8. // adding the trigger element to each ARTICLES parent and binding the event
  9. $(ARTICLES)
  10. .parent(CHAPTER)
  11. .children('a, span')
  12. .append(
  13. $(TRIGGER_TEMPLATE)
  14. .on('click', function(e) {
  15. e.preventDefault();
  16. e.stopPropagation();
  17. toggle($(e.target).closest(CHAPTER));
  18. })
  19. );
  20. // hacky solution to make spans be clickable when used in combination with "ungrey" plugin
  21. $(CHAPTER + ' > span')
  22. .on('click', function(e) {
  23. e.preventDefault();
  24. e.stopPropagation();
  25. toggle($(e.target).closest(CHAPTER));
  26. });
  27. expand(lsItem());
  28. //expand current selected chapter with it's parents
  29. var activeChapter = $(CHAPTER + '.active');
  30. expand(activeChapter);
  31. expand(activeChapter.parents(CHAPTER));
  32. }
  33. var toggle = function ($chapter) {
  34. if ($chapter.hasClass('expanded')) {
  35. collapse($chapter);
  36. } else {
  37. expand($chapter);
  38. }
  39. }
  40. var collapse = function ($chapter) {
  41. if ($chapter.length && $chapter.hasClass(TOGGLE_CLASSNAME)) {
  42. $chapter.removeClass(TOGGLE_CLASSNAME);
  43. lsItem($chapter);
  44. }
  45. }
  46. var expand = function ($chapter) {
  47. if ($chapter.length && !$chapter.hasClass(TOGGLE_CLASSNAME)) {
  48. $chapter.addClass(TOGGLE_CLASSNAME);
  49. lsItem($chapter);
  50. }
  51. }
  52. var lsItem = function () {
  53. var map = JSON.parse(localStorage.getItem(LS_NAMESPACE)) || {}
  54. if (arguments.length) {
  55. var $chapters = arguments[0];
  56. $chapters.each(function (index, element) {
  57. var level = $(this).data('level');
  58. var value = $(this).hasClass(TOGGLE_CLASSNAME);
  59. map[level] = value;
  60. })
  61. localStorage.setItem(LS_NAMESPACE, JSON.stringify(map));
  62. } else {
  63. return $(CHAPTER).map(function(index, element){
  64. if (map[$(this).data('level')]) {
  65. return this;
  66. }
  67. })
  68. }
  69. }
  70. gitbook.events.bind('start', function() {
  71. init()
  72. });
  73. gitbook.events.bind('page.change', function() {
  74. init()
  75. });
  76. });