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.

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