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.

845 lines
26 KiB

11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
11 years ago
  1. /*
  2. * # Semantic - Popup
  3. * http://github.com/jlukic/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.popup = function(parameters) {
  13. var
  14. $allModules = $(this),
  15. $document = $(document),
  16. moduleSelector = $allModules.selector || '',
  17. time = new Date().getTime(),
  18. performance = [],
  19. query = arguments[0],
  20. methodInvoked = (typeof query == 'string'),
  21. queryArguments = [].slice.call(arguments, 1),
  22. returnedValue
  23. ;
  24. $allModules
  25. .each(function() {
  26. var
  27. settings = ( $.isPlainObject(parameters) )
  28. ? $.extend(true, {}, $.fn.popup.settings, parameters)
  29. : $.extend({}, $.fn.popup.settings),
  30. selector = settings.selector,
  31. className = settings.className,
  32. error = settings.error,
  33. metadata = settings.metadata,
  34. namespace = settings.namespace,
  35. eventNamespace = '.' + settings.namespace,
  36. moduleNamespace = 'module-' + namespace,
  37. $module = $(this),
  38. $context = $(settings.context),
  39. $target = (settings.target)
  40. ? $(settings.target)
  41. : $module,
  42. $window = $(window),
  43. $offsetParent = (settings.inline)
  44. ? $target.offsetParent()
  45. : $window,
  46. $popup = (settings.inline)
  47. ? $target.next(settings.selector.popup)
  48. : $window.children(settings.selector.popup).last(),
  49. searchDepth = 0,
  50. element = this,
  51. instance = $module.data(moduleNamespace),
  52. module
  53. ;
  54. module = {
  55. // binds events
  56. initialize: function() {
  57. module.debug('Initializing module', $module);
  58. if(settings.on == 'click') {
  59. $module
  60. .on('click', module.toggle)
  61. ;
  62. }
  63. else {
  64. $module
  65. .on(module.get.startEvent() + eventNamespace, module.event.start)
  66. .on(module.get.endEvent() + eventNamespace, module.event.end)
  67. ;
  68. }
  69. if(settings.target) {
  70. module.debug('Target set to element', $target);
  71. }
  72. $window
  73. .on('resize' + eventNamespace, module.event.resize)
  74. ;
  75. module.instantiate();
  76. },
  77. instantiate: function() {
  78. module.verbose('Storing instance of module', module);
  79. instance = module;
  80. $module
  81. .data(moduleNamespace, instance)
  82. ;
  83. },
  84. refresh: function() {
  85. if(settings.inline) {
  86. $popup = $target.next(selector.popup);
  87. $offsetParent = $target.offsetParent();
  88. }
  89. else {
  90. $popup = $window.children(selector.popup).last();
  91. }
  92. },
  93. destroy: function() {
  94. module.debug('Destroying previous module');
  95. $window
  96. .off(eventNamespace)
  97. ;
  98. $popup
  99. .remove()
  100. ;
  101. $module
  102. .off(eventNamespace)
  103. .removeData(moduleNamespace)
  104. ;
  105. },
  106. event: {
  107. start: function(event) {
  108. module.timer = setTimeout(function() {
  109. if( module.is.hidden() ) {
  110. module.show();
  111. }
  112. }, settings.delay);
  113. },
  114. end: function() {
  115. clearTimeout(module.timer);
  116. if( module.is.visible() ) {
  117. module.hide();
  118. }
  119. },
  120. resize: function() {
  121. if( module.is.visible() ) {
  122. module.set.position();
  123. }
  124. }
  125. },
  126. // generates popup html from metadata
  127. create: function() {
  128. module.debug('Creating pop-up html');
  129. var
  130. html = $module.data(metadata.html) || settings.html,
  131. variation = $module.data(metadata.variation) || settings.variation,
  132. title = $module.data(metadata.title) || settings.title,
  133. content = $module.data(metadata.content) || $module.attr('title') || settings.content
  134. ;
  135. if(html || content || title) {
  136. if(!html) {
  137. html = settings.template({
  138. title : title,
  139. content : content
  140. });
  141. }
  142. $popup = $('<div/>')
  143. .addClass(className.popup)
  144. .addClass(variation)
  145. .html(html)
  146. ;
  147. if(settings.inline) {
  148. module.verbose('Inserting popup element inline', $popup);
  149. $popup
  150. .insertAfter($module)
  151. ;
  152. }
  153. else {
  154. module.verbose('Appending popup element to body', $popup);
  155. $popup
  156. .appendTo( $context )
  157. ;
  158. }
  159. $.proxy(settings.onCreate, $popup)();
  160. }
  161. else {
  162. module.error(error.content);
  163. }
  164. },
  165. // determines popup state
  166. toggle: function() {
  167. module.debug('Toggling pop-up');
  168. if( module.is.hidden() ) {
  169. module.hideAll();
  170. module.show();
  171. }
  172. else {
  173. module.hide();
  174. }
  175. },
  176. show: function(callback) {
  177. callback = callback || function(){};
  178. module.debug('Showing pop-up', settings.transition);
  179. if(!settings.preserve) {
  180. module.refresh();
  181. }
  182. if( !module.exists() ) {
  183. module.create();
  184. }
  185. module.save.conditions();
  186. module.set.position();
  187. module.animate.show(callback);
  188. },
  189. hide: function(callback) {
  190. callback = callback || function(){};
  191. $module
  192. .removeClass(className.visible)
  193. ;
  194. module.restore.conditions();
  195. module.unbind.close();
  196. if( module.is.visible() ) {
  197. module.animate.hide(callback);
  198. }
  199. },
  200. hideAll: function() {
  201. $(selector.popup)
  202. .filter(':visible')
  203. .popup('hide')
  204. ;
  205. },
  206. hideGracefully: function(event) {
  207. // don't close on clicks inside popup
  208. if( $(event.target).closest(selector.popup).size() === 0) {
  209. module.hide();
  210. }
  211. },
  212. exists: function() {
  213. if(settings.inline) {
  214. return ( $popup.size() !== 0 );
  215. }
  216. else {
  217. return ( $popup.parent($context).size() );
  218. }
  219. },
  220. remove: function() {
  221. module.debug('Removing popup');
  222. $popup
  223. .remove()
  224. ;
  225. },
  226. save: {
  227. conditions: function() {
  228. module.cache = {
  229. title: $module.attr('title')
  230. };
  231. if (module.cache.title) {
  232. $module.removeAttr('title');
  233. }
  234. module.verbose('Saving original attributes', module.cache.title);
  235. }
  236. },
  237. restore: {
  238. conditions: function() {
  239. if(module.cache === undefined) {
  240. module.error(error.cache);
  241. return false;
  242. }
  243. if(module.cache.title) {
  244. $module.attr('title', module.cache.title);
  245. }
  246. module.verbose('Restoring original attributes', module.cache.title);
  247. return true;
  248. }
  249. },
  250. animate: {
  251. show: function(callback) {
  252. callback = callback || function(){};
  253. $module
  254. .addClass(className.visible)
  255. ;
  256. if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
  257. $popup
  258. .transition(settings.transition + ' in', settings.duration, function() {
  259. module.bind.close();
  260. $.proxy(callback, element)();
  261. })
  262. ;
  263. }
  264. else {
  265. $popup
  266. .stop()
  267. .fadeIn(settings.duration, settings.easing, function() {
  268. module.bind.close();
  269. $.proxy(callback, element)();
  270. })
  271. ;
  272. }
  273. $.proxy(settings.onShow, element)();
  274. },
  275. hide: function(callback) {
  276. callback = callback || function(){};
  277. module.debug('Hiding pop-up');
  278. if(settings.transition && $.fn.transition !== undefined && $module.transition('is supported')) {
  279. $popup
  280. .transition(settings.transition + ' out', settings.duration, function() {
  281. module.reset();
  282. callback();
  283. })
  284. ;
  285. }
  286. else {
  287. $popup
  288. .stop()
  289. .fadeOut(settings.duration, settings.easing, function() {
  290. module.reset();
  291. callback();
  292. })
  293. ;
  294. }
  295. $.proxy(settings.onHide, element)();
  296. }
  297. },
  298. get: {
  299. startEvent: function() {
  300. if(settings.on == 'hover') {
  301. return 'mouseenter';
  302. }
  303. else if(settings.on == 'focus') {
  304. return 'focus';
  305. }
  306. },
  307. endEvent: function() {
  308. if(settings.on == 'hover') {
  309. return 'mouseleave';
  310. }
  311. else if(settings.on == 'focus') {
  312. return 'blur';
  313. }
  314. },
  315. offstagePosition: function() {
  316. var
  317. boundary = {
  318. top : $(window).scrollTop(),
  319. bottom : $(window).scrollTop() + $(window).height(),
  320. left : 0,
  321. right : $(window).width()
  322. },
  323. popup = {
  324. width : $popup.width(),
  325. height : $popup.outerHeight(),
  326. position : $popup.offset()
  327. },
  328. offstage = {},
  329. offstagePositions = []
  330. ;
  331. if(popup.position) {
  332. offstage = {
  333. top : (popup.position.top < boundary.top),
  334. bottom : (popup.position.top + popup.height > boundary.bottom),
  335. right : (popup.position.left + popup.width > boundary.right),
  336. left : (popup.position.left < boundary.left)
  337. };
  338. }
  339. module.verbose('Checking if outside viewable area', popup.position);
  340. // return only boundaries that have been surpassed
  341. $.each(offstage, function(direction, isOffstage) {
  342. if(isOffstage) {
  343. offstagePositions.push(direction);
  344. }
  345. });
  346. return (offstagePositions.length > 0)
  347. ? offstagePositions.join(' ')
  348. : false
  349. ;
  350. },
  351. nextPosition: function(position) {
  352. switch(position) {
  353. case 'top left':
  354. position = 'bottom left';
  355. break;
  356. case 'bottom left':
  357. position = 'top right';
  358. break;
  359. case 'top right':
  360. position = 'bottom right';
  361. break;
  362. case 'bottom right':
  363. position = 'top center';
  364. break;
  365. case 'top center':
  366. position = 'bottom center';
  367. break;
  368. case 'bottom center':
  369. position = 'right center';
  370. break;
  371. case 'right center':
  372. position = 'left center';
  373. break;
  374. case 'left center':
  375. position = 'top center';
  376. break;
  377. }
  378. return position;
  379. }
  380. },
  381. set: {
  382. position: function(position, arrowOffset) {
  383. var
  384. windowWidth = $(window).width(),
  385. windowHeight = $(window).height(),
  386. width = $target.outerWidth(),
  387. height = $target.outerHeight(),
  388. popupWidth = $popup.width(),
  389. popupHeight = $popup.outerHeight(),
  390. parentWidth = $offsetParent.outerWidth(),
  391. parentHeight = $offsetParent.outerHeight(),
  392. distanceAway = settings.distanceAway,
  393. offset = (settings.inline)
  394. ? $target.position()
  395. : $target.offset(),
  396. positioning,
  397. offstagePosition
  398. ;
  399. position = position || $module.data(metadata.position) || settings.position;
  400. arrowOffset = arrowOffset || $module.data(metadata.offset) || settings.offset;
  401. // adjust for margin when inline
  402. if(settings.inline) {
  403. if(position == 'left center' || position == 'right center') {
  404. arrowOffset += parseInt( window.getComputedStyle(element).getPropertyValue('margin-top'), 10);
  405. distanceAway += -parseInt( window.getComputedStyle(element).getPropertyValue('margin-left'), 10);
  406. }
  407. else {
  408. arrowOffset += parseInt( window.getComputedStyle(element).getPropertyValue('margin-left'), 10);
  409. distanceAway += parseInt( window.getComputedStyle(element).getPropertyValue('margin-top'), 10);
  410. }
  411. }
  412. module.debug('Calculating offset for position', position);
  413. switch(position) {
  414. case 'top left':
  415. positioning = {
  416. bottom : parentHeight - offset.top + distanceAway,
  417. right : parentWidth - offset.left - arrowOffset,
  418. top : 'auto',
  419. left : 'auto'
  420. };
  421. break;
  422. case 'top center':
  423. positioning = {
  424. bottom : parentHeight - offset.top + distanceAway,
  425. left : offset.left + (width / 2) - (popupWidth / 2) + arrowOffset,
  426. top : 'auto',
  427. right : 'auto'
  428. };
  429. break;
  430. case 'top right':
  431. positioning = {
  432. top : 'auto',
  433. bottom : parentHeight - offset.top + distanceAway,
  434. left : offset.left + width + arrowOffset,
  435. right : 'auto'
  436. };
  437. break;
  438. case 'left center':
  439. positioning = {
  440. top : offset.top + (height / 2) - (popupHeight / 2) + arrowOffset,
  441. right : parentWidth - offset.left + distanceAway,
  442. left : 'auto',
  443. bottom : 'auto'
  444. };
  445. break;
  446. case 'right center':
  447. positioning = {
  448. top : offset.top + (height / 2) - (popupHeight / 2) + arrowOffset,
  449. left : offset.left + width + distanceAway,
  450. bottom : 'auto',
  451. right : 'auto'
  452. };
  453. break;
  454. case 'bottom left':
  455. positioning = {
  456. top : offset.top + height + distanceAway,
  457. right : parentWidth - offset.left - arrowOffset,
  458. left : 'auto',
  459. bottom : 'auto'
  460. };
  461. break;
  462. case 'bottom center':
  463. positioning = {
  464. top : offset.top + height + distanceAway,
  465. left : offset.left + (width / 2) - (popupWidth / 2) + arrowOffset,
  466. bottom : 'auto',
  467. right : 'auto'
  468. };
  469. break;
  470. case 'bottom right':
  471. positioning = {
  472. top : offset.top + height + distanceAway,
  473. left : offset.left + width + arrowOffset,
  474. bottom : 'auto',
  475. right : 'auto'
  476. };
  477. break;
  478. }
  479. // tentatively place on stage
  480. $popup
  481. .css(positioning)
  482. .removeClass(className.position)
  483. .addClass(position)
  484. .addClass(className.loading)
  485. ;
  486. // check if is offstage
  487. offstagePosition = module.get.offstagePosition();
  488. // recursively find new positioning
  489. if(offstagePosition) {
  490. module.debug('Element is outside boundaries', offstagePosition);
  491. if(searchDepth < settings.maxSearchDepth) {
  492. position = module.get.nextPosition(position);
  493. searchDepth++;
  494. module.debug('Trying new position', position);
  495. return module.set.position(position);
  496. }
  497. else {
  498. module.error(error.recursion);
  499. searchDepth = 0;
  500. module.reset();
  501. return false;
  502. }
  503. }
  504. else {
  505. module.debug('Position is on stage', position);
  506. searchDepth = 0;
  507. return true;
  508. }
  509. $module.removeClass(className.loading);
  510. }
  511. },
  512. bind: {
  513. close:function() {
  514. if(settings.on == 'click' && settings.closable) {
  515. module.verbose('Binding popup close event to document');
  516. $document
  517. .on('click' + eventNamespace, module.hideGracefully)
  518. ;
  519. }
  520. }
  521. },
  522. unbind: {
  523. close: function() {
  524. if(settings.on == 'click' && settings.closable) {
  525. module.verbose('Removing close event from document');
  526. $document
  527. .off('click' + eventNamespace)
  528. ;
  529. }
  530. }
  531. },
  532. is: {
  533. visible: function() {
  534. return $popup.is(':visible');
  535. },
  536. hidden: function() {
  537. return !module.is.visible();
  538. }
  539. },
  540. reset: function() {
  541. $popup
  542. .attr('style', '')
  543. .removeAttr('style')
  544. ;
  545. if(!settings.preserve) {
  546. module.remove();
  547. }
  548. },
  549. setting: function(name, value) {
  550. if( $.isPlainObject(name) ) {
  551. $.extend(true, settings, name);
  552. }
  553. else if(value !== undefined) {
  554. settings[name] = value;
  555. }
  556. else {
  557. return settings[name];
  558. }
  559. },
  560. internal: function(name, value) {
  561. if( $.isPlainObject(name) ) {
  562. $.extend(true, module, name);
  563. }
  564. else if(value !== undefined) {
  565. module[name] = value;
  566. }
  567. else {
  568. return module[name];
  569. }
  570. },
  571. debug: function() {
  572. if(settings.debug) {
  573. if(settings.performance) {
  574. module.performance.log(arguments);
  575. }
  576. else {
  577. module.debug = Function.prototype.bind.call(console.info, console, settings.name + ':');
  578. module.debug.apply(console, arguments);
  579. }
  580. }
  581. },
  582. verbose: function() {
  583. if(settings.verbose && settings.debug) {
  584. if(settings.performance) {
  585. module.performance.log(arguments);
  586. }
  587. else {
  588. module.verbose = Function.prototype.bind.call(console.info, console, settings.name + ':');
  589. module.verbose.apply(console, arguments);
  590. }
  591. }
  592. },
  593. error: function() {
  594. module.error = Function.prototype.bind.call(console.error, console, settings.name + ':');
  595. module.error.apply(console, arguments);
  596. },
  597. performance: {
  598. log: function(message) {
  599. var
  600. currentTime,
  601. executionTime,
  602. previousTime
  603. ;
  604. if(settings.performance) {
  605. currentTime = new Date().getTime();
  606. previousTime = time || currentTime;
  607. executionTime = currentTime - previousTime;
  608. time = currentTime;
  609. performance.push({
  610. 'Element' : element,
  611. 'Name' : message[0],
  612. 'Arguments' : [].slice.call(message, 1) || '',
  613. 'Execution Time' : executionTime
  614. });
  615. }
  616. clearTimeout(module.performance.timer);
  617. module.performance.timer = setTimeout(module.performance.display, 100);
  618. },
  619. display: function() {
  620. var
  621. title = settings.name + ':',
  622. totalTime = 0
  623. ;
  624. time = false;
  625. clearTimeout(module.performance.timer);
  626. $.each(performance, function(index, data) {
  627. totalTime += data['Execution Time'];
  628. });
  629. title += ' ' + totalTime + 'ms';
  630. if(moduleSelector) {
  631. title += ' \'' + moduleSelector + '\'';
  632. }
  633. if( (console.group !== undefined || console.table !== undefined) && performance.length > 0) {
  634. console.groupCollapsed(title);
  635. if(console.table) {
  636. console.table(performance);
  637. }
  638. else {
  639. $.each(performance, function(index, data) {
  640. console.log(data['Name'] + ': ' + data['Execution Time']+'ms');
  641. });
  642. }
  643. console.groupEnd();
  644. }
  645. performance = [];
  646. }
  647. },
  648. invoke: function(query, passedArguments, context) {
  649. var
  650. maxDepth,
  651. found,
  652. response
  653. ;
  654. passedArguments = passedArguments || queryArguments;
  655. context = element || context;
  656. if(typeof query == 'string' && instance !== undefined) {
  657. query = query.split(/[\. ]/);
  658. maxDepth = query.length - 1;
  659. $.each(query, function(depth, value) {
  660. var camelCaseValue = (depth != maxDepth)
  661. ? value + query[depth + 1].charAt(0).toUpperCase() + query[depth + 1].slice(1)
  662. : query
  663. ;
  664. if( $.isPlainObject( instance[value] ) && (depth != maxDepth) ) {
  665. instance = instance[value];
  666. }
  667. else if( $.isPlainObject( instance[camelCaseValue] ) && (depth != maxDepth) ) {
  668. instance = instance[camelCaseValue];
  669. }
  670. else if( instance[value] !== undefined ) {
  671. found = instance[value];
  672. return false;
  673. }
  674. else if( instance[camelCaseValue] !== undefined ) {
  675. found = instance[camelCaseValue];
  676. return false;
  677. }
  678. else {
  679. module.error(error.method, query);
  680. return false;
  681. }
  682. });
  683. }
  684. if ( $.isFunction( found ) ) {
  685. response = found.apply(context, passedArguments);
  686. }
  687. else if(found !== undefined) {
  688. response = found;
  689. }
  690. if($.isArray(returnedValue)) {
  691. returnedValue.push(response);
  692. }
  693. else if(returnedValue !== undefined) {
  694. returnedValue = [returnedValue, response];
  695. }
  696. else if(response !== undefined) {
  697. returnedValue = response;
  698. }
  699. return found;
  700. }
  701. };
  702. if(methodInvoked) {
  703. if(instance === undefined) {
  704. module.initialize();
  705. }
  706. module.invoke(query);
  707. }
  708. else {
  709. if(instance !== undefined) {
  710. module.destroy();
  711. }
  712. module.initialize();
  713. }
  714. })
  715. ;
  716. return (returnedValue !== undefined)
  717. ? returnedValue
  718. : this
  719. ;
  720. };
  721. $.fn.popup.settings = {
  722. name : 'Popup',
  723. debug : true,
  724. verbose : true,
  725. performance : true,
  726. namespace : 'popup',
  727. onCreate : function(){},
  728. onShow : function(){},
  729. onHide : function(){},
  730. variation : '',
  731. content : false,
  732. html : false,
  733. title : false,
  734. on : 'hover',
  735. target : false,
  736. closable : true,
  737. context : 'body',
  738. position : 'top center',
  739. delay : 150,
  740. inline : false,
  741. preserve : false,
  742. duration : 250,
  743. easing : 'easeOutQuint',
  744. transition : 'scale',
  745. distanceAway : 0,
  746. offset : 0,
  747. maxSearchDepth : 10,
  748. error: {
  749. content : 'Your popup has no content specified',
  750. method : 'The method you called is not defined.',
  751. recursion : 'Popup attempted to reposition element to fit, but could not find an adequate position.'
  752. },
  753. metadata: {
  754. content : 'content',
  755. html : 'html',
  756. offset : 'offset',
  757. position : 'position',
  758. title : 'title',
  759. variation : 'variation'
  760. },
  761. className : {
  762. loading : 'loading',
  763. popup : 'ui popup',
  764. position : 'top left center bottom right',
  765. visible : 'visible'
  766. },
  767. selector : {
  768. popup : '.ui.popup'
  769. },
  770. template: function(text) {
  771. var html = '';
  772. if(typeof text !== undefined) {
  773. if(typeof text.title !== undefined && text.title) {
  774. html += '<div class="header">' + text.title + '</div class="header">';
  775. }
  776. if(typeof text.content !== undefined && text.content) {
  777. html += '<div class="content">' + text.content + '</div>';
  778. }
  779. }
  780. return html;
  781. }
  782. };
  783. })( jQuery, window , document );