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.

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