bookmarkableTabset.js 1.6 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758
  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.getAttribute('href').split('#').pop()
  29. _makeActive(hash)
  30. }
  31. if (linksToTabs) {
  32. Array.from(linksToTabs).map(link =>
  33. link.addEventListener('click', _clickLinkToTab)
  34. )
  35. }
  36. })
  37. },
  38. }))
  39. App.directive('bookmarkableTab', $location => ({
  40. restrict: 'A',
  41. require: 'tab',
  42. link(scope, el, attrs, tab) {
  43. const tabScope = el.isolateScope()
  44. const tabId = attrs.bookmarkableTab
  45. if (tabScope && tabId && tabId !== '') {
  46. tabScope.bookmarkableTabId = tabId
  47. tabScope.$watch('active', function (isActive, wasActive) {
  48. if (isActive && !wasActive && $location.hash() !== tabId) {
  49. return $location.hash(tabId)
  50. }
  51. })
  52. }
  53. },
  54. }))