bookmarkableTabset.js 1.8 KB

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