bookmarkableTabset.js 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061
  1. define(['base'], function(App) {
  2. App.directive('bookmarkableTabset', ($location, _) => ({
  3. restrict: 'A',
  4. require: 'tabset',
  5. link(scope, el, attrs, tabset) {
  6. const _makeActive = function(hash) {
  7. if (hash && hash !== '') {
  8. const matchingTab = _.find(
  9. tabset.tabs,
  10. tab => tab.bookmarkableTabId === hash
  11. )
  12. if (matchingTab) {
  13. matchingTab.select()
  14. return el.children()[0].scrollIntoView({ behavior: 'smooth' })
  15. }
  16. }
  17. }
  18. scope.$applyAsync(function() {
  19. // for page load
  20. const hash = $location.hash()
  21. _makeActive(hash)
  22. // for links within page to a tab
  23. // this needs to be within applyAsync because there could be a link
  24. // within a tab to another tab
  25. const linksToTabs = document.querySelectorAll('.link-to-tab')
  26. const _clickLinkToTab = event => {
  27. const hash = event.currentTarget
  28. .getAttribute('href')
  29. .split('#')
  30. .pop()
  31. _makeActive(hash)
  32. }
  33. if (linksToTabs) {
  34. Array.from(linksToTabs).map(link =>
  35. link.addEventListener('click', _clickLinkToTab)
  36. )
  37. }
  38. })
  39. }
  40. }))
  41. App.directive('bookmarkableTab', $location => ({
  42. restrict: 'A',
  43. require: 'tab',
  44. link(scope, el, attrs, tab) {
  45. const tabScope = el.isolateScope()
  46. const tabId = attrs.bookmarkableTab
  47. if (tabScope && tabId && tabId !== '') {
  48. tabScope.bookmarkableTabId = tabId
  49. tabScope.$watch('active', function(isActive, wasActive) {
  50. if (isActive && !wasActive && $location.hash() !== tabId) {
  51. return $location.hash(tabId)
  52. }
  53. })
  54. }
  55. }
  56. }))
  57. })