tabs.js 51 KB

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