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.

544 lines
16 KiB

10 years ago
  1. /*
  2. * # Semantic - Nag
  3. * http://github.com/semantic-org/semantic-ui/
  4. *
  5. *
  6. * Copyright 2013 Contributors
  7. * Released under the MIT license
  8. * http://opensource.org/licenses/MIT
  9. *
  10. */
  11. ;(function ($, window, document, undefined) {
  12. $.fn.nag = function(parameters) {
  13. var
  14. $allModules = $(this),
  15. moduleSelector = $allModules.selector || '',
  16. time = new Date().getTime(),
  17. performance = [],
  18. query = arguments[0],
  19. methodInvoked = (typeof query == 'string'),
  20. queryArguments = [].slice.call(arguments, 1),
  21. returnedValue
  22. ;
  23. $(this)
  24. .each(function() {
  25. var
  26. settings = $.extend(true, {}, $.fn.nag.settings, parameters),
  27. className = settings.className,
  28. selector = settings.selector,
  29. error = settings.error,
  30. namespace = settings.namespace,
  31. eventNamespace = '.' + namespace,
  32. moduleNamespace = namespace + '-module',
  33. $module = $(this),
  34. $close = $module.find(selector.close),
  35. $context = $(settings.context),
  36. element = this,
  37. instance = $module.data(moduleNamespace),
  38. moduleOffset,
  39. moduleHeight,
  40. contextWidth,
  41. contextHeight,
  42. contextOffset,
  43. yOffset,
  44. yPosition,
  45. timer,
  46. module,
  47. requestAnimationFrame = window.requestAnimationFrame
  48. || window.mozRequestAnimationFrame
  49. || window.webkitRequestAnimationFrame
  50. || window.msRequestAnimationFrame
  51. || function(callback) { setTimeout(callback, 0); }
  52. ;
  53. module = {
  54. initialize: function() {
  55. module.verbose('Initializing element');
  56. // calculate module offset once
  57. moduleOffset = $module.offset();
  58. moduleHeight = $module.outerHeight();
  59. contextWidth = $context.outerWidth();
  60. contextHeight = $context.outerHeight();
  61. contextOffset = $context.offset();
  62. $module
  63. .data(moduleNamespace, module)
  64. ;
  65. $close
  66. .on('click' + eventNamespace, module.dismiss)
  67. ;
  68. // lets avoid javascript if we dont need to reposition
  69. if(settings.context == window && settings.position == 'fixed') {
  70. $module
  71. .addClass(className.fixed)
  72. ;
  73. }
  74. if(settings.sticky) {
  75. module.verbose('Adding scroll events');
  76. // retrigger on scroll for absolute
  77. if(settings.position == 'absolute') {
  78. $context
  79. .on('scroll' + eventNamespace, module.event.scroll)
  80. .on('resize' + eventNamespace, module.event.scroll)
  81. ;
  82. }
  83. // fixed is always relative to window
  84. else {
  85. $(window)
  86. .on('scroll' + eventNamespace, module.event.scroll)
  87. .on('resize' + eventNamespace, module.event.scroll)
  88. ;
  89. }
  90. // fire once to position on init
  91. $.proxy(module.event.scroll, this)();
  92. }
  93. if(settings.displayTime > 0) {
  94. setTimeout(module.hide, settings.displayTime);
  95. }
  96. if(module.should.show()) {
  97. if( !$module.is(':visible') ) {
  98. module.show();
  99. }
  100. }
  101. else {
  102. module.hide();
  103. }
  104. },
  105. destroy: function() {
  106. module.verbose('Destroying instance');
  107. $module
  108. .removeData(moduleNamespace)
  109. .off(eventNamespace)
  110. ;
  111. if(settings.sticky) {
  112. $context
  113. .off(eventNamespace)
  114. ;
  115. }
  116. },
  117. refresh: function() {
  118. module.debug('Refreshing cached calculations');
  119. moduleOffset = $module.offset();
  120. moduleHeight = $module.outerHeight();
  121. contextWidth = $context.outerWidth();
  122. contextHeight = $context.outerHeight();
  123. contextOffset = $context.offset();
  124. },
  125. show: function() {
  126. module.debug('Showing nag', settings.animation.show);
  127. if(settings.animation.show == 'fade') {
  128. $module
  129. .fadeIn(settings.duration, settings.easing)
  130. ;
  131. }
  132. else {
  133. $module
  134. .slideDown(settings.duration, settings.easing)
  135. ;
  136. }
  137. },
  138. hide: function() {
  139. module.debug('Showing nag', settings.animation.hide);
  140. if(settings.animation.show == 'fade') {
  141. $module
  142. .fadeIn(settings.duration, settings.easing)
  143. ;
  144. }
  145. else {
  146. $module
  147. .slideUp(settings.duration, settings.easing)
  148. ;
  149. }
  150. },
  151. onHide: function() {
  152. module.debug('Removing nag', settings.animation.hide);
  153. $module.remove();
  154. if (settings.onHide) {
  155. settings.onHide();
  156. }
  157. },
  158. stick: function() {
  159. module.refresh();
  160. if(settings.position == 'fixed') {
  161. var
  162. windowScroll = $(window).prop('pageYOffset') || $(window).scrollTop(),
  163. fixedOffset = ( $module.hasClass(className.bottom) )
  164. ? contextOffset.top + (contextHeight - moduleHeight) - windowScroll
  165. : contextOffset.top - windowScroll
  166. ;
  167. $module
  168. .css({
  169. position : 'fixed',
  170. top : fixedOffset,
  171. left : contextOffset.left,
  172. width : contextWidth - settings.scrollBarWidth
  173. })
  174. ;
  175. }
  176. else {
  177. $module
  178. .css({
  179. top : yPosition
  180. })
  181. ;
  182. }
  183. },
  184. unStick: function() {
  185. $module
  186. .css({
  187. top : ''
  188. })
  189. ;
  190. },
  191. dismiss: function(event) {
  192. if(settings.storageMethod) {
  193. module.storage.set(settings.storedKey, settings.storedValue);
  194. }
  195. module.hide();
  196. event.stopImmediatePropagation();
  197. event.preventDefault();
  198. },
  199. should: {
  200. show: function() {
  201. if(settings.persist) {
  202. module.debug('Persistent nag is set, can show nag');
  203. return true;
  204. }
  205. if(module.storage.get(settings.storedKey) != settings.storedValue) {
  206. module.debug('Stored value is not set, can show nag', module.storage.get(settings.storedKey));
  207. return true;
  208. }
  209. module.debug('Stored value is set, cannot show nag', module.storage.get(settings.storedKey));
  210. return false;
  211. },
  212. stick: function() {
  213. yOffset = $context.prop('pageYOffset') || $context.scrollTop();
  214. yPosition = ( $module.hasClass(className.bottom) )
  215. ? (contextHeight - $module.outerHeight() ) + yOffset
  216. : yOffset
  217. ;
  218. // absolute position calculated when y offset met
  219. if(yPosition > moduleOffset.top) {
  220. return true;
  221. }
  222. else if(settings.position == 'fixed') {
  223. return true;
  224. }
  225. return false;
  226. }
  227. },
  228. storage: {
  229. set: function(key, value) {
  230. module.debug('Setting stored value', key, value, settings.storageMethod);
  231. if(settings.storageMethod == 'local' && window.store !== undefined) {
  232. window.store.set(key, value);
  233. }
  234. // store by cookie
  235. else if($.cookie !== undefined) {
  236. $.cookie(key, value);
  237. }
  238. else {
  239. module.error(error.noStorage);
  240. }
  241. },
  242. get: function(key) {
  243. module.debug('Getting stored value', key, settings.storageMethod);
  244. if(settings.storageMethod == 'local' && window.store !== undefined) {
  245. return window.store.get(key);
  246. }
  247. // get by cookie
  248. else if($.cookie !== undefined) {
  249. return $.cookie(key);
  250. }
  251. else {
  252. module.error(error.noStorage);
  253. }
  254. }
  255. },
  256. event: {
  257. scroll: function() {
  258. if(timer !== undefined) {
  259. clearTimeout(timer);
  260. }
  261. timer = setTimeout(function() {
  262. if(module.should.stick() ) {
  263. requestAnimationFrame(module.stick);
  264. }
  265. else {
  266. module.unStick();
  267. }
  268. }, settings.lag);
  269. }
  270. },
  271. setting: function(name, value) {
  272. module.debug('Changing setting', name, value);
  273. if( $.isPlainObject(name) ) {
  274. $.extend(true, settings, name);
  275. }
  276. else if(value !== undefined) {
  277. settings[name] = value;
  278. }
  279. else {
  280. return settings[name];
  281. }
  282. },
  283. internal: function(name, value) {
  284. module.debug('Changing internal', name, value);
  285. if(value !== undefined) {
  286. if( $.isPlainObject(name) ) {
  287. $.extend(true, module, name);
  288. }
  289. else {
  290. module[name] = value;
  291. }
  292. }
  293. else {
  294. return module[name];
  295. }
  296. },
  297. debug: function() {
  298. if(settings.debug) {
  299. if(settings.performance) {
  300. module.performance.log(arguments);
  301. }
  302. else {
  303. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  304. module.debug.apply(console, arguments);
  305. }
  306. }
  307. },
  308. verbose: function() {
  309. if(settings.verbose && settings.debug) {
  310. if(settings.performance) {
  311. module.performance.log(arguments);
  312. }
  313. else {
  314. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  315. module.verbose.apply(console, arguments);
  316. }
  317. }
  318. },
  319. error: function() {
  320. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  321. module.error.apply(console, arguments);
  322. },
  323. performance: {
  324. log: function(message) {
  325. var
  326. currentTime,
  327. executionTime,
  328. previousTime
  329. ;
  330. if(settings.performance) {
  331. currentTime = new Date().getTime();
  332. previousTime = time || currentTime;
  333. executionTime = currentTime - previousTime;
  334. time = currentTime;
  335. performance.push({
  336. 'Element' : element,
  337. 'Name' : message[0],
  338. 'Arguments' : [].slice.call(message, 1) || '',
  339. 'Execution Time' : executionTime
  340. });
  341. }
  342. clearTimeout(module.performance.timer);
  343. module.performance.timer = setTimeout(module.performance.display, 100);
  344. },
  345. display: function() {
  346. var
  347. title = settings.name + ':',
  348. totalTime = 0
  349. ;
  350. time = false;
  351. clearTimeout(module.performance.timer);
  352. $.each(performance, function(index, data) {
  353. totalTime += data['Execution Time'];
  354. });
  355. title += ' ' + totalTime + 'ms';
  356. if(moduleSelector) {
  357. title += ' \'' + moduleSelector + '\'';
  358. }
  359. if($allModules.size() > 1) {
  360. title += ' ' + '(' + $allModules.size() + ')';
  361. }
  362. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  363. console.groupCollapsed(title);
  364. if(console.table) {
  365. console.table(performance);
  366. }
  367. else {
  368. $.each(performance, function(index, data) {
  369. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  370. });
  371. }
  372. console.groupEnd();
  373. }
  374. performance = [];
  375. }
  376. },
  377. invoke: function(query, passedArguments, context) {
  378. var
  379. object = instance,
  380. maxDepth,
  381. found,
  382. response
  383. ;
  384. passedArguments = passedArguments || queryArguments;
  385. context = element || context;
  386. if(typeof query == 'string' && object !== undefined) {
  387. query = query.split(/[\. ]/);
  388. maxDepth = query.length - 1;
  389. $.each(query, function(depth, value) {
  390. var camelCaseValue = (depth != maxDepth)
  391. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  392. : query
  393. ;
  394. if( $.isPlainObject( object[camelCaseValue] ) && (depth != maxDepth) ) {
  395. object = object[camelCaseValue];
  396. }
  397. else if( object[camelCaseValue] !== undefined ) {
  398. found = object[camelCaseValue];
  399. return false;
  400. }
  401. else if( $.isPlainObject( object[value] ) && (depth != maxDepth) ) {
  402. object = object[value];
  403. }
  404. else if( object[value] !== undefined ) {
  405. found = object[value];
  406. return false;
  407. }
  408. else {
  409. return false;
  410. }
  411. });
  412. }
  413. if ( $.isFunction( found ) ) {
  414. response = found.apply(context, passedArguments);
  415. }
  416. else if(found !== undefined) {
  417. response = found;
  418. }
  419. if($.isArray(returnedValue)) {
  420. returnedValue.push(response);
  421. }
  422. else if(returnedValue !== undefined) {
  423. returnedValue = [returnedValue, response];
  424. }
  425. else if(response !== undefined) {
  426. returnedValue = response;
  427. }
  428. return found;
  429. }
  430. };
  431. if(methodInvoked) {
  432. if(instance === undefined) {
  433. module.initialize();
  434. }
  435. module.invoke(query);
  436. }
  437. else {
  438. if(instance !== undefined) {
  439. module.destroy();
  440. }
  441. module.initialize();
  442. }
  443. })
  444. ;
  445. return (returnedValue !== undefined)
  446. ? returnedValue
  447. : this
  448. ;
  449. };
  450. $.fn.nag.settings = {
  451. name : 'Nag',
  452. debug : false,
  453. verbose : true,
  454. performance : true,
  455. namespace : 'Nag',
  456. // allows cookie to be overriden
  457. persist : false,
  458. // set to zero to manually dismiss, otherwise hides on its own
  459. displayTime : 0,
  460. animation : {
  461. show: 'slide',
  462. hide: 'slide'
  463. },
  464. // method of stickyness
  465. position : 'fixed',
  466. scrollBarWidth : 18,
  467. // type of storage to use
  468. storageMethod : 'cookie',
  469. // value to store in dismissed localstorage/cookie
  470. storedKey : 'nag',
  471. storedValue : 'dismiss',
  472. // need to calculate stickyness on scroll
  473. sticky : false,
  474. // how often to check scroll event
  475. lag : 0,
  476. // context for scroll event
  477. context : window,
  478. error: {
  479. noStorage : 'Neither $.cookie or store is defined. A storage solution is required for storing state',
  480. method : 'The method you called is not defined.'
  481. },
  482. className : {
  483. bottom : 'bottom',
  484. fixed : 'fixed'
  485. },
  486. selector : {
  487. close: '.icon.close'
  488. },
  489. speed : 500,
  490. easing : 'easeOutQuad',
  491. onHide: function() {}
  492. };
  493. })( jQuery, window , document );