bookmarkableTabset.js 2.0 KB

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