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.

857 lines
26 KiB

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