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.

779 lines
25 KiB

10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
10 years ago
  1. /*
  2. * # Semantic - Tab
  3. * http://github.com/semantic-org/semantic-ui/
  4. *
  5. *
  6. * Copyright 2014 Contributors
  7. * Released under the MIT license
  8. * http://opensource.org/licenses/MIT
  9. *
  10. */
  11. ;(function ($, window, document, undefined) {
  12. "use strict";
  13. $.tab = $.fn.tab = function(parameters) {
  14. var
  15. // use window context if none specified
  16. $allModules = $.isFunction(this)
  17. ? $(window)
  18. : $(this),
  19. settings = ( $.isPlainObject(parameters) )
  20. ? $.extend(true, {}, $.fn.tab.settings, parameters)
  21. : $.extend({}, $.fn.tab.settings),
  22. moduleSelector = $allModules.selector || '',
  23. time = new Date().getTime(),
  24. performance = [],
  25. query = arguments[0],
  26. methodInvoked = (typeof query == 'string'),
  27. queryArguments = [].slice.call(arguments, 1),
  28. module,
  29. returnedValue
  30. ;
  31. $allModules
  32. .each(function() {
  33. var
  34. className = settings.className,
  35. metadata = settings.metadata,
  36. selector = settings.selector,
  37. error = settings.error,
  38. eventNamespace = '.' + settings.namespace,
  39. moduleNamespace = 'module-' + settings.namespace,
  40. $module = $(this),
  41. $tabs = $(selector.tabs),
  42. cache = {},
  43. firstLoad = true,
  44. recursionDepth = 0,
  45. $context,
  46. activeTabPath,
  47. parameterArray,
  48. historyEvent,
  49. element = this,
  50. instance = $module.data(moduleNamespace)
  51. ;
  52. module = {
  53. initialize: function() {
  54. module.debug('Initializing tab menu item', $module);
  55. if(settings.context) {
  56. module.determineTabs();
  57. module.debug('Using only tabs inside context', settings.context, $tabs);
  58. }
  59. // set up automatic routing
  60. if(settings.auto) {
  61. module.verbose('Setting up automatic tab retrieval from server');
  62. settings.apiSettings = {
  63. url: settings.path + '/{$tab}'
  64. };
  65. }
  66. // attach events if navigation wasn't set to window
  67. if( !$.isWindow( element ) ) {
  68. module.debug('Attaching tab activation events to element', $module);
  69. $module
  70. .on('click' + eventNamespace, module.event.click)
  71. ;
  72. }
  73. module.instantiate();
  74. },
  75. determineTabs: function() {
  76. var
  77. $reference
  78. ;
  79. if(settings.context === 'parent') {
  80. if($module.closest('.' + className.ui).size() > 0) {
  81. $reference = $module.closest('.' + className.ui);
  82. module.verbose('Using closest UI element for determining parent', $reference);
  83. }
  84. else {
  85. $reference = $module;
  86. }
  87. $context = $reference.parent();
  88. module.verbose('Determining parent element for creating context', $context);
  89. }
  90. else {
  91. $context = $(settings.context);
  92. module.verbose('Using selector for tab context', settings.context, $context);
  93. }
  94. if(settings.childrenOnly) {
  95. $tabs = $context.children(selector.tabs);
  96. module.debug('Searching tab context children for tabs', $context, $tabs);
  97. }
  98. else {
  99. $tabs = $context.find(selector.tabs);
  100. module.debug('Searching tab context for tabs', $context, $tabs);
  101. }
  102. },
  103. initializeHistory: function() {
  104. if(settings.history) {
  105. module.debug('Initializing page state');
  106. if( $.address === undefined ) {
  107. module.error(error.state);
  108. return false;
  109. }
  110. else {
  111. if(settings.historyType == 'state') {
  112. module.debug('Using HTML5 to manage state');
  113. if(settings.path !== false) {
  114. $.address
  115. .history(true)
  116. .state(settings.path)
  117. ;
  118. }
  119. else {
  120. module.error(error.path);
  121. return false;
  122. }
  123. }
  124. $.address
  125. .bind('change', module.event.history.change)
  126. ;
  127. }
  128. }
  129. },
  130. instantiate: function () {
  131. module.verbose('Storing instance of module', module);
  132. $module
  133. .data(moduleNamespace, module)
  134. ;
  135. },
  136. destroy: function() {
  137. module.debug('Destroying tabs', $module);
  138. $module
  139. .removeData(moduleNamespace)
  140. .off(eventNamespace)
  141. ;
  142. },
  143. event: {
  144. click: function(event) {
  145. var
  146. tabPath = $(this).data(metadata.tab)
  147. ;
  148. if(tabPath !== undefined) {
  149. if(settings.history) {
  150. module.verbose('Updating page state', event);
  151. $.address.value(tabPath);
  152. }
  153. else {
  154. module.verbose('Changing tab', event);
  155. module.changeTab(tabPath);
  156. }
  157. event.preventDefault();
  158. }
  159. else {
  160. module.debug('No tab specified');
  161. }
  162. },
  163. history: {
  164. change: function(event) {
  165. var
  166. tabPath = event.pathNames.join('/') || module.get.initialPath(),
  167. pageTitle = settings.templates.determineTitle(tabPath) || false
  168. ;
  169. module.performance.display();
  170. module.debug('History change event', tabPath, event);
  171. historyEvent = event;
  172. if(tabPath !== undefined) {
  173. module.changeTab(tabPath);
  174. }
  175. if(pageTitle) {
  176. $.address.title(pageTitle);
  177. }
  178. }
  179. }
  180. },
  181. refresh: function() {
  182. if(activeTabPath) {
  183. module.debug('Refreshing tab', activeTabPath);
  184. module.changeTab(activeTabPath);
  185. }
  186. },
  187. cache: {
  188. read: function(cacheKey) {
  189. return (cacheKey !== undefined)
  190. ? cache[cacheKey]
  191. : false
  192. ;
  193. },
  194. add: function(cacheKey, content) {
  195. cacheKey = cacheKey || activeTabPath;
  196. module.debug('Adding cached content for', cacheKey);
  197. cache[cacheKey] = content;
  198. },
  199. remove: function(cacheKey) {
  200. cacheKey = cacheKey || activeTabPath;
  201. module.debug('Removing cached content for', cacheKey);
  202. delete cache[cacheKey];
  203. }
  204. },
  205. set: {
  206. state: function(state) {
  207. $.address.value(state);
  208. }
  209. },
  210. changeTab: function(tabPath) {
  211. var
  212. pushStateAvailable = (window.history && window.history.pushState),
  213. shouldIgnoreLoad = (pushStateAvailable && settings.ignoreFirstLoad && firstLoad),
  214. remoteContent = (settings.auto || $.isPlainObject(settings.apiSettings) ),
  215. // only get default path if not remote content
  216. pathArray = (remoteContent && !shouldIgnoreLoad)
  217. ? module.utilities.pathToArray(tabPath)
  218. : module.get.defaultPathArray(tabPath)
  219. ;
  220. tabPath = module.utilities.arrayToPath(pathArray);
  221. $.each(pathArray, function(index, tab) {
  222. var
  223. currentPathArray = pathArray.slice(0, index + 1),
  224. currentPath = module.utilities.arrayToPath(currentPathArray),
  225. isTab = module.is.tab(currentPath),
  226. isLastIndex = (index + 1 == pathArray.length),
  227. $tab = module.get.tabElement(currentPath),
  228. nextPathArray,
  229. nextPath,
  230. isLastTab
  231. ;
  232. module.verbose('Looking for tab', tab);
  233. if(isTab) {
  234. module.verbose('Tab was found', tab);
  235. // scope up
  236. activeTabPath = currentPath;
  237. parameterArray = module.utilities.filterArray(pathArray, currentPathArray);
  238. if(isLastIndex) {
  239. isLastTab = true;
  240. }
  241. else {
  242. nextPathArray = pathArray.slice(0, index + 2);
  243. nextPath = module.utilities.arrayToPath(nextPathArray);
  244. isLastTab = ( !module.is.tab(nextPath) );
  245. if(isLastTab) {
  246. module.verbose('Tab parameters found', nextPathArray);
  247. }
  248. }
  249. if(isLastTab && remoteContent) {
  250. if(!shouldIgnoreLoad) {
  251. module.activate.navigation(currentPath);
  252. module.content.fetch(currentPath, tabPath);
  253. }
  254. else {
  255. module.debug('Ignoring remote content on first tab load', currentPath);
  256. firstLoad = false;
  257. module.cache.add(tabPath, $tab.html());
  258. module.activate.all(currentPath);
  259. $.proxy(settings.onTabInit, $tab)(currentPath, parameterArray, historyEvent);
  260. $.proxy(settings.onTabLoad, $tab)(currentPath, parameterArray, historyEvent);
  261. }
  262. return false;
  263. }
  264. else {
  265. module.debug('Opened local tab', currentPath);
  266. module.activate.all(currentPath);
  267. if( !module.cache.read(currentPath) ) {
  268. module.cache.add(currentPath, true);
  269. module.debug('First time tab loaded calling tab init');
  270. $.proxy(settings.onTabInit, $tab)(currentPath, parameterArray, historyEvent);
  271. }
  272. $.proxy(settings.onTabLoad, $tab)(currentPath, parameterArray, historyEvent);
  273. }
  274. }
  275. else {
  276. if(!settings.history) {
  277. module.error(error.missingTab, $module, currentPath);
  278. }
  279. return false;
  280. }
  281. });
  282. },
  283. content: {
  284. fetch: function(tabPath, fullTabPath) {
  285. var
  286. $tab = module.get.tabElement(tabPath),
  287. apiSettings = {
  288. dataType : 'html',
  289. stateContext : $tab,
  290. onSuccess : function(response) {
  291. module.cache.add(fullTabPath, response);
  292. module.content.update(tabPath, response);
  293. if(tabPath == activeTabPath) {
  294. module.debug('Content loaded', tabPath);
  295. module.activate.tab(tabPath);
  296. }
  297. else {
  298. module.debug('Content loaded in background', tabPath);
  299. }
  300. $.proxy(settings.onTabInit, $tab)(tabPath, parameterArray, historyEvent);
  301. $.proxy(settings.onTabLoad, $tab)(tabPath, parameterArray, historyEvent);
  302. },
  303. urlData: { tab: fullTabPath }
  304. },
  305. request = $tab.data(metadata.promise) || false,
  306. existingRequest = ( request && request.state() === 'pending' ),
  307. requestSettings,
  308. cachedContent
  309. ;
  310. fullTabPath = fullTabPath || tabPath;
  311. cachedContent = module.cache.read(fullTabPath);
  312. if(settings.cache && cachedContent) {
  313. module.debug('Showing existing content', fullTabPath);
  314. module.content.update(tabPath, cachedContent);
  315. module.activate.tab(tabPath);
  316. $.proxy(settings.onTabLoad, $tab)(tabPath, parameterArray, historyEvent);
  317. }
  318. else if(existingRequest) {
  319. module.debug('Content is already loading', fullTabPath);
  320. $tab
  321. .addClass(className.loading)
  322. ;
  323. }
  324. else if($.api !== undefined) {
  325. requestSettings = $.extend(true, { headers: { 'X-Remote': true } }, settings.apiSettings, apiSettings);
  326. module.debug('Retrieving remote content', fullTabPath, requestSettings);
  327. $.api( requestSettings );
  328. }
  329. else {
  330. module.error(error.api);
  331. }
  332. },
  333. update: function(tabPath, html) {
  334. module.debug('Updating html for', tabPath);
  335. var
  336. $tab = module.get.tabElement(tabPath)
  337. ;
  338. $tab
  339. .html(html)
  340. ;
  341. }
  342. },
  343. activate: {
  344. all: function(tabPath) {
  345. module.activate.tab(tabPath);
  346. module.activate.navigation(tabPath);
  347. },
  348. tab: function(tabPath) {
  349. var
  350. $tab = module.get.tabElement(tabPath)
  351. ;
  352. module.verbose('Showing tab content for', $tab);
  353. $tab
  354. .addClass(className.active)
  355. .siblings($tabs)
  356. .removeClass(className.active + ' ' + className.loading)
  357. ;
  358. },
  359. navigation: function(tabPath) {
  360. var
  361. $navigation = module.get.navElement(tabPath)
  362. ;
  363. module.verbose('Activating tab navigation for', $navigation, tabPath);
  364. $navigation
  365. .addClass(className.active)
  366. .siblings($allModules)
  367. .removeClass(className.active + ' ' + className.loading)
  368. ;
  369. }
  370. },
  371. deactivate: {
  372. all: function() {
  373. module.deactivate.navigation();
  374. module.deactivate.tabs();
  375. },
  376. navigation: function() {
  377. $allModules
  378. .removeClass(className.active)
  379. ;
  380. },
  381. tabs: function() {
  382. $tabs
  383. .removeClass(className.active + ' ' + className.loading)
  384. ;
  385. }
  386. },
  387. is: {
  388. tab: function(tabName) {
  389. return (tabName !== undefined)
  390. ? ( module.get.tabElement(tabName).size() > 0 )
  391. : false
  392. ;
  393. }
  394. },
  395. get: {
  396. initialPath: function() {
  397. return $allModules.eq(0).data(metadata.tab) || $tabs.eq(0).data(metadata.tab);
  398. },
  399. path: function() {
  400. return $.address.value();
  401. },
  402. // adds default tabs to tab path
  403. defaultPathArray: function(tabPath) {
  404. return module.utilities.pathToArray( module.get.defaultPath(tabPath) );
  405. },
  406. defaultPath: function(tabPath) {
  407. var
  408. $defaultNav = $allModules.filter('[data-' + metadata.tab + '^="' + tabPath + '/"]').eq(0),
  409. defaultTab = $defaultNav.data(metadata.tab) || false
  410. ;
  411. if( defaultTab ) {
  412. module.debug('Found default tab', defaultTab);
  413. if(recursionDepth < settings.maxDepth) {
  414. recursionDepth++;
  415. return module.get.defaultPath(defaultTab);
  416. }
  417. module.error(error.recursion);
  418. }
  419. else {
  420. module.debug('No default tabs found for', tabPath, $tabs);
  421. }
  422. recursionDepth = 0;
  423. return tabPath;
  424. },
  425. navElement: function(tabPath) {
  426. tabPath = tabPath || activeTabPath;
  427. return $allModules.filter('[data-' + metadata.tab + '="' + tabPath + '"]');
  428. },
  429. tabElement: function(tabPath) {
  430. var
  431. $fullPathTab,
  432. $simplePathTab,
  433. tabPathArray,
  434. lastTab
  435. ;
  436. tabPath = tabPath || activeTabPath;
  437. tabPathArray = module.utilities.pathToArray(tabPath);
  438. lastTab = module.utilities.last(tabPathArray);
  439. $fullPathTab = $tabs.filter('[data-' + metadata.tab + '="' + lastTab + '"]');
  440. $simplePathTab = $tabs.filter('[data-' + metadata.tab + '="' + tabPath + '"]');
  441. return ($fullPathTab.size() > 0)
  442. ? $fullPathTab
  443. : $simplePathTab
  444. ;
  445. },
  446. tab: function() {
  447. return activeTabPath;
  448. }
  449. },
  450. utilities: {
  451. filterArray: function(keepArray, removeArray) {
  452. return $.grep(keepArray, function(keepValue) {
  453. return ( $.inArray(keepValue, removeArray) == -1);
  454. });
  455. },
  456. last: function(array) {
  457. return $.isArray(array)
  458. ? array[ array.length - 1]
  459. : false
  460. ;
  461. },
  462. pathToArray: function(pathName) {
  463. if(pathName === undefined) {
  464. pathName = activeTabPath;
  465. }
  466. return typeof pathName == 'string'
  467. ? pathName.split('/')
  468. : [pathName]
  469. ;
  470. },
  471. arrayToPath: function(pathArray) {
  472. return $.isArray(pathArray)
  473. ? pathArray.join('/')
  474. : false
  475. ;
  476. }
  477. },
  478. setting: function(name, value) {
  479. module.debug('Changing setting', name, value);
  480. if( $.isPlainObject(name) ) {
  481. $.extend(true, settings, name);
  482. }
  483. else if(value !== undefined) {
  484. settings[name] = value;
  485. }
  486. else {
  487. return settings[name];
  488. }
  489. },
  490. internal: function(name, value) {
  491. if( $.isPlainObject(name) ) {
  492. $.extend(true, module, name);
  493. }
  494. else if(value !== undefined) {
  495. module[name] = value;
  496. }
  497. else {
  498. return module[name];
  499. }
  500. },
  501. debug: function() {
  502. if(settings.debug) {
  503. if(settings.performance) {
  504. module.performance.log(arguments);
  505. }
  506. else {
  507. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  508. module.debug.apply(console, arguments);
  509. }
  510. }
  511. },
  512. verbose: function() {
  513. if(settings.verbose && settings.debug) {
  514. if(settings.performance) {
  515. module.performance.log(arguments);
  516. }
  517. else {
  518. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  519. module.verbose.apply(console, arguments);
  520. }
  521. }
  522. },
  523. error: function() {
  524. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  525. module.error.apply(console, arguments);
  526. },
  527. performance: {
  528. log: function(message) {
  529. var
  530. currentTime,
  531. executionTime,
  532. previousTime
  533. ;
  534. if(settings.performance) {
  535. currentTime = new Date().getTime();
  536. previousTime = time || currentTime;
  537. executionTime = currentTime - previousTime;
  538. time = currentTime;
  539. performance.push({
  540. 'Element' : element,
  541. 'Name' : message[0],
  542. 'Arguments' : [].slice.call(message, 1) || '',
  543. 'Execution Time' : executionTime
  544. });
  545. }
  546. clearTimeout(module.performance.timer);
  547. module.performance.timer = setTimeout(module.performance.display, 100);
  548. },
  549. display: function() {
  550. var
  551. title = settings.name + ':',
  552. totalTime = 0
  553. ;
  554. time = false;
  555. clearTimeout(module.performance.timer);
  556. $.each(performance, function(index, data) {
  557. totalTime += data['Execution Time'];
  558. });
  559. title += ' ' + totalTime + 'ms';
  560. if(moduleSelector) {
  561. title += ' \'' + moduleSelector + '\'';
  562. }
  563. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  564. console.groupCollapsed(title);
  565. if(console.table) {
  566. console.table(performance);
  567. }
  568. else {
  569. $.each(performance, function(index, data) {
  570. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  571. });
  572. }
  573. console.groupEnd();
  574. }
  575. performance = [];
  576. }
  577. },
  578. invoke: function(query, passedArguments, context) {
  579. var
  580. object = instance,
  581. maxDepth,
  582. found,
  583. response
  584. ;
  585. passedArguments = passedArguments || queryArguments;
  586. context = element || context;
  587. if(typeof query == 'string' && object !== undefined) {
  588. query = query.split(/[\. ]/);
  589. maxDepth = query.length - 1;
  590. $.each(query, function(depth, value) {
  591. var camelCaseValue = (depth != maxDepth)
  592. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  593. : query
  594. ;
  595. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  596. object = object[camelCaseValue];
  597. }
  598. else if( object[camelCaseValue] !== undefined ) {
  599. found = object[camelCaseValue];
  600. return false;
  601. }
  602. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  603. object = object[value];
  604. }
  605. else if( object[value] !== undefined ) {
  606. found = object[value];
  607. return false;
  608. }
  609. else {
  610. module.error(error.method, query);
  611. return false;
  612. }
  613. });
  614. }
  615. if ( $.isFunction( found ) ) {
  616. response = found.apply(context, passedArguments);
  617. }
  618. else if(found !== undefined) {
  619. response = found;
  620. }
  621. if($.isArray(returnedValue)) {
  622. returnedValue.push(response);
  623. }
  624. else if(returnedValue !== undefined) {
  625. returnedValue = [returnedValue, response];
  626. }
  627. else if(response !== undefined) {
  628. returnedValue = response;
  629. }
  630. return found;
  631. }
  632. };
  633. if(methodInvoked) {
  634. if(instance === undefined) {
  635. module.initialize();
  636. }
  637. module.invoke(query);
  638. }
  639. else {
  640. if(instance !== undefined) {
  641. module.destroy();
  642. }
  643. module.initialize();
  644. }
  645. })
  646. ;
  647. if(module && !methodInvoked) {
  648. module.initializeHistory();
  649. }
  650. return (returnedValue !== undefined)
  651. ? returnedValue
  652. : this
  653. ;
  654. };
  655. // shortcut for tabbed content with no defined navigation
  656. $.tab = function(settings) {
  657. $(window).tab(settings);
  658. };
  659. $.fn.tab.settings = {
  660. name : 'Tab',
  661. namespace : 'tab',
  662. debug : false,
  663. verbose : false,
  664. performance : false,
  665. // only called first time a tab's content is loaded (when remote source)
  666. onTabInit : function(tabPath, parameterArray, historyEvent) {},
  667. // called on every load
  668. onTabLoad : function(tabPath, parameterArray, historyEvent) {},
  669. templates : {
  670. determineTitle: function(tabArray) {}
  671. },
  672. // uses pjax style endpoints fetching content from same url with remote-content headers
  673. auto : false,
  674. history : false,
  675. historyType : 'hash',
  676. path : false,
  677. context : false,
  678. childrenOnly : false,
  679. // max depth a tab can be nested
  680. maxDepth : 25,
  681. // dont load content on first load
  682. ignoreFirstLoad : false,
  683. // load tab content new every tab click
  684. alwaysRefresh : false,
  685. // cache the content requests to pull locally
  686. cache : true,
  687. // settings for api call
  688. apiSettings : false,
  689. error: {
  690. api : 'You attempted to load content without API module',
  691. method : 'The method you called is not defined',
  692. missingTab : 'Activated tab cannot be found for this context.',
  693. noContent : 'The tab you specified is missing a content url.',
  694. path : 'History enabled, but no path was specified',
  695. recursion : 'Max recursive depth reached',
  696. state : 'The state library has not been initialized'
  697. },
  698. metadata : {
  699. tab : 'tab',
  700. loaded : 'loaded',
  701. promise: 'promise'
  702. },
  703. className : {
  704. loading : 'loading',
  705. active : 'active',
  706. ui : 'ui'
  707. },
  708. selector : {
  709. tabs : '.ui.tab'
  710. }
  711. };
  712. })( jQuery, window , document );