bookmarkableTabset.js 1.7 KB

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