chapter-fold.js 2.1 KB

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