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.

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