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.

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