expandable-chapters.js 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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(TRIGGER_TEMPLATE)
  13. .on('click', function(e) {
  14. if (!$(e.target).is('a')) {
  15. e.preventDefault();
  16. e.stopPropagation();
  17. toggle($(e.target).closest(CHAPTER));
  18. }
  19. });
  20. expand(lsItem());
  21. //expand current selected chapter with it's parents
  22. var activeChapter = $(CHAPTER + '.active');
  23. expand(activeChapter);
  24. expand(activeChapter.parents(CHAPTER));
  25. }
  26. var toggle = function ($chapter) {
  27. if ($chapter.hasClass('expanded')) {
  28. collapse($chapter);
  29. } else {
  30. expand($chapter);
  31. }
  32. }
  33. var collapse = function ($chapter) {
  34. if ($chapter.length && $chapter.hasClass(TOGGLE_CLASSNAME)) {
  35. $chapter.removeClass(TOGGLE_CLASSNAME);
  36. lsItem($chapter);
  37. }
  38. }
  39. var expand = function ($chapter) {
  40. if ($chapter.length && !$chapter.hasClass(TOGGLE_CLASSNAME)) {
  41. $chapter.addClass(TOGGLE_CLASSNAME);
  42. lsItem($chapter);
  43. }
  44. }
  45. var lsItem = function () {
  46. var map = JSON.parse(localStorage.getItem(LS_NAMESPACE)) || {}
  47. if (arguments.length) {
  48. var $chapters = arguments[0];
  49. $chapters.each(function (index, element) {
  50. var level = $(this).data('level');
  51. var value = $(this).hasClass(TOGGLE_CLASSNAME);
  52. map[level] = value;
  53. })
  54. localStorage.setItem(LS_NAMESPACE, JSON.stringify(map));
  55. } else {
  56. return $(CHAPTER).map(function(index, element){
  57. if (map[$(this).data('level')]) {
  58. return this;
  59. }
  60. })
  61. }
  62. }
  63. gitbook.events.bind('page.change', function() {
  64. init()
  65. });
  66. });