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.

726 lines
22 KiB

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