You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

1398 lines
47 KiB

7 years ago
  1. /*!
  2. * Angular Material Design
  3. * https://github.com/angular/material
  4. * @license MIT
  5. * v1.1.3
  6. */
  7. goog.provide('ngmaterial.components.tabs');
  8. goog.require('ngmaterial.components.icon');
  9. goog.require('ngmaterial.core');
  10. /**
  11. * @ngdoc module
  12. * @name material.components.tabs
  13. * @description
  14. *
  15. * Tabs, created with the `<md-tabs>` directive provide *tabbed* navigation with different styles.
  16. * The Tabs component consists of clickable tabs that are aligned horizontally side-by-side.
  17. *
  18. * Features include support for:
  19. *
  20. * - static or dynamic tabs,
  21. * - responsive designs,
  22. * - accessibility support (ARIA),
  23. * - tab pagination,
  24. * - external or internal tab content,
  25. * - focus indicators and arrow-key navigations,
  26. * - programmatic lookup and access to tab controllers, and
  27. * - dynamic transitions through different tab contents.
  28. *
  29. */
  30. /*
  31. * @see js folder for tabs implementation
  32. */
  33. angular.module('material.components.tabs', [
  34. 'material.core',
  35. 'material.components.icon'
  36. ]);
  37. /**
  38. * @ngdoc directive
  39. * @name mdTab
  40. * @module material.components.tabs
  41. *
  42. * @restrict E
  43. *
  44. * @description
  45. * Use the `<md-tab>` a nested directive used within `<md-tabs>` to specify a tab with a **label** and optional *view content*.
  46. *
  47. * If the `label` attribute is not specified, then an optional `<md-tab-label>` tag can be used to specify more
  48. * complex tab header markup. If neither the **label** nor the **md-tab-label** are specified, then the nested
  49. * markup of the `<md-tab>` is used as the tab header markup.
  50. *
  51. * Please note that if you use `<md-tab-label>`, your content **MUST** be wrapped in the `<md-tab-body>` tag. This
  52. * is to define a clear separation between the tab content and the tab label.
  53. *
  54. * This container is used by the TabsController to show/hide the active tab's content view. This synchronization is
  55. * automatically managed by the internal TabsController whenever the tab selection changes. Selection changes can
  56. * be initiated via data binding changes, programmatic invocation, or user gestures.
  57. *
  58. * @param {string=} label Optional attribute to specify a simple string as the tab label
  59. * @param {boolean=} ng-disabled If present and expression evaluates to truthy, disabled tab selection.
  60. * @param {expression=} md-on-deselect Expression to be evaluated after the tab has been de-selected.
  61. * @param {expression=} md-on-select Expression to be evaluated after the tab has been selected.
  62. * @param {boolean=} md-active When true, sets the active tab. Note: There can only be one active tab at a time.
  63. *
  64. *
  65. * @usage
  66. *
  67. * <hljs lang="html">
  68. * <md-tab label="" ng-disabled md-on-select="" md-on-deselect="" >
  69. * <h3>My Tab content</h3>
  70. * </md-tab>
  71. *
  72. * <md-tab >
  73. * <md-tab-label>
  74. * <h3>My Tab content</h3>
  75. * </md-tab-label>
  76. * <md-tab-body>
  77. * <p>
  78. * Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium,
  79. * totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae
  80. * dicta sunt explicabo. Nemo enim ipsam voluptatem quia voluptas sit aspernatur aut odit aut fugit,
  81. * sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt.
  82. * </p>
  83. * </md-tab-body>
  84. * </md-tab>
  85. * </hljs>
  86. *
  87. */
  88. angular
  89. .module('material.components.tabs')
  90. .directive('mdTab', MdTab);
  91. function MdTab () {
  92. return {
  93. require: '^?mdTabs',
  94. terminal: true,
  95. compile: function (element, attr) {
  96. var label = firstChild(element, 'md-tab-label'),
  97. body = firstChild(element, 'md-tab-body');
  98. if (label.length === 0) {
  99. label = angular.element('<md-tab-label></md-tab-label>');
  100. if (attr.label) label.text(attr.label);
  101. else label.append(element.contents());
  102. if (body.length === 0) {
  103. var contents = element.contents().detach();
  104. body = angular.element('<md-tab-body></md-tab-body>');
  105. body.append(contents);
  106. }
  107. }
  108. element.append(label);
  109. if (body.html()) element.append(body);
  110. return postLink;
  111. },
  112. scope: {
  113. active: '=?mdActive',
  114. disabled: '=?ngDisabled',
  115. select: '&?mdOnSelect',
  116. deselect: '&?mdOnDeselect'
  117. }
  118. };
  119. function postLink (scope, element, attr, ctrl) {
  120. if (!ctrl) return;
  121. var index = ctrl.getTabElementIndex(element),
  122. body = firstChild(element, 'md-tab-body').remove(),
  123. label = firstChild(element, 'md-tab-label').remove(),
  124. data = ctrl.insertTab({
  125. scope: scope,
  126. parent: scope.$parent,
  127. index: index,
  128. element: element,
  129. template: body.html(),
  130. label: label.html()
  131. }, index);
  132. scope.select = scope.select || angular.noop;
  133. scope.deselect = scope.deselect || angular.noop;
  134. scope.$watch('active', function (active) { if (active) ctrl.select(data.getIndex(), true); });
  135. scope.$watch('disabled', function () { ctrl.refreshIndex(); });
  136. scope.$watch(
  137. function () {
  138. return ctrl.getTabElementIndex(element);
  139. },
  140. function (newIndex) {
  141. data.index = newIndex;
  142. ctrl.updateTabOrder();
  143. }
  144. );
  145. scope.$on('$destroy', function () { ctrl.removeTab(data); });
  146. }
  147. function firstChild (element, tagName) {
  148. var children = element[0].children;
  149. for (var i = 0, len = children.length; i < len; i++) {
  150. var child = children[i];
  151. if (child.tagName === tagName.toUpperCase()) return angular.element(child);
  152. }
  153. return angular.element();
  154. }
  155. }
  156. angular
  157. .module('material.components.tabs')
  158. .directive('mdTabItem', MdTabItem);
  159. function MdTabItem () {
  160. return {
  161. require: '^?mdTabs',
  162. link: function link (scope, element, attr, ctrl) {
  163. if (!ctrl) return;
  164. ctrl.attachRipple(scope, element);
  165. }
  166. };
  167. }
  168. angular
  169. .module('material.components.tabs')
  170. .directive('mdTabLabel', MdTabLabel);
  171. function MdTabLabel () {
  172. return { terminal: true };
  173. }
  174. MdTabScroll['$inject'] = ["$parse"];angular.module('material.components.tabs')
  175. .directive('mdTabScroll', MdTabScroll);
  176. function MdTabScroll ($parse) {
  177. return {
  178. restrict: 'A',
  179. compile: function ($element, attr) {
  180. var fn = $parse(attr.mdTabScroll, null, true);
  181. return function ngEventHandler (scope, element) {
  182. element.on('mousewheel', function (event) {
  183. scope.$apply(function () { fn(scope, { $event: event }); });
  184. });
  185. };
  186. }
  187. };
  188. }
  189. MdTabsController['$inject'] = ["$scope", "$element", "$window", "$mdConstant", "$mdTabInkRipple", "$mdUtil", "$animateCss", "$attrs", "$compile", "$mdTheming", "$mdInteraction"];angular
  190. .module('material.components.tabs')
  191. .controller('MdTabsController', MdTabsController);
  192. /**
  193. * ngInject
  194. */
  195. function MdTabsController ($scope, $element, $window, $mdConstant, $mdTabInkRipple, $mdUtil,
  196. $animateCss, $attrs, $compile, $mdTheming, $mdInteraction) {
  197. // define private properties
  198. var ctrl = this,
  199. locked = false,
  200. elements = getElements(),
  201. queue = [],
  202. destroyed = false,
  203. loaded = false;
  204. // Define public methods
  205. ctrl.$onInit = $onInit;
  206. ctrl.updatePagination = $mdUtil.debounce(updatePagination, 100);
  207. ctrl.redirectFocus = redirectFocus;
  208. ctrl.attachRipple = attachRipple;
  209. ctrl.insertTab = insertTab;
  210. ctrl.removeTab = removeTab;
  211. ctrl.select = select;
  212. ctrl.scroll = scroll;
  213. ctrl.nextPage = nextPage;
  214. ctrl.previousPage = previousPage;
  215. ctrl.keydown = keydown;
  216. ctrl.canPageForward = canPageForward;
  217. ctrl.canPageBack = canPageBack;
  218. ctrl.refreshIndex = refreshIndex;
  219. ctrl.incrementIndex = incrementIndex;
  220. ctrl.getTabElementIndex = getTabElementIndex;
  221. ctrl.updateInkBarStyles = $mdUtil.debounce(updateInkBarStyles, 100);
  222. ctrl.updateTabOrder = $mdUtil.debounce(updateTabOrder, 100);
  223. ctrl.getFocusedTabId = getFocusedTabId;
  224. // For Angular 1.4 and older, where there are no lifecycle hooks but bindings are pre-assigned,
  225. // manually call the $onInit hook.
  226. if (angular.version.major === 1 && angular.version.minor <= 4) {
  227. this.$onInit();
  228. }
  229. /**
  230. * Angular Lifecycle hook for newer Angular versions.
  231. * Bindings are not guaranteed to have been assigned in the controller, but they are in the $onInit hook.
  232. */
  233. function $onInit() {
  234. // Define one-way bindings
  235. defineOneWayBinding('stretchTabs', handleStretchTabs);
  236. // Define public properties with change handlers
  237. defineProperty('focusIndex', handleFocusIndexChange, ctrl.selectedIndex || 0);
  238. defineProperty('offsetLeft', handleOffsetChange, 0);
  239. defineProperty('hasContent', handleHasContent, false);
  240. defineProperty('maxTabWidth', handleMaxTabWidth, getMaxTabWidth());
  241. defineProperty('shouldPaginate', handleShouldPaginate, false);
  242. // Define boolean attributes
  243. defineBooleanAttribute('noInkBar', handleInkBar);
  244. defineBooleanAttribute('dynamicHeight', handleDynamicHeight);
  245. defineBooleanAttribute('noPagination');
  246. defineBooleanAttribute('swipeContent');
  247. defineBooleanAttribute('noDisconnect');
  248. defineBooleanAttribute('autoselect');
  249. defineBooleanAttribute('noSelectClick');
  250. defineBooleanAttribute('centerTabs', handleCenterTabs, false);
  251. defineBooleanAttribute('enableDisconnect');
  252. // Define public properties
  253. ctrl.scope = $scope;
  254. ctrl.parent = $scope.$parent;
  255. ctrl.tabs = [];
  256. ctrl.lastSelectedIndex = null;
  257. ctrl.hasFocus = false;
  258. ctrl.styleTabItemFocus = false;
  259. ctrl.shouldCenterTabs = shouldCenterTabs();
  260. ctrl.tabContentPrefix = 'tab-content-';
  261. // Setup the tabs controller after all bindings are available.
  262. setupTabsController();
  263. }
  264. /**
  265. * Perform setup for the controller, setup events and watcher(s)
  266. */
  267. function setupTabsController () {
  268. ctrl.selectedIndex = ctrl.selectedIndex || 0;
  269. compileTemplate();
  270. configureWatchers();
  271. bindEvents();
  272. $mdTheming($element);
  273. $mdUtil.nextTick(function () {
  274. // Note that the element references need to be updated, because certain "browsers"
  275. // (IE/Edge) lose them and start throwing "Invalid calling object" errors, when we
  276. // compile the element contents down in `compileElement`.
  277. elements = getElements();
  278. updateHeightFromContent();
  279. adjustOffset();
  280. updateInkBarStyles();
  281. ctrl.tabs[ ctrl.selectedIndex ] && ctrl.tabs[ ctrl.selectedIndex ].scope.select();
  282. loaded = true;
  283. updatePagination();
  284. });
  285. }
  286. /**
  287. * Compiles the template provided by the user. This is passed as an attribute from the tabs
  288. * directive's template function.
  289. */
  290. function compileTemplate () {
  291. var template = $attrs.$mdTabsTemplate,
  292. element = angular.element($element[0].querySelector('md-tab-data'));
  293. element.html(template);
  294. $compile(element.contents())(ctrl.parent);
  295. delete $attrs.$mdTabsTemplate;
  296. }
  297. /**
  298. * Binds events used by the tabs component.
  299. */
  300. function bindEvents () {
  301. angular.element($window).on('resize', handleWindowResize);
  302. $scope.$on('$destroy', cleanup);
  303. }
  304. /**
  305. * Configure watcher(s) used by Tabs
  306. */
  307. function configureWatchers () {
  308. $scope.$watch('$mdTabsCtrl.selectedIndex', handleSelectedIndexChange);
  309. }
  310. /**
  311. * Creates a one-way binding manually rather than relying on Angular's isolated scope
  312. * @param key
  313. * @param handler
  314. */
  315. function defineOneWayBinding (key, handler) {
  316. var attr = $attrs.$normalize('md-' + key);
  317. if (handler) defineProperty(key, handler);
  318. $attrs.$observe(attr, function (newValue) { ctrl[ key ] = newValue; });
  319. }
  320. /**
  321. * Defines boolean attributes with default value set to true. (ie. md-stretch-tabs with no value
  322. * will be treated as being truthy)
  323. * @param key
  324. * @param handler
  325. */
  326. function defineBooleanAttribute (key, handler) {
  327. var attr = $attrs.$normalize('md-' + key);
  328. if (handler) defineProperty(key, handler);
  329. if ($attrs.hasOwnProperty(attr)) updateValue($attrs[attr]);
  330. $attrs.$observe(attr, updateValue);
  331. function updateValue (newValue) {
  332. ctrl[ key ] = newValue !== 'false';
  333. }
  334. }
  335. /**
  336. * Remove any events defined by this controller
  337. */
  338. function cleanup () {
  339. destroyed = true;
  340. angular.element($window).off('resize', handleWindowResize);
  341. }
  342. // Change handlers
  343. /**
  344. * Toggles stretch tabs class and updates inkbar when tab stretching changes
  345. * @param stretchTabs
  346. */
  347. function handleStretchTabs (stretchTabs) {
  348. var elements = getElements();
  349. angular.element(elements.wrapper).toggleClass('md-stretch-tabs', shouldStretchTabs());
  350. updateInkBarStyles();
  351. }
  352. function handleCenterTabs (newValue) {
  353. ctrl.shouldCenterTabs = shouldCenterTabs();
  354. }
  355. function handleMaxTabWidth (newWidth, oldWidth) {
  356. if (newWidth !== oldWidth) {
  357. var elements = getElements();
  358. angular.forEach(elements.tabs, function(tab) {
  359. tab.style.maxWidth = newWidth + 'px';
  360. });
  361. $mdUtil.nextTick(ctrl.updateInkBarStyles);
  362. }
  363. }
  364. function handleShouldPaginate (newValue, oldValue) {
  365. if (newValue !== oldValue) {
  366. ctrl.maxTabWidth = getMaxTabWidth();
  367. ctrl.shouldCenterTabs = shouldCenterTabs();
  368. $mdUtil.nextTick(function () {
  369. ctrl.maxTabWidth = getMaxTabWidth();
  370. adjustOffset(ctrl.selectedIndex);
  371. });
  372. }
  373. }
  374. /**
  375. * Add/remove the `md-no-tab-content` class depending on `ctrl.hasContent`
  376. * @param hasContent
  377. */
  378. function handleHasContent (hasContent) {
  379. $element[ hasContent ? 'removeClass' : 'addClass' ]('md-no-tab-content');
  380. }
  381. /**
  382. * Apply ctrl.offsetLeft to the paging element when it changes
  383. * @param left
  384. */
  385. function handleOffsetChange (left) {
  386. var elements = getElements();
  387. var newValue = ctrl.shouldCenterTabs ? '' : '-' + left + 'px';
  388. angular.element(elements.paging).css($mdConstant.CSS.TRANSFORM, 'translate3d(' + newValue + ', 0, 0)');
  389. $scope.$broadcast('$mdTabsPaginationChanged');
  390. }
  391. /**
  392. * Update the UI whenever `ctrl.focusIndex` is updated
  393. * @param newIndex
  394. * @param oldIndex
  395. */
  396. function handleFocusIndexChange (newIndex, oldIndex) {
  397. if (newIndex === oldIndex) return;
  398. if (!getElements().tabs[ newIndex ]) return;
  399. adjustOffset();
  400. redirectFocus();
  401. }
  402. /**
  403. * Update the UI whenever the selected index changes. Calls user-defined select/deselect methods.
  404. * @param newValue
  405. * @param oldValue
  406. */
  407. function handleSelectedIndexChange (newValue, oldValue) {
  408. if (newValue === oldValue) return;
  409. ctrl.selectedIndex = getNearestSafeIndex(newValue);
  410. ctrl.lastSelectedIndex = oldValue;
  411. ctrl.updateInkBarStyles();
  412. updateHeightFromContent();
  413. adjustOffset(newValue);
  414. $scope.$broadcast('$mdTabsChanged');
  415. ctrl.tabs[ oldValue ] && ctrl.tabs[ oldValue ].scope.deselect();
  416. ctrl.tabs[ newValue ] && ctrl.tabs[ newValue ].scope.select();
  417. }
  418. function getTabElementIndex(tabEl){
  419. var tabs = $element[0].getElementsByTagName('md-tab');
  420. return Array.prototype.indexOf.call(tabs, tabEl[0]);
  421. }
  422. /**
  423. * Queues up a call to `handleWindowResize` when a resize occurs while the tabs component is
  424. * hidden.
  425. */
  426. function handleResizeWhenVisible () {
  427. // if there is already a watcher waiting for resize, do nothing
  428. if (handleResizeWhenVisible.watcher) return;
  429. // otherwise, we will abuse the $watch function to check for visible
  430. handleResizeWhenVisible.watcher = $scope.$watch(function () {
  431. // since we are checking for DOM size, we use $mdUtil.nextTick() to wait for after the DOM updates
  432. $mdUtil.nextTick(function () {
  433. // if the watcher has already run (ie. multiple digests in one cycle), do nothing
  434. if (!handleResizeWhenVisible.watcher) return;
  435. if ($element.prop('offsetParent')) {
  436. handleResizeWhenVisible.watcher();
  437. handleResizeWhenVisible.watcher = null;
  438. handleWindowResize();
  439. }
  440. }, false);
  441. });
  442. }
  443. // Event handlers / actions
  444. /**
  445. * Handle user keyboard interactions
  446. * @param event
  447. */
  448. function keydown (event) {
  449. switch (event.keyCode) {
  450. case $mdConstant.KEY_CODE.LEFT_ARROW:
  451. event.preventDefault();
  452. incrementIndex(-1, true);
  453. break;
  454. case $mdConstant.KEY_CODE.RIGHT_ARROW:
  455. event.preventDefault();
  456. incrementIndex(1, true);
  457. break;
  458. case $mdConstant.KEY_CODE.SPACE:
  459. case $mdConstant.KEY_CODE.ENTER:
  460. event.preventDefault();
  461. if (!locked) select(ctrl.focusIndex);
  462. break;
  463. }
  464. }
  465. /**
  466. * Update the selected index. Triggers a click event on the original `md-tab` element in order
  467. * to fire user-added click events if canSkipClick or `md-no-select-click` are false.
  468. * @param index
  469. * @param canSkipClick Optionally allow not firing the click event if `md-no-select-click` is also true.
  470. */
  471. function select (index, canSkipClick) {
  472. if (!locked) ctrl.focusIndex = ctrl.selectedIndex = index;
  473. // skip the click event if noSelectClick is enabled
  474. if (canSkipClick && ctrl.noSelectClick) return;
  475. // nextTick is required to prevent errors in user-defined click events
  476. $mdUtil.nextTick(function () {
  477. ctrl.tabs[ index ].element.triggerHandler('click');
  478. }, false);
  479. }
  480. /**
  481. * When pagination is on, this makes sure the selected index is in view.
  482. * @param event
  483. */
  484. function scroll (event) {
  485. if (!ctrl.shouldPaginate) return;
  486. event.preventDefault();
  487. ctrl.offsetLeft = fixOffset(ctrl.offsetLeft - event.wheelDelta);
  488. }
  489. /**
  490. * Slides the tabs over approximately one page forward.
  491. */
  492. function nextPage () {
  493. var elements = getElements();
  494. var viewportWidth = elements.canvas.clientWidth,
  495. totalWidth = viewportWidth + ctrl.offsetLeft,
  496. i, tab;
  497. for (i = 0; i < elements.tabs.length; i++) {
  498. tab = elements.tabs[ i ];
  499. if (tab.offsetLeft + tab.offsetWidth > totalWidth) break;
  500. }
  501. if (viewportWidth > tab.offsetWidth) {
  502. //Canvas width *greater* than tab width: usual positioning
  503. ctrl.offsetLeft = fixOffset(tab.offsetLeft);
  504. } else {
  505. /**
  506. * Canvas width *smaller* than tab width: positioning at the *end* of current tab to let
  507. * pagination "for loop" to proceed correctly on next tab when nextPage() is called again
  508. */
  509. ctrl.offsetLeft = fixOffset(tab.offsetLeft + (tab.offsetWidth - viewportWidth + 1));
  510. }
  511. }
  512. /**
  513. * Slides the tabs over approximately one page backward.
  514. */
  515. function previousPage () {
  516. var i, tab, elements = getElements();
  517. for (i = 0; i < elements.tabs.length; i++) {
  518. tab = elements.tabs[ i ];
  519. if (tab.offsetLeft + tab.offsetWidth >= ctrl.offsetLeft) break;
  520. }
  521. if (elements.canvas.clientWidth > tab.offsetWidth) {
  522. //Canvas width *greater* than tab width: usual positioning
  523. ctrl.offsetLeft = fixOffset(tab.offsetLeft + tab.offsetWidth - elements.canvas.clientWidth);
  524. } else {
  525. /**
  526. * Canvas width *smaller* than tab width: positioning at the *beginning* of current tab to let
  527. * pagination "for loop" to break correctly on previous tab when previousPage() is called again
  528. */
  529. ctrl.offsetLeft = fixOffset(tab.offsetLeft);
  530. }
  531. }
  532. /**
  533. * Update size calculations when the window is resized.
  534. */
  535. function handleWindowResize () {
  536. ctrl.lastSelectedIndex = ctrl.selectedIndex;
  537. ctrl.offsetLeft = fixOffset(ctrl.offsetLeft);
  538. $mdUtil.nextTick(function () {
  539. ctrl.updateInkBarStyles();
  540. updatePagination();
  541. });
  542. }
  543. function handleInkBar (hide) {
  544. angular.element(getElements().inkBar).toggleClass('ng-hide', hide);
  545. }
  546. /**
  547. * Toggle dynamic height class when value changes
  548. * @param value
  549. */
  550. function handleDynamicHeight (value) {
  551. $element.toggleClass('md-dynamic-height', value);
  552. }
  553. /**
  554. * Remove a tab from the data and select the nearest valid tab.
  555. * @param tabData
  556. */
  557. function removeTab (tabData) {
  558. if (destroyed) return;
  559. var selectedIndex = ctrl.selectedIndex,
  560. tab = ctrl.tabs.splice(tabData.getIndex(), 1)[ 0 ];
  561. refreshIndex();
  562. // when removing a tab, if the selected index did not change, we have to manually trigger the
  563. // tab select/deselect events
  564. if (ctrl.selectedIndex === selectedIndex) {
  565. tab.scope.deselect();
  566. ctrl.tabs[ ctrl.selectedIndex ] && ctrl.tabs[ ctrl.selectedIndex ].scope.select();
  567. }
  568. $mdUtil.nextTick(function () {
  569. updatePagination();
  570. ctrl.offsetLeft = fixOffset(ctrl.offsetLeft);
  571. });
  572. }
  573. /**
  574. * Create an entry in the tabs array for a new tab at the specified index.
  575. * @param tabData
  576. * @param index
  577. * @returns {*}
  578. */
  579. function insertTab (tabData, index) {
  580. var hasLoaded = loaded;
  581. var proto = {
  582. getIndex: function () { return ctrl.tabs.indexOf(tab); },
  583. isActive: function () { return this.getIndex() === ctrl.selectedIndex; },
  584. isLeft: function () { return this.getIndex() < ctrl.selectedIndex; },
  585. isRight: function () { return this.getIndex() > ctrl.selectedIndex; },
  586. shouldRender: function () { return !ctrl.noDisconnect || this.isActive(); },
  587. hasFocus: function () {
  588. return ctrl.styleTabItemFocus
  589. && ctrl.hasFocus && this.getIndex() === ctrl.focusIndex;
  590. },
  591. id: $mdUtil.nextUid(),
  592. hasContent: !!(tabData.template && tabData.template.trim())
  593. },
  594. tab = angular.extend(proto, tabData);
  595. if (angular.isDefined(index)) {
  596. ctrl.tabs.splice(index, 0, tab);
  597. } else {
  598. ctrl.tabs.push(tab);
  599. }
  600. processQueue();
  601. updateHasContent();
  602. $mdUtil.nextTick(function () {
  603. updatePagination();
  604. setAriaControls(tab);
  605. // if autoselect is enabled, select the newly added tab
  606. if (hasLoaded && ctrl.autoselect) $mdUtil.nextTick(function () {
  607. $mdUtil.nextTick(function () { select(ctrl.tabs.indexOf(tab)); });
  608. });
  609. });
  610. return tab;
  611. }
  612. // Getter methods
  613. /**
  614. * Gathers references to all of the DOM elements used by this controller.
  615. * @returns {{}}
  616. */
  617. function getElements () {
  618. var elements = {};
  619. var node = $element[0];
  620. // gather tab bar elements
  621. elements.wrapper = node.querySelector('md-tabs-wrapper');
  622. elements.canvas = elements.wrapper.querySelector('md-tabs-canvas');
  623. elements.paging = elements.canvas.querySelector('md-pagination-wrapper');
  624. elements.inkBar = elements.paging.querySelector('md-ink-bar');
  625. elements.contents = node.querySelectorAll('md-tabs-content-wrapper > md-tab-content');
  626. elements.tabs = elements.paging.querySelectorAll('md-tab-item');
  627. elements.dummies = elements.canvas.querySelectorAll('md-dummy-tab');
  628. return elements;
  629. }
  630. /**
  631. * Determines whether or not the left pagination arrow should be enabled.
  632. * @returns {boolean}
  633. */
  634. function canPageBack () {
  635. return ctrl.offsetLeft > 0;
  636. }
  637. /**
  638. * Determines whether or not the right pagination arrow should be enabled.
  639. * @returns {*|boolean}
  640. */
  641. function canPageForward () {
  642. var elements = getElements();
  643. var lastTab = elements.tabs[ elements.tabs.length - 1 ];
  644. return lastTab && lastTab.offsetLeft + lastTab.offsetWidth > elements.canvas.clientWidth +
  645. ctrl.offsetLeft;
  646. }
  647. /**
  648. * Returns currently focused tab item's element ID
  649. */
  650. function getFocusedTabId() {
  651. var focusedTab = ctrl.tabs[ctrl.focusIndex];
  652. if (!focusedTab || !focusedTab.id) {
  653. return null;
  654. }
  655. return 'tab-item-' + focusedTab.id;
  656. }
  657. /**
  658. * Determines if the UI should stretch the tabs to fill the available space.
  659. * @returns {*}
  660. */
  661. function shouldStretchTabs () {
  662. switch (ctrl.stretchTabs) {
  663. case 'always':
  664. return true;
  665. case 'never':
  666. return false;
  667. default:
  668. return !ctrl.shouldPaginate
  669. && $window.matchMedia('(max-width: 600px)').matches;
  670. }
  671. }
  672. /**
  673. * Determines if the tabs should appear centered.
  674. * @returns {string|boolean}
  675. */
  676. function shouldCenterTabs () {
  677. return ctrl.centerTabs && !ctrl.shouldPaginate;
  678. }
  679. /**
  680. * Determines if pagination is necessary to display the tabs within the available space.
  681. * @returns {boolean}
  682. */
  683. function shouldPaginate () {
  684. if (ctrl.noPagination || !loaded) return false;
  685. var canvasWidth = $element.prop('clientWidth');
  686. angular.forEach(getElements().dummies, function (tab) {
  687. canvasWidth -= tab.offsetWidth;
  688. });
  689. return canvasWidth < 0;
  690. }
  691. /**
  692. * Finds the nearest tab index that is available. This is primarily used for when the active
  693. * tab is removed.
  694. * @param newIndex
  695. * @returns {*}
  696. */
  697. function getNearestSafeIndex (newIndex) {
  698. if (newIndex === -1) return -1;
  699. var maxOffset = Math.max(ctrl.tabs.length - newIndex, newIndex),
  700. i, tab;
  701. for (i = 0; i <= maxOffset; i++) {
  702. tab = ctrl.tabs[ newIndex + i ];
  703. if (tab && (tab.scope.disabled !== true)) return tab.getIndex();
  704. tab = ctrl.tabs[ newIndex - i ];
  705. if (tab && (tab.scope.disabled !== true)) return tab.getIndex();
  706. }
  707. return newIndex;
  708. }
  709. // Utility methods
  710. /**
  711. * Defines a property using a getter and setter in order to trigger a change handler without
  712. * using `$watch` to observe changes.
  713. * @param key
  714. * @param handler
  715. * @param value
  716. */
  717. function defineProperty (key, handler, value) {
  718. Object.defineProperty(ctrl, key, {
  719. get: function () { return value; },
  720. set: function (newValue) {
  721. var oldValue = value;
  722. value = newValue;
  723. handler && handler(newValue, oldValue);
  724. }
  725. });
  726. }
  727. /**
  728. * Updates whether or not pagination should be displayed.
  729. */
  730. function updatePagination () {
  731. ctrl.maxTabWidth = getMaxTabWidth();
  732. ctrl.shouldPaginate = shouldPaginate();
  733. }
  734. /**
  735. * Calculates the width of the pagination wrapper by summing the widths of the dummy tabs.
  736. * @returns {number}
  737. */
  738. function calcPagingWidth () {
  739. return calcTabsWidth(getElements().dummies);
  740. }
  741. function calcTabsWidth(tabs) {
  742. var width = 0;
  743. angular.forEach(tabs, function (tab) {
  744. //-- Uses the larger value between `getBoundingClientRect().width` and `offsetWidth`. This
  745. // prevents `offsetWidth` value from being rounded down and causing wrapping issues, but
  746. // also handles scenarios where `getBoundingClientRect()` is inaccurate (ie. tabs inside
  747. // of a dialog)
  748. width += Math.max(tab.offsetWidth, tab.getBoundingClientRect().width);
  749. });
  750. return Math.ceil(width);
  751. }
  752. function getMaxTabWidth () {
  753. return $element.prop('clientWidth');
  754. }
  755. /**
  756. * Re-orders the tabs and updates the selected and focus indexes to their new positions.
  757. * This is triggered by `tabDirective.js` when the user's tabs have been re-ordered.
  758. */
  759. function updateTabOrder () {
  760. var selectedItem = ctrl.tabs[ ctrl.selectedIndex ],
  761. focusItem = ctrl.tabs[ ctrl.focusIndex ];
  762. ctrl.tabs = ctrl.tabs.sort(function (a, b) {
  763. return a.index - b.index;
  764. });
  765. ctrl.selectedIndex = ctrl.tabs.indexOf(selectedItem);
  766. ctrl.focusIndex = ctrl.tabs.indexOf(focusItem);
  767. }
  768. /**
  769. * This moves the selected or focus index left or right. This is used by the keydown handler.
  770. * @param inc
  771. */
  772. function incrementIndex (inc, focus) {
  773. var newIndex,
  774. key = focus ? 'focusIndex' : 'selectedIndex',
  775. index = ctrl[ key ];
  776. for (newIndex = index + inc;
  777. ctrl.tabs[ newIndex ] && ctrl.tabs[ newIndex ].scope.disabled;
  778. newIndex += inc) {}
  779. if (ctrl.tabs[ newIndex ]) {
  780. ctrl[ key ] = newIndex;
  781. }
  782. }
  783. /**
  784. * This is used to forward focus to dummy elements. This method is necessary to avoid animation
  785. * issues when attempting to focus an item that is out of view.
  786. */
  787. function redirectFocus () {
  788. ctrl.styleTabItemFocus = ($mdInteraction.getLastInteractionType() === 'keyboard');
  789. getElements().dummies[ ctrl.focusIndex ].focus();
  790. }
  791. /**
  792. * Forces the pagination to move the focused tab into view.
  793. */
  794. function adjustOffset (index) {
  795. var elements = getElements();
  796. if (!angular.isNumber(index)) index = ctrl.focusIndex;
  797. if (!elements.tabs[ index ]) return;
  798. if (ctrl.shouldCenterTabs) return;
  799. var tab = elements.tabs[ index ],
  800. left = tab.offsetLeft,
  801. right = tab.offsetWidth + left;
  802. ctrl.offsetLeft = Math.max(ctrl.offsetLeft, fixOffset(right - elements.canvas.clientWidth + 32 * 2));
  803. ctrl.offsetLeft = Math.min(ctrl.offsetLeft, fixOffset(left));
  804. }
  805. /**
  806. * Iterates through all queued functions and clears the queue. This is used for functions that
  807. * are called before the UI is ready, such as size calculations.
  808. */
  809. function processQueue () {
  810. queue.forEach(function (func) { $mdUtil.nextTick(func); });
  811. queue = [];
  812. }
  813. /**
  814. * Determines if the tab content area is needed.
  815. */
  816. function updateHasContent () {
  817. var hasContent = false;
  818. for (var i = 0; i < ctrl.tabs.length; i++) {
  819. if (ctrl.tabs[i].hasContent) {
  820. hasContent = true;
  821. break;
  822. }
  823. }
  824. ctrl.hasContent = hasContent;
  825. }
  826. /**
  827. * Moves the indexes to their nearest valid values.
  828. */
  829. function refreshIndex () {
  830. ctrl.selectedIndex = getNearestSafeIndex(ctrl.selectedIndex);
  831. ctrl.focusIndex = getNearestSafeIndex(ctrl.focusIndex);
  832. }
  833. /**
  834. * Calculates the content height of the current tab.
  835. * @returns {*}
  836. */
  837. function updateHeightFromContent () {
  838. if (!ctrl.dynamicHeight) return $element.css('height', '');
  839. if (!ctrl.tabs.length) return queue.push(updateHeightFromContent);
  840. var elements = getElements();
  841. var tabContent = elements.contents[ ctrl.selectedIndex ],
  842. contentHeight = tabContent ? tabContent.offsetHeight : 0,
  843. tabsHeight = elements.wrapper.offsetHeight,
  844. newHeight = contentHeight + tabsHeight,
  845. currentHeight = $element.prop('clientHeight');
  846. if (currentHeight === newHeight) return;
  847. // Adjusts calculations for when the buttons are bottom-aligned since this relies on absolute
  848. // positioning. This should probably be cleaned up if a cleaner solution is possible.
  849. if ($element.attr('md-align-tabs') === 'bottom') {
  850. currentHeight -= tabsHeight;
  851. newHeight -= tabsHeight;
  852. // Need to include bottom border in these calculations
  853. if ($element.attr('md-border-bottom') !== undefined) ++currentHeight;
  854. }
  855. // Lock during animation so the user can't change tabs
  856. locked = true;
  857. var fromHeight = { height: currentHeight + 'px' },
  858. toHeight = { height: newHeight + 'px' };
  859. // Set the height to the current, specific pixel height to fix a bug on iOS where the height
  860. // first animates to 0, then back to the proper height causing a visual glitch
  861. $element.css(fromHeight);
  862. // Animate the height from the old to the new
  863. $animateCss($element, {
  864. from: fromHeight,
  865. to: toHeight,
  866. easing: 'cubic-bezier(0.35, 0, 0.25, 1)',
  867. duration: 0.5
  868. }).start().done(function () {
  869. // Then (to fix the same iOS issue as above), disable transitions and remove the specific
  870. // pixel height so the height can size with browser width/content changes, etc.
  871. $element.css({
  872. transition: 'none',
  873. height: ''
  874. });
  875. // In the next tick, re-allow transitions (if we do it all at once, $element.css is "smart"
  876. // enough to batch it for us instead of doing it immediately, which undoes the original
  877. // transition: none)
  878. $mdUtil.nextTick(function() {
  879. $element.css('transition', '');
  880. });
  881. // And unlock so tab changes can occur
  882. locked = false;
  883. });
  884. }
  885. /**
  886. * Repositions the ink bar to the selected tab.
  887. * @returns {*}
  888. */
  889. function updateInkBarStyles () {
  890. var elements = getElements();
  891. if (!elements.tabs[ ctrl.selectedIndex ]) {
  892. angular.element(elements.inkBar).css({ left: 'auto', right: 'auto' });
  893. return;
  894. }
  895. if (!ctrl.tabs.length) return queue.push(ctrl.updateInkBarStyles);
  896. // if the element is not visible, we will not be able to calculate sizes until it is
  897. // we should treat that as a resize event rather than just updating the ink bar
  898. if (!$element.prop('offsetParent')) return handleResizeWhenVisible();
  899. var index = ctrl.selectedIndex,
  900. totalWidth = elements.paging.offsetWidth,
  901. tab = elements.tabs[ index ],
  902. left = tab.offsetLeft,
  903. right = totalWidth - left - tab.offsetWidth;
  904. if (ctrl.shouldCenterTabs) {
  905. // We need to use the same calculate process as in the pagination wrapper, to avoid rounding deviations.
  906. var tabWidth = calcTabsWidth(elements.tabs);
  907. if (totalWidth > tabWidth) {
  908. $mdUtil.nextTick(updateInkBarStyles, false);
  909. }
  910. }
  911. updateInkBarClassName();
  912. angular.element(elements.inkBar).css({ left: left + 'px', right: right + 'px' });
  913. }
  914. /**
  915. * Adds left/right classes so that the ink bar will animate properly.
  916. */
  917. function updateInkBarClassName () {
  918. var elements = getElements();
  919. var newIndex = ctrl.selectedIndex,
  920. oldIndex = ctrl.lastSelectedIndex,
  921. ink = angular.element(elements.inkBar);
  922. if (!angular.isNumber(oldIndex)) return;
  923. ink
  924. .toggleClass('md-left', newIndex < oldIndex)
  925. .toggleClass('md-right', newIndex > oldIndex);
  926. }
  927. /**
  928. * Takes an offset value and makes sure that it is within the min/max allowed values.
  929. * @param value
  930. * @returns {*}
  931. */
  932. function fixOffset (value) {
  933. var elements = getElements();
  934. if (!elements.tabs.length || !ctrl.shouldPaginate) return 0;
  935. var lastTab = elements.tabs[ elements.tabs.length - 1 ],
  936. totalWidth = lastTab.offsetLeft + lastTab.offsetWidth;
  937. value = Math.max(0, value);
  938. value = Math.min(totalWidth - elements.canvas.clientWidth, value);
  939. return value;
  940. }
  941. /**
  942. * Attaches a ripple to the tab item element.
  943. * @param scope
  944. * @param element
  945. */
  946. function attachRipple (scope, element) {
  947. var elements = getElements();
  948. var options = { colorElement: angular.element(elements.inkBar) };
  949. $mdTabInkRipple.attach(scope, element, options);
  950. }
  951. /**
  952. * Sets the `aria-controls` attribute to the elements that
  953. * correspond to the passed-in tab.
  954. * @param tab
  955. */
  956. function setAriaControls (tab) {
  957. if (tab.hasContent) {
  958. var nodes = $element[0].querySelectorAll('[md-tab-id="' + tab.id + '"]');
  959. angular.element(nodes).attr('aria-controls', ctrl.tabContentPrefix + tab.id);
  960. }
  961. }
  962. }
  963. /**
  964. * @ngdoc directive
  965. * @name mdTabs
  966. * @module material.components.tabs
  967. *
  968. * @restrict E
  969. *
  970. * @description
  971. * The `<md-tabs>` directive serves as the container for 1..n `<md-tab>` child directives to
  972. * produces a Tabs components. In turn, the nested `<md-tab>` directive is used to specify a tab
  973. * label for the **header button** and a [optional] tab view content that will be associated with
  974. * each tab button.
  975. *
  976. * Below is the markup for its simplest usage:
  977. *
  978. * <hljs lang="html">
  979. * <md-tabs>
  980. * <md-tab label="Tab #1"></md-tab>
  981. * <md-tab label="Tab #2"></md-tab>
  982. * <md-tab label="Tab #3"></md-tab>
  983. * </md-tabs>
  984. * </hljs>
  985. *
  986. * Tabs supports three (3) usage scenarios:
  987. *
  988. * 1. Tabs (buttons only)
  989. * 2. Tabs with internal view content
  990. * 3. Tabs with external view content
  991. *
  992. * **Tab-only** support is useful when tab buttons are used for custom navigation regardless of any
  993. * other components, content, or views.
  994. *
  995. * <i><b>Note:</b> If you are using the Tabs component for page-level navigation, please take a look
  996. * at the <a ng-href="./api/directive/mdNavBar">NavBar component</a> instead as it can handle this
  997. * case a bit more natively.</i>
  998. *
  999. * **Tabs with internal views** are the traditional usages where each tab has associated view
  1000. * content and the view switching is managed internally by the Tabs component.
  1001. *
  1002. * **Tabs with external view content** is often useful when content associated with each tab is
  1003. * independently managed and data-binding notifications announce tab selection changes.
  1004. *
  1005. * Additional features also include:
  1006. *
  1007. * * Content can include any markup.
  1008. * * If a tab is disabled while active/selected, then the next tab will be auto-selected.
  1009. *
  1010. * ### Explanation of tab stretching
  1011. *
  1012. * Initially, tabs will have an inherent size. This size will either be defined by how much space is needed to accommodate their text or set by the user through CSS. Calculations will be based on this size.
  1013. *
  1014. * On mobile devices, tabs will be expanded to fill the available horizontal space. When this happens, all tabs will become the same size.
  1015. *
  1016. * On desktops, by default, stretching will never occur.
  1017. *
  1018. * This default behavior can be overridden through the `md-stretch-tabs` attribute. Here is a table showing when stretching will occur:
  1019. *
  1020. * `md-stretch-tabs` | mobile | desktop
  1021. * ------------------|-----------|--------
  1022. * `auto` | stretched | ---
  1023. * `always` | stretched | stretched
  1024. * `never` | --- | ---
  1025. *
  1026. * @param {integer=} md-selected Index of the active/selected tab
  1027. * @param {boolean=} md-no-ink If present, disables ink ripple effects.
  1028. * @param {boolean=} md-no-ink-bar If present, disables the selection ink bar.
  1029. * @param {string=} md-align-tabs Attribute to indicate position of tab buttons: `bottom` or `top`; default is `top`
  1030. * @param {string=} md-stretch-tabs Attribute to indicate whether or not to stretch tabs: `auto`, `always`, or `never`; default is `auto`
  1031. * @param {boolean=} md-dynamic-height When enabled, the tab wrapper will resize based on the contents of the selected tab
  1032. * @param {boolean=} md-border-bottom If present, shows a solid `1px` border between the tabs and their content
  1033. * @param {boolean=} md-center-tabs When enabled, tabs will be centered provided there is no need for pagination
  1034. * @param {boolean=} md-no-pagination When enabled, pagination will remain off
  1035. * @param {boolean=} md-swipe-content When enabled, swipe gestures will be enabled for the content area to jump between tabs
  1036. * @param {boolean=} md-enable-disconnect When enabled, scopes will be disconnected for tabs that are not being displayed. This provides a performance boost, but may also cause unexpected issues and is not recommended for most users.
  1037. * @param {boolean=} md-autoselect When present, any tabs added after the initial load will be automatically selected
  1038. * @param {boolean=} md-no-select-click When enabled, click events will not be fired when selecting tabs
  1039. *
  1040. * @usage
  1041. * <hljs lang="html">
  1042. * <md-tabs md-selected="selectedIndex" >
  1043. * <img ng-src="img/angular.png" class="centered">
  1044. * <md-tab
  1045. * ng-repeat="tab in tabs | orderBy:predicate:reversed"
  1046. * md-on-select="onTabSelected(tab)"
  1047. * md-on-deselect="announceDeselected(tab)"
  1048. * ng-disabled="tab.disabled">
  1049. * <md-tab-label>
  1050. * {{tab.title}}
  1051. * <img src="img/removeTab.png" ng-click="removeTab(tab)" class="delete">
  1052. * </md-tab-label>
  1053. * <md-tab-body>
  1054. * {{tab.content}}
  1055. * </md-tab-body>
  1056. * </md-tab>
  1057. * </md-tabs>
  1058. * </hljs>
  1059. *
  1060. */
  1061. MdTabs['$inject'] = ["$$mdSvgRegistry"];
  1062. angular
  1063. .module('material.components.tabs')
  1064. .directive('mdTabs', MdTabs);
  1065. function MdTabs ($$mdSvgRegistry) {
  1066. return {
  1067. scope: {
  1068. selectedIndex: '=?mdSelected'
  1069. },
  1070. template: function (element, attr) {
  1071. attr.$mdTabsTemplate = element.html();
  1072. return '' +
  1073. '<md-tabs-wrapper> ' +
  1074. '<md-tab-data></md-tab-data> ' +
  1075. '<md-prev-button ' +
  1076. 'tabindex="-1" ' +
  1077. 'role="button" ' +
  1078. 'aria-label="Previous Page" ' +
  1079. 'aria-disabled="{{!$mdTabsCtrl.canPageBack()}}" ' +
  1080. 'ng-class="{ \'md-disabled\': !$mdTabsCtrl.canPageBack() }" ' +
  1081. 'ng-if="$mdTabsCtrl.shouldPaginate" ' +
  1082. 'ng-click="$mdTabsCtrl.previousPage()"> ' +
  1083. '<md-icon md-svg-src="'+ $$mdSvgRegistry.mdTabsArrow +'"></md-icon> ' +
  1084. '</md-prev-button> ' +
  1085. '<md-next-button ' +
  1086. 'tabindex="-1" ' +
  1087. 'role="button" ' +
  1088. 'aria-label="Next Page" ' +
  1089. 'aria-disabled="{{!$mdTabsCtrl.canPageForward()}}" ' +
  1090. 'ng-class="{ \'md-disabled\': !$mdTabsCtrl.canPageForward() }" ' +
  1091. 'ng-if="$mdTabsCtrl.shouldPaginate" ' +
  1092. 'ng-click="$mdTabsCtrl.nextPage()"> ' +
  1093. '<md-icon md-svg-src="'+ $$mdSvgRegistry.mdTabsArrow +'"></md-icon> ' +
  1094. '</md-next-button> ' +
  1095. '<md-tabs-canvas ' +
  1096. 'tabindex="{{ $mdTabsCtrl.hasFocus ? -1 : 0 }}" ' +
  1097. 'aria-activedescendant="{{$mdTabsCtrl.getFocusedTabId()}}" ' +
  1098. 'ng-focus="$mdTabsCtrl.redirectFocus()" ' +
  1099. 'ng-class="{ ' +
  1100. '\'md-paginated\': $mdTabsCtrl.shouldPaginate, ' +
  1101. '\'md-center-tabs\': $mdTabsCtrl.shouldCenterTabs ' +
  1102. '}" ' +
  1103. 'ng-keydown="$mdTabsCtrl.keydown($event)" ' +
  1104. 'role="tablist"> ' +
  1105. '<md-pagination-wrapper ' +
  1106. 'ng-class="{ \'md-center-tabs\': $mdTabsCtrl.shouldCenterTabs }" ' +
  1107. 'md-tab-scroll="$mdTabsCtrl.scroll($event)"> ' +
  1108. '<md-tab-item ' +
  1109. 'tabindex="-1" ' +
  1110. 'class="md-tab" ' +
  1111. 'ng-repeat="tab in $mdTabsCtrl.tabs" ' +
  1112. 'role="tab" ' +
  1113. 'md-tab-id="{{::tab.id}}"' +
  1114. 'aria-selected="{{tab.isActive()}}" ' +
  1115. 'aria-disabled="{{tab.scope.disabled || \'false\'}}" ' +
  1116. 'ng-click="$mdTabsCtrl.select(tab.getIndex())" ' +
  1117. 'ng-class="{ ' +
  1118. '\'md-active\': tab.isActive(), ' +
  1119. '\'md-focused\': tab.hasFocus(), ' +
  1120. '\'md-disabled\': tab.scope.disabled ' +
  1121. '}" ' +
  1122. 'ng-disabled="tab.scope.disabled" ' +
  1123. 'md-swipe-left="$mdTabsCtrl.nextPage()" ' +
  1124. 'md-swipe-right="$mdTabsCtrl.previousPage()" ' +
  1125. 'md-tabs-template="::tab.label" ' +
  1126. 'md-scope="::tab.parent"></md-tab-item> ' +
  1127. '<md-ink-bar></md-ink-bar> ' +
  1128. '</md-pagination-wrapper> ' +
  1129. '<md-tabs-dummy-wrapper class="md-visually-hidden md-dummy-wrapper"> ' +
  1130. '<md-dummy-tab ' +
  1131. 'class="md-tab" ' +
  1132. 'tabindex="-1" ' +
  1133. 'id="tab-item-{{::tab.id}}" ' +
  1134. 'md-tab-id="{{::tab.id}}"' +
  1135. 'aria-selected="{{tab.isActive()}}" ' +
  1136. 'aria-disabled="{{tab.scope.disabled || \'false\'}}" ' +
  1137. 'ng-focus="$mdTabsCtrl.hasFocus = true" ' +
  1138. 'ng-blur="$mdTabsCtrl.hasFocus = false" ' +
  1139. 'ng-repeat="tab in $mdTabsCtrl.tabs" ' +
  1140. 'md-tabs-template="::tab.label" ' +
  1141. 'md-scope="::tab.parent"></md-dummy-tab> ' +
  1142. '</md-tabs-dummy-wrapper> ' +
  1143. '</md-tabs-canvas> ' +
  1144. '</md-tabs-wrapper> ' +
  1145. '<md-tabs-content-wrapper ng-show="$mdTabsCtrl.hasContent && $mdTabsCtrl.selectedIndex >= 0" class="_md"> ' +
  1146. '<md-tab-content ' +
  1147. 'id="{{:: $mdTabsCtrl.tabContentPrefix + tab.id}}" ' +
  1148. 'class="_md" ' +
  1149. 'role="tabpanel" ' +
  1150. 'aria-labelledby="tab-item-{{::tab.id}}" ' +
  1151. 'md-swipe-left="$mdTabsCtrl.swipeContent && $mdTabsCtrl.incrementIndex(1)" ' +
  1152. 'md-swipe-right="$mdTabsCtrl.swipeContent && $mdTabsCtrl.incrementIndex(-1)" ' +
  1153. 'ng-if="tab.hasContent" ' +
  1154. 'ng-repeat="(index, tab) in $mdTabsCtrl.tabs" ' +
  1155. 'ng-class="{ ' +
  1156. '\'md-no-transition\': $mdTabsCtrl.lastSelectedIndex == null, ' +
  1157. '\'md-active\': tab.isActive(), ' +
  1158. '\'md-left\': tab.isLeft(), ' +
  1159. '\'md-right\': tab.isRight(), ' +
  1160. '\'md-no-scroll\': $mdTabsCtrl.dynamicHeight ' +
  1161. '}"> ' +
  1162. '<div ' +
  1163. 'md-tabs-template="::tab.template" ' +
  1164. 'md-connected-if="tab.isActive()" ' +
  1165. 'md-scope="::tab.parent" ' +
  1166. 'ng-if="$mdTabsCtrl.enableDisconnect || tab.shouldRender()"></div> ' +
  1167. '</md-tab-content> ' +
  1168. '</md-tabs-content-wrapper>';
  1169. },
  1170. controller: 'MdTabsController',
  1171. controllerAs: '$mdTabsCtrl',
  1172. bindToController: true
  1173. };
  1174. }
  1175. MdTabsDummyWrapper['$inject'] = ["$mdUtil", "$window"];angular
  1176. .module('material.components.tabs')
  1177. .directive('mdTabsDummyWrapper', MdTabsDummyWrapper);
  1178. /**
  1179. * @private
  1180. *
  1181. * @param $mdUtil
  1182. * @param $window
  1183. * @returns {{require: string, link: link}}
  1184. * @constructor
  1185. *
  1186. * ngInject
  1187. */
  1188. function MdTabsDummyWrapper ($mdUtil, $window) {
  1189. return {
  1190. require: '^?mdTabs',
  1191. link: function link (scope, element, attr, ctrl) {
  1192. if (!ctrl) return;
  1193. var observer;
  1194. var disconnect;
  1195. var mutationCallback = function() {
  1196. ctrl.updatePagination();
  1197. ctrl.updateInkBarStyles();
  1198. };
  1199. if('MutationObserver' in $window) {
  1200. var config = {
  1201. childList: true,
  1202. subtree: true,
  1203. // Per https://bugzilla.mozilla.org/show_bug.cgi?id=1138368, browsers will not fire
  1204. // the childList mutation, once a <span> element's innerText changes.
  1205. // The characterData of the <span> element will change.
  1206. characterData: true
  1207. };
  1208. observer = new MutationObserver(mutationCallback);
  1209. observer.observe(element[0], config);
  1210. disconnect = observer.disconnect.bind(observer);
  1211. } else {
  1212. var debounced = $mdUtil.debounce(mutationCallback, 15, null, false);
  1213. element.on('DOMSubtreeModified', debounced);
  1214. disconnect = element.off.bind(element, 'DOMSubtreeModified', debounced);
  1215. }
  1216. // Disconnect the observer
  1217. scope.$on('$destroy', function() {
  1218. disconnect();
  1219. });
  1220. }
  1221. };
  1222. }
  1223. MdTabsTemplate['$inject'] = ["$compile", "$mdUtil"];angular
  1224. .module('material.components.tabs')
  1225. .directive('mdTabsTemplate', MdTabsTemplate);
  1226. function MdTabsTemplate ($compile, $mdUtil) {
  1227. return {
  1228. restrict: 'A',
  1229. link: link,
  1230. scope: {
  1231. template: '=mdTabsTemplate',
  1232. connected: '=?mdConnectedIf',
  1233. compileScope: '=mdScope'
  1234. },
  1235. require: '^?mdTabs'
  1236. };
  1237. function link (scope, element, attr, ctrl) {
  1238. if (!ctrl) return;
  1239. var compileScope = ctrl.enableDisconnect ? scope.compileScope.$new() : scope.compileScope;
  1240. element.html(scope.template);
  1241. $compile(element.contents())(compileScope);
  1242. return $mdUtil.nextTick(handleScope);
  1243. function handleScope () {
  1244. scope.$watch('connected', function (value) { value === false ? disconnect() : reconnect(); });
  1245. scope.$on('$destroy', reconnect);
  1246. }
  1247. function disconnect () {
  1248. if (ctrl.enableDisconnect) $mdUtil.disconnectScope(compileScope);
  1249. }
  1250. function reconnect () {
  1251. if (ctrl.enableDisconnect) $mdUtil.reconnectScope(compileScope);
  1252. }
  1253. }
  1254. }
  1255. ngmaterial.components.tabs = angular.module("material.components.tabs");